@helia/utils 1.4.0-061f3cdb → 1.4.0-1071f986

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,5 +1,5 @@
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 js=Object.create;var ft=Object.defineProperty;var Vs=Object.getOwnPropertyDescriptor;var Ks=Object.getOwnPropertyNames;var Hs=Object.getPrototypeOf,Ws=Object.prototype.hasOwnProperty;var lo=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),T=(r,e)=>{for(var t in e)ft(r,t,{get:e[t],enumerable:!0})},fo=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Ks(e))!Ws.call(r,o)&&o!==t&&ft(r,o,{get:()=>e[o],enumerable:!(n=Vs(e,o))||n.enumerable});return r};var ho=(r,e,t)=>(t=r!=null?js(Hs(r)):{},fo(e||!r||!r.__esModule?ft(t,"default",{value:r,enumerable:!0}):t,r)),Gs=r=>fo(ft({},"__esModule",{value:!0}),r);var Ao=lo((Ql,Wr)=>{"use strict";var Sa=Object.prototype.hasOwnProperty,R="~";function Ke(){}Object.create&&(Ke.prototype=Object.create(null),new Ke().__proto__||(R=!1));function Ia(r,e,t){this.fn=r,this.context=e,this.once=t||!1}function ko(r,e,t,n,o){if(typeof t!="function")throw new TypeError("The listener must be a function");var i=new Ia(t,n||r,o),s=R?R+e:e;return r._events[s]?r._events[s].fn?r._events[s]=[r._events[s],i]:r._events[s].push(i):(r._events[s]=i,r._eventsCount++),r}function yt(r,e){--r._eventsCount===0?r._events=new Ke:delete r._events[e]}function N(){this._events=new Ke,this._eventsCount=0}N.prototype.eventNames=function(){var e=[],t,n;if(this._eventsCount===0)return e;for(n in t=this._events)Sa.call(t,n)&&e.push(R?n.slice(1):n);return Object.getOwnPropertySymbols?e.concat(Object.getOwnPropertySymbols(t)):e};N.prototype.listeners=function(e){var t=R?R+e:e,n=this._events[t];if(!n)return[];if(n.fn)return[n.fn];for(var o=0,i=n.length,s=new Array(i);o<i;o++)s[o]=n[o].fn;return s};N.prototype.listenerCount=function(e){var t=R?R+e:e,n=this._events[t];return n?n.fn?1:n.length:0};N.prototype.emit=function(e,t,n,o,i,s){var a=R?R+e:e;if(!this._events[a])return!1;var u=this._events[a],d=arguments.length,l,f;if(u.fn){switch(u.once&&this.removeListener(e,u.fn,void 0,!0),d){case 1:return u.fn.call(u.context),!0;case 2:return u.fn.call(u.context,t),!0;case 3:return u.fn.call(u.context,t,n),!0;case 4:return u.fn.call(u.context,t,n,o),!0;case 5:return u.fn.call(u.context,t,n,o,i),!0;case 6:return u.fn.call(u.context,t,n,o,i,s),!0}for(f=1,l=new Array(d-1);f<d;f++)l[f-1]=arguments[f];u.fn.apply(u.context,l)}else{var g=u.length,y;for(f=0;f<g;f++)switch(u[f].once&&this.removeListener(e,u[f].fn,void 0,!0),d){case 1:u[f].fn.call(u[f].context);break;case 2:u[f].fn.call(u[f].context,t);break;case 3:u[f].fn.call(u[f].context,t,n);break;case 4:u[f].fn.call(u[f].context,t,n,o);break;default:if(!l)for(y=1,l=new Array(d-1);y<d;y++)l[y-1]=arguments[y];u[f].fn.apply(u[f].context,l)}}return!0};N.prototype.on=function(e,t,n){return ko(this,e,t,n,!1)};N.prototype.once=function(e,t,n){return ko(this,e,t,n,!0)};N.prototype.removeListener=function(e,t,n,o){var i=R?R+e:e;if(!this._events[i])return this;if(!t)return yt(this,i),this;var s=this._events[i];if(s.fn)s.fn===t&&(!o||s.once)&&(!n||s.context===n)&&yt(this,i);else{for(var a=0,u=[],d=s.length;a<d;a++)(s[a].fn!==t||o&&!s[a].once||n&&s[a].context!==n)&&u.push(s[a]);u.length?this._events[i]=u.length===1?u[0]:u:yt(this,i)}return this};N.prototype.removeAllListeners=function(e){var t;return e?(t=R?R+e:e,this._events[t]&&yt(this,t)):(this._events=new Ke,this._eventsCount=0),this};N.prototype.off=N.prototype.removeListener;N.prototype.addListener=N.prototype.on;N.prefixed=R;N.EventEmitter=N;typeof Wr<"u"&&(Wr.exports=N)});var Wo=lo((rh,Ho)=>{Ho.exports=function(r){if(!r)throw Error("hashlru must have a max value, of type number, greater than 0");var e=0,t=Object.create(null),n=Object.create(null);function o(i,s){t[i]=s,e++,e>=r&&(e=0,n=t,t=Object.create(null))}return{has:function(i){return t[i]!==void 0||n[i]!==void 0},remove:function(i){t[i]!==void 0&&(t[i]=void 0),n[i]!==void 0&&(n[i]=void 0)},get:function(i){var s=t[i];if(s!==void 0)return s;if((s=n[i])!==void 0)return o(i,s),s},set:function(i,s){t[i]!==void 0?t[i]=s:o(i,s)},clear:function(){t=Object.create(null),n=Object.create(null)}}}});var xl={};T(xl,{AbstractSession:()=>Ur,Helia:()=>uo});var Br=Symbol.for("@libp2p/content-routing");var J=class extends Error{static name="AbortError";constructor(e="The operation was aborted"){super(e),this.name="AbortError"}};var ht=class extends Error{static name="InvalidParametersError";constructor(e="Invalid parameters"){super(e),this.name="InvalidParametersError"}};var dt=class extends Error{static name="NotFoundError";constructor(e="Not found"){super(e),this.name="NotFoundError"}};var pt=class extends Error{static name="InvalidMultihashError";constructor(e="Invalid Multihash"){super(e),this.name="InvalidMultihashError"}};var Fr=Symbol.for("@libp2p/peer-routing");function po(r){return r!=null&&typeof r.start=="function"&&typeof r.stop=="function"}async function he(...r){let e=[];for(let t of r)po(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 de(...r){let e=[];for(let t of r)po(t)&&e.push(t);await Promise.all(e.map(async t=>{t.beforeStop!=null&&await t.beforeStop()})),await Promise.all(e.map(async t=>{await t.stop()})),await Promise.all(e.map(async t=>{t.afterStop!=null&&await t.afterStop()}))}var H=class extends EventTarget{#e=new Map;constructor(){super()}listenerCount(e){let t=this.#e.get(e);return t==null?0:t.length}addEventListener(e,t,n){super.addEventListener(e,t,n);let o=this.#e.get(e);o==null&&(o=[],this.#e.set(e,o)),o.push({callback:t,once:(n!==!0&&n!==!1&&n?.once)??!1})}removeEventListener(e,t,n){super.removeEventListener(e.toString(),t??null,n);let o=this.#e.get(e);o!=null&&(o=o.filter(({callback:i})=>i!==t),this.#e.set(e,o))}dispatchEvent(e){let t=super.dispatchEvent(e),n=this.#e.get(e.type);return n==null||(n=n.filter(({once:o})=>!o),this.#e.set(e.type,n)),t}safeDispatchEvent(e,t={}){return this.dispatchEvent(new CustomEvent(e,t))}};var jr={};T(jr,{base32:()=>me,base32hex:()=>oa,base32hexpad:()=>sa,base32hexpadupper:()=>aa,base32hexupper:()=>ia,base32pad:()=>ra,base32padupper:()=>na,base32upper:()=>ta,base32z:()=>ca});var Sl=new Uint8Array(0);function mo(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 Y(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength);throw new Error("Unknown type, must be binary type")}function go(r){return new TextEncoder().encode(r)}function yo(r){return new TextDecoder().decode(r)}function Qs(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),n=0;n<t.length;n++)t[n]=255;for(var o=0;o<r.length;o++){var i=r.charAt(o),s=i.charCodeAt(0);if(t[s]!==255)throw new TypeError(i+" is ambiguous");t[s]=o}var a=r.length,u=r.charAt(0),d=Math.log(a)/Math.log(256),l=Math.log(256)/Math.log(a);function f(b){if(b instanceof Uint8Array||(ArrayBuffer.isView(b)?b=new Uint8Array(b.buffer,b.byteOffset,b.byteLength):Array.isArray(b)&&(b=Uint8Array.from(b))),!(b instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(b.length===0)return"";for(var x=0,w=0,_=0,C=b.length;_!==C&&b[_]===0;)_++,x++;for(var S=(C-_)*l+1>>>0,I=new Uint8Array(S);_!==C;){for(var F=b[_],V=0,O=S-1;(F!==0||V<w)&&O!==-1;O--,V++)F+=256*I[O]>>>0,I[O]=F%a>>>0,F=F/a>>>0;if(F!==0)throw new Error("Non-zero carry");w=V,_++}for(var K=S-w;K!==S&&I[K]===0;)K++;for(var Ie=u.repeat(x);K<S;++K)Ie+=r.charAt(I[K]);return Ie}function g(b){if(typeof b!="string")throw new TypeError("Expected String");if(b.length===0)return new Uint8Array;var x=0;if(b[x]!==" "){for(var w=0,_=0;b[x]===u;)w++,x++;for(var C=(b.length-x)*d+1>>>0,S=new Uint8Array(C);b[x];){var I=t[b.charCodeAt(x)];if(I===255)return;for(var F=0,V=C-1;(I!==0||F<_)&&V!==-1;V--,F++)I+=a*S[V]>>>0,S[V]=I%256>>>0,I=I/256>>>0;if(I!==0)throw new Error("Non-zero carry");_=F,x++}if(b[x]!==" "){for(var O=C-_;O!==C&&S[O]===0;)O++;for(var K=new Uint8Array(w+(C-O)),Ie=w;O!==C;)K[Ie++]=S[O++];return K}}}function y(b){var x=g(b);if(x)return x;throw new Error(`Non-${e} character`)}return{encode:f,decodeUnsafe:g,decode:y}}var Js=Qs,Ys=Js,wo=Ys;var zr=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")}},Mr=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,n){this.name=e,this.prefix=t;let o=t.codePointAt(0);if(o===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=o,this.baseDecode=n}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return bo(this,e)}},$r=class{decoders;constructor(e){this.decoders=e}or(e){return bo(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 bo(r,e){return new $r({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var qr=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,n,o){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=o,this.encoder=new zr(e,t,n),this.decoder=new Mr(e,t,o)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function Te({name:r,prefix:e,encode:t,decode:n}){return new qr(r,e,t,n)}function pe({name:r,prefix:e,alphabet:t}){let{encode:n,decode:o}=wo(t,r);return Te({prefix:e,name:r,encode:n,decode:i=>Y(o(i))})}function Xs(r,e,t,n){let o=r.length;for(;r[o-1]==="=";)--o;let i=new Uint8Array(o*t/8|0),s=0,a=0,u=0;for(let d=0;d<o;++d){let l=e[r[d]];if(l===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<t|l,s+=t,s>=8&&(s-=8,i[u++]=255&a>>s)}if(s>=t||(255&a<<8-s)!==0)throw new SyntaxError("Unexpected end of data");return i}function Zs(r,e,t){let n=e[e.length-1]==="=",o=(1<<t)-1,i="",s=0,a=0;for(let u=0;u<r.length;++u)for(a=a<<8|r[u],s+=8;s>t;)s-=t,i+=e[o&a>>s];if(s!==0&&(i+=e[o&a<<t-s]),n)for(;(i.length*t&7)!==0;)i+="=";return i}function ea(r){let e={};for(let t=0;t<r.length;++t)e[r[t]]=t;return e}function A({name:r,prefix:e,bitsPerChar:t,alphabet:n}){let o=ea(n);return Te({prefix:e,name:r,encode(i){return Zs(i,n,t)},decode(i){return Xs(i,o,t,r)}})}var me=A({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),ta=A({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),ra=A({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),na=A({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),oa=A({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),ia=A({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),sa=A({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),aa=A({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),ca=A({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Vr={};T(Vr,{base58btc:()=>W,base58flickr:()=>ua});var W=pe({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),ua=pe({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var Kr={};T(Kr,{base64:()=>ge,base64pad:()=>la,base64url:()=>fa,base64urlpad:()=>ha});var ge=A({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),la=A({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),fa=A({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),ha=A({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});function da(r,e){if(typeof r=="string")return pa(r);if(typeof r=="number")return ya(r,e);throw Error(`Value provided to ms() must be a string or number. value=${JSON.stringify(r)}`)}var mt=da;function pa(r){if(typeof r!="string"||r.length===0||r.length>100)throw Error(`Value provided to ms.parse() must be a string with length between 1 and 99. value=${JSON.stringify(r)}`);let e=/^(?<value>-?\d*\.?\d+) *(?<unit>milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|months?|mo|years?|yrs?|y)?$/i.exec(r);if(!e?.groups)return NaN;let{value:t,unit:n="ms"}=e.groups,o=parseFloat(t),i=n.toLowerCase();switch(i){case"years":case"year":case"yrs":case"yr":case"y":return o*315576e5;case"months":case"month":case"mo":return o*26298e5;case"weeks":case"week":case"w":return o*6048e5;case"days":case"day":case"d":return o*864e5;case"hours":case"hour":case"hrs":case"hr":case"h":return o*36e5;case"minutes":case"minute":case"mins":case"min":case"m":return o*6e4;case"seconds":case"second":case"secs":case"sec":case"s":return o*1e3;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return o;default:throw Error(`Unknown unit "${i}" provided to ms.parse(). value=${JSON.stringify(r)}`)}}function ma(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 ga(r){let e=Math.abs(r);return e>=315576e5?be(r,e,315576e5,"year"):e>=26298e5?be(r,e,26298e5,"month"):e>=6048e5?be(r,e,6048e5,"week"):e>=864e5?be(r,e,864e5,"day"):e>=36e5?be(r,e,36e5,"hour"):e>=6e4?be(r,e,6e4,"minute"):e>=1e3?be(r,e,1e3,"second"):`${r} ms`}function ya(r,e){if(typeof r!="number"||!Number.isFinite(r))throw Error("Value provided to ms.format() must be of type number.");return e?.long?ga(r):ma(r)}function be(r,e,t,n){let o=e>=t*1.5;return`${Math.round(r/t)} ${n}${o?"s":""}`}function Hr(r){t.debug=t,t.default=t,t.coerce=u,t.disable=i,t.enable=o,t.enabled=s,t.humanize=mt,t.destroy=d,Object.keys(r).forEach(l=>{t[l]=r[l]}),t.names=[],t.skips=[],t.formatters={};function e(l){let f=0;for(let g=0;g<l.length;g++)f=(f<<5)-f+l.charCodeAt(g),f|=0;return t.colors[Math.abs(f)%t.colors.length]}t.selectColor=e;function t(l){let f,g=null,y,b;function x(...w){if(!x.enabled)return;let _=x,C=Number(new Date),S=C-(f||C);_.diff=S,_.prev=f,_.curr=C,f=C,w[0]=t.coerce(w[0]),typeof w[0]!="string"&&w.unshift("%O");let I=0;w[0]=w[0].replace(/%([a-zA-Z%])/g,(V,O)=>{if(V==="%%")return"%";I++;let K=t.formatters[O];if(typeof K=="function"){let Ie=w[I];V=K.call(_,Ie),w.splice(I,1),I--}return V}),t.formatArgs.call(_,w),(_.log||t.log).apply(_,w)}return x.namespace=l,x.useColors=t.useColors(),x.color=t.selectColor(l),x.extend=n,x.destroy=t.destroy,Object.defineProperty(x,"enabled",{enumerable:!0,configurable:!1,get:()=>g!==null?g:(y!==t.namespaces&&(y=t.namespaces,b=t.enabled(l)),b),set:w=>{g=w}}),typeof t.init=="function"&&t.init(x),x}function n(l,f){let g=t(this.namespace+(typeof f>"u"?":":f)+l);return g.log=this.log,g}function o(l){t.save(l),t.namespaces=l,t.names=[],t.skips=[];let f,g=(typeof l=="string"?l:"").split(/[\s,]+/),y=g.length;for(f=0;f<y;f++)g[f]&&(l=g[f].replace(/\*/g,".*?"),l[0]==="-"?t.skips.push(new RegExp("^"+l.substr(1)+"$")):t.names.push(new RegExp("^"+l+"$")))}function i(){let l=[...t.names.map(a),...t.skips.map(a).map(f=>"-"+f)].join(",");return t.enable(""),l}function s(l){if(l[l.length-1]==="*")return!0;let f,g;for(f=0,g=t.skips.length;f<g;f++)if(t.skips[f].test(l))return!1;for(f=0,g=t.names.length;f<g;f++)if(t.names[f].test(l))return!0;return!1}function a(l){return l.toString().substring(2,l.toString().length-2).replace(/\.\*\?$/,"*")}function u(l){return l instanceof Error?l.stack??l.message:l}function d(){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 gt=ka(),wa=["#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 ba(){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 xa(r){if(r[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+r[0]+(this.useColors?"%c ":" ")+"+"+mt(this.diff),!this.useColors)return;let e="color: "+this.color;r.splice(1,0,e,"color: inherit");let t=0,n=0;r[0].replace(/%[a-zA-Z%]/g,o=>{o!=="%%"&&(t++,o==="%c"&&(n=t))}),r.splice(n,0,e)}var Ea=console.debug??console.log??(()=>{});function va(r){try{r?gt?.setItem("debug",r):gt?.removeItem("debug")}catch{}}function _a(){let r;try{r=gt?.getItem("debug")}catch{}return!r&&typeof globalThis.process<"u"&&"env"in globalThis.process&&(r=globalThis.process.env.DEBUG),r}function ka(){try{return localStorage}catch{}}function Aa(r){r.j=function(e){try{return JSON.stringify(e)}catch(t){return"[UnexpectedJSONParseError]: "+t.message}}}var xo=Hr({formatArgs:xa,save:va,load:_a,useColors:ba,setupFormatters:Aa,colors:wa,storage:gt,log:Ea});var D=xo;D.formatters.b=r=>r==null?"undefined":W.baseEncode(r);D.formatters.t=r=>r==null?"undefined":me.baseEncode(r);D.formatters.m=r=>r==null?"undefined":ge.baseEncode(r);D.formatters.p=r=>r==null?"undefined":r.toString();D.formatters.c=r=>r==null?"undefined":r.toString();D.formatters.k=r=>r==null?"undefined":r.toString();D.formatters.a=r=>r==null?"undefined":r.toString();D.formatters.e=r=>{if(r==null)return"undefined";let e=Eo(r.message),t=Eo(r.stack);return e!=null&&t!=null?t.includes(e)?t:`${e}
3
- ${t}`:t??e??r.toString()};function Ca(r){let e=()=>{};return e.enabled=!1,e.color="",e.diff=0,e.log=()=>{},e.namespace=r,e.destroy=()=>!0,e.extend=()=>e,e}function vo(){return{forComponent(r){return _o(r)}}}function _o(r){let e=Ca(`${r}:trace`);return D.enabled(`${r}:trace`)&&D.names.map(t=>t.toString()).find(t=>t.includes(":trace"))!=null&&(e=D(`${r}:trace`)),Object.assign(D(r),{error:D(`${r}:error`),trace:e,newScope:t=>_o(`${r}:${t}`)})}function Eo(r){if(r!=null&&(r=r.trim(),r.length!==0))return r}var v=class extends Event{type;detail;constructor(e,t){super(e),this.type=e,this.detail=t}};var Gr=ho(Ao(),1);var He=class extends Error{constructor(e){super(e),this.name="TimeoutError"}},Qr=class extends Error{constructor(e){super(),this.name="AbortError",this.message=e}},Co=r=>globalThis.DOMException===void 0?new Qr(r):new DOMException(r),So=r=>{let e=r.reason===void 0?Co("This operation was aborted."):r.reason;return e instanceof Error?e:Co(e)};function We(r,e){let{milliseconds:t,fallback:n,message:o,customTimers:i={setTimeout,clearTimeout}}=e,s,a,d=new Promise((l,f)=>{if(typeof t!="number"||Math.sign(t)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${t}\``);if(e.signal){let{signal:y}=e;y.aborted&&f(So(y)),a=()=>{f(So(y))},y.addEventListener("abort",a,{once:!0})}if(t===Number.POSITIVE_INFINITY){r.then(l,f);return}let g=new He;s=i.setTimeout.call(void 0,()=>{if(n){try{l(n())}catch(y){f(y)}return}typeof r.cancel=="function"&&r.cancel(),o===!1?l():o instanceof Error?f(o):(g.message=o??`Promise timed out after ${t} milliseconds`,f(g))},t),(async()=>{try{l(await r)}catch(y){f(y)}})()}).finally(()=>{d.clear(),a&&e.signal&&e.signal.removeEventListener("abort",a)});return d.clear=()=>{i.clearTimeout.call(void 0,s),s=void 0},d}function Jr(r,e,t){let n=0,o=r.length;for(;o>0;){let i=Math.trunc(o/2),s=n+i;t(r[s],e)<=0?(n=++s,o-=i+1):o=i}return n}var Ge=class{#e=[];enqueue(e,t){t={priority:0,...t};let n={priority:t.priority,id:t.id,run:e};if(this.size===0||this.#e[this.size-1].priority>=t.priority){this.#e.push(n);return}let o=Jr(this.#e,n,(i,s)=>s.priority-i.priority);this.#e.splice(o,0,n)}setPriority(e,t){let n=this.#e.findIndex(i=>i.id===e);if(n===-1)throw new ReferenceError(`No promise function with the id "${e}" exists in the queue.`);let[o]=this.#e.splice(n,1);this.enqueue(o.run,{priority:t,id:e})}dequeue(){return this.#e.shift()?.run}filter(e){return this.#e.filter(t=>t.priority===e.priority).map(t=>t.run)}get size(){return this.#e.length}};var Qe=class extends Gr.default{#e;#o;#s=0;#d;#a;#p=0;#r;#c;#t;#m;#n=0;#u;#i;#g;#b=1n;timeout;constructor(e){if(super(),e={carryoverConcurrencyCount:!1,intervalCap:Number.POSITIVE_INFINITY,interval:0,concurrency:Number.POSITIVE_INFINITY,autoStart:!0,queueClass:Ge,...e},!(typeof e.intervalCap=="number"&&e.intervalCap>=1))throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${e.intervalCap?.toString()??""}\` (${typeof e.intervalCap})`);if(e.interval===void 0||!(Number.isFinite(e.interval)&&e.interval>=0))throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${e.interval?.toString()??""}\` (${typeof e.interval})`);this.#e=e.carryoverConcurrencyCount,this.#o=e.intervalCap===Number.POSITIVE_INFINITY||e.interval===0,this.#d=e.intervalCap,this.#a=e.interval,this.#t=new e.queueClass,this.#m=e.queueClass,this.concurrency=e.concurrency,this.timeout=e.timeout,this.#g=e.throwOnTimeout===!0,this.#i=e.autoStart===!1}get#x(){return this.#o||this.#s<this.#d}get#E(){return this.#n<this.#u}#v(){this.#n--,this.#l(),this.emit("next")}#_(){this.#w(),this.#y(),this.#c=void 0}get#k(){let e=Date.now();if(this.#r===void 0){let t=this.#p-e;if(t<0)this.#s=this.#e?this.#n:0;else return this.#c===void 0&&(this.#c=setTimeout(()=>{this.#_()},t)),!0}return!1}#l(){if(this.#t.size===0)return this.#r&&clearInterval(this.#r),this.#r=void 0,this.emit("empty"),this.#n===0&&this.emit("idle"),!1;if(!this.#i){let e=!this.#k;if(this.#x&&this.#E){let t=this.#t.dequeue();return t?(this.emit("active"),t(),e&&this.#y(),!0):!1}}return!1}#y(){this.#o||this.#r!==void 0||(this.#r=setInterval(()=>{this.#w()},this.#a),this.#p=Date.now()+this.#a)}#w(){this.#s===0&&this.#n===0&&this.#r&&(clearInterval(this.#r),this.#r=void 0),this.#s=this.#e?this.#n:0,this.#f()}#f(){for(;this.#l(););}get concurrency(){return this.#u}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.#u=e,this.#f()}async#A(e){return new Promise((t,n)=>{e.addEventListener("abort",()=>{n(e.reason)},{once:!0})})}setPriority(e,t){this.#t.setPriority(e,t)}async add(e,t={}){return t.id??=(this.#b++).toString(),t={timeout:this.timeout,throwOnTimeout:this.#g,...t},new Promise((n,o)=>{this.#t.enqueue(async()=>{this.#n++;try{t.signal?.throwIfAborted(),this.#s++;let i=e({signal:t.signal});t.timeout&&(i=We(Promise.resolve(i),{milliseconds:t.timeout})),t.signal&&(i=Promise.race([i,this.#A(t.signal)]));let s=await i;n(s),this.emit("completed",s)}catch(i){if(i instanceof He&&!t.throwOnTimeout){n();return}o(i),this.emit("error",i)}finally{this.#v()}},t),this.emit("add"),this.#l()})}async addAll(e,t){return Promise.all(e.map(async n=>this.add(n,t)))}start(){return this.#i?(this.#i=!1,this.#f(),this):this}pause(){this.#i=!0}clear(){this.#t=new this.#m}async onEmpty(){this.#t.size!==0&&await this.#h("empty")}async onSizeLessThan(e){this.#t.size<e||await this.#h("next",()=>this.#t.size<e)}async onIdle(){this.#n===0&&this.#t.size===0||await this.#h("idle")}async#h(e,t){return new Promise(n=>{let o=()=>{t&&!t()||(this.off(e,o),n())};this.on(e,o)})}get size(){return this.#t.size}sizeBy(e){return this.#t.filter(e).length}get pending(){return this.#n}get isPaused(){return this.#i}};function wt(r){let e=[X.A];return r==null?e:Array.isArray(r)?r.length===0?e:r:[r]}var Yr={};T(Yr,{base10:()=>Ta});var Ta=pe({prefix:"9",name:"base10",alphabet:"0123456789"});var Xr={};T(Xr,{base16:()=>La,base16upper:()=>Pa});var La=A({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),Pa=A({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var Zr={};T(Zr,{base2:()=>Na});var Na=A({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var en={};T(en,{base256emoji:()=>Fa});var Io=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}"),Ra=Io.reduce((r,e,t)=>(r[t]=e,r),[]),Da=Io.reduce((r,e,t)=>{let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);return r[n]=t,r},[]);function Ua(r){return r.reduce((e,t)=>(e+=Ra[t],e),"")}function Ba(r){let e=[];for(let t of r){let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);let o=Da[n];if(o==null)throw new Error(`Non-base256emoji character: ${t}`);e.push(o)}return new Uint8Array(e)}var Fa=Te({prefix:"\u{1F680}",name:"base256emoji",encode:Ua,decode:Ba});var tn={};T(tn,{base36:()=>se,base36upper:()=>Oa});var se=pe({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Oa=pe({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var rn={};T(rn,{base8:()=>za});var za=A({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var nn={};T(nn,{identity:()=>Ma});var Ma=Te({prefix:"\0",name:"identity",encode:r=>yo(r),decode:r=>go(r)});var bt={};T(bt,{code:()=>on,decode:()=>Ka,encode:()=>Va,name:()=>ja});var $a=new TextEncoder,qa=new TextDecoder,ja="json",on=512;function Va(r){return $a.encode(JSON.stringify(r))}function Ka(r){return JSON.parse(qa.decode(r))}var xt={};T(xt,{code:()=>sn,decode:()=>Ga,encode:()=>Wa,name:()=>Ha});var Ha="raw",sn=85;function Wa(r){return Y(r)}function Ga(r){return Y(r)}var cn={};T(cn,{identity:()=>vt});var Qa=Po,To=128,Ja=127,Ya=~Ja,Xa=Math.pow(2,31);function Po(r,e,t){e=e||[],t=t||0;for(var n=t;r>=Xa;)e[t++]=r&255|To,r/=128;for(;r&Ya;)e[t++]=r&255|To,r>>>=7;return e[t]=r|0,Po.bytes=t-n+1,e}var Za=an,ec=128,Lo=127;function an(r,n){var t=0,n=n||0,o=0,i=n,s,a=r.length;do{if(i>=a)throw an.bytes=0,new RangeError("Could not decode varint");s=r[i++],t+=o<28?(s&Lo)<<o:(s&Lo)*Math.pow(2,o),o+=7}while(s>=ec);return an.bytes=i-n,t}var tc=Math.pow(2,7),rc=Math.pow(2,14),nc=Math.pow(2,21),oc=Math.pow(2,28),ic=Math.pow(2,35),sc=Math.pow(2,42),ac=Math.pow(2,49),cc=Math.pow(2,56),uc=Math.pow(2,63),lc=function(r){return r<tc?1:r<rc?2:r<nc?3:r<oc?4:r<ic?5:r<sc?6:r<ac?7:r<cc?8:r<uc?9:10},fc={encode:Qa,decode:Za,encodingLength:lc},hc=fc,Je=hc;function Ye(r,e=0){return[Je.decode(r,e),Je.decode.bytes]}function Le(r,e,t=0){return Je.encode(r,e,t),e}function Pe(r){return Je.encodingLength(r)}function Re(r,e){let t=e.byteLength,n=Pe(r),o=n+Pe(t),i=new Uint8Array(o+t);return Le(r,i,0),Le(t,i,n),i.set(e,o),new Ne(r,t,e,i)}function No(r){let e=Y(r),[t,n]=Ye(e),[o,i]=Ye(e.subarray(n)),s=e.subarray(n+i);if(s.byteLength!==o)throw new Error("Incorrect length");return new Ne(t,o,s,e)}function Ro(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&mo(r.bytes,t.bytes)}}var Ne=class{code;size;digest;bytes;constructor(e,t,n,o){this.code=e,this.size=t,this.digest=n,this.bytes=o}};var Do=0,dc="identity",Uo=Y;function pc(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 Re(Do,Uo(r))}var vt={code:Do,name:dc,encode:Uo,digest:pc};var fn={};T(fn,{sha256:()=>_t,sha512:()=>kt});var mc=20;function ln({name:r,code:e,encode:t,minDigestLength:n,maxDigestLength:o}){return new un(r,e,t,n,o)}var un=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,n,o,i){this.name=e,this.code=t,this.encode=n,this.minDigestLength=o??mc,this.maxDigestLength=i}digest(e,t){if(t?.truncate!=null){if(t.truncate<this.minDigestLength)throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`);if(this.maxDigestLength!=null&&t.truncate>this.maxDigestLength)throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`)}if(e instanceof Uint8Array){let n=this.encode(e);return n instanceof Uint8Array?Bo(n,this.code,t?.truncate):n.then(o=>Bo(o,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}};function Bo(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 Re(e,r)}function Oo(r){return async e=>new Uint8Array(await crypto.subtle.digest(r,e))}var _t=ln({name:"sha2-256",code:18,encode:Oo("SHA-256")}),kt=ln({name:"sha2-512",code:19,encode:Oo("SHA-512")});function zo(r,e){let{bytes:t,version:n}=r;switch(n){case 0:return yc(t,hn(r),e??W.encoder);default:return wc(t,hn(r),e??me.encoder)}}var Mo=new WeakMap;function hn(r){let e=Mo.get(r);if(e==null){let t=new Map;return Mo.set(r,t),t}return e}var k=class r{code;version;multihash;bytes;"/";constructor(e,t,n,o){this.code=t,this.version=e,this.multihash=n,this.bytes=o,this["/"]=o}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:e,multihash:t}=this;if(e!==Ze)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==bc)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=Re(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&&Ro(e.multihash,n.multihash)}toString(e){return zo(this,e)}toJSON(){return{"/":zo(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(e){if(e==null)return null;let t=e;if(t instanceof r)return t;if(t["/"]!=null&&t["/"]===t.bytes||t.asCID===t){let{version:n,code:o,multihash:i,bytes:s}=t;return new r(n,o,i,s??$o(n,o,i.bytes))}else if(t[xc]===!0){let{version:n,multihash:o,code:i}=t,s=No(o);return r.create(n,i,s)}else return null}static create(e,t,n){if(typeof t!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(e){case 0:{if(t!==Ze)throw new Error(`Version 0 CID must use dag-pb (code: ${Ze}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let o=$o(e,t,n.bytes);return new r(e,t,n,o)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,Ze,e)}static createV1(e,t){return r.create(1,e,t)}static decode(e){let[t,n]=r.decodeFirst(e);if(n.length!==0)throw new Error("Incorrect length");return t}static decodeFirst(e){let t=r.inspectBytes(e),n=t.size-t.multihashSize,o=Y(e.subarray(n,n+t.multihashSize));if(o.byteLength!==t.multihashSize)throw new Error("Incorrect length");let i=o.subarray(t.multihashSize-t.digestSize),s=new Ne(t.multihashCode,t.digestSize,i,o);return[t.version===0?r.createV0(s):r.createV1(t.codec,s),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[f,g]=Ye(e.subarray(t));return t+=g,f},o=n(),i=Ze;if(o===18?(o=0,t=0):i=n(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);let s=t,a=n(),u=n(),d=t+u,l=d-s;return{version:o,codec:i,multihashCode:a,digestSize:u,multihashSize:l,size:d}}static parse(e,t){let[n,o]=gc(e,t),i=r.decode(o);if(i.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return hn(i).set(n,e),i}};function gc(r,e){switch(r[0]){case"Q":{let t=e??W;return[W.prefix,t.decode(`${W.prefix}${r}`)]}case W.prefix:{let t=e??W;return[W.prefix,t.decode(r)]}case me.prefix:{let t=e??me;return[me.prefix,t.decode(r)]}case se.prefix:{let t=e??se;return[se.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 yc(r,e,t){let{prefix:n}=t;if(n!==W.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let o=e.get(n);if(o==null){let i=t.encode(r).slice(1);return e.set(n,i),i}else return o}function wc(r,e,t){let{prefix:n}=t,o=e.get(n);if(o==null){let i=t.encode(r);return e.set(n,i),i}else return o}var Ze=112,bc=18;function $o(r,e,t){let n=Pe(r),o=n+Pe(e),i=new Uint8Array(o+t.byteLength);return Le(r,i,0),Le(e,i,n),i.set(t,o),i}var xc=Symbol.for("@ipld/js-cid/CID");var dn={...nn,...Zr,...rn,...Yr,...Xr,...jr,...tn,...Vr,...Kr,...en},Ff={...fn,...cn};function qo(r=0){return new Uint8Array(r)}function At(r=0){return new Uint8Array(r)}function Vo(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var jo=Vo("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),pn=Vo("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=At(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),Ec={utf8:jo,"utf-8":jo,hex:dn.base16,latin1:pn,ascii:pn,binary:pn,...dn},Ct=Ec;function De(r,e="utf8"){let t=Ct[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.encoder.encode(r).substring(1)}var mn=60;function St(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:X[e.type]})),Answer:(r.Answer??r.answers??[]).map(e=>({name:e.name,type:X[e.type],TTL:e.TTL??e.ttl??mn,data:e.data instanceof Uint8Array?De(e.data):e.data}))}}var vc=4;function gn(r,e={}){let t=new Qe({concurrency:e.queryConcurrency??vc});return async(n,o={})=>{let i=new URLSearchParams;i.set("name",n),wt(o.types).forEach(a=>{i.append("type",X[a])}),o.onProgress?.(new v("dns:query",n));let s=await t.add(async()=>{let a=await fetch(`${r}?${i}`,{headers:{accept:"application/dns-json"},signal:o?.signal});if(a.status!==200)throw new Error(`Unexpected HTTP status: ${a.status} - ${a.statusText}`);let u=St(await a.json());return o.onProgress?.(new v("dns:response",u)),u},{signal:o.signal});if(s==null)throw new Error("No DNS response received");return s}}function Ko(){return[gn("https://cloudflare-dns.com/dns-query"),gn("https://dns.google/resolve")]}var Go=ho(Wo(),1);var yn=class{lru;constructor(e){this.lru=(0,Go.default)(e)}get(e,t){let n=!0,o=[];for(let i of t){let s=this.getAnswers(e,i);if(s.length===0){n=!1;break}o.push(...s)}if(n)return St({answers:o})}getAnswers(e,t){let n=`${e.toLowerCase()}-${t}`,o=this.lru.get(n);if(o!=null){let i=o.filter(s=>s.expires>Date.now()).map(({expires:s,value:a})=>({...a,TTL:Math.round((s-Date.now())/1e3),type:X[a.type]}));return i.length===0&&this.lru.remove(n),i}return[]}add(e,t){let n=`${e.toLowerCase()}-${t.type}`,o=this.lru.get(n)??[];o.push({expires:Date.now()+(t.TTL??mn)*1e3,value:t}),this.lru.set(n,o)}remove(e,t){let n=`${e.toLowerCase()}-${t}`;this.lru.remove(n)}clear(){this.lru.clear()}};function Qo(r){return new yn(r)}var _c=1e3,It=class{resolvers;cache;constructor(e){this.resolvers={},this.cache=Qo(e.cacheSize??_c),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["."]=Ko())}async query(e,t={}){let n=wt(t.types),o=t.cached!==!1?this.cache.get(e,n):void 0;if(o!=null)return t.onProgress?.(new v("dns:cache",o)),o;let i=`${e.split(".").pop()}.`,s=(this.resolvers[i]??this.resolvers["."]).sort(()=>Math.random()>.5?-1:1),a=[];for(let u of s){if(t.signal?.aborted===!0)break;try{let d=await u(e,{...t,types:n});for(let l of d.Answer)this.cache.add(e,l);return d}catch(d){a.push(d),t.onProgress?.(new v("dns:error",d))}}throw a.length===1?a[0]:new AggregateError(a,`DNS lookup of ${e} ${n} failed`)}};var X;(function(r){r[r.A=1]="A",r[r.CNAME=5]="CNAME",r[r.TXT=16]="TXT",r[r.AAAA=28]="AAAA"})(X||(X={}));function Jo(r={}){return new It(r)}function kc(r){return r[Symbol.asyncIterator]!=null}function Ac(r){if(kc(r))return(async()=>{for await(let e of r);})();for(let e of r);}var Yo=Ac;function xe(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 wn(r,e){e==null&&(e=r.reduce((o,i)=>o+i.length,0));let t=At(e),n=0;for(let o of r)t.set(o,n),n+=o.length;return t}function U(r,e="utf8"){let t=Ct[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.decoder.decode(`${t.prefix}${r}`)}var bn={32:16777619n,64:1099511628211n,128:309485009821345068724781371n,256:374144419156711147060143317175368453031918731002211n,512:35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759n,1024:5016456510113118655434598811035278955030765345404790744303017523831112055108147451509157692220295382716162651878526895249385292291816524375083746691371804094271873160484737966720260389217684476157468082573n},Xo={32:2166136261n,64:14695981039346656037n,128:144066263297769815596495629667062367629n,256:100029257958052580907070968620625704837092796014241193945225284501741471925557n,512:9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785n,1024:14197795064947621068722070641403218320880622795441933960878474914617582723252296732303717722150864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915n},Zo=new globalThis.TextEncoder;function Cc(r,e){let t=bn[e],n=Xo[e];for(let o=0;o<r.length;o++)n^=BigInt(r[o]),n=BigInt.asUintN(e,n*t);return n}function Sc(r,e,t){if(t.length===0)throw new Error("The `utf8Buffer` option must have a length greater than zero");let n=bn[e],o=Xo[e],i=r;for(;i.length>0;){let s=Zo.encodeInto(i,t);i=i.slice(s.read);for(let a=0;a<s.written;a++)o^=BigInt(t[a]),o=BigInt.asUintN(e,o*n)}return o}function xn(r,{size:e=32,utf8Buffer:t}={}){if(!bn[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 Sc(r,e,t);r=Zo.encode(r)}return Cc(r,e)}var et={hash:r=>Number(xn(r,{size:32})),hashV:(r,e)=>Ic(et.hash(r,e))};function Ic(r){let e=r.toString(16);return e.length%2===1&&(e=`0${e}`),U(e,"base16")}var En=64,Z=class{fp;h;seed;constructor(e,t,n,o=2){if(o>En)throw new TypeError("Invalid Fingerprint Size");let i=t.hashV(e,n),s=qo(o);for(let a=0;a<s.length;a++)s[a]=i[a];s.length===0&&(s[0]=7),this.fp=s,this.h=t,this.seed=n}hash(){return this.h.hash(this.fp,this.seed)}equals(e){return e?.fp instanceof Uint8Array?xe(this.fp,e.fp):!1}};function Ee(r,e){return Math.floor(Math.random()*(e-r))+r}var ve=class{contents;constructor(e){this.contents=new Array(e).fill(null)}has(e){if(!(e instanceof Z))throw new TypeError("Invalid Fingerprint");return this.contents.some(t=>e.equals(t))}add(e){if(!(e instanceof Z))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 Z))throw new TypeError("Invalid Fingerprint");let t=Ee(0,this.contents.length-1),n=this.contents[t];return this.contents[t]=e,n}remove(e){if(!(e instanceof Z))throw new TypeError("Invalid Fingerprint");let t=this.contents.findIndex(n=>e.equals(n));return t>-1?(this.contents[t]=null,!0):!1}};var Tc=500,tt=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??et,this.seed=e.seed??Ee(0,Math.pow(2,10))}add(e){typeof e=="string"&&(e=U(e));let t=new Z(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,o=(n^t.hash())%this.filterSize;if(this.buckets[n]==null&&(this.buckets[n]=new ve(this.bucketSize)),this.buckets[o]==null&&(this.buckets[o]=new ve(this.bucketSize)),this.buckets[n].add(t)||this.buckets[o].add(t))return this.count++,!0;let i=[n,o],s=i[Ee(0,i.length-1)];this.buckets[s]==null&&(this.buckets[s]=new ve(this.bucketSize));for(let a=0;a<Tc;a++){let u=this.buckets[s].swap(t);if(u!=null&&(s=(s^u.hash())%this.filterSize,this.buckets[s]==null&&(this.buckets[s]=new ve(this.bucketSize)),this.buckets[s].add(u)))return this.count++,!0}return!1}has(e){typeof e=="string"&&(e=U(e));let t=new Z(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,o=this.buckets[n]?.has(t)??!1;if(o)return o;let i=(n^t.hash())%this.filterSize;return this.buckets[i]?.has(t)??!1}remove(e){typeof e=="string"&&(e=U(e));let t=new Z(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,o=this.buckets[n]?.remove(t)??!1;if(o)return this.count--,o;let i=(n^t.hash())%this.filterSize,s=this.buckets[i]?.remove(t)??!1;return s&&this.count--,s}get reliable(){return Math.floor(100*(this.count/this.filterSize))<=90}},Lc={1:.5,2:.84,4:.95,8:.98};function Pc(r=.001){return r>.002?2:r>1e-5?4:8}function ei(r,e=.001){let t=Pc(e),n=Lc[t],o=Math.round(r/n),i=Math.min(Math.ceil(Math.log2(1/e)+Math.log2(2*t)),En);return{filterSize:o,bucketSize:t,fingerprintSize:i}}var Tt=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??et,this.seed=e.seed??Ee(0,Math.pow(2,10)),this.filterSeries=[new tt({filterSize:this.filterSize,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed})]}add(e){if(typeof e=="string"&&(e=U(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 tt({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=U(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=U(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 vn(r,e=.001,t){return new Tt({...ei(r,e),...t??{}})}function B(){let r={};return r.promise=new Promise((e,t)=>{r.resolve=e,r.reject=t}),r}var Lt=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}},Ue=class{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new Lt(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 Lt(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 _n=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}};function Pt(r={}){return Nc(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 Nc(r,e){e=e??{};let t=e.onEnd,n=new Ue,o,i,s,a=B(),u=async()=>{try{return n.isEmpty()?s?{done:!0}:await new Promise((w,_)=>{i=C=>{i=null,n.push(C);try{w(r(n))}catch(S){_(S)}return o}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=B()})}},d=w=>i!=null?i(w):(n.push(w),o),l=w=>(n=new Ue,i!=null?i({error:w}):(n.push({error:w}),o)),f=w=>{if(s)return o;if(e?.objectMode!==!0&&w?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return d({done:!1,value:w})},g=w=>s?o:(s=!0,w!=null?l(w):d({done:!0})),y=()=>(n=new Ue,g(),{done:!0}),b=w=>(g(w),{done:!0});if(o={[Symbol.asyncIterator](){return this},next:u,return:y,throw:b,push:f,end:g,get readableLength(){return n.size},onEmpty:async w=>{let _=w?.signal;if(_?.throwIfAborted(),n.isEmpty())return;let C,S;_!=null&&(C=new Promise((I,F)=>{S=()=>{F(new _n)},_.addEventListener("abort",S)}));try{await Promise.race([a.promise,C])}finally{S!=null&&_!=null&&_?.removeEventListener("abort",S)}}},t==null)return o;let x=o;return o={[Symbol.asyncIterator](){return this},next(){return x.next()},throw(w){return x.throw(w),t!=null&&(t(w),t=void 0),{done:!0}},return(){return x.return(),t!=null&&(t(),t=void 0),{done:!0}},push:f,end(w){return x.end(w),t!=null&&(t(w),t=void 0),o},get readableLength(){return x.readableLength},onEmpty:w=>x.onEmpty(w)},o}var Rc=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 Dc(r,e,t){let n,o=new Promise((i,s)=>{if(t={rejectionEvents:["error"],multiArgs:!1,rejectionMultiArgs:!1,resolveImmediately:!1,...t},!(t.count>=0&&(t.count===Number.POSITIVE_INFINITY||Number.isInteger(t.count))))throw new TypeError("The `count` option should be at least 0 or more");t.signal?.throwIfAborted();let a=[e].flat(),u=[],{addListener:d,removeListener:l}=Rc(r),f=async(...y)=>{let b=t.multiArgs?y:y[0];if(t.filter)try{if(!await t.filter(b))return}catch(x){n(),s(x);return}u.push(b),t.count===u.length&&(n(),i(u))},g=(...y)=>{n(),s(t.rejectionMultiArgs?y:y[0])};n=()=>{for(let y of a)l(y,f);for(let y of t.rejectionEvents)a.includes(y)||l(y,g)};for(let y of a)d(y,f);for(let y of t.rejectionEvents)a.includes(y)||d(y,g);t.signal&&t.signal.addEventListener("abort",()=>{g(t.signal.reason)},{once:!0}),t.resolveImmediately&&i(u)});if(o.cancel=n,typeof t.timeout=="number"){let i=We(o,{milliseconds:t.timeout});return i.cancel=()=>{n(),i.clear()},i}return o}function Nt(r,e,t){typeof t=="function"&&(t={filter:t}),t={...t,count:1,resolveImmediately:!1};let n=Dc(r,e,t),o=n.then(i=>i[0]);return o.cancel=n.cancel,o}function kn(r,e){let t,n=function(){let o=function(){t=void 0,r()};clearTimeout(t),t=setTimeout(o,e)};return n.start=()=>{},n.stop=()=>{clearTimeout(t)},n}var Rt=class extends Error{static name="QueueFullError";constructor(e="The queue was full"){super(e),this.name="QueueFullError"}};function Uc(r){return r.reason}async function ti(r,e,t){if(e==null)return r;let n=t?.translateError??Uc;if(e.aborted)return r.catch(()=>{}),Promise.reject(n(e));let o;try{return await Promise.race([r,new Promise((i,s)=>{o=()=>{s(n(e))},e.addEventListener("abort",o)})])}finally{o!=null&&e.removeEventListener("abort",o)}}var Dt=class{deferred;signal;constructor(e){this.signal=e,this.deferred=B(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new J)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function Bc(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var Ut=class{id;fn;options;recipients;status;timeline;controller;constructor(e,t){this.id=Bc(),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 J),this.cleanup())}async join(e={}){let t=new Dt(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 ti(this.fn({...this.options??{},signal:this.controller.signal}),this.controller.signal);this.recipients.forEach(t=>{t.deferred.resolve(e)}),this.status="complete"}catch(e){this.recipients.forEach(t=>{t.deferred.reject(e)}),this.status="errored"}finally{this.timeline.finished=Date.now(),this.cleanup()}}cleanup(){this.recipients.forEach(e=>{e.cleanup(),e.signal?.removeEventListener("abort",this.onAbort)})}};var ae=class extends H{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=kn(this.emitEmpty.bind(this),1),this.emitIdle=kn(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 Rt;let n=new Ut(e,t);return this.enqueue(n),this.safeDispatchEvent("add"),this.tryToStartAnother(),n.join(t).then(o=>(this.safeDispatchEvent("completed",{detail:o}),this.safeDispatchEvent("success",{detail:{job:n,result:o}}),o)).catch(o=>{if(n.status==="queued"){for(let i=0;i<this.queue.length;i++)if(this.queue[i]===n){this.queue.splice(i,1);break}}throw this.safeDispatchEvent("failure",{detail:{job:n,error:o}}),o})}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(e=>{e.abort(new J)}),this.clear()}async onEmpty(e){this.size!==0&&await Nt(this,"empty",e)}async onSizeLessThan(e,t){this.size<e||await Nt(this,"next",{...t,filter:()=>this.size<e})}async onIdle(e){this.pending===0&&this.size===0||await Nt(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=Pt({objectMode:!0}),n=u=>{u!=null?this.abort():this.clear(),t.end(u)},o=u=>{u.detail!=null&&t.push(u.detail)},i=u=>{n(u.detail.error)},s=()=>{n()},a=()=>{n(new J("Queue aborted"))};this.addEventListener("completed",o),this.addEventListener("failure",i),this.addEventListener("idle",s),e?.signal?.addEventListener("abort",a);try{yield*t}finally{this.removeEventListener("completed",o),this.removeEventListener("failure",i),this.removeEventListener("idle",s),e?.signal?.removeEventListener("abort",a),n()}}};function oe(r){let e=new globalThis.AbortController;function t(){e.abort();for(let i of r)i?.removeEventListener!=null&&i.removeEventListener("abort",t)}for(let i of r){if(i?.aborted===!0){t();break}i?.addEventListener!=null&&i.addEventListener("abort",t)}function n(){for(let i of r)i?.removeEventListener!=null&&i.removeEventListener("abort",t)}let o=e.signal;return o.clear=n,o}var Bt=class extends Error{type;code;constructor(e,t,n){super(e??"The operation was aborted"),this.type="aborted",this.name=n??"AbortError",this.code=t??"ABORT_ERR"}};async function ri(r,e,t){if(e==null)return r;if(e.aborted)return r.catch(()=>{}),Promise.reject(new Bt(t?.errorMessage,t?.errorCode,t?.errorName));let n,o=new Bt(t?.errorMessage,t?.errorCode,t?.errorName);try{return await Promise.race([r,new Promise((i,s)=>{n=()=>{s(o)},e.addEventListener("abort",n)})])}finally{n!=null&&e.removeEventListener("abort",n)}}var An=class{readNext;haveNext;ended;nextResult;error;constructor(){this.ended=!1,this.readNext=B(),this.haveNext=B()}[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=B(),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=B(),await ri(this.readNext.promise,t?.signal,t)}};function ni(){return new An}function Fc(r){return r[Symbol.asyncIterator]!=null}async function Oc(r,e,t){try{await Promise.all(r.map(async n=>{for await(let o of n)await e.push(o,{signal:t}),t.throwIfAborted()})),await e.end(void 0,{signal:t})}catch(n){await e.end(n,{signal:t}).catch(()=>{})}}async function*zc(r){let e=new AbortController,t=ni();Oc(r,t,e.signal).catch(()=>{});try{yield*t}finally{e.abort()}}function*Mc(r){for(let e of r)yield*e}function $c(...r){let e=[];for(let t of r)Fc(t)||e.push(t);return e.length===r.length?Mc(e):zc(r)}var Ft=$c;var qc=["string","number","bigint","symbol"],jc=["Function","Generator","AsyncGenerator","GeneratorFunction","AsyncGeneratorFunction","AsyncFunction","Observable","Array","Buffer","Object","RegExp","Date","Error","Map","Set","WeakMap","WeakSet","ArrayBuffer","SharedArrayBuffer","DataView","Promise","URL","HTMLElement","Int8Array","Uint8Array","Uint8ClampedArray","Int16Array","Uint16Array","Int32Array","Uint32Array","Float32Array","Float64Array","BigInt64Array","BigUint64Array"];function oi(r){if(r===null)return"null";if(r===void 0)return"undefined";if(r===!0||r===!1)return"boolean";let e=typeof r;if(qc.includes(e))return e;if(e==="function")return"Function";if(Array.isArray(r))return"Array";if(Vc(r))return"Buffer";let t=Kc(r);return t||"Object"}function Vc(r){return r&&r.constructor&&r.constructor.isBuffer&&r.constructor.isBuffer.call(null,r)}function Kc(r){let e=Object.prototype.toString.call(r).slice(8,-1);if(jc.includes(e))return e}var c=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}};c.uint=new c(0,"uint",!0);c.negint=new c(1,"negint",!0);c.bytes=new c(2,"bytes",!0);c.string=new c(3,"string",!0);c.array=new c(4,"array",!1);c.map=new c(5,"map",!1);c.tag=new c(6,"tag",!1);c.float=new c(7,"float",!0);c.false=new c(7,"false",!0);c.true=new c(7,"true",!0);c.null=new c(7,"null",!0);c.undefined=new c(7,"undefined",!0);c.break=new c(7,"break",!0);var h=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 Be=globalThis.process&&!globalThis.process.browser&&globalThis.Buffer&&typeof globalThis.Buffer.isBuffer=="function",Hc=new TextDecoder,Wc=new TextEncoder;function Ot(r){return Be&&globalThis.Buffer.isBuffer(r)}function rt(r){return r instanceof Uint8Array?Ot(r)?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):r:Uint8Array.from(r)}var ci=Be?(r,e,t)=>t-e>64?globalThis.Buffer.from(r.subarray(e,t)).toString("utf8"):si(r,e,t):(r,e,t)=>t-e>64?Hc.decode(r.subarray(e,t)):si(r,e,t),zt=Be?r=>r.length>64?globalThis.Buffer.from(r):ii(r):r=>r.length>64?Wc.encode(r):ii(r),ie=r=>Uint8Array.from(r),Fe=Be?(r,e,t)=>Ot(r)?new Uint8Array(r.subarray(e,t)):r.slice(e,t):(r,e,t)=>r.slice(e,t),ui=Be?(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 o of r)n+o.length>t.length&&(o=o.subarray(0,t.length-n)),t.set(o,n),n+=o.length;return t},li=Be?r=>globalThis.Buffer.allocUnsafe(r):r=>new Uint8Array(r);function fi(r,e){if(Ot(r)&&Ot(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 ii(r){let e=[],t=0;for(let n=0;n<r.length;n++){let o=r.charCodeAt(n);o<128?e[t++]=o:o<2048?(e[t++]=o>>6|192,e[t++]=o&63|128):(o&64512)===55296&&n+1<r.length&&(r.charCodeAt(n+1)&64512)===56320?(o=65536+((o&1023)<<10)+(r.charCodeAt(++n)&1023),e[t++]=o>>18|240,e[t++]=o>>12&63|128,e[t++]=o>>6&63|128,e[t++]=o&63|128):(e[t++]=o>>12|224,e[t++]=o>>6&63|128,e[t++]=o&63|128)}return e}function si(r,e,t){let n=[];for(;e<t;){let o=r[e],i=null,s=o>239?4:o>223?3:o>191?2:1;if(e+s<=t){let a,u,d,l;switch(s){case 1:o<128&&(i=o);break;case 2:a=r[e+1],(a&192)===128&&(l=(o&31)<<6|a&63,l>127&&(i=l));break;case 3:a=r[e+1],u=r[e+2],(a&192)===128&&(u&192)===128&&(l=(o&15)<<12|(a&63)<<6|u&63,l>2047&&(l<55296||l>57343)&&(i=l));break;case 4:a=r[e+1],u=r[e+2],d=r[e+3],(a&192)===128&&(u&192)===128&&(d&192)===128&&(l=(o&15)<<18|(a&63)<<12|(u&63)<<6|d&63,l>65535&&l<1114112&&(i=l))}}i===null?(i=65533,s=1):i>65535&&(i-=65536,n.push(i>>>10&1023|55296),i=56320|i&1023),n.push(i),e+=s}return Cn(n)}var ai=4096;function Cn(r){let e=r.length;if(e<=ai)return String.fromCharCode.apply(String,r);let t="",n=0;for(;n<e;)t+=String.fromCharCode.apply(String,r.slice(n,n+=ai));return t}var Gc=256,nt=class{constructor(e=Gc){this.chunkSize=e,this.cursor=0,this.maxCursor=-1,this.chunks=[],this._initReuseChunk=null}reset(){this.cursor=0,this.maxCursor=-1,this.chunks.length&&(this.chunks=[]),this._initReuseChunk!==null&&(this.chunks.push(this._initReuseChunk),this.maxCursor=this._initReuseChunk.length-1)}push(e){let t=this.chunks[this.chunks.length-1];if(this.cursor+e.length<=this.maxCursor+1){let o=t.length-(this.maxCursor-this.cursor)-1;t.set(e,o)}else{if(t){let o=t.length-(this.maxCursor-this.cursor)-1;o<t.length&&(this.chunks[this.chunks.length-1]=t.subarray(0,o),this.maxCursor=this.cursor-1)}e.length<64&&e.length<this.chunkSize?(t=li(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=Fe(n,0,this.cursor)}else t=ui(this.chunks,this.cursor);return e&&this.reset(),t}};var m="CBOR decode error:",ce="CBOR encode error:",ot=[];ot[23]=1;ot[24]=2;ot[25]=3;ot[26]=5;ot[27]=9;function ue(r,e,t){if(r.length-e<t)throw new Error(`${m} not enough data for type`)}var L=[24,256,65536,4294967296,BigInt("18446744073709551616")];function z(r,e,t){ue(r,e,1);let n=r[e];if(t.strict===!0&&n<L[0])throw new Error(`${m} integer encoded in more bytes than necessary (strict decode)`);return n}function M(r,e,t){ue(r,e,2);let n=r[e]<<8|r[e+1];if(t.strict===!0&&n<L[1])throw new Error(`${m} integer encoded in more bytes than necessary (strict decode)`);return n}function $(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<L[2])throw new Error(`${m} integer encoded in more bytes than necessary (strict decode)`);return n}function q(r,e,t){ue(r,e,8);let n=r[e]*16777216+(r[e+1]<<16)+(r[e+2]<<8)+r[e+3],o=r[e+4]*16777216+(r[e+5]<<16)+(r[e+6]<<8)+r[e+7],i=(BigInt(n)<<BigInt(32))+BigInt(o);if(t.strict===!0&&i<L[3])throw new Error(`${m} integer encoded in more bytes than necessary (strict decode)`);if(i<=Number.MAX_SAFE_INTEGER)return Number(i);if(t.allowBigInt===!0)return i;throw new Error(`${m} integers outside of the safe integer range are not supported`)}function hi(r,e,t,n){return new h(c.uint,z(r,e+1,n),2)}function di(r,e,t,n){return new h(c.uint,M(r,e+1,n),3)}function pi(r,e,t,n){return new h(c.uint,$(r,e+1,n),5)}function mi(r,e,t,n){return new h(c.uint,q(r,e+1,n),9)}function G(r,e){return P(r,0,e.value)}function P(r,e,t){if(t<L[0]){let n=Number(t);r.push([e|n])}else if(t<L[1]){let n=Number(t);r.push([e|24,n])}else if(t<L[2]){let n=Number(t);r.push([e|25,n>>>8,n&255])}else if(t<L[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<L[4]){let o=[e|27,0,0,0,0,0,0,0],i=Number(n&BigInt(4294967295)),s=Number(n>>BigInt(32)&BigInt(4294967295));o[8]=i&255,i=i>>8,o[7]=i&255,i=i>>8,o[6]=i&255,i=i>>8,o[5]=i&255,o[4]=s&255,s=s>>8,o[3]=s&255,s=s>>8,o[2]=s&255,s=s>>8,o[1]=s&255,r.push(o)}else throw new Error(`${m} encountered BigInt larger than allowable range`)}}G.encodedSize=function(e){return P.encodedSize(e.value)};P.encodedSize=function(e){return e<L[0]?1:e<L[1]?2:e<L[2]?3:e<L[3]?5:9};G.compareTokens=function(e,t){return e.value<t.value?-1:e.value>t.value?1:0};function gi(r,e,t,n){return new h(c.negint,-1-z(r,e+1,n),2)}function yi(r,e,t,n){return new h(c.negint,-1-M(r,e+1,n),3)}function wi(r,e,t,n){return new h(c.negint,-1-$(r,e+1,n),5)}var Sn=BigInt(-1),bi=BigInt(1);function xi(r,e,t,n){let o=q(r,e+1,n);if(typeof o!="bigint"){let i=-1-o;if(i>=Number.MIN_SAFE_INTEGER)return new h(c.negint,i,9)}if(n.allowBigInt!==!0)throw new Error(`${m} integers outside of the safe integer range are not supported`);return new h(c.negint,Sn-BigInt(o),9)}function Mt(r,e){let t=e.value,n=typeof t=="bigint"?t*Sn-bi:t*-1-1;P(r,e.type.majorEncoded,n)}Mt.encodedSize=function(e){let t=e.value,n=typeof t=="bigint"?t*Sn-bi:t*-1-1;return n<L[0]?1:n<L[1]?2:n<L[2]?3:n<L[3]?5:9};Mt.compareTokens=function(e,t){return e.value<t.value?1:e.value>t.value?-1:0};function it(r,e,t,n){ue(r,e,t+n);let o=Fe(r,e+t,e+t+n);return new h(c.bytes,o,t+n)}function Ei(r,e,t,n){return it(r,e,1,t)}function vi(r,e,t,n){return it(r,e,2,z(r,e+1,n))}function _i(r,e,t,n){return it(r,e,3,M(r,e+1,n))}function ki(r,e,t,n){return it(r,e,5,$(r,e+1,n))}function Ai(r,e,t,n){let o=q(r,e+1,n);if(typeof o=="bigint")throw new Error(`${m} 64-bit integer bytes lengths not supported`);return it(r,e,9,o)}function $t(r){return r.encodedBytes===void 0&&(r.encodedBytes=r.type===c.string?zt(r.value):r.value),r.encodedBytes}function Oe(r,e){let t=$t(e);P(r,e.type.majorEncoded,t.length),r.push(t)}Oe.encodedSize=function(e){let t=$t(e);return P.encodedSize(t.length)+t.length};Oe.compareTokens=function(e,t){return Jc($t(e),$t(t))};function Jc(r,e){return r.length<e.length?-1:r.length>e.length?1:fi(r,e)}function st(r,e,t,n,o){let i=t+n;ue(r,e,i);let s=new h(c.string,ci(r,e+t,e+i),i);return o.retainStringBytes===!0&&(s.byteValue=Fe(r,e+t,e+i)),s}function Ci(r,e,t,n){return st(r,e,1,t,n)}function Si(r,e,t,n){return st(r,e,2,z(r,e+1,n),n)}function Ii(r,e,t,n){return st(r,e,3,M(r,e+1,n),n)}function Ti(r,e,t,n){return st(r,e,5,$(r,e+1,n),n)}function Li(r,e,t,n){let o=q(r,e+1,n);if(typeof o=="bigint")throw new Error(`${m} 64-bit integer string lengths not supported`);return st(r,e,9,o,n)}var Pi=Oe;function ze(r,e,t,n){return new h(c.array,n,t)}function Ni(r,e,t,n){return ze(r,e,1,t)}function Ri(r,e,t,n){return ze(r,e,2,z(r,e+1,n))}function Di(r,e,t,n){return ze(r,e,3,M(r,e+1,n))}function Ui(r,e,t,n){return ze(r,e,5,$(r,e+1,n))}function Bi(r,e,t,n){let o=q(r,e+1,n);if(typeof o=="bigint")throw new Error(`${m} 64-bit integer array lengths not supported`);return ze(r,e,9,o)}function Fi(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${m} indefinite length items not allowed`);return ze(r,e,1,1/0)}function qt(r,e){P(r,c.array.majorEncoded,e.value)}qt.compareTokens=G.compareTokens;qt.encodedSize=function(e){return P.encodedSize(e.value)};function Me(r,e,t,n){return new h(c.map,n,t)}function Oi(r,e,t,n){return Me(r,e,1,t)}function zi(r,e,t,n){return Me(r,e,2,z(r,e+1,n))}function Mi(r,e,t,n){return Me(r,e,3,M(r,e+1,n))}function $i(r,e,t,n){return Me(r,e,5,$(r,e+1,n))}function qi(r,e,t,n){let o=q(r,e+1,n);if(typeof o=="bigint")throw new Error(`${m} 64-bit integer map lengths not supported`);return Me(r,e,9,o)}function ji(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${m} indefinite length items not allowed`);return Me(r,e,1,1/0)}function jt(r,e){P(r,c.map.majorEncoded,e.value)}jt.compareTokens=G.compareTokens;jt.encodedSize=function(e){return P.encodedSize(e.value)};function Vi(r,e,t,n){return new h(c.tag,t,1)}function Ki(r,e,t,n){return new h(c.tag,z(r,e+1,n),2)}function Hi(r,e,t,n){return new h(c.tag,M(r,e+1,n),3)}function Wi(r,e,t,n){return new h(c.tag,$(r,e+1,n),5)}function Gi(r,e,t,n){return new h(c.tag,q(r,e+1,n),9)}function Vt(r,e){P(r,c.tag.majorEncoded,e.value)}Vt.compareTokens=G.compareTokens;Vt.encodedSize=function(e){return P.encodedSize(e.value)};var ru=20,nu=21,ou=22,iu=23;function Qi(r,e,t,n){if(n.allowUndefined===!1)throw new Error(`${m} undefined values are not supported`);return n.coerceUndefinedToNull===!0?new h(c.null,null,1):new h(c.undefined,void 0,1)}function Ji(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${m} indefinite length items not allowed`);return new h(c.break,void 0,1)}function In(r,e,t){if(t){if(t.allowNaN===!1&&Number.isNaN(r))throw new Error(`${m} NaN values are not supported`);if(t.allowInfinity===!1&&(r===1/0||r===-1/0))throw new Error(`${m} Infinity values are not supported`)}return new h(c.float,r,e)}function Yi(r,e,t,n){return In(Tn(r,e+1),3,n)}function Xi(r,e,t,n){return In(Ln(r,e+1),5,n)}function Zi(r,e,t,n){return In(ns(r,e+1),9,n)}function Kt(r,e,t){let n=e.value;if(n===!1)r.push([c.float.majorEncoded|ru]);else if(n===!0)r.push([c.float.majorEncoded|nu]);else if(n===null)r.push([c.float.majorEncoded|ou]);else if(n===void 0)r.push([c.float.majorEncoded|iu]);else{let o,i=!1;(!t||t.float64!==!0)&&(ts(n),o=Tn(ee,1),n===o||Number.isNaN(n)?(ee[0]=249,r.push(ee.slice(0,3)),i=!0):(rs(n),o=Ln(ee,1),n===o&&(ee[0]=250,r.push(ee.slice(0,5)),i=!0))),i||(su(n),o=ns(ee,1),ee[0]=251,r.push(ee.slice(0,9)))}}Kt.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){ts(n);let o=Tn(ee,1);if(n===o||Number.isNaN(n))return 3;if(rs(n),o=Ln(ee,1),n===o)return 5}return 9};var es=new ArrayBuffer(9),Q=new DataView(es,1),ee=new Uint8Array(es,0);function ts(r){if(r===1/0)Q.setUint16(0,31744,!1);else if(r===-1/0)Q.setUint16(0,64512,!1);else if(Number.isNaN(r))Q.setUint16(0,32256,!1);else{Q.setFloat32(0,r);let e=Q.getUint32(0),t=(e&2139095040)>>23,n=e&8388607;if(t===255)Q.setUint16(0,31744,!1);else if(t===0)Q.setUint16(0,(r&2147483648)>>16|n>>13,!1);else{let o=t-127;o<-24?Q.setUint16(0,0):o<-14?Q.setUint16(0,(e&2147483648)>>16|1<<24+o,!1):Q.setUint16(0,(e&2147483648)>>16|o+15<<10|n>>13,!1)}}}function Tn(r,e){if(r.length-e<2)throw new Error(`${m} not enough data for float16`);let t=(r[e]<<8)+r[e+1];if(t===31744)return 1/0;if(t===64512)return-1/0;if(t===32256)return NaN;let n=t>>10&31,o=t&1023,i;return n===0?i=o*2**-24:n!==31?i=(o+1024)*2**(n-25):i=o===0?1/0:NaN,t&32768?-i:i}function rs(r){Q.setFloat32(0,r,!1)}function Ln(r,e){if(r.length-e<4)throw new Error(`${m} not enough data for float32`);let t=(r.byteOffset||0)+e;return new DataView(r.buffer,t,4).getFloat32(0,!1)}function su(r){Q.setFloat64(0,r,!1)}function ns(r,e){if(r.length-e<8)throw new Error(`${m} not enough data for float64`);let t=(r.byteOffset||0)+e;return new DataView(r.buffer,t,8).getFloat64(0,!1)}Kt.compareTokens=G.compareTokens;function E(r,e,t){throw new Error(`${m} encountered invalid minor (${t}) for major ${r[e]>>>5}`)}function Ht(r){return()=>{throw new Error(`${m} ${r}`)}}var p=[];for(let r=0;r<=23;r++)p[r]=E;p[24]=hi;p[25]=di;p[26]=pi;p[27]=mi;p[28]=E;p[29]=E;p[30]=E;p[31]=E;for(let r=32;r<=55;r++)p[r]=E;p[56]=gi;p[57]=yi;p[58]=wi;p[59]=xi;p[60]=E;p[61]=E;p[62]=E;p[63]=E;for(let r=64;r<=87;r++)p[r]=Ei;p[88]=vi;p[89]=_i;p[90]=ki;p[91]=Ai;p[92]=E;p[93]=E;p[94]=E;p[95]=Ht("indefinite length bytes/strings are not supported");for(let r=96;r<=119;r++)p[r]=Ci;p[120]=Si;p[121]=Ii;p[122]=Ti;p[123]=Li;p[124]=E;p[125]=E;p[126]=E;p[127]=Ht("indefinite length bytes/strings are not supported");for(let r=128;r<=151;r++)p[r]=Ni;p[152]=Ri;p[153]=Di;p[154]=Ui;p[155]=Bi;p[156]=E;p[157]=E;p[158]=E;p[159]=Fi;for(let r=160;r<=183;r++)p[r]=Oi;p[184]=zi;p[185]=Mi;p[186]=$i;p[187]=qi;p[188]=E;p[189]=E;p[190]=E;p[191]=ji;for(let r=192;r<=215;r++)p[r]=Vi;p[216]=Ki;p[217]=Hi;p[218]=Wi;p[219]=Gi;p[220]=E;p[221]=E;p[222]=E;p[223]=E;for(let r=224;r<=243;r++)p[r]=Ht("simple values are not supported");p[244]=E;p[245]=E;p[246]=E;p[247]=Qi;p[248]=Ht("simple values are not supported");p[249]=Yi;p[250]=Xi;p[251]=Zi;p[252]=E;p[253]=E;p[254]=E;p[255]=Ji;var te=[];for(let r=0;r<24;r++)te[r]=new h(c.uint,r,1);for(let r=-1;r>=-24;r--)te[31-r]=new h(c.negint,r,1);te[64]=new h(c.bytes,new Uint8Array(0),1);te[96]=new h(c.string,"",1);te[128]=new h(c.array,0,1);te[160]=new h(c.map,0,1);te[244]=new h(c.false,!1,1);te[245]=new h(c.true,!0,1);te[246]=new h(c.null,null,1);function os(r){switch(r.type){case c.false:return ie([244]);case c.true:return ie([245]);case c.null:return ie([246]);case c.bytes:return r.value.length?void 0:ie([64]);case c.string:return r.value===""?ie([96]):void 0;case c.array:return r.value===0?ie([128]):void 0;case c.map:return r.value===0?ie([160]):void 0;case c.uint:return r.value<24?ie([Number(r.value)]):void 0;case c.negint:if(r.value>=-24)return ie([31-Number(r.value)])}}var cu={float64:!1,mapSorter:fu,quickEncodeToken:os};function uu(){let r=[];return r[c.uint.major]=G,r[c.negint.major]=Mt,r[c.bytes.major]=Oe,r[c.string.major]=Pi,r[c.array.major]=qt,r[c.map.major]=jt,r[c.tag.major]=Vt,r[c.float.major]=Kt,r}var is=uu(),Pn=new nt,Gt=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(`${ce} object contains circular references`);return new r(t,e)}},ye={null:new h(c.null,null),undefined:new h(c.undefined,void 0),true:new h(c.true,!0),false:new h(c.false,!1),emptyArray:new h(c.array,0),emptyMap:new h(c.map,0)},we={number(r,e,t,n){return!Number.isInteger(r)||!Number.isSafeInteger(r)?new h(c.float,r):r>=0?new h(c.uint,r):new h(c.negint,r)},bigint(r,e,t,n){return r>=BigInt(0)?new h(c.uint,r):new h(c.negint,r)},Uint8Array(r,e,t,n){return new h(c.bytes,r)},string(r,e,t,n){return new h(c.string,r)},boolean(r,e,t,n){return r?ye.true:ye.false},null(r,e,t,n){return ye.null},undefined(r,e,t,n){return ye.undefined},ArrayBuffer(r,e,t,n){return new h(c.bytes,new Uint8Array(r))},DataView(r,e,t,n){return new h(c.bytes,new Uint8Array(r.buffer,r.byteOffset,r.byteLength))},Array(r,e,t,n){if(!r.length)return t.addBreakTokens===!0?[ye.emptyArray,new h(c.break)]:ye.emptyArray;n=Gt.createCheck(n,r);let o=[],i=0;for(let s of r)o[i++]=Wt(s,t,n);return t.addBreakTokens?[new h(c.array,r.length),o,new h(c.break)]:[new h(c.array,r.length),o]},Object(r,e,t,n){let o=e!=="Object",i=o?r.keys():Object.keys(r),s=o?r.size:i.length;if(!s)return t.addBreakTokens===!0?[ye.emptyMap,new h(c.break)]:ye.emptyMap;n=Gt.createCheck(n,r);let a=[],u=0;for(let d of i)a[u++]=[Wt(d,t,n),Wt(o?r.get(d):r[d],t,n)];return lu(a,t),t.addBreakTokens?[new h(c.map,s),a,new h(c.break)]:[new h(c.map,s),a]}};we.Map=we.Object;we.Buffer=we.Uint8Array;for(let r of"Uint8Clamped Uint16 Uint32 Int8 Int16 Int32 BigUint64 BigInt64 Float32 Float64".split(" "))we[`${r}Array`]=we.DataView;function Wt(r,e={},t){let n=oi(r),o=e&&e.typeEncoders&&e.typeEncoders[n]||we[n];if(typeof o=="function"){let s=o(r,n,e,t);if(s!=null)return s}let i=we[n];if(!i)throw new Error(`${ce} unsupported type: ${n}`);return i(r,n,e,t)}function lu(r,e){e.mapSorter&&r.sort(e.mapSorter)}function fu(r,e){let t=Array.isArray(r[0])?r[0][0]:r[0],n=Array.isArray(e[0])?e[0][0]:e[0];if(t.type!==n.type)return t.type.compare(n.type);let o=t.type.major,i=is[o].compareTokens(t,n);return i===0&&console.warn("WARNING: complex key types used, CBOR key sorting guarantees are gone"),i}function ss(r,e,t,n){if(Array.isArray(e))for(let o of e)ss(r,o,t,n);else t[e.type.major](r,e,n)}function Nn(r,e,t){let n=Wt(r,t);if(!Array.isArray(n)&&t.quickEncodeToken){let o=t.quickEncodeToken(n);if(o)return o;let i=e[n.type.major];if(i.encodedSize){let s=i.encodedSize(n,t),a=new nt(s);if(i(a,n,t),a.chunks.length!==1)throw new Error(`Unexpected error: pre-calculated length for ${n} was wrong`);return rt(a.chunks[0])}}return Pn.reset(),ss(Pn,n,e,t),Pn.toBytes(!0)}function ke(r,e){return e=Object.assign({},cu,e),Nn(r,is,e)}var hu={strict:!1,allowIndefinite:!0,allowUndefined:!0,allowBigInt:!0},Qt=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=te[e];if(t===void 0){let n=p[e];if(!n)throw new Error(`${m} no decoder for major type ${e>>>5} (byte 0x${e.toString(16).padStart(2,"0")})`);let o=e&31;t=n(this.data,this._pos,o,this.options)}return this._pos+=t.encodedLength,t}},at=Symbol.for("DONE"),Jt=Symbol.for("BREAK");function du(r,e,t){let n=[];for(let o=0;o<r.value;o++){let i=$e(e,t);if(i===Jt){if(r.value===1/0)break;throw new Error(`${m} got unexpected break to lengthed array`)}if(i===at)throw new Error(`${m} found array but not enough entries (got ${o}, expected ${r.value})`);n[o]=i}return n}function pu(r,e,t){let n=t.useMaps===!0,o=n?void 0:{},i=n?new Map:void 0;for(let s=0;s<r.value;s++){let a=$e(e,t);if(a===Jt){if(r.value===1/0)break;throw new Error(`${m} got unexpected break to lengthed map`)}if(a===at)throw new Error(`${m} found map but not enough entries (got ${s} [no key], expected ${r.value})`);if(n!==!0&&typeof a!="string")throw new Error(`${m} non-string keys not supported (got ${typeof a})`);if(t.rejectDuplicateMapKeys===!0&&(n&&i.has(a)||!n&&a in o))throw new Error(`${m} found repeat map key "${a}"`);let u=$e(e,t);if(u===at)throw new Error(`${m} found map but not enough entries (got ${s} [no value], expected ${r.value})`);n?i.set(a,u):o[a]=u}return n?i:o}function $e(r,e){if(r.done())return at;let t=r.next();if(t.type===c.break)return Jt;if(t.type.terminal)return t.value;if(t.type===c.array)return du(t,r,e);if(t.type===c.map)return pu(t,r,e);if(t.type===c.tag){if(e.tags&&typeof e.tags[t.value]=="function"){let n=$e(r,e);return e.tags[t.value](n)}throw new Error(`${m} tag not supported (${t.value})`)}throw new Error("unsupported")}function Rn(r,e){if(!(r instanceof Uint8Array))throw new Error(`${m} data to decode must be a Uint8Array`);e=Object.assign({},hu,e);let t=e.tokenizer||new Qt(r,e),n=$e(t,e);if(n===at)throw new Error(`${m} did not find any content to decode`);if(n===Jt)throw new Error(`${m} got unexpected break`);return[n,r.subarray(t.pos())]}function re(r,e){let[t,n]=Rn(r,e);if(n.length>0)throw new Error(`${m} too many terminals, data makes no sense`);return t}var Yt=class extends ae{has(e){return this.find(e)!=null}find(e){return this.queue.find(t=>e.equals(t.options.peerId))}};var le="/",cs=new TextEncoder().encode(le),Xt=cs[0],fe=class r{_buf;constructor(e,t){if(typeof e=="string")this._buf=U(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]!==Xt)throw new Error("Invalid key")}toString(e="utf8"){return De(this._buf,e)}uint8Array(){return this._buf}get[Symbol.toStringTag](){return`Key(${this.toString()})`}static withNamespaces(e){return new r(e.join(le))}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=cs),this._buf[0]!==Xt){let e=new Uint8Array(this._buf.byteLength+1);e.fill(Xt,0,1),e.set(this._buf,1),this._buf=e}for(;this._buf.byteLength>1&&this._buf[this._buf.byteLength-1]===Xt;)this._buf=this._buf.subarray(0,-1)}less(e){let t=this.list(),n=e.list();for(let o=0;o<t.length;o++){if(n.length<o+1)return!1;let i=t[o],s=n[o];if(i<s)return!0;if(i>s)return!1}return t.length<n.length}reverse(){return r.withNamespaces(this.list().slice().reverse())}namespaces(){return this.list()}baseNamespace(){let e=this.namespaces();return e[e.length-1]}list(){return this.toString().split(le).slice(1)}type(){return mu(this.baseNamespace())}name(){return gu(this.baseNamespace())}instance(e){return new r(this.toString()+":"+e)}path(){let e=this.parent().toString();return e.endsWith(le)||(e+=le),e+=this.type(),new r(e)}parent(){let e=this.list();return e.length===1?new r(le):new r(e.slice(0,-1).join(le))}child(e){return this.toString()===le?e:e.toString()===le?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(),...yu(e.map(t=>t.namespaces()))])}};function mu(r){let e=r.split(":");return e.length<2?"":e.slice(0,-1).join(":")}function gu(r){let e=r.split(":");return e[e.length-1]}function yu(r){return[].concat(...r)}function wu(r){return r[Symbol.asyncIterator]!=null}function bu(r){if(wu(r))return(async()=>{let n=new Uint8Array(0);for await(let o of r)n=wn([n,o],n.length+o.length);return n})();let e=[],t=0;for(let n of r)e.push(n),t+=n.byteLength;return wn(e,t)}var us=bu;function Zt({enumerable:r=!0,configurable:e=!1}={}){return{enumerable:r,configurable:e,writable:!1}}function*xu(r,e){if(e!=null&&typeof e=="object")if(Array.isArray(e))for(let[t,n]of e.entries()){let o=[...r,t],i=k.asCID(n);i!=null?yield[o.join("/"),i]:typeof n=="object"&&(yield*Dn(n,o))}else{let t=k.asCID(e);t!=null?yield[r.join("/"),t]:yield*Dn(e,r)}}function*Dn(r,e){if(r==null||r instanceof Uint8Array)return;let t=k.asCID(r);t!=null&&(yield[e.join("/"),t]);for(let[n,o]of Object.entries(r)){let i=[...e,n];yield*xu(i,o)}}function*Eu(r,e){if(Array.isArray(e))for(let[t,n]of e.entries()){let o=[...r,t];yield o.join("/"),typeof n=="object"&&k.asCID(n)==null&&(yield*Un(n,o))}else yield*Un(e,r)}function*Un(r,e){if(!(r==null||typeof r!="object"))for(let[t,n]of Object.entries(r)){let o=[...e,t];yield o.join("/"),n!=null&&!(n instanceof Uint8Array)&&typeof n=="object"&&k.asCID(n)==null&&(yield*Eu(o,n))}}function vu(r,e){let t=r;for(let[n,o]of e.entries()){if(t=t[o],t==null)throw new Error(`Object has no property at ${e.slice(0,n+1).map(s=>`[${JSON.stringify(s)}]`).join("")}`);let i=k.asCID(t);if(i!=null)return{value:i,remaining:e.slice(n+1).join("/")}}return{value:t}}var Bn=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:Zt(),bytes:Zt(),value:Zt(),asBlock:Zt()})}links(){return Dn(this.value,[])}tree(){return Un(this.value,[])}get(e="/"){return vu(this.value,e.split("/").filter(Boolean))}};function ls({bytes:r,cid:e,value:t,codec:n}){let o=t!==void 0?t:n?.decode(r);if(o===void 0)throw new Error('Missing required argument, must either provide "value" or "codec"');return new Bn({cid:e,bytes:r,value:o})}var ds="/pin/",fs="/pinned-block/",Fn=se,hs=1;function er(r){return r.version===0&&(r=r.toV1()),new fe(`${ds}${r.toString(Fn)}`)}var tr=class{datastore;blockstore;getCodec;constructor(e,t,n){this.datastore=e,this.blockstore=t,this.getCodec=n}async*add(e,t={}){let n=er(e);if(await this.datastore.has(n))throw new Error("Already pinned");let o=Math.round(t.depth??1/0);if(o<0)throw new Error("Depth must be greater than or equal to 0");let i=new ae({concurrency:hs});for await(let a of this.#e(e,i,{...t,depth:o}))await this.#o(a,u=>u.pinnedBy.find(d=>xe(d,e.bytes))!=null?!1:(u.pinCount++,u.pinnedBy.push(e.bytes),!0),t),yield a;let s={depth:o,metadata:t.metadata??{}};await this.datastore.put(n,ke(s),t)}async*#e(e,t,n){if(n.depth===-1)return;let o=await this.getCodec(e.code),i=await us(this.blockstore.get(e,n)),s=ls({bytes:i,cid:e,codec:o});yield e;for(let[,a]of s.links())yield*await t.add(async()=>this.#e(a,t,{...n,depth:n.depth-1}))}async#o(e,t,n){let o=new fe(`${fs}${Fn.encode(e.multihash.bytes)}`),i={pinCount:0,pinnedBy:[]};try{i=re(await this.datastore.get(o,n))}catch(a){if(a.name!=="NotFoundError")throw a}if(t(i)){if(i.pinCount===0&&await this.datastore.has(o)){await this.datastore.delete(o);return}await this.datastore.put(o,ke(i),n),n.onProgress?.(new v("helia:pin:add",e))}}async*rm(e,t={}){let n=er(e),o=await this.datastore.get(n,t),i=re(o);await this.datastore.delete(n,t);let s=new ae({concurrency:hs});for await(let a of this.#e(e,s,{...t,depth:i.depth}))await this.#o(a,u=>(u.pinCount--,u.pinnedBy=u.pinnedBy.filter(d=>xe(d,e.bytes)),!0),{...t,depth:i.depth}),yield a}async*ls(e={}){for await(let{key:t,value:n}of this.datastore.query({prefix:ds+(e.cid!=null?`${e.cid.toString(se)}`:"")},e)){let o=k.parse(t.toString().substring(5),se),i=re(n);yield{cid:o,...i}}}async isPinned(e,t={}){let n=new fe(`${fs}${Fn.encode(e.multihash.bytes)}`);return this.datastore.has(n,t)}async get(e,t){let n=er(e),o=await this.datastore.get(n,t);return re(o)}async setMetadata(e,t,n){let o=er(e),i=await this.datastore.get(o,n),s=re(i);s.metadata=t??{},await this.datastore.put(o,ke(s),n)}};var rr=class extends Error{static name="InsufficientProvidersError";constructor(e="Insufficient providers found"){super(e),this.name="InsufficientProvidersError"}},Ae=class extends Error{static name="NoRoutersAvailableError";constructor(e="No routers available"){super(e),this.name="NoRoutersAvailableError"}},nr=class extends Error{static name="UnknownHashAlgorithmError";constructor(e="Unknown hash algorithm"){super(e),this.name="UnknownHashAlgorithmError"}},or=class extends Error{static name="UnknownCodecError";constructor(e="Unknown codec"){super(e),this.name="UnknownCodecError"}};var _u=5,ir=class{log;routers;providerLookupConcurrency;constructor(e,t){this.log=e.logger.forComponent("helia:routing"),this.routers=t.routers??[],this.providerLookupConcurrency=t.providerLookupConcurrency??_u,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 he(...this.routers)}async stop(){await de(...this.routers)}async*findProviders(e,t={}){if(this.routers.length===0)throw new Ae("No content routers available");let n=new Yt({concurrency:this.providerLookupConcurrency});for await(let o of Ft(n.toGenerator(),...Ce(this.routers,"findProviders").map(i=>i.findProviders(e,t))))if(o!=null){if(o.multiaddrs.length===0){if(n.find(o.id)!=null)continue;n.add(async()=>{try{let i=await this.findPeer(o.id,t);return i.multiaddrs.length===0?null:i}catch(i){return this.log.error("could not load multiaddrs for peer %p",o.id,i),null}},{peerId:o.id,signal:t.signal}).catch(i=>{this.log.error("could not load multiaddrs for peer %p",o.id,i)})}yield o}}async provide(e,t={}){if(this.routers.length===0)throw new Ae("No content routers available");await Promise.all(Ce(this.routers,"provide").map(async n=>{await n.provide(e,t)}))}async cancelReprovide(e,t={}){await Promise.all(Ce(this.routers,"cancelReprovide").map(async n=>{await n.cancelReprovide(e,t)}))}async put(e,t,n){await Promise.all(Ce(this.routers,"put").map(async o=>{await o.put(e,t,n)}))}async get(e,t){return Promise.any(Ce(this.routers,"get").map(async n=>n.get(e,t)))}async findPeer(e,t){if(this.routers.length===0)throw new Ae("No peer routers available");let n=this,o=Ft(...Ce(this.routers,"findPeer").map(i=>(async function*(){try{yield await i.findPeer(e,t)}catch(s){n.log.error(s)}})()));for await(let i of o)if(i!=null)return i;throw new dt("Could not find peer in routing")}async*getClosestPeers(e,t={}){if(this.routers.length===0)throw new Ae("No peer routers available");for await(let n of Ft(...Ce(this.routers,"getClosestPeers").map(o=>o.getClosestPeers(e,t))))n!=null&&(yield n)}};function Ce(r,e){return r.filter(t=>t[e]!=null)}var j=class extends Error{static name="AbortError";name="AbortError";constructor(e="The operation was aborted",...t){super(e,...t)}};async function sr(r,e,t,n){let o=new j(n?.errorMessage);n?.errorCode!=null&&(o.code=n.errorCode);let i=n?.errorEvent??"error";return t?.aborted===!0?Promise.reject(o):new Promise((s,a)=>{function u(){zn(t,"abort",f),zn(r,e,d),zn(r,i,l)}let d=g=>{try{if(n?.filter?.(g)===!1)return}catch(y){u(),a(y);return}u(),s(g)},l=g=>{if(u(),g instanceof Error){a(g);return}a(g.detail??n?.error??new Error(`The "${n?.errorEvent}" event was emitted but the event had no '.detail' field. Pass an 'error' option to race-event to change this message.`))},f=()=>{u(),a(o)};On(t,"abort",f),On(r,e,d),On(r,i,l)})}function On(r,e,t){r!=null&&(ps(r)?r.addEventListener(e,t):r.addListener(e,t))}function zn(r,e,t){r!=null&&(ps(r)?r.removeEventListener(e,t):r.removeListener(e,t))}function ps(r){return typeof r.addEventListener=="function"&&typeof r.removeEventListener=="function"}var ar=class extends Error{static name="QueueFullError";constructor(e="The queue was full"){super(e),this.name="QueueFullError"}};var cr=class extends Error{type;code;constructor(e,t,n){super(e??"The operation was aborted"),this.type="aborted",this.name=n??"AbortError",this.code=t??"ABORT_ERR"}};async function ms(r,e,t){if(e==null)return r;if(e.aborted)return r.catch(()=>{}),Promise.reject(new cr(t?.errorMessage,t?.errorCode,t?.errorName));let n,o=new cr(t?.errorMessage,t?.errorCode,t?.errorName);try{return await Promise.race([r,new Promise((i,s)=>{n=()=>{s(o)},e.addEventListener("abort",n)})])}finally{n!=null&&e.removeEventListener("abort",n)}}var ur=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 j)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function ku(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var lr=class{id;fn;options;recipients;status;timeline;controller;constructor(e,t){this.id=ku(),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 j),this.cleanup())}async join(e={}){let t=new ur(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 ms(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 Mn(r,e){let t,n=function(){let o=function(){t=void 0,r()};clearTimeout(t),t=setTimeout(o,e)};return n.start=()=>{},n.stop=()=>{clearTimeout(t)},n}var ct=class extends H{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=Mn(this.emitEmpty.bind(this),1),this.emitIdle=Mn(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 ar;let n=new lr(e,t);return this.enqueue(n),this.safeDispatchEvent("add"),this.autoStart&&this.tryToStartAnother(),n.join(t).then(o=>(this.safeDispatchEvent("success",{detail:{job:n,result:o}}),o)).catch(o=>{if(n.status==="queued"){for(let i=0;i<this.queue.length;i++)if(this.queue[i]===n){this.queue.splice(i,1);break}}throw this.safeDispatchEvent("failure",{detail:{job:n,error:o}}),o})}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(e=>{e.abort(new j)}),this.clear()}async onEmpty(e){this.size!==0&&await sr(this,"empty",e?.signal)}async onSizeLessThan(e,t){this.size<e||await sr(this,"next",t?.signal,{filter:()=>this.size<e})}async onIdle(e){this.pending===0&&this.size===0||await sr(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=Pt({objectMode:!0}),n=u=>{u!=null?this.abort():this.clear(),t.end(u)},o=u=>{u.detail!=null&&t.push(u.detail.result)},i=u=>{n(u.detail.error)},s=()=>{n()},a=()=>{n(new j("Queue aborted"))};this.addEventListener("success",o),this.addEventListener("failure",i),this.addEventListener("idle",s),e?.signal?.addEventListener("abort",a);try{yield*t}finally{this.removeEventListener("success",o),this.removeEventListener("failure",i),this.removeEventListener("idle",s),e?.signal?.removeEventListener("abort",a),n()}}};var fr="lock:worker:request-read",hr="lock:worker:abort-read-request",dr="lock:worker:release-read",pr="lock:master:grant-read",mr="lock:master:error-read",gr="lock:worker:request-write",yr="lock:worker:abort-write-request",wr="lock:worker:release-write",br="lock:master:grant-write",xr="lock:master:error-write",Er="lock:worker:finalize",vr="mortice",gs={singleProcess:!1};var $n=(r,e,t,n,o,i,s,a,u)=>d=>{if(d.data==null)return;let l={type:d.data.type,name:d.data.name,identifier:d.data.identifier};l.type===o&&r.safeDispatchEvent(t,{detail:{name:l.name,identifier:l.identifier,handler:async()=>{e.postMessage({type:u,name:l.name,identifier:l.identifier}),await new Promise(f=>{let g=y=>{if(y?.data==null)return;let b={type:y.data.type,name:y.data.name,identifier:y.data.identifier};b.type===a&&b.identifier===l.identifier&&(e.removeEventListener("message",g),f())};e.addEventListener("message",g)})},onError:f=>{e.postMessage({type:s,name:l.name,identifier:l.identifier,error:{message:f.message,name:f.name,stack:f.stack}})}}}),l.type===i&&r.safeDispatchEvent(n,{detail:{name:l.name,identifier:l.identifier}}),l.type===Er&&r.safeDispatchEvent("finalizeRequest",{detail:{name:l.name}})};var ys=(r=10)=>Math.random().toString().substring(2,r+2);var _r=class{name;channel;constructor(e){this.name=e,this.channel=new BroadcastChannel(vr)}readLock(e){return this.sendRequest(fr,hr,pr,mr,dr,e)}writeLock(e){return this.sendRequest(gr,yr,br,xr,wr,e)}finalize(){this.channel.postMessage({type:Er,name:this.name}),this.channel.close()}async sendRequest(e,t,n,o,i,s){s?.signal?.throwIfAborted();let a=ys();return this.channel.postMessage({type:e,identifier:a,name:this.name}),new Promise((u,d)=>{let l=()=>{this.channel.postMessage({type:t,identifier:a,name:this.name})};s?.signal?.addEventListener("abort",l,{once:!0});let f=g=>{if(g.data?.identifier===a&&(g.data?.type===n&&(this.channel.removeEventListener("message",f),s?.signal?.removeEventListener("abort",l),u(()=>{this.channel.postMessage({type:i,identifier:a,name:this.name})})),g.data.type===o)){this.channel.removeEventListener("message",f),s?.signal?.removeEventListener("abort",l);let y=new Error;g.data.error!=null&&(y.message=g.data.error.message,y.name=g.data.error.name,y.stack=g.data.error.stack),d(y)}};this.channel.addEventListener("message",f)})}};var ws=r=>{if(r=Object.assign({},gs,r),!!globalThis.document||r.singleProcess){let t=new BroadcastChannel(vr),n=new H;return t.addEventListener("message",$n(n,t,"requestReadLock","abortReadLockRequest",fr,hr,mr,dr,pr)),t.addEventListener("message",$n(n,t,"requestWriteLock","abortWriteLockRequest",gr,yr,xr,wr,br)),n}return new _r(r.name)};var Se=new Map,ut;function bs(r){return typeof r?.readLock=="function"&&typeof r?.writeLock=="function"}function Au(r){if(ut==null&&(ut=ws(r),!bs(ut))){let e=ut;e.addEventListener("requestReadLock",t=>{let n=t.detail.name,o=t.detail.identifier,i=Se.get(n);if(i==null)return;let s=new AbortController,a=u=>{u.detail.name!==n||u.detail.identifier!==o||s.abort()};e.addEventListener("abortReadLockRequest",a),i.readLock({signal:s.signal}).then(async u=>{await t.detail.handler().finally(()=>{u()})}).catch(u=>{t.detail.onError(u)}).finally(()=>{e.removeEventListener("abortReadLockRequest",a)})}),e.addEventListener("requestWriteLock",t=>{let n=t.detail.name,o=t.detail.identifier,i=Se.get(n);if(i==null)return;let s=new AbortController,a=u=>{u.detail.name!==n||u.detail.identifier!==o||s.abort()};e.addEventListener("abortWriteLockRequest",a),i.writeLock({signal:s.signal}).then(async u=>{await t.detail.handler().finally(()=>{u()})}).catch(u=>{t.detail.onError(u)}).finally(()=>{e.removeEventListener("abortWriteLockRequest",a)})}),e.addEventListener("finalizeRequest",t=>{let n=t.detail.name,o=Se.get(n);o?.finalize()})}return ut}async function qn(r,e){let t,n,o=new Promise((s,a)=>{t=s,n=a}),i=()=>{n(new j)};return e?.signal?.addEventListener("abort",i,{once:!0}),r.add(async()=>{await new Promise(s=>{t(()=>{e?.signal?.removeEventListener("abort",i),s()})})},{signal:e?.signal}).catch(s=>{n(s)}),o}var xs=(r,e)=>{let t=Se.get(r);if(t!=null)return t;let n=Au(e);if(bs(n))return t=n,Se.set(r,t),t;let o=new ct({concurrency:1}),i;return t={async readLock(s){if(i!=null)return qn(i,s);i=new ct({concurrency:e.concurrency,autoStart:!1});let a=i,u=qn(i,s);return o.add(async()=>{a.start(),await a.onIdle().then(()=>{i===a&&(i=null)})}),u},async writeLock(s){return i=null,qn(o,s)},finalize:()=>{Se.delete(r)},queue:o},Se.set(r,t),e.autoFinalize===!0&&o.addEventListener("idle",()=>{t.finalize()},{once:!0}),t};var Cu={name:"lock",concurrency:1/0,singleProcess:!1,autoFinalize:!1};function jn(r){let e=Object.assign({},Cu,r);return xs(e.name,e)}var kr=class{lock;child;pins;started;constructor(e,t,n={}){this.child=e,this.pins=t,this.lock=jn({singleProcess:n.holdGcLock}),this.started=!1}isStarted(){return this.started}async start(){await he(this.child),this.started=!0}async stop(){await de(this.child),this.started=!1}unwrap(){return this.child}async put(e,t,n={}){n?.signal?.throwIfAborted();let o=await this.lock.readLock();try{return await this.child.put(e,t,n)}finally{o()}}async*putMany(e,t={}){t?.signal?.throwIfAborted();let n=await this.lock.readLock();try{yield*this.child.putMany(e,t)}finally{n()}}async*get(e,t={}){t?.signal?.throwIfAborted();let n=await this.lock.readLock();try{yield*this.child.get(e,t)}finally{n()}}async*getMany(e,t={}){t?.signal?.throwIfAborted();let n=await this.lock.readLock();try{yield*this.child.getMany(e,t)}finally{n()}}async delete(e,t={}){t?.signal?.throwIfAborted();let n=await this.lock.writeLock();try{if(await this.pins.isPinned(e))throw new Error("CID was pinned");await this.child.delete(e,t)}finally{n()}}async*deleteMany(e,t={}){t?.signal?.throwIfAborted();let n=await this.lock.writeLock();try{let o=this;yield*this.child.deleteMany((async function*(){for await(let i of e){if(await o.pins.isPinned(i))throw new Error("CID was pinned");yield i}})(),t)}finally{n()}}async has(e,t={}){t?.signal?.throwIfAborted();let n=await this.lock.readLock();try{return await this.child.has(e,t)}finally{n()}}async*getAll(e={}){e?.signal?.throwIfAborted();let t=await this.lock.readLock();try{yield*this.child.getAll(e)}finally{t()}}createSession(e,t){return t?.signal?.throwIfAborted(),this.child.createSession(e,t)}};var Vn=new fe("/version"),Es=1;async function vs(r){if(!await r.has(Vn)){await r.put(Vn,U(`${Es}`));return}let e=await r.get(Vn),t=De(e);if(parseInt(t,10)!==Es)throw new Error("Unknown datastore version, a datastore migration may be required")}var Wn={};T(Wn,{code:()=>Hn,decode:()=>Bu,decodeOptions:()=>Ru,encode:()=>Uu,encodeOptions:()=>Pu,name:()=>Du,toByteView:()=>ks});var _s=42;function ks(r){return r instanceof ArrayBuffer?new Uint8Array(r,0,r.byteLength):r}function Su(r){if(r.asCID!==r&&r["/"]!==r.bytes)return null;let e=k.asCID(r);if(!e)return null;let t=new Uint8Array(e.bytes.byteLength+1);return t.set(e.bytes,1),[new h(c.tag,_s),new h(c.bytes,t)]}function Iu(){throw new Error("`undefined` is not supported by the IPLD Data Model and cannot be encoded")}function Tu(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 Lu(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 Kn={float64:!0,typeEncoders:{Map:Lu,Object:Su,undefined:Iu,number:Tu}},Pu={...Kn,typeEncoders:{...Kn.typeEncoders}};function Nu(r){if(r[0]!==0)throw new Error("Invalid CID for CBOR tag 42; expected leading 0x00");return k.decode(r.subarray(1))}var Ar={allowIndefinite:!1,coerceUndefinedToNull:!0,allowNaN:!1,allowInfinity:!1,allowBigInt:!0,strict:!0,useMaps:!1,rejectDuplicateMapKeys:!0,tags:[]};Ar.tags[_s]=Nu;var Ru={...Ar,tags:Ar.tags.slice()},Du="dag-cbor",Hn=113,Uu=r=>ke(r,Kn),Bu=r=>re(ks(r),Ar);var eo={};T(eo,{code:()=>Zn,decode:()=>Cs,encode:()=>As,format:()=>Wu,name:()=>Hu,parse:()=>Qu,stringify:()=>Wu});var Gn=class extends Array{constructor(){super(),this.inRecursive=[]}prefix(e){let t=this.inRecursive[this.inRecursive.length-1];t&&(t.type===c.array&&(t.elements++,t.elements!==1&&e.push([44])),t.type===c.map&&(t.elements++,t.elements!==1&&(t.elements%2===1?e.push([44]):e.push([58]))))}[c.uint.major](e,t){this.prefix(e);let n=String(t.value),o=[];for(let i=0;i<n.length;i++)o[i]=n.charCodeAt(i);e.push(o)}[c.negint.major](e,t){this[c.uint.major](e,t)}[c.bytes.major](e,t){throw new Error(`${ce} unsupported type: Uint8Array`)}[c.string.major](e,t){this.prefix(e);let n=zt(JSON.stringify(t.value));e.push(n.length>32?rt(n):n)}[c.array.major](e,t){this.prefix(e),this.inRecursive.push({type:c.array,elements:0}),e.push([91])}[c.map.major](e,t){this.prefix(e),this.inRecursive.push({type:c.map,elements:0}),e.push([123])}[c.tag.major](e,t){}[c.float.major](e,t){if(t.type.name==="break"){let s=this.inRecursive.pop();if(s){if(s.type===c.array)e.push([93]);else if(s.type===c.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(`${ce} unsupported type: undefined`);if(this.prefix(e),t.type.name==="true"){e.push([116,114,117,101]);return}else if(t.type.name==="false"){e.push([102,97,108,115,101]);return}else if(t.type.name==="null"){e.push([110,117,108,108]);return}let n=String(t.value),o=[],i=!1;for(let s=0;s<n.length;s++)o[s]=n.charCodeAt(s),!i&&(o[s]===46||o[s]===101||o[s]===69)&&(i=!0);i||(o.push(46),o.push(48)),e.push(o)}};function Fu(r,e){if(Array.isArray(r[0])||Array.isArray(e[0]))throw new Error(`${ce} complex map keys are not supported`);let t=r[0],n=e[0];if(t.type!==c.string||n.type!==c.string)throw new Error(`${ce} non-string map keys are not supported`);if(t<n)return-1;if(t>n)return 1;throw new Error(`${ce} unexpected duplicate map keys, this is not supported`)}var Ou={addBreakTokens:!0,mapSorter:Fu};function Qn(r,e){return e=Object.assign({},Ou,e),Nn(r,new Gn,e)}var qe=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(`${m} 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(`${m} unexpected token at position ${this._pos}, expected to find '${String.fromCharCode(...e)}'`)}parseNumber(){let e=this._pos,t=!1,n=!1,o=a=>{for(;!this.done();){let u=this.ch();if(a.includes(u))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 h(c.uint,0,this._pos-e);if(o([48,49,50,51,52,53,54,55,56,57]),t&&this._pos===e+1)throw new Error(`${m} unexpected token at position ${this._pos}`);if(!this.done()&&this.ch()===46){if(n)throw new Error(`${m} unexpected token at position ${this._pos}`);n=!0,this._pos++,o([48,49,50,51,52,53,54,55,56,57])}!this.done()&&(this.ch()===101||this.ch()===69)&&(n=!0,this._pos++,!this.done()&&(this.ch()===43||this.ch()===45)&&this._pos++,o([48,49,50,51,52,53,54,55,56,57]));let i=String.fromCharCode.apply(null,this.data.subarray(e,this._pos)),s=parseFloat(i);return n?new h(c.float,s,this._pos-e):this.options.allowBigInt!==!0||Number.isSafeInteger(s)?new h(s>=0?c.uint:c.negint,s,this._pos-e):new h(s>=0?c.uint:c.negint,BigInt(i),this._pos-e)}parseString(){if(this.ch()!==34)throw new Error(`${m} unexpected character at position ${this._pos}; this shouldn't happen`);this._pos++;for(let i=this._pos,s=0;i<this.data.length&&s<65536;i++,s++){let a=this.data[i];if(a===92||a<32||a>=128)break;if(a===34){let u=String.fromCharCode.apply(null,this.data.subarray(this._pos,i));return this._pos=i+1,new h(c.string,u,s)}}let e=this._pos,t=[],n=()=>{if(this._pos+4>=this.data.length)throw new Error(`${m} unexpected end of unicode escape sequence at position ${this._pos}`);let i=0;for(let s=0;s<4;s++){let a=this.ch();if(a>=48&&a<=57)a-=48;else if(a>=97&&a<=102)a=a-97+10;else if(a>=65&&a<=70)a=a-65+10;else throw new Error(`${m} unexpected unicode escape character at position ${this._pos}`);i=i*16+a,this._pos++}return i},o=()=>{let i=this.ch(),s=null,a=i>239?4:i>223?3:i>191?2:1;if(this._pos+a>this.data.length)throw new Error(`${m} unexpected unicode sequence at position ${this._pos}`);let u,d,l,f;switch(a){case 1:i<128&&(s=i);break;case 2:u=this.data[this._pos+1],(u&192)===128&&(f=(i&31)<<6|u&63,f>127&&(s=f));break;case 3:u=this.data[this._pos+1],d=this.data[this._pos+2],(u&192)===128&&(d&192)===128&&(f=(i&15)<<12|(u&63)<<6|d&63,f>2047&&(f<55296||f>57343)&&(s=f));break;case 4:u=this.data[this._pos+1],d=this.data[this._pos+2],l=this.data[this._pos+3],(u&192)===128&&(d&192)===128&&(l&192)===128&&(f=(i&15)<<18|(u&63)<<12|(d&63)<<6|l&63,f>65535&&f<1114112&&(s=f))}s===null?(s=65533,a=1):s>65535&&(s-=65536,t.push(s>>>10&1023|55296),s=56320|s&1023),t.push(s),this._pos+=a};for(;!this.done();){let i=this.ch(),s;switch(i){case 92:if(this._pos++,this.done())throw new Error(`${m} 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(`${m} unexpected string escape character at position ${this._pos}`)}break;case 34:return this._pos++,new h(c.string,Cn(t),this._pos-e);default:if(i<32)throw new Error(`${m} invalid control character at position ${this._pos}`);i<128?(t.push(i),this._pos++):o()}}throw new Error(`${m} unexpected end of string at position ${this._pos}`)}parseValue(){switch(this.ch()){case 123:return this.modeStack.push("obj-start"),this._pos++,new h(c.map,1/0,1);case 91:return this.modeStack.push("array-start"),this._pos++,new h(c.array,1/0,1);case 34:return this.parseString();case 110:return this.expect([110,117,108,108]),new h(c.null,null,4);case 102:return this.expect([102,97,108,115,101]),new h(c.false,!1,5);case 116:return this.expect([116,114,117,101]),new h(c.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(`${m} 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 h(c.break,void 0,1);if(this.ch()!==44)throw new Error(`${m} 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 h(c.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 h(c.break,void 0,1);if(this.ch()!==44)throw new Error(`${m} 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 h(c.break,void 0,1);let e=this.parseString();if(this.skipWhitespace(),this.ch()!==58)throw new Error(`${m} 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(`${m} unexpected parse state at position ${this._pos}; this shouldn't happen`)}}};function Jn(r,e){return e=Object.assign({tokenizer:new qe(r,e)},e),re(r,e)}function Mu(r){return r instanceof ArrayBuffer?new Uint8Array(r,0,r.byteLength):r}function $u(r){if(r.asCID!==r&&r["/"]!==r.bytes)return null;let e=k.asCID(r);if(!e)return null;let t=e.toString();return[new h(c.map,1/0,1),new h(c.string,"/",1),new h(c.string,t,t.length),new h(c.break,void 0,1)]}function Cr(r){let e=ge.encode(r).slice(1);return[new h(c.map,1/0,1),new h(c.string,"/",1),new h(c.map,1/0,1),new h(c.string,"bytes",5),new h(c.string,e,e.length),new h(c.break,void 0,1),new h(c.break,void 0,1)]}function ne(r){return Cr(new Uint8Array(r.buffer,r.byteOffset,r.byteLength))}function qu(r){return Cr(new Uint8Array(r))}function ju(){throw new Error("`undefined` is not supported by the IPLD Data Model and cannot be encoded")}function Vu(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 Ku={typeEncoders:{Object:$u,Buffer:Cr,Uint8Array:Cr,Int8Array:ne,Uint16Array:ne,Int16Array:ne,Uint32Array:ne,Int32Array:ne,Float32Array:ne,Float64Array:ne,Uint8ClampedArray:ne,BigInt64Array:ne,BigUint64Array:ne,DataView:ne,ArrayBuffer:qu,undefined:ju,number:Vu}},Yn=class extends qe{constructor(e,t){super(e,t),this.tokenBuffer=[]}done(){return this.tokenBuffer.length===0&&super.done()}_next(){return this.tokenBuffer.length>0?this.tokenBuffer.pop():super.next()}next(){let e=this._next();if(e.type===c.map){let t=this._next();if(t.type===c.string&&t.value==="/"){let n=this._next();if(n.type===c.string){if(this._next().type!==c.break)throw new Error("Invalid encoded CID form");return this.tokenBuffer.push(n),new h(c.tag,42,0)}if(n.type===c.map){let o=this._next();if(o.type===c.string&&o.value==="bytes"){let i=this._next();if(i.type===c.string){for(let a=0;a<2;a++)if(this._next().type!==c.break)throw new Error("Invalid encoded Bytes form");let s=ge.decode(`m${i.value}`);return new h(c.bytes,s,i.value.length)}this.tokenBuffer.push(i)}this.tokenBuffer.push(o)}this.tokenBuffer.push(n)}this.tokenBuffer.push(t)}return e}},Xn={allowIndefinite:!1,allowUndefined:!1,allowNaN:!1,allowInfinity:!1,allowBigInt:!0,strict:!0,useMaps:!1,rejectDuplicateMapKeys:!0,tags:[]};Xn.tags[42]=k.parse;var Hu="dag-json",Zn=297,As=r=>Qn(r,Ku),Cs=r=>{let e=Mu(r),t=Object.assign(Xn,{tokenizer:new Yn(e,Xn)});return Jn(e,t)},Wu=r=>Gu.decode(As(r));var Gu=new TextDecoder,Qu=r=>Cs(Ju.encode(r)),Ju=new TextEncoder;var so={};T(so,{code:()=>io,createLink:()=>Bs,createNode:()=>Us,decode:()=>ul,encode:()=>cl,name:()=>al,prepare:()=>no,validate:()=>oo});var Yu=new TextDecoder;function to(r,e){let t=0;for(let n=0;;n+=7){if(n>=64)throw new Error("protobuf: varint overflow");if(e>=r.length)throw new Error("protobuf: unexpected end of data");let o=r[e++];if(t+=n<28?(o&127)<<n:(o&127)*2**n,o<128)break}return[t,e]}function Sr(r,e){let t;[t,e]=to(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 Ss(r,e){let t;return[t,e]=to(r,e),[t&7,t>>3,e]}function Xu(r){let e={},t=r.length,n=0;for(;n<t;){let o,i;if([o,i,n]=Ss(r,n),i===1){if(e.Hash)throw new Error("protobuf: (PBLink) duplicate Hash section");if(o!==2)throw new Error(`protobuf: (PBLink) wrong wireType (${o}) for Hash`);if(e.Name!==void 0)throw new Error("protobuf: (PBLink) invalid order, found Name before Hash");if(e.Tsize!==void 0)throw new Error("protobuf: (PBLink) invalid order, found Tsize before Hash");[e.Hash,n]=Sr(r,n)}else if(i===2){if(e.Name!==void 0)throw new Error("protobuf: (PBLink) duplicate Name section");if(o!==2)throw new Error(`protobuf: (PBLink) wrong wireType (${o}) for Name`);if(e.Tsize!==void 0)throw new Error("protobuf: (PBLink) invalid order, found Tsize before Name");let s;[s,n]=Sr(r,n),e.Name=Yu.decode(s)}else if(i===3){if(e.Tsize!==void 0)throw new Error("protobuf: (PBLink) duplicate Tsize section");if(o!==0)throw new Error(`protobuf: (PBLink) wrong wireType (${o}) for Tsize`);[e.Tsize,n]=to(r,n)}else throw new Error(`protobuf: (PBLink) invalid fieldNumber, expected 1, 2 or 3, got ${i}`)}if(n>t)throw new Error("protobuf: (PBLink) unexpected end of data");return e}function Is(r){let e=r.length,t=0,n,o=!1,i;for(;t<e;){let a,u;if([a,u,t]=Ss(r,t),a!==2)throw new Error(`protobuf: (PBNode) invalid wireType, expected 2, got ${a}`);if(u===1){if(i)throw new Error("protobuf: (PBNode) duplicate Data section");[i,t]=Sr(r,t),n&&(o=!0)}else if(u===2){if(o)throw new Error("protobuf: (PBNode) duplicate Links section");n||(n=[]);let d;[d,t]=Sr(r,t),n.push(Xu(d))}else throw new Error(`protobuf: (PBNode) invalid fieldNumber, expected 1 or 2, got ${u}`)}if(t>e)throw new Error("protobuf: (PBNode) unexpected end of data");let s={};return i&&(s.Data=i),s.Links=n||[],s}var Ls=new TextEncoder,Ts=2**32,Zu=2**31;function el(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=lt(e,t,r.Tsize)-1,e[t]=24}if(typeof r.Name=="string"){let n=Ls.encode(r.Name);t-=n.length,e.set(n,t),t=lt(e,t,n.length)-1,e[t]=18}return r.Hash&&(t-=r.Hash.length,e.set(r.Hash,t),t=lt(e,t,r.Hash.length)-1,e[t]=10),e.length-t}function Ps(r){let e=rl(r),t=new Uint8Array(e),n=e;if(r.Data&&(n-=r.Data.length,t.set(r.Data,n),n=lt(t,n,r.Data.length)-1,t[n]=10),r.Links)for(let o=r.Links.length-1;o>=0;o--){let i=el(r.Links[o],t.subarray(0,n));n-=i,n=lt(t,n,i)-1,t[n]=18}return t}function tl(r){let e=0;if(r.Hash){let t=r.Hash.length;e+=1+t+je(t)}if(typeof r.Name=="string"){let t=Ls.encode(r.Name).length;e+=1+t+je(t)}return typeof r.Tsize=="number"&&(e+=1+je(r.Tsize)),e}function rl(r){let e=0;if(r.Data){let t=r.Data.length;e+=1+t+je(t)}if(r.Links)for(let t of r.Links){let n=tl(t);e+=1+n+je(n)}return e}function lt(r,e,t){e-=je(t);let n=e;for(;t>=Zu;)r[e++]=t&127|128,t/=128;for(;t>=128;)r[e++]=t&127|128,t>>>=7;return r[e]=t,n}function je(r){return r%2===0&&r++,Math.floor((nl(r)+6)/7)}function nl(r){let e=0;return r>=Ts&&(r=Math.floor(r/Ts),e=32),r>=65536&&(r>>>=16,e+=16),r>=256&&(r>>>=8,e+=8),e+ol[r]}var ol=[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 il=["Data","Links"],sl=["Hash","Name","Tsize"],ro=new TextEncoder;function Rs(r,e){if(r===e)return 0;let t=r.Name?ro.encode(r.Name):[],n=e.Name?ro.encode(e.Name):[],o=t.length,i=n.length;for(let s=0,a=Math.min(o,i);s<a;++s)if(t[s]!==n[s]){o=t[s],i=n[s];break}return o<i?-1:i<o?1:0}function Ns(r,e){return!Object.keys(r).some(t=>!e.includes(t))}function Ds(r){if(typeof r.asCID=="object"){let t=k.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=k.asCID(r.Hash);try{t||(typeof r.Hash=="string"?t=k.parse(r.Hash):r.Hash instanceof Uint8Array&&(t=k.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 no(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=ro.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(Ds),e.Links.sort(Rs);else throw new TypeError("Invalid DAG-PB form");else e.Links=[];return e}function oo(r){if(!r||typeof r!="object"||Array.isArray(r)||r instanceof Uint8Array||r["/"]&&r["/"]===r.bytes)throw new TypeError("Invalid DAG-PB form");if(!Ns(r,il))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(!Ns(t,sl))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&&Rs(t,r.Links[e-1])===-1)throw new TypeError("Invalid DAG-PB form (links must be sorted by Name bytes)")}}function Us(r,e=[]){return no({Data:r,Links:e})}function Bs(r,e,t){return Ds({Hash:t,Name:r,Tsize:e})}function Fs(r){return r instanceof ArrayBuffer?new Uint8Array(r,0,r.byteLength):r}var al="dag-pb",io=112;function cl(r){oo(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),Ps(e)}function ul(r){let e=Fs(r),t=Is(e),n={};return t.Data&&(n.Data=t.Data),t.Links&&(n.Links=t.Links.map(o=>{let i={};try{i.Hash=k.decode(o.Hash)}catch{}if(!i.Hash)throw new Error("Invalid Hash field found in link, expected CID");return o.Name!==void 0&&(i.Name=o.Name),o.Tsize!==void 0&&(i.Tsize=o.Tsize),i})),n}function Ve(r){return r?.then!=null}function Os(r=[],e){let t={[io]:so,[sn]:xt,[Hn]:Wn,[Zn]:eo,[on]:bt};return r.forEach(n=>{t[n.code]=n}),async n=>{let o=t[n];if(o==null&&e!=null){let i=e(n);Ve(i)?o=await i:o=i,t[o.code]=o}if(o!=null)return o;throw new or(`Could not load codec for ${n}`)}}function zs(r=[],e){let t={[_t.code]:_t,[kt.code]:kt,[vt.code]:vt};return r.forEach(n=>{t[n.code]=n}),async n=>{let o=t[n];if(o==null&&e!=null){let i=e(n);Ve(i)?o=await i:o=i,t[o.code]=o}if(o!=null)return o;throw new nr(`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 Ir=class r extends Error{static name="NotFoundError";static code="ERR_NOT_FOUND";name=r.name;code=r.code;constructor(e="Not Found"){super(e)}};var Tr=class{has(e,t){return Promise.reject(new Error(".has is not implemented"))}put(e,t,n){return Promise.reject(new Error(".put is not implemented"))}async*putMany(e,t){for await(let{cid:n,bytes:o}of e)await this.put(n,o,t),yield n}get(e,t){throw new Error(".get is not implemented")}async*getMany(e,t){for await(let n of e)yield{cid:n,bytes:this.get(n,t)}}delete(e,t){return Promise.reject(new Error(".delete is not implemented"))}async*deleteMany(e,t){for await(let n of e)await this.delete(n,t),yield n}async*getAll(e){throw new Error(".getAll is not implemented")}};var Lr=0,Pr=class extends Tr{child;constructor(e){super(),this.child=e}put(e,t,n){return e.multihash.code===Lr||this.child==null?(n?.signal?.throwIfAborted(),e):this.child.put(e,t,n)}*get(e,t){if(e.multihash.code===Lr){t?.signal?.throwIfAborted(),yield e.multihash.digest;return}if(this.child==null)throw t?.signal?.throwIfAborted(),new Ir;yield*this.child.get(e,t)}has(e,t){return e.multihash.code===Lr?(t?.signal?.throwIfAborted(),!0):this.child==null?(t?.signal?.throwIfAborted(),!1):this.child.has(e,t)}delete(e,t){if(e.code===Lr){t?.signal?.throwIfAborted();return}if(this.child!=null)return this.child.delete(e,t)}*getAll(e){this.child!=null&&(yield*this.child.getAll(e)),e?.signal?.throwIfAborted()}};function ll(r){let[e,t]=r[Symbol.asyncIterator]!=null?[r[Symbol.asyncIterator](),Symbol.asyncIterator]:[r[Symbol.iterator](),Symbol.iterator],n=[];return{peek:()=>e.next(),push:o=>{n.push(o)},next:()=>n.length>0?{done:!1,value:n.shift()}:e.next(),[t](){return this}}}var Nr=ll;function fl(r){return r[Symbol.asyncIterator]!=null}function hl(r,e){let t=0;if(fl(r))return(async function*(){for await(let u of r)await e(u,t++)&&(yield u)})();let n=Nr(r),{value:o,done:i}=n.next();if(i===!0)return(function*(){})();let s=e(o,t++);if(typeof s.then=="function")return(async function*(){await s&&(yield o);for(let u of n)await e(u,t++)&&(yield u)})();let a=e;return(function*(){s===!0&&(yield o);for(let u of n)a(u,t++)&&(yield u)})()}var Ms=hl;function dl(r){return r[Symbol.asyncIterator]!=null}function $s(r){return r?.then!=null}function pl(r,e){let t=0;if(dl(r))return(async function*(){for await(let u of r){let d=e(u,t++);$s(d)&&await d,yield u}})();let n=Nr(r),{value:o,done:i}=n.next();if(i===!0)return(function*(){})();if(typeof e(o,t++)?.then=="function")return(async function*(){yield o;for(let u of n){let d=e(u,t++);$s(d)&&await d,yield u}})();let a=e;return(function*(){yield o;for(let u of n)a(u,t++),yield u})()}var ao=pl;var Rr=class{child;getHasher;log;logger;components;constructor(e){this.log=e.logger.forComponent("helia:networked-storage"),this.logger=e.logger,this.components=e,this.child=new Pr(e.blockstore),this.getHasher=e.getHasher}async put(e,t,n={}){return await this.child.has(e,n)?(n.onProgress?.(new v("blocks:put:duplicate",e)),e):(n.onProgress?.(new v("blocks:put:providers:notify",e)),await Promise.all(this.components.blockBrokers.map(async o=>o.announce?.(e,n))),n.onProgress?.(new v("blocks:put:blockstore:put",e)),this.child.put(e,t,n))}async*putMany(e,t={}){let n=Ms(e,async({cid:i})=>{let s=await this.child.has(i,t);return s&&t.onProgress?.(new v("blocks:put-many:duplicate",i)),!s}),o=ao(n,async({cid:i})=>{t.onProgress?.(new v("blocks:put-many:providers:notify",i)),await Promise.all(this.components.blockBrokers.map(async s=>s.announce?.(i,t)))});t.onProgress?.(new v("blocks:put-many:blockstore:put-many")),yield*this.child.putMany(o,t)}async*get(e,t={}){if(t.offline!==!0&&!await this.child.has(e,t)){let n=await this.getHasher(e.multihash.code);t.onProgress?.(new v("blocks:get:providers:get",e));let o=await qs(e,this.components.blockBrokers,n,{...t,log:this.log});t.onProgress?.(new v("blocks:get:blockstore:put",e)),await this.child.put(e,o,t),t.onProgress?.(new v("blocks:get:providers:notify",e)),await Promise.all(this.components.blockBrokers.map(async i=>i.announce?.(e,t))),yield o;return}t.onProgress?.(new v("blocks:get:blockstore:get",e)),yield*this.child.get(e,t)}async*getMany(e,t={}){t.onProgress?.(new v("blocks:get-many:blockstore:get-many")),yield*this.child.getMany(ao(e,async n=>{if(t.offline!==!0&&!await this.child.has(n,t)){let o=await this.getHasher(n.multihash.code);t.onProgress?.(new v("blocks:get-many:providers:get",n));let i=await qs(n,this.components.blockBrokers,o,{...t,log:this.log});t.onProgress?.(new v("blocks:get-many:blockstore:put",n)),await this.child.put(n,i,t),t.onProgress?.(new v("blocks:get-many:providers:notify",n)),await Promise.all(this.components.blockBrokers.map(async s=>s.announce?.(n,t)))}}))}async delete(e,t={}){t.onProgress?.(new v("blocks:delete:blockstore:delete",e)),await this.child.delete(e,t)}async*deleteMany(e,t={}){t.onProgress?.(new v("blocks:delete-many:blockstore:delete-many")),yield*this.child.deleteMany((async function*(){for await(let n of e)yield n})(),t)}async has(e,t={}){return this.child.has(e,t)}async*getAll(e={}){e.onProgress?.(new v("blocks:get-all:blockstore:get-many")),yield*this.child.getAll(e)}},Dr=class extends Rr{started;constructor(e){super(e),this.started=!1}isStarted(){return this.started}async start(){await he(this.child,...this.components.blockBrokers),this.started=!0}async stop(){await de(this.child,...this.components.blockBrokers),this.started=!1}unwrap(){return this.child}createSession(e,t){let n=this.components.blockBrokers.map(o=>o.createSession==null?o:o.createSession(t));return new co({blockstore:this.child,blockBrokers:n,getHasher:this.getHasher,logger:this.logger},{root:e})}},co=class extends Rr{closeController;constructor(e,t){super(e),this.closeController=new AbortController,this.closeController.signal,this.log=e.logger.forComponent(`helia:session-storage:${t.root}`)}close(){this.closeController.abort()}async put(e,t,n={}){let o=oe([this.closeController.signal,n.signal]);try{return await super.put(e,t,{...n,signal:o})}finally{o.clear()}}async*putMany(e,t={}){let n=oe([this.closeController.signal,t.signal]);try{yield*super.putMany(e,{...t,signal:n})}finally{n.clear()}}async*get(e,t={}){let n=oe([this.closeController.signal,t.signal]);try{yield*super.get(e,{...t,signal:n})}finally{n.clear()}}async*getMany(e,t={}){let n=oe([this.closeController.signal,t.signal]);try{yield*super.getMany(e,{...t,signal:n})}finally{n.clear()}}async delete(e,t={}){let n=oe([this.closeController.signal,t.signal]);try{await super.delete(e,{...t,signal:n})}finally{n.clear()}}async*deleteMany(e,t={}){let n=oe([this.closeController.signal,t.signal]);try{yield*super.deleteMany(e,{...t,signal:n})}finally{n.clear()}}async has(e,t={}){let n=oe([this.closeController.signal,t.signal]);try{return await super.has(e,{...t,signal:n})}finally{n.clear()}}async*getAll(e={}){let t=oe([this.closeController.signal,e.signal]);try{yield*super.getAll({...e,signal:t})}finally{t.clear()}}};function gl(r){return typeof r.retrieve=="function"}var yl=(r,e)=>{if(e==null)throw new ht(`No hasher configured for multihash code 0x${r.multihash.code.toString(16)}, please configure one. You can look up which hash this is at https://github.com/multiformats/multicodec/blob/master/table.csv`);return async t=>{let n,o=e.digest(t);if(Ve(o)?n=await o:n=o,!xe(n.digest,r.multihash.digest))throw new pt("Hash of downloaded block did not match multihash from passed CID")}};async function qs(r,e,t,n){let o=yl(r,t),i=new AbortController,s=oe([i.signal,n.signal]);i.signal;let a=[];for(let u of e)gl(u)&&a.push(u);try{return await Promise.any(a.map(async u=>{try{let d=!1,l=await u.retrieve(r,{...n,signal:s,validateFn:async f=>{await o(f),d=!0}});return d||await o(l),l}catch(d){throw n.log.error("could not retrieve verified block for %c",r,d),d}}))}finally{i.abort(),s.clear()}}var Ur=class extends H{initialPeerSearchComplete;requests;name;log;logger;minProviders;maxProviders;providers;evictionFilter;initialProviders;constructor(e,t){super(),this.name=t.name,this.logger=e.logger,this.log=e.logger.forComponent(this.name),this.requests=new Map,this.minProviders=t.minProviders??1,this.maxProviders=t.maxProviders??5,this.providers=[],this.evictionFilter=vn(this.maxProviders),this.initialProviders=t.providers??[]}async retrieve(e,t={}){let n=ge.encode(e.multihash.bytes),o=this.requests.get(n);if(o!=null)return this.log("join existing request for %c",e),o;let i=B();if(this.requests.set(n,i.promise),this.providers.length===0){let l=!1;this.initialPeerSearchComplete==null&&(l=!0,this.log=this.logger.forComponent(`${this.name}:${e}`),this.initialPeerSearchComplete=this.findProviders(e,this.minProviders,t)),await this.initialPeerSearchComplete,l&&this.log("found initial session peers for %c",e)}let s=!1,a=new ae({concurrency:this.maxProviders});a.addEventListener("failure",l=>{this.log.error("error querying provider %o, evicting from session",l.detail.job.options.provider,l.detail.error),this.evict(l.detail.job.options.provider)}),a.addEventListener("success",l=>{s=!0,i.resolve(l.detail.result)}),a.addEventListener("idle",()=>{if(s||t.signal?.aborted===!0){this.log.trace("session idle, found block");return}Promise.resolve().then(async()=>{this.log("no session peers had block for for %c, finding new providers",e);for(let l=0;l<this.minProviders&&this.providers.length!==0;l++){let f=this.providers[Math.floor(Math.random()*this.providers.length)];this.evict(f)}await this.findProviders(e,this.minProviders,t),this.log("found new providers re-retrieving %c",e),this.requests.delete(n),i.resolve(await this.retrieve(e,t))}).catch(l=>{this.log.error("could not find new providers for %c",e,l),i.reject(l)})});let u=l=>{a.add(async()=>this.queryProvider(e,l.detail,t),{provider:l.detail}).catch(f=>{t.signal?.aborted!==!0&&this.log.error("error retrieving session block for %c",e,f)})};this.addEventListener("provider",u),Promise.all([...this.providers].map(async l=>a.add(async()=>this.queryProvider(e,l,t),{provider:l}))).catch(l=>{t.signal?.aborted!==!0&&this.log.error("error retrieving session block for %c",e,l)});let d=()=>{i.reject(new J(t.signal?.reason??"Session aborted")),a.abort()};t.signal?.addEventListener("abort",d);try{return await i.promise}finally{this.removeEventListener("provider",u),t.signal?.removeEventListener("abort",d),a.clear(),this.requests.delete(n)}}evict(e){this.evictionFilter.add(this.toEvictionKey(e));let t=this.providers.findIndex(n=>this.equals(n,e));t!==-1&&this.providers.splice(t,1)}isEvicted(e){return this.evictionFilter.has(this.toEvictionKey(e))}hasProvider(e){return!!(this.providers.find(t=>this.equals(t,e))!=null||this.isEvicted(e))}async findProviders(e,t,n){let o=B(),i=0;return Promise.resolve().then(async()=>{if(this.log("finding %d-%d new provider(s) for %c",t,this.maxProviders,e),this.initialProviders.length>0)for(;i<t&&this.initialProviders.length>0;){let s=this.initialProviders.pop();if(s==null)break;let a=await this.convertToProvider(s,n);if(n.signal?.aborted===!0)break;if(a!=null&&!this.hasProvider(a)&&(this.log("found %d/%d new providers",i,this.maxProviders),this.providers.push(a),this.safeDispatchEvent("provider",{detail:a}),i++,i===t&&(this.log("session is ready"),o.resolve()),this.providers.length===this.maxProviders)){this.log("found max session peers",i);break}}if(i<this.maxProviders)for await(let s of this.findNewProviders(e,n)){if(i===this.maxProviders||n.signal?.aborted===!0)break;if(!this.hasProvider(s)&&(this.log("found %d/%d new providers",i,this.maxProviders),this.providers.push(s),this.safeDispatchEvent("provider",{detail:s}),i++,i===t&&(this.log("session is ready"),o.resolve()),this.providers.length===this.maxProviders)){this.log("found max session peers",i);break}}if(this.log("found %d/%d new session peers",i,this.maxProviders),i<t)throw new rr(`Found ${i} of ${t} ${this.name} providers for ${e}`)}).catch(s=>{this.log.error("error searching routing for potential session peers for %c",e,s.errors??s),o.reject(s)}),o.promise}};var uo=class{libp2p;blockstore;datastore;events;pins;logger;routing;getCodec;getHasher;dns;metrics;log;constructor(e){this.logger=e.logger??vo(),this.log=this.logger.forComponent("helia"),this.getHasher=zs(e.hashers,e.loadHasher),this.getCodec=Os(e.codecs,e.loadCodec),this.dns=e.dns??Jo(),this.metrics=e.metrics,this.libp2p=e.libp2p,this.events=new H;let t={blockstore:e.blockstore,datastore:e.datastore,logger:this.logger,libp2p:this.libp2p,blockBrokers:[],getHasher:this.getHasher,getCodec:this.getCodec,dns:this.dns,metrics:this.metrics,...e.components??{}};this.routing=t.routing=new ir(t,{routers:(e.routers??[]).flatMap(o=>{let i=[o];return o[Br]!=null&&i.push(o[Br]),o[Fr]!=null&&i.push(o[Fr]),i}),providerLookupConcurrency:e.providerLookupConcurrency});let n=new Dr(t);this.pins=new tr(e.datastore,n,this.getCodec),this.blockstore=new kr(n,this.pins,{holdGcLock:e.holdGcLock??!0}),this.datastore=e.datastore,t.blockBrokers=e.blockBrokers.map(o=>o(t))}async start(){await vs(this.datastore),await he(this.blockstore,this.datastore,this.routing,this.libp2p),this.events.dispatchEvent(new CustomEvent("start",{detail:this}))}async stop(){await de(this.blockstore,this.datastore,this.routing,this.libp2p),this.events.dispatchEvent(new CustomEvent("stop",{detail:this}))}async gc(e={}){let t=await this.blockstore.lock.writeLock();try{let n=this,o=this.blockstore.unwrap();this.log("gc start"),await Yo(o.deleteMany((async function*(){for await(let{cid:i}of o.getAll())try{if(await n.pins.isPinned(i,e))continue;yield i,e.onProgress?.(new v("helia:gc:deleted",i))}catch(s){n.log.error("Error during gc",s),e.onProgress?.(new v("helia:gc:error",s))}})()))}finally{t()}this.log("gc finished")}};return Gs(xl);})();
2
+ "use strict";var HeliaUtils=(()=>{var Hs=Object.create;var dt=Object.defineProperty;var Ws=Object.getOwnPropertyDescriptor;var Gs=Object.getOwnPropertyNames;var Qs=Object.getPrototypeOf,Js=Object.prototype.hasOwnProperty;var po=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),T=(r,e)=>{for(var t in e)dt(r,t,{get:e[t],enumerable:!0})},mo=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Gs(e))!Js.call(r,o)&&o!==t&&dt(r,o,{get:()=>e[o],enumerable:!(n=Ws(e,o))||n.enumerable});return r};var go=(r,e,t)=>(t=r!=null?Hs(Qs(r)):{},mo(e||!r||!r.__esModule?dt(t,"default",{value:r,enumerable:!0}):t,r)),Ys=r=>mo(dt({},"__esModule",{value:!0}),r);var Io=po((Xl,Jr)=>{"use strict";var La=Object.prototype.hasOwnProperty,R="~";function He(){}Object.create&&(He.prototype=Object.create(null),new He().__proto__||(R=!1));function Pa(r,e,t){this.fn=r,this.context=e,this.once=t||!1}function So(r,e,t,n,o){if(typeof t!="function")throw new TypeError("The listener must be a function");var i=new Pa(t,n||r,o),s=R?R+e:e;return r._events[s]?r._events[s].fn?r._events[s]=[r._events[s],i]:r._events[s].push(i):(r._events[s]=i,r._eventsCount++),r}function wt(r,e){--r._eventsCount===0?r._events=new He:delete r._events[e]}function N(){this._events=new He,this._eventsCount=0}N.prototype.eventNames=function(){var e=[],t,n;if(this._eventsCount===0)return e;for(n in t=this._events)La.call(t,n)&&e.push(R?n.slice(1):n);return Object.getOwnPropertySymbols?e.concat(Object.getOwnPropertySymbols(t)):e};N.prototype.listeners=function(e){var t=R?R+e:e,n=this._events[t];if(!n)return[];if(n.fn)return[n.fn];for(var o=0,i=n.length,s=new Array(i);o<i;o++)s[o]=n[o].fn;return s};N.prototype.listenerCount=function(e){var t=R?R+e:e,n=this._events[t];return n?n.fn?1:n.length:0};N.prototype.emit=function(e,t,n,o,i,s){var a=R?R+e:e;if(!this._events[a])return!1;var u=this._events[a],d=arguments.length,l,f;if(u.fn){switch(u.once&&this.removeListener(e,u.fn,void 0,!0),d){case 1:return u.fn.call(u.context),!0;case 2:return u.fn.call(u.context,t),!0;case 3:return u.fn.call(u.context,t,n),!0;case 4:return u.fn.call(u.context,t,n,o),!0;case 5:return u.fn.call(u.context,t,n,o,i),!0;case 6:return u.fn.call(u.context,t,n,o,i,s),!0}for(f=1,l=new Array(d-1);f<d;f++)l[f-1]=arguments[f];u.fn.apply(u.context,l)}else{var g=u.length,y;for(f=0;f<g;f++)switch(u[f].once&&this.removeListener(e,u[f].fn,void 0,!0),d){case 1:u[f].fn.call(u[f].context);break;case 2:u[f].fn.call(u[f].context,t);break;case 3:u[f].fn.call(u[f].context,t,n);break;case 4:u[f].fn.call(u[f].context,t,n,o);break;default:if(!l)for(y=1,l=new Array(d-1);y<d;y++)l[y-1]=arguments[y];u[f].fn.apply(u[f].context,l)}}return!0};N.prototype.on=function(e,t,n){return So(this,e,t,n,!1)};N.prototype.once=function(e,t,n){return So(this,e,t,n,!0)};N.prototype.removeListener=function(e,t,n,o){var i=R?R+e:e;if(!this._events[i])return this;if(!t)return wt(this,i),this;var s=this._events[i];if(s.fn)s.fn===t&&(!o||s.once)&&(!n||s.context===n)&&wt(this,i);else{for(var a=0,u=[],d=s.length;a<d;a++)(s[a].fn!==t||o&&!s[a].once||n&&s[a].context!==n)&&u.push(s[a]);u.length?this._events[i]=u.length===1?u[0]:u:wt(this,i)}return this};N.prototype.removeAllListeners=function(e){var t;return e?(t=R?R+e:e,this._events[t]&&wt(this,t)):(this._events=new He,this._eventsCount=0),this};N.prototype.off=N.prototype.removeListener;N.prototype.addListener=N.prototype.on;N.prefixed=R;N.EventEmitter=N;typeof Jr<"u"&&(Jr.exports=N)});var Jo=po((ih,Qo)=>{Qo.exports=function(r){if(!r)throw Error("hashlru must have a max value, of type number, greater than 0");var e=0,t=Object.create(null),n=Object.create(null);function o(i,s){t[i]=s,e++,e>=r&&(e=0,n=t,t=Object.create(null))}return{has:function(i){return t[i]!==void 0||n[i]!==void 0},remove:function(i){t[i]!==void 0&&(t[i]=void 0),n[i]!==void 0&&(n[i]=void 0)},get:function(i){var s=t[i];if(s!==void 0)return s;if((s=n[i])!==void 0)return o(i,s),s},set:function(i,s){t[i]!==void 0?t[i]=s:o(i,s)},clear:function(){t=Object.create(null),n=Object.create(null)}}}});var _l={};T(_l,{AbstractSession:()=>Or,Helia:()=>ho});var zr=Symbol.for("@libp2p/content-routing");var J=class extends Error{static name="AbortError";constructor(e="The operation was aborted"){super(e),this.name="AbortError"}};var Te=class extends Error{static name="InvalidParametersError";constructor(e="Invalid parameters"){super(e),this.name="InvalidParametersError"}};var pt=class extends Error{static name="NotFoundError";constructor(e="Not found"){super(e),this.name="NotFoundError"}};var mt=class extends Error{static name="InvalidMultihashError";constructor(e="Invalid Multihash"){super(e),this.name="InvalidMultihashError"}};var Mr=Symbol.for("@libp2p/peer-routing");function yo(r){return r!=null&&typeof r.start=="function"&&typeof r.stop=="function"}async function he(...r){let e=[];for(let t of r)yo(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 de(...r){let e=[];for(let t of r)yo(t)&&e.push(t);await Promise.all(e.map(async t=>{t.beforeStop!=null&&await t.beforeStop()})),await Promise.all(e.map(async t=>{await t.stop()})),await Promise.all(e.map(async t=>{t.afterStop!=null&&await t.afterStop()}))}var H=class extends EventTarget{#e=new Map;constructor(){super()}listenerCount(e){let t=this.#e.get(e);return t==null?0:t.length}addEventListener(e,t,n){super.addEventListener(e,t,n);let o=this.#e.get(e);o==null&&(o=[],this.#e.set(e,o)),o.push({callback:t,once:(n!==!0&&n!==!1&&n?.once)??!1})}removeEventListener(e,t,n){super.removeEventListener(e.toString(),t??null,n);let o=this.#e.get(e);o!=null&&(o=o.filter(({callback:i})=>i!==t),this.#e.set(e,o))}dispatchEvent(e){let t=super.dispatchEvent(e),n=this.#e.get(e.type);return n==null||(n=n.filter(({once:o})=>!o),this.#e.set(e.type,n)),t}safeDispatchEvent(e,t={}){return this.dispatchEvent(new CustomEvent(e,t))}};var Hr={};T(Hr,{base32:()=>me,base32hex:()=>aa,base32hexpad:()=>ua,base32hexpadupper:()=>la,base32hexupper:()=>ca,base32pad:()=>ia,base32padupper:()=>sa,base32upper:()=>oa,base32z:()=>fa});var Ll=new Uint8Array(0);function wo(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 Y(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength);throw new Error("Unknown type, must be binary type")}function bo(r){return new TextEncoder().encode(r)}function xo(r){return new TextDecoder().decode(r)}function Xs(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),n=0;n<t.length;n++)t[n]=255;for(var o=0;o<r.length;o++){var i=r.charAt(o),s=i.charCodeAt(0);if(t[s]!==255)throw new TypeError(i+" is ambiguous");t[s]=o}var a=r.length,u=r.charAt(0),d=Math.log(a)/Math.log(256),l=Math.log(256)/Math.log(a);function f(b){if(b instanceof Uint8Array||(ArrayBuffer.isView(b)?b=new Uint8Array(b.buffer,b.byteOffset,b.byteLength):Array.isArray(b)&&(b=Uint8Array.from(b))),!(b instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(b.length===0)return"";for(var x=0,w=0,_=0,C=b.length;_!==C&&b[_]===0;)_++,x++;for(var S=(C-_)*l+1>>>0,I=new Uint8Array(S);_!==C;){for(var F=b[_],V=0,O=S-1;(F!==0||V<w)&&O!==-1;O--,V++)F+=256*I[O]>>>0,I[O]=F%a>>>0,F=F/a>>>0;if(F!==0)throw new Error("Non-zero carry");w=V,_++}for(var K=S-w;K!==S&&I[K]===0;)K++;for(var Ie=u.repeat(x);K<S;++K)Ie+=r.charAt(I[K]);return Ie}function g(b){if(typeof b!="string")throw new TypeError("Expected String");if(b.length===0)return new Uint8Array;var x=0;if(b[x]!==" "){for(var w=0,_=0;b[x]===u;)w++,x++;for(var C=(b.length-x)*d+1>>>0,S=new Uint8Array(C);b[x];){var I=t[b.charCodeAt(x)];if(I===255)return;for(var F=0,V=C-1;(I!==0||F<_)&&V!==-1;V--,F++)I+=a*S[V]>>>0,S[V]=I%256>>>0,I=I/256>>>0;if(I!==0)throw new Error("Non-zero carry");_=F,x++}if(b[x]!==" "){for(var O=C-_;O!==C&&S[O]===0;)O++;for(var K=new Uint8Array(w+(C-O)),Ie=w;O!==C;)K[Ie++]=S[O++];return K}}}function y(b){var x=g(b);if(x)return x;throw new Error(`Non-${e} character`)}return{encode:f,decodeUnsafe:g,decode:y}}var Zs=Xs,ea=Zs,Eo=ea;var qr=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")}},jr=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,n){this.name=e,this.prefix=t;let o=t.codePointAt(0);if(o===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=o,this.baseDecode=n}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return vo(this,e)}},Vr=class{decoders;constructor(e){this.decoders=e}or(e){return vo(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 vo(r,e){return new Vr({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var Kr=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,n,o){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=o,this.encoder=new qr(e,t,n),this.decoder=new jr(e,t,o)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function Le({name:r,prefix:e,encode:t,decode:n}){return new Kr(r,e,t,n)}function pe({name:r,prefix:e,alphabet:t}){let{encode:n,decode:o}=Eo(t,r);return Le({prefix:e,name:r,encode:n,decode:i=>Y(o(i))})}function ta(r,e,t,n){let o=r.length;for(;r[o-1]==="=";)--o;let i=new Uint8Array(o*t/8|0),s=0,a=0,u=0;for(let d=0;d<o;++d){let l=e[r[d]];if(l===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<t|l,s+=t,s>=8&&(s-=8,i[u++]=255&a>>s)}if(s>=t||(255&a<<8-s)!==0)throw new SyntaxError("Unexpected end of data");return i}function ra(r,e,t){let n=e[e.length-1]==="=",o=(1<<t)-1,i="",s=0,a=0;for(let u=0;u<r.length;++u)for(a=a<<8|r[u],s+=8;s>t;)s-=t,i+=e[o&a>>s];if(s!==0&&(i+=e[o&a<<t-s]),n)for(;(i.length*t&7)!==0;)i+="=";return i}function na(r){let e={};for(let t=0;t<r.length;++t)e[r[t]]=t;return e}function A({name:r,prefix:e,bitsPerChar:t,alphabet:n}){let o=na(n);return Le({prefix:e,name:r,encode(i){return ra(i,n,t)},decode(i){return ta(i,o,t,r)}})}var me=A({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),oa=A({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),ia=A({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),sa=A({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),aa=A({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),ca=A({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),ua=A({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),la=A({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),fa=A({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Wr={};T(Wr,{base58btc:()=>W,base58flickr:()=>ha});var W=pe({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),ha=pe({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var Gr={};T(Gr,{base64:()=>ge,base64pad:()=>da,base64url:()=>pa,base64urlpad:()=>ma});var ge=A({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),da=A({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),pa=A({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),ma=A({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});function ga(r,e){if(typeof r=="string")return ya(r);if(typeof r=="number")return xa(r,e);throw Error(`Value provided to ms() must be a string or number. value=${JSON.stringify(r)}`)}var gt=ga;function ya(r){if(typeof r!="string"||r.length===0||r.length>100)throw Error(`Value provided to ms.parse() must be a string with length between 1 and 99. value=${JSON.stringify(r)}`);let e=/^(?<value>-?\d*\.?\d+) *(?<unit>milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|months?|mo|years?|yrs?|y)?$/i.exec(r);if(!e?.groups)return NaN;let{value:t,unit:n="ms"}=e.groups,o=parseFloat(t),i=n.toLowerCase();switch(i){case"years":case"year":case"yrs":case"yr":case"y":return o*315576e5;case"months":case"month":case"mo":return o*26298e5;case"weeks":case"week":case"w":return o*6048e5;case"days":case"day":case"d":return o*864e5;case"hours":case"hour":case"hrs":case"hr":case"h":return o*36e5;case"minutes":case"minute":case"mins":case"min":case"m":return o*6e4;case"seconds":case"second":case"secs":case"sec":case"s":return o*1e3;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return o;default:throw Error(`Unknown unit "${i}" provided to ms.parse(). value=${JSON.stringify(r)}`)}}function wa(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 ba(r){let e=Math.abs(r);return e>=315576e5?be(r,e,315576e5,"year"):e>=26298e5?be(r,e,26298e5,"month"):e>=6048e5?be(r,e,6048e5,"week"):e>=864e5?be(r,e,864e5,"day"):e>=36e5?be(r,e,36e5,"hour"):e>=6e4?be(r,e,6e4,"minute"):e>=1e3?be(r,e,1e3,"second"):`${r} ms`}function xa(r,e){if(typeof r!="number"||!Number.isFinite(r))throw Error("Value provided to ms.format() must be of type number.");return e?.long?ba(r):wa(r)}function be(r,e,t,n){let o=e>=t*1.5;return`${Math.round(r/t)} ${n}${o?"s":""}`}function Qr(r){t.debug=t,t.default=t,t.coerce=u,t.disable=i,t.enable=o,t.enabled=s,t.humanize=gt,t.destroy=d,Object.keys(r).forEach(l=>{t[l]=r[l]}),t.names=[],t.skips=[],t.formatters={};function e(l){let f=0;for(let g=0;g<l.length;g++)f=(f<<5)-f+l.charCodeAt(g),f|=0;return t.colors[Math.abs(f)%t.colors.length]}t.selectColor=e;function t(l){let f,g=null,y,b;function x(...w){if(!x.enabled)return;let _=x,C=Number(new Date),S=C-(f||C);_.diff=S,_.prev=f,_.curr=C,f=C,w[0]=t.coerce(w[0]),typeof w[0]!="string"&&w.unshift("%O");let I=0;w[0]=w[0].replace(/%([a-zA-Z%])/g,(V,O)=>{if(V==="%%")return"%";I++;let K=t.formatters[O];if(typeof K=="function"){let Ie=w[I];V=K.call(_,Ie),w.splice(I,1),I--}return V}),t.formatArgs.call(_,w),(_.log||t.log).apply(_,w)}return x.namespace=l,x.useColors=t.useColors(),x.color=t.selectColor(l),x.extend=n,x.destroy=t.destroy,Object.defineProperty(x,"enabled",{enumerable:!0,configurable:!1,get:()=>g!==null?g:(y!==t.namespaces&&(y=t.namespaces,b=t.enabled(l)),b),set:w=>{g=w}}),typeof t.init=="function"&&t.init(x),x}function n(l,f){let g=t(this.namespace+(typeof f>"u"?":":f)+l);return g.log=this.log,g}function o(l){t.save(l),t.namespaces=l,t.names=[],t.skips=[];let f,g=(typeof l=="string"?l:"").split(/[\s,]+/),y=g.length;for(f=0;f<y;f++)g[f]&&(l=g[f].replace(/\*/g,".*?"),l[0]==="-"?t.skips.push(new RegExp("^"+l.substr(1)+"$")):t.names.push(new RegExp("^"+l+"$")))}function i(){let l=[...t.names.map(a),...t.skips.map(a).map(f=>"-"+f)].join(",");return t.enable(""),l}function s(l){if(l[l.length-1]==="*")return!0;let f,g;for(f=0,g=t.skips.length;f<g;f++)if(t.skips[f].test(l))return!1;for(f=0,g=t.names.length;f<g;f++)if(t.names[f].test(l))return!0;return!1}function a(l){return l.toString().substring(2,l.toString().length-2).replace(/\.\*\?$/,"*")}function u(l){return l instanceof Error?l.stack??l.message:l}function d(){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 yt=Sa(),Ea=["#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 va(){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 _a(r){if(r[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+r[0]+(this.useColors?"%c ":" ")+"+"+gt(this.diff),!this.useColors)return;let e="color: "+this.color;r.splice(1,0,e,"color: inherit");let t=0,n=0;r[0].replace(/%[a-zA-Z%]/g,o=>{o!=="%%"&&(t++,o==="%c"&&(n=t))}),r.splice(n,0,e)}var ka=console.debug??console.log??(()=>{});function Aa(r){try{r?yt?.setItem("debug",r):yt?.removeItem("debug")}catch{}}function Ca(){let r;try{r=yt?.getItem("debug")}catch{}return!r&&typeof globalThis.process<"u"&&"env"in globalThis.process&&(r=globalThis.process.env.DEBUG),r}function Sa(){try{return localStorage}catch{}}function Ia(r){r.j=function(e){try{return JSON.stringify(e)}catch(t){return"[UnexpectedJSONParseError]: "+t.message}}}var _o=Qr({formatArgs:_a,save:Aa,load:Ca,useColors:va,setupFormatters:Ia,colors:Ea,storage:yt,log:ka});var D=_o;D.formatters.b=r=>r==null?"undefined":W.baseEncode(r);D.formatters.t=r=>r==null?"undefined":me.baseEncode(r);D.formatters.m=r=>r==null?"undefined":ge.baseEncode(r);D.formatters.p=r=>r==null?"undefined":r.toString();D.formatters.c=r=>r==null?"undefined":r.toString();D.formatters.k=r=>r==null?"undefined":r.toString();D.formatters.a=r=>r==null?"undefined":r.toString();D.formatters.e=r=>{if(r==null)return"undefined";let e=ko(r.message),t=ko(r.stack);return e!=null&&t!=null?t.includes(e)?t:`${e}
3
+ ${t}`:t??e??r.toString()};function Ta(r){let e=()=>{};return e.enabled=!1,e.color="",e.diff=0,e.log=()=>{},e.namespace=r,e.destroy=()=>!0,e.extend=()=>e,e}function Ao(){return{forComponent(r){return Co(r)}}}function Co(r){let e=Ta(`${r}:trace`);return D.enabled(`${r}:trace`)&&D.names.map(t=>t.toString()).find(t=>t.includes(":trace"))!=null&&(e=D(`${r}:trace`)),Object.assign(D(r),{error:D(`${r}:error`),trace:e,newScope:t=>Co(`${r}:${t}`)})}function ko(r){if(r!=null&&(r=r.trim(),r.length!==0))return r}var v=class extends Event{type;detail;constructor(e,t){super(e),this.type=e,this.detail=t}};var Yr=go(Io(),1);var We=class extends Error{constructor(e){super(e),this.name="TimeoutError"}},Xr=class extends Error{constructor(e){super(),this.name="AbortError",this.message=e}},To=r=>globalThis.DOMException===void 0?new Xr(r):new DOMException(r),Lo=r=>{let e=r.reason===void 0?To("This operation was aborted."):r.reason;return e instanceof Error?e:To(e)};function Ge(r,e){let{milliseconds:t,fallback:n,message:o,customTimers:i={setTimeout,clearTimeout}}=e,s,a,d=new Promise((l,f)=>{if(typeof t!="number"||Math.sign(t)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${t}\``);if(e.signal){let{signal:y}=e;y.aborted&&f(Lo(y)),a=()=>{f(Lo(y))},y.addEventListener("abort",a,{once:!0})}if(t===Number.POSITIVE_INFINITY){r.then(l,f);return}let g=new We;s=i.setTimeout.call(void 0,()=>{if(n){try{l(n())}catch(y){f(y)}return}typeof r.cancel=="function"&&r.cancel(),o===!1?l():o instanceof Error?f(o):(g.message=o??`Promise timed out after ${t} milliseconds`,f(g))},t),(async()=>{try{l(await r)}catch(y){f(y)}})()}).finally(()=>{d.clear(),a&&e.signal&&e.signal.removeEventListener("abort",a)});return d.clear=()=>{i.clearTimeout.call(void 0,s),s=void 0},d}function Zr(r,e,t){let n=0,o=r.length;for(;o>0;){let i=Math.trunc(o/2),s=n+i;t(r[s],e)<=0?(n=++s,o-=i+1):o=i}return n}var Qe=class{#e=[];enqueue(e,t){t={priority:0,...t};let n={priority:t.priority,id:t.id,run:e};if(this.size===0||this.#e[this.size-1].priority>=t.priority){this.#e.push(n);return}let o=Zr(this.#e,n,(i,s)=>s.priority-i.priority);this.#e.splice(o,0,n)}setPriority(e,t){let n=this.#e.findIndex(i=>i.id===e);if(n===-1)throw new ReferenceError(`No promise function with the id "${e}" exists in the queue.`);let[o]=this.#e.splice(n,1);this.enqueue(o.run,{priority:t,id:e})}dequeue(){return this.#e.shift()?.run}filter(e){return this.#e.filter(t=>t.priority===e.priority).map(t=>t.run)}get size(){return this.#e.length}};var Je=class extends Yr.default{#e;#o;#s=0;#d;#a;#p=0;#r;#c;#t;#m;#n=0;#u;#i;#g;#b=1n;timeout;constructor(e){if(super(),e={carryoverConcurrencyCount:!1,intervalCap:Number.POSITIVE_INFINITY,interval:0,concurrency:Number.POSITIVE_INFINITY,autoStart:!0,queueClass:Qe,...e},!(typeof e.intervalCap=="number"&&e.intervalCap>=1))throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${e.intervalCap?.toString()??""}\` (${typeof e.intervalCap})`);if(e.interval===void 0||!(Number.isFinite(e.interval)&&e.interval>=0))throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${e.interval?.toString()??""}\` (${typeof e.interval})`);this.#e=e.carryoverConcurrencyCount,this.#o=e.intervalCap===Number.POSITIVE_INFINITY||e.interval===0,this.#d=e.intervalCap,this.#a=e.interval,this.#t=new e.queueClass,this.#m=e.queueClass,this.concurrency=e.concurrency,this.timeout=e.timeout,this.#g=e.throwOnTimeout===!0,this.#i=e.autoStart===!1}get#x(){return this.#o||this.#s<this.#d}get#E(){return this.#n<this.#u}#v(){this.#n--,this.#l(),this.emit("next")}#_(){this.#w(),this.#y(),this.#c=void 0}get#k(){let e=Date.now();if(this.#r===void 0){let t=this.#p-e;if(t<0)this.#s=this.#e?this.#n:0;else return this.#c===void 0&&(this.#c=setTimeout(()=>{this.#_()},t)),!0}return!1}#l(){if(this.#t.size===0)return this.#r&&clearInterval(this.#r),this.#r=void 0,this.emit("empty"),this.#n===0&&this.emit("idle"),!1;if(!this.#i){let e=!this.#k;if(this.#x&&this.#E){let t=this.#t.dequeue();return t?(this.emit("active"),t(),e&&this.#y(),!0):!1}}return!1}#y(){this.#o||this.#r!==void 0||(this.#r=setInterval(()=>{this.#w()},this.#a),this.#p=Date.now()+this.#a)}#w(){this.#s===0&&this.#n===0&&this.#r&&(clearInterval(this.#r),this.#r=void 0),this.#s=this.#e?this.#n:0,this.#f()}#f(){for(;this.#l(););}get concurrency(){return this.#u}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.#u=e,this.#f()}async#A(e){return new Promise((t,n)=>{e.addEventListener("abort",()=>{n(e.reason)},{once:!0})})}setPriority(e,t){this.#t.setPriority(e,t)}async add(e,t={}){return t.id??=(this.#b++).toString(),t={timeout:this.timeout,throwOnTimeout:this.#g,...t},new Promise((n,o)=>{this.#t.enqueue(async()=>{this.#n++;try{t.signal?.throwIfAborted(),this.#s++;let i=e({signal:t.signal});t.timeout&&(i=Ge(Promise.resolve(i),{milliseconds:t.timeout})),t.signal&&(i=Promise.race([i,this.#A(t.signal)]));let s=await i;n(s),this.emit("completed",s)}catch(i){if(i instanceof We&&!t.throwOnTimeout){n();return}o(i),this.emit("error",i)}finally{this.#v()}},t),this.emit("add"),this.#l()})}async addAll(e,t){return Promise.all(e.map(async n=>this.add(n,t)))}start(){return this.#i?(this.#i=!1,this.#f(),this):this}pause(){this.#i=!0}clear(){this.#t=new this.#m}async onEmpty(){this.#t.size!==0&&await this.#h("empty")}async onSizeLessThan(e){this.#t.size<e||await this.#h("next",()=>this.#t.size<e)}async onIdle(){this.#n===0&&this.#t.size===0||await this.#h("idle")}async#h(e,t){return new Promise(n=>{let o=()=>{t&&!t()||(this.off(e,o),n())};this.on(e,o)})}get size(){return this.#t.size}sizeBy(e){return this.#t.filter(e).length}get pending(){return this.#n}get isPaused(){return this.#i}};function bt(r){let e=[X.A];return r==null?e:Array.isArray(r)?r.length===0?e:r:[r]}var en={};T(en,{base10:()=>Na});var Na=pe({prefix:"9",name:"base10",alphabet:"0123456789"});var tn={};T(tn,{base16:()=>Ra,base16upper:()=>Da});var Ra=A({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),Da=A({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var rn={};T(rn,{base2:()=>Ba});var Ba=A({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var nn={};T(nn,{base256emoji:()=>Ma});var Po=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}"),Ua=Po.reduce((r,e,t)=>(r[t]=e,r),[]),Fa=Po.reduce((r,e,t)=>{let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);return r[n]=t,r},[]);function Oa(r){return r.reduce((e,t)=>(e+=Ua[t],e),"")}function za(r){let e=[];for(let t of r){let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);let o=Fa[n];if(o==null)throw new Error(`Non-base256emoji character: ${t}`);e.push(o)}return new Uint8Array(e)}var Ma=Le({prefix:"\u{1F680}",name:"base256emoji",encode:Oa,decode:za});var on={};T(on,{base36:()=>se,base36upper:()=>$a});var se=pe({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),$a=pe({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var sn={};T(sn,{base8:()=>qa});var qa=A({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var an={};T(an,{identity:()=>ja});var ja=Le({prefix:"\0",name:"identity",encode:r=>xo(r),decode:r=>bo(r)});var xt={};T(xt,{code:()=>cn,decode:()=>Ga,encode:()=>Wa,name:()=>Ha});var Va=new TextEncoder,Ka=new TextDecoder,Ha="json",cn=512;function Wa(r){return Va.encode(JSON.stringify(r))}function Ga(r){return JSON.parse(Ka.decode(r))}var Et={};T(Et,{code:()=>un,decode:()=>Ya,encode:()=>Ja,name:()=>Qa});var Qa="raw",un=85;function Ja(r){return Y(r)}function Ya(r){return Y(r)}var fn={};T(fn,{identity:()=>_t});var Xa=Do,No=128,Za=127,ec=~Za,tc=Math.pow(2,31);function Do(r,e,t){e=e||[],t=t||0;for(var n=t;r>=tc;)e[t++]=r&255|No,r/=128;for(;r&ec;)e[t++]=r&255|No,r>>>=7;return e[t]=r|0,Do.bytes=t-n+1,e}var rc=ln,nc=128,Ro=127;function ln(r,n){var t=0,n=n||0,o=0,i=n,s,a=r.length;do{if(i>=a)throw ln.bytes=0,new RangeError("Could not decode varint");s=r[i++],t+=o<28?(s&Ro)<<o:(s&Ro)*Math.pow(2,o),o+=7}while(s>=nc);return ln.bytes=i-n,t}var oc=Math.pow(2,7),ic=Math.pow(2,14),sc=Math.pow(2,21),ac=Math.pow(2,28),cc=Math.pow(2,35),uc=Math.pow(2,42),lc=Math.pow(2,49),fc=Math.pow(2,56),hc=Math.pow(2,63),dc=function(r){return r<oc?1:r<ic?2:r<sc?3:r<ac?4:r<cc?5:r<uc?6:r<lc?7:r<fc?8:r<hc?9:10},pc={encode:Xa,decode:rc,encodingLength:dc},mc=pc,Ye=mc;function Xe(r,e=0){return[Ye.decode(r,e),Ye.decode.bytes]}function Pe(r,e,t=0){return Ye.encode(r,e,t),e}function Ne(r){return Ye.encodingLength(r)}function De(r,e){let t=e.byteLength,n=Ne(r),o=n+Ne(t),i=new Uint8Array(o+t);return Pe(r,i,0),Pe(t,i,n),i.set(e,o),new Re(r,t,e,i)}function Bo(r){let e=Y(r),[t,n]=Xe(e),[o,i]=Xe(e.subarray(n)),s=e.subarray(n+i);if(s.byteLength!==o)throw new Error("Incorrect length");return new Re(t,o,s,e)}function Uo(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&wo(r.bytes,t.bytes)}}var Re=class{code;size;digest;bytes;constructor(e,t,n,o){this.code=e,this.size=t,this.digest=n,this.bytes=o}};var Fo=0,gc="identity",Oo=Y;function yc(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 De(Fo,Oo(r))}var _t={code:Fo,name:gc,encode:Oo,digest:yc};var pn={};T(pn,{sha256:()=>kt,sha512:()=>At});var wc=20;function dn({name:r,code:e,encode:t,minDigestLength:n,maxDigestLength:o}){return new hn(r,e,t,n,o)}var hn=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,n,o,i){this.name=e,this.code=t,this.encode=n,this.minDigestLength=o??wc,this.maxDigestLength=i}digest(e,t){if(t?.truncate!=null){if(t.truncate<this.minDigestLength)throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`);if(this.maxDigestLength!=null&&t.truncate>this.maxDigestLength)throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`)}if(e instanceof Uint8Array){let n=this.encode(e);return n instanceof Uint8Array?zo(n,this.code,t?.truncate):n.then(o=>zo(o,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}};function zo(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 De(e,r)}function $o(r){return async e=>new Uint8Array(await crypto.subtle.digest(r,e))}var kt=dn({name:"sha2-256",code:18,encode:$o("SHA-256")}),At=dn({name:"sha2-512",code:19,encode:$o("SHA-512")});function qo(r,e){let{bytes:t,version:n}=r;switch(n){case 0:return xc(t,mn(r),e??W.encoder);default:return Ec(t,mn(r),e??me.encoder)}}var jo=new WeakMap;function mn(r){let e=jo.get(r);if(e==null){let t=new Map;return jo.set(r,t),t}return e}var k=class r{code;version;multihash;bytes;"/";constructor(e,t,n,o){this.code=t,this.version=e,this.multihash=n,this.bytes=o,this["/"]=o}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:e,multihash:t}=this;if(e!==et)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==vc)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=De(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&&Uo(e.multihash,n.multihash)}toString(e){return qo(this,e)}toJSON(){return{"/":qo(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(e){if(e==null)return null;let t=e;if(t instanceof r)return t;if(t["/"]!=null&&t["/"]===t.bytes||t.asCID===t){let{version:n,code:o,multihash:i,bytes:s}=t;return new r(n,o,i,s??Vo(n,o,i.bytes))}else if(t[_c]===!0){let{version:n,multihash:o,code:i}=t,s=Bo(o);return r.create(n,i,s)}else return null}static create(e,t,n){if(typeof t!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(e){case 0:{if(t!==et)throw new Error(`Version 0 CID must use dag-pb (code: ${et}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let o=Vo(e,t,n.bytes);return new r(e,t,n,o)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,et,e)}static createV1(e,t){return r.create(1,e,t)}static decode(e){let[t,n]=r.decodeFirst(e);if(n.length!==0)throw new Error("Incorrect length");return t}static decodeFirst(e){let t=r.inspectBytes(e),n=t.size-t.multihashSize,o=Y(e.subarray(n,n+t.multihashSize));if(o.byteLength!==t.multihashSize)throw new Error("Incorrect length");let i=o.subarray(t.multihashSize-t.digestSize),s=new Re(t.multihashCode,t.digestSize,i,o);return[t.version===0?r.createV0(s):r.createV1(t.codec,s),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[f,g]=Xe(e.subarray(t));return t+=g,f},o=n(),i=et;if(o===18?(o=0,t=0):i=n(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);let s=t,a=n(),u=n(),d=t+u,l=d-s;return{version:o,codec:i,multihashCode:a,digestSize:u,multihashSize:l,size:d}}static parse(e,t){let[n,o]=bc(e,t),i=r.decode(o);if(i.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return mn(i).set(n,e),i}};function bc(r,e){switch(r[0]){case"Q":{let t=e??W;return[W.prefix,t.decode(`${W.prefix}${r}`)]}case W.prefix:{let t=e??W;return[W.prefix,t.decode(r)]}case me.prefix:{let t=e??me;return[me.prefix,t.decode(r)]}case se.prefix:{let t=e??se;return[se.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 xc(r,e,t){let{prefix:n}=t;if(n!==W.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let o=e.get(n);if(o==null){let i=t.encode(r).slice(1);return e.set(n,i),i}else return o}function Ec(r,e,t){let{prefix:n}=t,o=e.get(n);if(o==null){let i=t.encode(r);return e.set(n,i),i}else return o}var et=112,vc=18;function Vo(r,e,t){let n=Ne(r),o=n+Ne(e),i=new Uint8Array(o+t.byteLength);return Pe(r,i,0),Pe(e,i,n),i.set(t,o),i}var _c=Symbol.for("@ipld/js-cid/CID");var gn={...an,...rn,...sn,...en,...tn,...Hr,...on,...Wr,...Gr,...nn},Mf={...pn,...fn};function Ko(r=0){return new Uint8Array(r)}function Ct(r=0){return new Uint8Array(r)}function Wo(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var Ho=Wo("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),yn=Wo("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=Ct(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),kc={utf8:Ho,"utf-8":Ho,hex:gn.base16,latin1:yn,ascii:yn,binary:yn,...gn},St=kc;function Be(r,e="utf8"){let t=St[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.encoder.encode(r).substring(1)}var wn=60;function It(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:X[e.type]})),Answer:(r.Answer??r.answers??[]).map(e=>({name:e.name,type:X[e.type],TTL:e.TTL??e.ttl??wn,data:e.data instanceof Uint8Array?Be(e.data):e.data}))}}var Ac=4;function bn(r,e={}){let t=new Je({concurrency:e.queryConcurrency??Ac});return async(n,o={})=>{let i=new URLSearchParams;i.set("name",n),bt(o.types).forEach(a=>{i.append("type",X[a])}),o.onProgress?.(new v("dns:query",n));let s=await t.add(async()=>{let a=await fetch(`${r}?${i}`,{headers:{accept:"application/dns-json"},signal:o?.signal});if(a.status!==200)throw new Error(`Unexpected HTTP status: ${a.status} - ${a.statusText}`);let u=It(await a.json());return o.onProgress?.(new v("dns:response",u)),u},{signal:o.signal});if(s==null)throw new Error("No DNS response received");return s}}function Go(){return[bn("https://cloudflare-dns.com/dns-query"),bn("https://dns.google/resolve")]}var Yo=go(Jo(),1);var xn=class{lru;constructor(e){this.lru=(0,Yo.default)(e)}get(e,t){let n=!0,o=[];for(let i of t){let s=this.getAnswers(e,i);if(s.length===0){n=!1;break}o.push(...s)}if(n)return It({answers:o})}getAnswers(e,t){let n=`${e.toLowerCase()}-${t}`,o=this.lru.get(n);if(o!=null){let i=o.filter(s=>s.expires>Date.now()).map(({expires:s,value:a})=>({...a,TTL:Math.round((s-Date.now())/1e3),type:X[a.type]}));return i.length===0&&this.lru.remove(n),i}return[]}add(e,t){let n=`${e.toLowerCase()}-${t.type}`,o=this.lru.get(n)??[];o.push({expires:Date.now()+(t.TTL??wn)*1e3,value:t}),this.lru.set(n,o)}remove(e,t){let n=`${e.toLowerCase()}-${t}`;this.lru.remove(n)}clear(){this.lru.clear()}};function Xo(r){return new xn(r)}var Cc=1e3,Tt=class{resolvers;cache;constructor(e){this.resolvers={},this.cache=Xo(e.cacheSize??Cc),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["."]=Go())}async query(e,t={}){let n=bt(t.types),o=t.cached!==!1?this.cache.get(e,n):void 0;if(o!=null)return t.onProgress?.(new v("dns:cache",o)),o;let i=`${e.split(".").pop()}.`,s=(this.resolvers[i]??this.resolvers["."]).sort(()=>Math.random()>.5?-1:1),a=[];for(let u of s){if(t.signal?.aborted===!0)break;try{let d=await u(e,{...t,types:n});for(let l of d.Answer)this.cache.add(e,l);return d}catch(d){a.push(d),t.onProgress?.(new v("dns:error",d))}}throw a.length===1?a[0]:new AggregateError(a,`DNS lookup of ${e} ${n} failed`)}};var X;(function(r){r[r.A=1]="A",r[r.CNAME=5]="CNAME",r[r.TXT=16]="TXT",r[r.AAAA=28]="AAAA"})(X||(X={}));function Zo(r={}){return new Tt(r)}function Sc(r){return r[Symbol.asyncIterator]!=null}function Ic(r){if(Sc(r))return(async()=>{for await(let e of r);})();for(let e of r);}var ei=Ic;function xe(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 En(r,e){e==null&&(e=r.reduce((o,i)=>o+i.length,0));let t=Ct(e),n=0;for(let o of r)t.set(o,n),n+=o.length;return t}function B(r,e="utf8"){let t=St[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.decoder.decode(`${t.prefix}${r}`)}var vn={32:16777619n,64:1099511628211n,128:309485009821345068724781371n,256:374144419156711147060143317175368453031918731002211n,512:35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759n,1024:5016456510113118655434598811035278955030765345404790744303017523831112055108147451509157692220295382716162651878526895249385292291816524375083746691371804094271873160484737966720260389217684476157468082573n},ti={32:2166136261n,64:14695981039346656037n,128:144066263297769815596495629667062367629n,256:100029257958052580907070968620625704837092796014241193945225284501741471925557n,512:9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785n,1024:14197795064947621068722070641403218320880622795441933960878474914617582723252296732303717722150864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915n},ri=new globalThis.TextEncoder;function Tc(r,e){let t=vn[e],n=ti[e];for(let o=0;o<r.length;o++)n^=BigInt(r[o]),n=BigInt.asUintN(e,n*t);return n}function Lc(r,e,t){if(t.length===0)throw new Error("The `utf8Buffer` option must have a length greater than zero");let n=vn[e],o=ti[e],i=r;for(;i.length>0;){let s=ri.encodeInto(i,t);i=i.slice(s.read);for(let a=0;a<s.written;a++)o^=BigInt(t[a]),o=BigInt.asUintN(e,o*n)}return o}function _n(r,{size:e=32,utf8Buffer:t}={}){if(!vn[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 Lc(r,e,t);r=ri.encode(r)}return Tc(r,e)}var tt={hash:r=>Number(_n(r,{size:32})),hashV:(r,e)=>Pc(tt.hash(r,e))};function Pc(r){let e=r.toString(16);return e.length%2===1&&(e=`0${e}`),B(e,"base16")}var kn=64,Z=class{fp;h;seed;constructor(e,t,n,o=2){if(o>kn)throw new TypeError("Invalid Fingerprint Size");let i=t.hashV(e,n),s=Ko(o);for(let a=0;a<s.length;a++)s[a]=i[a];s.length===0&&(s[0]=7),this.fp=s,this.h=t,this.seed=n}hash(){return this.h.hash(this.fp,this.seed)}equals(e){return e?.fp instanceof Uint8Array?xe(this.fp,e.fp):!1}};function Ee(r,e){return Math.floor(Math.random()*(e-r))+r}var ve=class{contents;constructor(e){this.contents=new Array(e).fill(null)}has(e){if(!(e instanceof Z))throw new TypeError("Invalid Fingerprint");return this.contents.some(t=>e.equals(t))}add(e){if(!(e instanceof Z))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 Z))throw new TypeError("Invalid Fingerprint");let t=Ee(0,this.contents.length-1),n=this.contents[t];return this.contents[t]=e,n}remove(e){if(!(e instanceof Z))throw new TypeError("Invalid Fingerprint");let t=this.contents.findIndex(n=>e.equals(n));return t>-1?(this.contents[t]=null,!0):!1}};var Nc=500,rt=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??tt,this.seed=e.seed??Ee(0,Math.pow(2,10))}add(e){typeof e=="string"&&(e=B(e));let t=new Z(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,o=(n^t.hash())%this.filterSize;if(this.buckets[n]==null&&(this.buckets[n]=new ve(this.bucketSize)),this.buckets[o]==null&&(this.buckets[o]=new ve(this.bucketSize)),this.buckets[n].add(t)||this.buckets[o].add(t))return this.count++,!0;let i=[n,o],s=i[Ee(0,i.length-1)];this.buckets[s]==null&&(this.buckets[s]=new ve(this.bucketSize));for(let a=0;a<Nc;a++){let u=this.buckets[s].swap(t);if(u!=null&&(s=(s^u.hash())%this.filterSize,this.buckets[s]==null&&(this.buckets[s]=new ve(this.bucketSize)),this.buckets[s].add(u)))return this.count++,!0}return!1}has(e){typeof e=="string"&&(e=B(e));let t=new Z(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,o=this.buckets[n]?.has(t)??!1;if(o)return o;let i=(n^t.hash())%this.filterSize;return this.buckets[i]?.has(t)??!1}remove(e){typeof e=="string"&&(e=B(e));let t=new Z(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,o=this.buckets[n]?.remove(t)??!1;if(o)return this.count--,o;let i=(n^t.hash())%this.filterSize,s=this.buckets[i]?.remove(t)??!1;return s&&this.count--,s}get reliable(){return Math.floor(100*(this.count/this.filterSize))<=90}},Rc={1:.5,2:.84,4:.95,8:.98};function Dc(r=.001){return r>.002?2:r>1e-5?4:8}function ni(r,e=.001){let t=Dc(e),n=Rc[t],o=Math.round(r/n),i=Math.min(Math.ceil(Math.log2(1/e)+Math.log2(2*t)),kn);return{filterSize:o,bucketSize:t,fingerprintSize:i}}var Lt=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??tt,this.seed=e.seed??Ee(0,Math.pow(2,10)),this.filterSeries=[new rt({filterSize:this.filterSize,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed})]}add(e){if(typeof e=="string"&&(e=B(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 rt({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=B(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=B(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 An(r,e=.001,t){return new Lt({...ni(r,e),...t??{}})}function U(){let r={};return r.promise=new Promise((e,t)=>{r.resolve=e,r.reject=t}),r}var Pt=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}},Ue=class{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new Pt(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 Pt(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 Cn=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}};function Nt(r={}){return Bc(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 Bc(r,e){e=e??{};let t=e.onEnd,n=new Ue,o,i,s,a=U(),u=async()=>{try{return n.isEmpty()?s?{done:!0}:await new Promise((w,_)=>{i=C=>{i=null,n.push(C);try{w(r(n))}catch(S){_(S)}return o}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=U()})}},d=w=>i!=null?i(w):(n.push(w),o),l=w=>(n=new Ue,i!=null?i({error:w}):(n.push({error:w}),o)),f=w=>{if(s)return o;if(e?.objectMode!==!0&&w?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return d({done:!1,value:w})},g=w=>s?o:(s=!0,w!=null?l(w):d({done:!0})),y=()=>(n=new Ue,g(),{done:!0}),b=w=>(g(w),{done:!0});if(o={[Symbol.asyncIterator](){return this},next:u,return:y,throw:b,push:f,end:g,get readableLength(){return n.size},onEmpty:async w=>{let _=w?.signal;if(_?.throwIfAborted(),n.isEmpty())return;let C,S;_!=null&&(C=new Promise((I,F)=>{S=()=>{F(new Cn)},_.addEventListener("abort",S)}));try{await Promise.race([a.promise,C])}finally{S!=null&&_!=null&&_?.removeEventListener("abort",S)}}},t==null)return o;let x=o;return o={[Symbol.asyncIterator](){return this},next(){return x.next()},throw(w){return x.throw(w),t!=null&&(t(w),t=void 0),{done:!0}},return(){return x.return(),t!=null&&(t(),t=void 0),{done:!0}},push:f,end(w){return x.end(w),t!=null&&(t(w),t=void 0),o},get readableLength(){return x.readableLength},onEmpty:w=>x.onEmpty(w)},o}var Uc=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 Fc(r,e,t){let n,o=new Promise((i,s)=>{if(t={rejectionEvents:["error"],multiArgs:!1,rejectionMultiArgs:!1,resolveImmediately:!1,...t},!(t.count>=0&&(t.count===Number.POSITIVE_INFINITY||Number.isInteger(t.count))))throw new TypeError("The `count` option should be at least 0 or more");t.signal?.throwIfAborted();let a=[e].flat(),u=[],{addListener:d,removeListener:l}=Uc(r),f=async(...y)=>{let b=t.multiArgs?y:y[0];if(t.filter)try{if(!await t.filter(b))return}catch(x){n(),s(x);return}u.push(b),t.count===u.length&&(n(),i(u))},g=(...y)=>{n(),s(t.rejectionMultiArgs?y:y[0])};n=()=>{for(let y of a)l(y,f);for(let y of t.rejectionEvents)a.includes(y)||l(y,g)};for(let y of a)d(y,f);for(let y of t.rejectionEvents)a.includes(y)||d(y,g);t.signal&&t.signal.addEventListener("abort",()=>{g(t.signal.reason)},{once:!0}),t.resolveImmediately&&i(u)});if(o.cancel=n,typeof t.timeout=="number"){let i=Ge(o,{milliseconds:t.timeout});return i.cancel=()=>{n(),i.clear()},i}return o}function Rt(r,e,t){typeof t=="function"&&(t={filter:t}),t={...t,count:1,resolveImmediately:!1};let n=Fc(r,e,t),o=n.then(i=>i[0]);return o.cancel=n.cancel,o}function Sn(r,e){let t,n=function(){let o=function(){t=void 0,r()};clearTimeout(t),t=setTimeout(o,e)};return n.start=()=>{},n.stop=()=>{clearTimeout(t)},n}var Dt=class extends Error{static name="QueueFullError";constructor(e="The queue was full"){super(e),this.name="QueueFullError"}};function Oc(r){return r.reason}async function oi(r,e,t){if(e==null)return r;let n=t?.translateError??Oc;if(e.aborted)return r.catch(()=>{}),Promise.reject(n(e));let o;try{return await Promise.race([r,new Promise((i,s)=>{o=()=>{s(n(e))},e.addEventListener("abort",o)})])}finally{o!=null&&e.removeEventListener("abort",o)}}var Bt=class{deferred;signal;constructor(e){this.signal=e,this.deferred=U(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new J)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function zc(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var Ut=class{id;fn;options;recipients;status;timeline;controller;constructor(e,t){this.id=zc(),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 J),this.cleanup())}async join(e={}){let t=new Bt(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 oi(this.fn({...this.options??{},signal:this.controller.signal}),this.controller.signal);this.recipients.forEach(t=>{t.deferred.resolve(e)}),this.status="complete"}catch(e){this.recipients.forEach(t=>{t.deferred.reject(e)}),this.status="errored"}finally{this.timeline.finished=Date.now(),this.cleanup()}}cleanup(){this.recipients.forEach(e=>{e.cleanup(),e.signal?.removeEventListener("abort",this.onAbort)})}};var ae=class extends H{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=Sn(this.emitEmpty.bind(this),1),this.emitIdle=Sn(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 Dt;let n=new Ut(e,t);return this.enqueue(n),this.safeDispatchEvent("add"),this.tryToStartAnother(),n.join(t).then(o=>(this.safeDispatchEvent("completed",{detail:o}),this.safeDispatchEvent("success",{detail:{job:n,result:o}}),o)).catch(o=>{if(n.status==="queued"){for(let i=0;i<this.queue.length;i++)if(this.queue[i]===n){this.queue.splice(i,1);break}}throw this.safeDispatchEvent("failure",{detail:{job:n,error:o}}),o})}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(e=>{e.abort(new J)}),this.clear()}async onEmpty(e){this.size!==0&&await Rt(this,"empty",e)}async onSizeLessThan(e,t){this.size<e||await Rt(this,"next",{...t,filter:()=>this.size<e})}async onIdle(e){this.pending===0&&this.size===0||await Rt(this,"idle",e)}get size(){return this.queue.length}get queued(){return this.queue.length-this.pending}get running(){return this.pending}async*toGenerator(e){e?.signal?.throwIfAborted();let t=Nt({objectMode:!0}),n=u=>{u!=null?this.abort():this.clear(),t.end(u)},o=u=>{u.detail!=null&&t.push(u.detail)},i=u=>{n(u.detail.error)},s=()=>{n()},a=()=>{n(new J("Queue aborted"))};this.addEventListener("completed",o),this.addEventListener("failure",i),this.addEventListener("idle",s),e?.signal?.addEventListener("abort",a);try{yield*t}finally{this.removeEventListener("completed",o),this.removeEventListener("failure",i),this.removeEventListener("idle",s),e?.signal?.removeEventListener("abort",a),n()}}};function oe(r){let e=new globalThis.AbortController;function t(){e.abort();for(let i of r)i?.removeEventListener!=null&&i.removeEventListener("abort",t)}for(let i of r){if(i?.aborted===!0){t();break}i?.addEventListener!=null&&i.addEventListener("abort",t)}function n(){for(let i of r)i?.removeEventListener!=null&&i.removeEventListener("abort",t)}let o=e.signal;return o.clear=n,o}var Ft=class extends Error{type;code;constructor(e,t,n){super(e??"The operation was aborted"),this.type="aborted",this.name=n??"AbortError",this.code=t??"ABORT_ERR"}};async function ii(r,e,t){if(e==null)return r;if(e.aborted)return r.catch(()=>{}),Promise.reject(new Ft(t?.errorMessage,t?.errorCode,t?.errorName));let n,o=new Ft(t?.errorMessage,t?.errorCode,t?.errorName);try{return await Promise.race([r,new Promise((i,s)=>{n=()=>{s(o)},e.addEventListener("abort",n)})])}finally{n!=null&&e.removeEventListener("abort",n)}}var In=class{readNext;haveNext;ended;nextResult;error;constructor(){this.ended=!1,this.readNext=U(),this.haveNext=U()}[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=U(),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=U(),await ii(this.readNext.promise,t?.signal,t)}};function si(){return new In}function Mc(r){return r[Symbol.asyncIterator]!=null}async function $c(r,e,t){try{await Promise.all(r.map(async n=>{for await(let o of n)await e.push(o,{signal:t}),t.throwIfAborted()})),await e.end(void 0,{signal:t})}catch(n){await e.end(n,{signal:t}).catch(()=>{})}}async function*qc(r){let e=new AbortController,t=si();$c(r,t,e.signal).catch(()=>{});try{yield*t}finally{e.abort()}}function*jc(r){for(let e of r)yield*e}function Vc(...r){let e=[];for(let t of r)Mc(t)||e.push(t);return e.length===r.length?jc(e):qc(r)}var Ot=Vc;var Kc=["string","number","bigint","symbol"],Hc=["Function","Generator","AsyncGenerator","GeneratorFunction","AsyncGeneratorFunction","AsyncFunction","Observable","Array","Buffer","Object","RegExp","Date","Error","Map","Set","WeakMap","WeakSet","ArrayBuffer","SharedArrayBuffer","DataView","Promise","URL","HTMLElement","Int8Array","Uint8Array","Uint8ClampedArray","Int16Array","Uint16Array","Int32Array","Uint32Array","Float32Array","Float64Array","BigInt64Array","BigUint64Array"];function ai(r){if(r===null)return"null";if(r===void 0)return"undefined";if(r===!0||r===!1)return"boolean";let e=typeof r;if(Kc.includes(e))return e;if(e==="function")return"Function";if(Array.isArray(r))return"Array";if(Wc(r))return"Buffer";let t=Gc(r);return t||"Object"}function Wc(r){return r&&r.constructor&&r.constructor.isBuffer&&r.constructor.isBuffer.call(null,r)}function Gc(r){let e=Object.prototype.toString.call(r).slice(8,-1);if(Hc.includes(e))return e}var c=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}};c.uint=new c(0,"uint",!0);c.negint=new c(1,"negint",!0);c.bytes=new c(2,"bytes",!0);c.string=new c(3,"string",!0);c.array=new c(4,"array",!1);c.map=new c(5,"map",!1);c.tag=new c(6,"tag",!1);c.float=new c(7,"float",!0);c.false=new c(7,"false",!0);c.true=new c(7,"true",!0);c.null=new c(7,"null",!0);c.undefined=new c(7,"undefined",!0);c.break=new c(7,"break",!0);var h=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 Fe=globalThis.process&&!globalThis.process.browser&&globalThis.Buffer&&typeof globalThis.Buffer.isBuffer=="function",Qc=new TextDecoder,Jc=new TextEncoder;function zt(r){return Fe&&globalThis.Buffer.isBuffer(r)}function nt(r){return r instanceof Uint8Array?zt(r)?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):r:Uint8Array.from(r)}var fi=Fe?(r,e,t)=>t-e>64?globalThis.Buffer.from(r.subarray(e,t)).toString("utf8"):ui(r,e,t):(r,e,t)=>t-e>64?Qc.decode(r.subarray(e,t)):ui(r,e,t),Mt=Fe?r=>r.length>64?globalThis.Buffer.from(r):ci(r):r=>r.length>64?Jc.encode(r):ci(r),ie=r=>Uint8Array.from(r),Oe=Fe?(r,e,t)=>zt(r)?new Uint8Array(r.subarray(e,t)):r.slice(e,t):(r,e,t)=>r.slice(e,t),hi=Fe?(r,e)=>(r=r.map(t=>t instanceof Uint8Array?t:globalThis.Buffer.from(t)),nt(globalThis.Buffer.concat(r,e))):(r,e)=>{let t=new Uint8Array(e),n=0;for(let o of r)n+o.length>t.length&&(o=o.subarray(0,t.length-n)),t.set(o,n),n+=o.length;return t},di=Fe?r=>globalThis.Buffer.allocUnsafe(r):r=>new Uint8Array(r);function pi(r,e){if(zt(r)&&zt(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 ci(r){let e=[],t=0;for(let n=0;n<r.length;n++){let o=r.charCodeAt(n);o<128?e[t++]=o:o<2048?(e[t++]=o>>6|192,e[t++]=o&63|128):(o&64512)===55296&&n+1<r.length&&(r.charCodeAt(n+1)&64512)===56320?(o=65536+((o&1023)<<10)+(r.charCodeAt(++n)&1023),e[t++]=o>>18|240,e[t++]=o>>12&63|128,e[t++]=o>>6&63|128,e[t++]=o&63|128):(e[t++]=o>>12|224,e[t++]=o>>6&63|128,e[t++]=o&63|128)}return e}function ui(r,e,t){let n=[];for(;e<t;){let o=r[e],i=null,s=o>239?4:o>223?3:o>191?2:1;if(e+s<=t){let a,u,d,l;switch(s){case 1:o<128&&(i=o);break;case 2:a=r[e+1],(a&192)===128&&(l=(o&31)<<6|a&63,l>127&&(i=l));break;case 3:a=r[e+1],u=r[e+2],(a&192)===128&&(u&192)===128&&(l=(o&15)<<12|(a&63)<<6|u&63,l>2047&&(l<55296||l>57343)&&(i=l));break;case 4:a=r[e+1],u=r[e+2],d=r[e+3],(a&192)===128&&(u&192)===128&&(d&192)===128&&(l=(o&15)<<18|(a&63)<<12|(u&63)<<6|d&63,l>65535&&l<1114112&&(i=l))}}i===null?(i=65533,s=1):i>65535&&(i-=65536,n.push(i>>>10&1023|55296),i=56320|i&1023),n.push(i),e+=s}return Tn(n)}var li=4096;function Tn(r){let e=r.length;if(e<=li)return String.fromCharCode.apply(String,r);let t="",n=0;for(;n<e;)t+=String.fromCharCode.apply(String,r.slice(n,n+=li));return t}var Yc=256,ot=class{constructor(e=Yc){this.chunkSize=e,this.cursor=0,this.maxCursor=-1,this.chunks=[],this._initReuseChunk=null}reset(){this.cursor=0,this.maxCursor=-1,this.chunks.length&&(this.chunks=[]),this._initReuseChunk!==null&&(this.chunks.push(this._initReuseChunk),this.maxCursor=this._initReuseChunk.length-1)}push(e){let t=this.chunks[this.chunks.length-1];if(this.cursor+e.length<=this.maxCursor+1){let o=t.length-(this.maxCursor-this.cursor)-1;t.set(e,o)}else{if(t){let o=t.length-(this.maxCursor-this.cursor)-1;o<t.length&&(this.chunks[this.chunks.length-1]=t.subarray(0,o),this.maxCursor=this.cursor-1)}e.length<64&&e.length<this.chunkSize?(t=di(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=Oe(n,0,this.cursor)}else t=hi(this.chunks,this.cursor);return e&&this.reset(),t}};var m="CBOR decode error:",ce="CBOR encode error:",it=[];it[23]=1;it[24]=2;it[25]=3;it[26]=5;it[27]=9;function ue(r,e,t){if(r.length-e<t)throw new Error(`${m} not enough data for type`)}var L=[24,256,65536,4294967296,BigInt("18446744073709551616")];function z(r,e,t){ue(r,e,1);let n=r[e];if(t.strict===!0&&n<L[0])throw new Error(`${m} integer encoded in more bytes than necessary (strict decode)`);return n}function M(r,e,t){ue(r,e,2);let n=r[e]<<8|r[e+1];if(t.strict===!0&&n<L[1])throw new Error(`${m} integer encoded in more bytes than necessary (strict decode)`);return n}function $(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<L[2])throw new Error(`${m} integer encoded in more bytes than necessary (strict decode)`);return n}function q(r,e,t){ue(r,e,8);let n=r[e]*16777216+(r[e+1]<<16)+(r[e+2]<<8)+r[e+3],o=r[e+4]*16777216+(r[e+5]<<16)+(r[e+6]<<8)+r[e+7],i=(BigInt(n)<<BigInt(32))+BigInt(o);if(t.strict===!0&&i<L[3])throw new Error(`${m} integer encoded in more bytes than necessary (strict decode)`);if(i<=Number.MAX_SAFE_INTEGER)return Number(i);if(t.allowBigInt===!0)return i;throw new Error(`${m} integers outside of the safe integer range are not supported`)}function mi(r,e,t,n){return new h(c.uint,z(r,e+1,n),2)}function gi(r,e,t,n){return new h(c.uint,M(r,e+1,n),3)}function yi(r,e,t,n){return new h(c.uint,$(r,e+1,n),5)}function wi(r,e,t,n){return new h(c.uint,q(r,e+1,n),9)}function G(r,e){return P(r,0,e.value)}function P(r,e,t){if(t<L[0]){let n=Number(t);r.push([e|n])}else if(t<L[1]){let n=Number(t);r.push([e|24,n])}else if(t<L[2]){let n=Number(t);r.push([e|25,n>>>8,n&255])}else if(t<L[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<L[4]){let o=[e|27,0,0,0,0,0,0,0],i=Number(n&BigInt(4294967295)),s=Number(n>>BigInt(32)&BigInt(4294967295));o[8]=i&255,i=i>>8,o[7]=i&255,i=i>>8,o[6]=i&255,i=i>>8,o[5]=i&255,o[4]=s&255,s=s>>8,o[3]=s&255,s=s>>8,o[2]=s&255,s=s>>8,o[1]=s&255,r.push(o)}else throw new Error(`${m} encountered BigInt larger than allowable range`)}}G.encodedSize=function(e){return P.encodedSize(e.value)};P.encodedSize=function(e){return e<L[0]?1:e<L[1]?2:e<L[2]?3:e<L[3]?5:9};G.compareTokens=function(e,t){return e.value<t.value?-1:e.value>t.value?1:0};function bi(r,e,t,n){return new h(c.negint,-1-z(r,e+1,n),2)}function xi(r,e,t,n){return new h(c.negint,-1-M(r,e+1,n),3)}function Ei(r,e,t,n){return new h(c.negint,-1-$(r,e+1,n),5)}var Ln=BigInt(-1),vi=BigInt(1);function _i(r,e,t,n){let o=q(r,e+1,n);if(typeof o!="bigint"){let i=-1-o;if(i>=Number.MIN_SAFE_INTEGER)return new h(c.negint,i,9)}if(n.allowBigInt!==!0)throw new Error(`${m} integers outside of the safe integer range are not supported`);return new h(c.negint,Ln-BigInt(o),9)}function $t(r,e){let t=e.value,n=typeof t=="bigint"?t*Ln-vi:t*-1-1;P(r,e.type.majorEncoded,n)}$t.encodedSize=function(e){let t=e.value,n=typeof t=="bigint"?t*Ln-vi:t*-1-1;return n<L[0]?1:n<L[1]?2:n<L[2]?3:n<L[3]?5:9};$t.compareTokens=function(e,t){return e.value<t.value?1:e.value>t.value?-1:0};function st(r,e,t,n){ue(r,e,t+n);let o=Oe(r,e+t,e+t+n);return new h(c.bytes,o,t+n)}function ki(r,e,t,n){return st(r,e,1,t)}function Ai(r,e,t,n){return st(r,e,2,z(r,e+1,n))}function Ci(r,e,t,n){return st(r,e,3,M(r,e+1,n))}function Si(r,e,t,n){return st(r,e,5,$(r,e+1,n))}function Ii(r,e,t,n){let o=q(r,e+1,n);if(typeof o=="bigint")throw new Error(`${m} 64-bit integer bytes lengths not supported`);return st(r,e,9,o)}function qt(r){return r.encodedBytes===void 0&&(r.encodedBytes=r.type===c.string?Mt(r.value):r.value),r.encodedBytes}function ze(r,e){let t=qt(e);P(r,e.type.majorEncoded,t.length),r.push(t)}ze.encodedSize=function(e){let t=qt(e);return P.encodedSize(t.length)+t.length};ze.compareTokens=function(e,t){return Zc(qt(e),qt(t))};function Zc(r,e){return r.length<e.length?-1:r.length>e.length?1:pi(r,e)}function at(r,e,t,n,o){let i=t+n;ue(r,e,i);let s=new h(c.string,fi(r,e+t,e+i),i);return o.retainStringBytes===!0&&(s.byteValue=Oe(r,e+t,e+i)),s}function Ti(r,e,t,n){return at(r,e,1,t,n)}function Li(r,e,t,n){return at(r,e,2,z(r,e+1,n),n)}function Pi(r,e,t,n){return at(r,e,3,M(r,e+1,n),n)}function Ni(r,e,t,n){return at(r,e,5,$(r,e+1,n),n)}function Ri(r,e,t,n){let o=q(r,e+1,n);if(typeof o=="bigint")throw new Error(`${m} 64-bit integer string lengths not supported`);return at(r,e,9,o,n)}var Di=ze;function Me(r,e,t,n){return new h(c.array,n,t)}function Bi(r,e,t,n){return Me(r,e,1,t)}function Ui(r,e,t,n){return Me(r,e,2,z(r,e+1,n))}function Fi(r,e,t,n){return Me(r,e,3,M(r,e+1,n))}function Oi(r,e,t,n){return Me(r,e,5,$(r,e+1,n))}function zi(r,e,t,n){let o=q(r,e+1,n);if(typeof o=="bigint")throw new Error(`${m} 64-bit integer array lengths not supported`);return Me(r,e,9,o)}function Mi(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${m} indefinite length items not allowed`);return Me(r,e,1,1/0)}function jt(r,e){P(r,c.array.majorEncoded,e.value)}jt.compareTokens=G.compareTokens;jt.encodedSize=function(e){return P.encodedSize(e.value)};function $e(r,e,t,n){return new h(c.map,n,t)}function $i(r,e,t,n){return $e(r,e,1,t)}function qi(r,e,t,n){return $e(r,e,2,z(r,e+1,n))}function ji(r,e,t,n){return $e(r,e,3,M(r,e+1,n))}function Vi(r,e,t,n){return $e(r,e,5,$(r,e+1,n))}function Ki(r,e,t,n){let o=q(r,e+1,n);if(typeof o=="bigint")throw new Error(`${m} 64-bit integer map lengths not supported`);return $e(r,e,9,o)}function Hi(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${m} indefinite length items not allowed`);return $e(r,e,1,1/0)}function Vt(r,e){P(r,c.map.majorEncoded,e.value)}Vt.compareTokens=G.compareTokens;Vt.encodedSize=function(e){return P.encodedSize(e.value)};function Wi(r,e,t,n){return new h(c.tag,t,1)}function Gi(r,e,t,n){return new h(c.tag,z(r,e+1,n),2)}function Qi(r,e,t,n){return new h(c.tag,M(r,e+1,n),3)}function Ji(r,e,t,n){return new h(c.tag,$(r,e+1,n),5)}function Yi(r,e,t,n){return new h(c.tag,q(r,e+1,n),9)}function Kt(r,e){P(r,c.tag.majorEncoded,e.value)}Kt.compareTokens=G.compareTokens;Kt.encodedSize=function(e){return P.encodedSize(e.value)};var iu=20,su=21,au=22,cu=23;function Xi(r,e,t,n){if(n.allowUndefined===!1)throw new Error(`${m} undefined values are not supported`);return n.coerceUndefinedToNull===!0?new h(c.null,null,1):new h(c.undefined,void 0,1)}function Zi(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${m} indefinite length items not allowed`);return new h(c.break,void 0,1)}function Pn(r,e,t){if(t){if(t.allowNaN===!1&&Number.isNaN(r))throw new Error(`${m} NaN values are not supported`);if(t.allowInfinity===!1&&(r===1/0||r===-1/0))throw new Error(`${m} Infinity values are not supported`)}return new h(c.float,r,e)}function es(r,e,t,n){return Pn(Nn(r,e+1),3,n)}function ts(r,e,t,n){return Pn(Rn(r,e+1),5,n)}function rs(r,e,t,n){return Pn(ss(r,e+1),9,n)}function Ht(r,e,t){let n=e.value;if(n===!1)r.push([c.float.majorEncoded|iu]);else if(n===!0)r.push([c.float.majorEncoded|su]);else if(n===null)r.push([c.float.majorEncoded|au]);else if(n===void 0)r.push([c.float.majorEncoded|cu]);else{let o,i=!1;(!t||t.float64!==!0)&&(os(n),o=Nn(ee,1),n===o||Number.isNaN(n)?(ee[0]=249,r.push(ee.slice(0,3)),i=!0):(is(n),o=Rn(ee,1),n===o&&(ee[0]=250,r.push(ee.slice(0,5)),i=!0))),i||(uu(n),o=ss(ee,1),ee[0]=251,r.push(ee.slice(0,9)))}}Ht.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){os(n);let o=Nn(ee,1);if(n===o||Number.isNaN(n))return 3;if(is(n),o=Rn(ee,1),n===o)return 5}return 9};var ns=new ArrayBuffer(9),Q=new DataView(ns,1),ee=new Uint8Array(ns,0);function os(r){if(r===1/0)Q.setUint16(0,31744,!1);else if(r===-1/0)Q.setUint16(0,64512,!1);else if(Number.isNaN(r))Q.setUint16(0,32256,!1);else{Q.setFloat32(0,r);let e=Q.getUint32(0),t=(e&2139095040)>>23,n=e&8388607;if(t===255)Q.setUint16(0,31744,!1);else if(t===0)Q.setUint16(0,(r&2147483648)>>16|n>>13,!1);else{let o=t-127;o<-24?Q.setUint16(0,0):o<-14?Q.setUint16(0,(e&2147483648)>>16|1<<24+o,!1):Q.setUint16(0,(e&2147483648)>>16|o+15<<10|n>>13,!1)}}}function Nn(r,e){if(r.length-e<2)throw new Error(`${m} not enough data for float16`);let t=(r[e]<<8)+r[e+1];if(t===31744)return 1/0;if(t===64512)return-1/0;if(t===32256)return NaN;let n=t>>10&31,o=t&1023,i;return n===0?i=o*2**-24:n!==31?i=(o+1024)*2**(n-25):i=o===0?1/0:NaN,t&32768?-i:i}function is(r){Q.setFloat32(0,r,!1)}function Rn(r,e){if(r.length-e<4)throw new Error(`${m} not enough data for float32`);let t=(r.byteOffset||0)+e;return new DataView(r.buffer,t,4).getFloat32(0,!1)}function uu(r){Q.setFloat64(0,r,!1)}function ss(r,e){if(r.length-e<8)throw new Error(`${m} not enough data for float64`);let t=(r.byteOffset||0)+e;return new DataView(r.buffer,t,8).getFloat64(0,!1)}Ht.compareTokens=G.compareTokens;function E(r,e,t){throw new Error(`${m} encountered invalid minor (${t}) for major ${r[e]>>>5}`)}function Wt(r){return()=>{throw new Error(`${m} ${r}`)}}var p=[];for(let r=0;r<=23;r++)p[r]=E;p[24]=mi;p[25]=gi;p[26]=yi;p[27]=wi;p[28]=E;p[29]=E;p[30]=E;p[31]=E;for(let r=32;r<=55;r++)p[r]=E;p[56]=bi;p[57]=xi;p[58]=Ei;p[59]=_i;p[60]=E;p[61]=E;p[62]=E;p[63]=E;for(let r=64;r<=87;r++)p[r]=ki;p[88]=Ai;p[89]=Ci;p[90]=Si;p[91]=Ii;p[92]=E;p[93]=E;p[94]=E;p[95]=Wt("indefinite length bytes/strings are not supported");for(let r=96;r<=119;r++)p[r]=Ti;p[120]=Li;p[121]=Pi;p[122]=Ni;p[123]=Ri;p[124]=E;p[125]=E;p[126]=E;p[127]=Wt("indefinite length bytes/strings are not supported");for(let r=128;r<=151;r++)p[r]=Bi;p[152]=Ui;p[153]=Fi;p[154]=Oi;p[155]=zi;p[156]=E;p[157]=E;p[158]=E;p[159]=Mi;for(let r=160;r<=183;r++)p[r]=$i;p[184]=qi;p[185]=ji;p[186]=Vi;p[187]=Ki;p[188]=E;p[189]=E;p[190]=E;p[191]=Hi;for(let r=192;r<=215;r++)p[r]=Wi;p[216]=Gi;p[217]=Qi;p[218]=Ji;p[219]=Yi;p[220]=E;p[221]=E;p[222]=E;p[223]=E;for(let r=224;r<=243;r++)p[r]=Wt("simple values are not supported");p[244]=E;p[245]=E;p[246]=E;p[247]=Xi;p[248]=Wt("simple values are not supported");p[249]=es;p[250]=ts;p[251]=rs;p[252]=E;p[253]=E;p[254]=E;p[255]=Zi;var te=[];for(let r=0;r<24;r++)te[r]=new h(c.uint,r,1);for(let r=-1;r>=-24;r--)te[31-r]=new h(c.negint,r,1);te[64]=new h(c.bytes,new Uint8Array(0),1);te[96]=new h(c.string,"",1);te[128]=new h(c.array,0,1);te[160]=new h(c.map,0,1);te[244]=new h(c.false,!1,1);te[245]=new h(c.true,!0,1);te[246]=new h(c.null,null,1);function as(r){switch(r.type){case c.false:return ie([244]);case c.true:return ie([245]);case c.null:return ie([246]);case c.bytes:return r.value.length?void 0:ie([64]);case c.string:return r.value===""?ie([96]):void 0;case c.array:return r.value===0?ie([128]):void 0;case c.map:return r.value===0?ie([160]):void 0;case c.uint:return r.value<24?ie([Number(r.value)]):void 0;case c.negint:if(r.value>=-24)return ie([31-Number(r.value)])}}var fu={float64:!1,mapSorter:pu,quickEncodeToken:as};function hu(){let r=[];return r[c.uint.major]=G,r[c.negint.major]=$t,r[c.bytes.major]=ze,r[c.string.major]=Di,r[c.array.major]=jt,r[c.map.major]=Vt,r[c.tag.major]=Kt,r[c.float.major]=Ht,r}var cs=hu(),Dn=new ot,Qt=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(`${ce} object contains circular references`);return new r(t,e)}},ye={null:new h(c.null,null),undefined:new h(c.undefined,void 0),true:new h(c.true,!0),false:new h(c.false,!1),emptyArray:new h(c.array,0),emptyMap:new h(c.map,0)},we={number(r,e,t,n){return!Number.isInteger(r)||!Number.isSafeInteger(r)?new h(c.float,r):r>=0?new h(c.uint,r):new h(c.negint,r)},bigint(r,e,t,n){return r>=BigInt(0)?new h(c.uint,r):new h(c.negint,r)},Uint8Array(r,e,t,n){return new h(c.bytes,r)},string(r,e,t,n){return new h(c.string,r)},boolean(r,e,t,n){return r?ye.true:ye.false},null(r,e,t,n){return ye.null},undefined(r,e,t,n){return ye.undefined},ArrayBuffer(r,e,t,n){return new h(c.bytes,new Uint8Array(r))},DataView(r,e,t,n){return new h(c.bytes,new Uint8Array(r.buffer,r.byteOffset,r.byteLength))},Array(r,e,t,n){if(!r.length)return t.addBreakTokens===!0?[ye.emptyArray,new h(c.break)]:ye.emptyArray;n=Qt.createCheck(n,r);let o=[],i=0;for(let s of r)o[i++]=Gt(s,t,n);return t.addBreakTokens?[new h(c.array,r.length),o,new h(c.break)]:[new h(c.array,r.length),o]},Object(r,e,t,n){let o=e!=="Object",i=o?r.keys():Object.keys(r),s=o?r.size:i.length;if(!s)return t.addBreakTokens===!0?[ye.emptyMap,new h(c.break)]:ye.emptyMap;n=Qt.createCheck(n,r);let a=[],u=0;for(let d of i)a[u++]=[Gt(d,t,n),Gt(o?r.get(d):r[d],t,n)];return du(a,t),t.addBreakTokens?[new h(c.map,s),a,new h(c.break)]:[new h(c.map,s),a]}};we.Map=we.Object;we.Buffer=we.Uint8Array;for(let r of"Uint8Clamped Uint16 Uint32 Int8 Int16 Int32 BigUint64 BigInt64 Float32 Float64".split(" "))we[`${r}Array`]=we.DataView;function Gt(r,e={},t){let n=ai(r),o=e&&e.typeEncoders&&e.typeEncoders[n]||we[n];if(typeof o=="function"){let s=o(r,n,e,t);if(s!=null)return s}let i=we[n];if(!i)throw new Error(`${ce} unsupported type: ${n}`);return i(r,n,e,t)}function du(r,e){e.mapSorter&&r.sort(e.mapSorter)}function pu(r,e){let t=Array.isArray(r[0])?r[0][0]:r[0],n=Array.isArray(e[0])?e[0][0]:e[0];if(t.type!==n.type)return t.type.compare(n.type);let o=t.type.major,i=cs[o].compareTokens(t,n);return i===0&&console.warn("WARNING: complex key types used, CBOR key sorting guarantees are gone"),i}function us(r,e,t,n){if(Array.isArray(e))for(let o of e)us(r,o,t,n);else t[e.type.major](r,e,n)}function Bn(r,e,t){let n=Gt(r,t);if(!Array.isArray(n)&&t.quickEncodeToken){let o=t.quickEncodeToken(n);if(o)return o;let i=e[n.type.major];if(i.encodedSize){let s=i.encodedSize(n,t),a=new ot(s);if(i(a,n,t),a.chunks.length!==1)throw new Error(`Unexpected error: pre-calculated length for ${n} was wrong`);return nt(a.chunks[0])}}return Dn.reset(),us(Dn,n,e,t),Dn.toBytes(!0)}function ke(r,e){return e=Object.assign({},fu,e),Bn(r,cs,e)}var mu={strict:!1,allowIndefinite:!0,allowUndefined:!0,allowBigInt:!0},Jt=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=te[e];if(t===void 0){let n=p[e];if(!n)throw new Error(`${m} no decoder for major type ${e>>>5} (byte 0x${e.toString(16).padStart(2,"0")})`);let o=e&31;t=n(this.data,this._pos,o,this.options)}return this._pos+=t.encodedLength,t}},ct=Symbol.for("DONE"),Yt=Symbol.for("BREAK");function gu(r,e,t){let n=[];for(let o=0;o<r.value;o++){let i=qe(e,t);if(i===Yt){if(r.value===1/0)break;throw new Error(`${m} got unexpected break to lengthed array`)}if(i===ct)throw new Error(`${m} found array but not enough entries (got ${o}, expected ${r.value})`);n[o]=i}return n}function yu(r,e,t){let n=t.useMaps===!0,o=n?void 0:{},i=n?new Map:void 0;for(let s=0;s<r.value;s++){let a=qe(e,t);if(a===Yt){if(r.value===1/0)break;throw new Error(`${m} got unexpected break to lengthed map`)}if(a===ct)throw new Error(`${m} found map but not enough entries (got ${s} [no key], expected ${r.value})`);if(n!==!0&&typeof a!="string")throw new Error(`${m} non-string keys not supported (got ${typeof a})`);if(t.rejectDuplicateMapKeys===!0&&(n&&i.has(a)||!n&&a in o))throw new Error(`${m} found repeat map key "${a}"`);let u=qe(e,t);if(u===ct)throw new Error(`${m} found map but not enough entries (got ${s} [no value], expected ${r.value})`);n?i.set(a,u):o[a]=u}return n?i:o}function qe(r,e){if(r.done())return ct;let t=r.next();if(t.type===c.break)return Yt;if(t.type.terminal)return t.value;if(t.type===c.array)return gu(t,r,e);if(t.type===c.map)return yu(t,r,e);if(t.type===c.tag){if(e.tags&&typeof e.tags[t.value]=="function"){let n=qe(r,e);return e.tags[t.value](n)}throw new Error(`${m} tag not supported (${t.value})`)}throw new Error("unsupported")}function Un(r,e){if(!(r instanceof Uint8Array))throw new Error(`${m} data to decode must be a Uint8Array`);e=Object.assign({},mu,e);let t=e.tokenizer||new Jt(r,e),n=qe(t,e);if(n===ct)throw new Error(`${m} did not find any content to decode`);if(n===Yt)throw new Error(`${m} got unexpected break`);return[n,r.subarray(t.pos())]}function re(r,e){let[t,n]=Un(r,e);if(n.length>0)throw new Error(`${m} too many terminals, data makes no sense`);return t}var Xt=class extends ae{has(e){return this.find(e)!=null}find(e){return this.queue.find(t=>e.equals(t.options.peerId))}};var le="/",fs=new TextEncoder().encode(le),Zt=fs[0],fe=class r{_buf;constructor(e,t){if(typeof e=="string")this._buf=B(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]!==Zt)throw new Error("Invalid key")}toString(e="utf8"){return Be(this._buf,e)}uint8Array(){return this._buf}get[Symbol.toStringTag](){return`Key(${this.toString()})`}static withNamespaces(e){return new r(e.join(le))}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=fs),this._buf[0]!==Zt){let e=new Uint8Array(this._buf.byteLength+1);e.fill(Zt,0,1),e.set(this._buf,1),this._buf=e}for(;this._buf.byteLength>1&&this._buf[this._buf.byteLength-1]===Zt;)this._buf=this._buf.subarray(0,-1)}less(e){let t=this.list(),n=e.list();for(let o=0;o<t.length;o++){if(n.length<o+1)return!1;let i=t[o],s=n[o];if(i<s)return!0;if(i>s)return!1}return t.length<n.length}reverse(){return r.withNamespaces(this.list().slice().reverse())}namespaces(){return this.list()}baseNamespace(){let e=this.namespaces();return e[e.length-1]}list(){return this.toString().split(le).slice(1)}type(){return wu(this.baseNamespace())}name(){return bu(this.baseNamespace())}instance(e){return new r(this.toString()+":"+e)}path(){let e=this.parent().toString();return e.endsWith(le)||(e+=le),e+=this.type(),new r(e)}parent(){let e=this.list();return e.length===1?new r(le):new r(e.slice(0,-1).join(le))}child(e){return this.toString()===le?e:e.toString()===le?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(),...xu(e.map(t=>t.namespaces()))])}};function wu(r){let e=r.split(":");return e.length<2?"":e.slice(0,-1).join(":")}function bu(r){let e=r.split(":");return e[e.length-1]}function xu(r){return[].concat(...r)}function Eu(r){return r[Symbol.asyncIterator]!=null}function vu(r){if(Eu(r))return(async()=>{let n=new Uint8Array(0);for await(let o of r)n=En([n,o],n.length+o.length);return n})();let e=[],t=0;for(let n of r)e.push(n),t+=n.byteLength;return En(e,t)}var hs=vu;function er({enumerable:r=!0,configurable:e=!1}={}){return{enumerable:r,configurable:e,writable:!1}}function*_u(r,e){if(e!=null&&typeof e=="object")if(Array.isArray(e))for(let[t,n]of e.entries()){let o=[...r,t],i=k.asCID(n);i!=null?yield[o.join("/"),i]:typeof n=="object"&&(yield*Fn(n,o))}else{let t=k.asCID(e);t!=null?yield[r.join("/"),t]:yield*Fn(e,r)}}function*Fn(r,e){if(r==null||r instanceof Uint8Array)return;let t=k.asCID(r);t!=null&&(yield[e.join("/"),t]);for(let[n,o]of Object.entries(r)){let i=[...e,n];yield*_u(i,o)}}function*ku(r,e){if(Array.isArray(e))for(let[t,n]of e.entries()){let o=[...r,t];yield o.join("/"),typeof n=="object"&&k.asCID(n)==null&&(yield*On(n,o))}else yield*On(e,r)}function*On(r,e){if(!(r==null||typeof r!="object"))for(let[t,n]of Object.entries(r)){let o=[...e,t];yield o.join("/"),n!=null&&!(n instanceof Uint8Array)&&typeof n=="object"&&k.asCID(n)==null&&(yield*ku(o,n))}}function Au(r,e){let t=r;for(let[n,o]of e.entries()){if(t=t[o],t==null)throw new Error(`Object has no property at ${e.slice(0,n+1).map(s=>`[${JSON.stringify(s)}]`).join("")}`);let i=k.asCID(t);if(i!=null)return{value:i,remaining:e.slice(n+1).join("/")}}return{value:t}}var zn=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:er(),bytes:er(),value:er(),asBlock:er()})}links(){return Fn(this.value,[])}tree(){return On(this.value,[])}get(e="/"){return Au(this.value,e.split("/").filter(Boolean))}};function ds({bytes:r,cid:e,value:t,codec:n}){let o=t!==void 0?t:n?.decode(r);if(o===void 0)throw new Error('Missing required argument, must either provide "value" or "codec"');return new zn({cid:e,bytes:r,value:o})}var tr=class extends Error{static name="AlreadyPinnedError";name="AlreadyPinnedError"},ut=class extends Error{static name="BlockPinnedError";name="BlockPinnedError"},rr=class extends Error{static name="InvalidDatastoreVersion";name="InvalidDatastoreVersion"};var gs="/pin/",ps="/pinned-block/",Mn=se,ms=1;function nr(r){return r.version===0&&(r=r.toV1()),new fe(`${gs}${r.toString(Mn)}`)}var or=class{datastore;blockstore;getCodec;constructor(e,t,n){this.datastore=e,this.blockstore=t,this.getCodec=n}async*add(e,t={}){let n=nr(e);if(await this.datastore.has(n))throw new tr("Already pinned");let o=Math.round(t.depth??1/0);if(o<0)throw new Te("Depth must be greater than or equal to 0");let i=new ae({concurrency:ms});for await(let a of this.#e(e,i,{...t,depth:o}))await this.#o(a,u=>u.pinnedBy.find(d=>xe(d,e.bytes))!=null?!1:(u.pinCount++,u.pinnedBy.push(e.bytes),!0),t),yield a;let s={depth:o,metadata:t.metadata??{}};await this.datastore.put(n,ke(s),t)}async*#e(e,t,n){if(n.depth===-1)return;let o=await this.getCodec(e.code),i=await hs(this.blockstore.get(e,n)),s=ds({bytes:i,cid:e,codec:o});yield e;for(let[,a]of s.links())yield*await t.add(async()=>this.#e(a,t,{...n,depth:n.depth-1}))}async#o(e,t,n){let o=new fe(`${ps}${Mn.encode(e.multihash.bytes)}`),i={pinCount:0,pinnedBy:[]};try{i=re(await this.datastore.get(o,n))}catch(a){if(a.name!=="NotFoundError")throw a}if(t(i)){if(i.pinCount===0&&await this.datastore.has(o)){await this.datastore.delete(o);return}await this.datastore.put(o,ke(i),n),n.onProgress?.(new v("helia:pin:add",e))}}async*rm(e,t={}){let n=nr(e),o=await this.datastore.get(n,t),i=re(o);await this.datastore.delete(n,t);let s=new ae({concurrency:ms});for await(let a of this.#e(e,s,{...t,depth:i.depth}))await this.#o(a,u=>(u.pinCount--,u.pinnedBy=u.pinnedBy.filter(d=>xe(d,e.bytes)),!0),{...t,depth:i.depth}),yield a}async*ls(e={}){for await(let{key:t,value:n}of this.datastore.query({prefix:gs+(e.cid!=null?`${e.cid.toString(se)}`:"")},e)){let o=k.parse(t.toString().substring(5),se),i=re(n);yield{cid:o,...i}}}async isPinned(e,t={}){let n=new fe(`${ps}${Mn.encode(e.multihash.bytes)}`);return this.datastore.has(n,t)}async get(e,t){let n=nr(e),o=await this.datastore.get(n,t);return re(o)}async setMetadata(e,t,n){let o=nr(e),i=await this.datastore.get(o,n),s=re(i);s.metadata=t??{},await this.datastore.put(o,ke(s),n)}};var ir=class extends Error{static name="InsufficientProvidersError";constructor(e="Insufficient providers found"){super(e),this.name="InsufficientProvidersError"}},Ae=class extends Error{static name="NoRoutersAvailableError";constructor(e="No routers available"){super(e),this.name="NoRoutersAvailableError"}},sr=class extends Error{static name="UnknownHashAlgorithmError";constructor(e="Unknown hash algorithm"){super(e),this.name="UnknownHashAlgorithmError"}},ar=class extends Error{static name="UnknownCodecError";constructor(e="Unknown codec"){super(e),this.name="UnknownCodecError"}};var Cu=5,cr=class{log;routers;providerLookupConcurrency;constructor(e,t){this.log=e.logger.forComponent("helia:routing"),this.routers=t.routers??[],this.providerLookupConcurrency=t.providerLookupConcurrency??Cu,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 he(...this.routers)}async stop(){await de(...this.routers)}async*findProviders(e,t={}){if(this.routers.length===0)throw new Ae("No content routers available");let n=new Xt({concurrency:this.providerLookupConcurrency});for await(let o of Ot(n.toGenerator(),...Ce(this.routers,"findProviders").map(i=>i.findProviders(e,t))))if(o!=null){if(o.multiaddrs.length===0){if(n.find(o.id)!=null)continue;n.add(async()=>{try{let i=await this.findPeer(o.id,t);return i.multiaddrs.length===0?null:i}catch(i){return this.log.error("could not load multiaddrs for peer %p",o.id,i),null}},{peerId:o.id,signal:t.signal}).catch(i=>{this.log.error("could not load multiaddrs for peer %p",o.id,i)})}yield o}}async provide(e,t={}){if(this.routers.length===0)throw new Ae("No content routers available");await Promise.all(Ce(this.routers,"provide").map(async n=>{await n.provide(e,t)}))}async cancelReprovide(e,t={}){await Promise.all(Ce(this.routers,"cancelReprovide").map(async n=>{await n.cancelReprovide(e,t)}))}async put(e,t,n){await Promise.all(Ce(this.routers,"put").map(async o=>{await o.put(e,t,n)}))}async get(e,t){return Promise.any(Ce(this.routers,"get").map(async n=>n.get(e,t)))}async findPeer(e,t){if(this.routers.length===0)throw new Ae("No peer routers available");let n=this,o=Ot(...Ce(this.routers,"findPeer").map(i=>(async function*(){try{yield await i.findPeer(e,t)}catch(s){n.log.error(s)}})()));for await(let i of o)if(i!=null)return i;throw new pt("Could not find peer in routing")}async*getClosestPeers(e,t={}){if(this.routers.length===0)throw new Ae("No peer routers available");for await(let n of Ot(...Ce(this.routers,"getClosestPeers").map(o=>o.getClosestPeers(e,t))))n!=null&&(yield n)}};function Ce(r,e){return r.filter(t=>t[e]!=null)}var j=class extends Error{static name="AbortError";name="AbortError";constructor(e="The operation was aborted",...t){super(e,...t)}};async function ur(r,e,t,n){let o=new j(n?.errorMessage);n?.errorCode!=null&&(o.code=n.errorCode);let i=n?.errorEvent??"error";return t?.aborted===!0?Promise.reject(o):new Promise((s,a)=>{function u(){qn(t,"abort",f),qn(r,e,d),qn(r,i,l)}let d=g=>{try{if(n?.filter?.(g)===!1)return}catch(y){u(),a(y);return}u(),s(g)},l=g=>{if(u(),g instanceof Error){a(g);return}a(g.detail??n?.error??new Error(`The "${n?.errorEvent}" event was emitted but the event had no '.detail' field. Pass an 'error' option to race-event to change this message.`))},f=()=>{u(),a(o)};$n(t,"abort",f),$n(r,e,d),$n(r,i,l)})}function $n(r,e,t){r!=null&&(ys(r)?r.addEventListener(e,t):r.addListener(e,t))}function qn(r,e,t){r!=null&&(ys(r)?r.removeEventListener(e,t):r.removeListener(e,t))}function ys(r){return typeof r.addEventListener=="function"&&typeof r.removeEventListener=="function"}var lr=class extends Error{static name="QueueFullError";constructor(e="The queue was full"){super(e),this.name="QueueFullError"}};var fr=class extends Error{type;code;constructor(e,t,n){super(e??"The operation was aborted"),this.type="aborted",this.name=n??"AbortError",this.code=t??"ABORT_ERR"}};async function ws(r,e,t){if(e==null)return r;if(e.aborted)return r.catch(()=>{}),Promise.reject(new fr(t?.errorMessage,t?.errorCode,t?.errorName));let n,o=new fr(t?.errorMessage,t?.errorCode,t?.errorName);try{return await Promise.race([r,new Promise((i,s)=>{n=()=>{s(o)},e.addEventListener("abort",n)})])}finally{n!=null&&e.removeEventListener("abort",n)}}var hr=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 j)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function Su(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var dr=class{id;fn;options;recipients;status;timeline;controller;constructor(e,t){this.id=Su(),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 j),this.cleanup())}async join(e={}){let t=new hr(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 ws(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 jn(r,e){let t,n=function(){let o=function(){t=void 0,r()};clearTimeout(t),t=setTimeout(o,e)};return n.start=()=>{},n.stop=()=>{clearTimeout(t)},n}var lt=class extends H{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=jn(this.emitEmpty.bind(this),1),this.emitIdle=jn(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 lr;let n=new dr(e,t);return this.enqueue(n),this.safeDispatchEvent("add"),this.autoStart&&this.tryToStartAnother(),n.join(t).then(o=>(this.safeDispatchEvent("success",{detail:{job:n,result:o}}),o)).catch(o=>{if(n.status==="queued"){for(let i=0;i<this.queue.length;i++)if(this.queue[i]===n){this.queue.splice(i,1);break}}throw this.safeDispatchEvent("failure",{detail:{job:n,error:o}}),o})}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(e=>{e.abort(new j)}),this.clear()}async onEmpty(e){this.size!==0&&await ur(this,"empty",e?.signal)}async onSizeLessThan(e,t){this.size<e||await ur(this,"next",t?.signal,{filter:()=>this.size<e})}async onIdle(e){this.pending===0&&this.size===0||await ur(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=Nt({objectMode:!0}),n=u=>{u!=null?this.abort():this.clear(),t.end(u)},o=u=>{u.detail!=null&&t.push(u.detail.result)},i=u=>{n(u.detail.error)},s=()=>{n()},a=()=>{n(new j("Queue aborted"))};this.addEventListener("success",o),this.addEventListener("failure",i),this.addEventListener("idle",s),e?.signal?.addEventListener("abort",a);try{yield*t}finally{this.removeEventListener("success",o),this.removeEventListener("failure",i),this.removeEventListener("idle",s),e?.signal?.removeEventListener("abort",a),n()}}};var pr="lock:worker:request-read",mr="lock:worker:abort-read-request",gr="lock:worker:release-read",yr="lock:master:grant-read",wr="lock:master:error-read",br="lock:worker:request-write",xr="lock:worker:abort-write-request",Er="lock:worker:release-write",vr="lock:master:grant-write",_r="lock:master:error-write",kr="lock:worker:finalize",Ar="mortice",bs={singleProcess:!1};var Vn=(r,e,t,n,o,i,s,a,u)=>d=>{if(d.data==null)return;let l={type:d.data.type,name:d.data.name,identifier:d.data.identifier};l.type===o&&r.safeDispatchEvent(t,{detail:{name:l.name,identifier:l.identifier,handler:async()=>{e.postMessage({type:u,name:l.name,identifier:l.identifier}),await new Promise(f=>{let g=y=>{if(y?.data==null)return;let b={type:y.data.type,name:y.data.name,identifier:y.data.identifier};b.type===a&&b.identifier===l.identifier&&(e.removeEventListener("message",g),f())};e.addEventListener("message",g)})},onError:f=>{e.postMessage({type:s,name:l.name,identifier:l.identifier,error:{message:f.message,name:f.name,stack:f.stack}})}}}),l.type===i&&r.safeDispatchEvent(n,{detail:{name:l.name,identifier:l.identifier}}),l.type===kr&&r.safeDispatchEvent("finalizeRequest",{detail:{name:l.name}})};var xs=(r=10)=>Math.random().toString().substring(2,r+2);var Cr=class{name;channel;constructor(e){this.name=e,this.channel=new BroadcastChannel(Ar)}readLock(e){return this.sendRequest(pr,mr,yr,wr,gr,e)}writeLock(e){return this.sendRequest(br,xr,vr,_r,Er,e)}finalize(){this.channel.postMessage({type:kr,name:this.name}),this.channel.close()}async sendRequest(e,t,n,o,i,s){s?.signal?.throwIfAborted();let a=xs();return this.channel.postMessage({type:e,identifier:a,name:this.name}),new Promise((u,d)=>{let l=()=>{this.channel.postMessage({type:t,identifier:a,name:this.name})};s?.signal?.addEventListener("abort",l,{once:!0});let f=g=>{if(g.data?.identifier===a&&(g.data?.type===n&&(this.channel.removeEventListener("message",f),s?.signal?.removeEventListener("abort",l),u(()=>{this.channel.postMessage({type:i,identifier:a,name:this.name})})),g.data.type===o)){this.channel.removeEventListener("message",f),s?.signal?.removeEventListener("abort",l);let y=new Error;g.data.error!=null&&(y.message=g.data.error.message,y.name=g.data.error.name,y.stack=g.data.error.stack),d(y)}};this.channel.addEventListener("message",f)})}};var Es=r=>{if(r=Object.assign({},bs,r),!!globalThis.document||r.singleProcess){let t=new BroadcastChannel(Ar),n=new H;return t.addEventListener("message",Vn(n,t,"requestReadLock","abortReadLockRequest",pr,mr,wr,gr,yr)),t.addEventListener("message",Vn(n,t,"requestWriteLock","abortWriteLockRequest",br,xr,_r,Er,vr)),n}return new Cr(r.name)};var Se=new Map,ft;function vs(r){return typeof r?.readLock=="function"&&typeof r?.writeLock=="function"}function Iu(r){if(ft==null&&(ft=Es(r),!vs(ft))){let e=ft;e.addEventListener("requestReadLock",t=>{let n=t.detail.name,o=t.detail.identifier,i=Se.get(n);if(i==null)return;let s=new AbortController,a=u=>{u.detail.name!==n||u.detail.identifier!==o||s.abort()};e.addEventListener("abortReadLockRequest",a),i.readLock({signal:s.signal}).then(async u=>{await t.detail.handler().finally(()=>{u()})}).catch(u=>{t.detail.onError(u)}).finally(()=>{e.removeEventListener("abortReadLockRequest",a)})}),e.addEventListener("requestWriteLock",t=>{let n=t.detail.name,o=t.detail.identifier,i=Se.get(n);if(i==null)return;let s=new AbortController,a=u=>{u.detail.name!==n||u.detail.identifier!==o||s.abort()};e.addEventListener("abortWriteLockRequest",a),i.writeLock({signal:s.signal}).then(async u=>{await t.detail.handler().finally(()=>{u()})}).catch(u=>{t.detail.onError(u)}).finally(()=>{e.removeEventListener("abortWriteLockRequest",a)})}),e.addEventListener("finalizeRequest",t=>{let n=t.detail.name,o=Se.get(n);o?.finalize()})}return ft}async function Kn(r,e){let t,n,o=new Promise((s,a)=>{t=s,n=a}),i=()=>{n(new j)};return e?.signal?.addEventListener("abort",i,{once:!0}),r.add(async()=>{await new Promise(s=>{t(()=>{e?.signal?.removeEventListener("abort",i),s()})})},{signal:e?.signal}).catch(s=>{n(s)}),o}var _s=(r,e)=>{let t=Se.get(r);if(t!=null)return t;let n=Iu(e);if(vs(n))return t=n,Se.set(r,t),t;let o=new lt({concurrency:1}),i;return t={async readLock(s){if(i!=null)return Kn(i,s);i=new lt({concurrency:e.concurrency,autoStart:!1});let a=i,u=Kn(i,s);return o.add(async()=>{a.start(),await a.onIdle().then(()=>{i===a&&(i=null)})}),u},async writeLock(s){return i=null,Kn(o,s)},finalize:()=>{Se.delete(r)},queue:o},Se.set(r,t),e.autoFinalize===!0&&o.addEventListener("idle",()=>{t.finalize()},{once:!0}),t};var Tu={name:"lock",concurrency:1/0,singleProcess:!1,autoFinalize:!1};function Hn(r){let e=Object.assign({},Tu,r);return _s(e.name,e)}var Sr=class{lock;child;pins;started;constructor(e,t,n={}){this.child=e,this.pins=t,this.lock=Hn({singleProcess:n.holdGcLock}),this.started=!1}isStarted(){return this.started}async start(){await he(this.child),this.started=!0}async stop(){await de(this.child),this.started=!1}unwrap(){return this.child}async put(e,t,n={}){n?.signal?.throwIfAborted();let o=await this.lock.readLock();try{return await this.child.put(e,t,n)}finally{o()}}async*putMany(e,t={}){t?.signal?.throwIfAborted();let n=await this.lock.readLock();try{yield*this.child.putMany(e,t)}finally{n()}}async*get(e,t={}){t?.signal?.throwIfAborted();let n=await this.lock.readLock();try{yield*this.child.get(e,t)}finally{n()}}async*getMany(e,t={}){t?.signal?.throwIfAborted();let n=await this.lock.readLock();try{yield*this.child.getMany(e,t)}finally{n()}}async delete(e,t={}){t?.signal?.throwIfAborted();let n=await this.lock.writeLock();try{if(await this.pins.isPinned(e))throw new ut("Block was pinned - please unpin and try again");await this.child.delete(e,t)}finally{n()}}async*deleteMany(e,t={}){t?.signal?.throwIfAborted();let n=await this.lock.writeLock();try{let o=this;yield*this.child.deleteMany((async function*(){for await(let i of e){if(await o.pins.isPinned(i))throw new ut("Block was pinned - please unpin and try again");yield i}})(),t)}finally{n()}}async has(e,t={}){t?.signal?.throwIfAborted();let n=await this.lock.readLock();try{return await this.child.has(e,t)}finally{n()}}async*getAll(e={}){e?.signal?.throwIfAborted();let t=await this.lock.readLock();try{yield*this.child.getAll(e)}finally{t()}}createSession(e,t){return t?.signal?.throwIfAborted(),this.child.createSession(e,t)}};var Wn=new fe("/version"),ks=1;async function As(r){if(!await r.has(Wn)){await r.put(Wn,B(`${ks}`));return}let e=await r.get(Wn),t=Be(e);if(parseInt(t,10)!==ks)throw new rr("Invalid datastore version, a datastore migration may be required")}var Jn={};T(Jn,{code:()=>Qn,decode:()=>zu,decodeOptions:()=>Uu,encode:()=>Ou,encodeOptions:()=>Du,name:()=>Fu,toByteView:()=>Ss});var Cs=42;function Ss(r){return r instanceof ArrayBuffer?new Uint8Array(r,0,r.byteLength):r}function Lu(r){if(r.asCID!==r&&r["/"]!==r.bytes)return null;let e=k.asCID(r);if(!e)return null;let t=new Uint8Array(e.bytes.byteLength+1);return t.set(e.bytes,1),[new h(c.tag,Cs),new h(c.bytes,t)]}function Pu(){throw new Error("`undefined` is not supported by the IPLD Data Model and cannot be encoded")}function Nu(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 Ru(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 Gn={float64:!0,typeEncoders:{Map:Ru,Object:Lu,undefined:Pu,number:Nu}},Du={...Gn,typeEncoders:{...Gn.typeEncoders}};function Bu(r){if(r[0]!==0)throw new Error("Invalid CID for CBOR tag 42; expected leading 0x00");return k.decode(r.subarray(1))}var Ir={allowIndefinite:!1,coerceUndefinedToNull:!0,allowNaN:!1,allowInfinity:!1,allowBigInt:!0,strict:!0,useMaps:!1,rejectDuplicateMapKeys:!0,tags:[]};Ir.tags[Cs]=Bu;var Uu={...Ir,tags:Ir.tags.slice()},Fu="dag-cbor",Qn=113,Ou=r=>ke(r,Gn),zu=r=>re(Ss(r),Ir);var no={};T(no,{code:()=>ro,decode:()=>Ts,encode:()=>Is,format:()=>Ju,name:()=>Qu,parse:()=>Xu,stringify:()=>Ju});var Yn=class extends Array{constructor(){super(),this.inRecursive=[]}prefix(e){let t=this.inRecursive[this.inRecursive.length-1];t&&(t.type===c.array&&(t.elements++,t.elements!==1&&e.push([44])),t.type===c.map&&(t.elements++,t.elements!==1&&(t.elements%2===1?e.push([44]):e.push([58]))))}[c.uint.major](e,t){this.prefix(e);let n=String(t.value),o=[];for(let i=0;i<n.length;i++)o[i]=n.charCodeAt(i);e.push(o)}[c.negint.major](e,t){this[c.uint.major](e,t)}[c.bytes.major](e,t){throw new Error(`${ce} unsupported type: Uint8Array`)}[c.string.major](e,t){this.prefix(e);let n=Mt(JSON.stringify(t.value));e.push(n.length>32?nt(n):n)}[c.array.major](e,t){this.prefix(e),this.inRecursive.push({type:c.array,elements:0}),e.push([91])}[c.map.major](e,t){this.prefix(e),this.inRecursive.push({type:c.map,elements:0}),e.push([123])}[c.tag.major](e,t){}[c.float.major](e,t){if(t.type.name==="break"){let s=this.inRecursive.pop();if(s){if(s.type===c.array)e.push([93]);else if(s.type===c.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(`${ce} unsupported type: undefined`);if(this.prefix(e),t.type.name==="true"){e.push([116,114,117,101]);return}else if(t.type.name==="false"){e.push([102,97,108,115,101]);return}else if(t.type.name==="null"){e.push([110,117,108,108]);return}let n=String(t.value),o=[],i=!1;for(let s=0;s<n.length;s++)o[s]=n.charCodeAt(s),!i&&(o[s]===46||o[s]===101||o[s]===69)&&(i=!0);i||(o.push(46),o.push(48)),e.push(o)}};function Mu(r,e){if(Array.isArray(r[0])||Array.isArray(e[0]))throw new Error(`${ce} complex map keys are not supported`);let t=r[0],n=e[0];if(t.type!==c.string||n.type!==c.string)throw new Error(`${ce} non-string map keys are not supported`);if(t<n)return-1;if(t>n)return 1;throw new Error(`${ce} unexpected duplicate map keys, this is not supported`)}var $u={addBreakTokens:!0,mapSorter:Mu};function Xn(r,e){return e=Object.assign({},$u,e),Bn(r,new Yn,e)}var je=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(`${m} 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(`${m} unexpected token at position ${this._pos}, expected to find '${String.fromCharCode(...e)}'`)}parseNumber(){let e=this._pos,t=!1,n=!1,o=a=>{for(;!this.done();){let u=this.ch();if(a.includes(u))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 h(c.uint,0,this._pos-e);if(o([48,49,50,51,52,53,54,55,56,57]),t&&this._pos===e+1)throw new Error(`${m} unexpected token at position ${this._pos}`);if(!this.done()&&this.ch()===46){if(n)throw new Error(`${m} unexpected token at position ${this._pos}`);n=!0,this._pos++,o([48,49,50,51,52,53,54,55,56,57])}!this.done()&&(this.ch()===101||this.ch()===69)&&(n=!0,this._pos++,!this.done()&&(this.ch()===43||this.ch()===45)&&this._pos++,o([48,49,50,51,52,53,54,55,56,57]));let i=String.fromCharCode.apply(null,this.data.subarray(e,this._pos)),s=parseFloat(i);return n?new h(c.float,s,this._pos-e):this.options.allowBigInt!==!0||Number.isSafeInteger(s)?new h(s>=0?c.uint:c.negint,s,this._pos-e):new h(s>=0?c.uint:c.negint,BigInt(i),this._pos-e)}parseString(){if(this.ch()!==34)throw new Error(`${m} unexpected character at position ${this._pos}; this shouldn't happen`);this._pos++;for(let i=this._pos,s=0;i<this.data.length&&s<65536;i++,s++){let a=this.data[i];if(a===92||a<32||a>=128)break;if(a===34){let u=String.fromCharCode.apply(null,this.data.subarray(this._pos,i));return this._pos=i+1,new h(c.string,u,s)}}let e=this._pos,t=[],n=()=>{if(this._pos+4>=this.data.length)throw new Error(`${m} unexpected end of unicode escape sequence at position ${this._pos}`);let i=0;for(let s=0;s<4;s++){let a=this.ch();if(a>=48&&a<=57)a-=48;else if(a>=97&&a<=102)a=a-97+10;else if(a>=65&&a<=70)a=a-65+10;else throw new Error(`${m} unexpected unicode escape character at position ${this._pos}`);i=i*16+a,this._pos++}return i},o=()=>{let i=this.ch(),s=null,a=i>239?4:i>223?3:i>191?2:1;if(this._pos+a>this.data.length)throw new Error(`${m} unexpected unicode sequence at position ${this._pos}`);let u,d,l,f;switch(a){case 1:i<128&&(s=i);break;case 2:u=this.data[this._pos+1],(u&192)===128&&(f=(i&31)<<6|u&63,f>127&&(s=f));break;case 3:u=this.data[this._pos+1],d=this.data[this._pos+2],(u&192)===128&&(d&192)===128&&(f=(i&15)<<12|(u&63)<<6|d&63,f>2047&&(f<55296||f>57343)&&(s=f));break;case 4:u=this.data[this._pos+1],d=this.data[this._pos+2],l=this.data[this._pos+3],(u&192)===128&&(d&192)===128&&(l&192)===128&&(f=(i&15)<<18|(u&63)<<12|(d&63)<<6|l&63,f>65535&&f<1114112&&(s=f))}s===null?(s=65533,a=1):s>65535&&(s-=65536,t.push(s>>>10&1023|55296),s=56320|s&1023),t.push(s),this._pos+=a};for(;!this.done();){let i=this.ch(),s;switch(i){case 92:if(this._pos++,this.done())throw new Error(`${m} 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(`${m} unexpected string escape character at position ${this._pos}`)}break;case 34:return this._pos++,new h(c.string,Tn(t),this._pos-e);default:if(i<32)throw new Error(`${m} invalid control character at position ${this._pos}`);i<128?(t.push(i),this._pos++):o()}}throw new Error(`${m} unexpected end of string at position ${this._pos}`)}parseValue(){switch(this.ch()){case 123:return this.modeStack.push("obj-start"),this._pos++,new h(c.map,1/0,1);case 91:return this.modeStack.push("array-start"),this._pos++,new h(c.array,1/0,1);case 34:return this.parseString();case 110:return this.expect([110,117,108,108]),new h(c.null,null,4);case 102:return this.expect([102,97,108,115,101]),new h(c.false,!1,5);case 116:return this.expect([116,114,117,101]),new h(c.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(`${m} 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 h(c.break,void 0,1);if(this.ch()!==44)throw new Error(`${m} 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 h(c.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 h(c.break,void 0,1);if(this.ch()!==44)throw new Error(`${m} 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 h(c.break,void 0,1);let e=this.parseString();if(this.skipWhitespace(),this.ch()!==58)throw new Error(`${m} 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(`${m} unexpected parse state at position ${this._pos}; this shouldn't happen`)}}};function Zn(r,e){return e=Object.assign({tokenizer:new je(r,e)},e),re(r,e)}function ju(r){return r instanceof ArrayBuffer?new Uint8Array(r,0,r.byteLength):r}function Vu(r){if(r.asCID!==r&&r["/"]!==r.bytes)return null;let e=k.asCID(r);if(!e)return null;let t=e.toString();return[new h(c.map,1/0,1),new h(c.string,"/",1),new h(c.string,t,t.length),new h(c.break,void 0,1)]}function Tr(r){let e=ge.encode(r).slice(1);return[new h(c.map,1/0,1),new h(c.string,"/",1),new h(c.map,1/0,1),new h(c.string,"bytes",5),new h(c.string,e,e.length),new h(c.break,void 0,1),new h(c.break,void 0,1)]}function ne(r){return Tr(new Uint8Array(r.buffer,r.byteOffset,r.byteLength))}function Ku(r){return Tr(new Uint8Array(r))}function Hu(){throw new Error("`undefined` is not supported by the IPLD Data Model and cannot be encoded")}function Wu(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 Gu={typeEncoders:{Object:Vu,Buffer:Tr,Uint8Array:Tr,Int8Array:ne,Uint16Array:ne,Int16Array:ne,Uint32Array:ne,Int32Array:ne,Float32Array:ne,Float64Array:ne,Uint8ClampedArray:ne,BigInt64Array:ne,BigUint64Array:ne,DataView:ne,ArrayBuffer:Ku,undefined:Hu,number:Wu}},eo=class extends je{constructor(e,t){super(e,t),this.tokenBuffer=[]}done(){return this.tokenBuffer.length===0&&super.done()}_next(){return this.tokenBuffer.length>0?this.tokenBuffer.pop():super.next()}next(){let e=this._next();if(e.type===c.map){let t=this._next();if(t.type===c.string&&t.value==="/"){let n=this._next();if(n.type===c.string){if(this._next().type!==c.break)throw new Error("Invalid encoded CID form");return this.tokenBuffer.push(n),new h(c.tag,42,0)}if(n.type===c.map){let o=this._next();if(o.type===c.string&&o.value==="bytes"){let i=this._next();if(i.type===c.string){for(let a=0;a<2;a++)if(this._next().type!==c.break)throw new Error("Invalid encoded Bytes form");let s=ge.decode(`m${i.value}`);return new h(c.bytes,s,i.value.length)}this.tokenBuffer.push(i)}this.tokenBuffer.push(o)}this.tokenBuffer.push(n)}this.tokenBuffer.push(t)}return e}},to={allowIndefinite:!1,allowUndefined:!1,allowNaN:!1,allowInfinity:!1,allowBigInt:!0,strict:!0,useMaps:!1,rejectDuplicateMapKeys:!0,tags:[]};to.tags[42]=k.parse;var Qu="dag-json",ro=297,Is=r=>Xn(r,Gu),Ts=r=>{let e=ju(r),t=Object.assign(to,{tokenizer:new eo(e,to)});return Zn(e,t)},Ju=r=>Yu.decode(Is(r));var Yu=new TextDecoder,Xu=r=>Ts(Zu.encode(r)),Zu=new TextEncoder;var uo={};T(uo,{code:()=>co,createLink:()=>zs,createNode:()=>Os,decode:()=>hl,encode:()=>fl,name:()=>ll,prepare:()=>so,validate:()=>ao});var el=new TextDecoder;function oo(r,e){let t=0;for(let n=0;;n+=7){if(n>=64)throw new Error("protobuf: varint overflow");if(e>=r.length)throw new Error("protobuf: unexpected end of data");let o=r[e++];if(t+=n<28?(o&127)<<n:(o&127)*2**n,o<128)break}return[t,e]}function Lr(r,e){let t;[t,e]=oo(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 Ls(r,e){let t;return[t,e]=oo(r,e),[t&7,t>>3,e]}function tl(r){let e={},t=r.length,n=0;for(;n<t;){let o,i;if([o,i,n]=Ls(r,n),i===1){if(e.Hash)throw new Error("protobuf: (PBLink) duplicate Hash section");if(o!==2)throw new Error(`protobuf: (PBLink) wrong wireType (${o}) for Hash`);if(e.Name!==void 0)throw new Error("protobuf: (PBLink) invalid order, found Name before Hash");if(e.Tsize!==void 0)throw new Error("protobuf: (PBLink) invalid order, found Tsize before Hash");[e.Hash,n]=Lr(r,n)}else if(i===2){if(e.Name!==void 0)throw new Error("protobuf: (PBLink) duplicate Name section");if(o!==2)throw new Error(`protobuf: (PBLink) wrong wireType (${o}) for Name`);if(e.Tsize!==void 0)throw new Error("protobuf: (PBLink) invalid order, found Tsize before Name");let s;[s,n]=Lr(r,n),e.Name=el.decode(s)}else if(i===3){if(e.Tsize!==void 0)throw new Error("protobuf: (PBLink) duplicate Tsize section");if(o!==0)throw new Error(`protobuf: (PBLink) wrong wireType (${o}) for Tsize`);[e.Tsize,n]=oo(r,n)}else throw new Error(`protobuf: (PBLink) invalid fieldNumber, expected 1, 2 or 3, got ${i}`)}if(n>t)throw new Error("protobuf: (PBLink) unexpected end of data");return e}function Ps(r){let e=r.length,t=0,n,o=!1,i;for(;t<e;){let a,u;if([a,u,t]=Ls(r,t),a!==2)throw new Error(`protobuf: (PBNode) invalid wireType, expected 2, got ${a}`);if(u===1){if(i)throw new Error("protobuf: (PBNode) duplicate Data section");[i,t]=Lr(r,t),n&&(o=!0)}else if(u===2){if(o)throw new Error("protobuf: (PBNode) duplicate Links section");n||(n=[]);let d;[d,t]=Lr(r,t),n.push(tl(d))}else throw new Error(`protobuf: (PBNode) invalid fieldNumber, expected 1 or 2, got ${u}`)}if(t>e)throw new Error("protobuf: (PBNode) unexpected end of data");let s={};return i&&(s.Data=i),s.Links=n||[],s}var Rs=new TextEncoder,Ns=2**32,rl=2**31;function nl(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=ht(e,t,r.Tsize)-1,e[t]=24}if(typeof r.Name=="string"){let n=Rs.encode(r.Name);t-=n.length,e.set(n,t),t=ht(e,t,n.length)-1,e[t]=18}return r.Hash&&(t-=r.Hash.length,e.set(r.Hash,t),t=ht(e,t,r.Hash.length)-1,e[t]=10),e.length-t}function Ds(r){let e=il(r),t=new Uint8Array(e),n=e;if(r.Data&&(n-=r.Data.length,t.set(r.Data,n),n=ht(t,n,r.Data.length)-1,t[n]=10),r.Links)for(let o=r.Links.length-1;o>=0;o--){let i=nl(r.Links[o],t.subarray(0,n));n-=i,n=ht(t,n,i)-1,t[n]=18}return t}function ol(r){let e=0;if(r.Hash){let t=r.Hash.length;e+=1+t+Ve(t)}if(typeof r.Name=="string"){let t=Rs.encode(r.Name).length;e+=1+t+Ve(t)}return typeof r.Tsize=="number"&&(e+=1+Ve(r.Tsize)),e}function il(r){let e=0;if(r.Data){let t=r.Data.length;e+=1+t+Ve(t)}if(r.Links)for(let t of r.Links){let n=ol(t);e+=1+n+Ve(n)}return e}function ht(r,e,t){e-=Ve(t);let n=e;for(;t>=rl;)r[e++]=t&127|128,t/=128;for(;t>=128;)r[e++]=t&127|128,t>>>=7;return r[e]=t,n}function Ve(r){return r%2===0&&r++,Math.floor((sl(r)+6)/7)}function sl(r){let e=0;return r>=Ns&&(r=Math.floor(r/Ns),e=32),r>=65536&&(r>>>=16,e+=16),r>=256&&(r>>>=8,e+=8),e+al[r]}var al=[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 cl=["Data","Links"],ul=["Hash","Name","Tsize"],io=new TextEncoder;function Us(r,e){if(r===e)return 0;let t=r.Name?io.encode(r.Name):[],n=e.Name?io.encode(e.Name):[],o=t.length,i=n.length;for(let s=0,a=Math.min(o,i);s<a;++s)if(t[s]!==n[s]){o=t[s],i=n[s];break}return o<i?-1:i<o?1:0}function Bs(r,e){return!Object.keys(r).some(t=>!e.includes(t))}function Fs(r){if(typeof r.asCID=="object"){let t=k.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=k.asCID(r.Hash);try{t||(typeof r.Hash=="string"?t=k.parse(r.Hash):r.Hash instanceof Uint8Array&&(t=k.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 so(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=io.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(Fs),e.Links.sort(Us);else throw new TypeError("Invalid DAG-PB form");else e.Links=[];return e}function ao(r){if(!r||typeof r!="object"||Array.isArray(r)||r instanceof Uint8Array||r["/"]&&r["/"]===r.bytes)throw new TypeError("Invalid DAG-PB form");if(!Bs(r,cl))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(!Bs(t,ul))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&&Us(t,r.Links[e-1])===-1)throw new TypeError("Invalid DAG-PB form (links must be sorted by Name bytes)")}}function Os(r,e=[]){return so({Data:r,Links:e})}function zs(r,e,t){return Fs({Hash:t,Name:r,Tsize:e})}function Ms(r){return r instanceof ArrayBuffer?new Uint8Array(r,0,r.byteLength):r}var ll="dag-pb",co=112;function fl(r){ao(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),Ds(e)}function hl(r){let e=Ms(r),t=Ps(e),n={};return t.Data&&(n.Data=t.Data),t.Links&&(n.Links=t.Links.map(o=>{let i={};try{i.Hash=k.decode(o.Hash)}catch{}if(!i.Hash)throw new Error("Invalid Hash field found in link, expected CID");return o.Name!==void 0&&(i.Name=o.Name),o.Tsize!==void 0&&(i.Tsize=o.Tsize),i})),n}function Ke(r){return r?.then!=null}function $s(r=[],e){let t={[co]:uo,[un]:Et,[Qn]:Jn,[ro]:no,[cn]:xt};return r.forEach(n=>{t[n.code]=n}),async n=>{let o=t[n];if(o==null&&e!=null){let i=e(n);Ke(i)?o=await i:o=i,t[o.code]=o}if(o!=null)return o;throw new ar(`Could not load codec for ${n}`)}}function qs(r=[],e){let t={[kt.code]:kt,[At.code]:At,[_t.code]:_t};return r.forEach(n=>{t[n.code]=n}),async n=>{let o=t[n];if(o==null&&e!=null){let i=e(n);Ke(i)?o=await i:o=i,t[o.code]=o}if(o!=null)return o;throw new sr(`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 Pr=class r extends Error{static name="NotFoundError";static code="ERR_NOT_FOUND";name=r.name;code=r.code;constructor(e="Not Found"){super(e)}};var Nr=class{has(e,t){return Promise.reject(new Error(".has is not implemented"))}put(e,t,n){return Promise.reject(new Error(".put is not implemented"))}async*putMany(e,t){for await(let{cid:n,bytes:o}of e)await this.put(n,o,t),yield n}get(e,t){throw new Error(".get is not implemented")}async*getMany(e,t){for await(let n of e)yield{cid:n,bytes:this.get(n,t)}}delete(e,t){return Promise.reject(new Error(".delete is not implemented"))}async*deleteMany(e,t){for await(let n of e)await this.delete(n,t),yield n}async*getAll(e){throw new Error(".getAll is not implemented")}};var Rr=0,Dr=class extends Nr{child;constructor(e){super(),this.child=e}put(e,t,n){return e.multihash.code===Rr||this.child==null?(n?.signal?.throwIfAborted(),e):this.child.put(e,t,n)}*get(e,t){if(e.multihash.code===Rr){t?.signal?.throwIfAborted(),yield e.multihash.digest;return}if(this.child==null)throw t?.signal?.throwIfAborted(),new Pr;yield*this.child.get(e,t)}has(e,t){return e.multihash.code===Rr?(t?.signal?.throwIfAborted(),!0):this.child==null?(t?.signal?.throwIfAborted(),!1):this.child.has(e,t)}delete(e,t){if(e.code===Rr){t?.signal?.throwIfAborted();return}if(this.child!=null)return this.child.delete(e,t)}*getAll(e){this.child!=null&&(yield*this.child.getAll(e)),e?.signal?.throwIfAborted()}};function dl(r){let[e,t]=r[Symbol.asyncIterator]!=null?[r[Symbol.asyncIterator](),Symbol.asyncIterator]:[r[Symbol.iterator](),Symbol.iterator],n=[];return{peek:()=>e.next(),push:o=>{n.push(o)},next:()=>n.length>0?{done:!1,value:n.shift()}:e.next(),[t](){return this}}}var Br=dl;function pl(r){return r[Symbol.asyncIterator]!=null}function ml(r,e){let t=0;if(pl(r))return(async function*(){for await(let u of r)await e(u,t++)&&(yield u)})();let n=Br(r),{value:o,done:i}=n.next();if(i===!0)return(function*(){})();let s=e(o,t++);if(typeof s.then=="function")return(async function*(){await s&&(yield o);for(let u of n)await e(u,t++)&&(yield u)})();let a=e;return(function*(){s===!0&&(yield o);for(let u of n)a(u,t++)&&(yield u)})()}var js=ml;function gl(r){return r[Symbol.asyncIterator]!=null}function Vs(r){return r?.then!=null}function yl(r,e){let t=0;if(gl(r))return(async function*(){for await(let u of r){let d=e(u,t++);Vs(d)&&await d,yield u}})();let n=Br(r),{value:o,done:i}=n.next();if(i===!0)return(function*(){})();if(typeof e(o,t++)?.then=="function")return(async function*(){yield o;for(let u of n){let d=e(u,t++);Vs(d)&&await d,yield u}})();let a=e;return(function*(){yield o;for(let u of n)a(u,t++),yield u})()}var lo=yl;var Ur=class{child;getHasher;log;logger;components;constructor(e){this.log=e.logger.forComponent("helia:networked-storage"),this.logger=e.logger,this.components=e,this.child=new Dr(e.blockstore),this.getHasher=e.getHasher}async put(e,t,n={}){return await this.child.has(e,n)?(n.onProgress?.(new v("blocks:put:duplicate",e)),e):(n.onProgress?.(new v("blocks:put:providers:notify",e)),await Promise.all(this.components.blockBrokers.map(async o=>o.announce?.(e,n))),n.onProgress?.(new v("blocks:put:blockstore:put",e)),this.child.put(e,t,n))}async*putMany(e,t={}){let n=js(e,async({cid:i})=>{let s=await this.child.has(i,t);return s&&t.onProgress?.(new v("blocks:put-many:duplicate",i)),!s}),o=lo(n,async({cid:i})=>{t.onProgress?.(new v("blocks:put-many:providers:notify",i)),await Promise.all(this.components.blockBrokers.map(async s=>s.announce?.(i,t)))});t.onProgress?.(new v("blocks:put-many:blockstore:put-many")),yield*this.child.putMany(o,t)}async*get(e,t={}){if(t.offline!==!0&&!await this.child.has(e,t)){let n=await this.getHasher(e.multihash.code);t.onProgress?.(new v("blocks:get:providers:get",e));let o=await Ks(e,this.components.blockBrokers,n,{...t,log:this.log});t.onProgress?.(new v("blocks:get:blockstore:put",e)),await this.child.put(e,o,t),t.onProgress?.(new v("blocks:get:providers:notify",e)),await Promise.all(this.components.blockBrokers.map(async i=>i.announce?.(e,t))),yield o;return}t.onProgress?.(new v("blocks:get:blockstore:get",e)),yield*this.child.get(e,t)}async*getMany(e,t={}){t.onProgress?.(new v("blocks:get-many:blockstore:get-many")),yield*this.child.getMany(lo(e,async n=>{if(t.offline!==!0&&!await this.child.has(n,t)){let o=await this.getHasher(n.multihash.code);t.onProgress?.(new v("blocks:get-many:providers:get",n));let i=await Ks(n,this.components.blockBrokers,o,{...t,log:this.log});t.onProgress?.(new v("blocks:get-many:blockstore:put",n)),await this.child.put(n,i,t),t.onProgress?.(new v("blocks:get-many:providers:notify",n)),await Promise.all(this.components.blockBrokers.map(async s=>s.announce?.(n,t)))}}))}async delete(e,t={}){t.onProgress?.(new v("blocks:delete:blockstore:delete",e)),await this.child.delete(e,t)}async*deleteMany(e,t={}){t.onProgress?.(new v("blocks:delete-many:blockstore:delete-many")),yield*this.child.deleteMany((async function*(){for await(let n of e)yield n})(),t)}async has(e,t={}){return this.child.has(e,t)}async*getAll(e={}){e.onProgress?.(new v("blocks:get-all:blockstore:get-many")),yield*this.child.getAll(e)}},Fr=class extends Ur{started;constructor(e){super(e),this.started=!1}isStarted(){return this.started}async start(){await he(this.child,...this.components.blockBrokers),this.started=!0}async stop(){await de(this.child,...this.components.blockBrokers),this.started=!1}unwrap(){return this.child}createSession(e,t){let n=this.components.blockBrokers.map(o=>o.createSession==null?o:o.createSession(t));return new fo({blockstore:this.child,blockBrokers:n,getHasher:this.getHasher,logger:this.logger},{root:e})}},fo=class extends Ur{closeController;constructor(e,t){super(e),this.closeController=new AbortController,this.closeController.signal,this.log=e.logger.forComponent(`helia:session-storage:${t.root}`)}close(){this.closeController.abort()}async put(e,t,n={}){let o=oe([this.closeController.signal,n.signal]);try{return await super.put(e,t,{...n,signal:o})}finally{o.clear()}}async*putMany(e,t={}){let n=oe([this.closeController.signal,t.signal]);try{yield*super.putMany(e,{...t,signal:n})}finally{n.clear()}}async*get(e,t={}){let n=oe([this.closeController.signal,t.signal]);try{yield*super.get(e,{...t,signal:n})}finally{n.clear()}}async*getMany(e,t={}){let n=oe([this.closeController.signal,t.signal]);try{yield*super.getMany(e,{...t,signal:n})}finally{n.clear()}}async delete(e,t={}){let n=oe([this.closeController.signal,t.signal]);try{await super.delete(e,{...t,signal:n})}finally{n.clear()}}async*deleteMany(e,t={}){let n=oe([this.closeController.signal,t.signal]);try{yield*super.deleteMany(e,{...t,signal:n})}finally{n.clear()}}async has(e,t={}){let n=oe([this.closeController.signal,t.signal]);try{return await super.has(e,{...t,signal:n})}finally{n.clear()}}async*getAll(e={}){let t=oe([this.closeController.signal,e.signal]);try{yield*super.getAll({...e,signal:t})}finally{t.clear()}}};function bl(r){return typeof r.retrieve=="function"}var xl=(r,e)=>{if(e==null)throw new Te(`No hasher configured for multihash code 0x${r.multihash.code.toString(16)}, please configure one. You can look up which hash this is at https://github.com/multiformats/multicodec/blob/master/table.csv`);return async t=>{let n,o=e.digest(t);if(Ke(o)?n=await o:n=o,!xe(n.digest,r.multihash.digest))throw new mt("Hash of downloaded block did not match multihash from passed CID")}};async function Ks(r,e,t,n){let o=xl(r,t),i=new AbortController,s=oe([i.signal,n.signal]);i.signal;let a=[];for(let u of e)bl(u)&&a.push(u);try{return await Promise.any(a.map(async u=>{try{let d=!1,l=await u.retrieve(r,{...n,signal:s,validateFn:async f=>{await o(f),d=!0}});return d||await o(l),l}catch(d){throw n.log.error("could not retrieve verified block for %c",r,d),d}}))}finally{i.abort(),s.clear()}}var Or=class extends H{initialPeerSearchComplete;requests;name;log;logger;minProviders;maxProviders;providers;evictionFilter;initialProviders;constructor(e,t){super(),this.name=t.name,this.logger=e.logger,this.log=e.logger.forComponent(this.name),this.requests=new Map,this.minProviders=t.minProviders??1,this.maxProviders=t.maxProviders??5,this.providers=[],this.evictionFilter=An(this.maxProviders),this.initialProviders=t.providers??[]}async retrieve(e,t={}){let n=ge.encode(e.multihash.bytes),o=this.requests.get(n);if(o!=null)return this.log("join existing request for %c",e),o;let i=U();if(this.requests.set(n,i.promise),this.providers.length===0){let l=!1;this.initialPeerSearchComplete==null&&(l=!0,this.log=this.logger.forComponent(`${this.name}:${e}`),this.initialPeerSearchComplete=this.findProviders(e,this.minProviders,t)),await this.initialPeerSearchComplete,l&&this.log("found initial session peers for %c",e)}let s=!1,a=new ae({concurrency:this.maxProviders});a.addEventListener("failure",l=>{this.log.error("error querying provider %o, evicting from session",l.detail.job.options.provider,l.detail.error),this.evict(l.detail.job.options.provider)}),a.addEventListener("success",l=>{s=!0,i.resolve(l.detail.result)}),a.addEventListener("idle",()=>{if(s){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 l=0;l<this.minProviders&&this.providers.length!==0;l++){let f=this.providers[Math.floor(Math.random()*this.providers.length)];this.evict(f)}await this.findProviders(e,this.minProviders,t),this.log("found new providers re-retrieving %c",e),this.requests.delete(n),i.resolve(await this.retrieve(e,t))}).catch(l=>{this.log.error("could not find new providers for %c",e,l),i.reject(l)})});let u=l=>{a.add(async()=>this.queryProvider(e,l.detail,t),{provider:l.detail}).catch(f=>{t.signal?.aborted!==!0&&this.log.error("error retrieving session block for %c",e,f)})};this.addEventListener("provider",u),Promise.all([...this.providers].map(async l=>a.add(async()=>this.queryProvider(e,l,t),{provider:l}))).catch(l=>{t.signal?.aborted!==!0&&this.log.error("error retrieving session block for %c",e,l)});let d=()=>{i.reject(new J(t.signal?.reason??"Session aborted")),a.abort()};t.signal?.addEventListener("abort",d);try{return await i.promise}finally{this.removeEventListener("provider",u),t.signal?.removeEventListener("abort",d),a.clear(),this.requests.delete(n)}}evict(e){this.evictionFilter.add(this.toEvictionKey(e));let t=this.providers.findIndex(n=>this.equals(n,e));t!==-1&&this.providers.splice(t,1)}isEvicted(e){return this.evictionFilter.has(this.toEvictionKey(e))}hasProvider(e){return!!(this.providers.find(t=>this.equals(t,e))!=null||this.isEvicted(e))}async findProviders(e,t,n){let o=U(),i=0;return Promise.resolve().then(async()=>{if(this.log("finding %d-%d new provider(s) for %c",t,this.maxProviders,e),this.initialProviders.length>0)for(;i<t&&this.initialProviders.length>0;){let s=this.initialProviders.pop();if(s==null)break;let a=await this.convertToProvider(s,n);if(n.signal?.aborted===!0)break;if(a!=null&&!this.hasProvider(a)&&(this.log("found %d/%d new providers",i,this.maxProviders),this.providers.push(a),this.safeDispatchEvent("provider",{detail:a}),i++,i===t&&(this.log("session is ready"),o.resolve()),this.providers.length===this.maxProviders)){this.log("found max session peers",i);break}}if(i<this.maxProviders)for await(let s of this.findNewProviders(e,n)){if(i===this.maxProviders||n.signal?.aborted===!0)break;if(!this.hasProvider(s)&&(this.log("found %d/%d new providers",i,this.maxProviders),this.providers.push(s),this.safeDispatchEvent("provider",{detail:s}),i++,i===t&&(this.log("session is ready"),o.resolve()),this.providers.length===this.maxProviders)){this.log("found max session peers",i);break}}if(this.log("found %d/%d new session peers",i,this.maxProviders),i<t)throw new ir(`Found ${i} of ${t} ${this.name} providers for ${e}`)}).catch(s=>{this.log.error("error searching routing for potential session peers for %c",e,s.errors??s),o.reject(s)}),o.promise}};var ho=class{libp2p;blockstore;datastore;events;pins;logger;routing;getCodec;getHasher;dns;metrics;log;constructor(e){this.logger=e.logger??Ao(),this.log=this.logger.forComponent("helia"),this.getHasher=qs(e.hashers,e.loadHasher),this.getCodec=$s(e.codecs,e.loadCodec),this.dns=e.dns??Zo(),this.metrics=e.metrics,this.libp2p=e.libp2p,this.events=new H;let t={blockstore:e.blockstore,datastore:e.datastore,logger:this.logger,libp2p:this.libp2p,blockBrokers:[],getHasher:this.getHasher,getCodec:this.getCodec,dns:this.dns,metrics:this.metrics,...e.components??{}};this.routing=t.routing=new cr(t,{routers:(e.routers??[]).flatMap(o=>{let i=[o];return o[zr]!=null&&i.push(o[zr]),o[Mr]!=null&&i.push(o[Mr]),i}),providerLookupConcurrency:e.providerLookupConcurrency});let n=new Fr(t);this.pins=new or(e.datastore,n,this.getCodec),this.blockstore=new Sr(n,this.pins,{holdGcLock:e.holdGcLock??!0}),this.datastore=e.datastore,t.blockBrokers=e.blockBrokers.map(o=>o(t))}async start(){await As(this.datastore),await he(this.blockstore,this.datastore,this.routing,this.libp2p),this.events.dispatchEvent(new CustomEvent("start",{detail:this}))}async stop(){await de(this.blockstore,this.datastore,this.routing,this.libp2p),this.events.dispatchEvent(new CustomEvent("stop",{detail:this}))}async gc(e={}){let t=await this.blockstore.lock.writeLock();try{let n=this,o=this.blockstore.unwrap();this.log("gc start"),await ei(o.deleteMany((async function*(){for await(let{cid:i}of o.getAll())try{if(await n.pins.isPinned(i,e))continue;yield i,e.onProgress?.(new v("helia:gc:deleted",i))}catch(s){n.log.error("Error during gc",s),e.onProgress?.(new v("helia:gc:error",s))}})()))}finally{t()}this.log("gc finished")}};return Ys(_l);})();
4
4
  return HeliaUtils}));
5
5
  //# sourceMappingURL=index.min.js.map