@helia/utils 2.5.2-a464d83a → 2.5.2-ed6c3b79

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.min.js CHANGED
@@ -1,25 +1,25 @@
1
1
  (function (root, factory) {(typeof module === 'object' && module.exports) ? module.exports = factory() : root.HeliaUtils = factory()}(typeof self !== 'undefined' ? self : this, function () {
2
- "use strict";var HeliaUtils=(()=>{var Ru=Object.create;var Tr=Object.defineProperty;var Bu=Object.getOwnPropertyDescriptor;var Fu=Object.getOwnPropertyNames;var Uu=Object.getPrototypeOf,Mu=Object.prototype.hasOwnProperty;var ft=(r,e)=>()=>{try{return e||r((e={exports:{}}).exports,e),e.exports}catch(t){throw e=0,t}},F=(r,e)=>{for(var t in e)Tr(r,t,{get:e[t],enumerable:!0})},ls=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Fu(e))!Mu.call(r,i)&&i!==t&&Tr(r,i,{get:()=>e[i],enumerable:!(n=Bu(e,i))||n.enumerable});return r};var pi=(r,e,t)=>(t=r!=null?Ru(Uu(r)):{},ls(e||!r||!r.__esModule?Tr(t,"default",{value:r,enumerable:!0}):t,r)),$u=r=>ls(Tr({},"__esModule",{value:!0}),r);var Ws=ft((Ay,Hs)=>{"use strict";function df(r){return r>=55296&&r<=56319}function pf(r){return r>=56320&&r<=57343}Hs.exports=function(e,t,n){if(typeof t!="string")throw new Error("Input must be string");for(var i=t.length,o=0,s,a,c=0;c<i;c+=1){if(s=t.charCodeAt(c),a=t[c],df(s)&&pf(t.charCodeAt(c+1))&&(c+=1,a+=t[c]),o+=e(a),o===n)return t.slice(0,c+1);if(o>n)return t.slice(0,c-a.length+1)}return t}});var Js=ft((Sy,Gs)=>{"use strict";function mf(r){return r>=55296&&r<=56319}function yf(r){return r>=56320&&r<=57343}Gs.exports=function(e){if(typeof e!="string")throw new Error("Input must be string");for(var t=e.length,n=0,i=null,o=null,s=0;s<t;s++)i=e.charCodeAt(s),yf(i)?o!=null&&mf(o)?n+=1:n+=3:i<=127?n+=1:i>=128&&i<=2047?n+=2:i>=2048&&i<=65535&&(n+=3),o=i;return n}});var Ys=ft((Iy,Qs)=>{"use strict";var gf=Ws(),wf=Js();Qs.exports=gf.bind(null,wf)});var ea=ft((Cy,Zs)=>{"use strict";var bf=Ys(),xf=/[\/\?<>\\:\*\|"]/g,Ef=/[\x00-\x1f\x80-\x9f]/g,vf=/^\.+$/,_f=/^(con|prn|aux|nul|com[0-9]|lpt[0-9])(\..*)?$/i;function kf(r,e){for(var t=r.length;t>0&&(r[t-1]==="."||r[t-1]===" ");)t--;return t<r.length?r.slice(0,t)+e:r}function Xs(r,e){if(typeof r!="string")throw new Error("Input must be string");var t=r.replace(xf,e).replace(Ef,e).replace(vf,e).replace(_f,e);return t=kf(t,e),bf(t,255)}Zs.exports=function(r,e){var t=e&&e.replacement||"",n=Xs(r,t);return t===""?n:Xs(n,"")}});var va=ft((Vg,so)=>{"use strict";var ah=Object.prototype.hasOwnProperty,Q="~";function rr(){}Object.create&&(rr.prototype=Object.create(null),new rr().__proto__||(Q=!1));function ch(r,e,t){this.fn=r,this.context=e,this.once=t||!1}function Ea(r,e,t,n,i){if(typeof t!="function")throw new TypeError("The listener must be a function");var o=new ch(t,n||r,i),s=Q?Q+e:e;return r._events[s]?r._events[s].fn?r._events[s]=[r._events[s],o]:r._events[s].push(o):(r._events[s]=o,r._eventsCount++),r}function rn(r,e){--r._eventsCount===0?r._events=new rr:delete r._events[e]}function K(){this._events=new rr,this._eventsCount=0}K.prototype.eventNames=function(){var e=[],t,n;if(this._eventsCount===0)return e;for(n in t=this._events)ah.call(t,n)&&e.push(Q?n.slice(1):n);return Object.getOwnPropertySymbols?e.concat(Object.getOwnPropertySymbols(t)):e};K.prototype.listeners=function(e){var t=Q?Q+e:e,n=this._events[t];if(!n)return[];if(n.fn)return[n.fn];for(var i=0,o=n.length,s=new Array(o);i<o;i++)s[i]=n[i].fn;return s};K.prototype.listenerCount=function(e){var t=Q?Q+e:e,n=this._events[t];return n?n.fn?1:n.length:0};K.prototype.emit=function(e,t,n,i,o,s){var a=Q?Q+e:e;if(!this._events[a])return!1;var c=this._events[a],f=arguments.length,l,h;if(c.fn){switch(c.once&&this.removeListener(e,c.fn,void 0,!0),f){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,i),!0;case 5:return c.fn.call(c.context,t,n,i,o),!0;case 6:return c.fn.call(c.context,t,n,i,o,s),!0}for(h=1,l=new Array(f-1);h<f;h++)l[h-1]=arguments[h];c.fn.apply(c.context,l)}else{var d=c.length,g;for(h=0;h<d;h++)switch(c[h].once&&this.removeListener(e,c[h].fn,void 0,!0),f){case 1:c[h].fn.call(c[h].context);break;case 2:c[h].fn.call(c[h].context,t);break;case 3:c[h].fn.call(c[h].context,t,n);break;case 4:c[h].fn.call(c[h].context,t,n,i);break;default:if(!l)for(g=1,l=new Array(f-1);g<f;g++)l[g-1]=arguments[g];c[h].fn.apply(c[h].context,l)}}return!0};K.prototype.on=function(e,t,n){return Ea(this,e,t,n,!1)};K.prototype.once=function(e,t,n){return Ea(this,e,t,n,!0)};K.prototype.removeListener=function(e,t,n,i){var o=Q?Q+e:e;if(!this._events[o])return this;if(!t)return rn(this,o),this;var s=this._events[o];if(s.fn)s.fn===t&&(!i||s.once)&&(!n||s.context===n)&&rn(this,o);else{for(var a=0,c=[],f=s.length;a<f;a++)(s[a].fn!==t||i&&!s[a].once||n&&s[a].context!==n)&&c.push(s[a]);c.length?this._events[o]=c.length===1?c[0]:c:rn(this,o)}return this};K.prototype.removeAllListeners=function(e){var t;return e?(t=Q?Q+e:e,this._events[t]&&rn(this,t)):(this._events=new rr,this._eventsCount=0),this};K.prototype.off=K.prototype.removeListener;K.prototype.addListener=K.prototype.on;K.prefixed=Q;K.EventEmitter=K;typeof so<"u"&&(so.exports=K)});var Sa=ft((pw,Aa)=>{Aa.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 i(o,s){t[o]=s,e++,e>=r&&(e=0,n=t,t=Object.create(null))}return{has:function(o){return t[o]!==void 0||n[o]!==void 0},remove:function(o){t[o]!==void 0&&(t[o]=void 0),n[o]!==void 0&&(n[o]=void 0)},get:function(o){var s=t[o];if(s!==void 0)return s;if((s=n[o])!==void 0)return i(o,s),s},set:function(o,s){t[o]!==void 0?t[o]=s:i(o,s)},clear:function(){t=Object.create(null),n=Object.create(null)}}}});var Kp={};F(Kp,{AbstractSession:()=>di,Helia:()=>us,breadthFirstWalker:()=>Zc,depthFirstWalker:()=>Ar,isCID:()=>Pu,naturalOrderWalker:()=>eu});function pe(r=0){return new Uint8Array(r)}function Z(r=0){return new Uint8Array(r)}var Ou=Math.pow(2,7),Ku=Math.pow(2,14),zu=Math.pow(2,21),fs=Math.pow(2,28),hs=Math.pow(2,35),ds=Math.pow(2,42),ps=Math.pow(2,49),j=128,Me=127;function Ut(r){if(r<Ou)return 1;if(r<Ku)return 2;if(r<zu)return 3;if(r<fs)return 4;if(r<hs)return 5;if(r<ds)return 6;if(r<ps)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function ms(r,e,t=0){switch(Ut(r)){case 8:e[t++]=r&255|j,r/=128;case 7:e[t++]=r&255|j,r/=128;case 6:e[t++]=r&255|j,r/=128;case 5:e[t++]=r&255|j,r/=128;case 4:e[t++]=r&255|j,r>>>=7;case 3:e[t++]=r&255|j,r>>>=7;case 2:e[t++]=r&255|j,r>>>=7;case 1:{e[t++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return e}function ys(r,e){let t=r[e],n=0;if(n+=t&Me,t<j||(t=r[e+1],n+=(t&Me)<<7,t<j)||(t=r[e+2],n+=(t&Me)<<14,t<j)||(t=r[e+3],n+=(t&Me)<<21,t<j)||(t=r[e+4],n+=(t&Me)*fs,t<j)||(t=r[e+5],n+=(t&Me)*hs,t<j)||(t=r[e+6],n+=(t&Me)*ds,t<j)||(t=r[e+7],n+=(t&Me)*ps,t<j))return n;throw new RangeError("Could not decode varint")}function qu(r){return r.buffer instanceof ArrayBuffer}function N(r){return qu(r)?r:r.slice()}var mi=new Float32Array([-0]),$e=new Uint8Array(mi.buffer);function gs(r,e,t){mi[0]=r,e[t]=$e[0],e[t+1]=$e[1],e[t+2]=$e[2],e[t+3]=$e[3]}function ws(r,e){return $e[0]=r[e],$e[1]=r[e+1],$e[2]=r[e+2],$e[3]=r[e+3],mi[0]}var yi=new Float64Array([-0]),$=new Uint8Array(yi.buffer);function bs(r,e,t){yi[0]=r,e[t]=$[0],e[t+1]=$[1],e[t+2]=$[2],e[t+3]=$[3],e[t+4]=$[4],e[t+5]=$[5],e[t+6]=$[6],e[t+7]=$[7]}function xs(r,e){return $[0]=r[e],$[1]=r[e+1],$[2]=r[e+2],$[3]=r[e+3],$[4]=r[e+4],$[5]=r[e+5],$[6]=r[e+6],$[7]=r[e+7],yi[0]}var ju=BigInt(Number.MAX_SAFE_INTEGER),Vu=BigInt(Number.MIN_SAFE_INTEGER),ee=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 Ye;if(e<ju&&e>Vu)return this.fromNumber(Number(e));let t=e<0n;t&&(e=-e);let n=e>>32n,i=e-(n<<32n);return t&&(n=~n|0n,i=~i|0n,++i>Es&&(i=0n,++n>Es&&(n=0n))),new r(Number(i),Number(n))}static fromNumber(e){if(e===0)return Ye;let t=e<0;t&&(e=-e);let n=e>>>0,i=(e-n)/4294967296>>>0;return t&&(i=~i>>>0,n=~n>>>0,++n>4294967295&&(n=0,++i>4294967295&&(i=0))),new r(n,i)}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):Ye}},Ye=new ee(0,0);Ye.toBigInt=function(){return 0n};Ye.zzEncode=Ye.zzDecode=function(){return this};Ye.length=function(){return 1};var Es=4294967296n;function vs(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 _s(r,e,t){if(t-e<1)return"";let i,o=[],s=0,a;for(;e<t;)a=r[e++],a<128?o[s++]=a:a>191&&a<224?o[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,o[s++]=55296+(a>>10),o[s++]=56320+(a&1023)):o[s++]=(a&15)<<12|(r[e++]&63)<<6|r[e++]&63,s>8191&&((i??(i=[])).push(String.fromCharCode.apply(String,o)),s=0);return i!=null?(s>0&&i.push(String.fromCharCode.apply(String,o.slice(0,s))),i.join("")):String.fromCharCode.apply(String,o.slice(0,s))}function gi(r,e,t){let n=t,i,o;for(let s=0;s<r.length;++s)i=r.charCodeAt(s),i<128?e[t++]=i:i<2048?(e[t++]=i>>6|192,e[t++]=i&63|128):(i&64512)===55296&&((o=r.charCodeAt(s+1))&64512)===56320?(i=65536+((i&1023)<<10)+(o&1023),++s,e[t++]=i>>18|240,e[t++]=i>>12&63|128,e[t++]=i>>6&63|128,e[t++]=i&63|128):(e[t++]=i>>12|224,e[t++]=i>>6&63|128,e[t++]=i&63|128);return t-n}function me(r,e){return RangeError(`index out of range: ${r.pos} + ${e??1} > ${r.len}`)}function Lr(r,e){return(r[e-4]|r[e-3]<<8|r[e-2]<<16|r[e-1]<<24)>>>0}var wi=class{buf;pos;len;_slice=Uint8Array.prototype.subarray;constructor(e){this.buf=N(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,me(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 me(this,4);return Lr(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw me(this,4);return Lr(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw me(this,4);let e=ws(this.buf,this.pos);return this.pos+=4,e}double(){if(this.pos+8>this.len)throw me(this,4);let e=xs(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 me(this,e);return this.pos+=e,t===n?new Uint8Array(0):this.buf.subarray(t,n)}string(){let e=this.bytes();return _s(e,0,e.length)}skip(e){if(typeof e=="number"){if(this.pos+e>this.len)throw me(this,e);this.pos+=e}else do if(this.pos>=this.len)throw me(this);while((this.buf[this.pos++]&128)!==0);return this}skipType(e){switch(e){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;(e=this.uint32()&7)!==4;)this.skipType(e);break;case 5:this.skip(4);break;default:throw Error(`invalid wire type ${e} at offset ${this.pos}`)}return this}readLongVarint(){let e=new ee(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 me(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 me(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 me(this,8);let e=Lr(this.buf,this.pos+=4),t=Lr(this.buf,this.pos+=4);return new ee(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=ys(this.buf,this.pos);return this.pos+=Ut(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 Mt(r){return new wi(r instanceof Uint8Array?r:r.subarray())}function Dr(r,e,t){let n=Mt(r);return e.decode(n,void 0,t)}var ki={};F(ki,{base10:()=>Zu});var rm=new Uint8Array(0);function As(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 ye(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return Xe(r);if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return Xe(new Uint8Array(r.buffer,r.byteOffset,r.byteLength));throw new Error("Unknown type, must be binary type")}function Ss(r){return new TextEncoder().encode(r)}function Is(r){return new TextDecoder().decode(r)}function Hu(r){return r?.buffer instanceof ArrayBuffer}function Xe(r){return Hu(r)?r:r.slice()}function Wu(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 i=0;i<r.length;i++){var o=r.charAt(i),s=o.charCodeAt(0);if(t[s]!==255)throw new TypeError(o+" is ambiguous");t[s]=i}var a=r.length,c=r.charAt(0),f=Math.log(a)/Math.log(256),l=Math.log(256)/Math.log(a);function h(w){if(w instanceof Uint8Array||(ArrayBuffer.isView(w)?w=new Uint8Array(w.buffer,w.byteOffset,w.byteLength):Array.isArray(w)&&(w=Uint8Array.from(w))),!(w instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(w.length===0)return"";for(var A=0,E=0,_=0,T=w.length;_!==T&&w[_]===0;)_++,A++;for(var D=(T-_)*l+1>>>0,z=new Uint8Array(D);_!==T;){for(var M=w[_],Pe=0,q=D-1;(M!==0||Pe<E)&&q!==-1;q--,Pe++)M+=256*z[q]>>>0,z[q]=M%a>>>0,M=M/a>>>0;if(M!==0)throw new Error("Non-zero carry");E=Pe,_++}for(var de=D-E;de!==D&&z[de]===0;)de++;for(var Qe=c.repeat(A);de<D;++de)Qe+=r.charAt(z[de]);return Qe}function d(w){if(typeof w!="string")throw new TypeError("Expected String");if(w.length===0)return new Uint8Array;var A=0;if(w[A]!==" "){for(var E=0,_=0;w[A]===c;)E++,A++;for(var T=(w.length-A)*f+1>>>0,D=new Uint8Array(T);w[A];){var z=t[w.charCodeAt(A)];if(z===255)return;for(var M=0,Pe=T-1;(z!==0||M<_)&&Pe!==-1;Pe--,M++)z+=a*D[Pe]>>>0,D[Pe]=z%256>>>0,z=z/256>>>0;if(z!==0)throw new Error("Non-zero carry");_=M,A++}if(w[A]!==" "){for(var q=T-_;q!==T&&D[q]===0;)q++;for(var de=new Uint8Array(E+(T-q)),Qe=E;q!==T;)de[Qe++]=D[q++];return de}}}function g(w){var A=d(w);if(A)return A;throw new Error(`Non-${e} character`)}return{encode:h,decodeUnsafe:d,decode:g}}var Gu=Wu,Ju=Gu,Cs=Ju;var xi=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")}},Ei=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,n){this.name=e,this.prefix=t;let i=t.codePointAt(0);if(i===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=i,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 Ts(this,e)}},vi=class{decoders;constructor(e){this.decoders=e}or(e){return Ts(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 Ts(r,e){return new vi({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var _i=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,n,i){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=i,this.encoder=new xi(e,t,n),this.decoder=new Ei(e,t,i)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function ht({name:r,prefix:e,encode:t,decode:n}){return new _i(r,e,t,n)}function Oe({name:r,prefix:e,alphabet:t}){let{encode:n,decode:i}=Cs(t,r);return ht({prefix:e,name:r,encode:n,decode:o=>ye(i(o))})}function Qu(r,e,t,n){let i=r.length;for(;r[i-1]==="=";)--i;let o=new Uint8Array(i*t/8|0),s=0,a=0,c=0;for(let f=0;f<i;++f){let l=e[r[f]];if(l===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<t|l,s+=t,s>=8&&(s-=8,o[c++]=255&a>>s)}if(s>=t||(255&a<<8-s)!==0)throw new SyntaxError("Unexpected end of data");return o}function Yu(r,e,t){let n=e[e.length-1]==="=",i=(1<<t)-1,o="",s=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],s+=8;s>t;)s-=t,o+=e[i&a>>s];if(s!==0&&(o+=e[i&a<<t-s]),n)for(;(o.length*t&7)!==0;)o+="=";return o}function Xu(r){let e={};for(let t=0;t<r.length;++t)e[r[t]]=t;return e}function P({name:r,prefix:e,bitsPerChar:t,alphabet:n}){let i=Xu(n);return ht({prefix:e,name:r,encode(o){return Yu(o,n,t)},decode(o){return Qu(o,i,t,r)}})}var Zu=Oe({prefix:"9",name:"base10",alphabet:"0123456789"});var Ai={};F(Ai,{base16:()=>el,base16upper:()=>tl});var el=P({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),tl=P({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var Si={};F(Si,{base2:()=>rl});var rl=P({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var Ii={};F(Ii,{base256emoji:()=>al});var Ls=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}"),nl=Ls.reduce((r,e,t)=>(r[t]=e,r),[]),il=Ls.reduce((r,e,t)=>{let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);return r[n]=t,r},[]);function ol(r){return r.reduce((e,t)=>(e+=nl[t],e),"")}function sl(r){let e=[];for(let t of r){let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);let i=il[n];if(i==null)throw new Error(`Non-base256emoji character: ${t}`);e.push(i)}return new Uint8Array(e)}var al=ht({prefix:"\u{1F680}",name:"base256emoji",encode:ol,decode:sl});var Ci={};F(Ci,{base32:()=>O,base32hex:()=>fl,base32hexpad:()=>dl,base32hexpadupper:()=>pl,base32hexupper:()=>hl,base32pad:()=>ul,base32padupper:()=>ll,base32upper:()=>cl,base32z:()=>ml});var O=P({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),cl=P({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),ul=P({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),ll=P({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),fl=P({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),hl=P({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),dl=P({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),pl=P({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),ml=P({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Ti={};F(Ti,{base36:()=>te,base36upper:()=>yl});var te=Oe({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),yl=Oe({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var Li={};F(Li,{base58btc:()=>R,base58flickr:()=>gl});var R=Oe({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),gl=Oe({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var Di={};F(Di,{base64:()=>V,base64pad:()=>wl,base64url:()=>b,base64urlpad:()=>bl});var V=P({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),wl=P({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),b=P({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),bl=P({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var Pi={};F(Pi,{base8:()=>xl});var xl=P({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var Ni={};F(Ni,{identity:()=>El});var El=ht({prefix:"\0",name:"identity",encode:r=>Is(r),decode:r=>Ss(r)});var Pr={};F(Pr,{code:()=>Ri,decode:()=>Sl,encode:()=>Al,name:()=>kl});var vl=new TextEncoder,_l=new TextDecoder,kl="json",Ri=512;function Al(r){return vl.encode(JSON.stringify(r))}function Sl(r){return JSON.parse(_l.decode(r))}var Ot={};F(Ot,{code:()=>$t,decode:()=>Tl,encode:()=>Cl,name:()=>Il});var Il="raw",$t=85;function Cl(r){return ye(r)}function Tl(r){return ye(r)}var Fi={};F(Fi,{identity:()=>Ke});var Ll=Ns,Ds=128,Dl=127,Pl=~Dl,Nl=Math.pow(2,31);function Ns(r,e,t){e=e||[],t=t||0;for(var n=t;r>=Nl;)e[t++]=r&255|Ds,r/=128;for(;r&Pl;)e[t++]=r&255|Ds,r>>>=7;return e[t]=r|0,Ns.bytes=t-n+1,e}var Rl=Bi,Bl=128,Ps=127;function Bi(r,n){var t=0,n=n||0,i=0,o=n,s,a=r.length;do{if(o>=a)throw Bi.bytes=0,new RangeError("Could not decode varint");s=r[o++],t+=i<28?(s&Ps)<<i:(s&Ps)*Math.pow(2,i),i+=7}while(s>=Bl);return Bi.bytes=o-n,t}var Fl=Math.pow(2,7),Ul=Math.pow(2,14),Ml=Math.pow(2,21),$l=Math.pow(2,28),Ol=Math.pow(2,35),Kl=Math.pow(2,42),zl=Math.pow(2,49),ql=Math.pow(2,56),jl=Math.pow(2,63),Vl=function(r){return r<Fl?1:r<Ul?2:r<Ml?3:r<$l?4:r<Ol?5:r<Kl?6:r<zl?7:r<ql?8:r<jl?9:10},Hl={encode:Ll,decode:Rl,encodingLength:Vl},Wl=Hl,Kt=Wl;function zt(r,e=0){return[Kt.decode(r,e),Kt.decode.bytes]}function dt(r,e,t=0){return Kt.encode(r,e,t),e}function pt(r){return Kt.encodingLength(r)}function yt(r,e){let t=e.byteLength,n=pt(r),i=n+pt(t),o=new Uint8Array(i+t);return dt(r,o,0),dt(t,o,n),o.set(e,i),new mt(r,t,e,o)}function Rr(r){let e=ye(r),[t,n]=zt(e),[i,o]=zt(e.subarray(n)),s=e.subarray(n+o);if(s.byteLength!==i)throw new Error("Incorrect length");return new mt(t,i,s,e)}function Rs(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&As(r.bytes,t.bytes)}}var mt=class{code;size;digest;bytes;constructor(e,t,n,i){this.code=e,this.size=t,this.digest=Xe(n),this.bytes=Xe(i)}};var Bs=0,Gl="identity",Fs=ye;function Jl(r,e){if(e?.truncate!=null&&e.truncate!==r.byteLength){if(e.truncate<0||e.truncate>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,e.truncate)}return yt(Bs,Fs(r))}var Ke={code:Bs,name:Gl,encode:Fs,digest:Jl};var $i={};F($i,{sha256:()=>ze,sha512:()=>Br});var Ql=20;function Mi({name:r,code:e,encode:t,minDigestLength:n,maxDigestLength:i}){return new Ui(r,e,t,n,i)}var Ui=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,n,i,o){this.name=e,this.code=t,this.encode=n,this.minDigestLength=i??Ql,this.maxDigestLength=o}digest(e,t){if(t?.truncate!=null){if(t.truncate<this.minDigestLength)throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`);if(this.maxDigestLength!=null&&t.truncate>this.maxDigestLength)throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`)}if(e instanceof Uint8Array){let n=this.encode(e);return n instanceof Uint8Array?Us(n,this.code,t?.truncate):n.then(i=>Us(i,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}};function Us(r,e,t){if(t!=null&&t!==r.byteLength){if(t>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,t)}return yt(e,r)}function $s(r){return async e=>new Uint8Array(await crypto.subtle.digest(r,e))}var ze=Mi({name:"sha2-256",code:18,encode:$s("SHA-256")}),Br=Mi({name:"sha2-512",code:19,encode:$s("SHA-512")});function Os(r,e){let{bytes:t,version:n}=r;return n===0?Xl(t,Oi(r),e??R.encoder):Zl(t,Oi(r),e??O.encoder)}var Ks=new WeakMap;function Oi(r){let e=Ks.get(r);if(e==null){let t=new Map;return Ks.set(r,t),t}return e}var v=class r{code;version;multihash;bytes;"/";constructor(e,t,n,i){this.code=t,this.version=e,this.multihash=n,this.bytes=Xe(i),this["/"]=this.bytes}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:e,multihash:t}=this;if(e!==qt)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==ef)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=yt(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&&Rs(e.multihash,n.multihash)}toString(e){return Os(this,e)}toJSON(){return{"/":Os(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:i,multihash:o,bytes:s}=t;return new r(n,i,o,s??zs(n,i,o.bytes))}else if(t[tf]===!0){let{version:n,multihash:i,code:o}=t,s=Rr(i);return r.create(n,o,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!==qt)throw new Error(`Version 0 CID must use dag-pb (code: ${qt}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let i=zs(e,t,n.bytes);return new r(e,t,n,i)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,qt,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,i=ye(e.subarray(n,n+t.multihashSize));if(i.byteLength!==t.multihashSize)throw new Error("Incorrect length");let o=i.subarray(t.multihashSize-t.digestSize),s=new mt(t.multihashCode,t.digestSize,o,i);return[t.version===0?r.createV0(s):r.createV1(t.codec,s),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[h,d]=zt(e.subarray(t));return t+=d,h},i=n(),o=qt;if(i===18?(i=0,t=0):o=n(),i!==0&&i!==1)throw new RangeError(`Invalid CID version ${i}`);let s=t,a=n(),c=n(),f=t+c,l=f-s;return{version:i,codec:o,multihashCode:a,digestSize:c,multihashSize:l,size:f}}static parse(e,t){let[n,i]=Yl(e,t),o=r.decode(i);if(o.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return Oi(o).set(n,e),o}};function Yl(r,e){switch(r[0]){case"Q":{let t=e??R;return[R.prefix,t.decode(`${R.prefix}${r}`)]}case R.prefix:{let t=e??R;return[R.prefix,t.decode(r)]}case O.prefix:{let t=e??O;return[O.prefix,t.decode(r)]}case te.prefix:{let t=e??te;return[te.prefix,t.decode(r)]}default:{if(e==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[r[0],e.decode(r)]}}}function Xl(r,e,t){let{prefix:n}=t;if(n!==R.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let i=e.get(n);if(i==null){let o=t.encode(r).slice(1);return e.set(n,o),o}else return i}function Zl(r,e,t){let{prefix:n}=t,i=e.get(n);if(i==null){let o=t.encode(r);return e.set(n,o),o}else return i}var qt=112,ef=18;function zs(r,e,t){let n=pt(r),i=n+pt(e),o=new Uint8Array(i+t.byteLength);return dt(r,o,0),dt(e,o,n),o.set(t,i),o}var tf=Symbol.for("@ipld/js-cid/CID");var Ki={...Ni,...Si,...Pi,...ki,...Ai,...Ci,...Ti,...Li,...Di,...Ii},$m={...$i,...Fi};function js(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var qs=js("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),zi=js("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=Z(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),rf={utf8:qs,"utf-8":qs,hex:Ki.base16,latin1:zi,ascii:zi,binary:zi,...Ki},Fr=rf;function L(r,e="utf8"){let t=Fr[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.decoder.decode(`${t.prefix}${r}`)}function qi(r){let e=r??8192,t=e>>>1,n,i=e;return function(s){if(s<1||s>t)return Z(s);i+s>e&&(n=Z(e),i=0);let a=n.subarray(i,i+=s);return(i&7)!==0&&(i=(i|7)+1),a}}var Ze=class{fn;len;next;val;constructor(e,t,n){this.fn=e,this.len=t,this.next=void 0,this.val=n}};function ji(){}var Hi=class{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}},nf=qi();function of(r){return globalThis.Buffer!=null?Z(r):nf(r)}var Vt=class{len;head;tail;states;constructor(){this.len=0,this.head=new Ze(ji,0,0),this.tail=this.head,this.states=null}_push(e,t,n){return this.tail=this.tail.next=new Ze(e,t,n),this.len+=t,this}uint32(e){return this.len+=(this.tail=this.tail.next=new Wi((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(Ur,10,ee.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){let t=ee.fromBigInt(e);return this._push(Ur,t.length(),t)}uint64Number(e){return this._push(ms,Ut(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=ee.fromBigInt(e).zzEncode();return this._push(Ur,t.length(),t)}sint64Number(e){let t=ee.fromNumber(e).zzEncode();return this._push(Ur,t.length(),t)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(Vi,1,e?1:0)}fixed32(e){return this._push(jt,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){let t=ee.fromBigInt(e);return this._push(jt,4,t.lo)._push(jt,4,t.hi)}fixed64Number(e){let t=ee.fromNumber(e);return this._push(jt,4,t.lo)._push(jt,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(gs,4,e)}double(e){return this._push(bs,8,e)}bytes(e){let t=e.length>>>0;return t===0?this._push(Vi,1,0):this.uint32(t)._push(af,t,e)}string(e){let t=vs(e);return t!==0?this.uint32(t)._push(gi,t,e):this._push(Vi,1,0)}fork(){return this.states=new Hi(this),this.head=this.tail=new Ze(ji,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 Ze(ji,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=of(this.len),n=0;for(;e!=null;)e.fn(e.val,t,n),n+=e.len,e=e.next;return t}};function Vi(r,e,t){e[t]=r&255}function sf(r,e,t){for(;r>127;)e[t++]=r&127|128,r>>>=7;e[t]=r}var Wi=class extends Ze{next;constructor(e,t){super(sf,e,t),this.next=void 0}};function Ur(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 jt(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 af(r,e,t){e.set(r,t)}globalThis.Buffer!=null&&(Vt.prototype.bytes=function(r){let e=r.length>>>0;return this.uint32(e),e>0&&this._push(cf,e,r),this},Vt.prototype.string=function(r){let e=globalThis.Buffer.byteLength(r);return this.uint32(e),e>0&&this._push(uf,e,r),this});function cf(r,e,t){e.set(r,t)}function uf(r,e,t){r.length<40?gi(r,e,t):e.utf8Write!=null?e.utf8Write(r,t):e.set(L(r),t)}function Gi(){return new Vt}function Mr(r,e){let t=Gi();return e.encode(r,t,{lengthDelimited:!1}),t.finish()}function*$r(r,e,t){let n=Mt(r);yield*e.stream(n,void 0,"$",t)}var Or={VARINT:0,BIT64:1,LENGTH_DELIMITED:2,START_GROUP:3,END_GROUP:4,BIT32:5};function Kr(r,e,t,n,i){return{name:r,type:e,encode:t,decode:n,stream:i}}function Ji(r){function e(o){if(r[o.toString()]==null)throw new Error("Invalid enum value");return r[o]}let t=function(s,a){let c=e(s);a.int32(c)},n=function(s){let a=s.int32();return e(a)},i=function*(s){let a=s.int32();yield e(a)};return Kr("enum",Or.VARINT,t,n,i)}function zr(r,e,t){return Kr("message",Or.LENGTH_DELIMITED,r,e,t)}var qr;(function(r){r.RSA="RSA",r.Ed25519="Ed25519",r.secp256k1="secp256k1",r.ECDSA="ECDSA"})(qr||(qr={}));var Qi;(function(r){r[r.RSA=0]="RSA",r[r.Ed25519=1]="Ed25519",r[r.secp256k1=2]="secp256k1",r[r.ECDSA=3]="ECDSA"})(Qi||(Qi={}));(function(r){r.codec=()=>Ji(Qi)})(qr||(qr={}));var Y;(function(r){let e;r.codec=()=>(e==null&&(e=zr((o,s,a={})=>{a.lengthDelimited!==!1&&s.fork(),o.Type!=null&&(s.uint32(8),s.int32(o.Type)),o.Data!=null&&(s.uint32(18),s.bytes(o.Data)),a.lengthDelimited!==!1&&s.ldelim()},(o,s,a={})=>{let c={},f=s==null?o.len:o.pos+s;for(;o.pos<f;){let l=o.uint32();switch(l>>>3){case 1:{c.Type=o.int32();break}case 2:{c.Data=o.bytes();break}default:{o.skipType(l&7);break}}}return c},function*(o,s,a,c={}){let f=s==null?o.len:o.pos+s;for(;o.pos<f;){let l=o.uint32();switch(l>>>3){case 1:{yield{field:`${a}.Type`,value:o.int32()};break}case 2:{yield{field:`${a}.Data`,value:o.bytes()};break}default:{o.skipType(l&7);break}}}})),e);function t(o){return Mr(o,r.codec())}r.encode=t;function n(o,s){return Dr(o,r.codec(),s)}r.decode=n;function i(o,s){return $r(o,r.codec(),s)}r.stream=i})(Y||(Y={}));var H;(function(r){let e;r.codec=()=>(e==null&&(e=zr((o,s,a={})=>{a.lengthDelimited!==!1&&s.fork(),o.Type!=null&&(s.uint32(8),s.int32(o.Type)),o.Data!=null&&(s.uint32(18),s.bytes(o.Data)),a.lengthDelimited!==!1&&s.ldelim()},(o,s,a={})=>{let c={},f=s==null?o.len:o.pos+s;for(;o.pos<f;){let l=o.uint32();switch(l>>>3){case 1:{c.Type=o.int32();break}case 2:{c.Data=o.bytes();break}default:{o.skipType(l&7);break}}}return c},function*(o,s,a,c={}){let f=s==null?o.len:o.pos+s;for(;o.pos<f;){let l=o.uint32();switch(l>>>3){case 1:{yield{field:`${a}.Type`,value:o.int32()};break}case 2:{yield{field:`${a}.Data`,value:o.bytes()};break}default:{o.skipType(l&7);break}}}})),e);function t(o){return Mr(o,r.codec())}r.encode=t;function n(o,s){return Dr(o,r.codec(),s)}r.decode=n;function i(o,s){return $r(o,r.codec(),s)}r.stream=i})(H||(H={}));function ce(r,e="utf8"){let t=Fr[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.encoder.encode(r).substring(1)}var Ne="/",Vs=new TextEncoder().encode(Ne),jr=Vs[0],B=class r{_buf;constructor(e,t){if(typeof e=="string")this._buf=L(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]!==jr)throw new Error("Invalid key")}toString(e="utf8"){return ce(this._buf,e)}uint8Array(){return this._buf}get[Symbol.toStringTag](){return`Key(${this.toString()})`}static withNamespaces(e){return new r(e.join(Ne))}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=Vs),this._buf[0]!==jr){let e=new Uint8Array(this._buf.byteLength+1);e.fill(jr,0,1),e.set(this._buf,1),this._buf=e}for(;this._buf.byteLength>1&&this._buf[this._buf.byteLength-1]===jr;)this._buf=this._buf.subarray(0,-1)}less(e){let t=this.list(),n=e.list();for(let i=0;i<t.length;i++){if(n.length<i+1)return!1;let o=t[i],s=n[i];if(o<s)return!0;if(o>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(Ne).slice(1)}type(){return lf(this.baseNamespace())}name(){return ff(this.baseNamespace())}instance(e){return new r(this.toString()+":"+e)}path(){let e=this.parent().toString();return e.endsWith(Ne)||(e+=Ne),e+=this.type(),new r(e)}parent(){let e=this.list();return e.length===1?new r(Ne):new r(e.slice(0,-1).join(Ne))}child(e){return this.toString()===Ne?e:e.toString()===Ne?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(),...hf(e.map(t=>t.namespaces()))])}};function lf(r){let e=r.split(":");return e.length<2?"":e.slice(0,-1).join(":")}function ff(r){let e=r.split(":");return e[e.length-1]}function hf(r){return[].concat(...r)}var ga=pi(ea(),1);function Af(r){return r?.buffer instanceof ArrayBuffer}function ta(r){if(Af(r))return r;let e=r.slice();return new Uint8Array(e.buffer,0,e.byteLength)}function ge(r,e){e==null&&(e=r.reduce((i,o)=>i+o.length,0));let t=Z(e),n=0;for(let i of r)t.set(i,n),n+=i.length;return ta(t)}var W=class extends Error{static name="InvalidParametersError";name="InvalidParametersError"},Ht=class extends Error{static name="DecryptionFailedError";name="DecryptionFailedError"};function Re(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 na=Symbol.for("@achingbrain/uint8arraylist");function ra(r,e){if(e==null||e<0)throw new RangeError("index is out of bounds");let t=0;for(let n of r){let i=t+n.byteLength;if(e<i)return{buf:n,index:e-t};t=i}throw new RangeError("index is out of bounds")}function Vr(r){return!!r?.[na]}var G=class r{bufs;length;[na]=!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(Vr(n)){t+=n.byteLength;for(let i of n.bufs)this.bufs.push(i)}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(Vr(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=ra(this.bufs,e);return t.buf[t.index]}set(e,t){let n=ra(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(Vr(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:i}=this._subList(e,t);return ge(n,i)}subarray(e,t){let{bufs:n,length:i}=this._subList(e,t);return n.length===1?n[0]:ge(n,i)}sublist(e,t){let{bufs:n,length:i}=this._subList(e,t),o=new r;return o.length=i,o.bufs=n,o}_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=[],i=0;for(let o=0;o<this.bufs.length;o++){let s=this.bufs[o],a=i,c=a+s.byteLength;if(i=c,e>=c)continue;let f=e>=a&&e<c,l=t>a&&t<=c;if(f&&l){if(e===a&&t===c){n.push(s);break}let h=e-a;n.push(s.subarray(h,h+(t-e)));break}if(f){if(e===0){n.push(s);continue}n.push(s.subarray(e-a));continue}if(l){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(!Vr(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 i=n.byteLength;if(i===0)throw new TypeError("search must be at least 1 byte long");let o=256,s=new Int32Array(o);for(let h=0;h<o;h++)s[h]=-1;for(let h=0;h<i;h++)s[n[h]]=h;let a=s,c=this.byteLength-n.byteLength,f=n.byteLength-1,l;for(let h=t;h<=c;h+=l){l=0;for(let d=f;d>=0;d--){let g=this.get(h+d);if(n[d]!==g){l=Math.max(1,d-a[g]);break}}if(l===0)return h}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=Z(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 i=pe(2);new DataView(i.buffer,i.byteOffset,i.byteLength).setInt16(0,t,n),this.write(i,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 i=pe(4);new DataView(i.buffer,i.byteOffset,i.byteLength).setInt32(0,t,n),this.write(i,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 i=pe(8);new DataView(i.buffer,i.byteOffset,i.byteLength).setBigInt64(0,t,n),this.write(i,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=Z(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 i=pe(2);new DataView(i.buffer,i.byteOffset,i.byteLength).setUint16(0,t,n),this.write(i,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 i=pe(4);new DataView(i.buffer,i.byteOffset,i.byteLength).setUint32(0,t,n),this.write(i,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 i=pe(8);new DataView(i.buffer,i.byteOffset,i.byteLength).setBigUint64(0,t,n),this.write(i,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 i=pe(4);new DataView(i.buffer,i.byteOffset,i.byteLength).setFloat32(0,t,n),this.write(i,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 i=pe(8);new DataView(i.buffer,i.byteOffset,i.byteLength).setFloat64(0,t,n),this.write(i,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(!Re(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((i,o)=>i+o.byteLength,0)),n.length=t,n}};var Sf=parseInt("11111",2),Yi=parseInt("10000000",2),If=parseInt("01111111",2),ia={0:Wt,1:Wt,2:Cf,3:Df,4:Pf,5:Lf,6:Tf,16:Wt,22:Wt,48:Wt};function we(r,e={offset:0}){let t=r[e.offset]&Sf;if(e.offset++,ia[t]!=null)return ia[t](r,e);throw new Error("No decoder for tag 0x"+t.toString(16).padStart(2,"0"))}function Gt(r,e){let t=0;if((r[e.offset]&Yi)===Yi){let n=r[e.offset]&If,i="0x";e.offset++;for(let o=0;o<n;o++,e.offset++)i+=r[e.offset].toString(16).padStart(2,"0");t=parseInt(i,16)}else t=r[e.offset],e.offset++;return t}function Wt(r,e){Gt(r,e);let t=[];for(;!(e.offset>=r.byteLength);){let n=we(r,e);if(n===null)break;t.push(n)}return t}function Cf(r,e){let t=Gt(r,e),n=e.offset,i=e.offset+t,o=[];for(let s=n;s<i;s++)s===n&&r[s]===0||o.push(r[s]);return e.offset+=t,Uint8Array.from(o)}function Tf(r,e){let t=Gt(r,e),n=e.offset+t,i=r[e.offset];e.offset++;let o=0,s=0;i<40?(o=0,s=i):i<80?(o=1,s=i-40):(o=2,s=i-80);let a=`${o}.${s}`,c=[];for(;e.offset<n;){let f=r[e.offset];if(e.offset++,c.push(f&127),f<128){c.reverse();let l=0;for(let h=0;h<c.length;h++)l+=c[h]<<h*7;a+=`.${l}`,c=[]}}return a}function Lf(r,e){return e.offset++,null}function Df(r,e){let t=Gt(r,e),n=r[e.offset];e.offset++;let i=r.subarray(e.offset,e.offset+t-1);if(e.offset+=t,n!==0)throw new Error("Unused bits in bit string is unimplemented");return i}function Pf(r,e){let t=Gt(r,e),n=r.subarray(e.offset,e.offset+t);return e.offset+=t,n}function Nf(r){let e=r.toString(16);e.length%2===1&&(e="0"+e);let t=new G;for(let n=0;n<e.length;n+=2)t.append(Uint8Array.from([parseInt(`${e[n]}${e[n+1]}`,16)]));return t}function Hr(r){if(r.byteLength<128)return Uint8Array.from([r.byteLength]);let e=Nf(r.byteLength);return new G(Uint8Array.from([e.byteLength|Yi]),e)}function J(r){let e=new G,t=128;return(r.subarray()[0]&t)===t&&e.append(Uint8Array.from([0])),e.append(r),new G(Uint8Array.from([2]),Hr(e),e)}function Jt(r){let e=Uint8Array.from([0]),t=new G(e,r);return new G(Uint8Array.from([3]),Hr(t),t)}function oa(r){return new G(Uint8Array.from([4]),Hr(r),r)}function be(r,e=48){let t=new G;for(let n of r)t.append(N(n.subarray()));return new G(Uint8Array.from([e]),Hr(t),t)}var S=class extends Error{static name="InvalidParametersError";name="InvalidParametersError"};var Rf=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),Bf=Uint8Array.from([6,5,43,129,4,0,34]),Ff=Uint8Array.from([6,5,43,129,4,0,35]),sa={ext:!0,kty:"EC",crv:"P-256"},aa={ext:!0,kty:"EC",crv:"P-384"},ca={ext:!0,kty:"EC",crv:"P-521"},wt=32,bt=48,xt=66,Qt=class{type="ECDSA";code=3;jwk;constructor(e){this.jwk=e}toMultihash(){return Ke.digest(this.toProtobuf())}toCID(){return v.createV1(114,this.toMultihash())}toString(){return R.encode(this.toMultihash().bytes).substring(1)}toJWK(){return JSON.parse(JSON.stringify(this.jwk))}toProtobuf(){return Y.encode({Type:this.code,Data:Of(this.jwk)})}async verify(e,t,n){let i=await crypto.subtle.importKey("jwk",this.jwk,{name:"ECDSA",namedCurve:this.jwk.crv??"P-256"},!1,["verify"]),o=await crypto.subtle.verify({name:"ECDSA",hash:{name:"SHA-256"}},i,N(t),N(e));return n?.signal?.throwIfAborted(),o}},Wr=class{type="ECDSA";code=3;jwk;publicKey;constructor(e,t){this.jwk=e,this.publicKey=t}toProtobuf(){return H.encode({Type:this.code,Data:Kf(this.jwk)})}toJWK(){return JSON.parse(JSON.stringify(this.jwk))}async sign(e,t){let n=await crypto.subtle.importKey("jwk",this.jwk,{name:"ECDSA",namedCurve:this.jwk.crv??"P-256"},!0,["sign"]),i=await crypto.subtle.sign({name:"ECDSA",hash:{name:"SHA-256"}},n,N(e));return t?.signal?.throwIfAborted(),new Uint8Array(i,0,i.byteLength)}},Xi=class{type="ECDSA";code=3;async generatePrivateKey(e){let t=e?.curve??"P-256",n=await crypto.subtle.generateKey({name:"ECDSA",namedCurve:t},!0,["sign","verify"]),i=await crypto.subtle.exportKey("jwk",n.privateKey),o=await crypto.subtle.exportKey("jwk",n.publicKey);return e?.signal?.throwIfAborted(),new Wr(i,new Qt(o))}async publicKeyFromProtobuf(e,t){let n=Y.decode(e);if(n.Data==null)throw new S("Data field was missing from protobuf");if(n.Type!==this.code)throw new S("Incorrect Type field in protobuf");t?.signal?.throwIfAborted();let i=$f(n.Data);return new Qt(i)}async privateKeyFromProtobuf(e,t){let n=H.decode(e);if(n.Data==null)throw new S("Data field was missing from protobuf");if(n.Type!==this.code)throw new S("Incorrect Type field in protobuf");let i=Mf(n.Data),o=Uf(i);return t?.signal?.throwIfAborted(),new Wr(i,new Qt(o))}};function Zi(){return new Xi}function Uf(r){return{crv:r.crv,ext:!0,key_ops:["verify"],kty:"EC",x:r.x,y:r.y}}function Mf(r){let e=we(r),t=e[1],n=b.baseEncode(t),i=e[2][1][0],o=1,s,a;if(t.byteLength===wt)return s=b.baseEncode(i.subarray(o,o+wt)),a=b.baseEncode(i.subarray(o+wt)),{...sa,key_ops:["sign"],d:n,x:s,y:a};if(t.byteLength===bt)return s=b.baseEncode(i.subarray(o,o+bt)),a=b.baseEncode(i.subarray(o+bt)),{...aa,key_ops:["sign"],d:n,x:s,y:a};if(t.byteLength===xt)return s=b.baseEncode(i.subarray(o,o+xt)),a=b.baseEncode(i.subarray(o+xt)),{...ca,key_ops:["sign"],d:n,x:s,y:a};throw new S(`Private key length was wrong length, got ${t.byteLength}, expected 32, 48 or 66`)}function $f(r){let t=we(r)[1][1][0],n=1,i,o;if(t.byteLength===wt*2+1)return i=b.baseEncode(t.subarray(n,n+wt)),o=b.baseEncode(t.subarray(n+wt)),{...sa,key_ops:["verify"],x:i,y:o};if(t.byteLength===bt*2+1)return i=b.baseEncode(t.subarray(n,n+bt)),o=b.baseEncode(t.subarray(n+bt)),{...aa,key_ops:["verify"],x:i,y:o};if(t.byteLength===xt*2+1)return i=b.baseEncode(t.subarray(n,n+xt)),o=b.baseEncode(t.subarray(n+xt)),{...ca,key_ops:["verify"],x:i,y:o};throw new S(`coordinates were wrong length, got ${t.byteLength}, expected 65, 97 or 133`)}function Of(r){return be([J(Uint8Array.from([1])),be([ua(r.crv)],160),be([Jt(new G(Uint8Array.from([4]),b.baseDecode(r.x??""),b.baseDecode(r.y??"")))],161)]).subarray()}function Kf(r){return be([J(Uint8Array.from([1])),oa(b.baseDecode(r.d??"")),be([ua(r.crv)],160),be([Jt(new G(Uint8Array.from([4]),b.baseDecode(r.x??""),b.baseDecode(r.y??"")))],161)]).subarray()}function ua(r){if(r==="P-256")return Rf;if(r==="P-384")return Bf;if(r==="P-521")return Ff;throw new S(`Invalid curve ${r}`)}var zf=32,Yt=class{type="Ed25519";code=1;jwk;constructor(e){this.jwk=e}toMultihash(){return Ke.digest(this.toProtobuf())}toCID(){return v.createV1(114,this.toMultihash())}toString(){return R.encode(this.toMultihash().bytes).substring(1)}toJWK(){return JSON.parse(JSON.stringify(this.jwk))}toProtobuf(){return Y.encode({Type:this.code,Data:b.baseDecode(this.jwk.x??"")})}async verify(e,t,n){let i=await crypto.subtle.importKey("jwk",this.jwk,{name:"Ed25519"},!1,["verify"]),o=await crypto.subtle.verify({name:"Ed25519"},i,N(t),N(e));return n?.signal?.throwIfAborted(),o}},Gr=class{type="Ed25519";code=1;jwk;publicKey;constructor(e,t){this.jwk=e,this.publicKey=t}toProtobuf(){return H.encode({Type:this.code,Data:ge([b.baseDecode(this.jwk.d??""),b.baseDecode(this.jwk.x??"")],64)})}toJWK(){return JSON.parse(JSON.stringify(this.jwk))}async sign(e,t){let n=await crypto.subtle.importKey("jwk",this.jwk,{name:"Ed25519"},!0,["sign"]),i=await crypto.subtle.sign({name:"Ed25519"},n,N(e));return t?.signal?.throwIfAborted(),new Uint8Array(i,0,i.byteLength)}},eo=class{type="Ed25519";code=1;async generatePrivateKey(e){let t=await crypto.subtle.generateKey("Ed25519",!0,["sign","verify"]),n=await crypto.subtle.exportKey("jwk",t.privateKey),i=await crypto.subtle.exportKey("jwk",t.publicKey);return e?.signal?.throwIfAborted(),new Gr(n,new Yt(i))}async publicKeyFromProtobuf(e,t){let n=Y.decode(e);if(n.Data==null)throw new S("Data field was missing from protobuf");if(n.Type!==this.code)throw new S("Incorrect Type field in protobuf");t?.signal?.throwIfAborted();let i=Hf(n.Data);return new Yt(i)}async privateKeyFromProtobuf(e,t){let n=H.decode(e);if(n.Data==null)throw new S("Data field was missing from protobuf");if(n.Type!==this.code)throw new S("Incorrect Type field in protobuf");let i=await qf(n.Data,t),o=Vf(i);return new Gr(i,new Yt(o))}};function to(){return new eo}async function qf(r,e){let t=r.subarray(0,zf),n=jf(t),i=await crypto.subtle.importKey("pkcs8",n,{name:"Ed25519"},!0,["sign"]),o=await crypto.subtle.exportKey("jwk",i);return e?.signal?.throwIfAborted(),o}var la=Uint8Array.from([48,46,2,1,0,48,5,6,3,43,101,112,4,34,4]);function jf(r){return ge([la,Uint8Array.from([r.byteLength]),r],la.byteLength+1+r.byteLength)}function Vf(r){return{alg:"Ed25519",crv:"Ed25519",ext:!0,key_ops:["verify"],kty:"OKP",x:r.x}}function Hf(r){return{alg:"Ed25519",crv:"Ed25519",ext:!0,key_ops:["verify"],kty:"OKP",x:b.baseEncode(r)}}var io=8192,Xt=class{type="RSA";code=0;_raw;digest;jwk;constructor(e,t){if(ha(e)>io)throw new S("Key size is too large");this.jwk=e,this.digest=t}toMultihash(){return this.digest}toCID(){return v.createV1(114,this.toMultihash())}toString(){return this.toCID().toString(te)}toProtobuf(){return Xf(this.code,this.jwk)}toJWK(){return JSON.parse(JSON.stringify(this.jwk))}async verify(e,t,n){let i=await crypto.subtle.importKey("jwk",this.jwk,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]),o=await crypto.subtle.verify({name:"RSASSA-PKCS1-v1_5"},i,N(t),N(e));return n?.signal?.throwIfAborted(),o}},Jr=class{type="RSA";code=0;publicKey;jwk;constructor(e,t){if(ha(e)>io)throw new S("Key size is too large");this.jwk=e,this.publicKey=t}toProtobuf(){return Zf(this.code,this.jwk)}toJWK(){return JSON.parse(JSON.stringify(this.jwk))}async sign(e,t){let n=await crypto.subtle.importKey("jwk",this.jwk,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]),i=await crypto.subtle.sign({name:"RSASSA-PKCS1-v1_5"},n,N(e));return t?.signal?.throwIfAborted(),new Uint8Array(i,0,i.byteLength)}},no=class{type="RSA";code=0;async generatePrivateKey(e){let t=e?.bits??2048;if(t>io)throw new S("Key size is too large");let n=await crypto.subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:t,publicExponent:new Uint8Array([1,0,1]),hash:{name:"SHA-256"}},!0,["sign","verify"]),i=await crypto.subtle.exportKey("jwk",n.privateKey),o=await crypto.subtle.exportKey("jwk",n.publicKey),s=await ro(i);return e?.signal?.throwIfAborted(),new Jr(i,new Xt(o,s))}async publicKeyFromProtobuf(e,t){let n=Y.decode(e);if(n.Data==null)throw new S("Data field was missing from protobuf");if(n.Type!==this.code)throw new S("Incorrect Type field in protobuf");let i=Qf(n.Data),o=await ro(i);return t?.signal?.throwIfAborted(),new Xt(i,o)}async privateKeyFromProtobuf(e,t){let n=H.decode(e);if(n.Data==null)throw new S("Data field was missing from protobuf");if(n.Type!==this.code)throw new S("Incorrect Type field in protobuf");let i=we(n.Data),o=Wf(i),s=Yf(o),a=await ro(s);return t?.signal?.throwIfAborted(),new Jr(o,new Xt(s,a))}};function Zt(){return new no}function Wf(r){return{alg:"RS256",kty:"RSA",n:b.baseEncode(r[1]),e:b.baseEncode(r[2]),ext:!0,key_ops:["sign"],d:b.baseEncode(r[3]),p:b.baseEncode(r[4]),q:b.baseEncode(r[5]),dp:b.baseEncode(r[6]),dq:b.baseEncode(r[7]),qi:b.baseEncode(r[8])}}function Gf(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 S("JWK was missing components");return be([J(Uint8Array.from([0])),J(b.baseDecode(r.n)),J(b.baseDecode(r.e)),J(b.baseDecode(r.d)),J(b.baseDecode(r.p)),J(b.baseDecode(r.q)),J(b.baseDecode(r.dp)),J(b.baseDecode(r.dq)),J(b.baseDecode(r.qi))]).subarray()}var Jf=Uint8Array.from([48,13,6,9,42,134,72,134,247,13,1,1,1,5,0]);function fa(r){if(r.n==null||r.e==null)throw new S("JWK public key was missing components");return be([Jf,Jt(be([J(b.baseDecode(r.n)),J(b.baseDecode(r.e))]))]).subarray()}function Qf(r){let e=we(r);if(e.length<2||e[0]?.[0]!=="1.2.840.113549.1.1.1")throw new Error("PKIX certificate was invalid");let t=we(e[1]);return{kty:"RSA",n:b.baseEncode(t[0]),e:b.baseEncode(t[1])}}function Yf(r){return{key_ops:["verify"],ext:!0,alg:"RS256",kty:"RSA",n:r.n,e:"AQAB"}}function ha(r){if(r.kty!=="RSA")throw new S("Invalid key type");if(r.n==null)throw new S("Invalid key modulus");return b.baseDecode(r.n).length*8}async function ro(r){let e=Y.encode({Type:0,Data:fa(r)});return ze.digest(e)}function Xf(r,e){return Y.encode({Type:r,Data:fa(e)})}function Zf(r,e){return H.encode({Type:r,Data:Gf(e)})}async function pa(r,e,t){r=r.replaceAll("-----BEGIN ENCRYPTED PRIVATE KEY-----",""),r=r.replaceAll("-----END ENCRYPTED PRIVATE KEY-----",""),r=r.replaceAll("\r",""),r=r.replaceAll(`
3
- `,"");let n=V.decode(`m${r}`),i=we(n),o=i[0][1][0][1][0],s=da(i[0][1][0][1][1]),a=da(i[0][1][0][1][2]),c=i[0][1][0][1][4][1],f=i[0][1][0][1][4][2],l=await e.decrypt(o,c,f,{iterations:s,keyLength:a*8,hash:"SHA-512",algorithm:"AES-CBC",signal:t?.signal}),d=we(l)[2],g=H.encode({Type:0,Data:d});return Zt().privateKeyFromProtobuf(g)}function da(r){if(r.length===0)return 0;let e=[...r].map(t=>t.toString(16).padStart(2,"0")).join("");return parseInt(e,16)}var eh="/pkcs8/",wa="/info/",th=Symbol.for("@libp2p/service-capabilities"),er={iterations:1e4,salt:L("you should override this value with a crypto secure random number"),hash:"SHA-512",algorithm:"AES-GCM"},Et={iterations:32767,saltLength:16,ivLength:12,hash:"SHA-256",keyLength:128,algorithm:"AES-GCM"},oo=20,Qr={minKeyLength:112/8,minSaltLength:128/8,minIterations:1e3},ma={"SHA-256":128,"SHA-384":192,"SHA-512":256};function tr(r){return r==null||typeof r!="string"?!1:r===(0,ga.default)(r.trim())&&r.length>0}function vt(r){return new B(eh+r)}function Yr(r){return new B(wa+r)}async function rh(r,e){let t=r.toProtobuf(),n=await ze.digest(t);return e?.signal?.throwIfAborted(),R.encode(n.bytes).substring(1)}function nh(r){if(typeof r=="string")return L(r);if(r instanceof Uint8Array)return N(r)}var Xr=class{components;self;cipher;salt;keychainDekOptions;privateKeyDekOptions;constructor(e,t={}){if(this.components=e,this.self=t.selfKey??"self",this.salt=nh(t.salt)??er.salt,this.keychainDekOptions={iterations:t.iterations??er.iterations,hash:t.hash??er.hash,keyLength:ma[t.hash??er.hash],algorithm:er.algorithm},this.privateKeyDekOptions={iterations:Et.iterations,hash:Et.hash,saltLength:Et.saltLength,ivLength:Et.ivLength,keyLength:Et.keyLength,algorithm:Et.algorithm},t.password!=null&&t.password.length<oo)throw new Error("password must be least 20 characters");if(this.salt.byteLength!=null&&this.salt.byteLength<Qr.minSaltLength)throw new Error(`salt must be least ${Qr.minSaltLength} bytes`);if(t.iterations!=null&&t.iterations<Qr.minIterations)throw new Error(`iterations must be least ${Qr.minIterations}`);if(ma[this.keychainDekOptions.hash]==null)throw new W("Unsupported hash");this.cipher=ya(t.password??"",this.salt,this.keychainDekOptions,this.privateKeyDekOptions)}[th]=["@ipshipyard/keychain"];async generateKey(e,t){let i=await(await this.components.getCrypto(t?.type??"Ed25519",t)).generatePrivateKey(t);return this.importKey(e,i,t)}async importKey(e,t,n){if(!tr(e))throw new W(`Invalid key name '${e}'`);if(t==null)throw new W("Key is required");if(await this.components.datastore.has(vt(e),n))throw new W(`Key '${e}' already exists`);let o=this.components.datastore.batch();return await this._importKey(e,t,this.cipher,o,n),await o.commit(n),t}async _importKey(e,t,n,i,o){let s=t.toProtobuf(),a=await n.encrypt(s),c=ge([a.salt,a.iv,a.cipherText],a.salt.byteLength+a.iv.byteLength+a.cipherText.byteLength),f=V.encode(c),l={name:e,id:await rh(t,o)};i.put(vt(e),L(f)),i.put(Yr(e),L(JSON.stringify(l)))}async exportKey(e,t){if(!tr(e))throw new W(`Invalid key name '${e}'`);return this._exportKey(e,this.cipher,t)}async _exportKey(e,t,n){let i=await this.components.datastore.get(vt(e),n),o=ce(i),s;if(o.includes("BEGIN ENCRYPTED PRIVATE KEY"))return pa(o,t,n);try{let a=V.decode(o),c=a.subarray(0,16),f=a.subarray(16,28),l=a.subarray(28),h=await t.decrypt(c,f,l,n),d=H.decode(h);if(d.Type==null)throw new Ht("Unknown key type");return s=await this.components.getCrypto(d.Type,n),await s.privateKeyFromProtobuf(h)}catch(a){throw a.name==="OperationError"?new Ht(a.message):a}}async removeKey(e,t){if(!tr(e)||e===this.self)throw new W(`Invalid key name '${e}'`);let n=this.components.datastore.batch();n.delete(vt(e)),n.delete(Yr(e)),await n.commit(t)}async*listKeys(e){let t={prefix:wa};for await(let n of this.components.datastore.query(t,e))yield JSON.parse(ce(n.value))}async renameKey(e,t,n){if(!tr(e)||e===this.self)throw new W(`Invalid old key name '${e}'`);if(!tr(t)||t===this.self)throw new W(`Invalid new key name '${t}'`);let i=vt(e),o=vt(t),s=Yr(e),a=Yr(t);if(await this.components.datastore.has(o,n))throw new W(`Key '${t}' already exists`);let f=await this.components.datastore.get(i,n),l=await this.components.datastore.get(s,n),h=JSON.parse(ce(l));h.name=t;let d=this.components.datastore.batch();d.put(o,f),d.put(a,L(JSON.stringify(h))),d.delete(i),d.delete(s),await d.commit(n)}async rotateKeychainPass(e,t){if(typeof e!="string")throw new W(`Invalid new pass type '${typeof e}'`);if(e.length<oo)throw new W(`Invalid pass length ${e.length}, must be at least ${oo}`);let n=this.cipher,i=this.cipher=ya(e,this.salt,this.keychainDekOptions,this.privateKeyDekOptions),o=this.components.datastore.batch();for await(let s of this.listKeys(t)){let a=await this._exportKey(s.name,n);await this._importKey(s.name,a,i,o,t)}await o.commit(t)}async loadPublicKeyFromProtobuf(e,t){let n=Y.decode(e);if(n.Type==null)throw new W("Protobuf was missing Type");return(await this.components.getCrypto(n.Type,t)).publicKeyFromProtobuf(e,t)}},ih={alg:"A128GCM",ext:!0,k:"scm9jmO_4BJAgdwWGVulLg",key_ops:["encrypt","decrypt"],kty:"oct"};function ya(r,e,t,n){let i;async function o(f,l,h,d){let g,w=L(f),A=await crypto.subtle.importKey("raw",w,{name:"PBKDF2"},!1,["deriveKey"]);try{g=await crypto.subtle.deriveKey({name:"PBKDF2",salt:N(l),iterations:d.iterations,hash:{name:d.hash}},A,{name:d.algorithm??"AES-GCM",length:d.keyLength},!0,h)}catch(E){if(f==="")g=await crypto.subtle.importKey("jwk",ih,{name:d.algorithm??"AES-GCM"},!0,h);else throw E}return g}async function s(){if(r==="")return r;let f=await o(r,e,["encrypt","decrypt"],t);return(await crypto.subtle.exportKey("jwk",f)).k??""}async function a(f,l){i==null&&(i=await s());let h=crypto.getRandomValues(new Uint8Array(n.saltLength)),d=crypto.getRandomValues(new Uint8Array(n.ivLength)),g=await o(i,h,["encrypt"],n),w=await crypto.subtle.encrypt({name:"AES-GCM",iv:d},g,f);return l?.signal?.throwIfAborted(),{salt:h,iv:d,cipherText:new Uint8Array(w)}}async function c(f,l,h,d){i==null&&(i=await s());let g=await o(i,f,["decrypt"],{iterations:d?.iterations??n.iterations,keyLength:d?.keyLength??n.keyLength,hash:d?.hash??n.hash,algorithm:d?.algorithm??"AES-GCM"}),w=await crypto.subtle.decrypt({name:d?.algorithm??"AES-GCM",iv:N(l)},g,N(h));return d?.signal?.throwIfAborted(),new Uint8Array(w)}return{encrypt:a,decrypt:c}}function ba(r){return e=>new Xr(e,r)}var xe=class extends Error{static name="AbortError";constructor(e="The operation was aborted"){super(e),this.name="AbortError"}};var _t=class extends Error{static name="InvalidParametersError";constructor(e="Invalid parameters"){super(e),this.name="InvalidParametersError"}};var Zr=class extends Error{static name="NotFoundError";constructor(e="Not found"){super(e),this.name="NotFoundError"}};var en=class extends Error{static name="InvalidMultihashError";constructor(e="Invalid Multihash"){super(e),this.name="InvalidMultihashError"}};function xa(r){return r!=null&&typeof r.start=="function"&&typeof r.stop=="function"}async function qe(...r){let e=[];for(let t of r)xa(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 je(...r){let e=[];for(let t of r)xa(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 oh(r){return typeof r?.handleEvent=="function"}function sh(r){return(r!==!0&&r!==!1&&r?.once)??!1}var ue=class extends EventTarget{#e=new Map;constructor(){super()}listenerCount(e){let t=this.#e.get(e);return t==null?0:t.length}addEventListener(e,t,n){let i=sh(n);super.addEventListener(e,s=>{if(i){let a=this.#e.get(s.type);a!=null&&(a=a.filter(({callback:c})=>c!==t),this.#e.set(s.type,a))}oh(t)?t.handleEvent(s):t(s)},n);let o=this.#e.get(e);o==null&&(o=[],this.#e.set(e,o)),o.push({callback:t,once:i})}removeEventListener(e,t,n){super.removeEventListener(e.toString(),t??null,n);let i=this.#e.get(e);i!=null&&(i=i.filter(({callback:o})=>o!==t),this.#e.set(e,i))}safeDispatchEvent(e,t={}){return this.dispatchEvent(new CustomEvent(e,t))}};var x=class extends Event{type;detail;constructor(e,t){super(e),this.type=e,this.detail=t}};var tn=class extends AggregateError{static name="DNSQueryFailedError";name="DNSQueryFailedError"};var ao=pi(va(),1);var co=class r extends Error{name="TimeoutError";constructor(e,t){super(e,t),Error.captureStackTrace?.(this,r)}},_a=r=>r.reason??new DOMException("This operation was aborted.","AbortError");function nr(r,e){let{milliseconds:t,fallback:n,message:i,customTimers:o={setTimeout,clearTimeout},signal:s}=e,a,c,l=new Promise((h,d)=>{if(typeof t!="number"||Math.sign(t)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${t}\``);if(s?.aborted){d(_a(s));return}if(s&&(c=()=>{d(_a(s))},s.addEventListener("abort",c,{once:!0})),r.then(h,d),t===Number.POSITIVE_INFINITY)return;let g=new co;a=o.setTimeout.call(void 0,()=>{if(n){try{h(n())}catch(w){d(w)}return}typeof r.cancel=="function"&&r.cancel(),i===!1?h():i instanceof Error?d(i):(g.message=i??`Promise timed out after ${t} milliseconds`,d(g))},t)}).finally(()=>{l.clear(),c&&s&&s.removeEventListener("abort",c)});return l.clear=()=>{o.clearTimeout.call(void 0,a),a=void 0},l}function uo(r,e,t){let n=0,i=r.length;for(;i>0;){let o=Math.trunc(i/2),s=n+o;t(r[s],e)<=0?(n=++s,i-=o+1):i=o}return n}var uh=100,kt=class{#e=[];#t=0;enqueue(e,t){let{priority:n=0,id:i}=t??{},{size:o}=this,s={priority:n,id:i,run:e};if(o===0){this.#e.length=0,this.#t=0,this.#e.push(s);return}if(this.#e.at(-1).priority>=n){this.#e.push(s);return}this.#o();let a=uo(this.#e,s,(c,f)=>f.priority-c.priority);this.#e.splice(a,0,s)}setPriority(e,t){let n=this.#e.findIndex((o,s)=>s>=this.#t&&o.id===e);if(n===-1)throw new ReferenceError(`No promise function with the id "${e}" exists in the queue.`);let[i]=this.#e.splice(n,1);this.enqueue(i.run,{priority:t,id:e})}remove(e){let t=this.#e.findIndex((n,i)=>i<this.#t?!1:typeof e=="string"?n.id===e:n.run===e);t!==-1&&this.#e.splice(t,1)}dequeue(){if(this.#t===this.#e.length)return;let e=this.#e[this.#t];return this.#t++,this.#t===this.#e.length?(this.#e.length=0,this.#t=0):this.#t>uh&&this.#t>this.#e.length/2&&this.#o(),e?.run}filter(e){let t=[];for(let n=this.#t;n<this.#e.length;n++){let i=this.#e[n];i.priority===e.priority&&t.push(i.run)}return t}get size(){return this.#e.length-this.#t}#o(){this.#t!==0&&(this.#e.splice(0,this.#t),this.#t=0)}};var ir=class extends ao.default{#e;#t;#o=0;#d;#m=!1;#b=!1;#c;#I=0;#x=0;#u;#l;#a;#s=[];#i=0;#r;#C;#n=0;#y;#f;#N=1n;#g=new Map;#E=new Set;timeout;constructor(e){if(super(),e={carryoverIntervalCount:!1,intervalCap:Number.POSITIVE_INFINITY,interval:0,concurrency:Number.POSITIVE_INFINITY,autoStart:!0,queueClass:kt,strict:!1,...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})`);if(e.strict&&e.interval===0)throw new TypeError("The `strict` option requires a non-zero `interval`");if(e.strict&&e.intervalCap===Number.POSITIVE_INFINITY)throw new TypeError("The `strict` option requires a finite `intervalCap`");if(this.#e=e.carryoverIntervalCount??e.carryoverConcurrencyCount??!1,this.#t=e.intervalCap===Number.POSITIVE_INFINITY||e.interval===0,this.#d=e.intervalCap,this.#c=e.interval,this.#a=e.strict,this.#r=new e.queueClass,this.#C=e.queueClass,this.concurrency=e.concurrency,e.timeout!==void 0&&!(Number.isFinite(e.timeout)&&e.timeout>0))throw new TypeError(`Expected \`timeout\` to be a positive finite number, got \`${e.timeout}\` (${typeof e.timeout})`);this.timeout=e.timeout,this.#f=e.autoStart===!1,this.#K()}#v(e){for(;this.#i<this.#s.length;){let n=this.#s[this.#i];if(n!==void 0&&e-n>=this.#c)this.#i++;else break}(this.#i>100&&this.#i>this.#s.length/2||this.#i===this.#s.length)&&(this.#s=this.#s.slice(this.#i),this.#i=0)}#R(e){this.#a?this.#s.push(e):this.#o++}#B(){this.#a?this.#s.length>this.#i&&this.#s.pop():this.#o>0&&this.#o--}#_(){return this.#s.length-this.#i}get#F(){return this.#t?!0:this.#a?this.#_()<this.#d:this.#o<this.#d}get#U(){return this.#n<this.#y}#M(){this.#n--,this.#n===0&&this.emit("pendingZero"),this.#w(),this.emit("next")}#$(){this.#l=void 0,this.#D(),this.#L()}#O(e){if(this.#a){if(this.#v(e),this.#_()>=this.#d){let n=this.#s[this.#i],i=this.#c-(e-n);return this.#k(i),!0}return!1}if(this.#u===void 0){let t=this.#I-e;if(t<0){if(this.#x>0){let n=e-this.#x;if(n<this.#c)return this.#k(this.#c-n),!0}this.#o=this.#e?this.#n:0}else return this.#k(t),!0}return!1}#k(e){this.#l===void 0&&(this.#l=setTimeout(()=>{this.#$()},e))}#A(){this.#u&&(clearInterval(this.#u),this.#u=void 0)}#T(){this.#l&&(clearTimeout(this.#l),this.#l=void 0)}#w(){if(this.#r.size===0){if(this.#A(),this.emit("empty"),this.#n===0){if(this.#T(),this.#a&&this.#i>0){let t=Date.now();this.#v(t)}this.emit("idle")}return!1}let e=!1;if(!this.#f){let t=Date.now(),n=!this.#O(t);if(this.#F&&this.#U){let i=this.#r.dequeue();this.#t||(this.#R(t),this.#p()),this.emit("active"),i(),n&&this.#L(),e=!0}}return e}#L(){this.#t||this.#u!==void 0||this.#a||(this.#u=setInterval(()=>{this.#D()},this.#c),this.#I=Date.now()+this.#c)}#D(){this.#a||(this.#o===0&&this.#n===0&&this.#u&&this.#A(),this.#o=this.#e?this.#n:0),this.#S(),this.#p()}#S(){for(;this.#w(););}get concurrency(){return this.#y}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.#y=e,this.#S()}setPriority(e,t){if(typeof t!="number"||!Number.isFinite(t))throw new TypeError(`Expected \`priority\` to be a finite number, got \`${t}\` (${typeof t})`);this.#r.setPriority(e,t)}async add(e,t={}){return t={timeout:this.timeout,...t,id:t.id??(this.#N++).toString()},new Promise((n,i)=>{let o=Symbol(`task-${t.id}`),s=()=>{},a=async()=>{s(),this.#n++,this.#g.set(o,{id:t.id,priority:t.priority??0,startTime:Date.now(),timeout:t.timeout});let f;try{try{t.signal?.throwIfAborted()}catch(d){throw this.#z(),this.#g.delete(o),d}this.#x=Date.now();let l=e({signal:t.signal});if(t.timeout&&(l=nr(Promise.resolve(l),{milliseconds:t.timeout,message:`Task timed out after ${t.timeout}ms (queue has ${this.#n} running, ${this.#r.size} waiting)`})),t.signal){let{signal:d}=t;l=Promise.race([l,new Promise((g,w)=>{f=()=>{w(d.reason)},d.addEventListener("abort",f,{once:!0})})])}let h=await l;n(h),this.emit("completed",h)}catch(l){i(l),this.emit("error",l)}finally{f&&t.signal?.removeEventListener("abort",f),this.#g.delete(o),queueMicrotask(()=>{this.#M()})}};this.#r.enqueue(a,t);let c=()=>{if(this.#r instanceof kt){this.#r.remove(a);return}this.#r.remove?.(t.id)};if(t.signal){let{signal:f}=t,l=()=>{s(),c(),i(f.reason),this.#w(),this.emit("next")};if(s=()=>{f.removeEventListener("abort",l),this.#E.delete(s)},f.aborted){l();return}f.addEventListener("abort",l,{once:!0}),this.#E.add(s)}this.emit("add"),this.#w()})}async addAll(e,t){return Promise.all(e.map(async n=>this.add(n,t)))}start(){return this.#f?(this.#f=!1,this.#S(),this):this}pause(){this.#f=!0}clear(){for(let e of this.#E)e();this.#r=new this.#C,this.#A(),this.#P(),this.emit("empty"),this.#n===0&&(this.#T(),this.emit("idle")),this.emit("next")}async onEmpty(){this.#r.size!==0&&await this.#h("empty")}async onSizeLessThan(e){this.#r.size<e||await this.#h("next",()=>this.#r.size<e)}async onIdle(){this.#n===0&&this.#r.size===0||await this.#h("idle")}async onPendingZero(){this.#n!==0&&await this.#h("pendingZero")}async onRateLimit(){this.isRateLimited||await this.#h("rateLimit")}async onRateLimitCleared(){this.isRateLimited&&await this.#h("rateLimitCleared")}onError(){return new Promise((e,t)=>{let n=i=>{this.off("error",n),t(i)};this.on("error",n)})}async#h(e,t){return new Promise(n=>{let i=()=>{t&&!t()||(this.off(e,i),n())};this.on(e,i)})}get size(){return this.#r.size}sizeBy(e){return this.#r.filter(e).length}get pending(){return this.#n}get isPaused(){return this.#f}#K(){this.#t||(this.on("add",()=>{this.#r.size>0&&this.#p()}),this.on("next",()=>{this.#p()}))}#p(){this.#t||this.#b||(this.#b=!0,queueMicrotask(()=>{this.#b=!1,this.#P()}))}#z(){this.#t||(this.#B(),this.#p())}#P(){let e=this.#m;if(this.#t||this.#r.size===0){e&&(this.#m=!1,this.emit("rateLimitCleared"));return}let t;if(this.#a){let i=Date.now();this.#v(i),t=this.#_()}else t=this.#o;let n=t>=this.#d;n!==e&&(this.#m=n,this.emit(n?"rateLimit":"rateLimitCleared"))}get isRateLimited(){return this.#m}get isSaturated(){return this.#n===this.#y&&this.#r.size>0||this.isRateLimited&&this.#r.size>0}get runningTasks(){return[...this.#g.values()].map(e=>({...e,timeoutRemaining:e.timeout?Math.max(0,e.startTime+e.timeout-Date.now()):void 0}))}};function nn(r){let e=[Ee.A];return r==null?e:Array.isArray(r)?r.length===0?e:r:[r]}var lo=60;function on(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:Ee[e.type]})),Answer:(r.Answer??r.answers??[]).map(e=>({name:e.name,type:Ee[e.type],TTL:e.TTL??e.ttl??lo,data:e.data instanceof Uint8Array?ce(e.data):e.data}))}}var lh=4;function fo(r,e={}){let t=new ir({concurrency:e.queryConcurrency??lh});return async(n,i={})=>{let o=i?.logger?.forComponent("dns:dns-json-over-https"),s=new URLSearchParams;s.set("name",n),nn(i.types).forEach(c=>{s.append("type",Ee[c])}),i.onProgress?.(new x("dns:query",n)),o?.("GET %s",`${r}?${s}`);let a=await t.add(async()=>{let c=await fetch(`${r}?${s}`,{headers:{accept:"application/dns-json"},signal:i?.signal});if(o?.("GET %s %d",c.url,c.status),c.status!==200)throw new Error(`Unexpected HTTP status: ${c.status} - ${c.statusText}`);let f=on(await c.json());return i.onProgress?.(new x("dns:response",f)),f},{signal:i.signal});if(a==null)throw new Error("No DNS response received");return a}}function ka(){return[fo("https://cloudflare-dns.com/dns-query"),fo("https://dns.google/resolve")]}var Ia=pi(Sa(),1);var ho=class{lru;constructor(e){this.lru=(0,Ia.default)(e)}get(e,t){let n=!0,i=[];for(let o of t){let s=this.getAnswers(e,o);if(s.length===0){n=!1;break}i.push(...s)}if(n)return on({answers:i})}getAnswers(e,t){let n=`${e.toLowerCase()}-${t}`,i=this.lru.get(n);if(i!=null){let o=i.filter(s=>s.expires>Date.now()).map(({expires:s,value:a})=>({...a,TTL:Math.round((s-Date.now())/1e3),type:Ee[a.type]}));return o.length===0&&this.lru.remove(n),o}return[]}add(e,t){let n=`${e.toLowerCase()}-${t.type}`,i=this.lru.get(n)??[];i.push({expires:Date.now()+(t.TTL??lo)*1e3,value:t}),this.lru.set(n,i)}remove(e,t){let n=`${e.toLowerCase()}-${t}`;this.lru.remove(n)}clear(){this.lru.clear()}};function Ca(r){return new ho(r)}var fh=1e3,sn=class{resolvers;cache;logger;constructor(e){this.resolvers={},this.cache=Ca(e.cacheSize??fh),this.logger=e.logger,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["."]=ka())}async query(e,t={}){let n=nn(t.types),i=t.cached!==!1?this.cache.get(e,n):void 0;if(i!=null)return t.onProgress?.(new x("dns:cache",i)),i;let o=`${e.split(".").pop()}.`,s=(this.resolvers[o]??this.resolvers["."]).sort(()=>Math.random()>.5?-1:1),a=[];for(let c of s){if(t.signal?.aborted===!0)break;try{let f=await c(e,{...t,logger:this.logger,types:n});for(let l of f.Answer)this.cache.add(e,l);return f}catch(f){a.push(f),t.onProgress?.(new x("dns:error",f))}}throw new tn(a,`DNS lookup of ${e} ${n} failed`)}};var Ee;(function(r){r[r.A=1]="A",r[r.CNAME=5]="CNAME",r[r.TXT=16]="TXT",r[r.AAAA=28]="AAAA"})(Ee||(Ee={}));function Ta(r={}){return new sn(r)}function an(r,e){if(typeof r=="string")return hh(r);if(typeof r=="number")return mh(r,e);throw new Error(`Value provided to ms() must be a string or number. value=${JSON.stringify(r)}`)}function hh(r){if(typeof r!="string"||r.length===0||r.length>100)throw new Error(`Value provided to ms.parse() must be a string with length between 1 and 99. value=${JSON.stringify(r)}`);let e=/^(?<value>-?\d*\.?\d+) *(?<unit>milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|months?|mo|years?|yrs?|y)?$/i.exec(r);if(!e?.groups)return NaN;let{value:t,unit:n="ms"}=e.groups,i=parseFloat(t),o=n.toLowerCase();switch(o){case"years":case"year":case"yrs":case"yr":case"y":return i*315576e5;case"months":case"month":case"mo":return i*26298e5;case"weeks":case"week":case"w":return i*6048e5;case"days":case"day":case"d":return i*864e5;case"hours":case"hour":case"hrs":case"hr":case"h":return i*36e5;case"minutes":case"minute":case"mins":case"min":case"m":return i*6e4;case"seconds":case"second":case"secs":case"sec":case"s":return i*1e3;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return i;default:throw new Error(`Unknown unit "${o}" provided to ms.parse(). value=${JSON.stringify(r)}`)}}function dh(r){let e=Math.abs(r);return e>=315576e5?`${Math.round(r/315576e5)}y`:e>=26298e5?`${Math.round(r/26298e5)}mo`:e>=6048e5?`${Math.round(r/6048e5)}w`:e>=864e5?`${Math.round(r/864e5)}d`:e>=36e5?`${Math.round(r/36e5)}h`:e>=6e4?`${Math.round(r/6e4)}m`:e>=1e3?`${Math.round(r/1e3)}s`:`${r}ms`}function ph(r){let e=Math.abs(r);return e>=315576e5?et(r,e,315576e5,"year"):e>=26298e5?et(r,e,26298e5,"month"):e>=6048e5?et(r,e,6048e5,"week"):e>=864e5?et(r,e,864e5,"day"):e>=36e5?et(r,e,36e5,"hour"):e>=6e4?et(r,e,6e4,"minute"):e>=1e3?et(r,e,1e3,"second"):`${r} ms`}function mh(r,e){if(typeof r!="number"||!Number.isFinite(r))throw new Error("Value provided to ms.format() must be of type number.");return e?.long?ph(r):dh(r)}function et(r,e,t,n){let i=e>=t*1.5;return`${Math.round(r/t)} ${n}${i?"s":""}`}function po(r){t.debug=t,t.default=t,t.coerce=c,t.disable=o,t.enable=i,t.enabled=s,t.humanize=an,t.destroy=f,Object.keys(r).forEach(l=>{t[l]=r[l]}),t.names=[],t.skips=[],t.formatters={};function e(l){let h=0;for(let d=0;d<l.length;d++)h=(h<<5)-h+l.charCodeAt(d),h|=0;return t.colors[Math.abs(h)%t.colors.length]}t.selectColor=e;function t(l,h){let d,g=null,w,A;function E(..._){if(!E.enabled)return;let T=E,D=Number(new Date),z=D-(d||D);T.diff=z,T.prev=d,T.curr=D,d=D,_[0]=t.coerce(_[0]),typeof _[0]!="string"&&_.unshift("%O");let M=0;_[0]=_[0].replace(/%([a-zA-Z%])/g,(q,de)=>{if(q==="%%")return"%";M++;let Qe=t.formatters[de];if(typeof Qe=="function"){let Nu=_[M];q=Qe.call(T,Nu),_.splice(M,1),M--}return q}),t.formatArgs.call(T,_),h?.onLog!=null&&h.onLog(..._),(T.log||t.log).apply(T,_)}return E.namespace=l,E.useColors=t.useColors(),E.color=t.selectColor(l),E.extend=n,E.destroy=t.destroy,Object.defineProperty(E,"enabled",{enumerable:!0,configurable:!1,get:()=>g!==null?g:(w!==t.namespaces&&(w=t.namespaces,A=t.enabled(l)),A),set:_=>{g=_}}),typeof t.init=="function"&&t.init(E),E}function n(l,h){let d=t(this.namespace+(typeof h>"u"?":":h)+l);return d.log=this.log,d}function i(l){t.save(l),t.namespaces=l,t.names=[],t.skips=[];let h,d=(typeof l=="string"?l:"").split(/[\s,]+/),g=d.length;for(h=0;h<g;h++)d[h]&&(l=d[h].replace(/\*/g,".*?"),l[0]==="-"?t.skips.push(new RegExp("^"+l.substr(1)+"$")):t.names.push(new RegExp("^"+l+"$")))}function o(){let l=[...t.names.map(a),...t.skips.map(a).map(h=>"-"+h)].join(",");return t.enable(""),l}function s(l){if(l[l.length-1]==="*")return!0;let h,d;for(h=0,d=t.skips.length;h<d;h++)if(t.skips[h].test(l))return!1;for(h=0,d=t.names.length;h<d;h++)if(t.names[h].test(l))return!0;return!1}function a(l){return l.toString().substring(2,l.toString().length-2).replace(/\.\*\?$/,"*")}function c(l){return l instanceof Error?l.stack??l.message:l}function f(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return t.setupFormatters(t.formatters),t.enable(t.load()),t}var cn=vh(),yh=["#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 gh(){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 wh(r){if(r[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+r[0]+(this.useColors?"%c ":" ")+"+"+an(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,i=>{i!=="%%"&&(t++,i==="%c"&&(n=t))}),r.splice(n,0,e)}var bh=console.debug??console.log??(()=>{});function xh(r){try{r?cn?.setItem("debug",r):cn?.removeItem("debug")}catch{}}function Eh(){let r;try{r=cn?.getItem("debug")}catch{}return!r&&typeof globalThis.process<"u"&&"env"in globalThis.process&&(r=globalThis.process.env.DEBUG),r}function vh(){try{return localStorage}catch{}}function _h(r){r.j=function(e){try{return JSON.stringify(e)}catch(t){return"[UnexpectedJSONParseError]: "+t.message}}}var La=po({formatArgs:wh,save:xh,load:Eh,useColors:gh,setupFormatters:_h,colors:yh,storage:cn,log:bh});var I=La;I.formatters.z=r=>r==null?"undefined":R.baseEncode(r);I.formatters.b=r=>r==null?"undefined":O.baseEncode(r);I.formatters.k=r=>r==null?"undefined":te.baseEncode(r);I.formatters.m=r=>r==null?"undefined":V.baseEncode(r);I.formatters.e=r=>r==null?"undefined":Na(r);function Da(r,e=""){let t=Pa(r.message),n=Pa(r.stack);return t!=null&&n!=null?n.includes(t)?`${n.split(`
2
+ "use strict";var HeliaUtils=(()=>{var Bu=Object.create;var Cr=Object.defineProperty;var Fu=Object.getOwnPropertyDescriptor;var Uu=Object.getOwnPropertyNames;var Mu=Object.getPrototypeOf,$u=Object.prototype.hasOwnProperty;var ft=(r,e)=>()=>{try{return e||r((e={exports:{}}).exports,e),e.exports}catch(t){throw e=0,t}},F=(r,e)=>{for(var t in e)Cr(r,t,{get:e[t],enumerable:!0})},fs=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Uu(e))!$u.call(r,i)&&i!==t&&Cr(r,i,{get:()=>e[i],enumerable:!(n=Fu(e,i))||n.enumerable});return r};var mi=(r,e,t)=>(t=r!=null?Bu(Mu(r)):{},fs(e||!r||!r.__esModule?Cr(t,"default",{value:r,enumerable:!0}):t,r)),Ou=r=>fs(Cr({},"__esModule",{value:!0}),r);var Gs=ft((Sy,Ws)=>{"use strict";function pf(r){return r>=55296&&r<=56319}function mf(r){return r>=56320&&r<=57343}Ws.exports=function(e,t,n){if(typeof t!="string")throw new Error("Input must be string");for(var i=t.length,o=0,s,a,c=0;c<i;c+=1){if(s=t.charCodeAt(c),a=t[c],pf(s)&&mf(t.charCodeAt(c+1))&&(c+=1,a+=t[c]),o+=e(a),o===n)return t.slice(0,c+1);if(o>n)return t.slice(0,c-a.length+1)}return t}});var Qs=ft((Iy,Js)=>{"use strict";function yf(r){return r>=55296&&r<=56319}function gf(r){return r>=56320&&r<=57343}Js.exports=function(e){if(typeof e!="string")throw new Error("Input must be string");for(var t=e.length,n=0,i=null,o=null,s=0;s<t;s++)i=e.charCodeAt(s),gf(i)?o!=null&&yf(o)?n+=1:n+=3:i<=127?n+=1:i>=128&&i<=2047?n+=2:i>=2048&&i<=65535&&(n+=3),o=i;return n}});var Xs=ft((Cy,Ys)=>{"use strict";var wf=Gs(),bf=Qs();Ys.exports=wf.bind(null,bf)});var ta=ft((Ty,ea)=>{"use strict";var xf=Xs(),Ef=/[\/\?<>\\:\*\|"]/g,vf=/[\x00-\x1f\x80-\x9f]/g,_f=/^\.+$/,kf=/^(con|prn|aux|nul|com[0-9]|lpt[0-9])(\..*)?$/i;function Af(r,e){for(var t=r.length;t>0&&(r[t-1]==="."||r[t-1]===" ");)t--;return t<r.length?r.slice(0,t)+e:r}function Zs(r,e){if(typeof r!="string")throw new Error("Input must be string");var t=r.replace(Ef,e).replace(vf,e).replace(_f,e).replace(kf,e);return t=Af(t,e),xf(t,255)}ea.exports=function(r,e){var t=e&&e.replacement||"",n=Zs(r,t);return t===""?n:Zs(n,"")}});var _a=ft((Hg,ao)=>{"use strict";var ch=Object.prototype.hasOwnProperty,Q="~";function rr(){}Object.create&&(rr.prototype=Object.create(null),new rr().__proto__||(Q=!1));function uh(r,e,t){this.fn=r,this.context=e,this.once=t||!1}function va(r,e,t,n,i){if(typeof t!="function")throw new TypeError("The listener must be a function");var o=new uh(t,n||r,i),s=Q?Q+e:e;return r._events[s]?r._events[s].fn?r._events[s]=[r._events[s],o]:r._events[s].push(o):(r._events[s]=o,r._eventsCount++),r}function tn(r,e){--r._eventsCount===0?r._events=new rr:delete r._events[e]}function K(){this._events=new rr,this._eventsCount=0}K.prototype.eventNames=function(){var e=[],t,n;if(this._eventsCount===0)return e;for(n in t=this._events)ch.call(t,n)&&e.push(Q?n.slice(1):n);return Object.getOwnPropertySymbols?e.concat(Object.getOwnPropertySymbols(t)):e};K.prototype.listeners=function(e){var t=Q?Q+e:e,n=this._events[t];if(!n)return[];if(n.fn)return[n.fn];for(var i=0,o=n.length,s=new Array(o);i<o;i++)s[i]=n[i].fn;return s};K.prototype.listenerCount=function(e){var t=Q?Q+e:e,n=this._events[t];return n?n.fn?1:n.length:0};K.prototype.emit=function(e,t,n,i,o,s){var a=Q?Q+e:e;if(!this._events[a])return!1;var c=this._events[a],f=arguments.length,l,h;if(c.fn){switch(c.once&&this.removeListener(e,c.fn,void 0,!0),f){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,i),!0;case 5:return c.fn.call(c.context,t,n,i,o),!0;case 6:return c.fn.call(c.context,t,n,i,o,s),!0}for(h=1,l=new Array(f-1);h<f;h++)l[h-1]=arguments[h];c.fn.apply(c.context,l)}else{var d=c.length,g;for(h=0;h<d;h++)switch(c[h].once&&this.removeListener(e,c[h].fn,void 0,!0),f){case 1:c[h].fn.call(c[h].context);break;case 2:c[h].fn.call(c[h].context,t);break;case 3:c[h].fn.call(c[h].context,t,n);break;case 4:c[h].fn.call(c[h].context,t,n,i);break;default:if(!l)for(g=1,l=new Array(f-1);g<f;g++)l[g-1]=arguments[g];c[h].fn.apply(c[h].context,l)}}return!0};K.prototype.on=function(e,t,n){return va(this,e,t,n,!1)};K.prototype.once=function(e,t,n){return va(this,e,t,n,!0)};K.prototype.removeListener=function(e,t,n,i){var o=Q?Q+e:e;if(!this._events[o])return this;if(!t)return tn(this,o),this;var s=this._events[o];if(s.fn)s.fn===t&&(!i||s.once)&&(!n||s.context===n)&&tn(this,o);else{for(var a=0,c=[],f=s.length;a<f;a++)(s[a].fn!==t||i&&!s[a].once||n&&s[a].context!==n)&&c.push(s[a]);c.length?this._events[o]=c.length===1?c[0]:c:tn(this,o)}return this};K.prototype.removeAllListeners=function(e){var t;return e?(t=Q?Q+e:e,this._events[t]&&tn(this,t)):(this._events=new rr,this._eventsCount=0),this};K.prototype.off=K.prototype.removeListener;K.prototype.addListener=K.prototype.on;K.prefixed=Q;K.EventEmitter=K;typeof ao<"u"&&(ao.exports=K)});var Ia=ft((mw,Sa)=>{Sa.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 i(o,s){t[o]=s,e++,e>=r&&(e=0,n=t,t=Object.create(null))}return{has:function(o){return t[o]!==void 0||n[o]!==void 0},remove:function(o){t[o]!==void 0&&(t[o]=void 0),n[o]!==void 0&&(n[o]=void 0)},get:function(o){var s=t[o];if(s!==void 0)return s;if((s=n[o])!==void 0)return i(o,s),s},set:function(o,s){t[o]!==void 0?t[o]=s:i(o,s)},clear:function(){t=Object.create(null),n=Object.create(null)}}}});var zp={};F(zp,{AbstractSession:()=>pi,Helia:()=>ls,breadthFirstWalker:()=>Pu,depthFirstWalker:()=>Du,isCID:()=>Lu,naturalOrderWalker:()=>Nu});function me(r=0){return new Uint8Array(r)}function Z(r=0){return new Uint8Array(r)}var Ku=Math.pow(2,7),zu=Math.pow(2,14),qu=Math.pow(2,21),hs=Math.pow(2,28),ds=Math.pow(2,35),ps=Math.pow(2,42),ms=Math.pow(2,49),j=128,Me=127;function Ut(r){if(r<Ku)return 1;if(r<zu)return 2;if(r<qu)return 3;if(r<hs)return 4;if(r<ds)return 5;if(r<ps)return 6;if(r<ms)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function ys(r,e,t=0){switch(Ut(r)){case 8:e[t++]=r&255|j,r/=128;case 7:e[t++]=r&255|j,r/=128;case 6:e[t++]=r&255|j,r/=128;case 5:e[t++]=r&255|j,r/=128;case 4:e[t++]=r&255|j,r>>>=7;case 3:e[t++]=r&255|j,r>>>=7;case 2:e[t++]=r&255|j,r>>>=7;case 1:{e[t++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return e}function gs(r,e){let t=r[e],n=0;if(n+=t&Me,t<j||(t=r[e+1],n+=(t&Me)<<7,t<j)||(t=r[e+2],n+=(t&Me)<<14,t<j)||(t=r[e+3],n+=(t&Me)<<21,t<j)||(t=r[e+4],n+=(t&Me)*hs,t<j)||(t=r[e+5],n+=(t&Me)*ds,t<j)||(t=r[e+6],n+=(t&Me)*ps,t<j)||(t=r[e+7],n+=(t&Me)*ms,t<j))return n;throw new RangeError("Could not decode varint")}function ju(r){return r.buffer instanceof ArrayBuffer}function N(r){return ju(r)?r:r.slice()}var yi=new Float32Array([-0]),$e=new Uint8Array(yi.buffer);function ws(r,e,t){yi[0]=r,e[t]=$e[0],e[t+1]=$e[1],e[t+2]=$e[2],e[t+3]=$e[3]}function bs(r,e){return $e[0]=r[e],$e[1]=r[e+1],$e[2]=r[e+2],$e[3]=r[e+3],yi[0]}var gi=new Float64Array([-0]),$=new Uint8Array(gi.buffer);function xs(r,e,t){gi[0]=r,e[t]=$[0],e[t+1]=$[1],e[t+2]=$[2],e[t+3]=$[3],e[t+4]=$[4],e[t+5]=$[5],e[t+6]=$[6],e[t+7]=$[7]}function Es(r,e){return $[0]=r[e],$[1]=r[e+1],$[2]=r[e+2],$[3]=r[e+3],$[4]=r[e+4],$[5]=r[e+5],$[6]=r[e+6],$[7]=r[e+7],gi[0]}var Vu=BigInt(Number.MAX_SAFE_INTEGER),Hu=BigInt(Number.MIN_SAFE_INTEGER),ee=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 Ye;if(e<Vu&&e>Hu)return this.fromNumber(Number(e));let t=e<0n;t&&(e=-e);let n=e>>32n,i=e-(n<<32n);return t&&(n=~n|0n,i=~i|0n,++i>vs&&(i=0n,++n>vs&&(n=0n))),new r(Number(i),Number(n))}static fromNumber(e){if(e===0)return Ye;let t=e<0;t&&(e=-e);let n=e>>>0,i=(e-n)/4294967296>>>0;return t&&(i=~i>>>0,n=~n>>>0,++n>4294967295&&(n=0,++i>4294967295&&(i=0))),new r(n,i)}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):Ye}},Ye=new ee(0,0);Ye.toBigInt=function(){return 0n};Ye.zzEncode=Ye.zzDecode=function(){return this};Ye.length=function(){return 1};var vs=4294967296n;function _s(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 ks(r,e,t){if(t-e<1)return"";let i,o=[],s=0,a;for(;e<t;)a=r[e++],a<128?o[s++]=a:a>191&&a<224?o[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,o[s++]=55296+(a>>10),o[s++]=56320+(a&1023)):o[s++]=(a&15)<<12|(r[e++]&63)<<6|r[e++]&63,s>8191&&((i??(i=[])).push(String.fromCharCode.apply(String,o)),s=0);return i!=null?(s>0&&i.push(String.fromCharCode.apply(String,o.slice(0,s))),i.join("")):String.fromCharCode.apply(String,o.slice(0,s))}function wi(r,e,t){let n=t,i,o;for(let s=0;s<r.length;++s)i=r.charCodeAt(s),i<128?e[t++]=i:i<2048?(e[t++]=i>>6|192,e[t++]=i&63|128):(i&64512)===55296&&((o=r.charCodeAt(s+1))&64512)===56320?(i=65536+((i&1023)<<10)+(o&1023),++s,e[t++]=i>>18|240,e[t++]=i>>12&63|128,e[t++]=i>>6&63|128,e[t++]=i&63|128):(e[t++]=i>>12|224,e[t++]=i>>6&63|128,e[t++]=i&63|128);return t-n}function ye(r,e){return RangeError(`index out of range: ${r.pos} + ${e??1} > ${r.len}`)}function Tr(r,e){return(r[e-4]|r[e-3]<<8|r[e-2]<<16|r[e-1]<<24)>>>0}var bi=class{buf;pos;len;_slice=Uint8Array.prototype.subarray;constructor(e){this.buf=N(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,ye(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 ye(this,4);return Tr(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw ye(this,4);return Tr(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw ye(this,4);let e=bs(this.buf,this.pos);return this.pos+=4,e}double(){if(this.pos+8>this.len)throw ye(this,4);let e=Es(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 ye(this,e);return this.pos+=e,t===n?new Uint8Array(0):this.buf.subarray(t,n)}string(){let e=this.bytes();return ks(e,0,e.length)}skip(e){if(typeof e=="number"){if(this.pos+e>this.len)throw ye(this,e);this.pos+=e}else do if(this.pos>=this.len)throw ye(this);while((this.buf[this.pos++]&128)!==0);return this}skipType(e){switch(e){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;(e=this.uint32()&7)!==4;)this.skipType(e);break;case 5:this.skip(4);break;default:throw Error(`invalid wire type ${e} at offset ${this.pos}`)}return this}readLongVarint(){let e=new ee(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 ye(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 ye(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 ye(this,8);let e=Tr(this.buf,this.pos+=4),t=Tr(this.buf,this.pos+=4);return new ee(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=gs(this.buf,this.pos);return this.pos+=Ut(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 Mt(r){return new bi(r instanceof Uint8Array?r:r.subarray())}function Lr(r,e,t){let n=Mt(r);return e.decode(n,void 0,t)}var Ai={};F(Ai,{base10:()=>el});var nm=new Uint8Array(0);function Ss(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 ge(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return Xe(r);if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return Xe(new Uint8Array(r.buffer,r.byteOffset,r.byteLength));throw new Error("Unknown type, must be binary type")}function Is(r){return new TextEncoder().encode(r)}function Cs(r){return new TextDecoder().decode(r)}function Wu(r){return r?.buffer instanceof ArrayBuffer}function Xe(r){return Wu(r)?r:r.slice()}function Gu(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 i=0;i<r.length;i++){var o=r.charAt(i),s=o.charCodeAt(0);if(t[s]!==255)throw new TypeError(o+" is ambiguous");t[s]=i}var a=r.length,c=r.charAt(0),f=Math.log(a)/Math.log(256),l=Math.log(256)/Math.log(a);function h(w){if(w instanceof Uint8Array||(ArrayBuffer.isView(w)?w=new Uint8Array(w.buffer,w.byteOffset,w.byteLength):Array.isArray(w)&&(w=Uint8Array.from(w))),!(w instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(w.length===0)return"";for(var A=0,E=0,_=0,T=w.length;_!==T&&w[_]===0;)_++,A++;for(var D=(T-_)*l+1>>>0,z=new Uint8Array(D);_!==T;){for(var M=w[_],Pe=0,q=D-1;(M!==0||Pe<E)&&q!==-1;q--,Pe++)M+=256*z[q]>>>0,z[q]=M%a>>>0,M=M/a>>>0;if(M!==0)throw new Error("Non-zero carry");E=Pe,_++}for(var pe=D-E;pe!==D&&z[pe]===0;)pe++;for(var Qe=c.repeat(A);pe<D;++pe)Qe+=r.charAt(z[pe]);return Qe}function d(w){if(typeof w!="string")throw new TypeError("Expected String");if(w.length===0)return new Uint8Array;var A=0;if(w[A]!==" "){for(var E=0,_=0;w[A]===c;)E++,A++;for(var T=(w.length-A)*f+1>>>0,D=new Uint8Array(T);w[A];){var z=t[w.charCodeAt(A)];if(z===255)return;for(var M=0,Pe=T-1;(z!==0||M<_)&&Pe!==-1;Pe--,M++)z+=a*D[Pe]>>>0,D[Pe]=z%256>>>0,z=z/256>>>0;if(z!==0)throw new Error("Non-zero carry");_=M,A++}if(w[A]!==" "){for(var q=T-_;q!==T&&D[q]===0;)q++;for(var pe=new Uint8Array(E+(T-q)),Qe=E;q!==T;)pe[Qe++]=D[q++];return pe}}}function g(w){var A=d(w);if(A)return A;throw new Error(`Non-${e} character`)}return{encode:h,decodeUnsafe:d,decode:g}}var Ju=Gu,Qu=Ju,Ts=Qu;var Ei=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")}},vi=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,n){this.name=e,this.prefix=t;let i=t.codePointAt(0);if(i===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=i,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 Ls(this,e)}},_i=class{decoders;constructor(e){this.decoders=e}or(e){return Ls(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 Ls(r,e){return new _i({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var ki=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,n,i){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=i,this.encoder=new Ei(e,t,n),this.decoder=new vi(e,t,i)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function ht({name:r,prefix:e,encode:t,decode:n}){return new ki(r,e,t,n)}function Oe({name:r,prefix:e,alphabet:t}){let{encode:n,decode:i}=Ts(t,r);return ht({prefix:e,name:r,encode:n,decode:o=>ge(i(o))})}function Yu(r,e,t,n){let i=r.length;for(;r[i-1]==="=";)--i;let o=new Uint8Array(i*t/8|0),s=0,a=0,c=0;for(let f=0;f<i;++f){let l=e[r[f]];if(l===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<t|l,s+=t,s>=8&&(s-=8,o[c++]=255&a>>s)}if(s>=t||(255&a<<8-s)!==0)throw new SyntaxError("Unexpected end of data");return o}function Xu(r,e,t){let n=e[e.length-1]==="=",i=(1<<t)-1,o="",s=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],s+=8;s>t;)s-=t,o+=e[i&a>>s];if(s!==0&&(o+=e[i&a<<t-s]),n)for(;(o.length*t&7)!==0;)o+="=";return o}function Zu(r){let e={};for(let t=0;t<r.length;++t)e[r[t]]=t;return e}function P({name:r,prefix:e,bitsPerChar:t,alphabet:n}){let i=Zu(n);return ht({prefix:e,name:r,encode(o){return Xu(o,n,t)},decode(o){return Yu(o,i,t,r)}})}var el=Oe({prefix:"9",name:"base10",alphabet:"0123456789"});var Si={};F(Si,{base16:()=>tl,base16upper:()=>rl});var tl=P({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),rl=P({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var Ii={};F(Ii,{base2:()=>nl});var nl=P({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var Ci={};F(Ci,{base256emoji:()=>cl});var Ds=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}"),il=Ds.reduce((r,e,t)=>(r[t]=e,r),[]),ol=Ds.reduce((r,e,t)=>{let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);return r[n]=t,r},[]);function sl(r){return r.reduce((e,t)=>(e+=il[t],e),"")}function al(r){let e=[];for(let t of r){let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);let i=ol[n];if(i==null)throw new Error(`Non-base256emoji character: ${t}`);e.push(i)}return new Uint8Array(e)}var cl=ht({prefix:"\u{1F680}",name:"base256emoji",encode:sl,decode:al});var Ti={};F(Ti,{base32:()=>O,base32hex:()=>hl,base32hexpad:()=>pl,base32hexpadupper:()=>ml,base32hexupper:()=>dl,base32pad:()=>ll,base32padupper:()=>fl,base32upper:()=>ul,base32z:()=>yl});var O=P({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),ul=P({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),ll=P({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),fl=P({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),hl=P({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),dl=P({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),pl=P({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),ml=P({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),yl=P({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Li={};F(Li,{base36:()=>te,base36upper:()=>gl});var te=Oe({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),gl=Oe({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var Di={};F(Di,{base58btc:()=>R,base58flickr:()=>wl});var R=Oe({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),wl=Oe({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var Pi={};F(Pi,{base64:()=>V,base64pad:()=>bl,base64url:()=>b,base64urlpad:()=>xl});var V=P({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),bl=P({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),b=P({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),xl=P({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var Ni={};F(Ni,{base8:()=>El});var El=P({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var Ri={};F(Ri,{identity:()=>vl});var vl=ht({prefix:"\0",name:"identity",encode:r=>Cs(r),decode:r=>Is(r)});var Dr={};F(Dr,{code:()=>Bi,decode:()=>Il,encode:()=>Sl,name:()=>Al});var _l=new TextEncoder,kl=new TextDecoder,Al="json",Bi=512;function Sl(r){return _l.encode(JSON.stringify(r))}function Il(r){return JSON.parse(kl.decode(r))}var Ot={};F(Ot,{code:()=>$t,decode:()=>Ll,encode:()=>Tl,name:()=>Cl});var Cl="raw",$t=85;function Tl(r){return ge(r)}function Ll(r){return ge(r)}var Ui={};F(Ui,{identity:()=>Ke});var Dl=Rs,Ps=128,Pl=127,Nl=~Pl,Rl=Math.pow(2,31);function Rs(r,e,t){e=e||[],t=t||0;for(var n=t;r>=Rl;)e[t++]=r&255|Ps,r/=128;for(;r&Nl;)e[t++]=r&255|Ps,r>>>=7;return e[t]=r|0,Rs.bytes=t-n+1,e}var Bl=Fi,Fl=128,Ns=127;function Fi(r,n){var t=0,n=n||0,i=0,o=n,s,a=r.length;do{if(o>=a)throw Fi.bytes=0,new RangeError("Could not decode varint");s=r[o++],t+=i<28?(s&Ns)<<i:(s&Ns)*Math.pow(2,i),i+=7}while(s>=Fl);return Fi.bytes=o-n,t}var Ul=Math.pow(2,7),Ml=Math.pow(2,14),$l=Math.pow(2,21),Ol=Math.pow(2,28),Kl=Math.pow(2,35),zl=Math.pow(2,42),ql=Math.pow(2,49),jl=Math.pow(2,56),Vl=Math.pow(2,63),Hl=function(r){return r<Ul?1:r<Ml?2:r<$l?3:r<Ol?4:r<Kl?5:r<zl?6:r<ql?7:r<jl?8:r<Vl?9:10},Wl={encode:Dl,decode:Bl,encodingLength:Hl},Gl=Wl,Kt=Gl;function zt(r,e=0){return[Kt.decode(r,e),Kt.decode.bytes]}function dt(r,e,t=0){return Kt.encode(r,e,t),e}function pt(r){return Kt.encodingLength(r)}function yt(r,e){let t=e.byteLength,n=pt(r),i=n+pt(t),o=new Uint8Array(i+t);return dt(r,o,0),dt(t,o,n),o.set(e,i),new mt(r,t,e,o)}function Nr(r){let e=ge(r),[t,n]=zt(e),[i,o]=zt(e.subarray(n)),s=e.subarray(n+o);if(s.byteLength!==i)throw new Error("Incorrect length");return new mt(t,i,s,e)}function Bs(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&Ss(r.bytes,t.bytes)}}var mt=class{code;size;digest;bytes;constructor(e,t,n,i){this.code=e,this.size=t,this.digest=Xe(n),this.bytes=Xe(i)}};var Fs=0,Jl="identity",Us=ge;function Ql(r,e){if(e?.truncate!=null&&e.truncate!==r.byteLength){if(e.truncate<0||e.truncate>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,e.truncate)}return yt(Fs,Us(r))}var Ke={code:Fs,name:Jl,encode:Us,digest:Ql};var Oi={};F(Oi,{sha256:()=>ze,sha512:()=>Rr});var Yl=20;function $i({name:r,code:e,encode:t,minDigestLength:n,maxDigestLength:i}){return new Mi(r,e,t,n,i)}var Mi=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,n,i,o){this.name=e,this.code=t,this.encode=n,this.minDigestLength=i??Yl,this.maxDigestLength=o}digest(e,t){if(t?.truncate!=null){if(t.truncate<this.minDigestLength)throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`);if(this.maxDigestLength!=null&&t.truncate>this.maxDigestLength)throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`)}if(e instanceof Uint8Array){let n=this.encode(e);return n instanceof Uint8Array?Ms(n,this.code,t?.truncate):n.then(i=>Ms(i,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}};function Ms(r,e,t){if(t!=null&&t!==r.byteLength){if(t>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,t)}return yt(e,r)}function Os(r){return async e=>new Uint8Array(await crypto.subtle.digest(r,e))}var ze=$i({name:"sha2-256",code:18,encode:Os("SHA-256")}),Rr=$i({name:"sha2-512",code:19,encode:Os("SHA-512")});function Ks(r,e){let{bytes:t,version:n}=r;return n===0?Zl(t,Ki(r),e??R.encoder):ef(t,Ki(r),e??O.encoder)}var zs=new WeakMap;function Ki(r){let e=zs.get(r);if(e==null){let t=new Map;return zs.set(r,t),t}return e}var v=class r{code;version;multihash;bytes;"/";constructor(e,t,n,i){this.code=t,this.version=e,this.multihash=n,this.bytes=Xe(i),this["/"]=this.bytes}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:e,multihash:t}=this;if(e!==qt)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==tf)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=yt(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&&Bs(e.multihash,n.multihash)}toString(e){return Ks(this,e)}toJSON(){return{"/":Ks(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:i,multihash:o,bytes:s}=t;return new r(n,i,o,s??qs(n,i,o.bytes))}else if(t[rf]===!0){let{version:n,multihash:i,code:o}=t,s=Nr(i);return r.create(n,o,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!==qt)throw new Error(`Version 0 CID must use dag-pb (code: ${qt}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let i=qs(e,t,n.bytes);return new r(e,t,n,i)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,qt,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,i=ge(e.subarray(n,n+t.multihashSize));if(i.byteLength!==t.multihashSize)throw new Error("Incorrect length");let o=i.subarray(t.multihashSize-t.digestSize),s=new mt(t.multihashCode,t.digestSize,o,i);return[t.version===0?r.createV0(s):r.createV1(t.codec,s),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[h,d]=zt(e.subarray(t));return t+=d,h},i=n(),o=qt;if(i===18?(i=0,t=0):o=n(),i!==0&&i!==1)throw new RangeError(`Invalid CID version ${i}`);let s=t,a=n(),c=n(),f=t+c,l=f-s;return{version:i,codec:o,multihashCode:a,digestSize:c,multihashSize:l,size:f}}static parse(e,t){let[n,i]=Xl(e,t),o=r.decode(i);if(o.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return Ki(o).set(n,e),o}};function Xl(r,e){switch(r[0]){case"Q":{let t=e??R;return[R.prefix,t.decode(`${R.prefix}${r}`)]}case R.prefix:{let t=e??R;return[R.prefix,t.decode(r)]}case O.prefix:{let t=e??O;return[O.prefix,t.decode(r)]}case te.prefix:{let t=e??te;return[te.prefix,t.decode(r)]}default:{if(e==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[r[0],e.decode(r)]}}}function Zl(r,e,t){let{prefix:n}=t;if(n!==R.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let i=e.get(n);if(i==null){let o=t.encode(r).slice(1);return e.set(n,o),o}else return i}function ef(r,e,t){let{prefix:n}=t,i=e.get(n);if(i==null){let o=t.encode(r);return e.set(n,o),o}else return i}var qt=112,tf=18;function qs(r,e,t){let n=pt(r),i=n+pt(e),o=new Uint8Array(i+t.byteLength);return dt(r,o,0),dt(e,o,n),o.set(t,i),o}var rf=Symbol.for("@ipld/js-cid/CID");var zi={...Ri,...Ii,...Ni,...Ai,...Si,...Ti,...Li,...Di,...Pi,...Ci},Om={...Oi,...Ui};function Vs(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var js=Vs("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),qi=Vs("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=Z(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),nf={utf8:js,"utf-8":js,hex:zi.base16,latin1:qi,ascii:qi,binary:qi,...zi},Br=nf;function L(r,e="utf8"){let t=Br[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.decoder.decode(`${t.prefix}${r}`)}function ji(r){let e=r??8192,t=e>>>1,n,i=e;return function(s){if(s<1||s>t)return Z(s);i+s>e&&(n=Z(e),i=0);let a=n.subarray(i,i+=s);return(i&7)!==0&&(i=(i|7)+1),a}}var Ze=class{fn;len;next;val;constructor(e,t,n){this.fn=e,this.len=t,this.next=void 0,this.val=n}};function Vi(){}var Wi=class{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}},of=ji();function sf(r){return globalThis.Buffer!=null?Z(r):of(r)}var Vt=class{len;head;tail;states;constructor(){this.len=0,this.head=new Ze(Vi,0,0),this.tail=this.head,this.states=null}_push(e,t,n){return this.tail=this.tail.next=new Ze(e,t,n),this.len+=t,this}uint32(e){return this.len+=(this.tail=this.tail.next=new Gi((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(Fr,10,ee.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){let t=ee.fromBigInt(e);return this._push(Fr,t.length(),t)}uint64Number(e){return this._push(ys,Ut(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=ee.fromBigInt(e).zzEncode();return this._push(Fr,t.length(),t)}sint64Number(e){let t=ee.fromNumber(e).zzEncode();return this._push(Fr,t.length(),t)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(Hi,1,e?1:0)}fixed32(e){return this._push(jt,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){let t=ee.fromBigInt(e);return this._push(jt,4,t.lo)._push(jt,4,t.hi)}fixed64Number(e){let t=ee.fromNumber(e);return this._push(jt,4,t.lo)._push(jt,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(ws,4,e)}double(e){return this._push(xs,8,e)}bytes(e){let t=e.length>>>0;return t===0?this._push(Hi,1,0):this.uint32(t)._push(cf,t,e)}string(e){let t=_s(e);return t!==0?this.uint32(t)._push(wi,t,e):this._push(Hi,1,0)}fork(){return this.states=new Wi(this),this.head=this.tail=new Ze(Vi,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 Ze(Vi,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=sf(this.len),n=0;for(;e!=null;)e.fn(e.val,t,n),n+=e.len,e=e.next;return t}};function Hi(r,e,t){e[t]=r&255}function af(r,e,t){for(;r>127;)e[t++]=r&127|128,r>>>=7;e[t]=r}var Gi=class extends Ze{next;constructor(e,t){super(af,e,t),this.next=void 0}};function Fr(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 jt(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 cf(r,e,t){e.set(r,t)}globalThis.Buffer!=null&&(Vt.prototype.bytes=function(r){let e=r.length>>>0;return this.uint32(e),e>0&&this._push(uf,e,r),this},Vt.prototype.string=function(r){let e=globalThis.Buffer.byteLength(r);return this.uint32(e),e>0&&this._push(lf,e,r),this});function uf(r,e,t){e.set(r,t)}function lf(r,e,t){r.length<40?wi(r,e,t):e.utf8Write!=null?e.utf8Write(r,t):e.set(L(r),t)}function Ji(){return new Vt}function Ur(r,e){let t=Ji();return e.encode(r,t,{lengthDelimited:!1}),t.finish()}function*Mr(r,e,t){let n=Mt(r);yield*e.stream(n,void 0,"$",t)}var $r={VARINT:0,BIT64:1,LENGTH_DELIMITED:2,START_GROUP:3,END_GROUP:4,BIT32:5};function Or(r,e,t,n,i){return{name:r,type:e,encode:t,decode:n,stream:i}}function Qi(r){function e(o){if(r[o.toString()]==null)throw new Error("Invalid enum value");return r[o]}let t=function(s,a){let c=e(s);a.int32(c)},n=function(s){let a=s.int32();return e(a)},i=function*(s){let a=s.int32();yield e(a)};return Or("enum",$r.VARINT,t,n,i)}function Kr(r,e,t){return Or("message",$r.LENGTH_DELIMITED,r,e,t)}var zr;(function(r){r.RSA="RSA",r.Ed25519="Ed25519",r.secp256k1="secp256k1",r.ECDSA="ECDSA"})(zr||(zr={}));var Yi;(function(r){r[r.RSA=0]="RSA",r[r.Ed25519=1]="Ed25519",r[r.secp256k1=2]="secp256k1",r[r.ECDSA=3]="ECDSA"})(Yi||(Yi={}));(function(r){r.codec=()=>Qi(Yi)})(zr||(zr={}));var Y;(function(r){let e;r.codec=()=>(e==null&&(e=Kr((o,s,a={})=>{a.lengthDelimited!==!1&&s.fork(),o.Type!=null&&(s.uint32(8),s.int32(o.Type)),o.Data!=null&&(s.uint32(18),s.bytes(o.Data)),a.lengthDelimited!==!1&&s.ldelim()},(o,s,a={})=>{let c={},f=s==null?o.len:o.pos+s;for(;o.pos<f;){let l=o.uint32();switch(l>>>3){case 1:{c.Type=o.int32();break}case 2:{c.Data=o.bytes();break}default:{o.skipType(l&7);break}}}return c},function*(o,s,a,c={}){let f=s==null?o.len:o.pos+s;for(;o.pos<f;){let l=o.uint32();switch(l>>>3){case 1:{yield{field:`${a}.Type`,value:o.int32()};break}case 2:{yield{field:`${a}.Data`,value:o.bytes()};break}default:{o.skipType(l&7);break}}}})),e);function t(o){return Ur(o,r.codec())}r.encode=t;function n(o,s){return Lr(o,r.codec(),s)}r.decode=n;function i(o,s){return Mr(o,r.codec(),s)}r.stream=i})(Y||(Y={}));var H;(function(r){let e;r.codec=()=>(e==null&&(e=Kr((o,s,a={})=>{a.lengthDelimited!==!1&&s.fork(),o.Type!=null&&(s.uint32(8),s.int32(o.Type)),o.Data!=null&&(s.uint32(18),s.bytes(o.Data)),a.lengthDelimited!==!1&&s.ldelim()},(o,s,a={})=>{let c={},f=s==null?o.len:o.pos+s;for(;o.pos<f;){let l=o.uint32();switch(l>>>3){case 1:{c.Type=o.int32();break}case 2:{c.Data=o.bytes();break}default:{o.skipType(l&7);break}}}return c},function*(o,s,a,c={}){let f=s==null?o.len:o.pos+s;for(;o.pos<f;){let l=o.uint32();switch(l>>>3){case 1:{yield{field:`${a}.Type`,value:o.int32()};break}case 2:{yield{field:`${a}.Data`,value:o.bytes()};break}default:{o.skipType(l&7);break}}}})),e);function t(o){return Ur(o,r.codec())}r.encode=t;function n(o,s){return Lr(o,r.codec(),s)}r.decode=n;function i(o,s){return Mr(o,r.codec(),s)}r.stream=i})(H||(H={}));function ue(r,e="utf8"){let t=Br[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.encoder.encode(r).substring(1)}var Ne="/",Hs=new TextEncoder().encode(Ne),qr=Hs[0],B=class r{_buf;constructor(e,t){if(typeof e=="string")this._buf=L(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]!==qr)throw new Error("Invalid key")}toString(e="utf8"){return ue(this._buf,e)}uint8Array(){return this._buf}get[Symbol.toStringTag](){return`Key(${this.toString()})`}static withNamespaces(e){return new r(e.join(Ne))}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=Hs),this._buf[0]!==qr){let e=new Uint8Array(this._buf.byteLength+1);e.fill(qr,0,1),e.set(this._buf,1),this._buf=e}for(;this._buf.byteLength>1&&this._buf[this._buf.byteLength-1]===qr;)this._buf=this._buf.subarray(0,-1)}less(e){let t=this.list(),n=e.list();for(let i=0;i<t.length;i++){if(n.length<i+1)return!1;let o=t[i],s=n[i];if(o<s)return!0;if(o>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(Ne).slice(1)}type(){return ff(this.baseNamespace())}name(){return hf(this.baseNamespace())}instance(e){return new r(this.toString()+":"+e)}path(){let e=this.parent().toString();return e.endsWith(Ne)||(e+=Ne),e+=this.type(),new r(e)}parent(){let e=this.list();return e.length===1?new r(Ne):new r(e.slice(0,-1).join(Ne))}child(e){return this.toString()===Ne?e:e.toString()===Ne?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(),...df(e.map(t=>t.namespaces()))])}};function ff(r){let e=r.split(":");return e.length<2?"":e.slice(0,-1).join(":")}function hf(r){let e=r.split(":");return e[e.length-1]}function df(r){return[].concat(...r)}var wa=mi(ta(),1);function Sf(r){return r?.buffer instanceof ArrayBuffer}function ra(r){if(Sf(r))return r;let e=r.slice();return new Uint8Array(e.buffer,0,e.byteLength)}function we(r,e){e==null&&(e=r.reduce((i,o)=>i+o.length,0));let t=Z(e),n=0;for(let i of r)t.set(i,n),n+=i.length;return ra(t)}var W=class extends Error{static name="InvalidParametersError";name="InvalidParametersError"},Ht=class extends Error{static name="DecryptionFailedError";name="DecryptionFailedError"};function Re(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 ia=Symbol.for("@achingbrain/uint8arraylist");function na(r,e){if(e==null||e<0)throw new RangeError("index is out of bounds");let t=0;for(let n of r){let i=t+n.byteLength;if(e<i)return{buf:n,index:e-t};t=i}throw new RangeError("index is out of bounds")}function jr(r){return!!r?.[ia]}var G=class r{bufs;length;[ia]=!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(jr(n)){t+=n.byteLength;for(let i of n.bufs)this.bufs.push(i)}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(jr(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=na(this.bufs,e);return t.buf[t.index]}set(e,t){let n=na(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(jr(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:i}=this._subList(e,t);return we(n,i)}subarray(e,t){let{bufs:n,length:i}=this._subList(e,t);return n.length===1?n[0]:we(n,i)}sublist(e,t){let{bufs:n,length:i}=this._subList(e,t),o=new r;return o.length=i,o.bufs=n,o}_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=[],i=0;for(let o=0;o<this.bufs.length;o++){let s=this.bufs[o],a=i,c=a+s.byteLength;if(i=c,e>=c)continue;let f=e>=a&&e<c,l=t>a&&t<=c;if(f&&l){if(e===a&&t===c){n.push(s);break}let h=e-a;n.push(s.subarray(h,h+(t-e)));break}if(f){if(e===0){n.push(s);continue}n.push(s.subarray(e-a));continue}if(l){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(!jr(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 i=n.byteLength;if(i===0)throw new TypeError("search must be at least 1 byte long");let o=256,s=new Int32Array(o);for(let h=0;h<o;h++)s[h]=-1;for(let h=0;h<i;h++)s[n[h]]=h;let a=s,c=this.byteLength-n.byteLength,f=n.byteLength-1,l;for(let h=t;h<=c;h+=l){l=0;for(let d=f;d>=0;d--){let g=this.get(h+d);if(n[d]!==g){l=Math.max(1,d-a[g]);break}}if(l===0)return h}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=Z(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 i=me(2);new DataView(i.buffer,i.byteOffset,i.byteLength).setInt16(0,t,n),this.write(i,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 i=me(4);new DataView(i.buffer,i.byteOffset,i.byteLength).setInt32(0,t,n),this.write(i,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 i=me(8);new DataView(i.buffer,i.byteOffset,i.byteLength).setBigInt64(0,t,n),this.write(i,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=Z(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 i=me(2);new DataView(i.buffer,i.byteOffset,i.byteLength).setUint16(0,t,n),this.write(i,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 i=me(4);new DataView(i.buffer,i.byteOffset,i.byteLength).setUint32(0,t,n),this.write(i,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 i=me(8);new DataView(i.buffer,i.byteOffset,i.byteLength).setBigUint64(0,t,n),this.write(i,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 i=me(4);new DataView(i.buffer,i.byteOffset,i.byteLength).setFloat32(0,t,n),this.write(i,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 i=me(8);new DataView(i.buffer,i.byteOffset,i.byteLength).setFloat64(0,t,n),this.write(i,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(!Re(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((i,o)=>i+o.byteLength,0)),n.length=t,n}};var If=parseInt("11111",2),Xi=parseInt("10000000",2),Cf=parseInt("01111111",2),oa={0:Wt,1:Wt,2:Tf,3:Pf,4:Nf,5:Df,6:Lf,16:Wt,22:Wt,48:Wt};function be(r,e={offset:0}){let t=r[e.offset]&If;if(e.offset++,oa[t]!=null)return oa[t](r,e);throw new Error("No decoder for tag 0x"+t.toString(16).padStart(2,"0"))}function Gt(r,e){let t=0;if((r[e.offset]&Xi)===Xi){let n=r[e.offset]&Cf,i="0x";e.offset++;for(let o=0;o<n;o++,e.offset++)i+=r[e.offset].toString(16).padStart(2,"0");t=parseInt(i,16)}else t=r[e.offset],e.offset++;return t}function Wt(r,e){Gt(r,e);let t=[];for(;!(e.offset>=r.byteLength);){let n=be(r,e);if(n===null)break;t.push(n)}return t}function Tf(r,e){let t=Gt(r,e),n=e.offset,i=e.offset+t,o=[];for(let s=n;s<i;s++)s===n&&r[s]===0||o.push(r[s]);return e.offset+=t,Uint8Array.from(o)}function Lf(r,e){let t=Gt(r,e),n=e.offset+t,i=r[e.offset];e.offset++;let o=0,s=0;i<40?(o=0,s=i):i<80?(o=1,s=i-40):(o=2,s=i-80);let a=`${o}.${s}`,c=[];for(;e.offset<n;){let f=r[e.offset];if(e.offset++,c.push(f&127),f<128){c.reverse();let l=0;for(let h=0;h<c.length;h++)l+=c[h]<<h*7;a+=`.${l}`,c=[]}}return a}function Df(r,e){return e.offset++,null}function Pf(r,e){let t=Gt(r,e),n=r[e.offset];e.offset++;let i=r.subarray(e.offset,e.offset+t-1);if(e.offset+=t,n!==0)throw new Error("Unused bits in bit string is unimplemented");return i}function Nf(r,e){let t=Gt(r,e),n=r.subarray(e.offset,e.offset+t);return e.offset+=t,n}function Rf(r){let e=r.toString(16);e.length%2===1&&(e="0"+e);let t=new G;for(let n=0;n<e.length;n+=2)t.append(Uint8Array.from([parseInt(`${e[n]}${e[n+1]}`,16)]));return t}function Vr(r){if(r.byteLength<128)return Uint8Array.from([r.byteLength]);let e=Rf(r.byteLength);return new G(Uint8Array.from([e.byteLength|Xi]),e)}function J(r){let e=new G,t=128;return(r.subarray()[0]&t)===t&&e.append(Uint8Array.from([0])),e.append(r),new G(Uint8Array.from([2]),Vr(e),e)}function Jt(r){let e=Uint8Array.from([0]),t=new G(e,r);return new G(Uint8Array.from([3]),Vr(t),t)}function sa(r){return new G(Uint8Array.from([4]),Vr(r),r)}function xe(r,e=48){let t=new G;for(let n of r)t.append(N(n.subarray()));return new G(Uint8Array.from([e]),Vr(t),t)}var S=class extends Error{static name="InvalidParametersError";name="InvalidParametersError"};var Bf=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),Ff=Uint8Array.from([6,5,43,129,4,0,34]),Uf=Uint8Array.from([6,5,43,129,4,0,35]),aa={ext:!0,kty:"EC",crv:"P-256"},ca={ext:!0,kty:"EC",crv:"P-384"},ua={ext:!0,kty:"EC",crv:"P-521"},wt=32,bt=48,xt=66,Qt=class{type="ECDSA";code=3;jwk;constructor(e){this.jwk=e}toMultihash(){return Ke.digest(this.toProtobuf())}toCID(){return v.createV1(114,this.toMultihash())}toString(){return R.encode(this.toMultihash().bytes).substring(1)}toJWK(){return JSON.parse(JSON.stringify(this.jwk))}toProtobuf(){return Y.encode({Type:this.code,Data:Kf(this.jwk)})}async verify(e,t,n){let i=await crypto.subtle.importKey("jwk",this.jwk,{name:"ECDSA",namedCurve:this.jwk.crv??"P-256"},!1,["verify"]),o=await crypto.subtle.verify({name:"ECDSA",hash:{name:"SHA-256"}},i,N(t),N(e));return n?.signal?.throwIfAborted(),o}},Hr=class{type="ECDSA";code=3;jwk;publicKey;constructor(e,t){this.jwk=e,this.publicKey=t}toProtobuf(){return H.encode({Type:this.code,Data:zf(this.jwk)})}toJWK(){return JSON.parse(JSON.stringify(this.jwk))}async sign(e,t){let n=await crypto.subtle.importKey("jwk",this.jwk,{name:"ECDSA",namedCurve:this.jwk.crv??"P-256"},!0,["sign"]),i=await crypto.subtle.sign({name:"ECDSA",hash:{name:"SHA-256"}},n,N(e));return t?.signal?.throwIfAborted(),new Uint8Array(i,0,i.byteLength)}},Zi=class{type="ECDSA";code=3;async generatePrivateKey(e){let t=e?.curve??"P-256",n=await crypto.subtle.generateKey({name:"ECDSA",namedCurve:t},!0,["sign","verify"]),i=await crypto.subtle.exportKey("jwk",n.privateKey),o=await crypto.subtle.exportKey("jwk",n.publicKey);return e?.signal?.throwIfAborted(),new Hr(i,new Qt(o))}async publicKeyFromProtobuf(e,t){let n=Y.decode(e);if(n.Data==null)throw new S("Data field was missing from protobuf");if(n.Type!==this.code)throw new S("Incorrect Type field in protobuf");t?.signal?.throwIfAborted();let i=Of(n.Data);return new Qt(i)}async privateKeyFromProtobuf(e,t){let n=H.decode(e);if(n.Data==null)throw new S("Data field was missing from protobuf");if(n.Type!==this.code)throw new S("Incorrect Type field in protobuf");let i=$f(n.Data),o=Mf(i);return t?.signal?.throwIfAborted(),new Hr(i,new Qt(o))}};function eo(){return new Zi}function Mf(r){return{crv:r.crv,ext:!0,key_ops:["verify"],kty:"EC",x:r.x,y:r.y}}function $f(r){let e=be(r),t=e[1],n=b.baseEncode(t),i=e[2][1][0],o=1,s,a;if(t.byteLength===wt)return s=b.baseEncode(i.subarray(o,o+wt)),a=b.baseEncode(i.subarray(o+wt)),{...aa,key_ops:["sign"],d:n,x:s,y:a};if(t.byteLength===bt)return s=b.baseEncode(i.subarray(o,o+bt)),a=b.baseEncode(i.subarray(o+bt)),{...ca,key_ops:["sign"],d:n,x:s,y:a};if(t.byteLength===xt)return s=b.baseEncode(i.subarray(o,o+xt)),a=b.baseEncode(i.subarray(o+xt)),{...ua,key_ops:["sign"],d:n,x:s,y:a};throw new S(`Private key length was wrong length, got ${t.byteLength}, expected 32, 48 or 66`)}function Of(r){let t=be(r)[1][1][0],n=1,i,o;if(t.byteLength===wt*2+1)return i=b.baseEncode(t.subarray(n,n+wt)),o=b.baseEncode(t.subarray(n+wt)),{...aa,key_ops:["verify"],x:i,y:o};if(t.byteLength===bt*2+1)return i=b.baseEncode(t.subarray(n,n+bt)),o=b.baseEncode(t.subarray(n+bt)),{...ca,key_ops:["verify"],x:i,y:o};if(t.byteLength===xt*2+1)return i=b.baseEncode(t.subarray(n,n+xt)),o=b.baseEncode(t.subarray(n+xt)),{...ua,key_ops:["verify"],x:i,y:o};throw new S(`coordinates were wrong length, got ${t.byteLength}, expected 65, 97 or 133`)}function Kf(r){return xe([J(Uint8Array.from([1])),xe([la(r.crv)],160),xe([Jt(new G(Uint8Array.from([4]),b.baseDecode(r.x??""),b.baseDecode(r.y??"")))],161)]).subarray()}function zf(r){return xe([J(Uint8Array.from([1])),sa(b.baseDecode(r.d??"")),xe([la(r.crv)],160),xe([Jt(new G(Uint8Array.from([4]),b.baseDecode(r.x??""),b.baseDecode(r.y??"")))],161)]).subarray()}function la(r){if(r==="P-256")return Bf;if(r==="P-384")return Ff;if(r==="P-521")return Uf;throw new S(`Invalid curve ${r}`)}var qf=32,Yt=class{type="Ed25519";code=1;jwk;constructor(e){this.jwk=e}toMultihash(){return Ke.digest(this.toProtobuf())}toCID(){return v.createV1(114,this.toMultihash())}toString(){return R.encode(this.toMultihash().bytes).substring(1)}toJWK(){return JSON.parse(JSON.stringify(this.jwk))}toProtobuf(){return Y.encode({Type:this.code,Data:b.baseDecode(this.jwk.x??"")})}async verify(e,t,n){let i=await crypto.subtle.importKey("jwk",this.jwk,{name:"Ed25519"},!1,["verify"]),o=await crypto.subtle.verify({name:"Ed25519"},i,N(t),N(e));return n?.signal?.throwIfAborted(),o}},Wr=class{type="Ed25519";code=1;jwk;publicKey;constructor(e,t){this.jwk=e,this.publicKey=t}toProtobuf(){return H.encode({Type:this.code,Data:we([b.baseDecode(this.jwk.d??""),b.baseDecode(this.jwk.x??"")],64)})}toJWK(){return JSON.parse(JSON.stringify(this.jwk))}async sign(e,t){let n=await crypto.subtle.importKey("jwk",this.jwk,{name:"Ed25519"},!0,["sign"]),i=await crypto.subtle.sign({name:"Ed25519"},n,N(e));return t?.signal?.throwIfAborted(),new Uint8Array(i,0,i.byteLength)}},to=class{type="Ed25519";code=1;async generatePrivateKey(e){let t=await crypto.subtle.generateKey("Ed25519",!0,["sign","verify"]),n=await crypto.subtle.exportKey("jwk",t.privateKey),i=await crypto.subtle.exportKey("jwk",t.publicKey);return e?.signal?.throwIfAborted(),new Wr(n,new Yt(i))}async publicKeyFromProtobuf(e,t){let n=Y.decode(e);if(n.Data==null)throw new S("Data field was missing from protobuf");if(n.Type!==this.code)throw new S("Incorrect Type field in protobuf");t?.signal?.throwIfAborted();let i=Wf(n.Data);return new Yt(i)}async privateKeyFromProtobuf(e,t){let n=H.decode(e);if(n.Data==null)throw new S("Data field was missing from protobuf");if(n.Type!==this.code)throw new S("Incorrect Type field in protobuf");let i=await jf(n.Data,t),o=Hf(i);return new Wr(i,new Yt(o))}};function ro(){return new to}async function jf(r,e){let t=r.subarray(0,qf),n=Vf(t),i=await crypto.subtle.importKey("pkcs8",n,{name:"Ed25519"},!0,["sign"]),o=await crypto.subtle.exportKey("jwk",i);return e?.signal?.throwIfAborted(),o}var fa=Uint8Array.from([48,46,2,1,0,48,5,6,3,43,101,112,4,34,4]);function Vf(r){return we([fa,Uint8Array.from([r.byteLength]),r],fa.byteLength+1+r.byteLength)}function Hf(r){return{alg:"Ed25519",crv:"Ed25519",ext:!0,key_ops:["verify"],kty:"OKP",x:r.x}}function Wf(r){return{alg:"Ed25519",crv:"Ed25519",ext:!0,key_ops:["verify"],kty:"OKP",x:b.baseEncode(r)}}var oo=8192,Xt=class{type="RSA";code=0;_raw;digest;jwk;constructor(e,t){if(da(e)>oo)throw new S("Key size is too large");this.jwk=e,this.digest=t}toMultihash(){return this.digest}toCID(){return v.createV1(114,this.toMultihash())}toString(){return this.toCID().toString(te)}toProtobuf(){return Zf(this.code,this.jwk)}toJWK(){return JSON.parse(JSON.stringify(this.jwk))}async verify(e,t,n){let i=await crypto.subtle.importKey("jwk",this.jwk,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]),o=await crypto.subtle.verify({name:"RSASSA-PKCS1-v1_5"},i,N(t),N(e));return n?.signal?.throwIfAborted(),o}},Gr=class{type="RSA";code=0;publicKey;jwk;constructor(e,t){if(da(e)>oo)throw new S("Key size is too large");this.jwk=e,this.publicKey=t}toProtobuf(){return eh(this.code,this.jwk)}toJWK(){return JSON.parse(JSON.stringify(this.jwk))}async sign(e,t){let n=await crypto.subtle.importKey("jwk",this.jwk,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]),i=await crypto.subtle.sign({name:"RSASSA-PKCS1-v1_5"},n,N(e));return t?.signal?.throwIfAborted(),new Uint8Array(i,0,i.byteLength)}},io=class{type="RSA";code=0;async generatePrivateKey(e){let t=e?.bits??2048;if(t>oo)throw new S("Key size is too large");let n=await crypto.subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:t,publicExponent:new Uint8Array([1,0,1]),hash:{name:"SHA-256"}},!0,["sign","verify"]),i=await crypto.subtle.exportKey("jwk",n.privateKey),o=await crypto.subtle.exportKey("jwk",n.publicKey),s=await no(i);return e?.signal?.throwIfAborted(),new Gr(i,new Xt(o,s))}async publicKeyFromProtobuf(e,t){let n=Y.decode(e);if(n.Data==null)throw new S("Data field was missing from protobuf");if(n.Type!==this.code)throw new S("Incorrect Type field in protobuf");let i=Yf(n.Data),o=await no(i);return t?.signal?.throwIfAborted(),new Xt(i,o)}async privateKeyFromProtobuf(e,t){let n=H.decode(e);if(n.Data==null)throw new S("Data field was missing from protobuf");if(n.Type!==this.code)throw new S("Incorrect Type field in protobuf");let i=be(n.Data),o=Gf(i),s=Xf(o),a=await no(s);return t?.signal?.throwIfAborted(),new Gr(o,new Xt(s,a))}};function Zt(){return new io}function Gf(r){return{alg:"RS256",kty:"RSA",n:b.baseEncode(r[1]),e:b.baseEncode(r[2]),ext:!0,key_ops:["sign"],d:b.baseEncode(r[3]),p:b.baseEncode(r[4]),q:b.baseEncode(r[5]),dp:b.baseEncode(r[6]),dq:b.baseEncode(r[7]),qi:b.baseEncode(r[8])}}function Jf(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 S("JWK was missing components");return xe([J(Uint8Array.from([0])),J(b.baseDecode(r.n)),J(b.baseDecode(r.e)),J(b.baseDecode(r.d)),J(b.baseDecode(r.p)),J(b.baseDecode(r.q)),J(b.baseDecode(r.dp)),J(b.baseDecode(r.dq)),J(b.baseDecode(r.qi))]).subarray()}var Qf=Uint8Array.from([48,13,6,9,42,134,72,134,247,13,1,1,1,5,0]);function ha(r){if(r.n==null||r.e==null)throw new S("JWK public key was missing components");return xe([Qf,Jt(xe([J(b.baseDecode(r.n)),J(b.baseDecode(r.e))]))]).subarray()}function Yf(r){let e=be(r);if(e.length<2||e[0]?.[0]!=="1.2.840.113549.1.1.1")throw new Error("PKIX certificate was invalid");let t=be(e[1]);return{kty:"RSA",n:b.baseEncode(t[0]),e:b.baseEncode(t[1])}}function Xf(r){return{key_ops:["verify"],ext:!0,alg:"RS256",kty:"RSA",n:r.n,e:"AQAB"}}function da(r){if(r.kty!=="RSA")throw new S("Invalid key type");if(r.n==null)throw new S("Invalid key modulus");return b.baseDecode(r.n).length*8}async function no(r){let e=Y.encode({Type:0,Data:ha(r)});return ze.digest(e)}function Zf(r,e){return Y.encode({Type:r,Data:ha(e)})}function eh(r,e){return H.encode({Type:r,Data:Jf(e)})}async function ma(r,e,t){r=r.replaceAll("-----BEGIN ENCRYPTED PRIVATE KEY-----",""),r=r.replaceAll("-----END ENCRYPTED PRIVATE KEY-----",""),r=r.replaceAll("\r",""),r=r.replaceAll(`
3
+ `,"");let n=V.decode(`m${r}`),i=be(n),o=i[0][1][0][1][0],s=pa(i[0][1][0][1][1]),a=pa(i[0][1][0][1][2]),c=i[0][1][0][1][4][1],f=i[0][1][0][1][4][2],l=await e.decrypt(o,c,f,{iterations:s,keyLength:a*8,hash:"SHA-512",algorithm:"AES-CBC",signal:t?.signal}),d=be(l)[2],g=H.encode({Type:0,Data:d});return Zt().privateKeyFromProtobuf(g)}function pa(r){if(r.length===0)return 0;let e=[...r].map(t=>t.toString(16).padStart(2,"0")).join("");return parseInt(e,16)}var th="/pkcs8/",ba="/info/",rh=Symbol.for("@libp2p/service-capabilities"),er={iterations:1e4,salt:L("you should override this value with a crypto secure random number"),hash:"SHA-512",algorithm:"AES-GCM"},Et={iterations:32767,saltLength:16,ivLength:12,hash:"SHA-256",keyLength:128,algorithm:"AES-GCM"},so=20,Jr={minKeyLength:112/8,minSaltLength:128/8,minIterations:1e3},ya={"SHA-256":128,"SHA-384":192,"SHA-512":256};function tr(r){return r==null||typeof r!="string"?!1:r===(0,wa.default)(r.trim())&&r.length>0}function vt(r){return new B(th+r)}function Qr(r){return new B(ba+r)}async function nh(r,e){let t=r.toProtobuf(),n=await ze.digest(t);return e?.signal?.throwIfAborted(),R.encode(n.bytes).substring(1)}function ih(r){if(typeof r=="string")return L(r);if(r instanceof Uint8Array)return N(r)}var Yr=class{components;self;cipher;salt;keychainDekOptions;privateKeyDekOptions;constructor(e,t={}){if(this.components=e,this.self=t.selfKey??"self",this.salt=ih(t.salt)??er.salt,this.keychainDekOptions={iterations:t.iterations??er.iterations,hash:t.hash??er.hash,keyLength:ya[t.hash??er.hash],algorithm:er.algorithm},this.privateKeyDekOptions={iterations:Et.iterations,hash:Et.hash,saltLength:Et.saltLength,ivLength:Et.ivLength,keyLength:Et.keyLength,algorithm:Et.algorithm},t.password!=null&&t.password.length<so)throw new Error("password must be least 20 characters");if(this.salt.byteLength!=null&&this.salt.byteLength<Jr.minSaltLength)throw new Error(`salt must be least ${Jr.minSaltLength} bytes`);if(t.iterations!=null&&t.iterations<Jr.minIterations)throw new Error(`iterations must be least ${Jr.minIterations}`);if(ya[this.keychainDekOptions.hash]==null)throw new W("Unsupported hash");this.cipher=ga(t.password??"",this.salt,this.keychainDekOptions,this.privateKeyDekOptions)}[rh]=["@ipshipyard/keychain"];async generateKey(e,t){let i=await(await this.components.getCrypto(t?.type??"Ed25519",t)).generatePrivateKey(t);return this.importKey(e,i,t)}async importKey(e,t,n){if(!tr(e))throw new W(`Invalid key name '${e}'`);if(t==null)throw new W("Key is required");if(await this.components.datastore.has(vt(e),n))throw new W(`Key '${e}' already exists`);let o=this.components.datastore.batch();return await this._importKey(e,t,this.cipher,o,n),await o.commit(n),t}async _importKey(e,t,n,i,o){let s=t.toProtobuf(),a=await n.encrypt(s),c=we([a.salt,a.iv,a.cipherText],a.salt.byteLength+a.iv.byteLength+a.cipherText.byteLength),f=V.encode(c),l={name:e,id:await nh(t,o)};i.put(vt(e),L(f)),i.put(Qr(e),L(JSON.stringify(l)))}async exportKey(e,t){if(!tr(e))throw new W(`Invalid key name '${e}'`);return this._exportKey(e,this.cipher,t)}async _exportKey(e,t,n){let i=await this.components.datastore.get(vt(e),n),o=ue(i),s;if(o.includes("BEGIN ENCRYPTED PRIVATE KEY"))return ma(o,t,n);try{let a=V.decode(o),c=a.subarray(0,16),f=a.subarray(16,28),l=a.subarray(28),h=await t.decrypt(c,f,l,n),d=H.decode(h);if(d.Type==null)throw new Ht("Unknown key type");return s=await this.components.getCrypto(d.Type,n),await s.privateKeyFromProtobuf(h)}catch(a){throw a.name==="OperationError"?new Ht(a.message):a}}async removeKey(e,t){if(!tr(e)||e===this.self)throw new W(`Invalid key name '${e}'`);let n=this.components.datastore.batch();n.delete(vt(e)),n.delete(Qr(e)),await n.commit(t)}async*listKeys(e){let t={prefix:ba};for await(let n of this.components.datastore.query(t,e))yield JSON.parse(ue(n.value))}async renameKey(e,t,n){if(!tr(e)||e===this.self)throw new W(`Invalid old key name '${e}'`);if(!tr(t)||t===this.self)throw new W(`Invalid new key name '${t}'`);let i=vt(e),o=vt(t),s=Qr(e),a=Qr(t);if(await this.components.datastore.has(o,n))throw new W(`Key '${t}' already exists`);let f=await this.components.datastore.get(i,n),l=await this.components.datastore.get(s,n),h=JSON.parse(ue(l));h.name=t;let d=this.components.datastore.batch();d.put(o,f),d.put(a,L(JSON.stringify(h))),d.delete(i),d.delete(s),await d.commit(n)}async rotateKeychainPass(e,t){if(typeof e!="string")throw new W(`Invalid new pass type '${typeof e}'`);if(e.length<so)throw new W(`Invalid pass length ${e.length}, must be at least ${so}`);let n=this.cipher,i=this.cipher=ga(e,this.salt,this.keychainDekOptions,this.privateKeyDekOptions),o=this.components.datastore.batch();for await(let s of this.listKeys(t)){let a=await this._exportKey(s.name,n);await this._importKey(s.name,a,i,o,t)}await o.commit(t)}async loadPublicKeyFromProtobuf(e,t){let n=Y.decode(e);if(n.Type==null)throw new W("Protobuf was missing Type");return(await this.components.getCrypto(n.Type,t)).publicKeyFromProtobuf(e,t)}},oh={alg:"A128GCM",ext:!0,k:"scm9jmO_4BJAgdwWGVulLg",key_ops:["encrypt","decrypt"],kty:"oct"};function ga(r,e,t,n){let i;async function o(f,l,h,d){let g,w=L(f),A=await crypto.subtle.importKey("raw",w,{name:"PBKDF2"},!1,["deriveKey"]);try{g=await crypto.subtle.deriveKey({name:"PBKDF2",salt:N(l),iterations:d.iterations,hash:{name:d.hash}},A,{name:d.algorithm??"AES-GCM",length:d.keyLength},!0,h)}catch(E){if(f==="")g=await crypto.subtle.importKey("jwk",oh,{name:d.algorithm??"AES-GCM"},!0,h);else throw E}return g}async function s(){if(r==="")return r;let f=await o(r,e,["encrypt","decrypt"],t);return(await crypto.subtle.exportKey("jwk",f)).k??""}async function a(f,l){i==null&&(i=await s());let h=crypto.getRandomValues(new Uint8Array(n.saltLength)),d=crypto.getRandomValues(new Uint8Array(n.ivLength)),g=await o(i,h,["encrypt"],n),w=await crypto.subtle.encrypt({name:"AES-GCM",iv:d},g,f);return l?.signal?.throwIfAborted(),{salt:h,iv:d,cipherText:new Uint8Array(w)}}async function c(f,l,h,d){i==null&&(i=await s());let g=await o(i,f,["decrypt"],{iterations:d?.iterations??n.iterations,keyLength:d?.keyLength??n.keyLength,hash:d?.hash??n.hash,algorithm:d?.algorithm??"AES-GCM"}),w=await crypto.subtle.decrypt({name:d?.algorithm??"AES-GCM",iv:N(l)},g,N(h));return d?.signal?.throwIfAborted(),new Uint8Array(w)}return{encrypt:a,decrypt:c}}function xa(r){return e=>new Yr(e,r)}var Ee=class extends Error{static name="AbortError";constructor(e="The operation was aborted"){super(e),this.name="AbortError"}};var _t=class extends Error{static name="InvalidParametersError";constructor(e="Invalid parameters"){super(e),this.name="InvalidParametersError"}};var Xr=class extends Error{static name="NotFoundError";constructor(e="Not found"){super(e),this.name="NotFoundError"}};var Zr=class extends Error{static name="InvalidMultihashError";constructor(e="Invalid Multihash"){super(e),this.name="InvalidMultihashError"}};function Ea(r){return r!=null&&typeof r.start=="function"&&typeof r.stop=="function"}async function qe(...r){let e=[];for(let t of r)Ea(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 je(...r){let e=[];for(let t of r)Ea(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 sh(r){return typeof r?.handleEvent=="function"}function ah(r){return(r!==!0&&r!==!1&&r?.once)??!1}var le=class extends EventTarget{#e=new Map;constructor(){super()}listenerCount(e){let t=this.#e.get(e);return t==null?0:t.length}addEventListener(e,t,n){let i=ah(n);super.addEventListener(e,s=>{if(i){let a=this.#e.get(s.type);a!=null&&(a=a.filter(({callback:c})=>c!==t),this.#e.set(s.type,a))}sh(t)?t.handleEvent(s):t(s)},n);let o=this.#e.get(e);o==null&&(o=[],this.#e.set(e,o)),o.push({callback:t,once:i})}removeEventListener(e,t,n){super.removeEventListener(e.toString(),t??null,n);let i=this.#e.get(e);i!=null&&(i=i.filter(({callback:o})=>o!==t),this.#e.set(e,i))}safeDispatchEvent(e,t={}){return this.dispatchEvent(new CustomEvent(e,t))}};var x=class extends Event{type;detail;constructor(e,t){super(e),this.type=e,this.detail=t}};var en=class extends AggregateError{static name="DNSQueryFailedError";name="DNSQueryFailedError"};var co=mi(_a(),1);var uo=class r extends Error{name="TimeoutError";constructor(e,t){super(e,t),Error.captureStackTrace?.(this,r)}},ka=r=>r.reason??new DOMException("This operation was aborted.","AbortError");function nr(r,e){let{milliseconds:t,fallback:n,message:i,customTimers:o={setTimeout,clearTimeout},signal:s}=e,a,c,l=new Promise((h,d)=>{if(typeof t!="number"||Math.sign(t)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${t}\``);if(s?.aborted){d(ka(s));return}if(s&&(c=()=>{d(ka(s))},s.addEventListener("abort",c,{once:!0})),r.then(h,d),t===Number.POSITIVE_INFINITY)return;let g=new uo;a=o.setTimeout.call(void 0,()=>{if(n){try{h(n())}catch(w){d(w)}return}typeof r.cancel=="function"&&r.cancel(),i===!1?h():i instanceof Error?d(i):(g.message=i??`Promise timed out after ${t} milliseconds`,d(g))},t)}).finally(()=>{l.clear(),c&&s&&s.removeEventListener("abort",c)});return l.clear=()=>{o.clearTimeout.call(void 0,a),a=void 0},l}function lo(r,e,t){let n=0,i=r.length;for(;i>0;){let o=Math.trunc(i/2),s=n+o;t(r[s],e)<=0?(n=++s,i-=o+1):i=o}return n}var lh=100,kt=class{#e=[];#t=0;enqueue(e,t){let{priority:n=0,id:i}=t??{},{size:o}=this,s={priority:n,id:i,run:e};if(o===0){this.#e.length=0,this.#t=0,this.#e.push(s);return}if(this.#e.at(-1).priority>=n){this.#e.push(s);return}this.#o();let a=lo(this.#e,s,(c,f)=>f.priority-c.priority);this.#e.splice(a,0,s)}setPriority(e,t){let n=this.#e.findIndex((o,s)=>s>=this.#t&&o.id===e);if(n===-1)throw new ReferenceError(`No promise function with the id "${e}" exists in the queue.`);let[i]=this.#e.splice(n,1);this.enqueue(i.run,{priority:t,id:e})}remove(e){let t=this.#e.findIndex((n,i)=>i<this.#t?!1:typeof e=="string"?n.id===e:n.run===e);t!==-1&&this.#e.splice(t,1)}dequeue(){if(this.#t===this.#e.length)return;let e=this.#e[this.#t];return this.#t++,this.#t===this.#e.length?(this.#e.length=0,this.#t=0):this.#t>lh&&this.#t>this.#e.length/2&&this.#o(),e?.run}filter(e){let t=[];for(let n=this.#t;n<this.#e.length;n++){let i=this.#e[n];i.priority===e.priority&&t.push(i.run)}return t}get size(){return this.#e.length-this.#t}#o(){this.#t!==0&&(this.#e.splice(0,this.#t),this.#t=0)}};var ir=class extends co.default{#e;#t;#o=0;#d;#m=!1;#b=!1;#c;#I=0;#x=0;#u;#l;#a;#s=[];#i=0;#r;#C;#n=0;#y;#f;#N=1n;#g=new Map;#E=new Set;timeout;constructor(e){if(super(),e={carryoverIntervalCount:!1,intervalCap:Number.POSITIVE_INFINITY,interval:0,concurrency:Number.POSITIVE_INFINITY,autoStart:!0,queueClass:kt,strict:!1,...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})`);if(e.strict&&e.interval===0)throw new TypeError("The `strict` option requires a non-zero `interval`");if(e.strict&&e.intervalCap===Number.POSITIVE_INFINITY)throw new TypeError("The `strict` option requires a finite `intervalCap`");if(this.#e=e.carryoverIntervalCount??e.carryoverConcurrencyCount??!1,this.#t=e.intervalCap===Number.POSITIVE_INFINITY||e.interval===0,this.#d=e.intervalCap,this.#c=e.interval,this.#a=e.strict,this.#r=new e.queueClass,this.#C=e.queueClass,this.concurrency=e.concurrency,e.timeout!==void 0&&!(Number.isFinite(e.timeout)&&e.timeout>0))throw new TypeError(`Expected \`timeout\` to be a positive finite number, got \`${e.timeout}\` (${typeof e.timeout})`);this.timeout=e.timeout,this.#f=e.autoStart===!1,this.#K()}#v(e){for(;this.#i<this.#s.length;){let n=this.#s[this.#i];if(n!==void 0&&e-n>=this.#c)this.#i++;else break}(this.#i>100&&this.#i>this.#s.length/2||this.#i===this.#s.length)&&(this.#s=this.#s.slice(this.#i),this.#i=0)}#R(e){this.#a?this.#s.push(e):this.#o++}#B(){this.#a?this.#s.length>this.#i&&this.#s.pop():this.#o>0&&this.#o--}#_(){return this.#s.length-this.#i}get#F(){return this.#t?!0:this.#a?this.#_()<this.#d:this.#o<this.#d}get#U(){return this.#n<this.#y}#M(){this.#n--,this.#n===0&&this.emit("pendingZero"),this.#w(),this.emit("next")}#$(){this.#l=void 0,this.#D(),this.#L()}#O(e){if(this.#a){if(this.#v(e),this.#_()>=this.#d){let n=this.#s[this.#i],i=this.#c-(e-n);return this.#k(i),!0}return!1}if(this.#u===void 0){let t=this.#I-e;if(t<0){if(this.#x>0){let n=e-this.#x;if(n<this.#c)return this.#k(this.#c-n),!0}this.#o=this.#e?this.#n:0}else return this.#k(t),!0}return!1}#k(e){this.#l===void 0&&(this.#l=setTimeout(()=>{this.#$()},e))}#A(){this.#u&&(clearInterval(this.#u),this.#u=void 0)}#T(){this.#l&&(clearTimeout(this.#l),this.#l=void 0)}#w(){if(this.#r.size===0){if(this.#A(),this.emit("empty"),this.#n===0){if(this.#T(),this.#a&&this.#i>0){let t=Date.now();this.#v(t)}this.emit("idle")}return!1}let e=!1;if(!this.#f){let t=Date.now(),n=!this.#O(t);if(this.#F&&this.#U){let i=this.#r.dequeue();this.#t||(this.#R(t),this.#p()),this.emit("active"),i(),n&&this.#L(),e=!0}}return e}#L(){this.#t||this.#u!==void 0||this.#a||(this.#u=setInterval(()=>{this.#D()},this.#c),this.#I=Date.now()+this.#c)}#D(){this.#a||(this.#o===0&&this.#n===0&&this.#u&&this.#A(),this.#o=this.#e?this.#n:0),this.#S(),this.#p()}#S(){for(;this.#w(););}get concurrency(){return this.#y}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.#y=e,this.#S()}setPriority(e,t){if(typeof t!="number"||!Number.isFinite(t))throw new TypeError(`Expected \`priority\` to be a finite number, got \`${t}\` (${typeof t})`);this.#r.setPriority(e,t)}async add(e,t={}){return t={timeout:this.timeout,...t,id:t.id??(this.#N++).toString()},new Promise((n,i)=>{let o=Symbol(`task-${t.id}`),s=()=>{},a=async()=>{s(),this.#n++,this.#g.set(o,{id:t.id,priority:t.priority??0,startTime:Date.now(),timeout:t.timeout});let f;try{try{t.signal?.throwIfAborted()}catch(d){throw this.#z(),this.#g.delete(o),d}this.#x=Date.now();let l=e({signal:t.signal});if(t.timeout&&(l=nr(Promise.resolve(l),{milliseconds:t.timeout,message:`Task timed out after ${t.timeout}ms (queue has ${this.#n} running, ${this.#r.size} waiting)`})),t.signal){let{signal:d}=t;l=Promise.race([l,new Promise((g,w)=>{f=()=>{w(d.reason)},d.addEventListener("abort",f,{once:!0})})])}let h=await l;n(h),this.emit("completed",h)}catch(l){i(l),this.emit("error",l)}finally{f&&t.signal?.removeEventListener("abort",f),this.#g.delete(o),queueMicrotask(()=>{this.#M()})}};this.#r.enqueue(a,t);let c=()=>{if(this.#r instanceof kt){this.#r.remove(a);return}this.#r.remove?.(t.id)};if(t.signal){let{signal:f}=t,l=()=>{s(),c(),i(f.reason),this.#w(),this.emit("next")};if(s=()=>{f.removeEventListener("abort",l),this.#E.delete(s)},f.aborted){l();return}f.addEventListener("abort",l,{once:!0}),this.#E.add(s)}this.emit("add"),this.#w()})}async addAll(e,t){return Promise.all(e.map(async n=>this.add(n,t)))}start(){return this.#f?(this.#f=!1,this.#S(),this):this}pause(){this.#f=!0}clear(){for(let e of this.#E)e();this.#r=new this.#C,this.#A(),this.#P(),this.emit("empty"),this.#n===0&&(this.#T(),this.emit("idle")),this.emit("next")}async onEmpty(){this.#r.size!==0&&await this.#h("empty")}async onSizeLessThan(e){this.#r.size<e||await this.#h("next",()=>this.#r.size<e)}async onIdle(){this.#n===0&&this.#r.size===0||await this.#h("idle")}async onPendingZero(){this.#n!==0&&await this.#h("pendingZero")}async onRateLimit(){this.isRateLimited||await this.#h("rateLimit")}async onRateLimitCleared(){this.isRateLimited&&await this.#h("rateLimitCleared")}onError(){return new Promise((e,t)=>{let n=i=>{this.off("error",n),t(i)};this.on("error",n)})}async#h(e,t){return new Promise(n=>{let i=()=>{t&&!t()||(this.off(e,i),n())};this.on(e,i)})}get size(){return this.#r.size}sizeBy(e){return this.#r.filter(e).length}get pending(){return this.#n}get isPaused(){return this.#f}#K(){this.#t||(this.on("add",()=>{this.#r.size>0&&this.#p()}),this.on("next",()=>{this.#p()}))}#p(){this.#t||this.#b||(this.#b=!0,queueMicrotask(()=>{this.#b=!1,this.#P()}))}#z(){this.#t||(this.#B(),this.#p())}#P(){let e=this.#m;if(this.#t||this.#r.size===0){e&&(this.#m=!1,this.emit("rateLimitCleared"));return}let t;if(this.#a){let i=Date.now();this.#v(i),t=this.#_()}else t=this.#o;let n=t>=this.#d;n!==e&&(this.#m=n,this.emit(n?"rateLimit":"rateLimitCleared"))}get isRateLimited(){return this.#m}get isSaturated(){return this.#n===this.#y&&this.#r.size>0||this.isRateLimited&&this.#r.size>0}get runningTasks(){return[...this.#g.values()].map(e=>({...e,timeoutRemaining:e.timeout?Math.max(0,e.startTime+e.timeout-Date.now()):void 0}))}};function rn(r){let e=[ve.A];return r==null?e:Array.isArray(r)?r.length===0?e:r:[r]}var fo=60;function nn(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:ve[e.type]})),Answer:(r.Answer??r.answers??[]).map(e=>({name:e.name,type:ve[e.type],TTL:e.TTL??e.ttl??fo,data:e.data instanceof Uint8Array?ue(e.data):e.data}))}}var fh=4;function ho(r,e={}){let t=new ir({concurrency:e.queryConcurrency??fh});return async(n,i={})=>{let o=i?.logger?.forComponent("dns:dns-json-over-https"),s=new URLSearchParams;s.set("name",n),rn(i.types).forEach(c=>{s.append("type",ve[c])}),i.onProgress?.(new x("dns:query",n)),o?.("GET %s",`${r}?${s}`);let a=await t.add(async()=>{let c=await fetch(`${r}?${s}`,{headers:{accept:"application/dns-json"},signal:i?.signal});if(o?.("GET %s %d",c.url,c.status),c.status!==200)throw new Error(`Unexpected HTTP status: ${c.status} - ${c.statusText}`);let f=nn(await c.json());return i.onProgress?.(new x("dns:response",f)),f},{signal:i.signal});if(a==null)throw new Error("No DNS response received");return a}}function Aa(){return[ho("https://cloudflare-dns.com/dns-query"),ho("https://dns.google/resolve")]}var Ca=mi(Ia(),1);var po=class{lru;constructor(e){this.lru=(0,Ca.default)(e)}get(e,t){let n=!0,i=[];for(let o of t){let s=this.getAnswers(e,o);if(s.length===0){n=!1;break}i.push(...s)}if(n)return nn({answers:i})}getAnswers(e,t){let n=`${e.toLowerCase()}-${t}`,i=this.lru.get(n);if(i!=null){let o=i.filter(s=>s.expires>Date.now()).map(({expires:s,value:a})=>({...a,TTL:Math.round((s-Date.now())/1e3),type:ve[a.type]}));return o.length===0&&this.lru.remove(n),o}return[]}add(e,t){let n=`${e.toLowerCase()}-${t.type}`,i=this.lru.get(n)??[];i.push({expires:Date.now()+(t.TTL??fo)*1e3,value:t}),this.lru.set(n,i)}remove(e,t){let n=`${e.toLowerCase()}-${t}`;this.lru.remove(n)}clear(){this.lru.clear()}};function Ta(r){return new po(r)}var hh=1e3,on=class{resolvers;cache;logger;constructor(e){this.resolvers={},this.cache=Ta(e.cacheSize??hh),this.logger=e.logger,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["."]=Aa())}async query(e,t={}){let n=rn(t.types),i=t.cached!==!1?this.cache.get(e,n):void 0;if(i!=null)return t.onProgress?.(new x("dns:cache",i)),i;let o=`${e.split(".").pop()}.`,s=(this.resolvers[o]??this.resolvers["."]).sort(()=>Math.random()>.5?-1:1),a=[];for(let c of s){if(t.signal?.aborted===!0)break;try{let f=await c(e,{...t,logger:this.logger,types:n});for(let l of f.Answer)this.cache.add(e,l);return f}catch(f){a.push(f),t.onProgress?.(new x("dns:error",f))}}throw new en(a,`DNS lookup of ${e} ${n} failed`)}};var ve;(function(r){r[r.A=1]="A",r[r.CNAME=5]="CNAME",r[r.TXT=16]="TXT",r[r.AAAA=28]="AAAA"})(ve||(ve={}));function La(r={}){return new on(r)}function sn(r,e){if(typeof r=="string")return dh(r);if(typeof r=="number")return yh(r,e);throw new Error(`Value provided to ms() must be a string or number. value=${JSON.stringify(r)}`)}function dh(r){if(typeof r!="string"||r.length===0||r.length>100)throw new Error(`Value provided to ms.parse() must be a string with length between 1 and 99. value=${JSON.stringify(r)}`);let e=/^(?<value>-?\d*\.?\d+) *(?<unit>milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|months?|mo|years?|yrs?|y)?$/i.exec(r);if(!e?.groups)return NaN;let{value:t,unit:n="ms"}=e.groups,i=parseFloat(t),o=n.toLowerCase();switch(o){case"years":case"year":case"yrs":case"yr":case"y":return i*315576e5;case"months":case"month":case"mo":return i*26298e5;case"weeks":case"week":case"w":return i*6048e5;case"days":case"day":case"d":return i*864e5;case"hours":case"hour":case"hrs":case"hr":case"h":return i*36e5;case"minutes":case"minute":case"mins":case"min":case"m":return i*6e4;case"seconds":case"second":case"secs":case"sec":case"s":return i*1e3;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return i;default:throw new Error(`Unknown unit "${o}" provided to ms.parse(). value=${JSON.stringify(r)}`)}}function ph(r){let e=Math.abs(r);return e>=315576e5?`${Math.round(r/315576e5)}y`:e>=26298e5?`${Math.round(r/26298e5)}mo`:e>=6048e5?`${Math.round(r/6048e5)}w`:e>=864e5?`${Math.round(r/864e5)}d`:e>=36e5?`${Math.round(r/36e5)}h`:e>=6e4?`${Math.round(r/6e4)}m`:e>=1e3?`${Math.round(r/1e3)}s`:`${r}ms`}function mh(r){let e=Math.abs(r);return e>=315576e5?et(r,e,315576e5,"year"):e>=26298e5?et(r,e,26298e5,"month"):e>=6048e5?et(r,e,6048e5,"week"):e>=864e5?et(r,e,864e5,"day"):e>=36e5?et(r,e,36e5,"hour"):e>=6e4?et(r,e,6e4,"minute"):e>=1e3?et(r,e,1e3,"second"):`${r} ms`}function yh(r,e){if(typeof r!="number"||!Number.isFinite(r))throw new Error("Value provided to ms.format() must be of type number.");return e?.long?mh(r):ph(r)}function et(r,e,t,n){let i=e>=t*1.5;return`${Math.round(r/t)} ${n}${i?"s":""}`}function mo(r){t.debug=t,t.default=t,t.coerce=c,t.disable=o,t.enable=i,t.enabled=s,t.humanize=sn,t.destroy=f,Object.keys(r).forEach(l=>{t[l]=r[l]}),t.names=[],t.skips=[],t.formatters={};function e(l){let h=0;for(let d=0;d<l.length;d++)h=(h<<5)-h+l.charCodeAt(d),h|=0;return t.colors[Math.abs(h)%t.colors.length]}t.selectColor=e;function t(l,h){let d,g=null,w,A;function E(..._){if(!E.enabled)return;let T=E,D=Number(new Date),z=D-(d||D);T.diff=z,T.prev=d,T.curr=D,d=D,_[0]=t.coerce(_[0]),typeof _[0]!="string"&&_.unshift("%O");let M=0;_[0]=_[0].replace(/%([a-zA-Z%])/g,(q,pe)=>{if(q==="%%")return"%";M++;let Qe=t.formatters[pe];if(typeof Qe=="function"){let Ru=_[M];q=Qe.call(T,Ru),_.splice(M,1),M--}return q}),t.formatArgs.call(T,_),h?.onLog!=null&&h.onLog(..._),(T.log||t.log).apply(T,_)}return E.namespace=l,E.useColors=t.useColors(),E.color=t.selectColor(l),E.extend=n,E.destroy=t.destroy,Object.defineProperty(E,"enabled",{enumerable:!0,configurable:!1,get:()=>g!==null?g:(w!==t.namespaces&&(w=t.namespaces,A=t.enabled(l)),A),set:_=>{g=_}}),typeof t.init=="function"&&t.init(E),E}function n(l,h){let d=t(this.namespace+(typeof h>"u"?":":h)+l);return d.log=this.log,d}function i(l){t.save(l),t.namespaces=l,t.names=[],t.skips=[];let h,d=(typeof l=="string"?l:"").split(/[\s,]+/),g=d.length;for(h=0;h<g;h++)d[h]&&(l=d[h].replace(/\*/g,".*?"),l[0]==="-"?t.skips.push(new RegExp("^"+l.substr(1)+"$")):t.names.push(new RegExp("^"+l+"$")))}function o(){let l=[...t.names.map(a),...t.skips.map(a).map(h=>"-"+h)].join(",");return t.enable(""),l}function s(l){if(l[l.length-1]==="*")return!0;let h,d;for(h=0,d=t.skips.length;h<d;h++)if(t.skips[h].test(l))return!1;for(h=0,d=t.names.length;h<d;h++)if(t.names[h].test(l))return!0;return!1}function a(l){return l.toString().substring(2,l.toString().length-2).replace(/\.\*\?$/,"*")}function c(l){return l instanceof Error?l.stack??l.message:l}function f(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return t.setupFormatters(t.formatters),t.enable(t.load()),t}var an=_h(),gh=["#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 wh(){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 bh(r){if(r[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+r[0]+(this.useColors?"%c ":" ")+"+"+sn(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,i=>{i!=="%%"&&(t++,i==="%c"&&(n=t))}),r.splice(n,0,e)}var xh=console.debug??console.log??(()=>{});function Eh(r){try{r?an?.setItem("debug",r):an?.removeItem("debug")}catch{}}function vh(){let r;try{r=an?.getItem("debug")}catch{}return!r&&typeof globalThis.process<"u"&&"env"in globalThis.process&&(r=globalThis.process.env.DEBUG),r}function _h(){try{return localStorage}catch{}}function kh(r){r.j=function(e){try{return JSON.stringify(e)}catch(t){return"[UnexpectedJSONParseError]: "+t.message}}}var Da=mo({formatArgs:bh,save:Eh,load:vh,useColors:wh,setupFormatters:kh,colors:gh,storage:an,log:xh});var I=Da;I.formatters.z=r=>r==null?"undefined":R.baseEncode(r);I.formatters.b=r=>r==null?"undefined":O.baseEncode(r);I.formatters.k=r=>r==null?"undefined":te.baseEncode(r);I.formatters.m=r=>r==null?"undefined":V.baseEncode(r);I.formatters.e=r=>r==null?"undefined":Ra(r);function Pa(r,e=""){let t=Na(r.message),n=Na(r.stack);return t!=null&&n!=null?n.includes(t)?`${n.split(`
4
4
  `).join(`
5
5
  ${e}`)}`:`${t}
6
6
  ${e}${n.split(`
7
7
  `).join(`
8
8
  ${e}`)}`:n!=null?`${n.split(`
9
9
  `).join(`
10
- ${e}`)}`:t!=null?`${t}`:`${r.toString()}`}function kh(r){return r instanceof AggregateError||r?.name==="AggregateError"&&Array.isArray(r.errors)}function Na(r,e=""){if(kh(r)){let t=Da(r,e);return r.errors.length>0?(e=`${e} `,t+=`
11
- ${e}${r.errors.map(n=>`${Na(n,`${e}`)}`).join(`
10
+ ${e}`)}`:t!=null?`${t}`:`${r.toString()}`}function Ah(r){return r instanceof AggregateError||r?.name==="AggregateError"&&Array.isArray(r.errors)}function Ra(r,e=""){if(Ah(r)){let t=Pa(r,e);return r.errors.length>0?(e=`${e} `,t+=`
11
+ ${e}${r.errors.map(n=>`${Ra(n,`${e}`)}`).join(`
12
12
  ${e}`)}`):t+=`
13
- ${e}[Error list was empty]`,t.trim()}return Da(r,e)}function Ah(r){let e=()=>{};return e.enabled=!1,e.color="",e.diff=0,e.log=()=>{},e.namespace=r,e.destroy=()=>!0,e.extend=()=>e,e.useColors=()=>!1,e}function Ra(r){return{forComponent(e){return Ba(e,r)}}}function Ba(r,e){let t=Ah(`${r}:trace`);return I.enabled(`${r}:trace`)&&I.names.map(n=>n.toString()).find(n=>n.includes(":trace"))!=null&&(t=I(`${r}:trace`,e)),Object.assign(I(r,e),{error:I(`${r}:error`,e),trace:t,newScope:n=>Ba(`${r}:${n}`,e)})}function Pa(r){if(r!=null&&(r=r.trim(),r.length!==0))return r}var Be=class{has(e,t){return Promise.reject(new Error(".has is not implemented"))}put(e,t,n){return Promise.reject(new Error(".put is not implemented"))}async*putMany(e,t){for await(let{cid:n,bytes:i}of e)await this.put(n,i,t),yield n}get(e,t){throw new Error(".get is not implemented")}async*getMany(e,t){for await(let n of e)yield{cid:n,bytes:this.get(n,t)}}delete(e,t){return Promise.reject(new Error(".delete is not implemented"))}async*deleteMany(e,t){for await(let n of e)await this.delete(n,t),yield n}async*getAll(e){throw new Error(".getAll is not implemented")}};var le=class r extends Error{static name="NotFoundError";name=r.name;static code="ERR_NOT_FOUND";code=r.code;constructor(e="Not Found"){super(e)}};function Sh(r){return r[Symbol.asyncIterator]!=null}function Ih(r){if(Sh(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 or=Ih;function Ch(r){return typeof r?.then=="function"}var sr=class extends Be{data;constructor(){super(),this.data=new Map}put(e,t,n){n?.signal?.throwIfAborted();let i;if(t instanceof Uint8Array)i=[t];else{let o=or(t);if(Ch(o))return o.then(s=>this._put(e,s,n));i=o}return this._put(e,i,n)}_put(e,t,n){return n?.signal?.throwIfAborted(),this.data.set(O.encode(e.multihash.bytes),t),e}*get(e,t){t?.signal?.throwIfAborted();let n=this.data.get(O.encode(e.multihash.bytes));if(n==null)throw new le;yield*n}has(e,t){return t?.signal?.throwIfAborted(),this.data.has(O.encode(e.multihash.bytes))}async delete(e,t){t?.signal?.throwIfAborted(),this.data.delete(O.encode(e.multihash.bytes))}*getAll(e){e?.signal?.throwIfAborted();for(let[t,n]of this.data.entries())yield{cid:v.createV1($t,Rr(O.decode(t))),bytes:(async function*(){yield*n})()},e?.signal?.throwIfAborted()}};I.formatters.b=r=>r==null?"undefined":R.baseEncode(r);I.formatters.t=r=>r==null?"undefined":O.baseEncode(r);I.formatters.m=r=>r==null?"undefined":V.baseEncode(r);I.formatters.p=r=>r==null?"undefined":r.toString();I.formatters.c=r=>r==null?"undefined":r.toString();I.formatters.k=r=>r==null?"undefined":r.toString();I.formatters.a=r=>r==null?"undefined":r.toString();function Fa(r,e=""){let t=Ua(r.message),n=Ua(r.stack);return t!=null&&n!=null?n.includes(t)?`${n.split(`
13
+ ${e}[Error list was empty]`,t.trim()}return Pa(r,e)}function Sh(r){let e=()=>{};return e.enabled=!1,e.color="",e.diff=0,e.log=()=>{},e.namespace=r,e.destroy=()=>!0,e.extend=()=>e,e.useColors=()=>!1,e}function Ba(r){return{forComponent(e){return Fa(e,r)}}}function Fa(r,e){let t=Sh(`${r}:trace`);return I.enabled(`${r}:trace`)&&I.names.map(n=>n.toString()).find(n=>n.includes(":trace"))!=null&&(t=I(`${r}:trace`,e)),Object.assign(I(r,e),{error:I(`${r}:error`,e),trace:t,newScope:n=>Fa(`${r}:${n}`,e)})}function Na(r){if(r!=null&&(r=r.trim(),r.length!==0))return r}var Be=class{has(e,t){return Promise.reject(new Error(".has is not implemented"))}put(e,t,n){return Promise.reject(new Error(".put is not implemented"))}async*putMany(e,t){for await(let{cid:n,bytes:i}of e)await this.put(n,i,t),yield n}get(e,t){throw new Error(".get is not implemented")}async*getMany(e,t){for await(let n of e)yield{cid:n,bytes:this.get(n,t)}}delete(e,t){return Promise.reject(new Error(".delete is not implemented"))}async*deleteMany(e,t){for await(let n of e)await this.delete(n,t),yield n}async*getAll(e){throw new Error(".getAll is not implemented")}};var fe=class r extends Error{static name="NotFoundError";name=r.name;static code="ERR_NOT_FOUND";code=r.code;constructor(e="Not Found"){super(e)}};function Ih(r){return r[Symbol.asyncIterator]!=null}function Ch(r){if(Ih(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 or=Ch;function Th(r){return typeof r?.then=="function"}var sr=class extends Be{data;constructor(){super(),this.data=new Map}put(e,t,n){n?.signal?.throwIfAborted();let i;if(t instanceof Uint8Array)i=[t];else{let o=or(t);if(Th(o))return o.then(s=>this._put(e,s,n));i=o}return this._put(e,i,n)}_put(e,t,n){return n?.signal?.throwIfAborted(),this.data.set(O.encode(e.multihash.bytes),t),e}*get(e,t){t?.signal?.throwIfAborted();let n=this.data.get(O.encode(e.multihash.bytes));if(n==null)throw new fe;yield*n}has(e,t){return t?.signal?.throwIfAborted(),this.data.has(O.encode(e.multihash.bytes))}async delete(e,t){t?.signal?.throwIfAborted(),this.data.delete(O.encode(e.multihash.bytes))}*getAll(e){e?.signal?.throwIfAborted();for(let[t,n]of this.data.entries())yield{cid:v.createV1($t,Nr(O.decode(t))),bytes:(async function*(){yield*n})()},e?.signal?.throwIfAborted()}};I.formatters.b=r=>r==null?"undefined":R.baseEncode(r);I.formatters.t=r=>r==null?"undefined":O.baseEncode(r);I.formatters.m=r=>r==null?"undefined":V.baseEncode(r);I.formatters.p=r=>r==null?"undefined":r.toString();I.formatters.c=r=>r==null?"undefined":r.toString();I.formatters.k=r=>r==null?"undefined":r.toString();I.formatters.a=r=>r==null?"undefined":r.toString();function Ua(r,e=""){let t=Ma(r.message),n=Ma(r.stack);return t!=null&&n!=null?n.includes(t)?`${n.split(`
14
14
  `).join(`
15
15
  ${e}`)}`:`${t}
16
16
  ${e}${n.split(`
17
17
  `).join(`
18
18
  ${e}`)}`:n!=null?`${n.split(`
19
19
  `).join(`
20
- ${e}`)}`:t!=null?`${t}`:`${r.toString()}`}function Th(r){return r instanceof AggregateError||r?.name==="AggregateError"&&Array.isArray(r.errors)}function Ma(r,e=""){if(Th(r)){let t=Fa(r,e);return r.errors.length>0?(e=`${e} `,t+=`
21
- ${e}${r.errors.map(n=>`${Ma(n,`${e}`)}`).join(`
20
+ ${e}`)}`:t!=null?`${t}`:`${r.toString()}`}function Lh(r){return r instanceof AggregateError||r?.name==="AggregateError"&&Array.isArray(r.errors)}function $a(r,e=""){if(Lh(r)){let t=Ua(r,e);return r.errors.length>0?(e=`${e} `,t+=`
21
+ ${e}${r.errors.map(n=>`${$a(n,`${e}`)}`).join(`
22
22
  ${e}`)}`):t+=`
23
- ${e}[Error list was empty]`,t.trim()}return Fa(r,e)}I.formatters.e=r=>r==null?"undefined":Ma(r);function Lh(r){let e=()=>{};return e.enabled=!1,e.color="",e.diff=0,e.log=()=>{},e.namespace=r,e.destroy=()=>!0,e.extend=()=>e,e.useColors=()=>!1,e}function ar(r,e){let t=Lh(`${r}:trace`);return I.enabled(`${r}:trace`)&&I.names.map(n=>n.toString()).find(n=>n.includes(":trace"))!=null&&(t=I(`${r}:trace`,e)),Object.assign(I(r,e),{error:I(`${r}:error`,e),trace:t,newScope:n=>ar(`${r}:${n}`,e)})}function Ua(r){if(r!=null&&(r=r.trim(),r.length!==0))return r}function Dh(r){let[e,t]=r[Symbol.asyncIterator]!=null?[r[Symbol.asyncIterator](),Symbol.asyncIterator]:[r[Symbol.iterator](),Symbol.iterator],n=[];return{peek:()=>e.next(),push:i=>{n.push(i)},next:()=>n.length>0?{done:!1,value:n.shift()}:e.next(),[t](){return this}}}var cr=Dh;function Ph(r){return r[Symbol.asyncIterator]!=null}function Nh(r,e){let t=0;if(Ph(r))return(async function*(){for await(let c of r)await e(c,t++)&&(yield c)})();let n=cr(r),{value:i,done:o}=n.next();if(o===!0)return(function*(){})();let s=e(i,t++);if(typeof s.then=="function")return(async function*(){await s&&(yield i);for(let c of n)await e(c,t++)&&(yield c)})();let a=e;return(function*(){s===!0&&(yield i);for(let c of n)a(c,t++)&&(yield c)})()}var re=Nh;function X(){let r={};return r.promise=new Promise((e,t)=>{r.resolve=e,r.reject=t}),r}function Rh(r){return r.reason}async function Ve(r,e,t){if(e==null)return r;let n=t?.translateError??Rh;if(e.aborted)return r.catch(()=>{}),Promise.reject(n(e));let i;try{return await Promise.race([r,new Promise((o,s)=>{i=()=>{s(n(e))},e.addEventListener("abort",i)})])}finally{i!=null&&e.removeEventListener("abort",i)}}var mo=class{readNext;haveNext;ended;nextResult;error;constructor(){this.ended=!1,this.readNext=X(),this.haveNext=X()}[Symbol.asyncIterator](){return this}async next(){if(this.nextResult==null&&await this.haveNext.promise,this.nextResult==null)throw new Error("HaveNext promise resolved but nextResult was undefined");let e=this.nextResult;return this.nextResult=void 0,this.readNext.resolve(),this.readNext=X(),e}async throw(e){return this.ended=!0,this.error=e,e!=null&&(this.haveNext.promise.catch(()=>{}),this.haveNext.reject(e)),{done:!0,value:void 0}}async return(){let e={done:!0,value:void 0};return this.ended=!0,this.nextResult=e,this.haveNext.resolve(),e}async push(e,t){await this._push(e,t)}async end(e,t){e!=null?await this.throw(e):await this._push(void 0,t)}async _push(e,t){if(e!=null&&this.ended)throw this.error??new Error("Cannot push value onto an ended pushable");for(;this.nextResult!=null;)await this.readNext.promise;e!=null?this.nextResult={done:!1,value:e}:(this.ended=!0,this.nextResult={done:!0,value:void 0}),this.haveNext.resolve(),this.haveNext=X(),await Ve(this.readNext.promise,t?.signal,t)}};function $a(){return new mo}function Bh(r){return r[Symbol.asyncIterator]!=null}async function Fh(r,e,t){try{await Promise.all(r.map(async n=>{for await(let i of n)await e.push(i,{signal:t}),t.throwIfAborted()})),await e.end(void 0,{signal:t})}catch(n){await e.end(n,{signal:t}).catch(()=>{})}}async function*Uh(r){let e=new AbortController,t=$a();Fh(r,t,e.signal).catch(()=>{});try{yield*t}finally{e.abort()}}function*Mh(r){for(let e of r)yield*e}function $h(...r){let e=[];for(let t of r)Bh(t)||e.push(t);return e.length===r.length?Mh(e):Uh(r)}var tt=$h;var xb=ar("blockstore:core:tiered");var Oa="SHARDING";function Kh(r){return r[Symbol.asyncIterator]!=null}function zh(r){if(Kh(r))return(async()=>{for await(let e of r);})();for(let e of r);}var ur=zh;function qh(r){return r[Symbol.asyncIterator]!=null}function jh(r,e){return qh(r)?(async function*(){yield*(await or(r)).sort(e)})():(function*(){yield*or(r).sort(e)})()}var un=jh;function Vh(r){return r[Symbol.asyncIterator]!=null}function Hh(r,e){return Vh(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 ln=Hh;var Fe=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:i}of e)await this.put(n,i,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,i){e.push({key:n,value:i})},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 i=e.prefix;n=re(n,o=>o.key.toString().startsWith(i))}if(Array.isArray(e.filters)&&(n=e.filters.reduce((i,o)=>re(i,o),n)),Array.isArray(e.orders)&&(n=e.orders.reduce((i,o)=>un(i,o),n)),e.offset!=null){let i=0,o=e.offset;n=re(n,()=>i++>=o)}return e.limit!=null&&(n=ln(n,e.limit)),n}queryKeys(e,t){let n=this._allKeys(e,t);if(e.prefix!=null){let i=e.prefix;n=re(n,o=>o.toString().startsWith(i))}if(Array.isArray(e.filters)&&(n=e.filters.reduce((i,o)=>re(i,o),n)),Array.isArray(e.orders)&&(n=e.orders.reduce((i,o)=>un(i,o),n)),e.offset!=null){let i=e.offset,o=0;n=re(n,()=>o++>=i)}return e.limit!=null&&(n=ln(n,e.limit)),n}};var lr=class extends Fe{data;constructor(){super(),this.data=new Map}put(e,t,n){return n?.signal?.throwIfAborted(),this.data.set(e.toString(),t),e}get(e,t){t?.signal?.throwIfAborted();let n=this.data.get(e.toString());if(n==null)throw new le;return n}has(e,t){return t?.signal?.throwIfAborted(),this.data.has(e.toString())}delete(e,t){t?.signal?.throwIfAborted(),this.data.delete(e.toString())}*_all(e,t){t?.signal?.throwIfAborted();for(let[n,i]of this.data.entries())yield{key:new B(n),value:i},t?.signal?.throwIfAborted()}*_allKeys(e,t){t?.signal?.throwIfAborted();for(let n of this.data.keys())yield new B(n),t?.signal?.throwIfAborted()}};var fn=class{buffer;mask;top;btm;next;constructor(e){if(!(e>0)||(e-1&e)!==0)throw new Error("Max size for a FixedFIFO should be a power of two");this.buffer=new Array(e),this.mask=e-1,this.top=0,this.btm=0,this.next=null}push(e){return this.buffer[this.top]!==void 0?!1:(this.buffer[this.top]=e,this.top=this.top+1&this.mask,!0)}shift(){let e=this.buffer[this.btm];if(e!==void 0)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,e}isEmpty(){return this.buffer[this.btm]===void 0}},At=class{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new fn(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 fn(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 yo=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}};function fr(r={}){return Wh(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 Wh(r,e){e=e??{};let t=e.onEnd,n=new At,i,o,s,a=X(),c=async()=>{try{return n.isEmpty()?s?{done:!0}:await new Promise((E,_)=>{o=T=>{o=null,n.push(T);try{E(r(n))}catch(D){_(D)}return i}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=X()})}},f=E=>o!=null?o(E):(n.push(E),i),l=E=>(n=new At,o!=null?o({error:E}):(n.push({error:E}),i)),h=E=>{if(s)return i;if(e?.objectMode!==!0&&E?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return f({done:!1,value:E})},d=E=>s?i:(s=!0,E!=null?l(E):f({done:!0})),g=()=>(n=new At,d(),{done:!0}),w=E=>(d(E),{done:!0});if(i={[Symbol.asyncIterator](){return this},next:c,return:g,throw:w,push:h,end:d,get readableLength(){return n.size},onEmpty:async E=>{let _=E?.signal;if(_?.throwIfAborted(),n.isEmpty())return;let T,D;_!=null&&(T=new Promise((z,M)=>{D=()=>{M(new yo)},_.addEventListener("abort",D)}));try{await Promise.race([a.promise,T])}finally{D!=null&&_!=null&&_?.removeEventListener("abort",D)}}},t==null)return i;let A=i;return i={[Symbol.asyncIterator](){return this},next(){return A.next()},throw(E){return A.throw(E),t!=null&&(t(E),t=void 0),{done:!0}},return(){return A.return(),t!=null&&(t(),t=void 0),{done:!0}},push:h,end(E){return A.end(E),t!=null&&(t(E),t=void 0),i},get readableLength(){return A.readableLength},onEmpty:E=>A.onEmpty(E)},i}var h0=new B(Oa);var S0=ar("datastore:core:tiered");var Jh=["Object","RegExp","Date","Error","Map","Set","WeakMap","WeakSet","ArrayBuffer","SharedArrayBuffer","DataView","Promise","URL","HTMLElement","Int8Array","Uint8ClampedArray","Int16Array","Uint16Array","Int32Array","Uint32Array","Float32Array","Float64Array","BigInt64Array","BigUint64Array","Tagged"];function go(r){if(r===null)return"null";if(r===void 0)return"undefined";if(r===!0||r===!1)return"boolean";let e=typeof r;if(e==="string"||e==="number"||e==="bigint"||e==="symbol")return e;if(e==="function")return"Function";if(Array.isArray(r))return"Array";if(r instanceof Uint8Array)return"Uint8Array";if(r.constructor===Object)return"Object";let t=Qh(r);return t||"Object"}function Qh(r){let e=Object.prototype.toString.call(r).slice(8,-1);if(Jh.includes(e))return e}var u=class{constructor(e,t,n){this.major=e,this.majorEncoded=e<<5,this.name=t,this.terminal=n}toString(){return`Type[${this.major}].${this.name}`}compare(e){return this.major<e.major?-1:this.major>e.major?1:0}static equals(e,t){return e===t||e.major===t.major&&e.name===t.name}};u.uint=new u(0,"uint",!0);u.negint=new u(1,"negint",!0);u.bytes=new u(2,"bytes",!0);u.string=new u(3,"string",!0);u.array=new u(4,"array",!1);u.map=new u(5,"map",!1);u.tag=new u(6,"tag",!1);u.float=new u(7,"float",!0);u.false=new u(7,"false",!0);u.true=new u(7,"true",!0);u.null=new u(7,"null",!0);u.undefined=new u(7,"undefined",!0);u.break=new u(7,"break",!0);var p=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 hr=globalThis.process&&!globalThis.process.browser&&globalThis.Buffer&&typeof globalThis.Buffer.isBuffer=="function",Yh=new TextEncoder;function hn(r){return hr&&globalThis.Buffer.isBuffer(r)}function rt(r){return r instanceof Uint8Array?hn(r)?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):r:Uint8Array.from(r)}var Xh=24,Zh=200,St=hr?r=>r.length>=Xh?globalThis.Buffer.from(r):za(r):r=>r.length>=Zh?Yh.encode(r):za(r),Ce=r=>Uint8Array.from(r),ja=hr?(r,e,t)=>hn(r)?new Uint8Array(r.subarray(e,t)):r.slice(e,t):(r,e,t)=>r.slice(e,t),Va=hr?(r,e)=>(r=r.map(t=>t instanceof Uint8Array?t:globalThis.Buffer.from(t)),rt(globalThis.Buffer.concat(r,e))):(r,e)=>{let t=new Uint8Array(e),n=0;for(let i of r)n+i.length>t.length&&(i=i.subarray(0,t.length-n)),t.set(i,n),n+=i.length;return t},Ha=hr?r=>globalThis.Buffer.allocUnsafe(r):r=>new Uint8Array(r);function dn(r,e){if(hn(r)&&hn(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 za(r){let e=[],t=0;for(let n=0;n<r.length;n++){let i=r.charCodeAt(n);i<128?e[t++]=i:i<2048?(e[t++]=i>>6|192,e[t++]=i&63|128):(i&64512)===55296&&n+1<r.length&&(r.charCodeAt(n+1)&64512)===56320?(i=65536+((i&1023)<<10)+(r.charCodeAt(++n)&1023),e[t++]=i>>18|240,e[t++]=i>>12&63|128,e[t++]=i>>6&63|128,e[t++]=i&63|128):(i>=55296&&i<=57343&&(i=65533),e[t++]=i>>12|224,e[t++]=i>>6&63|128,e[t++]=i&63|128)}return e}var qa=4096;function Wa(r){let e=r.length;if(e<=qa)return String.fromCharCode.apply(String,r);let t="",n=0;for(;n<e;)t+=String.fromCharCode.apply(String,r.slice(n,n+=qa));return t}var ed=256,dr=class{constructor(e=ed){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 i=t.length-(this.maxCursor-this.cursor)-1;t.set(e,i)}else{if(t){let i=t.length-(this.maxCursor-this.cursor)-1;i<t.length&&(this.chunks[this.chunks.length-1]=t.subarray(0,i),this.maxCursor=this.cursor-1)}e.length<64&&e.length<this.chunkSize?(t=Ha(this.chunkSize),this.chunks.push(t),this.maxCursor+=t.length,this._initReuseChunk===null&&(this._initReuseChunk=t),t.set(e,0)):(this.chunks.push(e),this.maxCursor+=e.length)}this.cursor+=e.length}toBytes(e=!1){let t;if(this.chunks.length===1){let n=this.chunks[0];e&&this.cursor>n.length/2?(t=this.cursor===n.length?n:n.subarray(0,this.cursor),this._initReuseChunk=null,this.chunks=[]):t=ja(n,0,this.cursor)}else t=Va(this.chunks,this.cursor);return e&&this.reset(),t}},pn=class{constructor(e){this.dest=e,this.cursor=0,this.chunks=[e]}reset(){this.cursor=0}push(e){if(this.cursor+e.length>this.dest.length)throw new Error("write out of bounds, destination buffer is too small");this.dest.set(e,this.cursor),this.cursor+=e.length}toBytes(e=!1){let t=this.dest.subarray(0,this.cursor);return e&&this.reset(),t}};var y="CBOR decode error:",Te="CBOR encode error:",pr=[];pr[23]=1;pr[24]=2;pr[25]=3;pr[26]=5;pr[27]=9;function Ue(r,e,t){if(r.length-e<t)throw new Error(`${y} not enough data for type`)}var U=[24,256,65536,4294967296,BigInt("18446744073709551616")];function ne(r,e,t){Ue(r,e,1);let n=r[e];if(t.strict===!0&&n<U[0])throw new Error(`${y} integer encoded in more bytes than necessary (strict decode)`);return n}function ie(r,e,t){Ue(r,e,2);let n=r[e]<<8|r[e+1];if(t.strict===!0&&n<U[1])throw new Error(`${y} integer encoded in more bytes than necessary (strict decode)`);return n}function oe(r,e,t){Ue(r,e,4);let n=r[e]*16777216+(r[e+1]<<16)+(r[e+2]<<8)+r[e+3];if(t.strict===!0&&n<U[2])throw new Error(`${y} integer encoded in more bytes than necessary (strict decode)`);return n}function se(r,e,t){Ue(r,e,8);let n=r[e]*16777216+(r[e+1]<<16)+(r[e+2]<<8)+r[e+3],i=r[e+4]*16777216+(r[e+5]<<16)+(r[e+6]<<8)+r[e+7],o=(BigInt(n)<<BigInt(32))+BigInt(i);if(t.strict===!0&&o<U[3])throw new Error(`${y} integer encoded in more bytes than necessary (strict decode)`);if(o<=Number.MAX_SAFE_INTEGER)return Number(o);if(t.allowBigInt===!0)return o;throw new Error(`${y} integers outside of the safe integer range are not supported`)}function Ga(r,e,t,n){return new p(u.uint,ne(r,e+1,n),2)}function Ja(r,e,t,n){return new p(u.uint,ie(r,e+1,n),3)}function Qa(r,e,t,n){return new p(u.uint,oe(r,e+1,n),5)}function Ya(r,e,t,n){return new p(u.uint,se(r,e+1,n),9)}function fe(r,e){return C(r,0,e.value)}function C(r,e,t){if(t<U[0]){let n=Number(t);r.push([e|n])}else if(t<U[1]){let n=Number(t);r.push([e|24,n])}else if(t<U[2]){let n=Number(t);r.push([e|25,n>>>8,n&255])}else if(t<U[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<U[4]){let i=[e|27,0,0,0,0,0,0,0],o=Number(n&BigInt(4294967295)),s=Number(n>>BigInt(32)&BigInt(4294967295));i[8]=o&255,o=o>>8,i[7]=o&255,o=o>>8,i[6]=o&255,o=o>>8,i[5]=o&255,i[4]=s&255,s=s>>8,i[3]=s&255,s=s>>8,i[2]=s&255,s=s>>8,i[1]=s&255,r.push(i)}else throw new Error(`${y} encountered BigInt larger than allowable range`)}}fe.encodedSize=function(e){return C.encodedSize(e.value)};C.encodedSize=function(e){return e<U[0]?1:e<U[1]?2:e<U[2]?3:e<U[3]?5:9};fe.compareTokens=function(e,t){return e.value<t.value?-1:e.value>t.value?1:0};function Xa(r,e,t,n){return new p(u.negint,-1-ne(r,e+1,n),2)}function Za(r,e,t,n){return new p(u.negint,-1-ie(r,e+1,n),3)}function ec(r,e,t,n){return new p(u.negint,-1-oe(r,e+1,n),5)}var wo=BigInt(-1),tc=BigInt(1);function rc(r,e,t,n){let i=se(r,e+1,n);if(typeof i!="bigint"){let o=-1-i;if(o>=Number.MIN_SAFE_INTEGER)return new p(u.negint,o,9)}if(n.allowBigInt!==!0)throw new Error(`${y} integers outside of the safe integer range are not supported`);return new p(u.negint,wo-BigInt(i),9)}function mn(r,e){let t=e.value,n=typeof t=="bigint"?t*wo-tc:t*-1-1;C(r,e.type.majorEncoded,n)}mn.encodedSize=function(e){let t=e.value,n=typeof t=="bigint"?t*wo-tc:t*-1-1;return n<U[0]?1:n<U[1]?2:n<U[2]?3:n<U[3]?5:9};mn.compareTokens=function(e,t){return e.value<t.value?1:e.value>t.value?-1:0};function mr(r,e,t,n){Ue(r,e,t+n);let i=r.slice(e+t,e+t+n);return new p(u.bytes,i,t+n)}function nc(r,e,t,n){return mr(r,e,1,t)}function ic(r,e,t,n){return mr(r,e,2,ne(r,e+1,n))}function oc(r,e,t,n){return mr(r,e,3,ie(r,e+1,n))}function sc(r,e,t,n){return mr(r,e,5,oe(r,e+1,n))}function ac(r,e,t,n){let i=se(r,e+1,n);if(typeof i=="bigint")throw new Error(`${y} 64-bit integer bytes lengths not supported`);return mr(r,e,9,i)}function yn(r){return r.encodedBytes===void 0&&(r.encodedBytes=u.equals(r.type,u.string)?St(r.value):r.value),r.encodedBytes}function It(r,e){let t=yn(e);C(r,e.type.majorEncoded,t.length),r.push(t)}It.encodedSize=function(e){let t=yn(e);return C.encodedSize(t.length)+t.length};It.compareTokens=function(e,t){return rd(yn(e),yn(t))};function rd(r,e){return r.length<e.length?-1:r.length>e.length?1:dn(r,e)}var cc=new TextDecoder,id=32;function od(r,e,t){if(t-e<id){let i="";for(let o=e;o<t;o++){let s=r[o];if(s&128)return cc.decode(r.subarray(e,t));i+=String.fromCharCode(s)}return i}return cc.decode(r.subarray(e,t))}function yr(r,e,t,n,i){let o=t+n;Ue(r,e,o);let s=new p(u.string,od(r,e+t,e+o),o);return i.retainStringBytes===!0&&(s.byteValue=r.slice(e+t,e+o)),s}function uc(r,e,t,n){return yr(r,e,1,t,n)}function lc(r,e,t,n){return yr(r,e,2,ne(r,e+1,n),n)}function fc(r,e,t,n){return yr(r,e,3,ie(r,e+1,n),n)}function hc(r,e,t,n){return yr(r,e,5,oe(r,e+1,n),n)}function dc(r,e,t,n){let i=se(r,e+1,n);if(typeof i=="bigint")throw new Error(`${y} 64-bit integer string lengths not supported`);return yr(r,e,9,i,n)}var pc=It;function Ct(r,e,t,n){return new p(u.array,n,t)}function mc(r,e,t,n){return Ct(r,e,1,t)}function yc(r,e,t,n){return Ct(r,e,2,ne(r,e+1,n))}function gc(r,e,t,n){return Ct(r,e,3,ie(r,e+1,n))}function wc(r,e,t,n){return Ct(r,e,5,oe(r,e+1,n))}function bc(r,e,t,n){let i=se(r,e+1,n);if(typeof i=="bigint")throw new Error(`${y} 64-bit integer array lengths not supported`);return Ct(r,e,9,i)}function xc(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${y} indefinite length items not allowed`);return Ct(r,e,1,1/0)}function gn(r,e){C(r,u.array.majorEncoded,e.value)}gn.compareTokens=fe.compareTokens;gn.encodedSize=function(e){return C.encodedSize(e.value)};function Tt(r,e,t,n){return new p(u.map,n,t)}function Ec(r,e,t,n){return Tt(r,e,1,t)}function vc(r,e,t,n){return Tt(r,e,2,ne(r,e+1,n))}function _c(r,e,t,n){return Tt(r,e,3,ie(r,e+1,n))}function kc(r,e,t,n){return Tt(r,e,5,oe(r,e+1,n))}function Ac(r,e,t,n){let i=se(r,e+1,n);if(typeof i=="bigint")throw new Error(`${y} 64-bit integer map lengths not supported`);return Tt(r,e,9,i)}function Sc(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${y} indefinite length items not allowed`);return Tt(r,e,1,1/0)}function wn(r,e){C(r,u.map.majorEncoded,e.value)}wn.compareTokens=fe.compareTokens;wn.encodedSize=function(e){return C.encodedSize(e.value)};function Ic(r,e,t,n){return new p(u.tag,t,1)}function Cc(r,e,t,n){return new p(u.tag,ne(r,e+1,n),2)}function Tc(r,e,t,n){return new p(u.tag,ie(r,e+1,n),3)}function Lc(r,e,t,n){return new p(u.tag,oe(r,e+1,n),5)}function Dc(r,e,t,n){return new p(u.tag,se(r,e+1,n),9)}function bn(r,e){C(r,u.tag.majorEncoded,e.value)}bn.compareTokens=fe.compareTokens;bn.encodedSize=function(e){return C.encodedSize(e.value)};var bo=20,xo=21,Eo=22,vo=23;function Pc(r,e,t,n){if(n.allowUndefined===!1)throw new Error(`${y} undefined values are not supported`);return n.coerceUndefinedToNull===!0?new p(u.null,null,1):new p(u.undefined,void 0,1)}function Nc(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${y} indefinite length items not allowed`);return new p(u.break,void 0,1)}function _o(r,e,t){if(t){if(t.allowNaN===!1&&Number.isNaN(r))throw new Error(`${y} NaN values are not supported`);if(t.allowInfinity===!1&&(r===1/0||r===-1/0))throw new Error(`${y} Infinity values are not supported`)}return new p(u.float,r,e)}function Rc(r,e,t,n){return _o(ko(r,e+1),3,n)}function Bc(r,e,t,n){return _o(Ao(r,e+1),5,n)}function Fc(r,e,t,n){return _o(Oc(r,e+1),9,n)}function gr(r,e,t){let n=e.value;if(n===!1)r.push([u.float.majorEncoded|bo]);else if(n===!0)r.push([u.float.majorEncoded|xo]);else if(n===null)r.push([u.float.majorEncoded|Eo]);else if(n===void 0)r.push([u.float.majorEncoded|vo]);else{let i,o=!1;(!t||t.float64!==!0)&&(Mc(n),i=ko(ve,1),n===i||Number.isNaN(n)?(ve[0]=249,r.push(ve.slice(0,3)),o=!0):($c(n),i=Ao(ve,1),n===i&&(ve[0]=250,r.push(ve.slice(0,5)),o=!0))),o||(ld(n),i=Oc(ve,1),ve[0]=251,r.push(ve.slice(0,9)))}}gr.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){Mc(n);let i=ko(ve,1);if(n===i||Number.isNaN(n))return 3;if($c(n),i=Ao(ve,1),n===i)return 5}return 9};var Uc=new ArrayBuffer(9),he=new DataView(Uc,1),ve=new Uint8Array(Uc,0);function Mc(r){if(r===1/0)he.setUint16(0,31744,!1);else if(r===-1/0)he.setUint16(0,64512,!1);else if(Number.isNaN(r))he.setUint16(0,32256,!1);else{he.setFloat32(0,r);let e=he.getUint32(0),t=(e&2139095040)>>23,n=e&8388607;if(t===255)he.setUint16(0,31744,!1);else if(t===0)he.setUint16(0,(e&2147483648)>>16|n>>13,!1);else{let i=t-127;i<-24?he.setUint16(0,0):i<-14?he.setUint16(0,(e&2147483648)>>16|1<<24+i,!1):he.setUint16(0,(e&2147483648)>>16|i+15<<10|n>>13,!1)}}}function ko(r,e){if(r.length-e<2)throw new Error(`${y} 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,i=t&1023,o;return n===0?o=i*2**-24:n!==31?o=(i+1024)*2**(n-25):o=i===0?1/0:NaN,t&32768?-o:o}function $c(r){he.setFloat32(0,r,!1)}function Ao(r,e){if(r.length-e<4)throw new Error(`${y} not enough data for float32`);let t=(r.byteOffset||0)+e;return new DataView(r.buffer,t,4).getFloat32(0,!1)}function ld(r){he.setFloat64(0,r,!1)}function Oc(r,e){if(r.length-e<8)throw new Error(`${y} not enough data for float64`);let t=(r.byteOffset||0)+e;return new DataView(r.buffer,t,8).getFloat64(0,!1)}gr.compareTokens=fe.compareTokens;function k(r,e,t){throw new Error(`${y} encountered invalid minor (${t}) for major ${r[e]>>>5}`)}function xn(r){return()=>{throw new Error(`${y} ${r}`)}}var m=[];for(let r=0;r<=23;r++)m[r]=k;m[24]=Ga;m[25]=Ja;m[26]=Qa;m[27]=Ya;m[28]=k;m[29]=k;m[30]=k;m[31]=k;for(let r=32;r<=55;r++)m[r]=k;m[56]=Xa;m[57]=Za;m[58]=ec;m[59]=rc;m[60]=k;m[61]=k;m[62]=k;m[63]=k;for(let r=64;r<=87;r++)m[r]=nc;m[88]=ic;m[89]=oc;m[90]=sc;m[91]=ac;m[92]=k;m[93]=k;m[94]=k;m[95]=xn("indefinite length bytes/strings are not supported");for(let r=96;r<=119;r++)m[r]=uc;m[120]=lc;m[121]=fc;m[122]=hc;m[123]=dc;m[124]=k;m[125]=k;m[126]=k;m[127]=xn("indefinite length bytes/strings are not supported");for(let r=128;r<=151;r++)m[r]=mc;m[152]=yc;m[153]=gc;m[154]=wc;m[155]=bc;m[156]=k;m[157]=k;m[158]=k;m[159]=xc;for(let r=160;r<=183;r++)m[r]=Ec;m[184]=vc;m[185]=_c;m[186]=kc;m[187]=Ac;m[188]=k;m[189]=k;m[190]=k;m[191]=Sc;for(let r=192;r<=215;r++)m[r]=Ic;m[216]=Cc;m[217]=Tc;m[218]=Lc;m[219]=Dc;m[220]=k;m[221]=k;m[222]=k;m[223]=k;for(let r=224;r<=243;r++)m[r]=xn("simple values are not supported");m[244]=k;m[245]=k;m[246]=k;m[247]=Pc;m[248]=xn("simple values are not supported");m[249]=Rc;m[250]=Bc;m[251]=Fc;m[252]=k;m[253]=k;m[254]=k;m[255]=Nc;var _e=[];for(let r=0;r<24;r++)_e[r]=new p(u.uint,r,1);for(let r=-1;r>=-24;r--)_e[31-r]=new p(u.negint,r,1);_e[64]=new p(u.bytes,new Uint8Array(0),1);_e[96]=new p(u.string,"",1);_e[128]=new p(u.array,0,1);_e[160]=new p(u.map,0,1);_e[244]=new p(u.false,!1,1);_e[245]=new p(u.true,!0,1);_e[246]=new p(u.null,null,1);function So(r){switch(r.type){case u.false:return Ce([244]);case u.true:return Ce([245]);case u.null:return Ce([246]);case u.bytes:return r.value.length?void 0:Ce([64]);case u.string:return r.value===""?Ce([96]):void 0;case u.array:return r.value===0?Ce([128]):void 0;case u.map:return r.value===0?Ce([160]):void 0;case u.uint:return r.value<24?Ce([Number(r.value)]):void 0;case u.negint:if(r.value>=-24)return Ce([31-Number(r.value)])}}var hd={float64:!1,mapSorter:md,quickEncodeToken:So},Vc=Object.freeze({float64:!0,mapSorter:yd,quickEncodeToken:So});function dd(){let r=[];return r[u.uint.major]=fe,r[u.negint.major]=mn,r[u.bytes.major]=It,r[u.string.major]=pc,r[u.array.major]=gn,r[u.map.major]=wn,r[u.tag.major]=bn,r[u.float.major]=gr,r}var Dt=dd(),En=new dr,br=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(`${Te} object contains circular references`);return new r(t,e)}},He={null:new p(u.null,null),undefined:new p(u.undefined,void 0),true:new p(u.true,!0),false:new p(u.false,!1),emptyArray:new p(u.array,0),emptyMap:new p(u.map,0)},Le={number(r,e,t,n){return!Number.isInteger(r)||!Number.isSafeInteger(r)?new p(u.float,r):r>=0?new p(u.uint,r):new p(u.negint,r)},bigint(r,e,t,n){return r>=BigInt(0)?new p(u.uint,r):new p(u.negint,r)},Uint8Array(r,e,t,n){return new p(u.bytes,r)},string(r,e,t,n){return new p(u.string,r)},boolean(r,e,t,n){return r?He.true:He.false},null(r,e,t,n){return He.null},undefined(r,e,t,n){return He.undefined},ArrayBuffer(r,e,t,n){return new p(u.bytes,new Uint8Array(r))},DataView(r,e,t,n){return new p(u.bytes,new Uint8Array(r.buffer,r.byteOffset,r.byteLength))},Array(r,e,t,n){if(!r.length)return t.addBreakTokens===!0?[He.emptyArray,new p(u.break)]:He.emptyArray;n=br.createCheck(n,r);let i=[],o=0;for(let s of r)i[o++]=Lt(s,t,n);return t.addBreakTokens?[new p(u.array,r.length),i,new p(u.break)]:[new p(u.array,r.length),i]},Object(r,e,t,n){let i=e!=="Object",o=i?r.keys():Object.keys(r),s=i?r.size:o.length,a;if(s){a=new Array(s),n=br.createCheck(n,r);let c=!i&&t.ignoreUndefinedProperties,f=0;for(let l of o){let h=i?r.get(l):r[l];c&&h===void 0||(a[f++]=[Lt(l,t,n),Lt(h,t,n)])}f<s&&(a.length=f)}return a?.length?(pd(a,t),t.addBreakTokens?[new p(u.map,a.length),a,new p(u.break)]:[new p(u.map,a.length),a]):t.addBreakTokens===!0?[He.emptyMap,new p(u.break)]:He.emptyMap},Tagged(r,e,t,n){return[new p(u.tag,r.tag),Lt(r.value,t,n)]}};Le.Map=Le.Object;Le.Buffer=Le.Uint8Array;for(let r of"Uint8Clamped Uint16 Uint32 Int8 Int16 Int32 BigUint64 BigInt64 Float32 Float64".split(" "))Le[`${r}Array`]=Le.DataView;function Lt(r,e={},t){let n=go(r),i=e&&e.typeEncoders&&e.typeEncoders[n]||Le[n];if(typeof i=="function"){let s=i(r,n,e,t);if(s!=null)return s}let o=Le[n];if(!o)throw new Error(`${Te} unsupported type: ${n}`);return o(r,n,e,t)}function pd(r,e){e.mapSorter&&r.sort(e.mapSorter)}function md(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 i=t.type.major,o=Dt[i].compareTokens(t,n);return o===0&&console.warn("WARNING: complex key types used, CBOR key sorting guarantees are gone"),o}function yd(r,e){if(r[0]instanceof p&&e[0]instanceof p){let t=r[0],n=e[0];return t._keyBytes||(t._keyBytes=Kc(t.value)),n._keyBytes||(n._keyBytes=Kc(n.value)),dn(t._keyBytes,n._keyBytes)}throw new Error("rfc8949MapSorter: complex key types are not supported yet")}function Kc(r){return vn(r,Dt,Vc)}function wr(r,e,t,n){if(Array.isArray(e))for(let i of e)wr(r,i,t,n);else t[e.type.major](r,e,n)}var zc=u.uint.majorEncoded,qc=u.negint.majorEncoded,gd=u.bytes.majorEncoded,wd=u.string.majorEncoded,jc=u.array.majorEncoded,bd=u.float.majorEncoded|bo,xd=u.float.majorEncoded|xo,Ed=u.float.majorEncoded|Eo,vd=u.float.majorEncoded|vo,_d=BigInt(-1),kd=BigInt(1);function Ad(r){return r.addBreakTokens!==!0}function Hc(r,e,t,n){let i=go(e),o=t.typeEncoders&&t.typeEncoders[i];if(o){let s=o(e,i,t,n);if(s!=null){wr(r,s,Dt,t);return}}switch(i){case"null":r.push([Ed]);return;case"undefined":r.push([vd]);return;case"boolean":r.push([e?xd:bd]);return;case"number":!Number.isInteger(e)||!Number.isSafeInteger(e)?gr(r,new p(u.float,e),t):e>=0?C(r,zc,e):C(r,qc,e*-1-1);return;case"bigint":e>=BigInt(0)?C(r,zc,e):C(r,qc,e*_d-kd);return;case"string":{let s=St(e);C(r,wd,s.length),r.push(s);return}case"Uint8Array":C(r,gd,e.length),r.push(e);return;case"Array":if(!e.length){r.push([jc]);return}n=br.createCheck(n,e),C(r,jc,e.length);for(let s of e)Hc(r,s,t,n);return;case"Object":case"Map":{let s=Le.Object(e,i,t,n);wr(r,s,Dt,t)}return;default:{let s=Le[i];if(!s)throw new Error(`${Te} unsupported type: ${i}`);let a=s(e,i,t,n);wr(r,a,Dt,t)}}}function vn(r,e,t,n){let i=n instanceof Uint8Array,o=i?new pn(n):En,s=Lt(r,t);if(!Array.isArray(s)&&t.quickEncodeToken){let a=t.quickEncodeToken(s);if(a)return i?(o.push(a),o.toBytes()):a;let c=e[s.type.major];if(c.encodedSize){let f=c.encodedSize(s,t);if(i||(o=new dr(f)),c(o,s,t),o.chunks.length!==1)throw new Error(`Unexpected error: pre-calculated length for ${s} was wrong`);return i?o.toBytes():rt(o.chunks[0])}}return o.reset(),wr(o,s,e,t),o.toBytes(!0)}function it(r,e){return e=Object.assign({},hd,e),Ad(e)?(En.reset(),Hc(En,r,e,void 0),En.toBytes(!0)):vn(r,Dt,e)}var Sd={strict:!1,allowIndefinite:!0,allowUndefined:!0,allowBigInt:!0},_n=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=_e[e];if(t===void 0){let n=m[e];if(!n)throw new Error(`${y} no decoder for major type ${e>>>5} (byte 0x${e.toString(16).padStart(2,"0")})`);let i=e&31;t=n(this.data,this._pos,i,this.options)}return this._pos+=t.encodedLength,t}},We=Symbol.for("DONE"),Pt=Symbol.for("BREAK");function Id(r,e,t){let n=[];for(let i=0;i<r.value;i++){let o=Ge(e,t);if(o===Pt){if(r.value===1/0)break;throw new Error(`${y} got unexpected break to lengthed array`)}if(o===We)throw new Error(`${y} found array but not enough entries (got ${i}, expected ${r.value})`);n[i]=o}return n}function Cd(r,e,t){let n=t.useMaps===!0,i=t.rejectDuplicateMapKeys===!0,o=n?void 0:{},s=n?new Map:void 0;for(let a=0;a<r.value;a++){let c=Ge(e,t);if(c===Pt){if(r.value===1/0)break;throw new Error(`${y} got unexpected break to lengthed map`)}if(c===We)throw new Error(`${y} found map but not enough entries (got ${a} [no key], expected ${r.value})`);if(!n&&typeof c!="string")throw new Error(`${y} non-string keys not supported (got ${typeof c})`);if(i&&(n&&s.has(c)||!n&&Object.hasOwn(o,c)))throw new Error(`${y} found repeat map key "${c}"`);let f=Ge(e,t);if(f===We)throw new Error(`${y} found map but not enough entries (got ${a} [no value], expected ${r.value})`);n?s.set(c,f):o[c]=f}return n?s:o}function*Td(r,e,t){for(let n=0;n<r.value;n++){let i=Ge(e,t);if(i===Pt){if(r.value===1/0)break;throw new Error(`${y} got unexpected break to lengthed map`)}if(i===We)throw new Error(`${y} found map but not enough entries (got ${n} [no key], expected ${r.value})`);let o=Ge(e,t);if(o===We)throw new Error(`${y} found map but not enough entries (got ${n} [no value], expected ${r.value})`);yield[i,o]}}function Ld(r,e){let t=!1,n=function(){if(t)throw new Error(`${y} tag decode() may only be called once`);t=!0;let i=Ge(r,e);if(i===We)throw new Error(`${y} tag content missing`);if(i===Pt)throw new Error(`${y} got unexpected break in tag content`);return i};return n.entries=function(){if(t)throw new Error(`${y} tag decode() may only be called once`);t=!0;let i=r.next();if(!u.equals(i.type,u.map))throw new Error(`${y} entries() requires map content, got ${i.type.name}`);let o=[];for(let s of Td(i,r,e))o.push(s);return o},Object.defineProperty(n,"_called",{get(){return t},enumerable:!1}),n}function Ge(r,e){if(r.done())return We;let t=r.next();if(u.equals(t.type,u.break))return Pt;if(t.type.terminal)return t.value;if(u.equals(t.type,u.array))return Id(t,r,e);if(u.equals(t.type,u.map))return Cd(t,r,e);if(u.equals(t.type,u.tag)){if(e.tags&&typeof e.tags[t.value]=="function"){let n=Ld(r,e),i=e.tags[t.value](n);if(!n._called)throw new Error(`${y} tag decoder must call decode() or entries()`);return i}throw new Error(`${y} tag not supported (${t.value})`)}throw new Error("unsupported")}function Io(r,e){if(!(r instanceof Uint8Array))throw new Error(`${y} data to decode must be a Uint8Array`);e=Object.assign({},Sd,e);let t=rt(r),n=e.tokenizer||new _n(t,e),i=Ge(n,e);if(i===We)throw new Error(`${y} did not find any content to decode`);if(i===Pt)throw new Error(`${y} got unexpected break`);return[i,r.subarray(n.pos())]}function ke(r,e){let[t,n]=Io(r,e);if(n.length>0)throw new Error(`${y} too many terminals, data makes no sense`);return t}var kn=class r{constructor(e,t){if(typeof e!="number"||!Number.isInteger(e)||e<0)throw new TypeError("Tagged: tag must be a non-negative integer");this.tag=e,this.value=t}static decoder(e){return t=>new r(e,t())}static preserve(...e){let t={};for(let n of e)t[n]=r.decoder(n);return t}};Object.defineProperty(kn.prototype,Symbol.toStringTag,{value:"Tagged"});var An=class extends Error{static name="AlreadyPinnedError";name="AlreadyPinnedError"},xr=class extends Error{static name="BlockPinnedError";name="BlockPinnedError"},Sn=class extends Error{static name="InvalidDatastoreVersionError";name="InvalidDatastoreVersionError"},ot=class extends Error{static name="InvalidConfigurationError";name="InvalidConfigurationError"},In=class extends AggregateError{static name="GetFailedError";name="GetFailedError"},Cn=class extends AggregateError{static name="LoadBlockFailedError";name="LoadBlockFailedError"},Er=class extends Error{static name="BlockNotFoundWhileOfflineError";name="BlockNotFoundWhileOfflineError"};var Co={32:16777619n,64:1099511628211n,128:309485009821345068724781371n,256:374144419156711147060143317175368453031918731002211n,512:35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759n,1024:5016456510113118655434598811035278955030765345404790744303017523831112055108147451509157692220295382716162651878526895249385292291816524375083746691371804094271873160484737966720260389217684476157468082573n},Gc={32:2166136261n,64:14695981039346656037n,128:144066263297769815596495629667062367629n,256:100029257958052580907070968620625704837092796014241193945225284501741471925557n,512:9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785n,1024:14197795064947621068722070641403218320880622795441933960878474914617582723252296732303717722150864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915n},Jc=new globalThis.TextEncoder;function Dd(r,e){let t=Co[e],n=Gc[e];for(let i=0;i<r.length;i++)n^=BigInt(r[i]),n=BigInt.asUintN(e,n*t);return n}function Pd(r,e,t){if(t.length===0)throw new Error("The `utf8Buffer` option must have a length greater than zero");let n=Co[e],i=Gc[e],o=r;for(;o.length>0;){let s=Jc.encodeInto(o,t);o=o.slice(s.read);for(let a=0;a<s.written;a++)i^=BigInt(t[a]),i=BigInt.asUintN(e,i*n)}return i}function To(r,{size:e=32,utf8Buffer:t}={}){if(!Co[e])throw new Error("The `size` option must be one of 32, 64, 128, 256, 512, or 1024");if(typeof r=="string"){if(t)return Pd(r,e,t);r=Jc.encode(r)}return Dd(r,e)}var vr={hash:r=>Number(To(r,{size:32})),hashV:(r,e)=>Nd(vr.hash(r,e))};function Nd(r){let e=r.toString(16);return e.length%2===1&&(e=`0${e}`),L(e,"base16")}var Lo=64,Ae=class{fp;h;seed;constructor(e,t,n,i=2){if(i>Lo)throw new TypeError("Invalid Fingerprint Size");let o=t.hashV(e,n),s=pe(i);for(let a=0;a<s.length;a++)s[a]=o[a];s.length===0&&(s[0]=7),this.fp=s,this.h=t,this.seed=n}hash(){return this.h.hash(this.fp,this.seed)}equals(e){return e?.fp instanceof Uint8Array?Re(this.fp,e.fp):!1}};function st(r,e){return Math.floor(Math.random()*(e-r))+r}var at=class{contents;constructor(e){this.contents=new Array(e).fill(null)}has(e){if(!(e instanceof Ae))throw new TypeError("Invalid Fingerprint");return this.contents.some(t=>e.equals(t))}add(e){if(!(e instanceof Ae))throw new TypeError("Invalid Fingerprint");for(let t=0;t<this.contents.length;t++)if(this.contents[t]==null)return this.contents[t]=e,!0;return!0}swap(e){if(!(e instanceof Ae))throw new TypeError("Invalid Fingerprint");let t=st(0,this.contents.length-1),n=this.contents[t];return this.contents[t]=e,n}remove(e){if(!(e instanceof Ae))throw new TypeError("Invalid Fingerprint");let t=this.contents.findIndex(n=>e.equals(n));return t>-1?(this.contents[t]=null,!0):!1}};var Rd=500,_r=class{bucketSize;filterSize;fingerprintSize;buckets;count;hash;seed;constructor(e){this.filterSize=e.filterSize,this.bucketSize=e.bucketSize??4,this.fingerprintSize=e.fingerprintSize??2,this.count=0,this.buckets=[],this.hash=e.hash??vr,this.seed=e.seed??st(0,Math.pow(2,10))}add(e){typeof e=="string"&&(e=L(e));let t=new Ae(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,i=(n^t.hash())%this.filterSize;if(this.buckets[n]==null&&(this.buckets[n]=new at(this.bucketSize)),this.buckets[i]==null&&(this.buckets[i]=new at(this.bucketSize)),this.buckets[n].add(t)||this.buckets[i].add(t))return this.count++,!0;let o=[n,i],s=o[st(0,o.length-1)];this.buckets[s]==null&&(this.buckets[s]=new at(this.bucketSize));for(let a=0;a<Rd;a++){let c=this.buckets[s].swap(t);if(c!=null&&(s=(s^c.hash())%this.filterSize,this.buckets[s]==null&&(this.buckets[s]=new at(this.bucketSize)),this.buckets[s].add(c)))return this.count++,!0}return!1}has(e){typeof e=="string"&&(e=L(e));let t=new Ae(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,i=this.buckets[n]?.has(t)??!1;if(i)return i;let o=(n^t.hash())%this.filterSize;return this.buckets[o]?.has(t)??!1}remove(e){typeof e=="string"&&(e=L(e));let t=new Ae(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,i=this.buckets[n]?.remove(t)??!1;if(i)return this.count--,i;let o=(n^t.hash())%this.filterSize,s=this.buckets[o]?.remove(t)??!1;return s&&this.count--,s}get reliable(){return Math.floor(100*(this.count/this.filterSize))<=90}},Bd={1:.5,2:.84,4:.95,8:.98};function Fd(r=.001){return r>.002?2:r>1e-5?4:8}function Qc(r,e=.001){let t=Fd(e),n=Bd[t],i=Math.round(r/n),o=Math.min(Math.ceil(Math.log2(1/e)+Math.log2(2*t)),Lo);return{filterSize:i,bucketSize:t,fingerprintSize:o}}var Tn=class{filterSize;bucketSize;fingerprintSize;scale;filterSeries;hash;seed;constructor(e){this.bucketSize=e.bucketSize??4,this.filterSize=e.filterSize??(1<<18)/this.bucketSize,this.fingerprintSize=e.fingerprintSize??2,this.scale=e.scale??2,this.hash=e.hash??vr,this.seed=e.seed??st(0,Math.pow(2,10)),this.filterSeries=[new _r({filterSize:this.filterSize,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed})]}add(e){if(typeof e=="string"&&(e=L(e)),this.has(e))return!0;let t=this.filterSeries.find(n=>n.reliable);if(t==null){let n=this.filterSize*Math.pow(this.scale,this.filterSeries.length);t=new _r({filterSize:n,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed}),this.filterSeries.push(t)}return t.add(e)}has(e){typeof e=="string"&&(e=L(e));for(let t=0;t<this.filterSeries.length;t++)if(this.filterSeries[t].has(e))return!0;return!1}remove(e){typeof e=="string"&&(e=L(e));for(let t=0;t<this.filterSeries.length;t++)if(this.filterSeries[t].remove(e))return!0;return!1}get count(){return this.filterSeries.reduce((e,t)=>e+t.count,0)}};function Ln(r,e=.001,t){return new Tn({...Qc(r,e),...t??{}})}var Ud=r=>{let e=r.addEventListener||r.on||r.addListener,t=r.removeEventListener||r.off||r.removeListener;if(!e||!t)throw new TypeError("Emitter is not compatible");return{addListener:e.bind(r),removeListener:t.bind(r)}};function Md(r,e,t){let n,i=new Promise((o,s)=>{if(t={rejectionEvents:["error"],multiArgs:!1,rejectionMultiArgs:!1,resolveImmediately:!1,...t},!(t.count>=0&&(t.count===Number.POSITIVE_INFINITY||Number.isInteger(t.count))))throw new TypeError("The `count` option should be at least 0 or more");t.signal?.throwIfAborted();let a=[e].flat(),c=[],{addListener:f,removeListener:l}=Ud(r),h=async(...g)=>{let w=t.multiArgs?g:g[0];if(t.filter)try{if(!await t.filter(w))return}catch(A){n(),s(A);return}c.push(w),t.count===c.length&&(n(),o(c))},d=(...g)=>{n(),s(t.rejectionMultiArgs?g:g[0])};n=()=>{for(let g of a)l(g,h);for(let g of t.rejectionEvents)a.includes(g)||l(g,d)};for(let g of a)f(g,h);for(let g of t.rejectionEvents)a.includes(g)||f(g,d);t.signal&&t.signal.addEventListener("abort",()=>{d(t.signal.reason)},{once:!0}),t.resolveImmediately&&o(c)});if(i.cancel=n,typeof t.timeout=="number"){let o=nr(i,{milliseconds:t.timeout});return o.cancel=()=>{n(),o.clear()},o}return i}function Dn(r,e,t){typeof t=="function"&&(t={filter:t}),t={...t,count:1,resolveImmediately:!1};let n=Md(r,e,t),i=n.then(o=>o[0]);return i.cancel=n.cancel,i}function Do(r,e){let t,n=function(){let i=function(){t=void 0,r()};clearTimeout(t),t=setTimeout(i,e)};return n.start=()=>{},n.stop=()=>{clearTimeout(t)},n}var Pn=class extends Error{static name="QueueFullError";constructor(e="The queue was full"){super(e),this.name="QueueFullError"}};var Nn=class{deferred;signal;onProgress;constructor(e){this.signal=e?.signal,this.onProgress=e?.onProgress,this.deferred=X(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new xe)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function $d(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var Rn=class{id;fn;options;recipients;status;timeline;controller;dispatchingProgress;constructor(e,t){this.id=$d(),this.status="queued",this.fn=e,this.options=t,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,this.controller.signal,this.dispatchingProgress=!1,this.onAbort=this.onAbort.bind(this)}abort(e){this.controller.abort(e)}onAbort(){this.recipients.reduce((t,n)=>t&&n.signal?.aborted===!0,!0)&&(this.controller.abort(new xe),this.cleanup())}async join(e){let t=new Nn(e);return this.recipients.push(t),e?.signal?.addEventListener("abort",this.onAbort),t.deferred.promise}async run(){this.status="running",this.timeline.started=Date.now();try{this.controller.signal.throwIfAborted();let e=await Ve(this.fn({...this.options??{},signal:this.controller.signal,onProgress:t=>{if(!this.dispatchingProgress){this.dispatchingProgress=!0;try{this.recipients.forEach(n=>{n.onProgress?.(t)})}finally{this.dispatchingProgress=!1}}}}),this.controller.signal);this.recipients.forEach(t=>{t.deferred.resolve(e)}),this.status="complete"}catch(e){this.recipients.forEach(t=>{t.deferred.reject(e)}),this.status="errored"}finally{this.timeline.finished=Date.now(),this.cleanup()}}cleanup(){this.recipients.forEach(e=>{e.cleanup(),e.signal?.removeEventListener("abort",this.onAbort)})}};var De=class extends ue{concurrency;maxSize;queue;pending;sort;paused;constructor(e={}){super(),this.concurrency=e.concurrency??Number.POSITIVE_INFINITY,this.maxSize=e.maxSize??Number.POSITIVE_INFINITY,this.pending=0,this.paused=!1,e.metricName!=null&&e.metrics?.registerMetricGroup(e.metricName,{calculate:()=>({size:this.queue.length,running:this.pending,queued:this.queue.length-this.pending})}),this.sort=e.sort,this.queue=[],this.emitEmpty=Do(this.emitEmpty.bind(this),1),this.emitIdle=Do(this.emitIdle.bind(this),1)}emitEmpty(){this.size===0&&this.safeDispatchEvent("empty")}emitIdle(){this.running===0&&this.safeDispatchEvent("idle")}pause(){this.paused=!0}resume(){this.paused&&(this.paused=!1,this.tryToStartAnother())}tryToStartAnother(){if(this.paused)return!1;if(this.size===0)return this.emitEmpty(),this.running===0&&this.emitIdle(),!1;if(this.pending<this.concurrency){let e;for(let t of this.queue)if(t.status==="queued"){e=t;break}return e==null?!1:(this.safeDispatchEvent("active"),this.pending++,e.run().finally(()=>{for(let t=0;t<this.queue.length;t++)if(this.queue[t]===e){this.queue.splice(t,1);break}this.pending--,this.tryToStartAnother(),this.safeDispatchEvent("next")}),!0)}return!1}enqueue(e){this.queue.push(e),this.sort!=null&&this.queue.sort(this.sort)}async add(e,t){if(t?.signal?.throwIfAborted(),this.size===this.maxSize)throw new Pn;let n=new Rn(e,t);this.enqueue(n),this.safeDispatchEvent("add");let i=n.join(t).then(o=>(this.safeDispatchEvent("completed",{detail:o}),this.safeDispatchEvent("success",{detail:{job:n,result:o}}),o)).catch(o=>{if(n.status==="queued"){for(let s=0;s<this.queue.length;s++)if(this.queue[s]===n){this.queue.splice(s,1);break}}throw this.safeDispatchEvent("failure",{detail:{job:n,error:o}}),o});return this.tryToStartAnother(),i}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(e=>{e.abort(new xe)}),this.clear()}async onEmpty(e){this.size!==0&&await Dn(this,"empty",e)}async onSizeLessThan(e,t){this.size<e||await Dn(this,"next",{...t,filter:()=>this.size<e})}async onIdle(e){this.pending===0&&this.size===0||await Dn(this,"idle",e)}get size(){return this.queue.length}get queued(){return this.queue.length-this.pending}get running(){return this.pending}async*toGenerator(e){e?.signal?.throwIfAborted();let t=fr({objectMode:!0}),n=c=>{c!=null?this.abort():this.clear(),t.end(c)},i=c=>{c.detail!=null&&t.push(c.detail)},o=c=>{n(c.detail.error)},s=()=>{n()},a=()=>{n(new xe("Queue aborted"))};this.addEventListener("completed",i),this.addEventListener("failure",o),this.addEventListener("idle",s),e?.signal?.addEventListener("abort",a);try{yield*t}finally{this.removeEventListener("completed",i),this.removeEventListener("failure",o),this.removeEventListener("idle",s),e?.signal?.removeEventListener("abort",a),n()}}};function Se(r){let e=new globalThis.AbortController;function t(){let o=r.filter(s=>s?.aborted===!0).map(s=>s?.reason).pop();e.abort(o);for(let s of r)s?.removeEventListener!=null&&s.removeEventListener("abort",t)}for(let o of r){if(o?.aborted===!0){t();break}o?.addEventListener!=null&&o.addEventListener("abort",t)}function n(){for(let o of r)o?.removeEventListener!=null&&o.removeEventListener("abort",t)}let i=e.signal;return i.clear=n,i}function Od(r){return r[Symbol.asyncIterator]!=null}function Kd(r){if(Od(r))return(async()=>{let n=new Uint8Array(0);for await(let i of r)n=ge([n,i],n.length+i.length);return n})();let e=[],t=0;for(let n of r)e.push(n),t+=n.byteLength;return ge(e,t)}var Yc=Kd;function Bn({enumerable:r=!0,configurable:e=!1}={}){return{enumerable:r,configurable:e,writable:!1}}function*zd(r,e){if(e!=null&&typeof e=="object")if(Array.isArray(e))for(let[t,n]of e.entries()){let i=[...r,t],o=v.asCID(n);o!=null?yield[i.join("/"),o]:typeof n=="object"&&(yield*Po(n,i))}else{let t=v.asCID(e);t!=null?yield[r.join("/"),t]:yield*Po(e,r)}}function*Po(r,e){if(r==null||r instanceof Uint8Array)return;let t=v.asCID(r);t!=null&&(yield[e.join("/"),t]);for(let[n,i]of Object.entries(r)){let o=[...e,n];yield*zd(o,i)}}function*qd(r,e){if(Array.isArray(e))for(let[t,n]of e.entries()){let i=[...r,t];yield i.join("/"),typeof n=="object"&&v.asCID(n)==null&&(yield*No(n,i))}else yield*No(e,r)}function*No(r,e){if(!(r==null||typeof r!="object"))for(let[t,n]of Object.entries(r)){let i=[...e,t];yield i.join("/"),n!=null&&!(n instanceof Uint8Array)&&typeof n=="object"&&v.asCID(n)==null&&(yield*qd(i,n))}}function jd(r,e){let t=r;for(let[n,i]of e.entries()){if(t=t[i],t==null)throw new Error(`Object has no property at ${e.slice(0,n+1).map(s=>`[${JSON.stringify(s)}]`).join("")}`);let o=v.asCID(t);if(o!=null)return{value:o,remaining:e.slice(n+1).join("/")}}return{value:t}}var Ro=class{cid;bytes;value;asBlock;constructor({cid:e,bytes:t,value:n}){if(e==null||t==null||typeof n>"u")throw new Error("Missing required argument");this.cid=e,this.bytes=t,this.value=n,this.asBlock=this,Object.defineProperties(this,{cid:Bn(),bytes:Bn(),value:Bn(),asBlock:Bn()})}links(){return Po(this.value,[])}tree(){return No(this.value,[])}get(e="/"){return jd(this.value,e.split("/").filter(Boolean))}};function Xc({bytes:r,cid:e,value:t,codec:n}){let i=t!==void 0?t:n?.decode(r);if(i===void 0)throw new Error('Missing required argument, must either provide "value" or "codec"');return new Ro({cid:e,bytes:r,value:i})}function Ar(r){return e=>new Bo(e,r)}function Zc(r){return e=>new Fo(e,r)}function eu(r){return e=>new Uo(e,r)}var kr=class{components;constructor(e,t={}){this.components=e}async*walk(e,t){let n=this.getQueue(),i=re(n.toGenerator(t),c=>c!=null),o=!1,s=t?.depth??1/0,a=async c=>{let f=c.cid,l=await Yc(this.components.blockstore.get(f,c)),h=Xc({cid:f,bytes:l,codec:await this.components.getCodec(f.code)});if(c.depth<s)for(let[,d]of h.links())t?.includeChild?.(d,h)!==!1&&n.add(a,{...c,cid:d,depth:c.depth+1,path:[...c.path,d]}).catch(g=>{o||i.throw(g)});return{block:h,depth:c.depth,path:c.path}};n.add(a,{...t,cid:e,depth:0,path:[e]}).catch(c=>{o||i.throw(c)});try{yield*i}finally{o=!0,n.abort()}}},Bo=class extends kr{getQueue(){return new De({concurrency:1,sort:(e,t)=>e.options.depth===t.options.depth?0:e.options.depth<t.options.depth?1:-1})}},Fo=class extends kr{getQueue(){return new De({concurrency:1,sort:(e,t)=>e.options.depth===t.options.depth?0:e.options.depth<t.options.depth?-1:1})}},Uo=class extends kr{getQueue(){return new De({concurrency:1})}};var ru="/pin/",tu="/pinned-block/",Mo=te;function Fn(r){return r.version===0&&(r=r.toV1()),new B(`${ru}${r.toString(Mo)}`)}var Un=class{datastore;blockstore;getCodec;constructor(e,t,n){this.datastore=e,this.blockstore=t,this.getCodec=n}async*add(e,t={}){let n=Fn(e);if(await this.datastore.has(n))throw new An("Already pinned");let i=Math.round(t.depth??1/0);if(i<0)throw new _t("Depth must be greater than or equal to 0");let o=(t.walker??Ar())({blockstore:this.blockstore,getCodec:this.getCodec});for await(let a of o.walk(e,{...t,depth:i})){let c=a.block.cid;await this.#e(c,f=>f.pinnedBy.find(l=>Re(l,e.bytes))!=null?!1:(f.pinCount++,f.pinnedBy.push(e.bytes),!0),t),yield c}let s={depth:i,metadata:t.metadata??{}};await this.datastore.put(n,it(s),t)}async#e(e,t,n){let i=new B(`${tu}${Mo.encode(e.multihash.bytes)}`),o={pinCount:0,pinnedBy:[]};try{o=ke(await this.datastore.get(i,n))}catch(a){if(a.name!=="NotFoundError")throw a}if(t(o)){if(o.pinCount===0&&await this.datastore.has(i)){await this.datastore.delete(i);return}await this.datastore.put(i,it(o),n),n.onProgress?.(new x("helia:pin:add",e))}}async*rm(e,t={}){let n=Fn(e),i=await this.datastore.get(n,t),o=ke(i);await this.datastore.delete(n,t);let s=(t.walker??Ar())({blockstore:this.blockstore,getCodec:this.getCodec});for await(let a of s.walk(e,{...t,depth:o.depth})){let c=a.block.cid;await this.#e(c,f=>(f.pinCount--,f.pinnedBy=f.pinnedBy.filter(l=>Re(l,e.bytes)),!0),{...t,depth:o.depth}),yield c}}async*ls(e={}){for await(let{key:t,value:n}of this.datastore.query({prefix:ru+(e.cid!=null?`${e.cid.toString(te)}`:"")},e)){let i=v.parse(t.toString().substring(5),te),o=ke(n);yield{cid:i,...o}}}async isPinned(e,t={}){let n=new B(`${tu}${Mo.encode(e.multihash.bytes)}`);return this.datastore.has(n,t)}async get(e,t){let n=Fn(e),i=await this.datastore.get(n,t);return ke(i)}async setMetadata(e,t,n){let i=Fn(e),o=await this.datastore.get(i,n),s=ke(o);s.metadata=t??{},await this.datastore.put(i,it(s),n)}};var Mn=class extends Error{static name="InsufficientProvidersError";constructor(e="Insufficient providers found"){super(e),this.name="InsufficientProvidersError"}},ct=class extends Error{static name="NoRoutersAvailableError";constructor(e="No routers available"){super(e),this.name="NoRoutersAvailableError"}},$n=class extends Error{static name="UnknownHashAlgorithmError";constructor(e="Unknown hash algorithm"){super(e),this.name="UnknownHashAlgorithmError"}},On=class extends Error{static name="UnknownCodecError";constructor(e="Unknown codec"){super(e),this.name="UnknownCodecError"}};var Kn=class extends Error{static name="UnknownCryptoError";name="UnknownCryptoError"};var Vd=5,zn=class{name;log;routers;providerLookupConcurrency;constructor(e,t){this.name="helia",this.log=e.logger.forComponent("helia:routing"),this.routers=t.routers??[],this.providerLookupConcurrency=t.providerLookupConcurrency??Vd,this.findProviders=e.metrics?.traceFunction("helia.routing.findProviders",this.findProviders.bind(this),{optionsIndex:1})??this.findProviders,this.provide=e.metrics?.traceFunction("helia.routing.provide",this.provide.bind(this),{optionsIndex:1})??this.provide,this.cancelReprovide=e.metrics?.traceFunction("helia.routing.cancelReprovide",this.cancelReprovide.bind(this),{optionsIndex:1})??this.cancelReprovide,this.put=e.metrics?.traceFunction("helia.routing.put",this.put.bind(this),{optionsIndex:2})??this.put,this.get=e.metrics?.traceFunction("helia.routing.get",this.get.bind(this),{optionsIndex:1})??this.get,this.findPeer=e.metrics?.traceFunction("helia.routing.findPeer",this.findPeer.bind(this),{optionsIndex:1})??this.findPeer,this.getClosestPeers=e.metrics?.traceFunction("helia.routing.getClosestPeers",this.getClosestPeers.bind(this),{optionsIndex:1})??this.getClosestPeers}async start(){await qe(...this.routers)}async stop(){await je(...this.routers)}hasRouter(e){return this.routers.findIndex(t=>t.name===e)!==-1}addRouter(e){this.routers.push(e)}async*findProviders(e,t={}){if(this.routers.length===0)throw new ct("No content routers available");let n=new De({concurrency:this.providerLookupConcurrency}),i=0,o=[],s=this,a=0;this.log("findProviders for %c start using routers %s",e,this.routers.map(f=>f.toString()).join(", "));let c=ut(this.routers,"findProviders").map(async function*(f){let l=0;t?.onProgress?.(new x("helia:routing:find-providers:start",{routing:f.name,cid:e}));try{for await(let h of f.findProviders(e,t))l++,t?.onProgress?.(new x("helia:routing:find-providers:provider",{routing:f.name,cid:e,provider:h})),yield h}catch(h){o.push(h)}finally{s.log("router %s found %d providers for %c",f,l,e),t?.onProgress?.(new x("helia:routing:find-providers:end",{routing:f.name,cid:e,found:l})),a++,a===c.length&&n.size===0&&n.emitIdle()}});for await(let f of tt(n.toGenerator(),...c))if(f!=null){if(f.multiaddrs.length===0){if(n.queue.find(l=>l.options.peer.equals(f.id))!=null)continue;n.add(async()=>{try{let l=await this.findPeer(f.id,t);return l.multiaddrs.length===0?null:{...l,protocols:f.protocols,routing:f.routing}}catch(l){return this.log.error("could not load multiaddrs for peer %p - %e",f.id,l),null}},{peer:f.id,signal:t.signal}).catch(l=>{this.log.error("could not load multiaddrs for peer %p - %e",f.id,l)});continue}i++,yield f}this.log("findProviders finished, found %d providers for %c",i,e)}async provide(e,t={}){if(this.routers.length===0)throw new ct("No content routers available");await Promise.all(ut(this.routers,"provide").map(async n=>{t?.onProgress?.(new x("helia:routing:provide:start",{routing:n.name,cid:e})),await n.provide(e,t),t?.onProgress?.(new x("helia:routing:provide:end",{routing:n.name,cid:e}))}))}async cancelReprovide(e,t={}){await Promise.all(ut(this.routers,"cancelReprovide").map(async n=>{t?.onProgress?.(new x("helia:routing:cancel-reprovide:start",{routing:n.name,cid:e})),await n.cancelReprovide(e,t),t?.onProgress?.(new x("helia:routing:cancel-reprovide:end",{routing:n.name,cid:e}))}))}async put(e,t,n){await Promise.all(ut(this.routers,"put").map(async i=>{n?.onProgress?.(new x("helia:routing:put:start",{routing:i.name,key:e,value:t})),await i.put(e,t,n),n?.onProgress?.(new x("helia:routing:put:end",{routing:i.name,key:e,value:t}))}))}async get(e,t){let n=[],i;try{i=await Promise.any(ut(this.routers,"get").map(async o=>{t?.onProgress?.(new x("helia:routing:get:start",{routing:o.name,key:e}));try{return await o.get(e,t)}catch(s){this.log("router %s failed with %e",o,s),n.push(s)}finally{t?.onProgress?.(new x("helia:routing:get:end",{routing:o.name,key:e}))}}))}catch{}if(i==null)throw new In(n,`Failed to get value key ${ce(e,"base58btc")}`);return i}async findPeer(e,t){if(this.routers.length===0)throw new ct("No peer routers available");let n=this,i=tt(...ut(this.routers,"findPeer").map(o=>(async function*(){t?.onProgress?.(new x("helia:routing:find-peer:start",{routing:o.name,peerId:e}));try{yield await o.findPeer(e,t)}catch(s){n.log.error(s)}finally{t?.onProgress?.(new x("helia:routing:find-peer:end",{routing:o.name,peerId:e}))}})()));for await(let o of i)if(o!=null)return o;throw new Zr("Could not find peer in routing")}async*getClosestPeers(e,t={}){if(this.routers.length===0)throw new ct("No peer routers available");for await(let n of tt(...ut(this.routers,"getClosestPeers").map(async function*(i){t?.onProgress?.(new x("helia:routing:get-closest-peers:start",{routing:i.name,key:e}));try{yield*i.getClosestPeers(e,t)}finally{t?.onProgress?.(new x("helia:routing:get-closest-peers:end",{routing:i.name,key:e}))}})))n!=null&&(yield n)}};function ut(r,e){return r.filter(t=>t[e]!=null)}var ae=class extends Error{static name="AbortError";name="AbortError";constructor(e="The operation was aborted",...t){super(e,...t)}};async function qn(r,e,t,n){let i=new ae(n?.errorMessage);n?.errorCode!=null&&(i.code=n.errorCode);let o=n?.errorEvent??"error";return t?.aborted===!0?Promise.reject(i):new Promise((s,a)=>{function c(){Oo(t,"abort",h),Oo(r,e,f),Oo(r,o,l)}let f=d=>{try{if(n?.filter?.(d)===!1)return}catch(g){c(),a(g);return}c(),s(d)},l=d=>{if(c(),d instanceof Error){a(d);return}a(d.detail??n?.error??new Error(`The "${n?.errorEvent}" event was emitted but the event had no '.detail' field. Pass an 'error' option to race-event to change this message.`))},h=()=>{c(),a(i)};$o(t,"abort",h),$o(r,e,f),$o(r,o,l)})}function $o(r,e,t){r!=null&&(nu(r)?r.addEventListener(e,t):r.addListener(e,t))}function Oo(r,e,t){r!=null&&(nu(r)?r.removeEventListener(e,t):r.removeListener(e,t))}function nu(r){return typeof r.addEventListener=="function"&&typeof r.removeEventListener=="function"}var jn=class extends Error{static name="QueueFullError";constructor(e="The queue was full"){super(e),this.name="QueueFullError"}};var Vn=class{deferred;signal;constructor(e){this.signal=e,this.deferred=Promise.withResolvers(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new ae)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function Hd(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var Hn=class{id;fn;options;recipients;status;timeline;controller;constructor(e,t){this.id=Hd(),this.status="queued",this.fn=e,this.options=t,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,this.controller.signal,this.onAbort=this.onAbort.bind(this)}abort(e){this.controller.abort(e)}onAbort(){this.recipients.reduce((t,n)=>t&&n.signal?.aborted===!0,!0)&&(this.controller.abort(new ae),this.cleanup())}async join(e={}){let t=new Vn(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 Ve(this.fn({...this.options??{},signal:this.controller.signal}),this.controller.signal);this.recipients.forEach(t=>{t.deferred.resolve(e)}),this.status="complete"}catch(e){this.recipients.forEach(t=>{t.deferred.reject(e)}),this.status="errored"}finally{this.timeline.finished=Date.now(),this.cleanup()}}cleanup(){this.recipients.forEach(e=>{e.cleanup(),e.signal?.removeEventListener("abort",this.onAbort)})}};function Ko(r,e){let t,n=function(){let i=function(){t=void 0,r()};clearTimeout(t),t=setTimeout(i,e)};return n.start=()=>{},n.stop=()=>{clearTimeout(t)},n}var Sr=class extends ue{concurrency;maxSize;queue;pending;sort;autoStart;constructor(e={}){super(),this.concurrency=e.concurrency??Number.POSITIVE_INFINITY,this.maxSize=e.maxSize??Number.POSITIVE_INFINITY,this.pending=0,this.autoStart=e.autoStart??!0,this.sort=e.sort,this.queue=[],this.emitEmpty=Ko(this.emitEmpty.bind(this),1),this.emitIdle=Ko(this.emitIdle.bind(this),1)}[Symbol.asyncIterator](){return this.toGenerator()}emitEmpty(){this.size===0&&this.safeDispatchEvent("empty")}emitIdle(){this.running===0&&this.safeDispatchEvent("idle")}tryToStartAnother(){if(this.size===0)return this.emitEmpty(),this.running===0&&this.emitIdle(),!1;if(this.pending<this.concurrency){let e;for(let t of this.queue)if(t.status==="queued"){e=t;break}return e==null?!1:(this.safeDispatchEvent("active"),this.pending++,e.run().finally(()=>{for(let t=0;t<this.queue.length;t++)if(this.queue[t]===e){this.queue.splice(t,1);break}this.pending--,this.safeDispatchEvent("next"),this.autoStart&&this.tryToStartAnother()}),!0)}return!1}enqueue(e){this.queue.push(e),this.sort!=null&&this.queue.sort(this.sort)}start(){this.autoStart===!1&&(this.autoStart=!0,this.tryToStartAnother())}pause(){this.autoStart=!1}async add(e,t){if(t?.signal?.throwIfAborted(),this.size===this.maxSize)throw new jn;let n=new Hn(e,t);return this.enqueue(n),this.safeDispatchEvent("add"),this.autoStart&&this.tryToStartAnother(),n.join(t).then(i=>(this.safeDispatchEvent("success",{detail:{job:n,result:i}}),i)).catch(i=>{if(n.status==="queued"){for(let o=0;o<this.queue.length;o++)if(this.queue[o]===n){this.queue.splice(o,1);break}}throw this.safeDispatchEvent("failure",{detail:{job:n,error:i}}),i})}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(e=>{e.abort(new ae)}),this.clear()}async onEmpty(e){this.size!==0&&await qn(this,"empty",e?.signal)}async onSizeLessThan(e,t){this.size<e||await qn(this,"next",t?.signal,{filter:()=>this.size<e})}async onIdle(e){this.pending===0&&this.size===0||await qn(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=fr({objectMode:!0}),n=c=>{c!=null?this.abort():this.clear(),t.end(c)},i=c=>{c.detail!=null&&t.push(c.detail.result)},o=c=>{n(c.detail.error)},s=()=>{n()},a=()=>{n(new ae("Queue aborted"))};this.addEventListener("success",i),this.addEventListener("failure",o),this.addEventListener("idle",s),e?.signal?.addEventListener("abort",a);try{yield*t}finally{this.removeEventListener("success",i),this.removeEventListener("failure",o),this.removeEventListener("idle",s),e?.signal?.removeEventListener("abort",a),n()}}};var Wn="lock:worker:request-read",Gn="lock:worker:abort-read-request",Jn="lock:worker:release-read",Qn="lock:master:grant-read",Yn="lock:master:error-read",Xn="lock:worker:request-write",Zn="lock:worker:abort-write-request",ei="lock:worker:release-write",ti="lock:master:grant-write",ri="lock:master:error-write",ni="lock:worker:finalize",ii="mortice",iu={singleProcess:!1};var zo=(r,e,t,n,i,o,s,a,c)=>f=>{if(f.data==null)return;let l={type:f.data.type,name:f.data.name,identifier:f.data.identifier};l.type===i&&r.safeDispatchEvent(t,{detail:{name:l.name,identifier:l.identifier,handler:async()=>{e.postMessage({type:c,name:l.name,identifier:l.identifier}),await new Promise(h=>{let d=g=>{if(g?.data==null)return;let w={type:g.data.type,name:g.data.name,identifier:g.data.identifier};w.type===a&&w.identifier===l.identifier&&(e.removeEventListener("message",d),h())};e.addEventListener("message",d)})},onError:h=>{e.postMessage({type:s,name:l.name,identifier:l.identifier,error:{message:h.message,name:h.name,stack:h.stack}})}}}),l.type===o&&r.safeDispatchEvent(n,{detail:{name:l.name,identifier:l.identifier}}),l.type===ni&&r.safeDispatchEvent("finalizeRequest",{detail:{name:l.name}})};var ou=(r=10)=>Math.random().toString().substring(2,r+2);var oi=class{name;channel;constructor(e){this.name=e,this.channel=new BroadcastChannel(ii)}readLock(e){return this.sendRequest(Wn,Gn,Qn,Yn,Jn,e)}writeLock(e){return this.sendRequest(Xn,Zn,ti,ri,ei,e)}finalize(){this.channel.postMessage({type:ni,name:this.name}),this.channel.close()}async sendRequest(e,t,n,i,o,s){s?.signal?.throwIfAborted();let a=ou();return this.channel.postMessage({type:e,identifier:a,name:this.name}),new Promise((c,f)=>{let l=()=>{this.channel.postMessage({type:t,identifier:a,name:this.name})};s?.signal?.addEventListener("abort",l,{once:!0});let h=d=>{if(d.data?.identifier===a&&(d.data?.type===n&&(this.channel.removeEventListener("message",h),s?.signal?.removeEventListener("abort",l),c(()=>{this.channel.postMessage({type:o,identifier:a,name:this.name})})),d.data.type===i)){this.channel.removeEventListener("message",h),s?.signal?.removeEventListener("abort",l);let g=new Error;d.data.error!=null&&(g.message=d.data.error.message,g.name=d.data.error.name,g.stack=d.data.error.stack),f(g)}};this.channel.addEventListener("message",h)})}};var su=r=>{if(r=Object.assign({},iu,r),!!globalThis.document||r.singleProcess){let t=new BroadcastChannel(ii),n=new ue;return t.addEventListener("message",zo(n,t,"requestReadLock","abortReadLockRequest",Wn,Gn,Yn,Jn,Qn)),t.addEventListener("message",zo(n,t,"requestWriteLock","abortWriteLockRequest",Xn,Zn,ri,ei,ti)),n}return new oi(r.name)};var lt=new Map,Ir;function au(r){return typeof r?.readLock=="function"&&typeof r?.writeLock=="function"}function Wd(r){if(Ir==null&&(Ir=su(r),!au(Ir))){let e=Ir;e.addEventListener("requestReadLock",t=>{let n=t.detail.name,i=t.detail.identifier,o=lt.get(n);if(o==null)return;let s=new AbortController,a=c=>{c.detail.name!==n||c.detail.identifier!==i||s.abort()};e.addEventListener("abortReadLockRequest",a),o.readLock({signal:s.signal}).then(async c=>{await t.detail.handler().finally(()=>{c()})}).catch(c=>{t.detail.onError(c)}).finally(()=>{e.removeEventListener("abortReadLockRequest",a)})}),e.addEventListener("requestWriteLock",t=>{let n=t.detail.name,i=t.detail.identifier,o=lt.get(n);if(o==null)return;let s=new AbortController,a=c=>{c.detail.name!==n||c.detail.identifier!==i||s.abort()};e.addEventListener("abortWriteLockRequest",a),o.writeLock({signal:s.signal}).then(async c=>{await t.detail.handler().finally(()=>{c()})}).catch(c=>{t.detail.onError(c)}).finally(()=>{e.removeEventListener("abortWriteLockRequest",a)})}),e.addEventListener("finalizeRequest",t=>{let n=t.detail.name,i=lt.get(n);i?.finalize()})}return Ir}async function qo(r,e){let t,n,i=new Promise((s,a)=>{t=s,n=a}),o=()=>{n(new ae)};return e?.signal?.addEventListener("abort",o,{once:!0}),r.add(async()=>{await new Promise(s=>{t(()=>{e?.signal?.removeEventListener("abort",o),s()})})},{signal:e?.signal}).catch(s=>{n(s)}),i}var cu=(r,e)=>{let t=lt.get(r);if(t!=null)return t;let n=Wd(e);if(au(n))return t=n,lt.set(r,t),t;let i=new Sr({concurrency:1}),o;return t={async readLock(s){if(o!=null)return qo(o,s);o=new Sr({concurrency:e.concurrency,autoStart:!1});let a=o,c=qo(o,s);return i.add(async()=>{a.start(),await a.onIdle().then(()=>{o===a&&(o=null)})}),c},async writeLock(s){return o=null,qo(i,s)},finalize:()=>{lt.delete(r)},queue:i},lt.set(r,t),e.autoFinalize===!0&&i.addEventListener("idle",()=>{t.finalize()},{once:!0}),t};var Gd={name:"lock",concurrency:1/0,singleProcess:!1,autoFinalize:!1};function jo(r){let e=Object.assign({},Gd,r);return cu(e.name,e)}var si=class{lock;child;pins;routing;started;constructor(e,t,n,i={}){this.child=e,this.pins=t,this.routing=n,this.lock=jo({singleProcess:i.holdGcLock}),this.started=!1}isStarted(){return this.started}async start(){await qe(this.child),this.started=!0}async stop(){await je(this.child),this.started=!1}unwrap(){return this.child}async put(e,t,n={}){n?.signal?.throwIfAborted();let i=await this.lock.readLock();try{return await this.child.put(e,t,n)}finally{i()}}async*putMany(e,t={}){t?.signal?.throwIfAborted();let n=await this.lock.readLock();try{yield*this.child.putMany(e,t)}finally{n()}}async*get(e,t={}){t?.signal?.throwIfAborted();let n=await this.lock.readLock();try{yield*this.child.get(e,t)}finally{n()}}async*getMany(e,t={}){t?.signal?.throwIfAborted();let n=await this.lock.readLock();try{yield*this.child.getMany(e,t)}finally{n()}}async delete(e,t={}){t?.signal?.throwIfAborted();let n=await this.lock.writeLock();try{if(await this.pins.isPinned(e))throw new xr("Block was pinned - please unpin and try again");await this.routing.cancelReprovide(e,t),await this.child.delete(e,t)}finally{n()}}async*deleteMany(e,t={}){t?.signal?.throwIfAborted();let n=await this.lock.writeLock();try{let i=this;yield*this.child.deleteMany((async function*(){for await(let o of e){if(await i.pins.isPinned(o))throw new xr("Block was pinned - please unpin and try again");await i.routing.cancelReprovide(o,t),yield o}})(),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 Vo=new B("/version"),uu=1;async function lu(r){if(!await r.has(Vo)){await r.put(Vo,L(`${uu}`));return}let e=await r.get(Vo),t=ce(e);if(parseInt(t,10)!==uu)throw new Sn("Invalid datastore version, a datastore migration may be required")}var Jo={};F(Jo,{code:()=>Go,decode:()=>ip,decodeOptions:()=>tp,encode:()=>np,encodeOptions:()=>Zd,name:()=>rp,toByteView:()=>hu});var fu=42;function hu(r){return r instanceof ArrayBuffer?new Uint8Array(r,0,r.byteLength):r}function Jd(r){if(r.asCID!==r&&r["/"]!==r.bytes)return null;let e=v.asCID(r);if(!e)return null;let t=new Uint8Array(e.bytes.byteLength+1);return t.set(e.bytes,1),[new p(u.tag,fu),new p(u.bytes,t)]}function Qd(){throw new Error("`undefined` is not supported by the IPLD Data Model and cannot be encoded")}function Yd(r){if(Number.isNaN(r))throw new Error("`NaN` is not supported by the IPLD Data Model and cannot be encoded");if(r===1/0||r===-1/0)throw new Error("`Infinity` and `-Infinity` is not supported by the IPLD Data Model and cannot be encoded");return null}function Xd(r){for(let e of r.keys())if(typeof e!="string"||e.length===0)throw new Error("Non-string Map keys are not supported by the IPLD Data Model and cannot be encoded");return null}var Ho={float64:!0,typeEncoders:{Map:Xd,Object:Jd,undefined:Qd,number:Yd}},Zd={...Ho,typeEncoders:{...Ho.typeEncoders}};function ep(r){let e=r();if(e[0]!==0)throw new Error("Invalid CID for CBOR tag 42; expected leading 0x00");return v.decode(e.subarray(1))}var Wo={allowIndefinite:!1,coerceUndefinedToNull:!0,allowNaN:!1,allowInfinity:!1,allowBigInt:!0,strict:!0,useMaps:!1,rejectDuplicateMapKeys:!0,tags:{[fu]:ep}},tp={...Wo,tags:{...Wo.tags}},rp="dag-cbor",Go=113,np=r=>it(r,Ho),ip=r=>ke(hu(r),Wo);var ts={};F(ts,{code:()=>es,decode:()=>mu,encode:()=>pu,format:()=>mp,name:()=>pp,parse:()=>gp,stringify:()=>mp});var Qo=class extends Array{constructor(){super(),this.inRecursive=[]}prefix(e){let t=this.inRecursive[this.inRecursive.length-1];t&&(u.equals(t.type,u.array)&&(t.elements++,t.elements!==1&&e.push([44])),u.equals(t.type,u.map)&&(t.elements++,t.elements!==1&&(t.elements%2===1?e.push([44]):e.push([58]))))}[u.uint.major](e,t){this.prefix(e);let n=String(t.value),i=[];for(let o=0;o<n.length;o++)i[o]=n.charCodeAt(o);e.push(i)}[u.negint.major](e,t){this[u.uint.major](e,t)}[u.bytes.major](e,t){throw new Error(`${Te} unsupported type: Uint8Array`)}[u.string.major](e,t){this.prefix(e);let n=St(JSON.stringify(t.value));e.push(n.length>32?rt(n):n)}[u.array.major](e,t){this.prefix(e),this.inRecursive.push({type:u.array,elements:0}),e.push([91])}[u.map.major](e,t){this.prefix(e),this.inRecursive.push({type:u.map,elements:0}),e.push([123])}[u.tag.major](e,t){}[u.float.major](e,t){if(t.type.name==="break"){let s=this.inRecursive.pop();if(s){if(u.equals(s.type,u.array))e.push([93]);else if(u.equals(s.type,u.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(`${Te} 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),i=[],o=!1;for(let s=0;s<n.length;s++)i[s]=n.charCodeAt(s),!o&&(i[s]===46||i[s]===101||i[s]===69)&&(o=!0);o||(i.push(46),i.push(48)),e.push(i)}};function op(r,e){if(Array.isArray(r[0])||Array.isArray(e[0]))throw new Error(`${Te} complex map keys are not supported`);let t=r[0],n=e[0];if(t.type!==u.string||n.type!==u.string)throw new Error(`${Te} non-string map keys are not supported`);if(t<n)return-1;if(t>n)return 1;throw new Error(`${Te} unexpected duplicate map keys, this is not supported`)}var sp={addBreakTokens:!0,mapSorter:op};function Yo(r,e){return e=Object.assign({},sp,e),vn(r,new Qo,e)}var Nt=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(`${y} 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(`${y} unexpected token at position ${this._pos}, expected to find '${String.fromCharCode(...e)}'`)}parseNumber(){let e=this._pos,t=!1,n=!1,i=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 p(u.uint,0,this._pos-e);if(i([48,49,50,51,52,53,54,55,56,57]),t&&this._pos===e+1)throw new Error(`${y} unexpected token at position ${this._pos}`);if(!this.done()&&this.ch()===46){if(n)throw new Error(`${y} unexpected token at position ${this._pos}`);n=!0,this._pos++,i([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++,i([48,49,50,51,52,53,54,55,56,57]));let o=String.fromCharCode.apply(null,this.data.subarray(e,this._pos)),s=parseFloat(o);return n?new p(u.float,s,this._pos-e):this.options.allowBigInt!==!0||Number.isSafeInteger(s)?new p(s>=0?u.uint:u.negint,s,this._pos-e):new p(s>=0?u.uint:u.negint,BigInt(o),this._pos-e)}parseString(){if(this.ch()!==34)throw new Error(`${y} unexpected character at position ${this._pos}; this shouldn't happen`);this._pos++;for(let o=this._pos,s=0;o<this.data.length&&s<65536;o++,s++){let a=this.data[o];if(a===92||a<32||a>=128)break;if(a===34){let c=String.fromCharCode.apply(null,this.data.subarray(this._pos,o));return this._pos=o+1,new p(u.string,c,s)}}let e=this._pos,t=[],n=()=>{if(this._pos+4>=this.data.length)throw new Error(`${y} unexpected end of unicode escape sequence at position ${this._pos}`);let o=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(`${y} unexpected unicode escape character at position ${this._pos}`);o=o*16+a,this._pos++}return o},i=()=>{let o=this.ch(),s=null,a=o>239?4:o>223?3:o>191?2:1;if(this._pos+a>this.data.length)throw new Error(`${y} unexpected unicode sequence at position ${this._pos}`);let c,f,l,h;switch(a){case 1:o<128&&(s=o);break;case 2:c=this.data[this._pos+1],(c&192)===128&&(h=(o&31)<<6|c&63,h>127&&(s=h));break;case 3:c=this.data[this._pos+1],f=this.data[this._pos+2],(c&192)===128&&(f&192)===128&&(h=(o&15)<<12|(c&63)<<6|f&63,h>2047&&(h<55296||h>57343)&&(s=h));break;case 4:c=this.data[this._pos+1],f=this.data[this._pos+2],l=this.data[this._pos+3],(c&192)===128&&(f&192)===128&&(l&192)===128&&(h=(o&15)<<18|(c&63)<<12|(f&63)<<6|l&63,h>65535&&h<1114112&&(s=h))}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 o=this.ch(),s;switch(o){case 92:if(this._pos++,this.done())throw new Error(`${y} 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(`${y} unexpected string escape character at position ${this._pos}`)}break;case 34:return this._pos++,new p(u.string,Wa(t),this._pos-e);default:if(o<32)throw new Error(`${y} invalid control character at position ${this._pos}`);o<128?(t.push(o),this._pos++):i()}}throw new Error(`${y} unexpected end of string at position ${this._pos}`)}parseValue(){switch(this.ch()){case 123:return this.modeStack.push("obj-start"),this._pos++,new p(u.map,1/0,1);case 91:return this.modeStack.push("array-start"),this._pos++,new p(u.array,1/0,1);case 34:return this.parseString();case 110:return this.expect([110,117,108,108]),new p(u.null,null,4);case 102:return this.expect([102,97,108,115,101]),new p(u.false,!1,5);case 116:return this.expect([116,114,117,101]),new p(u.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(`${y} 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 p(u.break,void 0,1);if(this.ch()!==44)throw new Error(`${y} 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 p(u.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 p(u.break,void 0,1);if(this.ch()!==44)throw new Error(`${y} 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 p(u.break,void 0,1);let e=this.parseString();if(this.skipWhitespace(),this.ch()!==58)throw new Error(`${y} 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(`${y} unexpected parse state at position ${this._pos}; this shouldn't happen`)}}};function Xo(r,e){return e=Object.assign({tokenizer:new Nt(r,e)},e),ke(r,e)}function cp(r){return r instanceof ArrayBuffer?new Uint8Array(r,0,r.byteLength):r}function up(r){if(r.asCID!==r&&r["/"]!==r.bytes)return null;let e=v.asCID(r);if(!e)return null;let t=e.toString();return[new p(u.map,1/0,1),new p(u.string,"/",1),new p(u.string,t,t.length),new p(u.break,void 0,1)]}function ai(r){let e=V.encode(r).slice(1);return[new p(u.map,1/0,1),new p(u.string,"/",1),new p(u.map,1/0,1),new p(u.string,"bytes",5),new p(u.string,e,e.length),new p(u.break,void 0,1),new p(u.break,void 0,1)]}function Ie(r){return ai(new Uint8Array(r.buffer,r.byteOffset,r.byteLength))}function lp(r){return ai(new Uint8Array(r))}function fp(){throw new Error("`undefined` is not supported by the IPLD Data Model and cannot be encoded")}function hp(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 dp={typeEncoders:{Object:up,Buffer:ai,Uint8Array:ai,Int8Array:Ie,Uint16Array:Ie,Int16Array:Ie,Uint32Array:Ie,Int32Array:Ie,Float32Array:Ie,Float64Array:Ie,Uint8ClampedArray:Ie,BigInt64Array:Ie,BigUint64Array:Ie,DataView:Ie,ArrayBuffer:lp,undefined:fp,number:hp}},Zo=class extends Nt{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(u.equals(e.type,u.map)){let t=this._next();if(u.equals(t.type,u.string)&&t.value==="/"){let n=this._next();if(u.equals(n.type,u.string)){let i=this._next();if(!u.equals(i.type,u.break))throw new Error("Invalid encoded CID form");return this.tokenBuffer.push(n),new p(u.tag,42,0)}if(u.equals(n.type,u.map)){let i=this._next();if(u.equals(i.type,u.string)&&i.value==="bytes"){let o=this._next();if(u.equals(o.type,u.string)){for(let a=0;a<2;a++){let c=this._next();if(!u.equals(c.type,u.break))throw new Error("Invalid encoded Bytes form")}let s=V.decode(`m${o.value}`);return new p(u.bytes,s,o.value.length)}this.tokenBuffer.push(o)}this.tokenBuffer.push(i)}this.tokenBuffer.push(n)}this.tokenBuffer.push(t)}return e}},du={allowIndefinite:!1,allowUndefined:!1,allowNaN:!1,allowInfinity:!1,allowBigInt:!0,strict:!0,useMaps:!1,rejectDuplicateMapKeys:!0,tags:{42:r=>v.parse(r())}},pp="dag-json",es=297,pu=r=>Yo(r,dp),mu=r=>{let e=cp(r),t=Object.assign(du,{tokenizer:new Zo(e,du)});return Xo(e,t)},mp=r=>yp.decode(pu(r));var yp=new TextDecoder,gp=r=>mu(wp.encode(r)),wp=new TextEncoder;var as={};F(as,{code:()=>ss,createLink:()=>Au,createNode:()=>ku,decode:()=>Dp,encode:()=>Lp,name:()=>Tp,prepare:()=>is,validate:()=>os});var bp=new TextDecoder;function rs(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 i=r[e++];if(t+=n<28?(i&127)<<n:(i&127)*2**n,i<128)break}return[t,e]}function ci(r,e){let t;[t,e]=rs(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 yu(r,e){let t;return[t,e]=rs(r,e),[t&7,t>>3,e]}function xp(r){let e={},t=r.length,n=0;for(;n<t;){let i,o;if([i,o,n]=yu(r,n),o===1){if(e.Hash)throw new Error("protobuf: (PBLink) duplicate Hash section");if(i!==2)throw new Error(`protobuf: (PBLink) wrong wireType (${i}) 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]=ci(r,n)}else if(o===2){if(e.Name!==void 0)throw new Error("protobuf: (PBLink) duplicate Name section");if(i!==2)throw new Error(`protobuf: (PBLink) wrong wireType (${i}) for Name`);if(e.Tsize!==void 0)throw new Error("protobuf: (PBLink) invalid order, found Tsize before Name");let s;[s,n]=ci(r,n),e.Name=bp.decode(s)}else if(o===3){if(e.Tsize!==void 0)throw new Error("protobuf: (PBLink) duplicate Tsize section");if(i!==0)throw new Error(`protobuf: (PBLink) wrong wireType (${i}) for Tsize`);[e.Tsize,n]=rs(r,n)}else throw new Error(`protobuf: (PBLink) invalid fieldNumber, expected 1, 2 or 3, got ${o}`)}if(n>t)throw new Error("protobuf: (PBLink) unexpected end of data");return e}function gu(r){let e=r.length,t=0,n,i=!1,o;for(;t<e;){let a,c;if([a,c,t]=yu(r,t),a!==2)throw new Error(`protobuf: (PBNode) invalid wireType, expected 2, got ${a}`);if(c===1){if(o)throw new Error("protobuf: (PBNode) duplicate Data section");[o,t]=ci(r,t),n&&(i=!0)}else if(c===2){if(i)throw new Error("protobuf: (PBNode) duplicate Links section");n||(n=[]);let f;[f,t]=ci(r,t),n.push(xp(f))}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 o&&(s.Data=o),s.Links=n||[],s}var bu=new TextEncoder,wu=2**32,Ep=2**31;function vp(r,e){let t=e.length;if(typeof r.Tsize=="number"){if(r.Tsize<0)throw new Error("Tsize cannot be negative");if(!Number.isSafeInteger(r.Tsize))throw new Error("Tsize too large for encoding");t=Cr(e,t,r.Tsize)-1,e[t]=24}if(typeof r.Name=="string"){let n=bu.encode(r.Name);t-=n.length,e.set(n,t),t=Cr(e,t,n.length)-1,e[t]=18}return r.Hash&&(t-=r.Hash.length,e.set(r.Hash,t),t=Cr(e,t,r.Hash.length)-1,e[t]=10),e.length-t}function xu(r){let e=kp(r),t=new Uint8Array(e),n=e;if(r.Data&&(n-=r.Data.length,t.set(r.Data,n),n=Cr(t,n,r.Data.length)-1,t[n]=10),r.Links)for(let i=r.Links.length-1;i>=0;i--){let o=vp(r.Links[i],t.subarray(0,n));n-=o,n=Cr(t,n,o)-1,t[n]=18}return t}function _p(r){let e=0;if(r.Hash){let t=r.Hash.length;e+=1+t+Rt(t)}if(typeof r.Name=="string"){let t=bu.encode(r.Name).length;e+=1+t+Rt(t)}return typeof r.Tsize=="number"&&(e+=1+Rt(r.Tsize)),e}function kp(r){let e=0;if(r.Data){let t=r.Data.length;e+=1+t+Rt(t)}if(r.Links)for(let t of r.Links){let n=_p(t);e+=1+n+Rt(n)}return e}function Cr(r,e,t){e-=Rt(t);let n=e;for(;t>=Ep;)r[e++]=t&127|128,t/=128;for(;t>=128;)r[e++]=t&127|128,t>>>=7;return r[e]=t,n}function Rt(r){return r%2===0&&r++,Math.floor((Ap(r)+6)/7)}function Ap(r){let e=0;return r>=wu&&(r=Math.floor(r/wu),e=32),r>=65536&&(r>>>=16,e+=16),r>=256&&(r>>>=8,e+=8),e+Sp[r]}var Sp=[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 Ip=["Data","Links"],Cp=["Hash","Name","Tsize"],ns=new TextEncoder;function vu(r,e){if(r===e)return 0;let t=r.Name?ns.encode(r.Name):[],n=e.Name?ns.encode(e.Name):[],i=t.length,o=n.length;for(let s=0,a=Math.min(i,o);s<a;++s)if(t[s]!==n[s]){i=t[s],o=n[s];break}return i<o?-1:o<i?1:0}function Eu(r,e){return!Object.keys(r).some(t=>!e.includes(t))}function _u(r){if(typeof r.asCID=="object"){let t=v.asCID(r);if(!t)throw new TypeError("Invalid DAG-PB form");return{Hash:t}}if(typeof r!="object"||Array.isArray(r))throw new TypeError("Invalid DAG-PB form");let e={};if(r.Hash){let t=v.asCID(r.Hash);try{t||(typeof r.Hash=="string"?t=v.parse(r.Hash):r.Hash instanceof Uint8Array&&(t=v.decode(r.Hash)))}catch(n){throw new TypeError(`Invalid DAG-PB form: ${n.message}`)}t&&(e.Hash=t)}if(!e.Hash)throw new TypeError("Invalid DAG-PB form");return typeof r.Name=="string"&&(e.Name=r.Name),typeof r.Tsize=="number"&&(e.Tsize=r.Tsize),e}function is(r){if((r instanceof Uint8Array||typeof r=="string")&&(r={Data:r}),typeof r!="object"||Array.isArray(r))throw new TypeError("Invalid DAG-PB form");let e={};if(r.Data!==void 0)if(typeof r.Data=="string")e.Data=ns.encode(r.Data);else if(r.Data instanceof Uint8Array)e.Data=r.Data;else throw new TypeError("Invalid DAG-PB form");if(r.Links!==void 0)if(Array.isArray(r.Links))e.Links=r.Links.map(_u),e.Links.sort(vu);else throw new TypeError("Invalid DAG-PB form");else e.Links=[];return e}function os(r){if(!r||typeof r!="object"||Array.isArray(r)||r instanceof Uint8Array||r["/"]&&r["/"]===r.bytes)throw new TypeError("Invalid DAG-PB form");if(!Eu(r,Ip))throw new TypeError("Invalid DAG-PB form (extraneous properties)");if(r.Data!==void 0&&!(r.Data instanceof Uint8Array))throw new TypeError("Invalid DAG-PB form (Data must be bytes)");if(!Array.isArray(r.Links))throw new TypeError("Invalid DAG-PB form (Links must be a list)");for(let e=0;e<r.Links.length;e++){let t=r.Links[e];if(!t||typeof t!="object"||Array.isArray(t)||t instanceof Uint8Array||t["/"]&&t["/"]===t.bytes)throw new TypeError("Invalid DAG-PB form (bad link)");if(!Eu(t,Cp))throw new TypeError("Invalid DAG-PB form (extraneous properties on link)");if(t.Hash===void 0)throw new TypeError("Invalid DAG-PB form (link must have a Hash)");if(t.Hash==null||!t.Hash["/"]||t.Hash["/"]!==t.Hash.bytes)throw new TypeError("Invalid DAG-PB form (link Hash must be a CID)");if(t.Name!==void 0&&typeof t.Name!="string")throw new TypeError("Invalid DAG-PB form (link Name must be a string)");if(t.Tsize!==void 0){if(typeof t.Tsize!="number"||t.Tsize%1!==0)throw new TypeError("Invalid DAG-PB form (link Tsize must be an integer)");if(t.Tsize<0)throw new TypeError("Invalid DAG-PB form (link Tsize cannot be negative)")}if(e>0&&vu(t,r.Links[e-1])===-1)throw new TypeError("Invalid DAG-PB form (links must be sorted by Name bytes)")}}function ku(r,e=[]){return is({Data:r,Links:e})}function Au(r,e,t){return _u({Hash:t,Name:r,Tsize:e})}function Su(r){return r instanceof ArrayBuffer?new Uint8Array(r,0,r.byteLength):r}var Tp="dag-pb",ss=112;function Lp(r){os(r);let e={};return r.Links&&(e.Links=r.Links.map(t=>{let n={};return t.Hash&&(n.Hash=t.Hash.bytes),t.Name!==void 0&&(n.Name=t.Name),t.Tsize!==void 0&&(n.Tsize=t.Tsize),n})),r.Data&&(e.Data=r.Data),xu(e)}function Dp(r){let e=Su(r),t=gu(e),n={};return t.Data&&(n.Data=t.Data),t.Links&&(n.Links=t.Links.map(i=>{let o={};try{o.Hash=v.decode(i.Hash)}catch{}if(!o.Hash)throw new Error("Invalid Hash field found in link, expected CID");return i.Name!==void 0&&(o.Name=i.Name),i.Tsize!==void 0&&(o.Tsize=i.Tsize),o})),n}function Je(r){return r?.then!=null}function Iu(r=[],e){let t={[ss]:as,[$t]:Ot,[Go]:Jo,[es]:ts,[Ri]:Pr};return r.forEach(n=>{t[n.code]=n}),async n=>{let i=t[n];if(i==null&&e!=null){let o=e(n);Je(o)?i=await o:i=o,t[i.code]=i}if(i!=null)return i;throw new On(`Could not load codec for ${n}`)}}function Cu(r=[],e){let t={};return r=[Zi(),to(),Zt(),...r],r.forEach(n=>{t[n.type]=n,t[n.code]=n}),async n=>{let i=t[n];if(i==null&&e!=null){let o=e(n);Je(o)?i=await o:i=o,t[i.type]=i,t[i.code]=i}if(i!=null)return i;throw new Kn(`Could not load crypto for ${i}`)}}function Tu(r=[],e){let t={[ze.code]:ze,[Br.code]:Br,[Ke.code]:Ke};return r.forEach(n=>{t[n.code]=n}),async n=>{let i=t[n];if(i==null&&e!=null){let o=e(n);Je(o)?i=await o:i=o,t[i.code]=i}if(i!=null)return i;throw new $n(`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 ui=0,Bt=class extends Error{static name="IdentityHashDigestTooLongError";name="IdentityHashDigestTooLongError"},li=class extends Be{child;maxDigestLength;constructor(e,t){super(),this.child=e,this.maxDigestLength=t?.maxDigestLength}put(e,t,n){if(e.multihash.code===ui){if(this.maxDigestLength!=null&&e.multihash.digest.byteLength>this.maxDigestLength)throw new Bt(`Identity digest too long - ${e.multihash.digest.byteLength} > this.maxDigestLength`);return n?.signal?.throwIfAborted(),e}return this.child==null?(n?.signal?.throwIfAborted(),e):this.child.put(e,t,n)}async*get(e,t){if(e.multihash.code===ui){if(this.maxDigestLength!=null&&e.multihash.digest.byteLength>this.maxDigestLength)throw new Bt(`Identity digest too long - ${e.multihash.digest.byteLength} > this.maxDigestLength`);t?.signal?.throwIfAborted(),yield e.multihash.digest;return}if(this.child==null)throw t?.signal?.throwIfAborted(),new le;yield*this.child.get(e,t)}has(e,t){if(e.multihash.code===ui){if(this.maxDigestLength!=null&&e.multihash.digest.byteLength>this.maxDigestLength)throw new Bt(`Identity digest too long - ${e.multihash.digest.byteLength} > this.maxDigestLength`);return t?.signal?.throwIfAborted(),!0}return this.child==null?(t?.signal?.throwIfAborted(),!1):this.child.has(e,t)}delete(e,t){if(e.code===ui){if(this.maxDigestLength!=null&&e.multihash.digest.byteLength>this.maxDigestLength)throw new Bt(`Identity digest too long - ${e.multihash.digest.byteLength} > this.maxDigestLength`);t?.signal?.throwIfAborted();return}if(this.child!=null)return this.child.delete(e,t)}async*getAll(e){this.child!=null&&(yield*this.child.getAll(e)),e?.signal?.throwIfAborted()}};function Pp(r){return r[Symbol.asyncIterator]!=null}function Lu(r){return r?.then!=null}function Np(r,e){let t=0;if(Pp(r))return(async function*(){for await(let c of r){let f=e(c,t++);Lu(f)&&await f,yield c}})();let n=cr(r),{value:i,done:o}=n.next();if(o===!0)return(function*(){})();let s=e(i,t++);if(typeof s?.then=="function")return(async function*(){await s,yield i;for(let c of n){let f=e(c,t++);Lu(f)&&await f,yield c}})();let a=e;return(function*(){yield i;for(let c of n)a(c,t++),yield c})()}var cs=Np;var Bp=128,Ft=class{child;getHasher;log;logger;blockBrokers;constructor(e,t={}){this.log=e.logger.forComponent("helia:networked-storage"),this.logger=e.logger,this.blockBrokers=e.blockBrokers,this.child=new li(e.blockstore,{maxDigestLength:t.maxIdentityHashDigestLength??Bp}),this.getHasher=e.getHasher}async put(e,t,n={}){return await this.child.has(e,n)?(n.onProgress?.(new x("blocks:put:duplicate",e)),e):(n.onProgress?.(new x("blocks:put:providers:notify",e)),await Promise.all(this.blockBrokers.map(async i=>i.announce?.(e,n))),n.onProgress?.(new x("blocks:put:blockstore:put",e)),this.child.put(e,t,n))}async*putMany(e,t={}){let n=re(e,async({cid:o})=>{let s=await this.child.has(o,t);return s&&t.onProgress?.(new x("blocks:put-many:duplicate",o)),!s}),i=cs(n,async({cid:o})=>{t.onProgress?.(new x("blocks:put-many:providers:notify",o)),await Promise.all(this.blockBrokers.map(async s=>s.announce?.(o,t)))});t.onProgress?.(new x("blocks:put-many:blockstore:put-many")),yield*this.child.putMany(i,t)}async*get(e,t={}){let n=await this.child.has(e,t),i=t.offline===!0;if(!n){if(i)throw new Er("The block was present in the blockstore and the node is running offline so cannot fetch it");let o=await this.getHasher(e.multihash.code);t?.signal?.throwIfAborted(),t.onProgress?.(new x("blocks:get:providers:get",e));let s=await Du(e,this.blockBrokers,o,{...t,log:this.log});t.onProgress?.(new x("blocks:get:blockstore:put",e)),await this.child.put(e,s,t),t.onProgress?.(new x("blocks:get:providers:notify",e)),await Promise.all(this.blockBrokers.map(async a=>a.announce?.(e,t))),yield s;return}t.onProgress?.(new x("blocks:get:blockstore:get",e)),yield*this.child.get(e,t)}async*getMany(e,t={}){t.onProgress?.(new x("blocks:get-many:blockstore:get-many")),yield*this.child.getMany(cs(e,async n=>{let i=await this.child.has(n,t),o=t.offline===!0;if(!i){if(o)throw new Er("The block was present in the blockstore and the node is running offline so cannot fetch it");let s=await this.getHasher(n.multihash.code);t?.signal?.throwIfAborted(),t.onProgress?.(new x("blocks:get-many:providers:get",n));let a=await Du(n,this.blockBrokers,s,{...t,log:this.log});t.onProgress?.(new x("blocks:get-many:blockstore:put",n)),await this.child.put(n,a,t),t.onProgress?.(new x("blocks:get-many:providers:notify",n)),await Promise.all(this.blockBrokers.map(async c=>c.announce?.(n,t)))}}))}async delete(e,t={}){t.onProgress?.(new x("blocks:delete:blockstore:delete",e)),await this.child.delete(e,t)}async*deleteMany(e,t={}){t.onProgress?.(new x("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 x("blocks:get-all:blockstore:get-many")),yield*this.child.getAll(e)}};async function Du(r,e,t,n){let i=Up(r,t),o=new AbortController,s=Se([o.signal,n.signal]);o.signal;let a=[];for(let c of e)Fp(c)&&a.push(c);if(a.length===0)throw new ot(`No block brokers capable of retrieving blocks are configured, the CID ${r} cannot be fetched from the network`);try{return await Promise.any(a.map(async c=>{try{let f=!1,l=await c.retrieve(r,{...n,signal:s,validateFn:async h=>{await i(h),n.signal?.throwIfAborted(),f=!0}});return f||(await i(l),n.signal?.throwIfAborted()),l}catch(f){throw n.log.error("could not retrieve verified block for %c from %s - %e",r,c.name,f),f}}))}catch(c){throw new Cn(c.errors,`Failed to load block for ${r}`)}finally{o.abort(),s.clear()}}function Fp(r){return typeof r.retrieve=="function"}var Up=(r,e)=>{if(e==null)throw new _t(`No hasher configured for multihash code 0x${r.multihash.code.toString(16)}, please configure one. You can look up which hash this is at https://github.com/multiformats/multicodec/blob/master/table.csv`);return async t=>{let n,i=e.digest(t,{truncate:r.multihash.digest.byteLength});if(Je(i)?n=await i:n=i,!Re(n.digest,r.multihash.digest))throw new en("Hash of downloaded block did not match multihash from passed CID")}};var fi=class extends Ft{closeController;constructor(e,t){super(e),this.closeController=new AbortController,this.closeController.signal,this.log=e.logger.forComponent(`helia:session-storage:${t.root}`)}close(){this.closeController.abort()}async addPeer(e,t){await Promise.all(this.blockBrokers.map(n=>n.addPeer(e,t)))}async put(e,t,n={}){let i=Se([this.closeController.signal,n.signal]);try{return await super.put(e,t,{...n,signal:i})}finally{i.clear()}}async*putMany(e,t={}){let n=Se([this.closeController.signal,t.signal]);try{yield*super.putMany(e,{...t,signal:n})}finally{n.clear()}}async*get(e,t={}){let n=Se([this.closeController.signal,t.signal]);try{yield*super.get(e,{...t,signal:n})}finally{n.clear()}}async*getMany(e,t={}){let n=Se([this.closeController.signal,t.signal]);try{yield*super.getMany(e,{...t,signal:n})}finally{n.clear()}}async delete(e,t={}){let n=Se([this.closeController.signal,t.signal]);try{await super.delete(e,{...t,signal:n})}finally{n.clear()}}async*deleteMany(e,t={}){let n=Se([this.closeController.signal,t.signal]);try{yield*super.deleteMany(e,{...t,signal:n})}finally{n.clear()}}async has(e,t={}){let n=Se([this.closeController.signal,t.signal]);try{return await super.has(e,{...t,signal:n})}finally{n.clear()}}async*getAll(e={}){let t=Se([this.closeController.signal,e.signal]);try{yield*super.getAll({...e,signal:t})}finally{t.clear()}}};var hi=class extends Ft{started;constructor(e,t={}){super(e,t),this.started=!1}isStarted(){return this.started}async start(){await qe(this.child,...this.blockBrokers),this.started=!0}async stop(){await je(this.child,...this.blockBrokers),this.started=!1}unwrap(){return this.child}createSession(e,t){if(this.blockBrokers.length===0)throw new ot("No block brokers configured");let n=this.blockBrokers.map(i=>i.createSession?.(t)).filter(i=>i!=null);if(n.length===0)throw new ot(`No configured block brokers support sessions - tried ${this.blockBrokers.map(i=>i.name).join(", ")}`);return new fi({blockstore:this.child,blockBrokers:n,getHasher:this.getHasher,logger:this.logger},{root:e})}};var di=class extends ue{initialPeerSearchComplete;requests;logName;log;logger;minProviders;maxProviders;providers;evictionFilter;initialProviders;cidPeerFilterSize;constructor(e,t){super(),this.logName=t.name,this.logger=e.logger,this.log=e.logger.forComponent(this.logName),this.requests=new Map,this.minProviders=t.minProviders??1,this.maxProviders=t.maxProviders??5,this.cidPeerFilterSize=t.cidPeerFilterSize??100,this.providers=[],this.evictionFilter=Ln(this.maxProviders),this.initialProviders=[...t.providers??[]]}async retrieve(e,t={}){let n=V.encode(e.multihash.bytes),i=this.requests.get(n);if(i!=null)return this.log("join existing request for %c",e),i.observers++,i.promise;let o=X(),s={promise:o.promise,observers:1,queryFilter:Ln(this.cidPeerFilterSize)};this.requests.set(n,s);let a=!1;this.initialPeerSearchComplete==null&&(a=!0,this.log=this.logger.forComponent(`${this.logName}:${e}`),this.initialPeerSearchComplete=this.findProviders(e,this.minProviders,t));let c=!1,f=new De({concurrency:this.maxProviders});f.addEventListener("failure",d=>{this.log.error("error querying provider %s, evicting from session - %e",d.detail.job.options.provider,d.detail.error),this.evict(d.detail.job.options.provider)}),f.addEventListener("success",d=>{c=!0,o.resolve(d.detail.result)}),f.addEventListener("idle",()=>{if(c){this.log.trace("session idle, found block");return}if(t.signal?.aborted===!0){this.log.trace("session idle, signal aborted");return}Promise.resolve().then(async()=>{this.log("no session peers had block for for %c, finding new providers",e);for(let d=0;d<this.minProviders&&this.providers.length!==0;d++){let g=this.providers[Math.floor(Math.random()*this.providers.length)];this.evict(g)}await this.findProviders(e,this.minProviders,t),this.log("found new providers re-retrieving %c",e),this.requests.delete(n),o.resolve(await this.retrieve(e,t))}).catch(d=>{this.log.error("could not find new providers for %c - %e",e,d),o.reject(d)})});let l=d=>{let g=this.toFilterKey(d.detail);s.queryFilter.has(g)||(s.queryFilter.add(g),this.emitFoundProviderProgressEvent(e,d.detail,t),f.add(async()=>this.queryProvider(e,d.detail,t),{provider:d.detail}).catch(w=>{t.signal?.aborted!==!0&&this.log.error("error retrieving session block for %c - %e",e,w)}))};if(this.addEventListener("provider",l),a)try{await Ve(this.initialPeerSearchComplete,t.signal),a&&this.log("found initial session peers for %c",e)}catch(d){throw a&&this.log("failed to find initial session peers for %c - %e",e,d),this.requests.delete(n),s.observers>1&&o.reject(d),d}Promise.all([...this.providers].filter(d=>{let g=this.toFilterKey(d),w=s.queryFilter.has(g);return w||s.queryFilter.add(this.toFilterKey(d)),!w}).map(async d=>f.add(async()=>this.queryProvider(e,d,t),{provider:d}))).catch(d=>{t.signal?.aborted!==!0&&this.log.error("error retrieving session block for %c - %e",e,d)});let h=()=>{o.reject(new xe(t.signal?.reason??"Session aborted")),f.abort()};t.signal?.addEventListener("abort",h);try{return await o.promise}finally{this.removeEventListener("provider",l),t.signal?.removeEventListener("abort",h),f.clear(),this.requests.delete(n)}}evict(e){this.evictionFilter.add(this.toFilterKey(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.toFilterKey(e))}hasProvider(e){return!!(this.providers.find(t=>this.equals(t,e))!=null||this.isEvicted(e))}async addPeer(e,t){let n=await this.convertToProvider(e,"manually-added",t);n==null||this.hasProvider(n)||(this.providers.push(n),this.safeDispatchEvent("provider",{detail:n}))}async findProviders(e,t,n){let i=X(),o=0;return Promise.resolve().then(async()=>{this.log("finding %d-%d new provider(s) for %c - %d initial providers",t,this.maxProviders,e,this.initialProviders.length);let s=this,a=async function*(){for(;s.initialProviders.length>0;){let f=s.initialProviders.pop();if(f==null)continue;let l=await s.convertToProvider(f,"manual",n);l!=null&&(yield l)}},c=async function*(){yield*a(),yield*s.findNewProviders(e,n)};for await(let f of c()){if(this.providers.length===this.maxProviders||n.signal?.aborted===!0)break;if(!this.hasProvider(f)&&(this.log("found %d providers, %d in session",o,this.providers.length),this.providers.push(f),this.safeDispatchEvent("provider",{detail:f}),o++,this.providers.length===t&&(this.log("session is ready with %d peer(s), new peers present",this.providers.length),i.resolve()),this.providers.length===this.maxProviders)){this.log("found max session peers %d",this.providers.length);break}}if(this.log("found %d new session peers while trying to find %d, %d in session",o,t,this.providers.length),this.providers.length<t)throw new Mn(`Found ${o} of ${t} ${this.name} providers for ${e}, ${this.providers.length} in session after evictions`)}).catch(s=>{this.log.error("error searching routing for potential session peers for %c - %e",e,s),i.reject(s)}),i.promise}};function Pu(r){return r==null?!1:v.asCID(r)!=null}var us=class{info;blockstore;datastore;events;pins;logger;routing;getCodec;getHasher;getCrypto;dns;keychain;metrics;status;log;blockBrokers;mixins;constructor(e){this.info={name:e.name,version:e.version},this.logger=e.logger??Ra(),this.log=this.logger.forComponent("helia"),this.getHasher=Tu(e.hashers,e.loadHasher),this.getCodec=Iu(e.codecs,e.loadCodec),this.getCrypto=Cu(e.cryptos,e.loadCrypto),this.dns=e.dns??Ta(),this.metrics=e.metrics,this.events=new ue,this.status="stopped",this.mixins=[];let t={blockstore:e.blockstore??new sr,datastore:e.datastore??new lr,logger:this.logger,blockBrokers:[],getHasher:this.getHasher,getCodec:this.getCodec,getCrypto:this.getCrypto,dns:this.dns,metrics:this.metrics,...e.components??{}};this.keychain=t.keychain=ba()(t),this.routing=t.routing=new zn(t,{routers:(e.routers??[]).flatMap(i=>(typeof i=="function"&&(i=i(t)),[i])),providerLookupConcurrency:e.providerLookupConcurrency}),this.blockBrokers=t.blockBrokers=(e.blockBrokers??[]).map(i=>(typeof i=="function"&&(i=i(t)),i));let n=new hi(t,e);this.pins=new Un(t.datastore,n,this.getCodec),this.blockstore=new si(n,this.pins,this.routing,{holdGcLock:e.holdGcLock??!0}),this.datastore=t.datastore}hasRouter(e){return this.routing.hasRouter(e)}addRouter(e){this.routing.addRouter(e)}hasBlockBroker(e){return this.blockBrokers.findIndex(t=>t.name===e)!==-1}addBlockBroker(e){this.blockBrokers.push(e)}addMixin(e){this.mixins.push(e)}async start(){this.status="starting",await lu(this.datastore),await qe(this.blockstore,this.datastore,this.routing,...this.blockBrokers);for(let e of this.mixins)await e.start?.(this);return this.status="started",this.events.dispatchEvent(new CustomEvent("start",{detail:this})),this}async stop(){this.status="stopping";for(let e of this.mixins)await e.stop?.(this);return await je(this.blockstore,this.datastore,this.routing,...this.blockBrokers),this.status="stopped",this.events.dispatchEvent(new CustomEvent("stop",{detail:this})),this}async gc(e={}){let t=await this.blockstore.lock.writeLock();try{let n=this,i=this.blockstore.unwrap();this.log("gc start"),await ur(i.deleteMany((async function*(){for await(let{cid:o}of i.getAll())try{if(await n.pins.isPinned(o,e))continue;yield o,e.onProgress?.(new x("helia:gc:deleted",o))}catch(s){n.log.error("error during gc - %e",s),e.onProgress?.(new x("helia:gc:error",s))}})()))}finally{t()}this.log("gc finished")}};return $u(Kp);})();
23
+ ${e}[Error list was empty]`,t.trim()}return Ua(r,e)}I.formatters.e=r=>r==null?"undefined":$a(r);function Dh(r){let e=()=>{};return e.enabled=!1,e.color="",e.diff=0,e.log=()=>{},e.namespace=r,e.destroy=()=>!0,e.extend=()=>e,e.useColors=()=>!1,e}function ar(r,e){let t=Dh(`${r}:trace`);return I.enabled(`${r}:trace`)&&I.names.map(n=>n.toString()).find(n=>n.includes(":trace"))!=null&&(t=I(`${r}:trace`,e)),Object.assign(I(r,e),{error:I(`${r}:error`,e),trace:t,newScope:n=>ar(`${r}:${n}`,e)})}function Ma(r){if(r!=null&&(r=r.trim(),r.length!==0))return r}function Ph(r){let[e,t]=r[Symbol.asyncIterator]!=null?[r[Symbol.asyncIterator](),Symbol.asyncIterator]:[r[Symbol.iterator](),Symbol.iterator],n=[];return{peek:()=>e.next(),push:i=>{n.push(i)},next:()=>n.length>0?{done:!1,value:n.shift()}:e.next(),[t](){return this}}}var cr=Ph;function Nh(r){return r[Symbol.asyncIterator]!=null}function Rh(r,e){let t=0;if(Nh(r))return(async function*(){for await(let c of r)await e(c,t++)&&(yield c)})();let n=cr(r),{value:i,done:o}=n.next();if(o===!0)return(function*(){})();let s=e(i,t++);if(typeof s.then=="function")return(async function*(){await s&&(yield i);for(let c of n)await e(c,t++)&&(yield c)})();let a=e;return(function*(){s===!0&&(yield i);for(let c of n)a(c,t++)&&(yield c)})()}var re=Rh;function X(){let r={};return r.promise=new Promise((e,t)=>{r.resolve=e,r.reject=t}),r}function Bh(r){return r.reason}async function Ve(r,e,t){if(e==null)return r;let n=t?.translateError??Bh;if(e.aborted)return r.catch(()=>{}),Promise.reject(n(e));let i;try{return await Promise.race([r,new Promise((o,s)=>{i=()=>{s(n(e))},e.addEventListener("abort",i)})])}finally{i!=null&&e.removeEventListener("abort",i)}}var yo=class{readNext;haveNext;ended;nextResult;error;constructor(){this.ended=!1,this.readNext=X(),this.haveNext=X()}[Symbol.asyncIterator](){return this}async next(){if(this.nextResult==null&&await this.haveNext.promise,this.nextResult==null)throw new Error("HaveNext promise resolved but nextResult was undefined");let e=this.nextResult;return this.nextResult=void 0,this.readNext.resolve(),this.readNext=X(),e}async throw(e){return this.ended=!0,this.error=e,e!=null&&(this.haveNext.promise.catch(()=>{}),this.haveNext.reject(e)),{done:!0,value:void 0}}async return(){let e={done:!0,value:void 0};return this.ended=!0,this.nextResult=e,this.haveNext.resolve(),e}async push(e,t){await this._push(e,t)}async end(e,t){e!=null?await this.throw(e):await this._push(void 0,t)}async _push(e,t){if(e!=null&&this.ended)throw this.error??new Error("Cannot push value onto an ended pushable");for(;this.nextResult!=null;)await this.readNext.promise;e!=null?this.nextResult={done:!1,value:e}:(this.ended=!0,this.nextResult={done:!0,value:void 0}),this.haveNext.resolve(),this.haveNext=X(),await Ve(this.readNext.promise,t?.signal,t)}};function Oa(){return new yo}function Fh(r){return r[Symbol.asyncIterator]!=null}async function Uh(r,e,t){try{await Promise.all(r.map(async n=>{for await(let i of n)await e.push(i,{signal:t}),t.throwIfAborted()})),await e.end(void 0,{signal:t})}catch(n){await e.end(n,{signal:t}).catch(()=>{})}}async function*Mh(r){let e=new AbortController,t=Oa();Uh(r,t,e.signal).catch(()=>{});try{yield*t}finally{e.abort()}}function*$h(r){for(let e of r)yield*e}function Oh(...r){let e=[];for(let t of r)Fh(t)||e.push(t);return e.length===r.length?$h(e):Mh(r)}var tt=Oh;var Eb=ar("blockstore:core:tiered");var Ka="SHARDING";function zh(r){return r[Symbol.asyncIterator]!=null}function qh(r){if(zh(r))return(async()=>{for await(let e of r);})();for(let e of r);}var ur=qh;function jh(r){return r[Symbol.asyncIterator]!=null}function Vh(r,e){return jh(r)?(async function*(){yield*(await or(r)).sort(e)})():(function*(){yield*or(r).sort(e)})()}var cn=Vh;function Hh(r){return r[Symbol.asyncIterator]!=null}function Wh(r,e){return Hh(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 un=Wh;var Fe=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:i}of e)await this.put(n,i,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,i){e.push({key:n,value:i})},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 i=e.prefix;n=re(n,o=>o.key.toString().startsWith(i))}if(Array.isArray(e.filters)&&(n=e.filters.reduce((i,o)=>re(i,o),n)),Array.isArray(e.orders)&&(n=e.orders.reduce((i,o)=>cn(i,o),n)),e.offset!=null){let i=0,o=e.offset;n=re(n,()=>i++>=o)}return e.limit!=null&&(n=un(n,e.limit)),n}queryKeys(e,t){let n=this._allKeys(e,t);if(e.prefix!=null){let i=e.prefix;n=re(n,o=>o.toString().startsWith(i))}if(Array.isArray(e.filters)&&(n=e.filters.reduce((i,o)=>re(i,o),n)),Array.isArray(e.orders)&&(n=e.orders.reduce((i,o)=>cn(i,o),n)),e.offset!=null){let i=e.offset,o=0;n=re(n,()=>o++>=i)}return e.limit!=null&&(n=un(n,e.limit)),n}};var lr=class extends Fe{data;constructor(){super(),this.data=new Map}put(e,t,n){return n?.signal?.throwIfAborted(),this.data.set(e.toString(),t),e}get(e,t){t?.signal?.throwIfAborted();let n=this.data.get(e.toString());if(n==null)throw new fe;return n}has(e,t){return t?.signal?.throwIfAborted(),this.data.has(e.toString())}delete(e,t){t?.signal?.throwIfAborted(),this.data.delete(e.toString())}*_all(e,t){t?.signal?.throwIfAborted();for(let[n,i]of this.data.entries())yield{key:new B(n),value:i},t?.signal?.throwIfAborted()}*_allKeys(e,t){t?.signal?.throwIfAborted();for(let n of this.data.keys())yield new B(n),t?.signal?.throwIfAborted()}};var ln=class{buffer;mask;top;btm;next;constructor(e){if(!(e>0)||(e-1&e)!==0)throw new Error("Max size for a FixedFIFO should be a power of two");this.buffer=new Array(e),this.mask=e-1,this.top=0,this.btm=0,this.next=null}push(e){return this.buffer[this.top]!==void 0?!1:(this.buffer[this.top]=e,this.top=this.top+1&this.mask,!0)}shift(){let e=this.buffer[this.btm];if(e!==void 0)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,e}isEmpty(){return this.buffer[this.btm]===void 0}},At=class{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new ln(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 ln(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 go=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}};function fr(r={}){return Gh(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 Gh(r,e){e=e??{};let t=e.onEnd,n=new At,i,o,s,a=X(),c=async()=>{try{return n.isEmpty()?s?{done:!0}:await new Promise((E,_)=>{o=T=>{o=null,n.push(T);try{E(r(n))}catch(D){_(D)}return i}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=X()})}},f=E=>o!=null?o(E):(n.push(E),i),l=E=>(n=new At,o!=null?o({error:E}):(n.push({error:E}),i)),h=E=>{if(s)return i;if(e?.objectMode!==!0&&E?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return f({done:!1,value:E})},d=E=>s?i:(s=!0,E!=null?l(E):f({done:!0})),g=()=>(n=new At,d(),{done:!0}),w=E=>(d(E),{done:!0});if(i={[Symbol.asyncIterator](){return this},next:c,return:g,throw:w,push:h,end:d,get readableLength(){return n.size},onEmpty:async E=>{let _=E?.signal;if(_?.throwIfAborted(),n.isEmpty())return;let T,D;_!=null&&(T=new Promise((z,M)=>{D=()=>{M(new go)},_.addEventListener("abort",D)}));try{await Promise.race([a.promise,T])}finally{D!=null&&_!=null&&_?.removeEventListener("abort",D)}}},t==null)return i;let A=i;return i={[Symbol.asyncIterator](){return this},next(){return A.next()},throw(E){return A.throw(E),t!=null&&(t(E),t=void 0),{done:!0}},return(){return A.return(),t!=null&&(t(),t=void 0),{done:!0}},push:h,end(E){return A.end(E),t!=null&&(t(E),t=void 0),i},get readableLength(){return A.readableLength},onEmpty:E=>A.onEmpty(E)},i}var d0=new B(Ka);var I0=ar("datastore:core:tiered");var wo={32:16777619n,64:1099511628211n,128:309485009821345068724781371n,256:374144419156711147060143317175368453031918731002211n,512:35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759n,1024:5016456510113118655434598811035278955030765345404790744303017523831112055108147451509157692220295382716162651878526895249385292291816524375083746691371804094271873160484737966720260389217684476157468082573n},qa={32:2166136261n,64:14695981039346656037n,128:144066263297769815596495629667062367629n,256:100029257958052580907070968620625704837092796014241193945225284501741471925557n,512:9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785n,1024:14197795064947621068722070641403218320880622795441933960878474914617582723252296732303717722150864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915n},ja=new globalThis.TextEncoder;function Qh(r,e){let t=wo[e],n=qa[e];for(let i=0;i<r.length;i++)n^=BigInt(r[i]),n=BigInt.asUintN(e,n*t);return n}function Yh(r,e,t){if(t.length===0)throw new Error("The `utf8Buffer` option must have a length greater than zero");let n=wo[e],i=qa[e],o=r;for(;o.length>0;){let s=ja.encodeInto(o,t);o=o.slice(s.read);for(let a=0;a<s.written;a++)i^=BigInt(t[a]),i=BigInt.asUintN(e,i*n)}return i}function bo(r,{size:e=32,utf8Buffer:t}={}){if(!wo[e])throw new Error("The `size` option must be one of 32, 64, 128, 256, 512, or 1024");if(typeof r=="string"){if(t)return Yh(r,e,t);r=ja.encode(r)}return Qh(r,e)}var hr={hash:r=>Number(bo(r,{size:32})),hashV:(r,e)=>Xh(hr.hash(r,e))};function Xh(r){let e=r.toString(16);return e.length%2===1&&(e=`0${e}`),L(e,"base16")}var xo=64,_e=class{fp;h;seed;constructor(e,t,n,i=2){if(i>xo)throw new TypeError("Invalid Fingerprint Size");let o=t.hashV(e,n),s=me(i);for(let a=0;a<s.length;a++)s[a]=o[a];s.length===0&&(s[0]=7),this.fp=s,this.h=t,this.seed=n}hash(){return this.h.hash(this.fp,this.seed)}equals(e){return e?.fp instanceof Uint8Array?Re(this.fp,e.fp):!1}};function rt(r,e){return Math.floor(Math.random()*(e-r))+r}var nt=class{contents;constructor(e){this.contents=new Array(e).fill(null)}has(e){if(!(e instanceof _e))throw new TypeError("Invalid Fingerprint");return this.contents.some(t=>e.equals(t))}add(e){if(!(e instanceof _e))throw new TypeError("Invalid Fingerprint");for(let t=0;t<this.contents.length;t++)if(this.contents[t]==null)return this.contents[t]=e,!0;return!0}swap(e){if(!(e instanceof _e))throw new TypeError("Invalid Fingerprint");let t=rt(0,this.contents.length-1),n=this.contents[t];return this.contents[t]=e,n}remove(e){if(!(e instanceof _e))throw new TypeError("Invalid Fingerprint");let t=this.contents.findIndex(n=>e.equals(n));return t>-1?(this.contents[t]=null,!0):!1}};var Zh=500,dr=class{bucketSize;filterSize;fingerprintSize;buckets;count;hash;seed;constructor(e){this.filterSize=e.filterSize,this.bucketSize=e.bucketSize??4,this.fingerprintSize=e.fingerprintSize??2,this.count=0,this.buckets=[],this.hash=e.hash??hr,this.seed=e.seed??rt(0,Math.pow(2,10))}add(e){typeof e=="string"&&(e=L(e));let t=new _e(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,i=(n^t.hash())%this.filterSize;if(this.buckets[n]==null&&(this.buckets[n]=new nt(this.bucketSize)),this.buckets[i]==null&&(this.buckets[i]=new nt(this.bucketSize)),this.buckets[n].add(t)||this.buckets[i].add(t))return this.count++,!0;let o=[n,i],s=o[rt(0,o.length-1)];this.buckets[s]==null&&(this.buckets[s]=new nt(this.bucketSize));for(let a=0;a<Zh;a++){let c=this.buckets[s].swap(t);if(c!=null&&(s=(s^c.hash())%this.filterSize,this.buckets[s]==null&&(this.buckets[s]=new nt(this.bucketSize)),this.buckets[s].add(c)))return this.count++,!0}return!1}has(e){typeof e=="string"&&(e=L(e));let t=new _e(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,i=this.buckets[n]?.has(t)??!1;if(i)return i;let o=(n^t.hash())%this.filterSize;return this.buckets[o]?.has(t)??!1}remove(e){typeof e=="string"&&(e=L(e));let t=new _e(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,i=this.buckets[n]?.remove(t)??!1;if(i)return this.count--,i;let o=(n^t.hash())%this.filterSize,s=this.buckets[o]?.remove(t)??!1;return s&&this.count--,s}get reliable(){return Math.floor(100*(this.count/this.filterSize))<=90}},ed={1:.5,2:.84,4:.95,8:.98};function td(r=.001){return r>.002?2:r>1e-5?4:8}function Va(r,e=.001){let t=td(e),n=ed[t],i=Math.round(r/n),o=Math.min(Math.ceil(Math.log2(1/e)+Math.log2(2*t)),xo);return{filterSize:i,bucketSize:t,fingerprintSize:o}}var fn=class{filterSize;bucketSize;fingerprintSize;scale;filterSeries;hash;seed;constructor(e){this.bucketSize=e.bucketSize??4,this.filterSize=e.filterSize??(1<<18)/this.bucketSize,this.fingerprintSize=e.fingerprintSize??2,this.scale=e.scale??2,this.hash=e.hash??hr,this.seed=e.seed??rt(0,Math.pow(2,10)),this.filterSeries=[new dr({filterSize:this.filterSize,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed})]}add(e){if(typeof e=="string"&&(e=L(e)),this.has(e))return!0;let t=this.filterSeries.find(n=>n.reliable);if(t==null){let n=this.filterSize*Math.pow(this.scale,this.filterSeries.length);t=new dr({filterSize:n,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed}),this.filterSeries.push(t)}return t.add(e)}has(e){typeof e=="string"&&(e=L(e));for(let t=0;t<this.filterSeries.length;t++)if(this.filterSeries[t].has(e))return!0;return!1}remove(e){typeof e=="string"&&(e=L(e));for(let t=0;t<this.filterSeries.length;t++)if(this.filterSeries[t].remove(e))return!0;return!1}get count(){return this.filterSeries.reduce((e,t)=>e+t.count,0)}};function hn(r,e=.001,t){return new fn({...Va(r,e),...t??{}})}var rd=r=>{let e=r.addEventListener||r.on||r.addListener,t=r.removeEventListener||r.off||r.removeListener;if(!e||!t)throw new TypeError("Emitter is not compatible");return{addListener:e.bind(r),removeListener:t.bind(r)}};function nd(r,e,t){let n,i=new Promise((o,s)=>{if(t={rejectionEvents:["error"],multiArgs:!1,rejectionMultiArgs:!1,resolveImmediately:!1,...t},!(t.count>=0&&(t.count===Number.POSITIVE_INFINITY||Number.isInteger(t.count))))throw new TypeError("The `count` option should be at least 0 or more");t.signal?.throwIfAborted();let a=[e].flat(),c=[],{addListener:f,removeListener:l}=rd(r),h=async(...g)=>{let w=t.multiArgs?g:g[0];if(t.filter)try{if(!await t.filter(w))return}catch(A){n(),s(A);return}c.push(w),t.count===c.length&&(n(),o(c))},d=(...g)=>{n(),s(t.rejectionMultiArgs?g:g[0])};n=()=>{for(let g of a)l(g,h);for(let g of t.rejectionEvents)a.includes(g)||l(g,d)};for(let g of a)f(g,h);for(let g of t.rejectionEvents)a.includes(g)||f(g,d);t.signal&&t.signal.addEventListener("abort",()=>{d(t.signal.reason)},{once:!0}),t.resolveImmediately&&o(c)});if(i.cancel=n,typeof t.timeout=="number"){let o=nr(i,{milliseconds:t.timeout});return o.cancel=()=>{n(),o.clear()},o}return i}function dn(r,e,t){typeof t=="function"&&(t={filter:t}),t={...t,count:1,resolveImmediately:!1};let n=nd(r,e,t),i=n.then(o=>o[0]);return i.cancel=n.cancel,i}function Eo(r,e){let t,n=function(){let i=function(){t=void 0,r()};clearTimeout(t),t=setTimeout(i,e)};return n.start=()=>{},n.stop=()=>{clearTimeout(t)},n}var pn=class extends Error{static name="QueueFullError";constructor(e="The queue was full"){super(e),this.name="QueueFullError"}};var mn=class{deferred;signal;onProgress;constructor(e){this.signal=e?.signal,this.onProgress=e?.onProgress,this.deferred=X(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new Ee)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function id(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var yn=class{id;fn;options;recipients;status;timeline;controller;dispatchingProgress;constructor(e,t){this.id=id(),this.status="queued",this.fn=e,this.options=t,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,this.controller.signal,this.dispatchingProgress=!1,this.onAbort=this.onAbort.bind(this)}abort(e){this.controller.abort(e)}onAbort(){this.recipients.reduce((t,n)=>t&&n.signal?.aborted===!0,!0)&&(this.controller.abort(new Ee),this.cleanup())}async join(e){let t=new mn(e);return this.recipients.push(t),e?.signal?.addEventListener("abort",this.onAbort),t.deferred.promise}async run(){this.status="running",this.timeline.started=Date.now();try{this.controller.signal.throwIfAborted();let e=await Ve(this.fn({...this.options??{},signal:this.controller.signal,onProgress:t=>{if(!this.dispatchingProgress){this.dispatchingProgress=!0;try{this.recipients.forEach(n=>{n.onProgress?.(t)})}finally{this.dispatchingProgress=!1}}}}),this.controller.signal);this.recipients.forEach(t=>{t.deferred.resolve(e)}),this.status="complete"}catch(e){this.recipients.forEach(t=>{t.deferred.reject(e)}),this.status="errored"}finally{this.timeline.finished=Date.now(),this.cleanup()}}cleanup(){this.recipients.forEach(e=>{e.cleanup(),e.signal?.removeEventListener("abort",this.onAbort)})}};var ne=class extends le{concurrency;maxSize;queue;pending;sort;paused;constructor(e={}){super(),this.concurrency=e.concurrency??Number.POSITIVE_INFINITY,this.maxSize=e.maxSize??Number.POSITIVE_INFINITY,this.pending=0,this.paused=!1,e.metricName!=null&&e.metrics?.registerMetricGroup(e.metricName,{calculate:()=>({size:this.queue.length,running:this.pending,queued:this.queue.length-this.pending})}),this.sort=e.sort,this.queue=[],this.emitEmpty=Eo(this.emitEmpty.bind(this),1),this.emitIdle=Eo(this.emitIdle.bind(this),1)}emitEmpty(){this.size===0&&this.safeDispatchEvent("empty")}emitIdle(){this.running===0&&this.safeDispatchEvent("idle")}pause(){this.paused=!0}resume(){this.paused&&(this.paused=!1,this.tryToStartAnother())}tryToStartAnother(){if(this.paused)return!1;if(this.size===0)return this.emitEmpty(),this.running===0&&this.emitIdle(),!1;if(this.pending<this.concurrency){let e;for(let t of this.queue)if(t.status==="queued"){e=t;break}return e==null?!1:(this.safeDispatchEvent("active"),this.pending++,e.run().finally(()=>{for(let t=0;t<this.queue.length;t++)if(this.queue[t]===e){this.queue.splice(t,1);break}this.pending--,this.tryToStartAnother(),this.safeDispatchEvent("next")}),!0)}return!1}enqueue(e){this.queue.push(e),this.sort!=null&&this.queue.sort(this.sort)}async add(e,t){if(t?.signal?.throwIfAborted(),this.size===this.maxSize)throw new pn;let n=new yn(e,t);this.enqueue(n),this.safeDispatchEvent("add");let i=n.join(t).then(o=>(this.safeDispatchEvent("completed",{detail:o}),this.safeDispatchEvent("success",{detail:{job:n,result:o}}),o)).catch(o=>{if(n.status==="queued"){for(let s=0;s<this.queue.length;s++)if(this.queue[s]===n){this.queue.splice(s,1);break}}throw this.safeDispatchEvent("failure",{detail:{job:n,error:o}}),o});return this.tryToStartAnother(),i}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(e=>{e.abort(new Ee)}),this.clear()}async onEmpty(e){this.size!==0&&await dn(this,"empty",e)}async onSizeLessThan(e,t){this.size<e||await dn(this,"next",{...t,filter:()=>this.size<e})}async onIdle(e){this.pending===0&&this.size===0||await dn(this,"idle",e)}get size(){return this.queue.length}get queued(){return this.queue.length-this.pending}get running(){return this.pending}async*toGenerator(e){e?.signal?.throwIfAborted();let t=fr({objectMode:!0}),n=c=>{c!=null?this.abort():this.clear(),t.end(c)},i=c=>{c.detail!=null&&t.push(c.detail)},o=c=>{n(c.detail.error)},s=()=>{n()},a=()=>{n(new Ee("Queue aborted"))};this.addEventListener("completed",i),this.addEventListener("failure",o),this.addEventListener("idle",s),e?.signal?.addEventListener("abort",a);try{yield*t}finally{this.removeEventListener("completed",i),this.removeEventListener("failure",o),this.removeEventListener("idle",s),e?.signal?.removeEventListener("abort",a),n()}}};function ke(r){let e=new globalThis.AbortController;function t(){let o=r.filter(s=>s?.aborted===!0).map(s=>s?.reason).pop();e.abort(o);for(let s of r)s?.removeEventListener!=null&&s.removeEventListener("abort",t)}for(let o of r){if(o?.aborted===!0){t();break}o?.addEventListener!=null&&o.addEventListener("abort",t)}function n(){for(let o of r)o?.removeEventListener!=null&&o.removeEventListener("abort",t)}let i=e.signal;return i.clear=n,i}var od=["Object","RegExp","Date","Error","Map","Set","WeakMap","WeakSet","ArrayBuffer","SharedArrayBuffer","DataView","Promise","URL","HTMLElement","Int8Array","Uint8ClampedArray","Int16Array","Uint16Array","Int32Array","Uint32Array","Float32Array","Float64Array","BigInt64Array","BigUint64Array","Tagged"];function vo(r){if(r===null)return"null";if(r===void 0)return"undefined";if(r===!0||r===!1)return"boolean";let e=typeof r;if(e==="string"||e==="number"||e==="bigint"||e==="symbol")return e;if(e==="function")return"Function";if(Array.isArray(r))return"Array";if(r instanceof Uint8Array)return"Uint8Array";if(r.constructor===Object)return"Object";let t=sd(r);return t||"Object"}function sd(r){let e=Object.prototype.toString.call(r).slice(8,-1);if(od.includes(e))return e}var u=class{constructor(e,t,n){this.major=e,this.majorEncoded=e<<5,this.name=t,this.terminal=n}toString(){return`Type[${this.major}].${this.name}`}compare(e){return this.major<e.major?-1:this.major>e.major?1:0}static equals(e,t){return e===t||e.major===t.major&&e.name===t.name}};u.uint=new u(0,"uint",!0);u.negint=new u(1,"negint",!0);u.bytes=new u(2,"bytes",!0);u.string=new u(3,"string",!0);u.array=new u(4,"array",!1);u.map=new u(5,"map",!1);u.tag=new u(6,"tag",!1);u.float=new u(7,"float",!0);u.false=new u(7,"false",!0);u.true=new u(7,"true",!0);u.null=new u(7,"null",!0);u.undefined=new u(7,"undefined",!0);u.break=new u(7,"break",!0);var p=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 pr=globalThis.process&&!globalThis.process.browser&&globalThis.Buffer&&typeof globalThis.Buffer.isBuffer=="function",ad=new TextEncoder;function gn(r){return pr&&globalThis.Buffer.isBuffer(r)}function it(r){return r instanceof Uint8Array?gn(r)?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):r:Uint8Array.from(r)}var cd=24,ud=200,St=pr?r=>r.length>=cd?globalThis.Buffer.from(r):Ha(r):r=>r.length>=ud?ad.encode(r):Ha(r),Te=r=>Uint8Array.from(r),Ga=pr?(r,e,t)=>gn(r)?new Uint8Array(r.subarray(e,t)):r.slice(e,t):(r,e,t)=>r.slice(e,t),Ja=pr?(r,e)=>(r=r.map(t=>t instanceof Uint8Array?t:globalThis.Buffer.from(t)),it(globalThis.Buffer.concat(r,e))):(r,e)=>{let t=new Uint8Array(e),n=0;for(let i of r)n+i.length>t.length&&(i=i.subarray(0,t.length-n)),t.set(i,n),n+=i.length;return t},Qa=pr?r=>globalThis.Buffer.allocUnsafe(r):r=>new Uint8Array(r);function wn(r,e){if(gn(r)&&gn(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 Ha(r){let e=[],t=0;for(let n=0;n<r.length;n++){let i=r.charCodeAt(n);i<128?e[t++]=i:i<2048?(e[t++]=i>>6|192,e[t++]=i&63|128):(i&64512)===55296&&n+1<r.length&&(r.charCodeAt(n+1)&64512)===56320?(i=65536+((i&1023)<<10)+(r.charCodeAt(++n)&1023),e[t++]=i>>18|240,e[t++]=i>>12&63|128,e[t++]=i>>6&63|128,e[t++]=i&63|128):(i>=55296&&i<=57343&&(i=65533),e[t++]=i>>12|224,e[t++]=i>>6&63|128,e[t++]=i&63|128)}return e}var Wa=4096;function Ya(r){let e=r.length;if(e<=Wa)return String.fromCharCode.apply(String,r);let t="",n=0;for(;n<e;)t+=String.fromCharCode.apply(String,r.slice(n,n+=Wa));return t}var ld=256,mr=class{constructor(e=ld){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 i=t.length-(this.maxCursor-this.cursor)-1;t.set(e,i)}else{if(t){let i=t.length-(this.maxCursor-this.cursor)-1;i<t.length&&(this.chunks[this.chunks.length-1]=t.subarray(0,i),this.maxCursor=this.cursor-1)}e.length<64&&e.length<this.chunkSize?(t=Qa(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=Ga(n,0,this.cursor)}else t=Ja(this.chunks,this.cursor);return e&&this.reset(),t}},bn=class{constructor(e){this.dest=e,this.cursor=0,this.chunks=[e]}reset(){this.cursor=0}push(e){if(this.cursor+e.length>this.dest.length)throw new Error("write out of bounds, destination buffer is too small");this.dest.set(e,this.cursor),this.cursor+=e.length}toBytes(e=!1){let t=this.dest.subarray(0,this.cursor);return e&&this.reset(),t}};var y="CBOR decode error:",Le="CBOR encode error:",yr=[];yr[23]=1;yr[24]=2;yr[25]=3;yr[26]=5;yr[27]=9;function Ue(r,e,t){if(r.length-e<t)throw new Error(`${y} not enough data for type`)}var U=[24,256,65536,4294967296,BigInt("18446744073709551616")];function ie(r,e,t){Ue(r,e,1);let n=r[e];if(t.strict===!0&&n<U[0])throw new Error(`${y} integer encoded in more bytes than necessary (strict decode)`);return n}function oe(r,e,t){Ue(r,e,2);let n=r[e]<<8|r[e+1];if(t.strict===!0&&n<U[1])throw new Error(`${y} integer encoded in more bytes than necessary (strict decode)`);return n}function se(r,e,t){Ue(r,e,4);let n=r[e]*16777216+(r[e+1]<<16)+(r[e+2]<<8)+r[e+3];if(t.strict===!0&&n<U[2])throw new Error(`${y} integer encoded in more bytes than necessary (strict decode)`);return n}function ae(r,e,t){Ue(r,e,8);let n=r[e]*16777216+(r[e+1]<<16)+(r[e+2]<<8)+r[e+3],i=r[e+4]*16777216+(r[e+5]<<16)+(r[e+6]<<8)+r[e+7],o=(BigInt(n)<<BigInt(32))+BigInt(i);if(t.strict===!0&&o<U[3])throw new Error(`${y} integer encoded in more bytes than necessary (strict decode)`);if(o<=Number.MAX_SAFE_INTEGER)return Number(o);if(t.allowBigInt===!0)return o;throw new Error(`${y} integers outside of the safe integer range are not supported`)}function Xa(r,e,t,n){return new p(u.uint,ie(r,e+1,n),2)}function Za(r,e,t,n){return new p(u.uint,oe(r,e+1,n),3)}function ec(r,e,t,n){return new p(u.uint,se(r,e+1,n),5)}function tc(r,e,t,n){return new p(u.uint,ae(r,e+1,n),9)}function he(r,e){return C(r,0,e.value)}function C(r,e,t){if(t<U[0]){let n=Number(t);r.push([e|n])}else if(t<U[1]){let n=Number(t);r.push([e|24,n])}else if(t<U[2]){let n=Number(t);r.push([e|25,n>>>8,n&255])}else if(t<U[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<U[4]){let i=[e|27,0,0,0,0,0,0,0],o=Number(n&BigInt(4294967295)),s=Number(n>>BigInt(32)&BigInt(4294967295));i[8]=o&255,o=o>>8,i[7]=o&255,o=o>>8,i[6]=o&255,o=o>>8,i[5]=o&255,i[4]=s&255,s=s>>8,i[3]=s&255,s=s>>8,i[2]=s&255,s=s>>8,i[1]=s&255,r.push(i)}else throw new Error(`${y} encountered BigInt larger than allowable range`)}}he.encodedSize=function(e){return C.encodedSize(e.value)};C.encodedSize=function(e){return e<U[0]?1:e<U[1]?2:e<U[2]?3:e<U[3]?5:9};he.compareTokens=function(e,t){return e.value<t.value?-1:e.value>t.value?1:0};function rc(r,e,t,n){return new p(u.negint,-1-ie(r,e+1,n),2)}function nc(r,e,t,n){return new p(u.negint,-1-oe(r,e+1,n),3)}function ic(r,e,t,n){return new p(u.negint,-1-se(r,e+1,n),5)}var _o=BigInt(-1),oc=BigInt(1);function sc(r,e,t,n){let i=ae(r,e+1,n);if(typeof i!="bigint"){let o=-1-i;if(o>=Number.MIN_SAFE_INTEGER)return new p(u.negint,o,9)}if(n.allowBigInt!==!0)throw new Error(`${y} integers outside of the safe integer range are not supported`);return new p(u.negint,_o-BigInt(i),9)}function xn(r,e){let t=e.value,n=typeof t=="bigint"?t*_o-oc:t*-1-1;C(r,e.type.majorEncoded,n)}xn.encodedSize=function(e){let t=e.value,n=typeof t=="bigint"?t*_o-oc:t*-1-1;return n<U[0]?1:n<U[1]?2:n<U[2]?3:n<U[3]?5:9};xn.compareTokens=function(e,t){return e.value<t.value?1:e.value>t.value?-1:0};function gr(r,e,t,n){Ue(r,e,t+n);let i=r.slice(e+t,e+t+n);return new p(u.bytes,i,t+n)}function ac(r,e,t,n){return gr(r,e,1,t)}function cc(r,e,t,n){return gr(r,e,2,ie(r,e+1,n))}function uc(r,e,t,n){return gr(r,e,3,oe(r,e+1,n))}function lc(r,e,t,n){return gr(r,e,5,se(r,e+1,n))}function fc(r,e,t,n){let i=ae(r,e+1,n);if(typeof i=="bigint")throw new Error(`${y} 64-bit integer bytes lengths not supported`);return gr(r,e,9,i)}function En(r){return r.encodedBytes===void 0&&(r.encodedBytes=u.equals(r.type,u.string)?St(r.value):r.value),r.encodedBytes}function It(r,e){let t=En(e);C(r,e.type.majorEncoded,t.length),r.push(t)}It.encodedSize=function(e){let t=En(e);return C.encodedSize(t.length)+t.length};It.compareTokens=function(e,t){return hd(En(e),En(t))};function hd(r,e){return r.length<e.length?-1:r.length>e.length?1:wn(r,e)}var hc=new TextDecoder,pd=32;function md(r,e,t){if(t-e<pd){let i="";for(let o=e;o<t;o++){let s=r[o];if(s&128)return hc.decode(r.subarray(e,t));i+=String.fromCharCode(s)}return i}return hc.decode(r.subarray(e,t))}function wr(r,e,t,n,i){let o=t+n;Ue(r,e,o);let s=new p(u.string,md(r,e+t,e+o),o);return i.retainStringBytes===!0&&(s.byteValue=r.slice(e+t,e+o)),s}function dc(r,e,t,n){return wr(r,e,1,t,n)}function pc(r,e,t,n){return wr(r,e,2,ie(r,e+1,n),n)}function mc(r,e,t,n){return wr(r,e,3,oe(r,e+1,n),n)}function yc(r,e,t,n){return wr(r,e,5,se(r,e+1,n),n)}function gc(r,e,t,n){let i=ae(r,e+1,n);if(typeof i=="bigint")throw new Error(`${y} 64-bit integer string lengths not supported`);return wr(r,e,9,i,n)}var wc=It;function Ct(r,e,t,n){return new p(u.array,n,t)}function bc(r,e,t,n){return Ct(r,e,1,t)}function xc(r,e,t,n){return Ct(r,e,2,ie(r,e+1,n))}function Ec(r,e,t,n){return Ct(r,e,3,oe(r,e+1,n))}function vc(r,e,t,n){return Ct(r,e,5,se(r,e+1,n))}function _c(r,e,t,n){let i=ae(r,e+1,n);if(typeof i=="bigint")throw new Error(`${y} 64-bit integer array lengths not supported`);return Ct(r,e,9,i)}function kc(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${y} indefinite length items not allowed`);return Ct(r,e,1,1/0)}function vn(r,e){C(r,u.array.majorEncoded,e.value)}vn.compareTokens=he.compareTokens;vn.encodedSize=function(e){return C.encodedSize(e.value)};function Tt(r,e,t,n){return new p(u.map,n,t)}function Ac(r,e,t,n){return Tt(r,e,1,t)}function Sc(r,e,t,n){return Tt(r,e,2,ie(r,e+1,n))}function Ic(r,e,t,n){return Tt(r,e,3,oe(r,e+1,n))}function Cc(r,e,t,n){return Tt(r,e,5,se(r,e+1,n))}function Tc(r,e,t,n){let i=ae(r,e+1,n);if(typeof i=="bigint")throw new Error(`${y} 64-bit integer map lengths not supported`);return Tt(r,e,9,i)}function Lc(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${y} indefinite length items not allowed`);return Tt(r,e,1,1/0)}function _n(r,e){C(r,u.map.majorEncoded,e.value)}_n.compareTokens=he.compareTokens;_n.encodedSize=function(e){return C.encodedSize(e.value)};function Dc(r,e,t,n){return new p(u.tag,t,1)}function Pc(r,e,t,n){return new p(u.tag,ie(r,e+1,n),2)}function Nc(r,e,t,n){return new p(u.tag,oe(r,e+1,n),3)}function Rc(r,e,t,n){return new p(u.tag,se(r,e+1,n),5)}function Bc(r,e,t,n){return new p(u.tag,ae(r,e+1,n),9)}function kn(r,e){C(r,u.tag.majorEncoded,e.value)}kn.compareTokens=he.compareTokens;kn.encodedSize=function(e){return C.encodedSize(e.value)};var ko=20,Ao=21,So=22,Io=23;function Fc(r,e,t,n){if(n.allowUndefined===!1)throw new Error(`${y} undefined values are not supported`);return n.coerceUndefinedToNull===!0?new p(u.null,null,1):new p(u.undefined,void 0,1)}function Uc(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${y} indefinite length items not allowed`);return new p(u.break,void 0,1)}function Co(r,e,t){if(t){if(t.allowNaN===!1&&Number.isNaN(r))throw new Error(`${y} NaN values are not supported`);if(t.allowInfinity===!1&&(r===1/0||r===-1/0))throw new Error(`${y} Infinity values are not supported`)}return new p(u.float,r,e)}function Mc(r,e,t,n){return Co(To(r,e+1),3,n)}function $c(r,e,t,n){return Co(Lo(r,e+1),5,n)}function Oc(r,e,t,n){return Co(jc(r,e+1),9,n)}function br(r,e,t){let n=e.value;if(n===!1)r.push([u.float.majorEncoded|ko]);else if(n===!0)r.push([u.float.majorEncoded|Ao]);else if(n===null)r.push([u.float.majorEncoded|So]);else if(n===void 0)r.push([u.float.majorEncoded|Io]);else{let i,o=!1;(!t||t.float64!==!0)&&(zc(n),i=To(Ae,1),n===i||Number.isNaN(n)?(Ae[0]=249,r.push(Ae.slice(0,3)),o=!0):(qc(n),i=Lo(Ae,1),n===i&&(Ae[0]=250,r.push(Ae.slice(0,5)),o=!0))),o||(xd(n),i=jc(Ae,1),Ae[0]=251,r.push(Ae.slice(0,9)))}}br.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){zc(n);let i=To(Ae,1);if(n===i||Number.isNaN(n))return 3;if(qc(n),i=Lo(Ae,1),n===i)return 5}return 9};var Kc=new ArrayBuffer(9),de=new DataView(Kc,1),Ae=new Uint8Array(Kc,0);function zc(r){if(r===1/0)de.setUint16(0,31744,!1);else if(r===-1/0)de.setUint16(0,64512,!1);else if(Number.isNaN(r))de.setUint16(0,32256,!1);else{de.setFloat32(0,r);let e=de.getUint32(0),t=(e&2139095040)>>23,n=e&8388607;if(t===255)de.setUint16(0,31744,!1);else if(t===0)de.setUint16(0,(e&2147483648)>>16|n>>13,!1);else{let i=t-127;i<-24?de.setUint16(0,0):i<-14?de.setUint16(0,(e&2147483648)>>16|1<<24+i,!1):de.setUint16(0,(e&2147483648)>>16|i+15<<10|n>>13,!1)}}}function To(r,e){if(r.length-e<2)throw new Error(`${y} 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,i=t&1023,o;return n===0?o=i*2**-24:n!==31?o=(i+1024)*2**(n-25):o=i===0?1/0:NaN,t&32768?-o:o}function qc(r){de.setFloat32(0,r,!1)}function Lo(r,e){if(r.length-e<4)throw new Error(`${y} not enough data for float32`);let t=(r.byteOffset||0)+e;return new DataView(r.buffer,t,4).getFloat32(0,!1)}function xd(r){de.setFloat64(0,r,!1)}function jc(r,e){if(r.length-e<8)throw new Error(`${y} not enough data for float64`);let t=(r.byteOffset||0)+e;return new DataView(r.buffer,t,8).getFloat64(0,!1)}br.compareTokens=he.compareTokens;function k(r,e,t){throw new Error(`${y} encountered invalid minor (${t}) for major ${r[e]>>>5}`)}function An(r){return()=>{throw new Error(`${y} ${r}`)}}var m=[];for(let r=0;r<=23;r++)m[r]=k;m[24]=Xa;m[25]=Za;m[26]=ec;m[27]=tc;m[28]=k;m[29]=k;m[30]=k;m[31]=k;for(let r=32;r<=55;r++)m[r]=k;m[56]=rc;m[57]=nc;m[58]=ic;m[59]=sc;m[60]=k;m[61]=k;m[62]=k;m[63]=k;for(let r=64;r<=87;r++)m[r]=ac;m[88]=cc;m[89]=uc;m[90]=lc;m[91]=fc;m[92]=k;m[93]=k;m[94]=k;m[95]=An("indefinite length bytes/strings are not supported");for(let r=96;r<=119;r++)m[r]=dc;m[120]=pc;m[121]=mc;m[122]=yc;m[123]=gc;m[124]=k;m[125]=k;m[126]=k;m[127]=An("indefinite length bytes/strings are not supported");for(let r=128;r<=151;r++)m[r]=bc;m[152]=xc;m[153]=Ec;m[154]=vc;m[155]=_c;m[156]=k;m[157]=k;m[158]=k;m[159]=kc;for(let r=160;r<=183;r++)m[r]=Ac;m[184]=Sc;m[185]=Ic;m[186]=Cc;m[187]=Tc;m[188]=k;m[189]=k;m[190]=k;m[191]=Lc;for(let r=192;r<=215;r++)m[r]=Dc;m[216]=Pc;m[217]=Nc;m[218]=Rc;m[219]=Bc;m[220]=k;m[221]=k;m[222]=k;m[223]=k;for(let r=224;r<=243;r++)m[r]=An("simple values are not supported");m[244]=k;m[245]=k;m[246]=k;m[247]=Fc;m[248]=An("simple values are not supported");m[249]=Mc;m[250]=$c;m[251]=Oc;m[252]=k;m[253]=k;m[254]=k;m[255]=Uc;var Se=[];for(let r=0;r<24;r++)Se[r]=new p(u.uint,r,1);for(let r=-1;r>=-24;r--)Se[31-r]=new p(u.negint,r,1);Se[64]=new p(u.bytes,new Uint8Array(0),1);Se[96]=new p(u.string,"",1);Se[128]=new p(u.array,0,1);Se[160]=new p(u.map,0,1);Se[244]=new p(u.false,!1,1);Se[245]=new p(u.true,!0,1);Se[246]=new p(u.null,null,1);function Do(r){switch(r.type){case u.false:return Te([244]);case u.true:return Te([245]);case u.null:return Te([246]);case u.bytes:return r.value.length?void 0:Te([64]);case u.string:return r.value===""?Te([96]):void 0;case u.array:return r.value===0?Te([128]):void 0;case u.map:return r.value===0?Te([160]):void 0;case u.uint:return r.value<24?Te([Number(r.value)]):void 0;case u.negint:if(r.value>=-24)return Te([31-Number(r.value)])}}var vd={float64:!1,mapSorter:Ad,quickEncodeToken:Do},Jc=Object.freeze({float64:!0,mapSorter:Sd,quickEncodeToken:Do});function _d(){let r=[];return r[u.uint.major]=he,r[u.negint.major]=xn,r[u.bytes.major]=It,r[u.string.major]=wc,r[u.array.major]=vn,r[u.map.major]=_n,r[u.tag.major]=kn,r[u.float.major]=br,r}var Dt=_d(),Sn=new mr,Er=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(`${Le} object contains circular references`);return new r(t,e)}},He={null:new p(u.null,null),undefined:new p(u.undefined,void 0),true:new p(u.true,!0),false:new p(u.false,!1),emptyArray:new p(u.array,0),emptyMap:new p(u.map,0)},De={number(r,e,t,n){return!Number.isInteger(r)||!Number.isSafeInteger(r)?new p(u.float,r):r>=0?new p(u.uint,r):new p(u.negint,r)},bigint(r,e,t,n){return r>=BigInt(0)?new p(u.uint,r):new p(u.negint,r)},Uint8Array(r,e,t,n){return new p(u.bytes,r)},string(r,e,t,n){return new p(u.string,r)},boolean(r,e,t,n){return r?He.true:He.false},null(r,e,t,n){return He.null},undefined(r,e,t,n){return He.undefined},ArrayBuffer(r,e,t,n){return new p(u.bytes,new Uint8Array(r))},DataView(r,e,t,n){return new p(u.bytes,new Uint8Array(r.buffer,r.byteOffset,r.byteLength))},Array(r,e,t,n){if(!r.length)return t.addBreakTokens===!0?[He.emptyArray,new p(u.break)]:He.emptyArray;n=Er.createCheck(n,r);let i=[],o=0;for(let s of r)i[o++]=Lt(s,t,n);return t.addBreakTokens?[new p(u.array,r.length),i,new p(u.break)]:[new p(u.array,r.length),i]},Object(r,e,t,n){let i=e!=="Object",o=i?r.keys():Object.keys(r),s=i?r.size:o.length,a;if(s){a=new Array(s),n=Er.createCheck(n,r);let c=!i&&t.ignoreUndefinedProperties,f=0;for(let l of o){let h=i?r.get(l):r[l];c&&h===void 0||(a[f++]=[Lt(l,t,n),Lt(h,t,n)])}f<s&&(a.length=f)}return a?.length?(kd(a,t),t.addBreakTokens?[new p(u.map,a.length),a,new p(u.break)]:[new p(u.map,a.length),a]):t.addBreakTokens===!0?[He.emptyMap,new p(u.break)]:He.emptyMap},Tagged(r,e,t,n){return[new p(u.tag,r.tag),Lt(r.value,t,n)]}};De.Map=De.Object;De.Buffer=De.Uint8Array;for(let r of"Uint8Clamped Uint16 Uint32 Int8 Int16 Int32 BigUint64 BigInt64 Float32 Float64".split(" "))De[`${r}Array`]=De.DataView;function Lt(r,e={},t){let n=vo(r),i=e&&e.typeEncoders&&e.typeEncoders[n]||De[n];if(typeof i=="function"){let s=i(r,n,e,t);if(s!=null)return s}let o=De[n];if(!o)throw new Error(`${Le} unsupported type: ${n}`);return o(r,n,e,t)}function kd(r,e){e.mapSorter&&r.sort(e.mapSorter)}function Ad(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 i=t.type.major,o=Dt[i].compareTokens(t,n);return o===0&&console.warn("WARNING: complex key types used, CBOR key sorting guarantees are gone"),o}function Sd(r,e){if(r[0]instanceof p&&e[0]instanceof p){let t=r[0],n=e[0];return t._keyBytes||(t._keyBytes=Vc(t.value)),n._keyBytes||(n._keyBytes=Vc(n.value)),wn(t._keyBytes,n._keyBytes)}throw new Error("rfc8949MapSorter: complex key types are not supported yet")}function Vc(r){return In(r,Dt,Jc)}function xr(r,e,t,n){if(Array.isArray(e))for(let i of e)xr(r,i,t,n);else t[e.type.major](r,e,n)}var Hc=u.uint.majorEncoded,Wc=u.negint.majorEncoded,Id=u.bytes.majorEncoded,Cd=u.string.majorEncoded,Gc=u.array.majorEncoded,Td=u.float.majorEncoded|ko,Ld=u.float.majorEncoded|Ao,Dd=u.float.majorEncoded|So,Pd=u.float.majorEncoded|Io,Nd=BigInt(-1),Rd=BigInt(1);function Bd(r){return r.addBreakTokens!==!0}function Qc(r,e,t,n){let i=vo(e),o=t.typeEncoders&&t.typeEncoders[i];if(o){let s=o(e,i,t,n);if(s!=null){xr(r,s,Dt,t);return}}switch(i){case"null":r.push([Dd]);return;case"undefined":r.push([Pd]);return;case"boolean":r.push([e?Ld:Td]);return;case"number":!Number.isInteger(e)||!Number.isSafeInteger(e)?br(r,new p(u.float,e),t):e>=0?C(r,Hc,e):C(r,Wc,e*-1-1);return;case"bigint":e>=BigInt(0)?C(r,Hc,e):C(r,Wc,e*Nd-Rd);return;case"string":{let s=St(e);C(r,Cd,s.length),r.push(s);return}case"Uint8Array":C(r,Id,e.length),r.push(e);return;case"Array":if(!e.length){r.push([Gc]);return}n=Er.createCheck(n,e),C(r,Gc,e.length);for(let s of e)Qc(r,s,t,n);return;case"Object":case"Map":{let s=De.Object(e,i,t,n);xr(r,s,Dt,t)}return;default:{let s=De[i];if(!s)throw new Error(`${Le} unsupported type: ${i}`);let a=s(e,i,t,n);xr(r,a,Dt,t)}}}function In(r,e,t,n){let i=n instanceof Uint8Array,o=i?new bn(n):Sn,s=Lt(r,t);if(!Array.isArray(s)&&t.quickEncodeToken){let a=t.quickEncodeToken(s);if(a)return i?(o.push(a),o.toBytes()):a;let c=e[s.type.major];if(c.encodedSize){let f=c.encodedSize(s,t);if(i||(o=new mr(f)),c(o,s,t),o.chunks.length!==1)throw new Error(`Unexpected error: pre-calculated length for ${s} was wrong`);return i?o.toBytes():it(o.chunks[0])}}return o.reset(),xr(o,s,e,t),o.toBytes(!0)}function st(r,e){return e=Object.assign({},vd,e),Bd(e)?(Sn.reset(),Qc(Sn,r,e,void 0),Sn.toBytes(!0)):In(r,Dt,e)}var Fd={strict:!1,allowIndefinite:!0,allowUndefined:!0,allowBigInt:!0},Cn=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=Se[e];if(t===void 0){let n=m[e];if(!n)throw new Error(`${y} no decoder for major type ${e>>>5} (byte 0x${e.toString(16).padStart(2,"0")})`);let i=e&31;t=n(this.data,this._pos,i,this.options)}return this._pos+=t.encodedLength,t}},We=Symbol.for("DONE"),Pt=Symbol.for("BREAK");function Ud(r,e,t){let n=[];for(let i=0;i<r.value;i++){let o=Ge(e,t);if(o===Pt){if(r.value===1/0)break;throw new Error(`${y} got unexpected break to lengthed array`)}if(o===We)throw new Error(`${y} found array but not enough entries (got ${i}, expected ${r.value})`);n[i]=o}return n}function Md(r,e,t){let n=t.useMaps===!0,i=t.rejectDuplicateMapKeys===!0,o=n?void 0:{},s=n?new Map:void 0;for(let a=0;a<r.value;a++){let c=Ge(e,t);if(c===Pt){if(r.value===1/0)break;throw new Error(`${y} got unexpected break to lengthed map`)}if(c===We)throw new Error(`${y} found map but not enough entries (got ${a} [no key], expected ${r.value})`);if(!n&&typeof c!="string")throw new Error(`${y} non-string keys not supported (got ${typeof c})`);if(i&&(n&&s.has(c)||!n&&Object.hasOwn(o,c)))throw new Error(`${y} found repeat map key "${c}"`);let f=Ge(e,t);if(f===We)throw new Error(`${y} found map but not enough entries (got ${a} [no value], expected ${r.value})`);n?s.set(c,f):o[c]=f}return n?s:o}function*$d(r,e,t){for(let n=0;n<r.value;n++){let i=Ge(e,t);if(i===Pt){if(r.value===1/0)break;throw new Error(`${y} got unexpected break to lengthed map`)}if(i===We)throw new Error(`${y} found map but not enough entries (got ${n} [no key], expected ${r.value})`);let o=Ge(e,t);if(o===We)throw new Error(`${y} found map but not enough entries (got ${n} [no value], expected ${r.value})`);yield[i,o]}}function Od(r,e){let t=!1,n=function(){if(t)throw new Error(`${y} tag decode() may only be called once`);t=!0;let i=Ge(r,e);if(i===We)throw new Error(`${y} tag content missing`);if(i===Pt)throw new Error(`${y} got unexpected break in tag content`);return i};return n.entries=function(){if(t)throw new Error(`${y} tag decode() may only be called once`);t=!0;let i=r.next();if(!u.equals(i.type,u.map))throw new Error(`${y} entries() requires map content, got ${i.type.name}`);let o=[];for(let s of $d(i,r,e))o.push(s);return o},Object.defineProperty(n,"_called",{get(){return t},enumerable:!1}),n}function Ge(r,e){if(r.done())return We;let t=r.next();if(u.equals(t.type,u.break))return Pt;if(t.type.terminal)return t.value;if(u.equals(t.type,u.array))return Ud(t,r,e);if(u.equals(t.type,u.map))return Md(t,r,e);if(u.equals(t.type,u.tag)){if(e.tags&&typeof e.tags[t.value]=="function"){let n=Od(r,e),i=e.tags[t.value](n);if(!n._called)throw new Error(`${y} tag decoder must call decode() or entries()`);return i}throw new Error(`${y} tag not supported (${t.value})`)}throw new Error("unsupported")}function Po(r,e){if(!(r instanceof Uint8Array))throw new Error(`${y} data to decode must be a Uint8Array`);e=Object.assign({},Fd,e);let t=it(r),n=e.tokenizer||new Cn(t,e),i=Ge(n,e);if(i===We)throw new Error(`${y} did not find any content to decode`);if(i===Pt)throw new Error(`${y} got unexpected break`);return[i,r.subarray(n.pos())]}function Ie(r,e){let[t,n]=Po(r,e);if(n.length>0)throw new Error(`${y} too many terminals, data makes no sense`);return t}var Tn=class r{constructor(e,t){if(typeof e!="number"||!Number.isInteger(e)||e<0)throw new TypeError("Tagged: tag must be a non-negative integer");this.tag=e,this.value=t}static decoder(e){return t=>new r(e,t())}static preserve(...e){let t={};for(let n of e)t[n]=r.decoder(n);return t}};Object.defineProperty(Tn.prototype,Symbol.toStringTag,{value:"Tagged"});function Kd(r){return r[Symbol.asyncIterator]!=null}function zd(r){if(Kd(r))return(async()=>{let n=new Uint8Array(0);for await(let i of r)n=we([n,i],n.length+i.length);return n})();let e=[],t=0;for(let n of r)e.push(n),t+=n.byteLength;return we(e,t)}var Ln=zd;function Dn({enumerable:r=!0,configurable:e=!1}={}){return{enumerable:r,configurable:e,writable:!1}}function*qd(r,e){if(e!=null&&typeof e=="object")if(Array.isArray(e))for(let[t,n]of e.entries()){let i=[...r,t],o=v.asCID(n);o!=null?yield[i.join("/"),o]:typeof n=="object"&&(yield*No(n,i))}else{let t=v.asCID(e);t!=null?yield[r.join("/"),t]:yield*No(e,r)}}function*No(r,e){if(r==null||r instanceof Uint8Array)return;let t=v.asCID(r);t!=null&&(yield[e.join("/"),t]);for(let[n,i]of Object.entries(r)){let o=[...e,n];yield*qd(o,i)}}function*jd(r,e){if(Array.isArray(e))for(let[t,n]of e.entries()){let i=[...r,t];yield i.join("/"),typeof n=="object"&&v.asCID(n)==null&&(yield*Ro(n,i))}else yield*Ro(e,r)}function*Ro(r,e){if(!(r==null||typeof r!="object"))for(let[t,n]of Object.entries(r)){let i=[...e,t];yield i.join("/"),n!=null&&!(n instanceof Uint8Array)&&typeof n=="object"&&v.asCID(n)==null&&(yield*jd(i,n))}}function Vd(r,e){let t=r;for(let[n,i]of e.entries()){if(t=t[i],t==null)throw new Error(`Object has no property at ${e.slice(0,n+1).map(s=>`[${JSON.stringify(s)}]`).join("")}`);let o=v.asCID(t);if(o!=null)return{value:o,remaining:e.slice(n+1).join("/")}}return{value:t}}var Bo=class{cid;bytes;value;asBlock;constructor({cid:e,bytes:t,value:n}){if(e==null||t==null||typeof n>"u")throw new Error("Missing required argument");this.cid=e,this.bytes=t,this.value=n,this.asBlock=this,Object.defineProperties(this,{cid:Dn(),bytes:Dn(),value:Dn(),asBlock:Dn()})}links(){return No(this.value,[])}tree(){return Ro(this.value,[])}get(e="/"){return Vd(this.value,e.split("/").filter(Boolean))}};function Pn({bytes:r,cid:e,value:t,codec:n}){let i=t!==void 0?t:n?.decode(r);if(i===void 0)throw new Error('Missing required argument, must either provide "value" or "codec"');return new Bo({cid:e,bytes:r,value:i})}var Nn=class extends Error{static name="AlreadyPinnedError";name="AlreadyPinnedError"},vr=class extends Error{static name="BlockPinnedError";name="BlockPinnedError"},Rn=class extends Error{static name="InvalidDatastoreVersionError";name="InvalidDatastoreVersionError"},at=class extends Error{static name="InvalidConfigurationError";name="InvalidConfigurationError"},Bn=class extends AggregateError{static name="GetFailedError";name="GetFailedError"},Fn=class extends AggregateError{static name="LoadBlockFailedError";name="LoadBlockFailedError"},_r=class extends Error{static name="BlockNotFoundWhileOfflineError";name="BlockNotFoundWhileOfflineError"};var eu="/pin/",Xc="/pinned-block/",Fo=te,Zc=1;function Un(r){return r.version===0&&(r=r.toV1()),new B(`${eu}${r.toString(Fo)}`)}var Mn=class{datastore;blockstore;getCodec;constructor(e,t,n){this.datastore=e,this.blockstore=t,this.getCodec=n}async*add(e,t={}){let n=Un(e);if(await this.datastore.has(n))throw new Nn("Already pinned");let i=Math.round(t.depth??1/0);if(i<0)throw new _t("Depth must be greater than or equal to 0");let o=new ne({concurrency:Zc});for await(let a of this.#e(e,o,{...t,depth:i}))await this.#t(a,c=>c.pinnedBy.find(f=>Re(f,e.bytes))!=null?!1:(c.pinCount++,c.pinnedBy.push(e.bytes),!0),t),yield a;let s={depth:i,metadata:t.metadata??{}};await this.datastore.put(n,st(s),t)}async*#e(e,t,n){if(n.depth===-1)return;let i=await this.getCodec(e.code),o=await Ln(this.blockstore.get(e,n)),s=Pn({bytes:o,cid:e,codec:i});yield e;for(let[,a]of s.links())yield*await t.add(async()=>this.#e(a,t,{...n,depth:n.depth-1}))}async#t(e,t,n){let i=new B(`${Xc}${Fo.encode(e.multihash.bytes)}`),o={pinCount:0,pinnedBy:[]};try{o=Ie(await this.datastore.get(i,n))}catch(a){if(a.name!=="NotFoundError")throw a}if(t(o)){if(o.pinCount===0&&await this.datastore.has(i)){await this.datastore.delete(i);return}await this.datastore.put(i,st(o),n),n.onProgress?.(new x("helia:pin:add",e))}}async*rm(e,t={}){let n=Un(e),i=await this.datastore.get(n,t),o=Ie(i);await this.datastore.delete(n,t);let s=new ne({concurrency:Zc});for await(let a of this.#e(e,s,{...t,depth:o.depth}))await this.#t(a,c=>(c.pinCount--,c.pinnedBy=c.pinnedBy.filter(f=>Re(f,e.bytes)),!0),{...t,depth:o.depth}),yield a}async*ls(e={}){for await(let{key:t,value:n}of this.datastore.query({prefix:eu+(e.cid!=null?`${e.cid.toString(te)}`:"")},e)){let i=v.parse(t.toString().substring(5),te),o=Ie(n);yield{cid:i,...o}}}async isPinned(e,t={}){let n=new B(`${Xc}${Fo.encode(e.multihash.bytes)}`);return this.datastore.has(n,t)}async get(e,t){let n=Un(e),i=await this.datastore.get(n,t);return Ie(i)}async setMetadata(e,t,n){let i=Un(e),o=await this.datastore.get(i,n),s=Ie(o);s.metadata=t??{},await this.datastore.put(i,st(s),n)}};var $n=class extends Error{static name="InsufficientProvidersError";constructor(e="Insufficient providers found"){super(e),this.name="InsufficientProvidersError"}},ct=class extends Error{static name="NoRoutersAvailableError";constructor(e="No routers available"){super(e),this.name="NoRoutersAvailableError"}},On=class extends Error{static name="UnknownHashAlgorithmError";constructor(e="Unknown hash algorithm"){super(e),this.name="UnknownHashAlgorithmError"}},Kn=class extends Error{static name="UnknownCodecError";constructor(e="Unknown codec"){super(e),this.name="UnknownCodecError"}};var zn=class extends Error{static name="UnknownCryptoError";name="UnknownCryptoError"};var Hd=5,qn=class{name;log;routers;providerLookupConcurrency;constructor(e,t){this.name="helia",this.log=e.logger.forComponent("helia:routing"),this.routers=t.routers??[],this.providerLookupConcurrency=t.providerLookupConcurrency??Hd,this.findProviders=e.metrics?.traceFunction("helia.routing.findProviders",this.findProviders.bind(this),{optionsIndex:1})??this.findProviders,this.provide=e.metrics?.traceFunction("helia.routing.provide",this.provide.bind(this),{optionsIndex:1})??this.provide,this.cancelReprovide=e.metrics?.traceFunction("helia.routing.cancelReprovide",this.cancelReprovide.bind(this),{optionsIndex:1})??this.cancelReprovide,this.put=e.metrics?.traceFunction("helia.routing.put",this.put.bind(this),{optionsIndex:2})??this.put,this.get=e.metrics?.traceFunction("helia.routing.get",this.get.bind(this),{optionsIndex:1})??this.get,this.findPeer=e.metrics?.traceFunction("helia.routing.findPeer",this.findPeer.bind(this),{optionsIndex:1})??this.findPeer,this.getClosestPeers=e.metrics?.traceFunction("helia.routing.getClosestPeers",this.getClosestPeers.bind(this),{optionsIndex:1})??this.getClosestPeers}async start(){await qe(...this.routers)}async stop(){await je(...this.routers)}hasRouter(e){return this.routers.findIndex(t=>t.name===e)!==-1}addRouter(e){this.routers.push(e)}async*findProviders(e,t={}){if(this.routers.length===0)throw new ct("No content routers available");let n=new ne({concurrency:this.providerLookupConcurrency}),i=0,o=[],s=this,a=0;this.log("findProviders for %c start using routers %s",e,this.routers.map(f=>f.toString()).join(", "));let c=ut(this.routers,"findProviders").map(async function*(f){let l=0;t?.onProgress?.(new x("helia:routing:find-providers:start",{routing:f.name,cid:e}));try{for await(let h of f.findProviders(e,t))l++,t?.onProgress?.(new x("helia:routing:find-providers:provider",{routing:f.name,cid:e,provider:h})),yield h}catch(h){o.push(h)}finally{s.log("router %s found %d providers for %c",f,l,e),t?.onProgress?.(new x("helia:routing:find-providers:end",{routing:f.name,cid:e,found:l})),a++,a===c.length&&n.size===0&&n.emitIdle()}});for await(let f of tt(n.toGenerator(),...c))if(f!=null){if(f.multiaddrs.length===0){if(n.queue.find(l=>l.options.peer.equals(f.id))!=null)continue;n.add(async()=>{try{let l=await this.findPeer(f.id,t);return l.multiaddrs.length===0?null:{...l,protocols:f.protocols,routing:f.routing}}catch(l){return this.log.error("could not load multiaddrs for peer %p - %e",f.id,l),null}},{peer:f.id,signal:t.signal}).catch(l=>{this.log.error("could not load multiaddrs for peer %p - %e",f.id,l)});continue}i++,yield f}this.log("findProviders finished, found %d providers for %c",i,e)}async provide(e,t={}){if(this.routers.length===0)throw new ct("No content routers available");await Promise.all(ut(this.routers,"provide").map(async n=>{t?.onProgress?.(new x("helia:routing:provide:start",{routing:n.name,cid:e})),await n.provide(e,t),t?.onProgress?.(new x("helia:routing:provide:end",{routing:n.name,cid:e}))}))}async cancelReprovide(e,t={}){await Promise.all(ut(this.routers,"cancelReprovide").map(async n=>{t?.onProgress?.(new x("helia:routing:cancel-reprovide:start",{routing:n.name,cid:e})),await n.cancelReprovide(e,t),t?.onProgress?.(new x("helia:routing:cancel-reprovide:end",{routing:n.name,cid:e}))}))}async put(e,t,n){await Promise.all(ut(this.routers,"put").map(async i=>{n?.onProgress?.(new x("helia:routing:put:start",{routing:i.name,key:e,value:t})),await i.put(e,t,n),n?.onProgress?.(new x("helia:routing:put:end",{routing:i.name,key:e,value:t}))}))}async get(e,t){let n=[],i;try{i=await Promise.any(ut(this.routers,"get").map(async o=>{t?.onProgress?.(new x("helia:routing:get:start",{routing:o.name,key:e}));try{return await o.get(e,t)}catch(s){this.log("router %s failed with %e",o,s),n.push(s)}finally{t?.onProgress?.(new x("helia:routing:get:end",{routing:o.name,key:e}))}}))}catch{}if(i==null)throw new Bn(n,`Failed to get value key ${ue(e,"base58btc")}`);return i}async findPeer(e,t){if(this.routers.length===0)throw new ct("No peer routers available");let n=this,i=tt(...ut(this.routers,"findPeer").map(o=>(async function*(){t?.onProgress?.(new x("helia:routing:find-peer:start",{routing:o.name,peerId:e}));try{yield await o.findPeer(e,t)}catch(s){n.log.error(s)}finally{t?.onProgress?.(new x("helia:routing:find-peer:end",{routing:o.name,peerId:e}))}})()));for await(let o of i)if(o!=null)return o;throw new Xr("Could not find peer in routing")}async*getClosestPeers(e,t={}){if(this.routers.length===0)throw new ct("No peer routers available");for await(let n of tt(...ut(this.routers,"getClosestPeers").map(async function*(i){t?.onProgress?.(new x("helia:routing:get-closest-peers:start",{routing:i.name,key:e}));try{yield*i.getClosestPeers(e,t)}finally{t?.onProgress?.(new x("helia:routing:get-closest-peers:end",{routing:i.name,key:e}))}})))n!=null&&(yield n)}};function ut(r,e){return r.filter(t=>t[e]!=null)}var ce=class extends Error{static name="AbortError";name="AbortError";constructor(e="The operation was aborted",...t){super(e,...t)}};async function jn(r,e,t,n){let i=new ce(n?.errorMessage);n?.errorCode!=null&&(i.code=n.errorCode);let o=n?.errorEvent??"error";return t?.aborted===!0?Promise.reject(i):new Promise((s,a)=>{function c(){Mo(t,"abort",h),Mo(r,e,f),Mo(r,o,l)}let f=d=>{try{if(n?.filter?.(d)===!1)return}catch(g){c(),a(g);return}c(),s(d)},l=d=>{if(c(),d instanceof Error){a(d);return}a(d.detail??n?.error??new Error(`The "${n?.errorEvent}" event was emitted but the event had no '.detail' field. Pass an 'error' option to race-event to change this message.`))},h=()=>{c(),a(i)};Uo(t,"abort",h),Uo(r,e,f),Uo(r,o,l)})}function Uo(r,e,t){r!=null&&(tu(r)?r.addEventListener(e,t):r.addListener(e,t))}function Mo(r,e,t){r!=null&&(tu(r)?r.removeEventListener(e,t):r.removeListener(e,t))}function tu(r){return typeof r.addEventListener=="function"&&typeof r.removeEventListener=="function"}var Vn=class extends Error{static name="QueueFullError";constructor(e="The queue was full"){super(e),this.name="QueueFullError"}};var Hn=class{deferred;signal;constructor(e){this.signal=e,this.deferred=Promise.withResolvers(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new ce)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function Wd(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var Wn=class{id;fn;options;recipients;status;timeline;controller;constructor(e,t){this.id=Wd(),this.status="queued",this.fn=e,this.options=t,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,this.controller.signal,this.onAbort=this.onAbort.bind(this)}abort(e){this.controller.abort(e)}onAbort(){this.recipients.reduce((t,n)=>t&&n.signal?.aborted===!0,!0)&&(this.controller.abort(new ce),this.cleanup())}async join(e={}){let t=new Hn(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 Ve(this.fn({...this.options??{},signal:this.controller.signal}),this.controller.signal);this.recipients.forEach(t=>{t.deferred.resolve(e)}),this.status="complete"}catch(e){this.recipients.forEach(t=>{t.deferred.reject(e)}),this.status="errored"}finally{this.timeline.finished=Date.now(),this.cleanup()}}cleanup(){this.recipients.forEach(e=>{e.cleanup(),e.signal?.removeEventListener("abort",this.onAbort)})}};function $o(r,e){let t,n=function(){let i=function(){t=void 0,r()};clearTimeout(t),t=setTimeout(i,e)};return n.start=()=>{},n.stop=()=>{clearTimeout(t)},n}var kr=class extends le{concurrency;maxSize;queue;pending;sort;autoStart;constructor(e={}){super(),this.concurrency=e.concurrency??Number.POSITIVE_INFINITY,this.maxSize=e.maxSize??Number.POSITIVE_INFINITY,this.pending=0,this.autoStart=e.autoStart??!0,this.sort=e.sort,this.queue=[],this.emitEmpty=$o(this.emitEmpty.bind(this),1),this.emitIdle=$o(this.emitIdle.bind(this),1)}[Symbol.asyncIterator](){return this.toGenerator()}emitEmpty(){this.size===0&&this.safeDispatchEvent("empty")}emitIdle(){this.running===0&&this.safeDispatchEvent("idle")}tryToStartAnother(){if(this.size===0)return this.emitEmpty(),this.running===0&&this.emitIdle(),!1;if(this.pending<this.concurrency){let e;for(let t of this.queue)if(t.status==="queued"){e=t;break}return e==null?!1:(this.safeDispatchEvent("active"),this.pending++,e.run().finally(()=>{for(let t=0;t<this.queue.length;t++)if(this.queue[t]===e){this.queue.splice(t,1);break}this.pending--,this.safeDispatchEvent("next"),this.autoStart&&this.tryToStartAnother()}),!0)}return!1}enqueue(e){this.queue.push(e),this.sort!=null&&this.queue.sort(this.sort)}start(){this.autoStart===!1&&(this.autoStart=!0,this.tryToStartAnother())}pause(){this.autoStart=!1}async add(e,t){if(t?.signal?.throwIfAborted(),this.size===this.maxSize)throw new Vn;let n=new Wn(e,t);return this.enqueue(n),this.safeDispatchEvent("add"),this.autoStart&&this.tryToStartAnother(),n.join(t).then(i=>(this.safeDispatchEvent("success",{detail:{job:n,result:i}}),i)).catch(i=>{if(n.status==="queued"){for(let o=0;o<this.queue.length;o++)if(this.queue[o]===n){this.queue.splice(o,1);break}}throw this.safeDispatchEvent("failure",{detail:{job:n,error:i}}),i})}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(e=>{e.abort(new ce)}),this.clear()}async onEmpty(e){this.size!==0&&await jn(this,"empty",e?.signal)}async onSizeLessThan(e,t){this.size<e||await jn(this,"next",t?.signal,{filter:()=>this.size<e})}async onIdle(e){this.pending===0&&this.size===0||await jn(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=fr({objectMode:!0}),n=c=>{c!=null?this.abort():this.clear(),t.end(c)},i=c=>{c.detail!=null&&t.push(c.detail.result)},o=c=>{n(c.detail.error)},s=()=>{n()},a=()=>{n(new ce("Queue aborted"))};this.addEventListener("success",i),this.addEventListener("failure",o),this.addEventListener("idle",s),e?.signal?.addEventListener("abort",a);try{yield*t}finally{this.removeEventListener("success",i),this.removeEventListener("failure",o),this.removeEventListener("idle",s),e?.signal?.removeEventListener("abort",a),n()}}};var Gn="lock:worker:request-read",Jn="lock:worker:abort-read-request",Qn="lock:worker:release-read",Yn="lock:master:grant-read",Xn="lock:master:error-read",Zn="lock:worker:request-write",ei="lock:worker:abort-write-request",ti="lock:worker:release-write",ri="lock:master:grant-write",ni="lock:master:error-write",ii="lock:worker:finalize",oi="mortice",ru={singleProcess:!1};var Oo=(r,e,t,n,i,o,s,a,c)=>f=>{if(f.data==null)return;let l={type:f.data.type,name:f.data.name,identifier:f.data.identifier};l.type===i&&r.safeDispatchEvent(t,{detail:{name:l.name,identifier:l.identifier,handler:async()=>{e.postMessage({type:c,name:l.name,identifier:l.identifier}),await new Promise(h=>{let d=g=>{if(g?.data==null)return;let w={type:g.data.type,name:g.data.name,identifier:g.data.identifier};w.type===a&&w.identifier===l.identifier&&(e.removeEventListener("message",d),h())};e.addEventListener("message",d)})},onError:h=>{e.postMessage({type:s,name:l.name,identifier:l.identifier,error:{message:h.message,name:h.name,stack:h.stack}})}}}),l.type===o&&r.safeDispatchEvent(n,{detail:{name:l.name,identifier:l.identifier}}),l.type===ii&&r.safeDispatchEvent("finalizeRequest",{detail:{name:l.name}})};var nu=(r=10)=>Math.random().toString().substring(2,r+2);var si=class{name;channel;constructor(e){this.name=e,this.channel=new BroadcastChannel(oi)}readLock(e){return this.sendRequest(Gn,Jn,Yn,Xn,Qn,e)}writeLock(e){return this.sendRequest(Zn,ei,ri,ni,ti,e)}finalize(){this.channel.postMessage({type:ii,name:this.name}),this.channel.close()}async sendRequest(e,t,n,i,o,s){s?.signal?.throwIfAborted();let a=nu();return this.channel.postMessage({type:e,identifier:a,name:this.name}),new Promise((c,f)=>{let l=()=>{this.channel.postMessage({type:t,identifier:a,name:this.name})};s?.signal?.addEventListener("abort",l,{once:!0});let h=d=>{if(d.data?.identifier===a&&(d.data?.type===n&&(this.channel.removeEventListener("message",h),s?.signal?.removeEventListener("abort",l),c(()=>{this.channel.postMessage({type:o,identifier:a,name:this.name})})),d.data.type===i)){this.channel.removeEventListener("message",h),s?.signal?.removeEventListener("abort",l);let g=new Error;d.data.error!=null&&(g.message=d.data.error.message,g.name=d.data.error.name,g.stack=d.data.error.stack),f(g)}};this.channel.addEventListener("message",h)})}};var iu=r=>{if(r=Object.assign({},ru,r),!!globalThis.document||r.singleProcess){let t=new BroadcastChannel(oi),n=new le;return t.addEventListener("message",Oo(n,t,"requestReadLock","abortReadLockRequest",Gn,Jn,Xn,Qn,Yn)),t.addEventListener("message",Oo(n,t,"requestWriteLock","abortWriteLockRequest",Zn,ei,ni,ti,ri)),n}return new si(r.name)};var lt=new Map,Ar;function ou(r){return typeof r?.readLock=="function"&&typeof r?.writeLock=="function"}function Gd(r){if(Ar==null&&(Ar=iu(r),!ou(Ar))){let e=Ar;e.addEventListener("requestReadLock",t=>{let n=t.detail.name,i=t.detail.identifier,o=lt.get(n);if(o==null)return;let s=new AbortController,a=c=>{c.detail.name!==n||c.detail.identifier!==i||s.abort()};e.addEventListener("abortReadLockRequest",a),o.readLock({signal:s.signal}).then(async c=>{await t.detail.handler().finally(()=>{c()})}).catch(c=>{t.detail.onError(c)}).finally(()=>{e.removeEventListener("abortReadLockRequest",a)})}),e.addEventListener("requestWriteLock",t=>{let n=t.detail.name,i=t.detail.identifier,o=lt.get(n);if(o==null)return;let s=new AbortController,a=c=>{c.detail.name!==n||c.detail.identifier!==i||s.abort()};e.addEventListener("abortWriteLockRequest",a),o.writeLock({signal:s.signal}).then(async c=>{await t.detail.handler().finally(()=>{c()})}).catch(c=>{t.detail.onError(c)}).finally(()=>{e.removeEventListener("abortWriteLockRequest",a)})}),e.addEventListener("finalizeRequest",t=>{let n=t.detail.name,i=lt.get(n);i?.finalize()})}return Ar}async function Ko(r,e){let t,n,i=new Promise((s,a)=>{t=s,n=a}),o=()=>{n(new ce)};return e?.signal?.addEventListener("abort",o,{once:!0}),r.add(async()=>{await new Promise(s=>{t(()=>{e?.signal?.removeEventListener("abort",o),s()})})},{signal:e?.signal}).catch(s=>{n(s)}),i}var su=(r,e)=>{let t=lt.get(r);if(t!=null)return t;let n=Gd(e);if(ou(n))return t=n,lt.set(r,t),t;let i=new kr({concurrency:1}),o;return t={async readLock(s){if(o!=null)return Ko(o,s);o=new kr({concurrency:e.concurrency,autoStart:!1});let a=o,c=Ko(o,s);return i.add(async()=>{a.start(),await a.onIdle().then(()=>{o===a&&(o=null)})}),c},async writeLock(s){return o=null,Ko(i,s)},finalize:()=>{lt.delete(r)},queue:i},lt.set(r,t),e.autoFinalize===!0&&i.addEventListener("idle",()=>{t.finalize()},{once:!0}),t};var Jd={name:"lock",concurrency:1/0,singleProcess:!1,autoFinalize:!1};function zo(r){let e=Object.assign({},Jd,r);return su(e.name,e)}var ai=class{lock;child;pins;routing;started;constructor(e,t,n,i={}){this.child=e,this.pins=t,this.routing=n,this.lock=zo({singleProcess:i.holdGcLock}),this.started=!1}isStarted(){return this.started}async start(){await qe(this.child),this.started=!0}async stop(){await je(this.child),this.started=!1}unwrap(){return this.child}async put(e,t,n={}){n?.signal?.throwIfAborted();let i=await this.lock.readLock();try{return await this.child.put(e,t,n)}finally{i()}}async*putMany(e,t={}){t?.signal?.throwIfAborted();let n=await this.lock.readLock();try{yield*this.child.putMany(e,t)}finally{n()}}async*get(e,t={}){t?.signal?.throwIfAborted();let n=await this.lock.readLock();try{yield*this.child.get(e,t)}finally{n()}}async*getMany(e,t={}){t?.signal?.throwIfAborted();let n=await this.lock.readLock();try{yield*this.child.getMany(e,t)}finally{n()}}async delete(e,t={}){t?.signal?.throwIfAborted();let n=await this.lock.writeLock();try{if(await this.pins.isPinned(e))throw new vr("Block was pinned - please unpin and try again");await this.routing.cancelReprovide(e,t),await this.child.delete(e,t)}finally{n()}}async*deleteMany(e,t={}){t?.signal?.throwIfAborted();let n=await this.lock.writeLock();try{let i=this;yield*this.child.deleteMany((async function*(){for await(let o of e){if(await i.pins.isPinned(o))throw new vr("Block was pinned - please unpin and try again");await i.routing.cancelReprovide(o,t),yield o}})(),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 qo=new B("/version"),au=1;async function cu(r){if(!await r.has(qo)){await r.put(qo,L(`${au}`));return}let e=await r.get(qo),t=ue(e);if(parseInt(t,10)!==au)throw new Rn("Invalid datastore version, a datastore migration may be required")}var Wo={};F(Wo,{code:()=>Ho,decode:()=>op,decodeOptions:()=>rp,encode:()=>ip,encodeOptions:()=>ep,name:()=>np,toByteView:()=>lu});var uu=42;function lu(r){return r instanceof ArrayBuffer?new Uint8Array(r,0,r.byteLength):r}function Qd(r){if(r.asCID!==r&&r["/"]!==r.bytes)return null;let e=v.asCID(r);if(!e)return null;let t=new Uint8Array(e.bytes.byteLength+1);return t.set(e.bytes,1),[new p(u.tag,uu),new p(u.bytes,t)]}function Yd(){throw new Error("`undefined` is not supported by the IPLD Data Model and cannot be encoded")}function Xd(r){if(Number.isNaN(r))throw new Error("`NaN` is not supported by the IPLD Data Model and cannot be encoded");if(r===1/0||r===-1/0)throw new Error("`Infinity` and `-Infinity` is not supported by the IPLD Data Model and cannot be encoded");return null}function Zd(r){for(let e of r.keys())if(typeof e!="string"||e.length===0)throw new Error("Non-string Map keys are not supported by the IPLD Data Model and cannot be encoded");return null}var jo={float64:!0,typeEncoders:{Map:Zd,Object:Qd,undefined:Yd,number:Xd}},ep={...jo,typeEncoders:{...jo.typeEncoders}};function tp(r){let e=r();if(e[0]!==0)throw new Error("Invalid CID for CBOR tag 42; expected leading 0x00");return v.decode(e.subarray(1))}var Vo={allowIndefinite:!1,coerceUndefinedToNull:!0,allowNaN:!1,allowInfinity:!1,allowBigInt:!0,strict:!0,useMaps:!1,rejectDuplicateMapKeys:!0,tags:{[uu]:tp}},rp={...Vo,tags:{...Vo.tags}},np="dag-cbor",Ho=113,ip=r=>st(r,jo),op=r=>Ie(lu(r),Vo);var Zo={};F(Zo,{code:()=>Xo,decode:()=>du,encode:()=>hu,format:()=>yp,name:()=>mp,parse:()=>wp,stringify:()=>yp});var Go=class extends Array{constructor(){super(),this.inRecursive=[]}prefix(e){let t=this.inRecursive[this.inRecursive.length-1];t&&(u.equals(t.type,u.array)&&(t.elements++,t.elements!==1&&e.push([44])),u.equals(t.type,u.map)&&(t.elements++,t.elements!==1&&(t.elements%2===1?e.push([44]):e.push([58]))))}[u.uint.major](e,t){this.prefix(e);let n=String(t.value),i=[];for(let o=0;o<n.length;o++)i[o]=n.charCodeAt(o);e.push(i)}[u.negint.major](e,t){this[u.uint.major](e,t)}[u.bytes.major](e,t){throw new Error(`${Le} unsupported type: Uint8Array`)}[u.string.major](e,t){this.prefix(e);let n=St(JSON.stringify(t.value));e.push(n.length>32?it(n):n)}[u.array.major](e,t){this.prefix(e),this.inRecursive.push({type:u.array,elements:0}),e.push([91])}[u.map.major](e,t){this.prefix(e),this.inRecursive.push({type:u.map,elements:0}),e.push([123])}[u.tag.major](e,t){}[u.float.major](e,t){if(t.type.name==="break"){let s=this.inRecursive.pop();if(s){if(u.equals(s.type,u.array))e.push([93]);else if(u.equals(s.type,u.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(`${Le} 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),i=[],o=!1;for(let s=0;s<n.length;s++)i[s]=n.charCodeAt(s),!o&&(i[s]===46||i[s]===101||i[s]===69)&&(o=!0);o||(i.push(46),i.push(48)),e.push(i)}};function sp(r,e){if(Array.isArray(r[0])||Array.isArray(e[0]))throw new Error(`${Le} complex map keys are not supported`);let t=r[0],n=e[0];if(t.type!==u.string||n.type!==u.string)throw new Error(`${Le} non-string map keys are not supported`);if(t<n)return-1;if(t>n)return 1;throw new Error(`${Le} unexpected duplicate map keys, this is not supported`)}var ap={addBreakTokens:!0,mapSorter:sp};function Jo(r,e){return e=Object.assign({},ap,e),In(r,new Go,e)}var Nt=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(`${y} 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(`${y} unexpected token at position ${this._pos}, expected to find '${String.fromCharCode(...e)}'`)}parseNumber(){let e=this._pos,t=!1,n=!1,i=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 p(u.uint,0,this._pos-e);if(i([48,49,50,51,52,53,54,55,56,57]),t&&this._pos===e+1)throw new Error(`${y} unexpected token at position ${this._pos}`);if(!this.done()&&this.ch()===46){if(n)throw new Error(`${y} unexpected token at position ${this._pos}`);n=!0,this._pos++,i([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++,i([48,49,50,51,52,53,54,55,56,57]));let o=String.fromCharCode.apply(null,this.data.subarray(e,this._pos)),s=parseFloat(o);return n?new p(u.float,s,this._pos-e):this.options.allowBigInt!==!0||Number.isSafeInteger(s)?new p(s>=0?u.uint:u.negint,s,this._pos-e):new p(s>=0?u.uint:u.negint,BigInt(o),this._pos-e)}parseString(){if(this.ch()!==34)throw new Error(`${y} unexpected character at position ${this._pos}; this shouldn't happen`);this._pos++;for(let o=this._pos,s=0;o<this.data.length&&s<65536;o++,s++){let a=this.data[o];if(a===92||a<32||a>=128)break;if(a===34){let c=String.fromCharCode.apply(null,this.data.subarray(this._pos,o));return this._pos=o+1,new p(u.string,c,s)}}let e=this._pos,t=[],n=()=>{if(this._pos+4>=this.data.length)throw new Error(`${y} unexpected end of unicode escape sequence at position ${this._pos}`);let o=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(`${y} unexpected unicode escape character at position ${this._pos}`);o=o*16+a,this._pos++}return o},i=()=>{let o=this.ch(),s=null,a=o>239?4:o>223?3:o>191?2:1;if(this._pos+a>this.data.length)throw new Error(`${y} unexpected unicode sequence at position ${this._pos}`);let c,f,l,h;switch(a){case 1:o<128&&(s=o);break;case 2:c=this.data[this._pos+1],(c&192)===128&&(h=(o&31)<<6|c&63,h>127&&(s=h));break;case 3:c=this.data[this._pos+1],f=this.data[this._pos+2],(c&192)===128&&(f&192)===128&&(h=(o&15)<<12|(c&63)<<6|f&63,h>2047&&(h<55296||h>57343)&&(s=h));break;case 4:c=this.data[this._pos+1],f=this.data[this._pos+2],l=this.data[this._pos+3],(c&192)===128&&(f&192)===128&&(l&192)===128&&(h=(o&15)<<18|(c&63)<<12|(f&63)<<6|l&63,h>65535&&h<1114112&&(s=h))}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 o=this.ch(),s;switch(o){case 92:if(this._pos++,this.done())throw new Error(`${y} 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(`${y} unexpected string escape character at position ${this._pos}`)}break;case 34:return this._pos++,new p(u.string,Ya(t),this._pos-e);default:if(o<32)throw new Error(`${y} invalid control character at position ${this._pos}`);o<128?(t.push(o),this._pos++):i()}}throw new Error(`${y} unexpected end of string at position ${this._pos}`)}parseValue(){switch(this.ch()){case 123:return this.modeStack.push("obj-start"),this._pos++,new p(u.map,1/0,1);case 91:return this.modeStack.push("array-start"),this._pos++,new p(u.array,1/0,1);case 34:return this.parseString();case 110:return this.expect([110,117,108,108]),new p(u.null,null,4);case 102:return this.expect([102,97,108,115,101]),new p(u.false,!1,5);case 116:return this.expect([116,114,117,101]),new p(u.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(`${y} 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 p(u.break,void 0,1);if(this.ch()!==44)throw new Error(`${y} 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 p(u.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 p(u.break,void 0,1);if(this.ch()!==44)throw new Error(`${y} 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 p(u.break,void 0,1);let e=this.parseString();if(this.skipWhitespace(),this.ch()!==58)throw new Error(`${y} 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(`${y} unexpected parse state at position ${this._pos}; this shouldn't happen`)}}};function Qo(r,e){return e=Object.assign({tokenizer:new Nt(r,e)},e),Ie(r,e)}function up(r){return r instanceof ArrayBuffer?new Uint8Array(r,0,r.byteLength):r}function lp(r){if(r.asCID!==r&&r["/"]!==r.bytes)return null;let e=v.asCID(r);if(!e)return null;let t=e.toString();return[new p(u.map,1/0,1),new p(u.string,"/",1),new p(u.string,t,t.length),new p(u.break,void 0,1)]}function ci(r){let e=V.encode(r).slice(1);return[new p(u.map,1/0,1),new p(u.string,"/",1),new p(u.map,1/0,1),new p(u.string,"bytes",5),new p(u.string,e,e.length),new p(u.break,void 0,1),new p(u.break,void 0,1)]}function Ce(r){return ci(new Uint8Array(r.buffer,r.byteOffset,r.byteLength))}function fp(r){return ci(new Uint8Array(r))}function hp(){throw new Error("`undefined` is not supported by the IPLD Data Model and cannot be encoded")}function dp(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 pp={typeEncoders:{Object:lp,Buffer:ci,Uint8Array:ci,Int8Array:Ce,Uint16Array:Ce,Int16Array:Ce,Uint32Array:Ce,Int32Array:Ce,Float32Array:Ce,Float64Array:Ce,Uint8ClampedArray:Ce,BigInt64Array:Ce,BigUint64Array:Ce,DataView:Ce,ArrayBuffer:fp,undefined:hp,number:dp}},Yo=class extends Nt{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(u.equals(e.type,u.map)){let t=this._next();if(u.equals(t.type,u.string)&&t.value==="/"){let n=this._next();if(u.equals(n.type,u.string)){let i=this._next();if(!u.equals(i.type,u.break))throw new Error("Invalid encoded CID form");return this.tokenBuffer.push(n),new p(u.tag,42,0)}if(u.equals(n.type,u.map)){let i=this._next();if(u.equals(i.type,u.string)&&i.value==="bytes"){let o=this._next();if(u.equals(o.type,u.string)){for(let a=0;a<2;a++){let c=this._next();if(!u.equals(c.type,u.break))throw new Error("Invalid encoded Bytes form")}let s=V.decode(`m${o.value}`);return new p(u.bytes,s,o.value.length)}this.tokenBuffer.push(o)}this.tokenBuffer.push(i)}this.tokenBuffer.push(n)}this.tokenBuffer.push(t)}return e}},fu={allowIndefinite:!1,allowUndefined:!1,allowNaN:!1,allowInfinity:!1,allowBigInt:!0,strict:!0,useMaps:!1,rejectDuplicateMapKeys:!0,tags:{42:r=>v.parse(r())}},mp="dag-json",Xo=297,hu=r=>Jo(r,pp),du=r=>{let e=up(r),t=Object.assign(fu,{tokenizer:new Yo(e,fu)});return Qo(e,t)},yp=r=>gp.decode(hu(r));var gp=new TextDecoder,wp=r=>du(bp.encode(r)),bp=new TextEncoder;var os={};F(os,{code:()=>is,createLink:()=>_u,createNode:()=>vu,decode:()=>Pp,encode:()=>Dp,name:()=>Lp,prepare:()=>rs,validate:()=>ns});var xp=new TextDecoder;function es(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 i=r[e++];if(t+=n<28?(i&127)<<n:(i&127)*2**n,i<128)break}return[t,e]}function ui(r,e){let t;[t,e]=es(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 pu(r,e){let t;return[t,e]=es(r,e),[t&7,t>>3,e]}function Ep(r){let e={},t=r.length,n=0;for(;n<t;){let i,o;if([i,o,n]=pu(r,n),o===1){if(e.Hash)throw new Error("protobuf: (PBLink) duplicate Hash section");if(i!==2)throw new Error(`protobuf: (PBLink) wrong wireType (${i}) 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]=ui(r,n)}else if(o===2){if(e.Name!==void 0)throw new Error("protobuf: (PBLink) duplicate Name section");if(i!==2)throw new Error(`protobuf: (PBLink) wrong wireType (${i}) for Name`);if(e.Tsize!==void 0)throw new Error("protobuf: (PBLink) invalid order, found Tsize before Name");let s;[s,n]=ui(r,n),e.Name=xp.decode(s)}else if(o===3){if(e.Tsize!==void 0)throw new Error("protobuf: (PBLink) duplicate Tsize section");if(i!==0)throw new Error(`protobuf: (PBLink) wrong wireType (${i}) for Tsize`);[e.Tsize,n]=es(r,n)}else throw new Error(`protobuf: (PBLink) invalid fieldNumber, expected 1, 2 or 3, got ${o}`)}if(n>t)throw new Error("protobuf: (PBLink) unexpected end of data");return e}function mu(r){let e=r.length,t=0,n,i=!1,o;for(;t<e;){let a,c;if([a,c,t]=pu(r,t),a!==2)throw new Error(`protobuf: (PBNode) invalid wireType, expected 2, got ${a}`);if(c===1){if(o)throw new Error("protobuf: (PBNode) duplicate Data section");[o,t]=ui(r,t),n&&(i=!0)}else if(c===2){if(i)throw new Error("protobuf: (PBNode) duplicate Links section");n||(n=[]);let f;[f,t]=ui(r,t),n.push(Ep(f))}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 o&&(s.Data=o),s.Links=n||[],s}var gu=new TextEncoder,yu=2**32,vp=2**31;function _p(r,e){let t=e.length;if(typeof r.Tsize=="number"){if(r.Tsize<0)throw new Error("Tsize cannot be negative");if(!Number.isSafeInteger(r.Tsize))throw new Error("Tsize too large for encoding");t=Sr(e,t,r.Tsize)-1,e[t]=24}if(typeof r.Name=="string"){let n=gu.encode(r.Name);t-=n.length,e.set(n,t),t=Sr(e,t,n.length)-1,e[t]=18}return r.Hash&&(t-=r.Hash.length,e.set(r.Hash,t),t=Sr(e,t,r.Hash.length)-1,e[t]=10),e.length-t}function wu(r){let e=Ap(r),t=new Uint8Array(e),n=e;if(r.Data&&(n-=r.Data.length,t.set(r.Data,n),n=Sr(t,n,r.Data.length)-1,t[n]=10),r.Links)for(let i=r.Links.length-1;i>=0;i--){let o=_p(r.Links[i],t.subarray(0,n));n-=o,n=Sr(t,n,o)-1,t[n]=18}return t}function kp(r){let e=0;if(r.Hash){let t=r.Hash.length;e+=1+t+Rt(t)}if(typeof r.Name=="string"){let t=gu.encode(r.Name).length;e+=1+t+Rt(t)}return typeof r.Tsize=="number"&&(e+=1+Rt(r.Tsize)),e}function Ap(r){let e=0;if(r.Data){let t=r.Data.length;e+=1+t+Rt(t)}if(r.Links)for(let t of r.Links){let n=kp(t);e+=1+n+Rt(n)}return e}function Sr(r,e,t){e-=Rt(t);let n=e;for(;t>=vp;)r[e++]=t&127|128,t/=128;for(;t>=128;)r[e++]=t&127|128,t>>>=7;return r[e]=t,n}function Rt(r){return r%2===0&&r++,Math.floor((Sp(r)+6)/7)}function Sp(r){let e=0;return r>=yu&&(r=Math.floor(r/yu),e=32),r>=65536&&(r>>>=16,e+=16),r>=256&&(r>>>=8,e+=8),e+Ip[r]}var Ip=[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 Cp=["Data","Links"],Tp=["Hash","Name","Tsize"],ts=new TextEncoder;function xu(r,e){if(r===e)return 0;let t=r.Name?ts.encode(r.Name):[],n=e.Name?ts.encode(e.Name):[],i=t.length,o=n.length;for(let s=0,a=Math.min(i,o);s<a;++s)if(t[s]!==n[s]){i=t[s],o=n[s];break}return i<o?-1:o<i?1:0}function bu(r,e){return!Object.keys(r).some(t=>!e.includes(t))}function Eu(r){if(typeof r.asCID=="object"){let t=v.asCID(r);if(!t)throw new TypeError("Invalid DAG-PB form");return{Hash:t}}if(typeof r!="object"||Array.isArray(r))throw new TypeError("Invalid DAG-PB form");let e={};if(r.Hash){let t=v.asCID(r.Hash);try{t||(typeof r.Hash=="string"?t=v.parse(r.Hash):r.Hash instanceof Uint8Array&&(t=v.decode(r.Hash)))}catch(n){throw new TypeError(`Invalid DAG-PB form: ${n.message}`)}t&&(e.Hash=t)}if(!e.Hash)throw new TypeError("Invalid DAG-PB form");return typeof r.Name=="string"&&(e.Name=r.Name),typeof r.Tsize=="number"&&(e.Tsize=r.Tsize),e}function rs(r){if((r instanceof Uint8Array||typeof r=="string")&&(r={Data:r}),typeof r!="object"||Array.isArray(r))throw new TypeError("Invalid DAG-PB form");let e={};if(r.Data!==void 0)if(typeof r.Data=="string")e.Data=ts.encode(r.Data);else if(r.Data instanceof Uint8Array)e.Data=r.Data;else throw new TypeError("Invalid DAG-PB form");if(r.Links!==void 0)if(Array.isArray(r.Links))e.Links=r.Links.map(Eu),e.Links.sort(xu);else throw new TypeError("Invalid DAG-PB form");else e.Links=[];return e}function ns(r){if(!r||typeof r!="object"||Array.isArray(r)||r instanceof Uint8Array||r["/"]&&r["/"]===r.bytes)throw new TypeError("Invalid DAG-PB form");if(!bu(r,Cp))throw new TypeError("Invalid DAG-PB form (extraneous properties)");if(r.Data!==void 0&&!(r.Data instanceof Uint8Array))throw new TypeError("Invalid DAG-PB form (Data must be bytes)");if(!Array.isArray(r.Links))throw new TypeError("Invalid DAG-PB form (Links must be a list)");for(let e=0;e<r.Links.length;e++){let t=r.Links[e];if(!t||typeof t!="object"||Array.isArray(t)||t instanceof Uint8Array||t["/"]&&t["/"]===t.bytes)throw new TypeError("Invalid DAG-PB form (bad link)");if(!bu(t,Tp))throw new TypeError("Invalid DAG-PB form (extraneous properties on link)");if(t.Hash===void 0)throw new TypeError("Invalid DAG-PB form (link must have a Hash)");if(t.Hash==null||!t.Hash["/"]||t.Hash["/"]!==t.Hash.bytes)throw new TypeError("Invalid DAG-PB form (link Hash must be a CID)");if(t.Name!==void 0&&typeof t.Name!="string")throw new TypeError("Invalid DAG-PB form (link Name must be a string)");if(t.Tsize!==void 0){if(typeof t.Tsize!="number"||t.Tsize%1!==0)throw new TypeError("Invalid DAG-PB form (link Tsize must be an integer)");if(t.Tsize<0)throw new TypeError("Invalid DAG-PB form (link Tsize cannot be negative)")}if(e>0&&xu(t,r.Links[e-1])===-1)throw new TypeError("Invalid DAG-PB form (links must be sorted by Name bytes)")}}function vu(r,e=[]){return rs({Data:r,Links:e})}function _u(r,e,t){return Eu({Hash:t,Name:r,Tsize:e})}function ku(r){return r instanceof ArrayBuffer?new Uint8Array(r,0,r.byteLength):r}var Lp="dag-pb",is=112;function Dp(r){ns(r);let e={};return r.Links&&(e.Links=r.Links.map(t=>{let n={};return t.Hash&&(n.Hash=t.Hash.bytes),t.Name!==void 0&&(n.Name=t.Name),t.Tsize!==void 0&&(n.Tsize=t.Tsize),n})),r.Data&&(e.Data=r.Data),wu(e)}function Pp(r){let e=ku(r),t=mu(e),n={};return t.Data&&(n.Data=t.Data),t.Links&&(n.Links=t.Links.map(i=>{let o={};try{o.Hash=v.decode(i.Hash)}catch{}if(!o.Hash)throw new Error("Invalid Hash field found in link, expected CID");return i.Name!==void 0&&(o.Name=i.Name),i.Tsize!==void 0&&(o.Tsize=i.Tsize),o})),n}function Je(r){return r?.then!=null}function Au(r=[],e){let t={[is]:os,[$t]:Ot,[Ho]:Wo,[Xo]:Zo,[Bi]:Dr};return r.forEach(n=>{t[n.code]=n}),async n=>{let i=t[n];if(i==null&&e!=null){let o=e(n);Je(o)?i=await o:i=o,t[i.code]=i}if(i!=null)return i;throw new Kn(`Could not load codec for ${n}`)}}function Su(r=[],e){let t={};return r=[eo(),ro(),Zt(),...r],r.forEach(n=>{t[n.type]=n,t[n.code]=n}),async n=>{let i=t[n];if(i==null&&e!=null){let o=e(n);Je(o)?i=await o:i=o,t[i.type]=i,t[i.code]=i}if(i!=null)return i;throw new zn(`Could not load crypto for ${i}`)}}function Iu(r=[],e){let t={[ze.code]:ze,[Rr.code]:Rr,[Ke.code]:Ke};return r.forEach(n=>{t[n.code]=n}),async n=>{let i=t[n];if(i==null&&e!=null){let o=e(n);Je(o)?i=await o:i=o,t[i.code]=i}if(i!=null)return i;throw new On(`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 li=0,Bt=class extends Error{static name="IdentityHashDigestTooLongError";name="IdentityHashDigestTooLongError"},fi=class extends Be{child;maxDigestLength;constructor(e,t){super(),this.child=e,this.maxDigestLength=t?.maxDigestLength}put(e,t,n){if(e.multihash.code===li){if(this.maxDigestLength!=null&&e.multihash.digest.byteLength>this.maxDigestLength)throw new Bt(`Identity digest too long - ${e.multihash.digest.byteLength} > this.maxDigestLength`);return n?.signal?.throwIfAborted(),e}return this.child==null?(n?.signal?.throwIfAborted(),e):this.child.put(e,t,n)}async*get(e,t){if(e.multihash.code===li){if(this.maxDigestLength!=null&&e.multihash.digest.byteLength>this.maxDigestLength)throw new Bt(`Identity digest too long - ${e.multihash.digest.byteLength} > this.maxDigestLength`);t?.signal?.throwIfAborted(),yield e.multihash.digest;return}if(this.child==null)throw t?.signal?.throwIfAborted(),new fe;yield*this.child.get(e,t)}has(e,t){if(e.multihash.code===li){if(this.maxDigestLength!=null&&e.multihash.digest.byteLength>this.maxDigestLength)throw new Bt(`Identity digest too long - ${e.multihash.digest.byteLength} > this.maxDigestLength`);return t?.signal?.throwIfAborted(),!0}return this.child==null?(t?.signal?.throwIfAborted(),!1):this.child.has(e,t)}delete(e,t){if(e.code===li){if(this.maxDigestLength!=null&&e.multihash.digest.byteLength>this.maxDigestLength)throw new Bt(`Identity digest too long - ${e.multihash.digest.byteLength} > this.maxDigestLength`);t?.signal?.throwIfAborted();return}if(this.child!=null)return this.child.delete(e,t)}async*getAll(e){this.child!=null&&(yield*this.child.getAll(e)),e?.signal?.throwIfAborted()}};function Np(r){return r[Symbol.asyncIterator]!=null}function Cu(r){return r?.then!=null}function Rp(r,e){let t=0;if(Np(r))return(async function*(){for await(let c of r){let f=e(c,t++);Cu(f)&&await f,yield c}})();let n=cr(r),{value:i,done:o}=n.next();if(o===!0)return(function*(){})();let s=e(i,t++);if(typeof s?.then=="function")return(async function*(){await s,yield i;for(let c of n){let f=e(c,t++);Cu(f)&&await f,yield c}})();let a=e;return(function*(){yield i;for(let c of n)a(c,t++),yield c})()}var ss=Rp;var Fp=128,Ft=class{child;getHasher;log;logger;blockBrokers;constructor(e,t={}){this.log=e.logger.forComponent("helia:networked-storage"),this.logger=e.logger,this.blockBrokers=e.blockBrokers,this.child=new fi(e.blockstore,{maxDigestLength:t.maxIdentityHashDigestLength??Fp}),this.getHasher=e.getHasher}async put(e,t,n={}){return await this.child.has(e,n)?(n.onProgress?.(new x("blocks:put:duplicate",e)),e):(n.onProgress?.(new x("blocks:put:providers:notify",e)),await Promise.all(this.blockBrokers.map(async i=>i.announce?.(e,n))),n.onProgress?.(new x("blocks:put:blockstore:put",e)),this.child.put(e,t,n))}async*putMany(e,t={}){let n=re(e,async({cid:o})=>{let s=await this.child.has(o,t);return s&&t.onProgress?.(new x("blocks:put-many:duplicate",o)),!s}),i=ss(n,async({cid:o})=>{t.onProgress?.(new x("blocks:put-many:providers:notify",o)),await Promise.all(this.blockBrokers.map(async s=>s.announce?.(o,t)))});t.onProgress?.(new x("blocks:put-many:blockstore:put-many")),yield*this.child.putMany(i,t)}async*get(e,t={}){let n=await this.child.has(e,t),i=t.offline===!0;if(!n){if(i)throw new _r("The block was present in the blockstore and the node is running offline so cannot fetch it");let o=await this.getHasher(e.multihash.code);t?.signal?.throwIfAborted(),t.onProgress?.(new x("blocks:get:providers:get",e));let s=await Tu(e,this.blockBrokers,o,{...t,log:this.log});t.onProgress?.(new x("blocks:get:blockstore:put",e)),await this.child.put(e,s,t),t.onProgress?.(new x("blocks:get:providers:notify",e)),await Promise.all(this.blockBrokers.map(async a=>a.announce?.(e,t))),yield s;return}t.onProgress?.(new x("blocks:get:blockstore:get",e)),yield*this.child.get(e,t)}async*getMany(e,t={}){t.onProgress?.(new x("blocks:get-many:blockstore:get-many")),yield*this.child.getMany(ss(e,async n=>{let i=await this.child.has(n,t),o=t.offline===!0;if(!i){if(o)throw new _r("The block was present in the blockstore and the node is running offline so cannot fetch it");let s=await this.getHasher(n.multihash.code);t?.signal?.throwIfAborted(),t.onProgress?.(new x("blocks:get-many:providers:get",n));let a=await Tu(n,this.blockBrokers,s,{...t,log:this.log});t.onProgress?.(new x("blocks:get-many:blockstore:put",n)),await this.child.put(n,a,t),t.onProgress?.(new x("blocks:get-many:providers:notify",n)),await Promise.all(this.blockBrokers.map(async c=>c.announce?.(n,t)))}}))}async delete(e,t={}){t.onProgress?.(new x("blocks:delete:blockstore:delete",e)),await this.child.delete(e,t)}async*deleteMany(e,t={}){t.onProgress?.(new x("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 x("blocks:get-all:blockstore:get-many")),yield*this.child.getAll(e)}};async function Tu(r,e,t,n){let i=Mp(r,t),o=new AbortController,s=ke([o.signal,n.signal]);o.signal;let a=[];for(let c of e)Up(c)&&a.push(c);if(a.length===0)throw new at(`No block brokers capable of retrieving blocks are configured, the CID ${r} cannot be fetched from the network`);try{return await Promise.any(a.map(async c=>{try{let f=!1,l=await c.retrieve(r,{...n,signal:s,validateFn:async h=>{await i(h),n.signal?.throwIfAborted(),f=!0}});return f||(await i(l),n.signal?.throwIfAborted()),l}catch(f){throw n.log.error("could not retrieve verified block for %c from %s - %e",r,c.name,f),f}}))}catch(c){throw new Fn(c.errors,`Failed to load block for ${r}`)}finally{o.abort(),s.clear()}}function Up(r){return typeof r.retrieve=="function"}var Mp=(r,e)=>{if(e==null)throw new _t(`No hasher configured for multihash code 0x${r.multihash.code.toString(16)}, please configure one. You can look up which hash this is at https://github.com/multiformats/multicodec/blob/master/table.csv`);return async t=>{let n,i=e.digest(t,{truncate:r.multihash.digest.byteLength});if(Je(i)?n=await i:n=i,!Re(n.digest,r.multihash.digest))throw new Zr("Hash of downloaded block did not match multihash from passed CID")}};var hi=class extends Ft{closeController;constructor(e,t){super(e),this.closeController=new AbortController,this.closeController.signal,this.log=e.logger.forComponent(`helia:session-storage:${t.root}`)}close(){this.closeController.abort()}async addPeer(e,t){await Promise.all(this.blockBrokers.map(n=>n.addPeer(e,t)))}async put(e,t,n={}){let i=ke([this.closeController.signal,n.signal]);try{return await super.put(e,t,{...n,signal:i})}finally{i.clear()}}async*putMany(e,t={}){let n=ke([this.closeController.signal,t.signal]);try{yield*super.putMany(e,{...t,signal:n})}finally{n.clear()}}async*get(e,t={}){let n=ke([this.closeController.signal,t.signal]);try{yield*super.get(e,{...t,signal:n})}finally{n.clear()}}async*getMany(e,t={}){let n=ke([this.closeController.signal,t.signal]);try{yield*super.getMany(e,{...t,signal:n})}finally{n.clear()}}async delete(e,t={}){let n=ke([this.closeController.signal,t.signal]);try{await super.delete(e,{...t,signal:n})}finally{n.clear()}}async*deleteMany(e,t={}){let n=ke([this.closeController.signal,t.signal]);try{yield*super.deleteMany(e,{...t,signal:n})}finally{n.clear()}}async has(e,t={}){let n=ke([this.closeController.signal,t.signal]);try{return await super.has(e,{...t,signal:n})}finally{n.clear()}}async*getAll(e={}){let t=ke([this.closeController.signal,e.signal]);try{yield*super.getAll({...e,signal:t})}finally{t.clear()}}};var di=class extends Ft{started;constructor(e,t={}){super(e,t),this.started=!1}isStarted(){return this.started}async start(){await qe(this.child,...this.blockBrokers),this.started=!0}async stop(){await je(this.child,...this.blockBrokers),this.started=!1}unwrap(){return this.child}createSession(e,t){if(this.blockBrokers.length===0)throw new at("No block brokers configured");let n=this.blockBrokers.map(i=>i.createSession?.(t)).filter(i=>i!=null);if(n.length===0)throw new at(`No configured block brokers support sessions - tried ${this.blockBrokers.map(i=>i.name).join(", ")}`);return new hi({blockstore:this.child,blockBrokers:n,getHasher:this.getHasher,logger:this.logger},{root:e})}};var pi=class extends le{initialPeerSearchComplete;requests;logName;log;logger;minProviders;maxProviders;providers;evictionFilter;initialProviders;cidPeerFilterSize;constructor(e,t){super(),this.logName=t.name,this.logger=e.logger,this.log=e.logger.forComponent(this.logName),this.requests=new Map,this.minProviders=t.minProviders??1,this.maxProviders=t.maxProviders??5,this.cidPeerFilterSize=t.cidPeerFilterSize??100,this.providers=[],this.evictionFilter=hn(this.maxProviders),this.initialProviders=[...t.providers??[]]}async retrieve(e,t={}){let n=V.encode(e.multihash.bytes),i=this.requests.get(n);if(i!=null)return this.log("join existing request for %c",e),i.observers++,i.promise;let o=X(),s={promise:o.promise,observers:1,queryFilter:hn(this.cidPeerFilterSize)};this.requests.set(n,s);let a=!1;this.initialPeerSearchComplete==null&&(a=!0,this.log=this.logger.forComponent(`${this.logName}:${e}`),this.initialPeerSearchComplete=this.findProviders(e,this.minProviders,t));let c=!1,f=new ne({concurrency:this.maxProviders});f.addEventListener("failure",d=>{this.log.error("error querying provider %s, evicting from session - %e",d.detail.job.options.provider,d.detail.error),this.evict(d.detail.job.options.provider)}),f.addEventListener("success",d=>{c=!0,o.resolve(d.detail.result)}),f.addEventListener("idle",()=>{if(c){this.log.trace("session idle, found block");return}if(t.signal?.aborted===!0){this.log.trace("session idle, signal aborted");return}Promise.resolve().then(async()=>{this.log("no session peers had block for for %c, finding new providers",e);for(let d=0;d<this.minProviders&&this.providers.length!==0;d++){let g=this.providers[Math.floor(Math.random()*this.providers.length)];this.evict(g)}await this.findProviders(e,this.minProviders,t),this.log("found new providers re-retrieving %c",e),this.requests.delete(n),o.resolve(await this.retrieve(e,t))}).catch(d=>{this.log.error("could not find new providers for %c - %e",e,d),o.reject(d)})});let l=d=>{let g=this.toFilterKey(d.detail);s.queryFilter.has(g)||(s.queryFilter.add(g),this.emitFoundProviderProgressEvent(e,d.detail,t),f.add(async()=>this.queryProvider(e,d.detail,t),{provider:d.detail}).catch(w=>{t.signal?.aborted!==!0&&this.log.error("error retrieving session block for %c - %e",e,w)}))};if(this.addEventListener("provider",l),a)try{await Ve(this.initialPeerSearchComplete,t.signal),a&&this.log("found initial session peers for %c",e)}catch(d){throw a&&this.log("failed to find initial session peers for %c - %e",e,d),this.requests.delete(n),s.observers>1&&o.reject(d),d}Promise.all([...this.providers].filter(d=>{let g=this.toFilterKey(d),w=s.queryFilter.has(g);return w||s.queryFilter.add(this.toFilterKey(d)),!w}).map(async d=>f.add(async()=>this.queryProvider(e,d,t),{provider:d}))).catch(d=>{t.signal?.aborted!==!0&&this.log.error("error retrieving session block for %c - %e",e,d)});let h=()=>{o.reject(new Ee(t.signal?.reason??"Session aborted")),f.abort()};t.signal?.addEventListener("abort",h);try{return await o.promise}finally{this.removeEventListener("provider",l),t.signal?.removeEventListener("abort",h),f.clear(),this.requests.delete(n)}}evict(e){this.evictionFilter.add(this.toFilterKey(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.toFilterKey(e))}hasProvider(e){return!!(this.providers.find(t=>this.equals(t,e))!=null||this.isEvicted(e))}async addPeer(e,t){let n=await this.convertToProvider(e,"manually-added",t);n==null||this.hasProvider(n)||(this.providers.push(n),this.safeDispatchEvent("provider",{detail:n}))}async findProviders(e,t,n){let i=X(),o=0;return Promise.resolve().then(async()=>{this.log("finding %d-%d new provider(s) for %c - %d initial providers",t,this.maxProviders,e,this.initialProviders.length);let s=this,a=async function*(){for(;s.initialProviders.length>0;){let f=s.initialProviders.pop();if(f==null)continue;let l=await s.convertToProvider(f,"manual",n);l!=null&&(yield l)}},c=async function*(){yield*a(),yield*s.findNewProviders(e,n)};for await(let f of c()){if(this.providers.length===this.maxProviders||n.signal?.aborted===!0)break;if(!this.hasProvider(f)&&(this.log("found %d providers, %d in session",o,this.providers.length),this.providers.push(f),this.safeDispatchEvent("provider",{detail:f}),o++,this.providers.length===t&&(this.log("session is ready with %d peer(s), new peers present",this.providers.length),i.resolve()),this.providers.length===this.maxProviders)){this.log("found max session peers %d",this.providers.length);break}}if(this.log("found %d new session peers while trying to find %d, %d in session",o,t,this.providers.length),this.providers.length<t)throw new $n(`Found ${o} of ${t} ${this.name} providers for ${e}, ${this.providers.length} in session after evictions`)}).catch(s=>{this.log.error("error searching routing for potential session peers for %c - %e",e,s),i.reject(s)}),i.promise}};function Lu(r){return r==null?!1:v.asCID(r)!=null}function Du(r){return e=>new as(e,r)}function Pu(r){return e=>new cs(e,r)}function Nu(r){return e=>new us(e,r)}var Ir=class{components;constructor(e,t={}){this.components=e}async*walk(e,t){let n=this.getQueue(),i=re(n.toGenerator(t),a=>a!=null),o=!1,s=async a=>{let c=a.cid,f=await Ln(this.components.blockstore.get(c,a)),l=Pn({cid:c,bytes:f,codec:await this.components.getCodec(c.code)});for(let[,h]of l.links())t?.includeChild?.(h,l)!==!1&&n.add(s,{...a,cid:h,depth:a.depth+1,path:[...a.path,h]}).catch(d=>{o||i.throw(d)});return{block:l,depth:a.depth,path:a.path}};n.add(s,{...t,cid:e,depth:0,path:[e]}).catch(a=>{o||i.throw(a)});try{yield*i}finally{o=!0,n.abort()}}},as=class extends Ir{getQueue(){return new ne({concurrency:1,sort:(e,t)=>e.options.depth===t.options.depth?0:e.options.depth<t.options.depth?1:-1})}},cs=class extends Ir{getQueue(){return new ne({concurrency:1,sort:(e,t)=>e.options.depth===t.options.depth?0:e.options.depth<t.options.depth?-1:1})}},us=class extends Ir{getQueue(){return new ne({concurrency:1})}};var ls=class{info;blockstore;datastore;events;pins;logger;routing;getCodec;getHasher;getCrypto;dns;keychain;metrics;status;log;blockBrokers;mixins;constructor(e){this.info={name:e.name,version:e.version},this.logger=e.logger??Ba(),this.log=this.logger.forComponent("helia"),this.getHasher=Iu(e.hashers,e.loadHasher),this.getCodec=Au(e.codecs,e.loadCodec),this.getCrypto=Su(e.cryptos,e.loadCrypto),this.dns=e.dns??La(),this.metrics=e.metrics,this.events=new le,this.status="stopped",this.mixins=[];let t={blockstore:e.blockstore??new sr,datastore:e.datastore??new lr,logger:this.logger,blockBrokers:[],getHasher:this.getHasher,getCodec:this.getCodec,getCrypto:this.getCrypto,dns:this.dns,metrics:this.metrics,...e.components??{}};this.keychain=t.keychain=xa()(t),this.routing=t.routing=new qn(t,{routers:(e.routers??[]).flatMap(i=>(typeof i=="function"&&(i=i(t)),[i])),providerLookupConcurrency:e.providerLookupConcurrency}),this.blockBrokers=t.blockBrokers=(e.blockBrokers??[]).map(i=>(typeof i=="function"&&(i=i(t)),i));let n=new di(t,e);this.pins=new Mn(t.datastore,n,this.getCodec),this.blockstore=new ai(n,this.pins,this.routing,{holdGcLock:e.holdGcLock??!0}),this.datastore=t.datastore}hasRouter(e){return this.routing.hasRouter(e)}addRouter(e){this.routing.addRouter(e)}hasBlockBroker(e){return this.blockBrokers.findIndex(t=>t.name===e)!==-1}addBlockBroker(e){this.blockBrokers.push(e)}addMixin(e){this.mixins.push(e)}async start(){this.status="starting",await cu(this.datastore),await qe(this.blockstore,this.datastore,this.routing,...this.blockBrokers);for(let e of this.mixins)await e.start?.(this);return this.status="started",this.events.dispatchEvent(new CustomEvent("start",{detail:this})),this}async stop(){this.status="stopping";for(let e of this.mixins)await e.stop?.(this);return await je(this.blockstore,this.datastore,this.routing,...this.blockBrokers),this.status="stopped",this.events.dispatchEvent(new CustomEvent("stop",{detail:this})),this}async gc(e={}){let t=await this.blockstore.lock.writeLock();try{let n=this,i=this.blockstore.unwrap();this.log("gc start"),await ur(i.deleteMany((async function*(){for await(let{cid:o}of i.getAll())try{if(await n.pins.isPinned(o,e))continue;yield o,e.onProgress?.(new x("helia:gc:deleted",o))}catch(s){n.log.error("error during gc - %e",s),e.onProgress?.(new x("helia:gc:error",s))}})()))}finally{t()}this.log("gc finished")}};return Ou(zp);})();
24
24
  return HeliaUtils}));
25
25
  //# sourceMappingURL=index.min.js.map