@helia/utils 2.3.5-33e46813 → 2.3.5-50a7859b

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,4 +1,14 @@
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 ea=Object.create;var xt=Object.defineProperty;var ta=Object.getOwnPropertyDescriptor;var ra=Object.getOwnPropertyNames;var na=Object.getPrototypeOf,ia=Object.prototype.hasOwnProperty;var Ai=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),S=(r,e)=>{for(var t in e)xt(r,t,{get:e[t],enumerable:!0})},Ii=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of ra(e))!ia.call(r,i)&&i!==t&&xt(r,i,{get:()=>e[i],enumerable:!(n=ta(e,i))||n.enumerable});return r};var Si=(r,e,t)=>(t=r!=null?ea(na(r)):{},Ii(e||!r||!r.__esModule?xt(t,"default",{value:r,enumerable:!0}):t,r)),oa=r=>Ii(xt({},"__esModule",{value:!0}),r);var Pi=Ai((Ul,Qr)=>{"use strict";var sa=Object.prototype.hasOwnProperty,P="~";function Ge(){}Object.create&&(Ge.prototype=Object.create(null),new Ge().__proto__||(P=!1));function aa(r,e,t){this.fn=r,this.context=e,this.once=t||!1}function Ni(r,e,t,n,i){if(typeof t!="function")throw new TypeError("The listener must be a function");var o=new aa(t,n||r,i),s=P?P+e:e;return r._events[s]?r._events[s].fn?r._events[s]=[r._events[s],o]:r._events[s].push(o):(r._events[s]=o,r._eventsCount++),r}function kt(r,e){--r._eventsCount===0?r._events=new Ge:delete r._events[e]}function C(){this._events=new Ge,this._eventsCount=0}C.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(P?n.slice(1):n);return Object.getOwnPropertySymbols?e.concat(Object.getOwnPropertySymbols(t)):e};C.prototype.listeners=function(e){var t=P?P+e:e,n=this._events[t];if(!n)return[];if(n.fn)return[n.fn];for(var i=0,o=n.length,s=new Array(o);i<o;i++)s[i]=n[i].fn;return s};C.prototype.listenerCount=function(e){var t=P?P+e:e,n=this._events[t];return n?n.fn?1:n.length:0};C.prototype.emit=function(e,t,n,i,o,s){var c=P?P+e:e;if(!this._events[c])return!1;var u=this._events[c],l=arguments.length,p,h;if(u.fn){switch(u.once&&this.removeListener(e,u.fn,void 0,!0),l){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,i),!0;case 5:return u.fn.call(u.context,t,n,i,o),!0;case 6:return u.fn.call(u.context,t,n,i,o,s),!0}for(h=1,p=new Array(l-1);h<l;h++)p[h-1]=arguments[h];u.fn.apply(u.context,p)}else{var g=u.length,y;for(h=0;h<g;h++)switch(u[h].once&&this.removeListener(e,u[h].fn,void 0,!0),l){case 1:u[h].fn.call(u[h].context);break;case 2:u[h].fn.call(u[h].context,t);break;case 3:u[h].fn.call(u[h].context,t,n);break;case 4:u[h].fn.call(u[h].context,t,n,i);break;default:if(!p)for(y=1,p=new Array(l-1);y<l;y++)p[y-1]=arguments[y];u[h].fn.apply(u[h].context,p)}}return!0};C.prototype.on=function(e,t,n){return Ni(this,e,t,n,!1)};C.prototype.once=function(e,t,n){return Ni(this,e,t,n,!0)};C.prototype.removeListener=function(e,t,n,i){var o=P?P+e:e;if(!this._events[o])return this;if(!t)return kt(this,o),this;var s=this._events[o];if(s.fn)s.fn===t&&(!i||s.once)&&(!n||s.context===n)&&kt(this,o);else{for(var c=0,u=[],l=s.length;c<l;c++)(s[c].fn!==t||i&&!s[c].once||n&&s[c].context!==n)&&u.push(s[c]);u.length?this._events[o]=u.length===1?u[0]:u:kt(this,o)}return this};C.prototype.removeAllListeners=function(e){var t;return e?(t=P?P+e:e,this._events[t]&&kt(this,t)):(this._events=new Ge,this._eventsCount=0),this};C.prototype.off=C.prototype.removeListener;C.prototype.addListener=C.prototype.on;C.prefixed=P;C.EventEmitter=C;typeof Qr<"u"&&(Qr.exports=C)});var io=Ai((Yf,no)=>{no.exports=function(r){if(!r)throw Error("hashlru must have a max value, of type number, greater than 0");var e=0,t=Object.create(null),n=Object.create(null);function i(o,s){t[o]=s,e++,e>=r&&(e=0,n=t,t=Object.create(null))}return{has:function(o){return t[o]!==void 0||n[o]!==void 0},remove:function(o){t[o]!==void 0&&(t[o]=void 0),n[o]!==void 0&&(n[o]=void 0)},get:function(o){var s=t[o];if(s!==void 0)return s;if((s=n[o])!==void 0)return i(o,s),s},set:function(o,s){t[o]!==void 0?t[o]=s:i(o,s)},clear:function(){t=Object.create(null),n=Object.create(null)}}}});var Sl={};S(Sl,{AbstractSession:()=>Gr,Helia:()=>ki,breadthFirstWalker:()=>Xs,depthFirstWalker:()=>Ys,naturalOrderWalker:()=>Zs});var Ti=Symbol.for("@libp2p/content-routing");var W=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 Et=class extends Error{static name="NotFoundError";constructor(e="Not found"){super(e),this.name="NotFoundError"}};var vt=class extends Error{static name="InvalidMultihashError";constructor(e="Invalid Multihash"){super(e),this.name="InvalidMultihashError"}};var Li=Symbol.for("@libp2p/peer-routing");function Ci(r){return r!=null&&typeof r.start=="function"&&typeof r.stop=="function"}async function de(...r){let e=[];for(let t of r)Ci(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 pe(...r){let e=[];for(let t of r)Ci(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 j=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 i=this.#e.get(e);i==null&&(i=[],this.#e.set(e,i)),i.push({callback:t,once:(n!==!0&&n!==!1&&n?.once)??!1})}removeEventListener(e,t,n){super.removeEventListener(e.toString(),t??null,n);let i=this.#e.get(e);i!=null&&(i=i.filter(({callback:o})=>o!==t),this.#e.set(e,i))}dispatchEvent(e){let t=super.dispatchEvent(e),n=this.#e.get(e.type);return n==null||(n=n.filter(({once:i})=>!i),this.#e.set(e.type,n)),t}safeDispatchEvent(e,t={}){return this.dispatchEvent(new CustomEvent(e,t))}};var E=class extends Event{type;detail;constructor(e,t){super(e),this.type=e,this.detail=t}};var _t=class extends AggregateError{static name="DNSQueryFailedError";name="DNSQueryFailedError"};var Jr=Si(Pi(),1);var Yr=class r extends Error{name="TimeoutError";constructor(e,t){super(e,t),Error.captureStackTrace?.(this,r)}},Di=r=>r.reason??new DOMException("This operation was aborted.","AbortError");function Qe(r,e){let{milliseconds:t,fallback:n,message:i,customTimers:o={setTimeout,clearTimeout},signal:s}=e,c,u,p=new Promise((h,g)=>{if(typeof t!="number"||Math.sign(t)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${t}\``);if(s?.aborted){g(Di(s));return}if(s&&(u=()=>{g(Di(s))},s.addEventListener("abort",u,{once:!0})),r.then(h,g),t===Number.POSITIVE_INFINITY)return;let y=new Yr;c=o.setTimeout.call(void 0,()=>{if(n){try{h(n())}catch(w){g(w)}return}typeof r.cancel=="function"&&r.cancel(),i===!1?h():i instanceof Error?g(i):(y.message=i??`Promise timed out after ${t} milliseconds`,g(y))},t)}).finally(()=>{p.clear(),u&&s&&s.removeEventListener("abort",u)});return p.clear=()=>{o.clearTimeout.call(void 0,c),c=void 0},p}function Xr(r,e,t){let n=0,i=r.length;for(;i>0;){let o=Math.trunc(i/2),s=n+o;t(r[s],e)<=0?(n=++s,i-=o+1):i=o}return n}var Je=class{#e=[];enqueue(e,t){let{priority:n=0,id:i}=t??{},o={priority:n,id:i,run:e};if(this.size===0||this.#e[this.size-1].priority>=n){this.#e.push(o);return}let s=Xr(this.#e,o,(c,u)=>u.priority-c.priority);this.#e.splice(s,0,o)}setPriority(e,t){let n=this.#e.findIndex(o=>o.id===e);if(n===-1)throw new ReferenceError(`No promise function with the id "${e}" exists in the queue.`);let[i]=this.#e.splice(n,1);this.enqueue(i.run,{priority:t,id:e})}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 Ye=class extends Jr.default{#e;#i;#a=0;#d;#m=!1;#w=!1;#c;#I=0;#b=0;#u;#l;#s;#o=[];#n=0;#t;#S;#r=0;#g;#f;#P=1n;#y=new Map;timeout;constructor(e){if(super(),e={carryoverIntervalCount:!1,intervalCap:Number.POSITIVE_INFINITY,interval:0,concurrency:Number.POSITIVE_INFINITY,autoStart:!0,queueClass:Je,strict:!1,...e},!(typeof e.intervalCap=="number"&&e.intervalCap>=1))throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${e.intervalCap?.toString()??""}\` (${typeof e.intervalCap})`);if(e.interval===void 0||!(Number.isFinite(e.interval)&&e.interval>=0))throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${e.interval?.toString()??""}\` (${typeof e.interval})`);if(e.strict&&e.interval===0)throw new TypeError("The `strict` option requires a non-zero `interval`");if(e.strict&&e.intervalCap===Number.POSITIVE_INFINITY)throw new TypeError("The `strict` option requires a finite `intervalCap`");if(this.#e=e.carryoverIntervalCount??e.carryoverConcurrencyCount??!1,this.#i=e.intervalCap===Number.POSITIVE_INFINITY||e.interval===0,this.#d=e.intervalCap,this.#c=e.interval,this.#s=e.strict,this.#t=new e.queueClass,this.#S=e.queueClass,this.concurrency=e.concurrency,e.timeout!==void 0&&!(Number.isFinite(e.timeout)&&e.timeout>0))throw new TypeError(`Expected \`timeout\` to be a positive finite number, got \`${e.timeout}\` (${typeof e.timeout})`);this.timeout=e.timeout,this.#f=e.autoStart===!1,this.#$()}#x(e){for(;this.#n<this.#o.length;){let n=this.#o[this.#n];if(n!==void 0&&e-n>=this.#c)this.#n++;else break}(this.#n>100&&this.#n>this.#o.length/2||this.#n===this.#o.length)&&(this.#o=this.#o.slice(this.#n),this.#n=0)}#D(e){this.#s?this.#o.push(e):this.#a++}#R(){this.#s?this.#o.length>this.#n&&this.#o.pop():this.#a>0&&this.#a--}#E(){return this.#o.length-this.#n}get#B(){return this.#i?!0:this.#s?this.#E()<this.#d:this.#a<this.#d}get#U(){return this.#r<this.#g}#O(){this.#r--,this.#r===0&&this.emit("pendingZero"),this.#k(),this.emit("next")}#M(){this.#l=void 0,this.#C(),this.#L()}#z(e){if(this.#s){if(this.#x(e),this.#E()>=this.#d){let n=this.#o[this.#n],i=this.#c-(e-n);return this.#v(i),!0}return!1}if(this.#u===void 0){let t=this.#I-e;if(t<0){if(this.#b>0){let n=e-this.#b;if(n<this.#c)return this.#v(this.#c-n),!0}this.#a=this.#e?this.#r:0}else return this.#v(t),!0}return!1}#v(e){this.#l===void 0&&(this.#l=setTimeout(()=>{this.#M()},e))}#_(){this.#u&&(clearInterval(this.#u),this.#u=void 0)}#T(){this.#l&&(clearTimeout(this.#l),this.#l=void 0)}#k(){if(this.#t.size===0){if(this.#_(),this.emit("empty"),this.#r===0){if(this.#T(),this.#s&&this.#n>0){let t=Date.now();this.#x(t)}this.emit("idle")}return!1}let e=!1;if(!this.#f){let t=Date.now(),n=!this.#z(t);if(this.#B&&this.#U){let i=this.#t.dequeue();this.#i||(this.#D(t),this.#p()),this.emit("active"),i(),n&&this.#L(),e=!0}}return e}#L(){this.#i||this.#u!==void 0||this.#s||(this.#u=setInterval(()=>{this.#C()},this.#c),this.#I=Date.now()+this.#c)}#C(){this.#s||(this.#a===0&&this.#r===0&&this.#u&&this.#_(),this.#a=this.#e?this.#r:0),this.#A(),this.#p()}#A(){for(;this.#k(););}get concurrency(){return this.#g}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.#g=e,this.#A()}setPriority(e,t){if(typeof t!="number"||!Number.isFinite(t))throw new TypeError(`Expected \`priority\` to be a finite number, got \`${t}\` (${typeof t})`);this.#t.setPriority(e,t)}async add(e,t={}){return t={timeout:this.timeout,...t,id:t.id??(this.#P++).toString()},new Promise((n,i)=>{let o=Symbol(`task-${t.id}`);this.#t.enqueue(async()=>{this.#r++,this.#y.set(o,{id:t.id,priority:t.priority??0,startTime:Date.now(),timeout:t.timeout});let s;try{try{t.signal?.throwIfAborted()}catch(l){throw this.#q(),this.#y.delete(o),l}this.#b=Date.now();let c=e({signal:t.signal});if(t.timeout&&(c=Qe(Promise.resolve(c),{milliseconds:t.timeout,message:`Task timed out after ${t.timeout}ms (queue has ${this.#r} running, ${this.#t.size} waiting)`})),t.signal){let{signal:l}=t;c=Promise.race([c,new Promise((p,h)=>{s=()=>{h(l.reason)},l.addEventListener("abort",s,{once:!0})})])}let u=await c;n(u),this.emit("completed",u)}catch(c){i(c),this.emit("error",c)}finally{s&&t.signal?.removeEventListener("abort",s),this.#y.delete(o),queueMicrotask(()=>{this.#O()})}},t),this.emit("add"),this.#k()})}async addAll(e,t){return Promise.all(e.map(async n=>this.add(n,t)))}start(){return this.#f?(this.#f=!1,this.#A(),this):this}pause(){this.#f=!0}clear(){this.#t=new this.#S,this.#_(),this.#N(),this.emit("empty"),this.#r===0&&(this.#T(),this.emit("idle")),this.emit("next")}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.#r===0&&this.#t.size===0||await this.#h("idle")}async onPendingZero(){this.#r!==0&&await this.#h("pendingZero")}async onRateLimit(){this.isRateLimited||await this.#h("rateLimit")}async onRateLimitCleared(){this.isRateLimited&&await this.#h("rateLimitCleared")}onError(){return new Promise((e,t)=>{let n=i=>{this.off("error",n),t(i)};this.on("error",n)})}async#h(e,t){return new Promise(n=>{let i=()=>{t&&!t()||(this.off(e,i),n())};this.on(e,i)})}get size(){return this.#t.size}sizeBy(e){return this.#t.filter(e).length}get pending(){return this.#r}get isPaused(){return this.#f}#$(){this.#i||(this.on("add",()=>{this.#t.size>0&&this.#p()}),this.on("next",()=>{this.#p()}))}#p(){this.#i||this.#w||(this.#w=!0,queueMicrotask(()=>{this.#w=!1,this.#N()}))}#q(){this.#i||(this.#R(),this.#p())}#N(){let e=this.#m;if(this.#i||this.#t.size===0){e&&(this.#m=!1,this.emit("rateLimitCleared"));return}let t;if(this.#s){let i=Date.now();this.#x(i),t=this.#E()}else t=this.#a;let n=t>=this.#d;n!==e&&(this.#m=n,this.emit(n?"rateLimit":"rateLimitCleared"))}get isRateLimited(){return this.#m}get isSaturated(){return this.#r===this.#g&&this.#t.size>0||this.isRateLimited&&this.#t.size>0}get runningTasks(){return[...this.#y.values()].map(e=>({...e}))}};function At(r){let e=[G.A];return r==null?e:Array.isArray(r)?r.length===0?e:r:[r]}var on={};S(on,{base10:()=>pa});var Gl=new Uint8Array(0);function Ri(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 Q(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 Bi(r){return new TextEncoder().encode(r)}function Ui(r){return new TextDecoder().decode(r)}function ca(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),n=0;n<t.length;n++)t[n]=255;for(var i=0;i<r.length;i++){var o=r.charAt(i),s=o.charCodeAt(0);if(t[s]!==255)throw new TypeError(o+" is ambiguous");t[s]=i}var c=r.length,u=r.charAt(0),l=Math.log(c)/Math.log(256),p=Math.log(256)/Math.log(c);function h(w){if(w instanceof Uint8Array||(ArrayBuffer.isView(w)?w=new Uint8Array(w.buffer,w.byteOffset,w.byteLength):Array.isArray(w)&&(w=Uint8Array.from(w))),!(w instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(w.length===0)return"";for(var k=0,b=0,I=0,N=w.length;I!==N&&w[I]===0;)I++,k++;for(var L=(N-I)*p+1>>>0,B=new Uint8Array(L);I!==N;){for(var F=w[I],he=0,K=L-1;(F!==0||he<b)&&K!==-1;K--,he++)F+=256*B[K]>>>0,B[K]=F%c>>>0,F=F/c>>>0;if(F!==0)throw new Error("Non-zero carry");b=he,I++}for(var se=L-b;se!==L&&B[se]===0;)se++;for(var bt=u.repeat(k);se<L;++se)bt+=r.charAt(B[se]);return bt}function g(w){if(typeof w!="string")throw new TypeError("Expected String");if(w.length===0)return new Uint8Array;var k=0;if(w[k]!==" "){for(var b=0,I=0;w[k]===u;)b++,k++;for(var N=(w.length-k)*l+1>>>0,L=new Uint8Array(N);w[k];){var B=t[w.charCodeAt(k)];if(B===255)return;for(var F=0,he=N-1;(B!==0||F<I)&&he!==-1;he--,F++)B+=c*L[he]>>>0,L[he]=B%256>>>0,B=B/256>>>0;if(B!==0)throw new Error("Non-zero carry");I=F,k++}if(w[k]!==" "){for(var K=N-I;K!==N&&L[K]===0;)K++;for(var se=new Uint8Array(b+(N-K)),bt=b;K!==N;)se[bt++]=L[K++];return se}}}function y(w){var k=g(w);if(k)return k;throw new Error(`Non-${e} character`)}return{encode:h,decodeUnsafe:g,decode:y}}var ua=ca,la=ua,Oi=la;var en=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")}},tn=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,n){this.name=e,this.prefix=t;let i=t.codePointAt(0);if(i===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=i,this.baseDecode=n}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return Mi(this,e)}},rn=class{decoders;constructor(e){this.decoders=e}or(e){return Mi(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 Mi(r,e){return new rn({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var nn=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,n,i){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=i,this.encoder=new en(e,t,n),this.decoder=new tn(e,t,i)}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 nn(r,e,t,n)}function me({name:r,prefix:e,alphabet:t}){let{encode:n,decode:i}=Oi(t,r);return Le({prefix:e,name:r,encode:n,decode:o=>Q(i(o))})}function fa(r,e,t,n){let i=r.length;for(;r[i-1]==="=";)--i;let o=new Uint8Array(i*t/8|0),s=0,c=0,u=0;for(let l=0;l<i;++l){let p=e[r[l]];if(p===void 0)throw new SyntaxError(`Non-${n} character`);c=c<<t|p,s+=t,s>=8&&(s-=8,o[u++]=255&c>>s)}if(s>=t||(255&c<<8-s)!==0)throw new SyntaxError("Unexpected end of data");return o}function ha(r,e,t){let n=e[e.length-1]==="=",i=(1<<t)-1,o="",s=0,c=0;for(let u=0;u<r.length;++u)for(c=c<<8|r[u],s+=8;s>t;)s-=t,o+=e[i&c>>s];if(s!==0&&(o+=e[i&c<<t-s]),n)for(;(o.length*t&7)!==0;)o+="=";return o}function da(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 i=da(n);return Le({prefix:e,name:r,encode(o){return ha(o,n,t)},decode(o){return fa(o,i,t,r)}})}var pa=me({prefix:"9",name:"base10",alphabet:"0123456789"});var sn={};S(sn,{base16:()=>ma,base16upper:()=>ga});var ma=A({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),ga=A({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var an={};S(an,{base2:()=>ya});var ya=A({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var cn={};S(cn,{base256emoji:()=>va});var zi=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}"),wa=zi.reduce((r,e,t)=>(r[t]=e,r),[]),ba=zi.reduce((r,e,t)=>{let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);return r[n]=t,r},[]);function xa(r){return r.reduce((e,t)=>(e+=wa[t],e),"")}function Ea(r){let e=[];for(let t of r){let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);let i=ba[n];if(i==null)throw new Error(`Non-base256emoji character: ${t}`);e.push(i)}return new Uint8Array(e)}var va=Le({prefix:"\u{1F680}",name:"base256emoji",encode:xa,decode:Ea});var un={};S(un,{base32:()=>Ce,base32hex:()=>Ia,base32hexpad:()=>Ta,base32hexpadupper:()=>La,base32hexupper:()=>Sa,base32pad:()=>ka,base32padupper:()=>Aa,base32upper:()=>_a,base32z:()=>Ca});var Ce=A({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),_a=A({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),ka=A({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Aa=A({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Ia=A({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Sa=A({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Ta=A({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),La=A({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Ca=A({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var ln={};S(ln,{base36:()=>ae,base36upper:()=>Na});var ae=me({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Na=me({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var fn={};S(fn,{base58btc:()=>re,base58flickr:()=>Pa});var re=me({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Pa=me({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var hn={};S(hn,{base64:()=>Ne,base64pad:()=>Da,base64url:()=>Ra,base64urlpad:()=>Ba});var Ne=A({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Da=A({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Ra=A({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Ba=A({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var dn={};S(dn,{base8:()=>Ua});var Ua=A({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var pn={};S(pn,{identity:()=>Oa});var Oa=Le({prefix:"\0",name:"identity",encode:r=>Ui(r),decode:r=>Bi(r)});var It={};S(It,{code:()=>mn,decode:()=>Fa,encode:()=>qa,name:()=>$a});var Ma=new TextEncoder,za=new TextDecoder,$a="json",mn=512;function qa(r){return Ma.encode(JSON.stringify(r))}function Fa(r){return JSON.parse(za.decode(r))}var St={};S(St,{code:()=>gn,decode:()=>Va,encode:()=>Ha,name:()=>ja});var ja="raw",gn=85;function Ha(r){return Q(r)}function Va(r){return Q(r)}var wn={};S(wn,{identity:()=>Lt});var Ka=Fi,$i=128,Wa=127,Ga=~Wa,Qa=Math.pow(2,31);function Fi(r,e,t){e=e||[],t=t||0;for(var n=t;r>=Qa;)e[t++]=r&255|$i,r/=128;for(;r&Ga;)e[t++]=r&255|$i,r>>>=7;return e[t]=r|0,Fi.bytes=t-n+1,e}var Ja=yn,Ya=128,qi=127;function yn(r,n){var t=0,n=n||0,i=0,o=n,s,c=r.length;do{if(o>=c)throw yn.bytes=0,new RangeError("Could not decode varint");s=r[o++],t+=i<28?(s&qi)<<i:(s&qi)*Math.pow(2,i),i+=7}while(s>=Ya);return yn.bytes=o-n,t}var Xa=Math.pow(2,7),Za=Math.pow(2,14),ec=Math.pow(2,21),tc=Math.pow(2,28),rc=Math.pow(2,35),nc=Math.pow(2,42),ic=Math.pow(2,49),oc=Math.pow(2,56),sc=Math.pow(2,63),ac=function(r){return r<Xa?1:r<Za?2:r<ec?3:r<tc?4:r<rc?5:r<nc?6:r<ic?7:r<oc?8:r<sc?9:10},cc={encode:Ka,decode:Ja,encodingLength:ac},uc=cc,Xe=uc;function Ze(r,e=0){return[Xe.decode(r,e),Xe.decode.bytes]}function Pe(r,e,t=0){return Xe.encode(r,e,t),e}function De(r){return Xe.encodingLength(r)}function Be(r,e){let t=e.byteLength,n=De(r),i=n+De(t),o=new Uint8Array(i+t);return Pe(r,o,0),Pe(t,o,n),o.set(e,i),new Re(r,t,e,o)}function ji(r){let e=Q(r),[t,n]=Ze(e),[i,o]=Ze(e.subarray(n)),s=e.subarray(n+o);if(s.byteLength!==i)throw new Error("Incorrect length");return new Re(t,i,s,e)}function Hi(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&Ri(r.bytes,t.bytes)}}var Re=class{code;size;digest;bytes;constructor(e,t,n,i){this.code=e,this.size=t,this.digest=n,this.bytes=i}};var Vi=0,lc="identity",Ki=Q;function fc(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 Be(Vi,Ki(r))}var Lt={code:Vi,name:lc,encode:Ki,digest:fc};var En={};S(En,{sha256:()=>Ct,sha512:()=>Nt});var hc=20;function xn({name:r,code:e,encode:t,minDigestLength:n,maxDigestLength:i}){return new bn(r,e,t,n,i)}var bn=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,n,i,o){this.name=e,this.code=t,this.encode=n,this.minDigestLength=i??hc,this.maxDigestLength=o}digest(e,t){if(t?.truncate!=null){if(t.truncate<this.minDigestLength)throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`);if(this.maxDigestLength!=null&&t.truncate>this.maxDigestLength)throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`)}if(e instanceof Uint8Array){let n=this.encode(e);return n instanceof Uint8Array?Wi(n,this.code,t?.truncate):n.then(i=>Wi(i,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}};function Wi(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 Be(e,r)}function Qi(r){return async e=>new Uint8Array(await crypto.subtle.digest(r,e))}var Ct=xn({name:"sha2-256",code:18,encode:Qi("SHA-256")}),Nt=xn({name:"sha2-512",code:19,encode:Qi("SHA-512")});function Ji(r,e){let{bytes:t,version:n}=r;switch(n){case 0:return pc(t,vn(r),e??re.encoder);default:return mc(t,vn(r),e??Ce.encoder)}}var Yi=new WeakMap;function vn(r){let e=Yi.get(r);if(e==null){let t=new Map;return Yi.set(r,t),t}return e}var v=class r{code;version;multihash;bytes;"/";constructor(e,t,n,i){this.code=t,this.version=e,this.multihash=n,this.bytes=i,this["/"]=i}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!==tt)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==gc)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=Be(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&&Hi(e.multihash,n.multihash)}toString(e){return Ji(this,e)}toJSON(){return{"/":Ji(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(e){if(e==null)return null;let t=e;if(t instanceof r)return t;if(t["/"]!=null&&t["/"]===t.bytes||t.asCID===t){let{version:n,code:i,multihash:o,bytes:s}=t;return new r(n,i,o,s??Xi(n,i,o.bytes))}else if(t[yc]===!0){let{version:n,multihash:i,code:o}=t,s=ji(i);return r.create(n,o,s)}else return null}static create(e,t,n){if(typeof t!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(e){case 0:{if(t!==tt)throw new Error(`Version 0 CID must use dag-pb (code: ${tt}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let i=Xi(e,t,n.bytes);return new r(e,t,n,i)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,tt,e)}static createV1(e,t){return r.create(1,e,t)}static decode(e){let[t,n]=r.decodeFirst(e);if(n.length!==0)throw new Error("Incorrect length");return t}static decodeFirst(e){let t=r.inspectBytes(e),n=t.size-t.multihashSize,i=Q(e.subarray(n,n+t.multihashSize));if(i.byteLength!==t.multihashSize)throw new Error("Incorrect length");let o=i.subarray(t.multihashSize-t.digestSize),s=new Re(t.multihashCode,t.digestSize,o,i);return[t.version===0?r.createV0(s):r.createV1(t.codec,s),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[h,g]=Ze(e.subarray(t));return t+=g,h},i=n(),o=tt;if(i===18?(i=0,t=0):o=n(),i!==0&&i!==1)throw new RangeError(`Invalid CID version ${i}`);let s=t,c=n(),u=n(),l=t+u,p=l-s;return{version:i,codec:o,multihashCode:c,digestSize:u,multihashSize:p,size:l}}static parse(e,t){let[n,i]=dc(e,t),o=r.decode(i);if(o.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return vn(o).set(n,e),o}};function dc(r,e){switch(r[0]){case"Q":{let t=e??re;return[re.prefix,t.decode(`${re.prefix}${r}`)]}case re.prefix:{let t=e??re;return[re.prefix,t.decode(r)]}case Ce.prefix:{let t=e??Ce;return[Ce.prefix,t.decode(r)]}case ae.prefix:{let t=e??ae;return[ae.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 pc(r,e,t){let{prefix:n}=t;if(n!==re.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let i=e.get(n);if(i==null){let o=t.encode(r).slice(1);return e.set(n,o),o}else return i}function mc(r,e,t){let{prefix:n}=t,i=e.get(n);if(i==null){let o=t.encode(r);return e.set(n,o),o}else return i}var tt=112,gc=18;function Xi(r,e,t){let n=De(r),i=n+De(e),o=new Uint8Array(i+t.byteLength);return Pe(r,o,0),Pe(e,o,n),o.set(t,i),o}var yc=Symbol.for("@ipld/js-cid/CID");var _n={...pn,...an,...dn,...on,...sn,...un,...ln,...fn,...hn,...cn},Pf={...En,...wn};function Zi(r=0){return new Uint8Array(r)}function Pt(r=0){return new Uint8Array(r)}function to(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var eo=to("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),kn=to("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=Pt(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),wc={utf8:eo,"utf-8":eo,hex:_n.base16,latin1:kn,ascii:kn,binary:kn,..._n},Dt=wc;function ge(r,e="utf8"){let t=Dt[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.encoder.encode(r).substring(1)}var An=60;function Rt(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:G[e.type]})),Answer:(r.Answer??r.answers??[]).map(e=>({name:e.name,type:G[e.type],TTL:e.TTL??e.ttl??An,data:e.data instanceof Uint8Array?ge(e.data):e.data}))}}var bc=4;function In(r,e={}){let t=new Ye({concurrency:e.queryConcurrency??bc});return async(n,i={})=>{let o=i?.logger?.forComponent("dns:dns-json-over-https"),s=new URLSearchParams;s.set("name",n),At(i.types).forEach(u=>{s.append("type",G[u])}),i.onProgress?.(new E("dns:query",n)),o?.("GET %s",`${r}?${s}`);let c=await t.add(async()=>{let u=await fetch(`${r}?${s}`,{headers:{accept:"application/dns-json"},signal:i?.signal});if(o?.("GET %s %d",u.url,u.status),u.status!==200)throw new Error(`Unexpected HTTP status: ${u.status} - ${u.statusText}`);let l=Rt(await u.json());return i.onProgress?.(new E("dns:response",l)),l},{signal:i.signal});if(c==null)throw new Error("No DNS response received");return c}}function ro(){return[In("https://cloudflare-dns.com/dns-query"),In("https://dns.google/resolve")]}var oo=Si(io(),1);var Sn=class{lru;constructor(e){this.lru=(0,oo.default)(e)}get(e,t){let n=!0,i=[];for(let o of t){let s=this.getAnswers(e,o);if(s.length===0){n=!1;break}i.push(...s)}if(n)return Rt({answers:i})}getAnswers(e,t){let n=`${e.toLowerCase()}-${t}`,i=this.lru.get(n);if(i!=null){let o=i.filter(s=>s.expires>Date.now()).map(({expires:s,value:c})=>({...c,TTL:Math.round((s-Date.now())/1e3),type:G[c.type]}));return o.length===0&&this.lru.remove(n),o}return[]}add(e,t){let n=`${e.toLowerCase()}-${t.type}`,i=this.lru.get(n)??[];i.push({expires:Date.now()+(t.TTL??An)*1e3,value:t}),this.lru.set(n,i)}remove(e,t){let n=`${e.toLowerCase()}-${t}`;this.lru.remove(n)}clear(){this.lru.clear()}};function so(r){return new Sn(r)}var xc=1e3,Bt=class{resolvers;cache;logger;constructor(e){this.resolvers={},this.cache=so(e.cacheSize??xc),this.logger=e.logger,Object.entries(e.resolvers??{}).forEach(([t,n])=>{Array.isArray(n)||(n=[n]),t.endsWith(".")||(t=`${t}.`),this.resolvers[t]=n}),this.resolvers["."]==null&&(this.resolvers["."]=ro())}async query(e,t={}){let n=At(t.types),i=t.cached!==!1?this.cache.get(e,n):void 0;if(i!=null)return t.onProgress?.(new E("dns:cache",i)),i;let o=`${e.split(".").pop()}.`,s=(this.resolvers[o]??this.resolvers["."]).sort(()=>Math.random()>.5?-1:1),c=[];for(let u of s){if(t.signal?.aborted===!0)break;try{let l=await u(e,{...t,logger:this.logger,types:n});for(let p of l.Answer)this.cache.add(e,p);return l}catch(l){c.push(l),t.onProgress?.(new E("dns:error",l))}}throw new _t(c,`DNS lookup of ${e} ${n} failed`)}};var G;(function(r){r[r.A=1]="A",r[r.CNAME=5]="CNAME",r[r.TXT=16]="TXT",r[r.AAAA=28]="AAAA"})(G||(G={}));function ao(r={}){return new Bt(r)}function Ec(r){return r[Symbol.asyncIterator]!=null}function vc(r){if(Ec(r))return(async()=>{for await(let e of r);})();for(let e of r);}var co=vc;function we(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 Tn(r,e){e==null&&(e=r.reduce((i,o)=>i+o.length,0));let t=Pt(e),n=0;for(let i of r)t.set(i,n),n+=i.length;return t}function D(r,e="utf8"){let t=Dt[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.decoder.decode(`${t.prefix}${r}`)}var Ln={32:16777619n,64:1099511628211n,128:309485009821345068724781371n,256:374144419156711147060143317175368453031918731002211n,512:35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759n,1024:5016456510113118655434598811035278955030765345404790744303017523831112055108147451509157692220295382716162651878526895249385292291816524375083746691371804094271873160484737966720260389217684476157468082573n},uo={32:2166136261n,64:14695981039346656037n,128:144066263297769815596495629667062367629n,256:100029257958052580907070968620625704837092796014241193945225284501741471925557n,512:9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785n,1024:14197795064947621068722070641403218320880622795441933960878474914617582723252296732303717722150864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915n},lo=new globalThis.TextEncoder;function _c(r,e){let t=Ln[e],n=uo[e];for(let i=0;i<r.length;i++)n^=BigInt(r[i]),n=BigInt.asUintN(e,n*t);return n}function kc(r,e,t){if(t.length===0)throw new Error("The `utf8Buffer` option must have a length greater than zero");let n=Ln[e],i=uo[e],o=r;for(;o.length>0;){let s=lo.encodeInto(o,t);o=o.slice(s.read);for(let c=0;c<s.written;c++)i^=BigInt(t[c]),i=BigInt.asUintN(e,i*n)}return i}function Cn(r,{size:e=32,utf8Buffer:t}={}){if(!Ln[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 kc(r,e,t);r=lo.encode(r)}return _c(r,e)}var rt={hash:r=>Number(Cn(r,{size:32})),hashV:(r,e)=>Ac(rt.hash(r,e))};function Ac(r){let e=r.toString(16);return e.length%2===1&&(e=`0${e}`),D(e,"base16")}var Nn=64,J=class{fp;h;seed;constructor(e,t,n,i=2){if(i>Nn)throw new TypeError("Invalid Fingerprint Size");let o=t.hashV(e,n),s=Zi(i);for(let c=0;c<s.length;c++)s[c]=o[c];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?we(this.fp,e.fp):!1}};function be(r,e){return Math.floor(Math.random()*(e-r))+r}var xe=class{contents;constructor(e){this.contents=new Array(e).fill(null)}has(e){if(!(e instanceof J))throw new TypeError("Invalid Fingerprint");return this.contents.some(t=>e.equals(t))}add(e){if(!(e instanceof J))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 J))throw new TypeError("Invalid Fingerprint");let t=be(0,this.contents.length-1),n=this.contents[t];return this.contents[t]=e,n}remove(e){if(!(e instanceof J))throw new TypeError("Invalid Fingerprint");let t=this.contents.findIndex(n=>e.equals(n));return t>-1?(this.contents[t]=null,!0):!1}};var Ic=500,nt=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??rt,this.seed=e.seed??be(0,Math.pow(2,10))}add(e){typeof e=="string"&&(e=D(e));let t=new J(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,i=(n^t.hash())%this.filterSize;if(this.buckets[n]==null&&(this.buckets[n]=new xe(this.bucketSize)),this.buckets[i]==null&&(this.buckets[i]=new xe(this.bucketSize)),this.buckets[n].add(t)||this.buckets[i].add(t))return this.count++,!0;let o=[n,i],s=o[be(0,o.length-1)];this.buckets[s]==null&&(this.buckets[s]=new xe(this.bucketSize));for(let c=0;c<Ic;c++){let u=this.buckets[s].swap(t);if(u!=null&&(s=(s^u.hash())%this.filterSize,this.buckets[s]==null&&(this.buckets[s]=new xe(this.bucketSize)),this.buckets[s].add(u)))return this.count++,!0}return!1}has(e){typeof e=="string"&&(e=D(e));let t=new J(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,i=this.buckets[n]?.has(t)??!1;if(i)return i;let o=(n^t.hash())%this.filterSize;return this.buckets[o]?.has(t)??!1}remove(e){typeof e=="string"&&(e=D(e));let t=new J(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,i=this.buckets[n]?.remove(t)??!1;if(i)return this.count--,i;let o=(n^t.hash())%this.filterSize,s=this.buckets[o]?.remove(t)??!1;return s&&this.count--,s}get reliable(){return Math.floor(100*(this.count/this.filterSize))<=90}},Sc={1:.5,2:.84,4:.95,8:.98};function Tc(r=.001){return r>.002?2:r>1e-5?4:8}function fo(r,e=.001){let t=Tc(e),n=Sc[t],i=Math.round(r/n),o=Math.min(Math.ceil(Math.log2(1/e)+Math.log2(2*t)),Nn);return{filterSize:i,bucketSize:t,fingerprintSize:o}}var Ut=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??rt,this.seed=e.seed??be(0,Math.pow(2,10)),this.filterSeries=[new nt({filterSize:this.filterSize,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed})]}add(e){if(typeof e=="string"&&(e=D(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 nt({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=D(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=D(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 Pn(r,e=.001,t){return new Ut({...fo(r,e),...t??{}})}function R(){let r={};return r.promise=new Promise((e,t)=>{r.resolve=e,r.reject=t}),r}var Ot=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 Ot(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 Ot(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 Dn=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}};function Mt(r={}){return Lc(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 Lc(r,e){e=e??{};let t=e.onEnd,n=new Ue,i,o,s,c=R(),u=async()=>{try{return n.isEmpty()?s?{done:!0}:await new Promise((b,I)=>{o=N=>{o=null,n.push(N);try{b(r(n))}catch(L){I(L)}return i}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{c.resolve(),c=R()})}},l=b=>o!=null?o(b):(n.push(b),i),p=b=>(n=new Ue,o!=null?o({error:b}):(n.push({error:b}),i)),h=b=>{if(s)return i;if(e?.objectMode!==!0&&b?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return l({done:!1,value:b})},g=b=>s?i:(s=!0,b!=null?p(b):l({done:!0})),y=()=>(n=new Ue,g(),{done:!0}),w=b=>(g(b),{done:!0});if(i={[Symbol.asyncIterator](){return this},next:u,return:y,throw:w,push:h,end:g,get readableLength(){return n.size},onEmpty:async b=>{let I=b?.signal;if(I?.throwIfAborted(),n.isEmpty())return;let N,L;I!=null&&(N=new Promise((B,F)=>{L=()=>{F(new Dn)},I.addEventListener("abort",L)}));try{await Promise.race([c.promise,N])}finally{L!=null&&I!=null&&I?.removeEventListener("abort",L)}}},t==null)return i;let k=i;return i={[Symbol.asyncIterator](){return this},next(){return k.next()},throw(b){return k.throw(b),t!=null&&(t(b),t=void 0),{done:!0}},return(){return k.return(),t!=null&&(t(),t=void 0),{done:!0}},push:h,end(b){return k.end(b),t!=null&&(t(b),t=void 0),i},get readableLength(){return k.readableLength},onEmpty:b=>k.onEmpty(b)},i}var Cc=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 Nc(r,e,t){let n,i=new Promise((o,s)=>{if(t={rejectionEvents:["error"],multiArgs:!1,rejectionMultiArgs:!1,resolveImmediately:!1,...t},!(t.count>=0&&(t.count===Number.POSITIVE_INFINITY||Number.isInteger(t.count))))throw new TypeError("The `count` option should be at least 0 or more");t.signal?.throwIfAborted();let c=[e].flat(),u=[],{addListener:l,removeListener:p}=Cc(r),h=async(...y)=>{let w=t.multiArgs?y:y[0];if(t.filter)try{if(!await t.filter(w))return}catch(k){n(),s(k);return}u.push(w),t.count===u.length&&(n(),o(u))},g=(...y)=>{n(),s(t.rejectionMultiArgs?y:y[0])};n=()=>{for(let y of c)p(y,h);for(let y of t.rejectionEvents)c.includes(y)||p(y,g)};for(let y of c)l(y,h);for(let y of t.rejectionEvents)c.includes(y)||l(y,g);t.signal&&t.signal.addEventListener("abort",()=>{g(t.signal.reason)},{once:!0}),t.resolveImmediately&&o(u)});if(i.cancel=n,typeof t.timeout=="number"){let o=Qe(i,{milliseconds:t.timeout});return o.cancel=()=>{n(),o.clear()},o}return i}function zt(r,e,t){typeof t=="function"&&(t={filter:t}),t={...t,count:1,resolveImmediately:!1};let n=Nc(r,e,t),i=n.then(o=>o[0]);return i.cancel=n.cancel,i}function Rn(r,e){let t,n=function(){let i=function(){t=void 0,r()};clearTimeout(t),t=setTimeout(i,e)};return n.start=()=>{},n.stop=()=>{clearTimeout(t)},n}var $t=class extends Error{static name="QueueFullError";constructor(e="The queue was full"){super(e),this.name="QueueFullError"}};function Pc(r){return r.reason}async function ce(r,e,t){if(e==null)return r;let n=t?.translateError??Pc;if(e.aborted)return r.catch(()=>{}),Promise.reject(n(e));let i;try{return await Promise.race([r,new Promise((o,s)=>{i=()=>{s(n(e))},e.addEventListener("abort",i)})])}finally{i!=null&&e.removeEventListener("abort",i)}}var qt=class{deferred;signal;constructor(e){this.signal=e,this.deferred=R(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new W)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function Dc(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var Ft=class{id;fn;options;recipients;status;timeline;controller;constructor(e,t){this.id=Dc(),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 W),this.cleanup())}async join(e={}){let t=new qt(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 ce(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 U=class extends j{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=Rn(this.emitEmpty.bind(this),1),this.emitIdle=Rn(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 $t;let n=new Ft(e,t);return this.enqueue(n),this.safeDispatchEvent("add"),this.tryToStartAnother(),n.join(t).then(i=>(this.safeDispatchEvent("completed",{detail:i}),this.safeDispatchEvent("success",{detail:{job:n,result:i}}),i)).catch(i=>{if(n.status==="queued"){for(let o=0;o<this.queue.length;o++)if(this.queue[o]===n){this.queue.splice(o,1);break}}throw this.safeDispatchEvent("failure",{detail:{job:n,error:i}}),i})}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(e=>{e.abort(new W)}),this.clear()}async onEmpty(e){this.size!==0&&await zt(this,"empty",e)}async onSizeLessThan(e,t){this.size<e||await zt(this,"next",{...t,filter:()=>this.size<e})}async onIdle(e){this.pending===0&&this.size===0||await zt(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=Mt({objectMode:!0}),n=u=>{u!=null?this.abort():this.clear(),t.end(u)},i=u=>{u.detail!=null&&t.push(u.detail)},o=u=>{n(u.detail.error)},s=()=>{n()},c=()=>{n(new W("Queue aborted"))};this.addEventListener("completed",i),this.addEventListener("failure",o),this.addEventListener("idle",s),e?.signal?.addEventListener("abort",c);try{yield*t}finally{this.removeEventListener("completed",i),this.removeEventListener("failure",o),this.removeEventListener("idle",s),e?.signal?.removeEventListener("abort",c),n()}}};function Y(r){let e=new globalThis.AbortController;function t(){let o=r.filter(s=>s?.aborted===!0).map(s=>s?.reason).pop();e.abort(o);for(let s of r)s?.removeEventListener!=null&&s.removeEventListener("abort",t)}for(let o of r){if(o?.aborted===!0){t();break}o?.addEventListener!=null&&o.addEventListener("abort",t)}function n(){for(let o of r)o?.removeEventListener!=null&&o.removeEventListener("abort",t)}let i=e.signal;return i.clear=n,i}var Bn=class{readNext;haveNext;ended;nextResult;error;constructor(){this.ended=!1,this.readNext=R(),this.haveNext=R()}[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=R(),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=R(),await ce(this.readNext.promise,t?.signal,t)}};function ho(){return new Bn}function Rc(r){return r[Symbol.asyncIterator]!=null}async function Bc(r,e,t){try{await Promise.all(r.map(async n=>{for await(let i of n)await e.push(i,{signal:t}),t.throwIfAborted()})),await e.end(void 0,{signal:t})}catch(n){await e.end(n,{signal:t}).catch(()=>{})}}async function*Uc(r){let e=new AbortController,t=ho();Bc(r,t,e.signal).catch(()=>{});try{yield*t}finally{e.abort()}}function*Oc(r){for(let e of r)yield*e}function Mc(...r){let e=[];for(let t of r)Rc(t)||e.push(t);return e.length===r.length?Oc(e):Uc(r)}var jt=Mc;var zc=["Object","RegExp","Date","Error","Map","Set","WeakMap","WeakSet","ArrayBuffer","SharedArrayBuffer","DataView","Promise","URL","HTMLElement","Int8Array","Uint8ClampedArray","Int16Array","Uint16Array","Int32Array","Uint32Array","Float32Array","Float64Array","BigInt64Array","BigUint64Array"];function Un(r){if(r===null)return"null";if(r===void 0)return"undefined";if(r===!0||r===!1)return"boolean";let e=typeof r;if(e==="string"||e==="number"||e==="bigint"||e==="symbol")return e;if(e==="function")return"Function";if(Array.isArray(r))return"Array";if(r instanceof Uint8Array)return"Uint8Array";if(r.constructor===Object)return"Object";let t=$c(r);return t||"Object"}function $c(r){let e=Object.prototype.toString.call(r).slice(8,-1);if(zc.includes(e))return e}var a=class{constructor(e,t,n){this.major=e,this.majorEncoded=e<<5,this.name=t,this.terminal=n}toString(){return`Type[${this.major}].${this.name}`}compare(e){return this.major<e.major?-1:this.major>e.major?1:0}static equals(e,t){return e===t||e.major===t.major&&e.name===t.name}};a.uint=new a(0,"uint",!0);a.negint=new a(1,"negint",!0);a.bytes=new a(2,"bytes",!0);a.string=new a(3,"string",!0);a.array=new a(4,"array",!1);a.map=new a(5,"map",!1);a.tag=new a(6,"tag",!1);a.float=new a(7,"float",!0);a.false=new a(7,"false",!0);a.true=new a(7,"true",!0);a.null=new a(7,"null",!0);a.undefined=new a(7,"undefined",!0);a.break=new a(7,"break",!0);var f=class{constructor(e,t,n){this.type=e,this.value=t,this.encodedLength=n,this.encodedBytes=void 0,this.byteValue=void 0}toString(){return`Token[${this.type}].${this.value}`}};var it=globalThis.process&&!globalThis.process.browser&&globalThis.Buffer&&typeof globalThis.Buffer.isBuffer=="function",qc=new TextEncoder;function Ht(r){return it&&globalThis.Buffer.isBuffer(r)}function Ee(r){return r instanceof Uint8Array?Ht(r)?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):r:Uint8Array.from(r)}var Fc=24,jc=200,Oe=it?r=>r.length>=Fc?globalThis.Buffer.from(r):po(r):r=>r.length>=jc?qc.encode(r):po(r),ne=r=>Uint8Array.from(r),go=it?(r,e,t)=>Ht(r)?new Uint8Array(r.subarray(e,t)):r.slice(e,t):(r,e,t)=>r.slice(e,t),yo=it?(r,e)=>(r=r.map(t=>t instanceof Uint8Array?t:globalThis.Buffer.from(t)),Ee(globalThis.Buffer.concat(r,e))):(r,e)=>{let t=new Uint8Array(e),n=0;for(let i of r)n+i.length>t.length&&(i=i.subarray(0,t.length-n)),t.set(i,n),n+=i.length;return t},wo=it?r=>globalThis.Buffer.allocUnsafe(r):r=>new Uint8Array(r);function Vt(r,e){if(Ht(r)&&Ht(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 po(r){let e=[],t=0;for(let n=0;n<r.length;n++){let i=r.charCodeAt(n);i<128?e[t++]=i:i<2048?(e[t++]=i>>6|192,e[t++]=i&63|128):(i&64512)===55296&&n+1<r.length&&(r.charCodeAt(n+1)&64512)===56320?(i=65536+((i&1023)<<10)+(r.charCodeAt(++n)&1023),e[t++]=i>>18|240,e[t++]=i>>12&63|128,e[t++]=i>>6&63|128,e[t++]=i&63|128):(i>=55296&&i<=57343&&(i=65533),e[t++]=i>>12|224,e[t++]=i>>6&63|128,e[t++]=i&63|128)}return e}var mo=4096;function bo(r){let e=r.length;if(e<=mo)return String.fromCharCode.apply(String,r);let t="",n=0;for(;n<e;)t+=String.fromCharCode.apply(String,r.slice(n,n+=mo));return t}var Hc=256,ot=class{constructor(e=Hc){this.chunkSize=e,this.cursor=0,this.maxCursor=-1,this.chunks=[],this._initReuseChunk=null}reset(){this.cursor=0,this.maxCursor=-1,this.chunks.length&&(this.chunks=[]),this._initReuseChunk!==null&&(this.chunks.push(this._initReuseChunk),this.maxCursor=this._initReuseChunk.length-1)}push(e){let t=this.chunks[this.chunks.length-1];if(this.cursor+e.length<=this.maxCursor+1){let i=t.length-(this.maxCursor-this.cursor)-1;t.set(e,i)}else{if(t){let i=t.length-(this.maxCursor-this.cursor)-1;i<t.length&&(this.chunks[this.chunks.length-1]=t.subarray(0,i),this.maxCursor=this.cursor-1)}e.length<64&&e.length<this.chunkSize?(t=wo(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=go(n,0,this.cursor)}else t=yo(this.chunks,this.cursor);return e&&this.reset(),t}},Kt=class{constructor(e){this.dest=e,this.cursor=0,this.chunks=[e]}reset(){this.cursor=0}push(e){if(this.cursor+e.length>this.dest.length)throw new Error("write out of bounds, destination buffer is too small");this.dest.set(e,this.cursor),this.cursor+=e.length}toBytes(e=!1){let t=this.dest.subarray(0,this.cursor);return e&&this.reset(),t}};var m="CBOR decode error:",ie="CBOR encode error:",st=[];st[23]=1;st[24]=2;st[25]=3;st[26]=5;st[27]=9;function ue(r,e,t){if(r.length-e<t)throw new Error(`${m} not enough data for type`)}var T=[24,256,65536,4294967296,BigInt("18446744073709551616")];function O(r,e,t){ue(r,e,1);let n=r[e];if(t.strict===!0&&n<T[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<T[1])throw new Error(`${m} integer encoded in more bytes than necessary (strict decode)`);return n}function z(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<T[2])throw new Error(`${m} integer encoded in more bytes than necessary (strict decode)`);return n}function $(r,e,t){ue(r,e,8);let n=r[e]*16777216+(r[e+1]<<16)+(r[e+2]<<8)+r[e+3],i=r[e+4]*16777216+(r[e+5]<<16)+(r[e+6]<<8)+r[e+7],o=(BigInt(n)<<BigInt(32))+BigInt(i);if(t.strict===!0&&o<T[3])throw new Error(`${m} integer encoded in more bytes than necessary (strict decode)`);if(o<=Number.MAX_SAFE_INTEGER)return Number(o);if(t.allowBigInt===!0)return o;throw new Error(`${m} integers outside of the safe integer range are not supported`)}function xo(r,e,t,n){return new f(a.uint,O(r,e+1,n),2)}function Eo(r,e,t,n){return new f(a.uint,M(r,e+1,n),3)}function vo(r,e,t,n){return new f(a.uint,z(r,e+1,n),5)}function _o(r,e,t,n){return new f(a.uint,$(r,e+1,n),9)}function H(r,e){return _(r,0,e.value)}function _(r,e,t){if(t<T[0]){let n=Number(t);r.push([e|n])}else if(t<T[1]){let n=Number(t);r.push([e|24,n])}else if(t<T[2]){let n=Number(t);r.push([e|25,n>>>8,n&255])}else if(t<T[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<T[4]){let i=[e|27,0,0,0,0,0,0,0],o=Number(n&BigInt(4294967295)),s=Number(n>>BigInt(32)&BigInt(4294967295));i[8]=o&255,o=o>>8,i[7]=o&255,o=o>>8,i[6]=o&255,o=o>>8,i[5]=o&255,i[4]=s&255,s=s>>8,i[3]=s&255,s=s>>8,i[2]=s&255,s=s>>8,i[1]=s&255,r.push(i)}else throw new Error(`${m} encountered BigInt larger than allowable range`)}}H.encodedSize=function(e){return _.encodedSize(e.value)};_.encodedSize=function(e){return e<T[0]?1:e<T[1]?2:e<T[2]?3:e<T[3]?5:9};H.compareTokens=function(e,t){return e.value<t.value?-1:e.value>t.value?1:0};function ko(r,e,t,n){return new f(a.negint,-1-O(r,e+1,n),2)}function Ao(r,e,t,n){return new f(a.negint,-1-M(r,e+1,n),3)}function Io(r,e,t,n){return new f(a.negint,-1-z(r,e+1,n),5)}var On=BigInt(-1),So=BigInt(1);function To(r,e,t,n){let i=$(r,e+1,n);if(typeof i!="bigint"){let o=-1-i;if(o>=Number.MIN_SAFE_INTEGER)return new f(a.negint,o,9)}if(n.allowBigInt!==!0)throw new Error(`${m} integers outside of the safe integer range are not supported`);return new f(a.negint,On-BigInt(i),9)}function Wt(r,e){let t=e.value,n=typeof t=="bigint"?t*On-So:t*-1-1;_(r,e.type.majorEncoded,n)}Wt.encodedSize=function(e){let t=e.value,n=typeof t=="bigint"?t*On-So:t*-1-1;return n<T[0]?1:n<T[1]?2:n<T[2]?3:n<T[3]?5:9};Wt.compareTokens=function(e,t){return e.value<t.value?1:e.value>t.value?-1:0};function at(r,e,t,n){ue(r,e,t+n);let i=r.slice(e+t,e+t+n);return new f(a.bytes,i,t+n)}function Lo(r,e,t,n){return at(r,e,1,t)}function Co(r,e,t,n){return at(r,e,2,O(r,e+1,n))}function No(r,e,t,n){return at(r,e,3,M(r,e+1,n))}function Po(r,e,t,n){return at(r,e,5,z(r,e+1,n))}function Do(r,e,t,n){let i=$(r,e+1,n);if(typeof i=="bigint")throw new Error(`${m} 64-bit integer bytes lengths not supported`);return at(r,e,9,i)}function Gt(r){return r.encodedBytes===void 0&&(r.encodedBytes=a.equals(r.type,a.string)?Oe(r.value):r.value),r.encodedBytes}function Me(r,e){let t=Gt(e);_(r,e.type.majorEncoded,t.length),r.push(t)}Me.encodedSize=function(e){let t=Gt(e);return _.encodedSize(t.length)+t.length};Me.compareTokens=function(e,t){return Kc(Gt(e),Gt(t))};function Kc(r,e){return r.length<e.length?-1:r.length>e.length?1:Vt(r,e)}var Ro=new TextDecoder,Gc=32;function Qc(r,e,t){if(t-e<Gc){let i="";for(let o=e;o<t;o++){let s=r[o];if(s&128)return Ro.decode(r.subarray(e,t));i+=String.fromCharCode(s)}return i}return Ro.decode(r.subarray(e,t))}function ct(r,e,t,n,i){let o=t+n;ue(r,e,o);let s=new f(a.string,Qc(r,e+t,e+o),o);return i.retainStringBytes===!0&&(s.byteValue=r.slice(e+t,e+o)),s}function Bo(r,e,t,n){return ct(r,e,1,t,n)}function Uo(r,e,t,n){return ct(r,e,2,O(r,e+1,n),n)}function Oo(r,e,t,n){return ct(r,e,3,M(r,e+1,n),n)}function Mo(r,e,t,n){return ct(r,e,5,z(r,e+1,n),n)}function zo(r,e,t,n){let i=$(r,e+1,n);if(typeof i=="bigint")throw new Error(`${m} 64-bit integer string lengths not supported`);return ct(r,e,9,i,n)}var $o=Me;function ze(r,e,t,n){return new f(a.array,n,t)}function qo(r,e,t,n){return ze(r,e,1,t)}function Fo(r,e,t,n){return ze(r,e,2,O(r,e+1,n))}function jo(r,e,t,n){return ze(r,e,3,M(r,e+1,n))}function Ho(r,e,t,n){return ze(r,e,5,z(r,e+1,n))}function Vo(r,e,t,n){let i=$(r,e+1,n);if(typeof i=="bigint")throw new Error(`${m} 64-bit integer array lengths not supported`);return ze(r,e,9,i)}function Ko(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){_(r,a.array.majorEncoded,e.value)}Qt.compareTokens=H.compareTokens;Qt.encodedSize=function(e){return _.encodedSize(e.value)};function $e(r,e,t,n){return new f(a.map,n,t)}function Wo(r,e,t,n){return $e(r,e,1,t)}function Go(r,e,t,n){return $e(r,e,2,O(r,e+1,n))}function Qo(r,e,t,n){return $e(r,e,3,M(r,e+1,n))}function Jo(r,e,t,n){return $e(r,e,5,z(r,e+1,n))}function Yo(r,e,t,n){let i=$(r,e+1,n);if(typeof i=="bigint")throw new Error(`${m} 64-bit integer map lengths not supported`);return $e(r,e,9,i)}function Xo(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 Jt(r,e){_(r,a.map.majorEncoded,e.value)}Jt.compareTokens=H.compareTokens;Jt.encodedSize=function(e){return _.encodedSize(e.value)};function Zo(r,e,t,n){return new f(a.tag,t,1)}function es(r,e,t,n){return new f(a.tag,O(r,e+1,n),2)}function ts(r,e,t,n){return new f(a.tag,M(r,e+1,n),3)}function rs(r,e,t,n){return new f(a.tag,z(r,e+1,n),5)}function ns(r,e,t,n){return new f(a.tag,$(r,e+1,n),9)}function Yt(r,e){_(r,a.tag.majorEncoded,e.value)}Yt.compareTokens=H.compareTokens;Yt.encodedSize=function(e){return _.encodedSize(e.value)};var Mn=20,zn=21,$n=22,qn=23;function is(r,e,t,n){if(n.allowUndefined===!1)throw new Error(`${m} undefined values are not supported`);return n.coerceUndefinedToNull===!0?new f(a.null,null,1):new f(a.undefined,void 0,1)}function os(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${m} indefinite length items not allowed`);return new f(a.break,void 0,1)}function Fn(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 f(a.float,r,e)}function ss(r,e,t,n){return Fn(jn(r,e+1),3,n)}function as(r,e,t,n){return Fn(Hn(r,e+1),5,n)}function cs(r,e,t,n){return Fn(hs(r,e+1),9,n)}function ut(r,e,t){let n=e.value;if(n===!1)r.push([a.float.majorEncoded|Mn]);else if(n===!0)r.push([a.float.majorEncoded|zn]);else if(n===null)r.push([a.float.majorEncoded|$n]);else if(n===void 0)r.push([a.float.majorEncoded|qn]);else{let i,o=!1;(!t||t.float64!==!0)&&(ls(n),i=jn(X,1),n===i||Number.isNaN(n)?(X[0]=249,r.push(X.slice(0,3)),o=!0):(fs(n),i=Hn(X,1),n===i&&(X[0]=250,r.push(X.slice(0,5)),o=!0))),o||(eu(n),i=hs(X,1),X[0]=251,r.push(X.slice(0,9)))}}ut.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){ls(n);let i=jn(X,1);if(n===i||Number.isNaN(n))return 3;if(fs(n),i=Hn(X,1),n===i)return 5}return 9};var us=new ArrayBuffer(9),V=new DataView(us,1),X=new Uint8Array(us,0);function ls(r){if(r===1/0)V.setUint16(0,31744,!1);else if(r===-1/0)V.setUint16(0,64512,!1);else if(Number.isNaN(r))V.setUint16(0,32256,!1);else{V.setFloat32(0,r);let e=V.getUint32(0),t=(e&2139095040)>>23,n=e&8388607;if(t===255)V.setUint16(0,31744,!1);else if(t===0)V.setUint16(0,(r&2147483648)>>16|n>>13,!1);else{let i=t-127;i<-24?V.setUint16(0,0):i<-14?V.setUint16(0,(e&2147483648)>>16|1<<24+i,!1):V.setUint16(0,(e&2147483648)>>16|i+15<<10|n>>13,!1)}}}function jn(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,i=t&1023,o;return n===0?o=i*2**-24:n!==31?o=(i+1024)*2**(n-25):o=i===0?1/0:NaN,t&32768?-o:o}function fs(r){V.setFloat32(0,r,!1)}function Hn(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 eu(r){V.setFloat64(0,r,!1)}function hs(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)}ut.compareTokens=H.compareTokens;function x(r,e,t){throw new Error(`${m} encountered invalid minor (${t}) for major ${r[e]>>>5}`)}function Xt(r){return()=>{throw new Error(`${m} ${r}`)}}var d=[];for(let r=0;r<=23;r++)d[r]=x;d[24]=xo;d[25]=Eo;d[26]=vo;d[27]=_o;d[28]=x;d[29]=x;d[30]=x;d[31]=x;for(let r=32;r<=55;r++)d[r]=x;d[56]=ko;d[57]=Ao;d[58]=Io;d[59]=To;d[60]=x;d[61]=x;d[62]=x;d[63]=x;for(let r=64;r<=87;r++)d[r]=Lo;d[88]=Co;d[89]=No;d[90]=Po;d[91]=Do;d[92]=x;d[93]=x;d[94]=x;d[95]=Xt("indefinite length bytes/strings are not supported");for(let r=96;r<=119;r++)d[r]=Bo;d[120]=Uo;d[121]=Oo;d[122]=Mo;d[123]=zo;d[124]=x;d[125]=x;d[126]=x;d[127]=Xt("indefinite length bytes/strings are not supported");for(let r=128;r<=151;r++)d[r]=qo;d[152]=Fo;d[153]=jo;d[154]=Ho;d[155]=Vo;d[156]=x;d[157]=x;d[158]=x;d[159]=Ko;for(let r=160;r<=183;r++)d[r]=Wo;d[184]=Go;d[185]=Qo;d[186]=Jo;d[187]=Yo;d[188]=x;d[189]=x;d[190]=x;d[191]=Xo;for(let r=192;r<=215;r++)d[r]=Zo;d[216]=es;d[217]=ts;d[218]=rs;d[219]=ns;d[220]=x;d[221]=x;d[222]=x;d[223]=x;for(let r=224;r<=243;r++)d[r]=Xt("simple values are not supported");d[244]=x;d[245]=x;d[246]=x;d[247]=is;d[248]=Xt("simple values are not supported");d[249]=ss;d[250]=as;d[251]=cs;d[252]=x;d[253]=x;d[254]=x;d[255]=os;var Z=[];for(let r=0;r<24;r++)Z[r]=new f(a.uint,r,1);for(let r=-1;r>=-24;r--)Z[31-r]=new f(a.negint,r,1);Z[64]=new f(a.bytes,new Uint8Array(0),1);Z[96]=new f(a.string,"",1);Z[128]=new f(a.array,0,1);Z[160]=new f(a.map,0,1);Z[244]=new f(a.false,!1,1);Z[245]=new f(a.true,!0,1);Z[246]=new f(a.null,null,1);function Vn(r){switch(r.type){case a.false:return ne([244]);case a.true:return ne([245]);case a.null:return ne([246]);case a.bytes:return r.value.length?void 0:ne([64]);case a.string:return r.value===""?ne([96]):void 0;case a.array:return r.value===0?ne([128]):void 0;case a.map:return r.value===0?ne([160]):void 0;case a.uint:return r.value<24?ne([Number(r.value)]):void 0;case a.negint:if(r.value>=-24)return ne([31-Number(r.value)])}}var ru={float64:!1,mapSorter:ou,quickEncodeToken:Vn},ys=Object.freeze({float64:!0,mapSorter:su,quickEncodeToken:Vn});function nu(){let r=[];return r[a.uint.major]=H,r[a.negint.major]=Wt,r[a.bytes.major]=Me,r[a.string.major]=$o,r[a.array.major]=Qt,r[a.map.major]=Jt,r[a.tag.major]=Yt,r[a.float.major]=ut,r}var qe=nu(),Zt=new ot,ft=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(`${ie} object contains circular references`);return new r(t,e)}},ye={null:new f(a.null,null),undefined:new f(a.undefined,void 0),true:new f(a.true,!0),false:new f(a.false,!1),emptyArray:new f(a.array,0),emptyMap:new f(a.map,0)},oe={number(r,e,t,n){return!Number.isInteger(r)||!Number.isSafeInteger(r)?new f(a.float,r):r>=0?new f(a.uint,r):new f(a.negint,r)},bigint(r,e,t,n){return r>=BigInt(0)?new f(a.uint,r):new f(a.negint,r)},Uint8Array(r,e,t,n){return new f(a.bytes,r)},string(r,e,t,n){return new f(a.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 f(a.bytes,new Uint8Array(r))},DataView(r,e,t,n){return new f(a.bytes,new Uint8Array(r.buffer,r.byteOffset,r.byteLength))},Array(r,e,t,n){if(!r.length)return t.addBreakTokens===!0?[ye.emptyArray,new f(a.break)]:ye.emptyArray;n=ft.createCheck(n,r);let i=[],o=0;for(let s of r)i[o++]=er(s,t,n);return t.addBreakTokens?[new f(a.array,r.length),i,new f(a.break)]:[new f(a.array,r.length),i]},Object(r,e,t,n){let i=e!=="Object",o=i?r.keys():Object.keys(r),s=i?r.size:o.length,c;if(s){c=new Array(s),n=ft.createCheck(n,r);let u=!i&&t.ignoreUndefinedProperties,l=0;for(let p of o){let h=i?r.get(p):r[p];u&&h===void 0||(c[l++]=[er(p,t,n),er(h,t,n)])}l<s&&(c.length=l)}return c?.length?(iu(c,t),t.addBreakTokens?[new f(a.map,c.length),c,new f(a.break)]:[new f(a.map,c.length),c]):t.addBreakTokens===!0?[ye.emptyMap,new f(a.break)]:ye.emptyMap}};oe.Map=oe.Object;oe.Buffer=oe.Uint8Array;for(let r of"Uint8Clamped Uint16 Uint32 Int8 Int16 Int32 BigUint64 BigInt64 Float32 Float64".split(" "))oe[`${r}Array`]=oe.DataView;function er(r,e={},t){let n=Un(r),i=e&&e.typeEncoders&&e.typeEncoders[n]||oe[n];if(typeof i=="function"){let s=i(r,n,e,t);if(s!=null)return s}let o=oe[n];if(!o)throw new Error(`${ie} unsupported type: ${n}`);return o(r,n,e,t)}function iu(r,e){e.mapSorter&&r.sort(e.mapSorter)}function ou(r,e){let t=Array.isArray(r[0])?r[0][0]:r[0],n=Array.isArray(e[0])?e[0][0]:e[0];if(t.type!==n.type)return t.type.compare(n.type);let i=t.type.major,o=qe[i].compareTokens(t,n);return o===0&&console.warn("WARNING: complex key types used, CBOR key sorting guarantees are gone"),o}function su(r,e){if(r[0]instanceof f&&e[0]instanceof f){let t=r[0],n=e[0];return t._keyBytes||(t._keyBytes=ds(t.value)),n._keyBytes||(n._keyBytes=ds(n.value)),Vt(t._keyBytes,n._keyBytes)}throw new Error("rfc8949MapSorter: complex key types are not supported yet")}function ds(r){return tr(r,qe,ys)}function lt(r,e,t,n){if(Array.isArray(e))for(let i of e)lt(r,i,t,n);else t[e.type.major](r,e,n)}var ps=a.uint.majorEncoded,ms=a.negint.majorEncoded,au=a.bytes.majorEncoded,cu=a.string.majorEncoded,gs=a.array.majorEncoded,uu=a.float.majorEncoded|Mn,lu=a.float.majorEncoded|zn,fu=a.float.majorEncoded|$n,hu=a.float.majorEncoded|qn,du=BigInt(-1),pu=BigInt(1);function mu(r){return r.addBreakTokens!==!0}function ws(r,e,t,n){let i=Un(e),o=t.typeEncoders&&t.typeEncoders[i];if(o){let s=o(e,i,t,n);if(s!=null){lt(r,s,qe,t);return}}switch(i){case"null":r.push([fu]);return;case"undefined":r.push([hu]);return;case"boolean":r.push([e?lu:uu]);return;case"number":!Number.isInteger(e)||!Number.isSafeInteger(e)?ut(r,new f(a.float,e),t):e>=0?_(r,ps,e):_(r,ms,e*-1-1);return;case"bigint":e>=BigInt(0)?_(r,ps,e):_(r,ms,e*du-pu);return;case"string":{let s=Oe(e);_(r,cu,s.length),r.push(s);return}case"Uint8Array":_(r,au,e.length),r.push(e);return;case"Array":if(!e.length){r.push([gs]);return}n=ft.createCheck(n,e),_(r,gs,e.length);for(let s of e)ws(r,s,t,n);return;case"Object":case"Map":{let s=oe.Object(e,i,t,n);lt(r,s,qe,t)}return;default:{let s=oe[i];if(!s)throw new Error(`${ie} unsupported type: ${i}`);let c=s(e,i,t,n);lt(r,c,qe,t)}}}function tr(r,e,t,n){let i=n instanceof Uint8Array,o=i?new Kt(n):Zt,s=er(r,t);if(!Array.isArray(s)&&t.quickEncodeToken){let c=t.quickEncodeToken(s);if(c)return i?(o.push(c),o.toBytes()):c;let u=e[s.type.major];if(u.encodedSize){let l=u.encodedSize(s,t);if(i||(o=new ot(l)),u(o,s,t),o.chunks.length!==1)throw new Error(`Unexpected error: pre-calculated length for ${s} was wrong`);return i?o.toBytes():Ee(o.chunks[0])}}return o.reset(),lt(o,s,e,t),o.toBytes(!0)}function _e(r,e){return e=Object.assign({},ru,e),mu(e)?(Zt.reset(),ws(Zt,r,e,void 0),Zt.toBytes(!0)):tr(r,qe,e)}var gu={strict:!1,allowIndefinite:!0,allowUndefined:!0,allowBigInt:!0},rr=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=Z[e];if(t===void 0){let n=d[e];if(!n)throw new Error(`${m} no decoder for major type ${e>>>5} (byte 0x${e.toString(16).padStart(2,"0")})`);let i=e&31;t=n(this.data,this._pos,i,this.options)}return this._pos+=t.encodedLength,t}},ht=Symbol.for("DONE"),nr=Symbol.for("BREAK");function yu(r,e,t){let n=[];for(let i=0;i<r.value;i++){let o=Fe(e,t);if(o===nr){if(r.value===1/0)break;throw new Error(`${m} got unexpected break to lengthed array`)}if(o===ht)throw new Error(`${m} found array but not enough entries (got ${i}, expected ${r.value})`);n[i]=o}return n}function wu(r,e,t){let n=t.useMaps===!0,i=t.rejectDuplicateMapKeys===!0,o=n?void 0:{},s=n?new Map:void 0;for(let c=0;c<r.value;c++){let u=Fe(e,t);if(u===nr){if(r.value===1/0)break;throw new Error(`${m} got unexpected break to lengthed map`)}if(u===ht)throw new Error(`${m} found map but not enough entries (got ${c} [no key], expected ${r.value})`);if(!n&&typeof u!="string")throw new Error(`${m} non-string keys not supported (got ${typeof u})`);if(i&&(n&&s.has(u)||!n&&Object.hasOwn(o,u)))throw new Error(`${m} found repeat map key "${u}"`);let l=Fe(e,t);if(l===ht)throw new Error(`${m} found map but not enough entries (got ${c} [no value], expected ${r.value})`);n?s.set(u,l):o[u]=l}return n?s:o}function Fe(r,e){if(r.done())return ht;let t=r.next();if(a.equals(t.type,a.break))return nr;if(t.type.terminal)return t.value;if(a.equals(t.type,a.array))return yu(t,r,e);if(a.equals(t.type,a.map))return wu(t,r,e);if(a.equals(t.type,a.tag)){if(e.tags&&typeof e.tags[t.value]=="function"){let n=Fe(r,e);return e.tags[t.value](n)}throw new Error(`${m} tag not supported (${t.value})`)}throw new Error("unsupported")}function Kn(r,e){if(!(r instanceof Uint8Array))throw new Error(`${m} data to decode must be a Uint8Array`);e=Object.assign({},gu,e);let t=Ee(r),n=e.tokenizer||new rr(t,e),i=Fe(n,e);if(i===ht)throw new Error(`${m} did not find any content to decode`);if(i===nr)throw new Error(`${m} got unexpected break`);return[i,r.subarray(n.pos())]}function ee(r,e){let[t,n]=Kn(r,e);if(n.length>0)throw new Error(`${m} too many terminals, data makes no sense`);return t}var ir=class extends U{has(e){return this.find(e)!=null}find(e){return this.queue.find(t=>e.equals(t.options.peerId))}};var le="/",xs=new TextEncoder().encode(le),or=xs[0],fe=class r{_buf;constructor(e,t){if(typeof e=="string")this._buf=D(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]!==or)throw new Error("Invalid key")}toString(e="utf8"){return ge(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=xs),this._buf[0]!==or){let e=new Uint8Array(this._buf.byteLength+1);e.fill(or,0,1),e.set(this._buf,1),this._buf=e}for(;this._buf.byteLength>1&&this._buf[this._buf.byteLength-1]===or;)this._buf=this._buf.subarray(0,-1)}less(e){let t=this.list(),n=e.list();for(let i=0;i<t.length;i++){if(n.length<i+1)return!1;let o=t[i],s=n[i];if(o<s)return!0;if(o>s)return!1}return t.length<n.length}reverse(){return r.withNamespaces(this.list().slice().reverse())}namespaces(){return this.list()}baseNamespace(){let e=this.namespaces();return e[e.length-1]}list(){return this.toString().split(le).slice(1)}type(){return bu(this.baseNamespace())}name(){return xu(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(),...Eu(e.map(t=>t.namespaces()))])}};function bu(r){let e=r.split(":");return e.length<2?"":e.slice(0,-1).join(":")}function xu(r){let e=r.split(":");return e[e.length-1]}function Eu(r){return[].concat(...r)}function vu(r){return r[Symbol.asyncIterator]!=null}function _u(r){if(vu(r))return(async()=>{let n=new Uint8Array(0);for await(let i of r)n=Tn([n,i],n.length+i.length);return n})();let e=[],t=0;for(let n of r)e.push(n),t+=n.byteLength;return Tn(e,t)}var sr=_u;function ar({enumerable:r=!0,configurable:e=!1}={}){return{enumerable:r,configurable:e,writable:!1}}function*ku(r,e){if(e!=null&&typeof e=="object")if(Array.isArray(e))for(let[t,n]of e.entries()){let i=[...r,t],o=v.asCID(n);o!=null?yield[i.join("/"),o]:typeof n=="object"&&(yield*Wn(n,i))}else{let t=v.asCID(e);t!=null?yield[r.join("/"),t]:yield*Wn(e,r)}}function*Wn(r,e){if(r==null||r instanceof Uint8Array)return;let t=v.asCID(r);t!=null&&(yield[e.join("/"),t]);for(let[n,i]of Object.entries(r)){let o=[...e,n];yield*ku(o,i)}}function*Au(r,e){if(Array.isArray(e))for(let[t,n]of e.entries()){let i=[...r,t];yield i.join("/"),typeof n=="object"&&v.asCID(n)==null&&(yield*Gn(n,i))}else yield*Gn(e,r)}function*Gn(r,e){if(!(r==null||typeof r!="object"))for(let[t,n]of Object.entries(r)){let i=[...e,t];yield i.join("/"),n!=null&&!(n instanceof Uint8Array)&&typeof n=="object"&&v.asCID(n)==null&&(yield*Au(i,n))}}function Iu(r,e){let t=r;for(let[n,i]of e.entries()){if(t=t[i],t==null)throw new Error(`Object has no property at ${e.slice(0,n+1).map(s=>`[${JSON.stringify(s)}]`).join("")}`);let o=v.asCID(t);if(o!=null)return{value:o,remaining:e.slice(n+1).join("/")}}return{value:t}}var Qn=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:ar(),bytes:ar(),value:ar(),asBlock:ar()})}links(){return Wn(this.value,[])}tree(){return Gn(this.value,[])}get(e="/"){return Iu(this.value,e.split("/").filter(Boolean))}};function cr({bytes:r,cid:e,value:t,codec:n}){let i=t!==void 0?t:n?.decode(r);if(i===void 0)throw new Error('Missing required argument, must either provide "value" or "codec"');return new Qn({cid:e,bytes:r,value:i})}var ur=class extends Error{static name="AlreadyPinnedError";name="AlreadyPinnedError"},dt=class extends Error{static name="BlockPinnedError";name="BlockPinnedError"},lr=class extends Error{static name="InvalidDatastoreVersionError";name="InvalidDatastoreVersionError"},ke=class extends Error{static name="InvalidConfigurationError";name="InvalidConfigurationError"},fr=class extends AggregateError{static name="GetFailedError";name="GetFailedError"},hr=class extends AggregateError{static name="LoadBlockFailedError";name="LoadBlockFailedError"},pt=class extends Error{static name="BlockNotFoundWhileOfflineError";name="BlockNotFoundWhileOfflineError"};var _s="/pin/",Es="/pinned-block/",Jn=ae,vs=1;function dr(r){return r.version===0&&(r=r.toV1()),new fe(`${_s}${r.toString(Jn)}`)}var pr=class{datastore;blockstore;getCodec;constructor(e,t,n){this.datastore=e,this.blockstore=t,this.getCodec=n}async*add(e,t={}){let n=dr(e);if(await this.datastore.has(n))throw new ur("Already pinned");let i=Math.round(t.depth??1/0);if(i<0)throw new Te("Depth must be greater than or equal to 0");let o=new U({concurrency:vs});for await(let c of this.#e(e,o,{...t,depth:i}))await this.#i(c,u=>u.pinnedBy.find(l=>we(l,e.bytes))!=null?!1:(u.pinCount++,u.pinnedBy.push(e.bytes),!0),t),yield c;let s={depth:i,metadata:t.metadata??{}};await this.datastore.put(n,_e(s),t)}async*#e(e,t,n){if(n.depth===-1)return;let i=await this.getCodec(e.code),o=await sr(this.blockstore.get(e,n)),s=cr({bytes:o,cid:e,codec:i});yield e;for(let[,c]of s.links())yield*await t.add(async()=>this.#e(c,t,{...n,depth:n.depth-1}))}async#i(e,t,n){let i=new fe(`${Es}${Jn.encode(e.multihash.bytes)}`),o={pinCount:0,pinnedBy:[]};try{o=ee(await this.datastore.get(i,n))}catch(c){if(c.name!=="NotFoundError")throw c}if(t(o)){if(o.pinCount===0&&await this.datastore.has(i)){await this.datastore.delete(i);return}await this.datastore.put(i,_e(o),n),n.onProgress?.(new E("helia:pin:add",e))}}async*rm(e,t={}){let n=dr(e),i=await this.datastore.get(n,t),o=ee(i);await this.datastore.delete(n,t);let s=new U({concurrency:vs});for await(let c of this.#e(e,s,{...t,depth:o.depth}))await this.#i(c,u=>(u.pinCount--,u.pinnedBy=u.pinnedBy.filter(l=>we(l,e.bytes)),!0),{...t,depth:o.depth}),yield c}async*ls(e={}){for await(let{key:t,value:n}of this.datastore.query({prefix:_s+(e.cid!=null?`${e.cid.toString(ae)}`:"")},e)){let i=v.parse(t.toString().substring(5),ae),o=ee(n);yield{cid:i,...o}}}async isPinned(e,t={}){let n=new fe(`${Es}${Jn.encode(e.multihash.bytes)}`);return this.datastore.has(n,t)}async get(e,t){let n=dr(e),i=await this.datastore.get(n,t);return ee(i)}async setMetadata(e,t,n){let i=dr(e),o=await this.datastore.get(i,n),s=ee(o);s.metadata=t??{},await this.datastore.put(i,_e(s),n)}};var mr=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"}},gr=class extends Error{static name="UnknownHashAlgorithmError";constructor(e="Unknown hash algorithm"){super(e),this.name="UnknownHashAlgorithmError"}},yr=class extends Error{static name="UnknownCodecError";constructor(e="Unknown codec"){super(e),this.name="UnknownCodecError"}};var Su=5,wr=class{log;routers;providerLookupConcurrency;constructor(e,t){this.log=e.logger.forComponent("helia:routing"),this.routers=t.routers??[],this.providerLookupConcurrency=t.providerLookupConcurrency??Su,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 de(...this.routers)}async stop(){await pe(...this.routers)}async*findProviders(e,t={}){if(this.routers.length===0)throw new Ae("No content routers available");let n=new ir({concurrency:this.providerLookupConcurrency}),i=0,o=[],s=this,c=0;this.log("findProviders for %c start using routers %s",e,this.routers.map(l=>l.toString()).join(", "));let u=Ie(this.routers,"findProviders").map(async function*(l){let p=0;try{for await(let h of l.findProviders(e,t))p++,yield h}catch(h){o.push(h)}finally{s.log("router %s found %d providers for %c",l,p,e),c++,c===u.length&&n.size===0&&n.emitIdle()}});for await(let l of jt(n.toGenerator(),...u))if(l!=null){if(l.multiaddrs.length===0){if(n.find(l.id)!=null)continue;n.add(async()=>{try{let p=await this.findPeer(l.id,t);return p.multiaddrs.length===0?null:{...p,protocols:l.protocols,routing:l.routing}}catch(p){return this.log.error("could not load multiaddrs for peer %p - %e",l.id,p),null}},{peerId:l.id,signal:t.signal}).catch(p=>{this.log.error("could not load multiaddrs for peer %p - %e",l.id,p)});continue}i++,yield l}this.log("findProviders finished, found %d providers for %c",i,e)}async provide(e,t={}){if(this.routers.length===0)throw new Ae("No content routers available");await Promise.all(Ie(this.routers,"provide").map(async n=>{await n.provide(e,t)}))}async cancelReprovide(e,t={}){await Promise.all(Ie(this.routers,"cancelReprovide").map(async n=>{await n.cancelReprovide(e,t)}))}async put(e,t,n){await Promise.all(Ie(this.routers,"put").map(async i=>{await i.put(e,t,n)}))}async get(e,t){let n=[],i;try{i=await Promise.any(Ie(this.routers,"get").map(async o=>{try{return await o.get(e,t)}catch(s){this.log("router %s failed with %e",o,s),n.push(s)}}))}catch{}if(i==null)throw new fr(n,`Failed to get value key ${ge(e,"base58btc")}`);return i}async findPeer(e,t){if(this.routers.length===0)throw new Ae("No peer routers available");let n=this,i=jt(...Ie(this.routers,"findPeer").map(o=>(async function*(){try{yield await o.findPeer(e,t)}catch(s){n.log.error(s)}})()));for await(let o of i)if(o!=null)return o;throw new Et("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 jt(...Ie(this.routers,"getClosestPeers").map(i=>i.getClosestPeers(e,t))))n!=null&&(yield n)}};function Ie(r,e){return r.filter(t=>t[e]!=null)}var q=class extends Error{static name="AbortError";name="AbortError";constructor(e="The operation was aborted",...t){super(e,...t)}};async function br(r,e,t,n){let i=new q(n?.errorMessage);n?.errorCode!=null&&(i.code=n.errorCode);let o=n?.errorEvent??"error";return t?.aborted===!0?Promise.reject(i):new Promise((s,c)=>{function u(){Xn(t,"abort",h),Xn(r,e,l),Xn(r,o,p)}let l=g=>{try{if(n?.filter?.(g)===!1)return}catch(y){u(),c(y);return}u(),s(g)},p=g=>{if(u(),g instanceof Error){c(g);return}c(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.`))},h=()=>{u(),c(i)};Yn(t,"abort",h),Yn(r,e,l),Yn(r,o,p)})}function Yn(r,e,t){r!=null&&(ks(r)?r.addEventListener(e,t):r.addListener(e,t))}function Xn(r,e,t){r!=null&&(ks(r)?r.removeEventListener(e,t):r.removeListener(e,t))}function ks(r){return typeof r.addEventListener=="function"&&typeof r.removeEventListener=="function"}var xr=class extends Error{static name="QueueFullError";constructor(e="The queue was full"){super(e),this.name="QueueFullError"}};var Er=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 q)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function Tu(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var vr=class{id;fn;options;recipients;status;timeline;controller;constructor(e,t){this.id=Tu(),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 q),this.cleanup())}async join(e={}){let t=new Er(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 ce(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 Zn(r,e){let t,n=function(){let i=function(){t=void 0,r()};clearTimeout(t),t=setTimeout(i,e)};return n.start=()=>{},n.stop=()=>{clearTimeout(t)},n}var mt=class extends j{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=Zn(this.emitEmpty.bind(this),1),this.emitIdle=Zn(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 xr;let n=new vr(e,t);return this.enqueue(n),this.safeDispatchEvent("add"),this.autoStart&&this.tryToStartAnother(),n.join(t).then(i=>(this.safeDispatchEvent("success",{detail:{job:n,result:i}}),i)).catch(i=>{if(n.status==="queued"){for(let o=0;o<this.queue.length;o++)if(this.queue[o]===n){this.queue.splice(o,1);break}}throw this.safeDispatchEvent("failure",{detail:{job:n,error:i}}),i})}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(e=>{e.abort(new q)}),this.clear()}async onEmpty(e){this.size!==0&&await br(this,"empty",e?.signal)}async onSizeLessThan(e,t){this.size<e||await br(this,"next",t?.signal,{filter:()=>this.size<e})}async onIdle(e){this.pending===0&&this.size===0||await br(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=Mt({objectMode:!0}),n=u=>{u!=null?this.abort():this.clear(),t.end(u)},i=u=>{u.detail!=null&&t.push(u.detail.result)},o=u=>{n(u.detail.error)},s=()=>{n()},c=()=>{n(new q("Queue aborted"))};this.addEventListener("success",i),this.addEventListener("failure",o),this.addEventListener("idle",s),e?.signal?.addEventListener("abort",c);try{yield*t}finally{this.removeEventListener("success",i),this.removeEventListener("failure",o),this.removeEventListener("idle",s),e?.signal?.removeEventListener("abort",c),n()}}};var _r="lock:worker:request-read",kr="lock:worker:abort-read-request",Ar="lock:worker:release-read",Ir="lock:master:grant-read",Sr="lock:master:error-read",Tr="lock:worker:request-write",Lr="lock:worker:abort-write-request",Cr="lock:worker:release-write",Nr="lock:master:grant-write",Pr="lock:master:error-write",Dr="lock:worker:finalize",Rr="mortice",As={singleProcess:!1};var ei=(r,e,t,n,i,o,s,c,u)=>l=>{if(l.data==null)return;let p={type:l.data.type,name:l.data.name,identifier:l.data.identifier};p.type===i&&r.safeDispatchEvent(t,{detail:{name:p.name,identifier:p.identifier,handler:async()=>{e.postMessage({type:u,name:p.name,identifier:p.identifier}),await new Promise(h=>{let g=y=>{if(y?.data==null)return;let w={type:y.data.type,name:y.data.name,identifier:y.data.identifier};w.type===c&&w.identifier===p.identifier&&(e.removeEventListener("message",g),h())};e.addEventListener("message",g)})},onError:h=>{e.postMessage({type:s,name:p.name,identifier:p.identifier,error:{message:h.message,name:h.name,stack:h.stack}})}}}),p.type===o&&r.safeDispatchEvent(n,{detail:{name:p.name,identifier:p.identifier}}),p.type===Dr&&r.safeDispatchEvent("finalizeRequest",{detail:{name:p.name}})};var Is=(r=10)=>Math.random().toString().substring(2,r+2);var Br=class{name;channel;constructor(e){this.name=e,this.channel=new BroadcastChannel(Rr)}readLock(e){return this.sendRequest(_r,kr,Ir,Sr,Ar,e)}writeLock(e){return this.sendRequest(Tr,Lr,Nr,Pr,Cr,e)}finalize(){this.channel.postMessage({type:Dr,name:this.name}),this.channel.close()}async sendRequest(e,t,n,i,o,s){s?.signal?.throwIfAborted();let c=Is();return this.channel.postMessage({type:e,identifier:c,name:this.name}),new Promise((u,l)=>{let p=()=>{this.channel.postMessage({type:t,identifier:c,name:this.name})};s?.signal?.addEventListener("abort",p,{once:!0});let h=g=>{if(g.data?.identifier===c&&(g.data?.type===n&&(this.channel.removeEventListener("message",h),s?.signal?.removeEventListener("abort",p),u(()=>{this.channel.postMessage({type:o,identifier:c,name:this.name})})),g.data.type===i)){this.channel.removeEventListener("message",h),s?.signal?.removeEventListener("abort",p);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),l(y)}};this.channel.addEventListener("message",h)})}};var Ss=r=>{if(r=Object.assign({},As,r),!!globalThis.document||r.singleProcess){let t=new BroadcastChannel(Rr),n=new j;return t.addEventListener("message",ei(n,t,"requestReadLock","abortReadLockRequest",_r,kr,Sr,Ar,Ir)),t.addEventListener("message",ei(n,t,"requestWriteLock","abortWriteLockRequest",Tr,Lr,Pr,Cr,Nr)),n}return new Br(r.name)};var Se=new Map,gt;function Ts(r){return typeof r?.readLock=="function"&&typeof r?.writeLock=="function"}function Lu(r){if(gt==null&&(gt=Ss(r),!Ts(gt))){let e=gt;e.addEventListener("requestReadLock",t=>{let n=t.detail.name,i=t.detail.identifier,o=Se.get(n);if(o==null)return;let s=new AbortController,c=u=>{u.detail.name!==n||u.detail.identifier!==i||s.abort()};e.addEventListener("abortReadLockRequest",c),o.readLock({signal:s.signal}).then(async u=>{await t.detail.handler().finally(()=>{u()})}).catch(u=>{t.detail.onError(u)}).finally(()=>{e.removeEventListener("abortReadLockRequest",c)})}),e.addEventListener("requestWriteLock",t=>{let n=t.detail.name,i=t.detail.identifier,o=Se.get(n);if(o==null)return;let s=new AbortController,c=u=>{u.detail.name!==n||u.detail.identifier!==i||s.abort()};e.addEventListener("abortWriteLockRequest",c),o.writeLock({signal:s.signal}).then(async u=>{await t.detail.handler().finally(()=>{u()})}).catch(u=>{t.detail.onError(u)}).finally(()=>{e.removeEventListener("abortWriteLockRequest",c)})}),e.addEventListener("finalizeRequest",t=>{let n=t.detail.name,i=Se.get(n);i?.finalize()})}return gt}async function ti(r,e){let t,n,i=new Promise((s,c)=>{t=s,n=c}),o=()=>{n(new q)};return e?.signal?.addEventListener("abort",o,{once:!0}),r.add(async()=>{await new Promise(s=>{t(()=>{e?.signal?.removeEventListener("abort",o),s()})})},{signal:e?.signal}).catch(s=>{n(s)}),i}var Ls=(r,e)=>{let t=Se.get(r);if(t!=null)return t;let n=Lu(e);if(Ts(n))return t=n,Se.set(r,t),t;let i=new mt({concurrency:1}),o;return t={async readLock(s){if(o!=null)return ti(o,s);o=new mt({concurrency:e.concurrency,autoStart:!1});let c=o,u=ti(o,s);return i.add(async()=>{c.start(),await c.onIdle().then(()=>{o===c&&(o=null)})}),u},async writeLock(s){return o=null,ti(i,s)},finalize:()=>{Se.delete(r)},queue:i},Se.set(r,t),e.autoFinalize===!0&&i.addEventListener("idle",()=>{t.finalize()},{once:!0}),t};var Cu={name:"lock",concurrency:1/0,singleProcess:!1,autoFinalize:!1};function ri(r){let e=Object.assign({},Cu,r);return Ls(e.name,e)}var Ur=class{lock;child;pins;started;constructor(e,t,n={}){this.child=e,this.pins=t,this.lock=ri({singleProcess:n.holdGcLock}),this.started=!1}isStarted(){return this.started}async start(){await de(this.child),this.started=!0}async stop(){await pe(this.child),this.started=!1}unwrap(){return this.child}async put(e,t,n={}){n?.signal?.throwIfAborted();let i=await this.lock.readLock();try{return await this.child.put(e,t,n)}finally{i()}}async*putMany(e,t={}){t?.signal?.throwIfAborted();let n=await this.lock.readLock();try{yield*this.child.putMany(e,t)}finally{n()}}async*get(e,t={}){t?.signal?.throwIfAborted();let n=await this.lock.readLock();try{yield*this.child.get(e,t)}finally{n()}}async*getMany(e,t={}){t?.signal?.throwIfAborted();let n=await this.lock.readLock();try{yield*this.child.getMany(e,t)}finally{n()}}async delete(e,t={}){t?.signal?.throwIfAborted();let n=await this.lock.writeLock();try{if(await this.pins.isPinned(e))throw new dt("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 i=this;yield*this.child.deleteMany((async function*(){for await(let o of e){if(await i.pins.isPinned(o))throw new dt("Block was pinned - please unpin and try again");yield o}})(),t)}finally{n()}}async has(e,t={}){t?.signal?.throwIfAborted();let n=await this.lock.readLock();try{return await this.child.has(e,t)}finally{n()}}async*getAll(e={}){e?.signal?.throwIfAborted();let t=await this.lock.readLock();try{yield*this.child.getAll(e)}finally{t()}}createSession(e,t){return t?.signal?.throwIfAborted(),this.child.createSession(e,t)}};var ni=new fe("/version"),Cs=1;async function Ns(r){if(!await r.has(ni)){await r.put(ni,D(`${Cs}`));return}let e=await r.get(ni),t=ge(e);if(parseInt(t,10)!==Cs)throw new lr("Invalid datastore version, a datastore migration may be required")}var si={};S(si,{code:()=>oi,decode:()=>$u,decodeOptions:()=>Ou,encode:()=>zu,encodeOptions:()=>Bu,name:()=>Mu,toByteView:()=>Ds});var Ps=42;function Ds(r){return r instanceof ArrayBuffer?new Uint8Array(r,0,r.byteLength):r}function Nu(r){if(r.asCID!==r&&r["/"]!==r.bytes)return null;let e=v.asCID(r);if(!e)return null;let t=new Uint8Array(e.bytes.byteLength+1);return t.set(e.bytes,1),[new f(a.tag,Ps),new f(a.bytes,t)]}function Pu(){throw new Error("`undefined` is not supported by the IPLD Data Model and cannot be encoded")}function Du(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 ii={float64:!0,typeEncoders:{Map:Ru,Object:Nu,undefined:Pu,number:Du}},Bu={...ii,typeEncoders:{...ii.typeEncoders}};function Uu(r){if(r[0]!==0)throw new Error("Invalid CID for CBOR tag 42; expected leading 0x00");return v.decode(r.subarray(1))}var Or={allowIndefinite:!1,coerceUndefinedToNull:!0,allowNaN:!1,allowInfinity:!1,allowBigInt:!0,strict:!0,useMaps:!1,rejectDuplicateMapKeys:!0,tags:[]};Or.tags[Ps]=Uu;var Ou={...Or,tags:Or.tags.slice()},Mu="dag-cbor",oi=113,zu=r=>_e(r,ii),$u=r=>ee(Ds(r),Or);var di={};S(di,{code:()=>hi,decode:()=>Bs,encode:()=>Rs,format:()=>Yu,name:()=>Ju,parse:()=>Zu,stringify:()=>Yu});var ai=class extends Array{constructor(){super(),this.inRecursive=[]}prefix(e){let t=this.inRecursive[this.inRecursive.length-1];t&&(a.equals(t.type,a.array)&&(t.elements++,t.elements!==1&&e.push([44])),a.equals(t.type,a.map)&&(t.elements++,t.elements!==1&&(t.elements%2===1?e.push([44]):e.push([58]))))}[a.uint.major](e,t){this.prefix(e);let n=String(t.value),i=[];for(let o=0;o<n.length;o++)i[o]=n.charCodeAt(o);e.push(i)}[a.negint.major](e,t){this[a.uint.major](e,t)}[a.bytes.major](e,t){throw new Error(`${ie} unsupported type: Uint8Array`)}[a.string.major](e,t){this.prefix(e);let n=Oe(JSON.stringify(t.value));e.push(n.length>32?Ee(n):n)}[a.array.major](e,t){this.prefix(e),this.inRecursive.push({type:a.array,elements:0}),e.push([91])}[a.map.major](e,t){this.prefix(e),this.inRecursive.push({type:a.map,elements:0}),e.push([123])}[a.tag.major](e,t){}[a.float.major](e,t){if(t.type.name==="break"){let s=this.inRecursive.pop();if(s){if(a.equals(s.type,a.array))e.push([93]);else if(a.equals(s.type,a.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(`${ie} unsupported type: undefined`);if(this.prefix(e),t.type.name==="true"){e.push([116,114,117,101]);return}else if(t.type.name==="false"){e.push([102,97,108,115,101]);return}else if(t.type.name==="null"){e.push([110,117,108,108]);return}let n=String(t.value),i=[],o=!1;for(let s=0;s<n.length;s++)i[s]=n.charCodeAt(s),!o&&(i[s]===46||i[s]===101||i[s]===69)&&(o=!0);o||(i.push(46),i.push(48)),e.push(i)}};function qu(r,e){if(Array.isArray(r[0])||Array.isArray(e[0]))throw new Error(`${ie} complex map keys are not supported`);let t=r[0],n=e[0];if(t.type!==a.string||n.type!==a.string)throw new Error(`${ie} non-string map keys are not supported`);if(t<n)return-1;if(t>n)return 1;throw new Error(`${ie} unexpected duplicate map keys, this is not supported`)}var Fu={addBreakTokens:!0,mapSorter:qu};function ci(r,e){return e=Object.assign({},Fu,e),tr(r,new ai,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,i=c=>{for(;!this.done();){let u=this.ch();if(c.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 f(a.uint,0,this._pos-e);if(i([48,49,50,51,52,53,54,55,56,57]),t&&this._pos===e+1)throw new Error(`${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++,i([48,49,50,51,52,53,54,55,56,57])}!this.done()&&(this.ch()===101||this.ch()===69)&&(n=!0,this._pos++,!this.done()&&(this.ch()===43||this.ch()===45)&&this._pos++,i([48,49,50,51,52,53,54,55,56,57]));let o=String.fromCharCode.apply(null,this.data.subarray(e,this._pos)),s=parseFloat(o);return n?new f(a.float,s,this._pos-e):this.options.allowBigInt!==!0||Number.isSafeInteger(s)?new f(s>=0?a.uint:a.negint,s,this._pos-e):new f(s>=0?a.uint:a.negint,BigInt(o),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 o=this._pos,s=0;o<this.data.length&&s<65536;o++,s++){let c=this.data[o];if(c===92||c<32||c>=128)break;if(c===34){let u=String.fromCharCode.apply(null,this.data.subarray(this._pos,o));return this._pos=o+1,new f(a.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 o=0;for(let s=0;s<4;s++){let c=this.ch();if(c>=48&&c<=57)c-=48;else if(c>=97&&c<=102)c=c-97+10;else if(c>=65&&c<=70)c=c-65+10;else throw new Error(`${m} unexpected unicode escape character at position ${this._pos}`);o=o*16+c,this._pos++}return o},i=()=>{let o=this.ch(),s=null,c=o>239?4:o>223?3:o>191?2:1;if(this._pos+c>this.data.length)throw new Error(`${m} unexpected unicode sequence at position ${this._pos}`);let u,l,p,h;switch(c){case 1:o<128&&(s=o);break;case 2:u=this.data[this._pos+1],(u&192)===128&&(h=(o&31)<<6|u&63,h>127&&(s=h));break;case 3:u=this.data[this._pos+1],l=this.data[this._pos+2],(u&192)===128&&(l&192)===128&&(h=(o&15)<<12|(u&63)<<6|l&63,h>2047&&(h<55296||h>57343)&&(s=h));break;case 4:u=this.data[this._pos+1],l=this.data[this._pos+2],p=this.data[this._pos+3],(u&192)===128&&(l&192)===128&&(p&192)===128&&(h=(o&15)<<18|(u&63)<<12|(l&63)<<6|p&63,h>65535&&h<1114112&&(s=h))}s===null?(s=65533,c=1):s>65535&&(s-=65536,t.push(s>>>10&1023|55296),s=56320|s&1023),t.push(s),this._pos+=c};for(;!this.done();){let o=this.ch(),s;switch(o){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 f(a.string,bo(t),this._pos-e);default:if(o<32)throw new Error(`${m} invalid control character at position ${this._pos}`);o<128?(t.push(o),this._pos++):i()}}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 f(a.map,1/0,1);case 91:return this.modeStack.push("array-start"),this._pos++,new f(a.array,1/0,1);case 34:return this.parseString();case 110:return this.expect([110,117,108,108]),new f(a.null,null,4);case 102:return this.expect([102,97,108,115,101]),new f(a.false,!1,5);case 116:return this.expect([116,114,117,101]),new f(a.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 f(a.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 f(a.break,void 0,1)):(this.modeStack.push("array-value"),this.skipWhitespace(),this.parseValue());case"obj-key":if(this.ch()===125)return this.modeStack.pop(),this._pos++,this.skipWhitespace(),new f(a.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 f(a.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 ui(r,e){return e=Object.assign({tokenizer:new je(r,e)},e),ee(r,e)}function Hu(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=v.asCID(r);if(!e)return null;let t=e.toString();return[new f(a.map,1/0,1),new f(a.string,"/",1),new f(a.string,t,t.length),new f(a.break,void 0,1)]}function Mr(r){let e=Ne.encode(r).slice(1);return[new f(a.map,1/0,1),new f(a.string,"/",1),new f(a.map,1/0,1),new f(a.string,"bytes",5),new f(a.string,e,e.length),new f(a.break,void 0,1),new f(a.break,void 0,1)]}function te(r){return Mr(new Uint8Array(r.buffer,r.byteOffset,r.byteLength))}function Ku(r){return Mr(new Uint8Array(r))}function Wu(){throw new Error("`undefined` is not supported by the IPLD Data Model and cannot be encoded")}function Gu(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 Qu={typeEncoders:{Object:Vu,Buffer:Mr,Uint8Array:Mr,Int8Array:te,Uint16Array:te,Int16Array:te,Uint32Array:te,Int32Array:te,Float32Array:te,Float64Array:te,Uint8ClampedArray:te,BigInt64Array:te,BigUint64Array:te,DataView:te,ArrayBuffer:Ku,undefined:Wu,number:Gu}},li=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(a.equals(e.type,a.map)){let t=this._next();if(a.equals(t.type,a.string)&&t.value==="/"){let n=this._next();if(a.equals(n.type,a.string)){let i=this._next();if(!a.equals(i.type,a.break))throw new Error("Invalid encoded CID form");return this.tokenBuffer.push(n),new f(a.tag,42,0)}if(a.equals(n.type,a.map)){let i=this._next();if(a.equals(i.type,a.string)&&i.value==="bytes"){let o=this._next();if(a.equals(o.type,a.string)){for(let c=0;c<2;c++){let u=this._next();if(!a.equals(u.type,a.break))throw new Error("Invalid encoded Bytes form")}let s=Ne.decode(`m${o.value}`);return new f(a.bytes,s,o.value.length)}this.tokenBuffer.push(o)}this.tokenBuffer.push(i)}this.tokenBuffer.push(n)}this.tokenBuffer.push(t)}return e}},fi={allowIndefinite:!1,allowUndefined:!1,allowNaN:!1,allowInfinity:!1,allowBigInt:!0,strict:!0,useMaps:!1,rejectDuplicateMapKeys:!0,tags:[]};fi.tags[42]=v.parse;var Ju="dag-json",hi=297,Rs=r=>ci(r,Qu),Bs=r=>{let e=Hu(r),t=Object.assign(fi,{tokenizer:new li(e,fi)});return ui(e,t)},Yu=r=>Xu.decode(Rs(r));var Xu=new TextDecoder,Zu=r=>Bs(el.encode(r)),el=new TextEncoder;var bi={};S(bi,{code:()=>wi,createLink:()=>Vs,createNode:()=>Hs,decode:()=>dl,encode:()=>hl,name:()=>fl,prepare:()=>gi,validate:()=>yi});var tl=new TextDecoder;function pi(r,e){let t=0;for(let n=0;;n+=7){if(n>=64)throw new Error("protobuf: varint overflow");if(e>=r.length)throw new Error("protobuf: unexpected end of data");let i=r[e++];if(t+=n<28?(i&127)<<n:(i&127)*2**n,i<128)break}return[t,e]}function zr(r,e){let t;[t,e]=pi(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 Us(r,e){let t;return[t,e]=pi(r,e),[t&7,t>>3,e]}function rl(r){let e={},t=r.length,n=0;for(;n<t;){let i,o;if([i,o,n]=Us(r,n),o===1){if(e.Hash)throw new Error("protobuf: (PBLink) duplicate Hash section");if(i!==2)throw new Error(`protobuf: (PBLink) wrong wireType (${i}) for Hash`);if(e.Name!==void 0)throw new Error("protobuf: (PBLink) invalid order, found Name before Hash");if(e.Tsize!==void 0)throw new Error("protobuf: (PBLink) invalid order, found Tsize before Hash");[e.Hash,n]=zr(r,n)}else if(o===2){if(e.Name!==void 0)throw new Error("protobuf: (PBLink) duplicate Name section");if(i!==2)throw new Error(`protobuf: (PBLink) wrong wireType (${i}) for Name`);if(e.Tsize!==void 0)throw new Error("protobuf: (PBLink) invalid order, found Tsize before Name");let s;[s,n]=zr(r,n),e.Name=tl.decode(s)}else if(o===3){if(e.Tsize!==void 0)throw new Error("protobuf: (PBLink) duplicate Tsize section");if(i!==0)throw new Error(`protobuf: (PBLink) wrong wireType (${i}) for Tsize`);[e.Tsize,n]=pi(r,n)}else throw new Error(`protobuf: (PBLink) invalid fieldNumber, expected 1, 2 or 3, got ${o}`)}if(n>t)throw new Error("protobuf: (PBLink) unexpected end of data");return e}function Os(r){let e=r.length,t=0,n,i=!1,o;for(;t<e;){let c,u;if([c,u,t]=Us(r,t),c!==2)throw new Error(`protobuf: (PBNode) invalid wireType, expected 2, got ${c}`);if(u===1){if(o)throw new Error("protobuf: (PBNode) duplicate Data section");[o,t]=zr(r,t),n&&(i=!0)}else if(u===2){if(i)throw new Error("protobuf: (PBNode) duplicate Links section");n||(n=[]);let l;[l,t]=zr(r,t),n.push(rl(l))}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 o&&(s.Data=o),s.Links=n||[],s}var zs=new TextEncoder,Ms=2**32,nl=2**31;function il(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=yt(e,t,r.Tsize)-1,e[t]=24}if(typeof r.Name=="string"){let n=zs.encode(r.Name);t-=n.length,e.set(n,t),t=yt(e,t,n.length)-1,e[t]=18}return r.Hash&&(t-=r.Hash.length,e.set(r.Hash,t),t=yt(e,t,r.Hash.length)-1,e[t]=10),e.length-t}function $s(r){let e=sl(r),t=new Uint8Array(e),n=e;if(r.Data&&(n-=r.Data.length,t.set(r.Data,n),n=yt(t,n,r.Data.length)-1,t[n]=10),r.Links)for(let i=r.Links.length-1;i>=0;i--){let o=il(r.Links[i],t.subarray(0,n));n-=o,n=yt(t,n,o)-1,t[n]=18}return t}function ol(r){let e=0;if(r.Hash){let t=r.Hash.length;e+=1+t+He(t)}if(typeof r.Name=="string"){let t=zs.encode(r.Name).length;e+=1+t+He(t)}return typeof r.Tsize=="number"&&(e+=1+He(r.Tsize)),e}function sl(r){let e=0;if(r.Data){let t=r.Data.length;e+=1+t+He(t)}if(r.Links)for(let t of r.Links){let n=ol(t);e+=1+n+He(n)}return e}function yt(r,e,t){e-=He(t);let n=e;for(;t>=nl;)r[e++]=t&127|128,t/=128;for(;t>=128;)r[e++]=t&127|128,t>>>=7;return r[e]=t,n}function He(r){return r%2===0&&r++,Math.floor((al(r)+6)/7)}function al(r){let e=0;return r>=Ms&&(r=Math.floor(r/Ms),e=32),r>=65536&&(r>>>=16,e+=16),r>=256&&(r>>>=8,e+=8),e+cl[r]}var cl=[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 ul=["Data","Links"],ll=["Hash","Name","Tsize"],mi=new TextEncoder;function Fs(r,e){if(r===e)return 0;let t=r.Name?mi.encode(r.Name):[],n=e.Name?mi.encode(e.Name):[],i=t.length,o=n.length;for(let s=0,c=Math.min(i,o);s<c;++s)if(t[s]!==n[s]){i=t[s],o=n[s];break}return i<o?-1:o<i?1:0}function qs(r,e){return!Object.keys(r).some(t=>!e.includes(t))}function js(r){if(typeof r.asCID=="object"){let t=v.asCID(r);if(!t)throw new TypeError("Invalid DAG-PB form");return{Hash:t}}if(typeof r!="object"||Array.isArray(r))throw new TypeError("Invalid DAG-PB form");let e={};if(r.Hash){let t=v.asCID(r.Hash);try{t||(typeof r.Hash=="string"?t=v.parse(r.Hash):r.Hash instanceof Uint8Array&&(t=v.decode(r.Hash)))}catch(n){throw new TypeError(`Invalid DAG-PB form: ${n.message}`)}t&&(e.Hash=t)}if(!e.Hash)throw new TypeError("Invalid DAG-PB form");return typeof r.Name=="string"&&(e.Name=r.Name),typeof r.Tsize=="number"&&(e.Tsize=r.Tsize),e}function gi(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=mi.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(js),e.Links.sort(Fs);else throw new TypeError("Invalid DAG-PB form");else e.Links=[];return e}function yi(r){if(!r||typeof r!="object"||Array.isArray(r)||r instanceof Uint8Array||r["/"]&&r["/"]===r.bytes)throw new TypeError("Invalid DAG-PB form");if(!qs(r,ul))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(!qs(t,ll))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&&Fs(t,r.Links[e-1])===-1)throw new TypeError("Invalid DAG-PB form (links must be sorted by Name bytes)")}}function Hs(r,e=[]){return gi({Data:r,Links:e})}function Vs(r,e,t){return js({Hash:t,Name:r,Tsize:e})}function Ks(r){return r instanceof ArrayBuffer?new Uint8Array(r,0,r.byteLength):r}var fl="dag-pb",wi=112;function hl(r){yi(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),$s(e)}function dl(r){let e=Ks(r),t=Os(e),n={};return t.Data&&(n.Data=t.Data),t.Links&&(n.Links=t.Links.map(i=>{let o={};try{o.Hash=v.decode(i.Hash)}catch{}if(!o.Hash)throw new Error("Invalid Hash field found in link, expected CID");return i.Name!==void 0&&(o.Name=i.Name),i.Tsize!==void 0&&(o.Tsize=i.Tsize),o})),n}function Ve(r){return r?.then!=null}function Ws(r=[],e){let t={[wi]:bi,[gn]:St,[oi]:si,[hi]:di,[mn]:It};return r.forEach(n=>{t[n.code]=n}),async n=>{let i=t[n];if(i==null&&e!=null){let o=e(n);Ve(o)?i=await o:i=o,t[i.code]=i}if(i!=null)return i;throw new yr(`Could not load codec for ${n}`)}}function Gs(r=[],e){let t={[Ct.code]:Ct,[Nt.code]:Nt,[Lt.code]:Lt};return r.forEach(n=>{t[n.code]=n}),async n=>{let i=t[n];if(i==null&&e!=null){let o=e(n);Ve(o)?i=await o:i=o,t[i.code]=i}if(i!=null)return i;throw new gr(`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 $r=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 qr=class{has(e,t){return Promise.reject(new Error(".has is not implemented"))}put(e,t,n){return Promise.reject(new Error(".put is not implemented"))}async*putMany(e,t){for await(let{cid:n,bytes:i}of e)await this.put(n,i,t),yield n}get(e,t){throw new Error(".get is not implemented")}async*getMany(e,t){for await(let n of e)yield{cid:n,bytes:this.get(n,t)}}delete(e,t){return Promise.reject(new Error(".delete is not implemented"))}async*deleteMany(e,t){for await(let n of e)await this.delete(n,t),yield n}async*getAll(e){throw new Error(".getAll is not implemented")}};var Fr=0,Ke=class extends Error{static name="IdentityHashDigestTooLongError";name="IdentityHashDigestTooLongError"},jr=class extends qr{child;maxDigestLength;constructor(e,t){super(),this.child=e,this.maxDigestLength=t?.maxDigestLength}put(e,t,n){if(e.multihash.code===Fr){if(this.maxDigestLength!=null&&e.multihash.digest.byteLength>this.maxDigestLength)throw new Ke(`Identity digest too long - ${e.multihash.digest.byteLength} > this.maxDigestLength`);return n?.signal?.throwIfAborted(),e}return this.child==null?(n?.signal?.throwIfAborted(),e):this.child.put(e,t,n)}async*get(e,t){if(e.multihash.code===Fr){if(this.maxDigestLength!=null&&e.multihash.digest.byteLength>this.maxDigestLength)throw new Ke(`Identity digest too long - ${e.multihash.digest.byteLength} > this.maxDigestLength`);t?.signal?.throwIfAborted(),yield e.multihash.digest;return}if(this.child==null)throw t?.signal?.throwIfAborted(),new $r;yield*this.child.get(e,t)}has(e,t){if(e.multihash.code===Fr){if(this.maxDigestLength!=null&&e.multihash.digest.byteLength>this.maxDigestLength)throw new Ke(`Identity digest too long - ${e.multihash.digest.byteLength} > this.maxDigestLength`);return t?.signal?.throwIfAborted(),!0}return this.child==null?(t?.signal?.throwIfAborted(),!1):this.child.has(e,t)}delete(e,t){if(e.code===Fr){if(this.maxDigestLength!=null&&e.multihash.digest.byteLength>this.maxDigestLength)throw new Ke(`Identity digest too long - ${e.multihash.digest.byteLength} > this.maxDigestLength`);t?.signal?.throwIfAborted();return}if(this.child!=null)return this.child.delete(e,t)}async*getAll(e){this.child!=null&&(yield*this.child.getAll(e)),e?.signal?.throwIfAborted()}};function pl(r){let[e,t]=r[Symbol.asyncIterator]!=null?[r[Symbol.asyncIterator](),Symbol.asyncIterator]:[r[Symbol.iterator](),Symbol.iterator],n=[];return{peek:()=>e.next(),push:i=>{n.push(i)},next:()=>n.length>0?{done:!1,value:n.shift()}:e.next(),[t](){return this}}}var Hr=pl;function ml(r){return r[Symbol.asyncIterator]!=null}function gl(r,e){let t=0;if(ml(r))return(async function*(){for await(let u of r)await e(u,t++)&&(yield u)})();let n=Hr(r),{value:i,done:o}=n.next();if(o===!0)return(function*(){})();let s=e(i,t++);if(typeof s.then=="function")return(async function*(){await s&&(yield i);for(let u of n)await e(u,t++)&&(yield u)})();let c=e;return(function*(){s===!0&&(yield i);for(let u of n)c(u,t++)&&(yield u)})()}var Vr=gl;function yl(r){return r[Symbol.asyncIterator]!=null}function Qs(r){return r?.then!=null}function wl(r,e){let t=0;if(yl(r))return(async function*(){for await(let u of r){let l=e(u,t++);Qs(l)&&await l,yield u}})();let n=Hr(r),{value:i,done:o}=n.next();if(o===!0)return(function*(){})();let s=e(i,t++);if(typeof s?.then=="function")return(async function*(){await s,yield i;for(let u of n){let l=e(u,t++);Qs(l)&&await l,yield u}})();let c=e;return(function*(){yield i;for(let u of n)c(u,t++),yield u})()}var xi=wl;var xl=128,We=class{child;getHasher;log;logger;blockBrokers;constructor(e,t={}){this.log=e.logger.forComponent("helia:networked-storage"),this.logger=e.logger,this.blockBrokers=e.blockBrokers,this.child=new jr(e.blockstore,{maxDigestLength:t.maxIdentityHashDigestLength??xl}),this.getHasher=e.getHasher}async put(e,t,n={}){return await this.child.has(e,n)?(n.onProgress?.(new E("blocks:put:duplicate",e)),e):(n.onProgress?.(new E("blocks:put:providers:notify",e)),await Promise.all(this.blockBrokers.map(async i=>i.announce?.(e,n))),n.onProgress?.(new E("blocks:put:blockstore:put",e)),this.child.put(e,t,n))}async*putMany(e,t={}){let n=Vr(e,async({cid:o})=>{let s=await this.child.has(o,t);return s&&t.onProgress?.(new E("blocks:put-many:duplicate",o)),!s}),i=xi(n,async({cid:o})=>{t.onProgress?.(new E("blocks:put-many:providers:notify",o)),await Promise.all(this.blockBrokers.map(async s=>s.announce?.(o,t)))});t.onProgress?.(new E("blocks:put-many:blockstore:put-many")),yield*this.child.putMany(i,t)}async*get(e,t={}){let n=await this.child.has(e,t),i=t.offline===!0;if(!n){if(i)throw new pt("The block was present in the blockstore and the node is running offline so cannot fetch it");let o=await this.getHasher(e.multihash.code);t?.signal?.throwIfAborted(),t.onProgress?.(new E("blocks:get:providers:get",e));let s=await Js(e,this.blockBrokers,o,{...t,log:this.log});t.onProgress?.(new E("blocks:get:blockstore:put",e)),await this.child.put(e,s,t),t.onProgress?.(new E("blocks:get:providers:notify",e)),await Promise.all(this.blockBrokers.map(async c=>c.announce?.(e,t))),yield s;return}t.onProgress?.(new E("blocks:get:blockstore:get",e)),yield*this.child.get(e,t)}async*getMany(e,t={}){t.onProgress?.(new E("blocks:get-many:blockstore:get-many")),yield*this.child.getMany(xi(e,async n=>{let i=await this.child.has(n,t),o=t.offline===!0;if(!i){if(o)throw new pt("The block was present in the blockstore and the node is running offline so cannot fetch it");let s=await this.getHasher(n.multihash.code);t?.signal?.throwIfAborted(),t.onProgress?.(new E("blocks:get-many:providers:get",n));let c=await Js(n,this.blockBrokers,s,{...t,log:this.log});t.onProgress?.(new E("blocks:get-many:blockstore:put",n)),await this.child.put(n,c,t),t.onProgress?.(new E("blocks:get-many:providers:notify",n)),await Promise.all(this.blockBrokers.map(async u=>u.announce?.(n,t)))}}))}async delete(e,t={}){t.onProgress?.(new E("blocks:delete:blockstore:delete",e)),await this.child.delete(e,t)}async*deleteMany(e,t={}){t.onProgress?.(new E("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 E("blocks:get-all:blockstore:get-many")),yield*this.child.getAll(e)}};async function Js(r,e,t,n){let i=vl(r,t),o=new AbortController,s=Y([o.signal,n.signal]);o.signal;let c=[];for(let u of e)El(u)&&c.push(u);if(c.length===0)throw new ke(`No block brokers capable of retrieving blocks are configured, the CID ${r} cannot be fetched from the network`);try{return await Promise.any(c.map(async u=>{try{let l=!1,p=await u.retrieve(r,{...n,signal:s,validateFn:async h=>{await i(h),n.signal?.throwIfAborted(),l=!0}});return l||(await i(p),n.signal?.throwIfAborted()),p}catch(l){throw n.log.error("could not retrieve verified block for %c from %s - %e",r,u.name,l),l}}))}catch(u){throw new hr(u.errors,`Failed to load block for ${r}`)}finally{o.abort(),s.clear()}}function El(r){return typeof r.retrieve=="function"}var vl=(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,i=e.digest(t,{truncate:r.multihash.digest.byteLength});if(Ve(i)?n=await i:n=i,!we(n.digest,r.multihash.digest))throw new vt("Hash of downloaded block did not match multihash from passed CID")}};var Kr=class extends We{closeController;constructor(e,t){super(e),this.closeController=new AbortController,this.closeController.signal,this.log=e.logger.forComponent(`helia:session-storage:${t.root}`)}close(){this.closeController.abort()}async addPeer(e,t){await Promise.all(this.blockBrokers.map(n=>n.addPeer(e,t)))}async put(e,t,n={}){let i=Y([this.closeController.signal,n.signal]);try{return await super.put(e,t,{...n,signal:i})}finally{i.clear()}}async*putMany(e,t={}){let n=Y([this.closeController.signal,t.signal]);try{yield*super.putMany(e,{...t,signal:n})}finally{n.clear()}}async*get(e,t={}){let n=Y([this.closeController.signal,t.signal]);try{yield*super.get(e,{...t,signal:n})}finally{n.clear()}}async*getMany(e,t={}){let n=Y([this.closeController.signal,t.signal]);try{yield*super.getMany(e,{...t,signal:n})}finally{n.clear()}}async delete(e,t={}){let n=Y([this.closeController.signal,t.signal]);try{await super.delete(e,{...t,signal:n})}finally{n.clear()}}async*deleteMany(e,t={}){let n=Y([this.closeController.signal,t.signal]);try{yield*super.deleteMany(e,{...t,signal:n})}finally{n.clear()}}async has(e,t={}){let n=Y([this.closeController.signal,t.signal]);try{return await super.has(e,{...t,signal:n})}finally{n.clear()}}async*getAll(e={}){let t=Y([this.closeController.signal,e.signal]);try{yield*super.getAll({...e,signal:t})}finally{t.clear()}}};var Wr=class extends We{started;constructor(e,t={}){super(e,t),this.started=!1}isStarted(){return this.started}async start(){await de(this.child,...this.blockBrokers),this.started=!0}async stop(){await pe(this.child,...this.blockBrokers),this.started=!1}unwrap(){return this.child}createSession(e,t){if(this.blockBrokers.length===0)throw new ke("No block brokers configured");let n=this.blockBrokers.map(i=>i.createSession?.(t)).filter(i=>i!=null);if(n.length===0)throw new ke(`No configured block brokers support sessions - tried ${this.blockBrokers.map(i=>i.name).join(", ")}`);return new Kr({blockstore:this.child,blockBrokers:n,getHasher:this.getHasher,logger:this.logger},{root:e})}};var Gr=class extends j{initialPeerSearchComplete;requests;logName;log;logger;minProviders;maxProviders;providers;evictionFilter;initialProviders;constructor(e,t){super(),this.logName=t.name,this.logger=e.logger,this.log=e.logger.forComponent(this.logName),this.requests=new Map,this.minProviders=t.minProviders??1,this.maxProviders=t.maxProviders??5,this.providers=[],this.evictionFilter=Pn(this.maxProviders),this.initialProviders=t.providers??[]}async retrieve(e,t={}){let n=Ne.encode(e.multihash.bytes),i=this.requests.get(n);if(i!=null)return this.log("join existing request for %c",e),i.observers++,i.promise;let o=R(),s={promise:o.promise,observers:1};if(this.requests.set(n,s),this.providers.length===0){let h=!1;this.initialPeerSearchComplete==null&&(h=!0,this.log=this.logger.forComponent(`${this.logName}:${e}`),this.initialPeerSearchComplete=this.findProviders(e,this.minProviders,t));try{await ce(this.initialPeerSearchComplete,t.signal),h&&this.log("found initial session peers for %c",e)}catch(g){throw h&&this.log("failed to find initial session peers for %c - %e",e,g),this.requests.delete(n),s.observers>1&&o.reject(g),g}}let c=!1,u=new U({concurrency:this.maxProviders});u.addEventListener("failure",h=>{this.log.error("error querying provider %s, evicting from session - %e",h.detail.job.options.provider,h.detail.error),this.evict(h.detail.job.options.provider)}),u.addEventListener("success",h=>{c=!0,o.resolve(h.detail.result)}),u.addEventListener("idle",()=>{if(c){this.log.trace("session idle, found block");return}if(t.signal?.aborted===!0){this.log.trace("session idle, signal aborted");return}Promise.resolve().then(async()=>{this.log("no session peers had block for for %c, finding new providers",e);for(let h=0;h<this.minProviders&&this.providers.length!==0;h++){let g=this.providers[Math.floor(Math.random()*this.providers.length)];this.evict(g)}await this.findProviders(e,this.minProviders,t),this.log("found new providers re-retrieving %c",e),this.requests.delete(n),o.resolve(await this.retrieve(e,t))}).catch(h=>{this.log.error("could not find new providers for %c - %e",e,h),o.reject(h)})});let l=h=>{u.add(async()=>this.queryProvider(e,h.detail,t),{provider:h.detail}).catch(g=>{t.signal?.aborted!==!0&&this.log.error("error retrieving session block for %c - %e",e,g)})};this.addEventListener("provider",l),Promise.all([...this.providers].map(async h=>u.add(async()=>this.queryProvider(e,h,t),{provider:h}))).catch(h=>{t.signal?.aborted!==!0&&this.log.error("error retrieving session block for %c - %e",e,h)});let p=()=>{o.reject(new W(t.signal?.reason??"Session aborted")),u.abort()};t.signal?.addEventListener("abort",p);try{return await ce(o.promise,t.signal)}finally{this.removeEventListener("provider",l),t.signal?.removeEventListener("abort",p),u.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 addPeer(e,t){let n=await this.convertToProvider(e,t);n==null||this.hasProvider(n)||(this.providers.push(n),this.safeDispatchEvent("provider",{detail:n}))}async findProviders(e,t,n){let i=R(),o=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(;o<t&&this.initialProviders.length>0;){let s=this.initialProviders.pop();if(s==null)break;let c=await this.convertToProvider(s,n);if(n.signal?.aborted===!0)break;if(c!=null&&!this.hasProvider(c)&&(this.log("found %d/%d new providers",o,this.maxProviders),this.providers.push(c),this.safeDispatchEvent("provider",{detail:c}),o++,o===t&&(this.log("session is ready"),i.resolve()),this.providers.length===this.maxProviders)){this.log("found max session peers",o);break}}if(o<this.maxProviders)for await(let s of this.findNewProviders(e,n)){if(o===this.maxProviders||n.signal?.aborted===!0)break;if(!this.hasProvider(s)&&(this.log("found %d/%d new providers",o,this.maxProviders),this.providers.push(s),this.safeDispatchEvent("provider",{detail:s}),o++,o===t&&(this.log("session is ready"),i.resolve()),this.providers.length===this.maxProviders)){this.log("found max session peers",o);break}}if(this.log("found %d/%d new session peers",o,this.maxProviders),o<t)throw new mr(`Found ${o} of ${t} ${this.name} providers for ${e}`)}).catch(s=>{this.log.error("error searching routing for potential session peers for %c - %e",e,s),i.reject(s)}),i.promise}};function Ys(r){return e=>new Ei(e,r)}function Xs(r){return e=>new vi(e,r)}function Zs(r){return e=>new _i(e,r)}var wt=class{components;constructor(e,t={}){this.components=e}async*walk(e,t){let n=this.getQueue(),i=Vr(n.toGenerator(t),c=>c!=null),o=!1,s=async c=>{let u=c.cid,l=await sr(this.components.blockstore.get(u,c)),p=cr({cid:u,bytes:l,codec:await this.components.getCodec(u.code)});for(let[,h]of p.links())t?.includeChild?.(h,p)!==!1&&n.add(s,{...c,cid:h,depth:c.depth+1,path:[...c.path,h]}).catch(g=>{o||i.throw(g)});return{block:p,depth:c.depth,path:c.path}};n.add(s,{...t,cid:e,depth:0,path:[e]}).catch(c=>{o||i.throw(c)});try{yield*i}finally{o=!0,n.abort()}}},Ei=class extends wt{getQueue(){return new U({concurrency:1,sort:(e,t)=>e.options.depth===t.options.depth?0:e.options.depth<t.options.depth?1:-1})}},vi=class extends wt{getQueue(){return new U({concurrency:1,sort:(e,t)=>e.options.depth===t.options.depth?0:e.options.depth<t.options.depth?-1:1})}},_i=class extends wt{getQueue(){return new U({concurrency:1})}};var ki=class{libp2p;blockstore;datastore;events;pins;logger;routing;getCodec;getHasher;dns;metrics;log;constructor(e){this.logger=e.logger??e.libp2p.logger,this.log=this.logger.forComponent("helia"),this.getHasher=Gs(e.hashers,e.loadHasher),this.getCodec=Ws(e.codecs,e.loadCodec),this.dns=e.dns??ao(),this.metrics=e.metrics,this.libp2p=e.libp2p,this.events=new j;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 wr(t,{routers:(e.routers??[]).flatMap(i=>{typeof i=="function"&&(i=i(t));let o=[i],s=Al(i);s!=null&&o.push(s);let c=Il(i);return c!=null&&o.push(c),o}),providerLookupConcurrency:e.providerLookupConcurrency}),t.blockBrokers=e.blockBrokers.map(i=>i(t));let n=new Wr(t,e);this.pins=new pr(e.datastore,n,this.getCodec),this.blockstore=new Ur(n,this.pins,{holdGcLock:e.holdGcLock??!0}),this.datastore=e.datastore}async start(){await Ns(this.datastore),await de(this.blockstore,this.datastore,this.routing,this.libp2p),this.events.dispatchEvent(new CustomEvent("start",{detail:this}))}async stop(){await pe(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,i=this.blockstore.unwrap();this.log("gc start"),await co(i.deleteMany((async function*(){for await(let{cid:o}of i.getAll())try{if(await n.pins.isPinned(o,e))continue;yield o,e.onProgress?.(new E("helia:gc:deleted",o))}catch(s){n.log.error("error during gc - %e",s),e.onProgress?.(new E("helia:gc:error",s))}})()))}finally{t()}this.log("gc finished")}};function Al(r){return r?.[Ti]}function Il(r){return r?.[Li]}return oa(Sl);})();
2
+ "use strict";var HeliaUtils=(()=>{var ha=Object.create;var xt=Object.defineProperty;var da=Object.getOwnPropertyDescriptor;var pa=Object.getOwnPropertyNames;var ma=Object.getPrototypeOf,ga=Object.prototype.hasOwnProperty;var Li=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),T=(r,e)=>{for(var t in e)xt(r,t,{get:e[t],enumerable:!0})},Ni=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of pa(e))!ga.call(r,i)&&i!==t&&xt(r,i,{get:()=>e[i],enumerable:!(n=da(e,i))||n.enumerable});return r};var Pi=(r,e,t)=>(t=r!=null?ha(ma(r)):{},Ni(e||!r||!r.__esModule?xt(t,"default",{value:r,enumerable:!0}):t,r)),ya=r=>Ni(xt({},"__esModule",{value:!0}),r);var Gi=Li((Nf,cn)=>{"use strict";var Ya=Object.prototype.hasOwnProperty,U="~";function Qe(){}Object.create&&(Qe.prototype=Object.create(null),new Qe().__proto__||(U=!1));function Xa(r,e,t){this.fn=r,this.context=e,this.once=t||!1}function Wi(r,e,t,n,i){if(typeof t!="function")throw new TypeError("The listener must be a function");var o=new Xa(t,n||r,i),s=U?U+e:e;return r._events[s]?r._events[s].fn?r._events[s]=[r._events[s],o]:r._events[s].push(o):(r._events[s]=o,r._eventsCount++),r}function It(r,e){--r._eventsCount===0?r._events=new Qe:delete r._events[e]}function P(){this._events=new Qe,this._eventsCount=0}P.prototype.eventNames=function(){var e=[],t,n;if(this._eventsCount===0)return e;for(n in t=this._events)Ya.call(t,n)&&e.push(U?n.slice(1):n);return Object.getOwnPropertySymbols?e.concat(Object.getOwnPropertySymbols(t)):e};P.prototype.listeners=function(e){var t=U?U+e:e,n=this._events[t];if(!n)return[];if(n.fn)return[n.fn];for(var i=0,o=n.length,s=new Array(o);i<o;i++)s[i]=n[i].fn;return s};P.prototype.listenerCount=function(e){var t=U?U+e:e,n=this._events[t];return n?n.fn?1:n.length:0};P.prototype.emit=function(e,t,n,i,o,s){var a=U?U+e:e;if(!this._events[a])return!1;var u=this._events[a],h=arguments.length,f,l;if(u.fn){switch(u.once&&this.removeListener(e,u.fn,void 0,!0),h){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,i),!0;case 5:return u.fn.call(u.context,t,n,i,o),!0;case 6:return u.fn.call(u.context,t,n,i,o,s),!0}for(l=1,f=new Array(h-1);l<h;l++)f[l-1]=arguments[l];u.fn.apply(u.context,f)}else{var m=u.length,y;for(l=0;l<m;l++)switch(u[l].once&&this.removeListener(e,u[l].fn,void 0,!0),h){case 1:u[l].fn.call(u[l].context);break;case 2:u[l].fn.call(u[l].context,t);break;case 3:u[l].fn.call(u[l].context,t,n);break;case 4:u[l].fn.call(u[l].context,t,n,i);break;default:if(!f)for(y=1,f=new Array(h-1);y<h;y++)f[y-1]=arguments[y];u[l].fn.apply(u[l].context,f)}}return!0};P.prototype.on=function(e,t,n){return Wi(this,e,t,n,!1)};P.prototype.once=function(e,t,n){return Wi(this,e,t,n,!0)};P.prototype.removeListener=function(e,t,n,i){var o=U?U+e:e;if(!this._events[o])return this;if(!t)return It(this,o),this;var s=this._events[o];if(s.fn)s.fn===t&&(!i||s.once)&&(!n||s.context===n)&&It(this,o);else{for(var a=0,u=[],h=s.length;a<h;a++)(s[a].fn!==t||i&&!s[a].once||n&&s[a].context!==n)&&u.push(s[a]);u.length?this._events[o]=u.length===1?u[0]:u:It(this,o)}return this};P.prototype.removeAllListeners=function(e){var t;return e?(t=U?U+e:e,this._events[t]&&It(this,t)):(this._events=new Qe,this._eventsCount=0),this};P.prototype.off=P.prototype.removeListener;P.prototype.addListener=P.prototype.on;P.prefixed=U;P.EventEmitter=P;typeof cn<"u"&&(cn.exports=P)});var go=Li((Fh,mo)=>{mo.exports=function(r){if(!r)throw Error("hashlru must have a max value, of type number, greater than 0");var e=0,t=Object.create(null),n=Object.create(null);function i(o,s){t[o]=s,e++,e>=r&&(e=0,n=t,t=Object.create(null))}return{has:function(o){return t[o]!==void 0||n[o]!==void 0},remove:function(o){t[o]!==void 0&&(t[o]=void 0),n[o]!==void 0&&(n[o]=void 0)},get:function(o){var s=t[o];if(s!==void 0)return s;if((s=n[o])!==void 0)return i(o,s),s},set:function(o,s){t[o]!==void 0?t[o]=s:i(o,s)},clear:function(){t=Object.create(null),n=Object.create(null)}}}});var ef={};T(ef,{AbstractSession:()=>Yr,Helia:()=>Ti,breadthFirstWalker:()=>ua,depthFirstWalker:()=>ca,naturalOrderWalker:()=>la});var Di=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 Pe=class extends Error{static name="InvalidParametersError";constructor(e="Invalid parameters"){super(e),this.name="InvalidParametersError"}};var Et=class extends Error{static name="NotFoundError";constructor(e="Not found"){super(e),this.name="NotFoundError"}};var vt=class extends Error{static name="InvalidMultihashError";constructor(e="Invalid Multihash"){super(e),this.name="InvalidMultihashError"}};var Ri=Symbol.for("@libp2p/peer-routing");function Ui(r){return r!=null&&typeof r.start=="function"&&typeof r.stop=="function"}async function pe(...r){let e=[];for(let t of r)Ui(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 me(...r){let e=[];for(let t of r)Ui(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 i=this.#e.get(e);i==null&&(i=[],this.#e.set(e,i)),i.push({callback:t,once:(n!==!0&&n!==!1&&n?.once)??!1})}removeEventListener(e,t,n){super.removeEventListener(e.toString(),t??null,n);let i=this.#e.get(e);i!=null&&(i=i.filter(({callback:o})=>o!==t),this.#e.set(e,i))}dispatchEvent(e){let t=super.dispatchEvent(e),n=this.#e.get(e.type);return n==null||(n=n.filter(({once:i})=>!i),this.#e.set(e.type,n)),t}safeDispatchEvent(e,t={}){return this.dispatchEvent(new CustomEvent(e,t))}};var nn={};T(nn,{base32:()=>ye,base32hex:()=>Sa,base32hexpad:()=>Ta,base32hexpadupper:()=>La,base32hexupper:()=>Ca,base32pad:()=>Aa,base32padupper:()=>Ia,base32upper:()=>ka,base32z:()=>Na});var cf=new Uint8Array(0);function Bi(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 Fi(r){return new TextEncoder().encode(r)}function $i(r){return new TextDecoder().decode(r)}function wa(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),n=0;n<t.length;n++)t[n]=255;for(var i=0;i<r.length;i++){var o=r.charAt(i),s=o.charCodeAt(0);if(t[s]!==255)throw new TypeError(o+" is ambiguous");t[s]=i}var a=r.length,u=r.charAt(0),h=Math.log(a)/Math.log(256),f=Math.log(256)/Math.log(a);function l(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 _=0,w=0,x=0,I=b.length;x!==I&&b[x]===0;)x++,_++;for(var S=(I-x)*f+1>>>0,D=new Uint8Array(S);x!==I;){for(var N=b[x],ce=0,R=S-1;(N!==0||ce<w)&&R!==-1;R--,ce++)N+=256*D[R]>>>0,D[R]=N%a>>>0,N=N/a>>>0;if(N!==0)throw new Error("Non-zero carry");w=ce,x++}for(var Q=S-w;Q!==S&&D[Q]===0;)Q++;for(var Ee=u.repeat(_);Q<S;++Q)Ee+=r.charAt(D[Q]);return Ee}function m(b){if(typeof b!="string")throw new TypeError("Expected String");if(b.length===0)return new Uint8Array;var _=0;if(b[_]!==" "){for(var w=0,x=0;b[_]===u;)w++,_++;for(var I=(b.length-_)*h+1>>>0,S=new Uint8Array(I);b[_];){var D=t[b.charCodeAt(_)];if(D===255)return;for(var N=0,ce=I-1;(D!==0||N<x)&&ce!==-1;ce--,N++)D+=a*S[ce]>>>0,S[ce]=D%256>>>0,D=D/256>>>0;if(D!==0)throw new Error("Non-zero carry");x=N,_++}if(b[_]!==" "){for(var R=I-x;R!==I&&S[R]===0;)R++;for(var Q=new Uint8Array(w+(I-R)),Ee=w;R!==I;)Q[Ee++]=S[R++];return Q}}}function y(b){var _=m(b);if(_)return _;throw new Error(`Non-${e} character`)}return{encode:l,decodeUnsafe:m,decode:y}}var ba=wa,xa=ba,Oi=xa;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")}},en=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,n){this.name=e,this.prefix=t;let i=t.codePointAt(0);if(i===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=i,this.baseDecode=n}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return Mi(this,e)}},tn=class{decoders;constructor(e){this.decoders=e}or(e){return Mi(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 Mi(r,e){return new tn({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var rn=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,n,i){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=i,this.encoder=new Zr(e,t,n),this.decoder=new en(e,t,i)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function De({name:r,prefix:e,encode:t,decode:n}){return new rn(r,e,t,n)}function ge({name:r,prefix:e,alphabet:t}){let{encode:n,decode:i}=Oi(t,r);return De({prefix:e,name:r,encode:n,decode:o=>Y(i(o))})}function Ea(r,e,t,n){let i=r.length;for(;r[i-1]==="=";)--i;let o=new Uint8Array(i*t/8|0),s=0,a=0,u=0;for(let h=0;h<i;++h){let f=e[r[h]];if(f===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<t|f,s+=t,s>=8&&(s-=8,o[u++]=255&a>>s)}if(s>=t||(255&a<<8-s)!==0)throw new SyntaxError("Unexpected end of data");return o}function va(r,e,t){let n=e[e.length-1]==="=",i=(1<<t)-1,o="",s=0,a=0;for(let u=0;u<r.length;++u)for(a=a<<8|r[u],s+=8;s>t;)s-=t,o+=e[i&a>>s];if(s!==0&&(o+=e[i&a<<t-s]),n)for(;(o.length*t&7)!==0;)o+="=";return o}function _a(r){let e={};for(let t=0;t<r.length;++t)e[r[t]]=t;return e}function C({name:r,prefix:e,bitsPerChar:t,alphabet:n}){let i=_a(n);return De({prefix:e,name:r,encode(o){return va(o,n,t)},decode(o){return Ea(o,i,t,r)}})}var ye=C({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),ka=C({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Aa=C({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Ia=C({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Sa=C({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Ca=C({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Ta=C({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),La=C({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Na=C({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var on={};T(on,{base58btc:()=>K,base58flickr:()=>Pa});var K=ge({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Pa=ge({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var sn={};T(sn,{base64:()=>we,base64pad:()=>Da,base64url:()=>Ra,base64urlpad:()=>Ua});var we=C({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Da=C({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Ra=C({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Ua=C({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});function Ba(r,e){if(typeof r=="string")return Fa(r);if(typeof r=="number")return Ma(r,e);throw Error(`Value provided to ms() must be a string or number. value=${JSON.stringify(r)}`)}var _t=Ba;function Fa(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,i=parseFloat(t),o=n.toLowerCase();switch(o){case"years":case"year":case"yrs":case"yr":case"y":return i*315576e5;case"months":case"month":case"mo":return i*26298e5;case"weeks":case"week":case"w":return i*6048e5;case"days":case"day":case"d":return i*864e5;case"hours":case"hour":case"hrs":case"hr":case"h":return i*36e5;case"minutes":case"minute":case"mins":case"min":case"m":return i*6e4;case"seconds":case"second":case"secs":case"sec":case"s":return i*1e3;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return i;default:throw Error(`Unknown unit "${o}" provided to ms.parse(). value=${JSON.stringify(r)}`)}}function $a(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 Oa(r){let e=Math.abs(r);return e>=315576e5?ve(r,e,315576e5,"year"):e>=26298e5?ve(r,e,26298e5,"month"):e>=6048e5?ve(r,e,6048e5,"week"):e>=864e5?ve(r,e,864e5,"day"):e>=36e5?ve(r,e,36e5,"hour"):e>=6e4?ve(r,e,6e4,"minute"):e>=1e3?ve(r,e,1e3,"second"):`${r} ms`}function Ma(r,e){if(typeof r!="number"||!Number.isFinite(r))throw Error("Value provided to ms.format() must be of type number.");return e?.long?Oa(r):$a(r)}function ve(r,e,t,n){let i=e>=t*1.5;return`${Math.round(r/t)} ${n}${i?"s":""}`}function an(r){t.debug=t,t.default=t,t.coerce=u,t.disable=o,t.enable=i,t.enabled=s,t.humanize=_t,t.destroy=h,Object.keys(r).forEach(f=>{t[f]=r[f]}),t.names=[],t.skips=[],t.formatters={};function e(f){let l=0;for(let m=0;m<f.length;m++)l=(l<<5)-l+f.charCodeAt(m),l|=0;return t.colors[Math.abs(l)%t.colors.length]}t.selectColor=e;function t(f,l){let m,y=null,b,_;function w(...x){if(!w.enabled)return;let I=w,S=Number(new Date),D=S-(m||S);I.diff=D,I.prev=m,I.curr=S,m=S,x[0]=t.coerce(x[0]),typeof x[0]!="string"&&x.unshift("%O");let N=0;x[0]=x[0].replace(/%([a-zA-Z%])/g,(R,Q)=>{if(R==="%%")return"%";N++;let Ee=t.formatters[Q];if(typeof Ee=="function"){let fa=x[N];R=Ee.call(I,fa),x.splice(N,1),N--}return R}),t.formatArgs.call(I,x),l?.onLog!=null&&l.onLog(...x),(I.log||t.log).apply(I,x)}return w.namespace=f,w.useColors=t.useColors(),w.color=t.selectColor(f),w.extend=n,w.destroy=t.destroy,Object.defineProperty(w,"enabled",{enumerable:!0,configurable:!1,get:()=>y!==null?y:(b!==t.namespaces&&(b=t.namespaces,_=t.enabled(f)),_),set:x=>{y=x}}),typeof t.init=="function"&&t.init(w),w}function n(f,l){let m=t(this.namespace+(typeof l>"u"?":":l)+f);return m.log=this.log,m}function i(f){t.save(f),t.namespaces=f,t.names=[],t.skips=[];let l,m=(typeof f=="string"?f:"").split(/[\s,]+/),y=m.length;for(l=0;l<y;l++)m[l]&&(f=m[l].replace(/\*/g,".*?"),f[0]==="-"?t.skips.push(new RegExp("^"+f.substr(1)+"$")):t.names.push(new RegExp("^"+f+"$")))}function o(){let f=[...t.names.map(a),...t.skips.map(a).map(l=>"-"+l)].join(",");return t.enable(""),f}function s(f){if(f[f.length-1]==="*")return!0;let l,m;for(l=0,m=t.skips.length;l<m;l++)if(t.skips[l].test(f))return!1;for(l=0,m=t.names.length;l<m;l++)if(t.names[l].test(f))return!0;return!1}function a(f){return f.toString().substring(2,f.toString().length-2).replace(/\.\*\?$/,"*")}function u(f){return f instanceof Error?f.stack??f.message:f}function h(){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 kt=Wa(),za=["#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 qa(){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 ja(r){if(r[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+r[0]+(this.useColors?"%c ":" ")+"+"+_t(this.diff),!this.useColors)return;let e="color: "+this.color;r.splice(1,0,e,"color: inherit");let t=0,n=0;r[0].replace(/%[a-zA-Z%]/g,i=>{i!=="%%"&&(t++,i==="%c"&&(n=t))}),r.splice(n,0,e)}var Va=console.debug??console.log??(()=>{});function Ha(r){try{r?kt?.setItem("debug",r):kt?.removeItem("debug")}catch{}}function Ka(){let r;try{r=kt?.getItem("debug")}catch{}return!r&&typeof globalThis.process<"u"&&"env"in globalThis.process&&(r=globalThis.process.env.DEBUG),r}function Wa(){try{return localStorage}catch{}}function Ga(r){r.j=function(e){try{return JSON.stringify(e)}catch(t){return"[UnexpectedJSONParseError]: "+t.message}}}var zi=an({formatArgs:ja,save:Ha,load:Ka,useColors:qa,setupFormatters:Ga,colors:za,storage:kt,log:Va});var B=zi;B.formatters.b=r=>r==null?"undefined":K.baseEncode(r);B.formatters.t=r=>r==null?"undefined":ye.baseEncode(r);B.formatters.m=r=>r==null?"undefined":we.baseEncode(r);B.formatters.p=r=>r==null?"undefined":r.toString();B.formatters.c=r=>r==null?"undefined":r.toString();B.formatters.k=r=>r==null?"undefined":r.toString();B.formatters.a=r=>r==null?"undefined":r.toString();function qi(r,e=""){let t=ji(r.message),n=ji(r.stack);return t!=null&&n!=null?n.includes(t)?`${n.split(`
3
+ `).join(`
4
+ ${e}`)}`:`${t}
5
+ ${e}${n.split(`
6
+ `).join(`
7
+ ${e}`)}`:n!=null?`${n.split(`
8
+ `).join(`
9
+ ${e}`)}`:t!=null?`${t}`:`${r.toString()}`}function Qa(r){return r instanceof AggregateError||r?.name==="AggregateError"&&Array.isArray(r.errors)}function Vi(r,e=""){if(Qa(r)){let t=qi(r,e);return r.errors.length>0?(e=`${e} `,t+=`
10
+ ${e}${r.errors.map(n=>`${Vi(n,`${e}`)}`).join(`
11
+ ${e}`)}`):t+=`
12
+ ${e}[Error list was empty]`,t.trim()}return qi(r,e)}B.formatters.e=r=>r==null?"undefined":Vi(r);function Ja(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 Hi(r){return{forComponent(e){return Ki(e,r)}}}function Ki(r,e){let t=Ja(`${r}:trace`);return B.enabled(`${r}:trace`)&&B.names.map(n=>n.toString()).find(n=>n.includes(":trace"))!=null&&(t=B(`${r}:trace`,e)),Object.assign(B(r,e),{error:B(`${r}:error`,e),trace:t,newScope:n=>Ki(`${r}:${n}`,e)})}function ji(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 At=class extends AggregateError{static name="DNSQueryFailedError";name="DNSQueryFailedError"};var un=Pi(Gi(),1);var ln=class r extends Error{name="TimeoutError";constructor(e,t){super(e,t),Error.captureStackTrace?.(this,r)}},Qi=r=>r.reason??new DOMException("This operation was aborted.","AbortError");function Je(r,e){let{milliseconds:t,fallback:n,message:i,customTimers:o={setTimeout,clearTimeout},signal:s}=e,a,u,f=new Promise((l,m)=>{if(typeof t!="number"||Math.sign(t)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${t}\``);if(s?.aborted){m(Qi(s));return}if(s&&(u=()=>{m(Qi(s))},s.addEventListener("abort",u,{once:!0})),r.then(l,m),t===Number.POSITIVE_INFINITY)return;let y=new ln;a=o.setTimeout.call(void 0,()=>{if(n){try{l(n())}catch(b){m(b)}return}typeof r.cancel=="function"&&r.cancel(),i===!1?l():i instanceof Error?m(i):(y.message=i??`Promise timed out after ${t} milliseconds`,m(y))},t)}).finally(()=>{f.clear(),u&&s&&s.removeEventListener("abort",u)});return f.clear=()=>{o.clearTimeout.call(void 0,a),a=void 0},f}function fn(r,e,t){let n=0,i=r.length;for(;i>0;){let o=Math.trunc(i/2),s=n+o;t(r[s],e)<=0?(n=++s,i-=o+1):i=o}return n}var Ye=class{#e=[];enqueue(e,t){let{priority:n=0,id:i}=t??{},o={priority:n,id:i,run:e};if(this.size===0||this.#e[this.size-1].priority>=n){this.#e.push(o);return}let s=fn(this.#e,o,(a,u)=>u.priority-a.priority);this.#e.splice(s,0,o)}setPriority(e,t){let n=this.#e.findIndex(o=>o.id===e);if(n===-1)throw new ReferenceError(`No promise function with the id "${e}" exists in the queue.`);let[i]=this.#e.splice(n,1);this.enqueue(i.run,{priority:t,id:e})}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 Xe=class extends un.default{#e;#i;#a=0;#d;#m=!1;#w=!1;#c;#I=0;#b=0;#u;#l;#s;#o=[];#n=0;#t;#S;#r=0;#g;#f;#P=1n;#y=new Map;timeout;constructor(e){if(super(),e={carryoverIntervalCount:!1,intervalCap:Number.POSITIVE_INFINITY,interval:0,concurrency:Number.POSITIVE_INFINITY,autoStart:!0,queueClass:Ye,strict:!1,...e},!(typeof e.intervalCap=="number"&&e.intervalCap>=1))throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${e.intervalCap?.toString()??""}\` (${typeof e.intervalCap})`);if(e.interval===void 0||!(Number.isFinite(e.interval)&&e.interval>=0))throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${e.interval?.toString()??""}\` (${typeof e.interval})`);if(e.strict&&e.interval===0)throw new TypeError("The `strict` option requires a non-zero `interval`");if(e.strict&&e.intervalCap===Number.POSITIVE_INFINITY)throw new TypeError("The `strict` option requires a finite `intervalCap`");if(this.#e=e.carryoverIntervalCount??e.carryoverConcurrencyCount??!1,this.#i=e.intervalCap===Number.POSITIVE_INFINITY||e.interval===0,this.#d=e.intervalCap,this.#c=e.interval,this.#s=e.strict,this.#t=new e.queueClass,this.#S=e.queueClass,this.concurrency=e.concurrency,e.timeout!==void 0&&!(Number.isFinite(e.timeout)&&e.timeout>0))throw new TypeError(`Expected \`timeout\` to be a positive finite number, got \`${e.timeout}\` (${typeof e.timeout})`);this.timeout=e.timeout,this.#f=e.autoStart===!1,this.#M()}#x(e){for(;this.#n<this.#o.length;){let n=this.#o[this.#n];if(n!==void 0&&e-n>=this.#c)this.#n++;else break}(this.#n>100&&this.#n>this.#o.length/2||this.#n===this.#o.length)&&(this.#o=this.#o.slice(this.#n),this.#n=0)}#D(e){this.#s?this.#o.push(e):this.#a++}#R(){this.#s?this.#o.length>this.#n&&this.#o.pop():this.#a>0&&this.#a--}#E(){return this.#o.length-this.#n}get#U(){return this.#i?!0:this.#s?this.#E()<this.#d:this.#a<this.#d}get#B(){return this.#r<this.#g}#F(){this.#r--,this.#r===0&&this.emit("pendingZero"),this.#k(),this.emit("next")}#$(){this.#l=void 0,this.#L(),this.#T()}#O(e){if(this.#s){if(this.#x(e),this.#E()>=this.#d){let n=this.#o[this.#n],i=this.#c-(e-n);return this.#v(i),!0}return!1}if(this.#u===void 0){let t=this.#I-e;if(t<0){if(this.#b>0){let n=e-this.#b;if(n<this.#c)return this.#v(this.#c-n),!0}this.#a=this.#e?this.#r:0}else return this.#v(t),!0}return!1}#v(e){this.#l===void 0&&(this.#l=setTimeout(()=>{this.#$()},e))}#_(){this.#u&&(clearInterval(this.#u),this.#u=void 0)}#C(){this.#l&&(clearTimeout(this.#l),this.#l=void 0)}#k(){if(this.#t.size===0){if(this.#_(),this.emit("empty"),this.#r===0){if(this.#C(),this.#s&&this.#n>0){let t=Date.now();this.#x(t)}this.emit("idle")}return!1}let e=!1;if(!this.#f){let t=Date.now(),n=!this.#O(t);if(this.#U&&this.#B){let i=this.#t.dequeue();this.#i||(this.#D(t),this.#p()),this.emit("active"),i(),n&&this.#T(),e=!0}}return e}#T(){this.#i||this.#u!==void 0||this.#s||(this.#u=setInterval(()=>{this.#L()},this.#c),this.#I=Date.now()+this.#c)}#L(){this.#s||(this.#a===0&&this.#r===0&&this.#u&&this.#_(),this.#a=this.#e?this.#r:0),this.#A(),this.#p()}#A(){for(;this.#k(););}get concurrency(){return this.#g}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.#g=e,this.#A()}setPriority(e,t){if(typeof t!="number"||!Number.isFinite(t))throw new TypeError(`Expected \`priority\` to be a finite number, got \`${t}\` (${typeof t})`);this.#t.setPriority(e,t)}async add(e,t={}){return t={timeout:this.timeout,...t,id:t.id??(this.#P++).toString()},new Promise((n,i)=>{let o=Symbol(`task-${t.id}`);this.#t.enqueue(async()=>{this.#r++,this.#y.set(o,{id:t.id,priority:t.priority??0,startTime:Date.now(),timeout:t.timeout});let s;try{try{t.signal?.throwIfAborted()}catch(h){throw this.#z(),this.#y.delete(o),h}this.#b=Date.now();let a=e({signal:t.signal});if(t.timeout&&(a=Je(Promise.resolve(a),{milliseconds:t.timeout,message:`Task timed out after ${t.timeout}ms (queue has ${this.#r} running, ${this.#t.size} waiting)`})),t.signal){let{signal:h}=t;a=Promise.race([a,new Promise((f,l)=>{s=()=>{l(h.reason)},h.addEventListener("abort",s,{once:!0})})])}let u=await a;n(u),this.emit("completed",u)}catch(a){i(a),this.emit("error",a)}finally{s&&t.signal?.removeEventListener("abort",s),this.#y.delete(o),queueMicrotask(()=>{this.#F()})}},t),this.emit("add"),this.#k()})}async addAll(e,t){return Promise.all(e.map(async n=>this.add(n,t)))}start(){return this.#f?(this.#f=!1,this.#A(),this):this}pause(){this.#f=!0}clear(){this.#t=new this.#S,this.#_(),this.#N(),this.emit("empty"),this.#r===0&&(this.#C(),this.emit("idle")),this.emit("next")}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.#r===0&&this.#t.size===0||await this.#h("idle")}async onPendingZero(){this.#r!==0&&await this.#h("pendingZero")}async onRateLimit(){this.isRateLimited||await this.#h("rateLimit")}async onRateLimitCleared(){this.isRateLimited&&await this.#h("rateLimitCleared")}onError(){return new Promise((e,t)=>{let n=i=>{this.off("error",n),t(i)};this.on("error",n)})}async#h(e,t){return new Promise(n=>{let i=()=>{t&&!t()||(this.off(e,i),n())};this.on(e,i)})}get size(){return this.#t.size}sizeBy(e){return this.#t.filter(e).length}get pending(){return this.#r}get isPaused(){return this.#f}#M(){this.#i||(this.on("add",()=>{this.#t.size>0&&this.#p()}),this.on("next",()=>{this.#p()}))}#p(){this.#i||this.#w||(this.#w=!0,queueMicrotask(()=>{this.#w=!1,this.#N()}))}#z(){this.#i||(this.#R(),this.#p())}#N(){let e=this.#m;if(this.#i||this.#t.size===0){e&&(this.#m=!1,this.emit("rateLimitCleared"));return}let t;if(this.#s){let i=Date.now();this.#x(i),t=this.#E()}else t=this.#a;let n=t>=this.#d;n!==e&&(this.#m=n,this.emit(n?"rateLimit":"rateLimitCleared"))}get isRateLimited(){return this.#m}get isSaturated(){return this.#r===this.#g&&this.#t.size>0||this.isRateLimited&&this.#t.size>0}get runningTasks(){return[...this.#y.values()].map(e=>({...e}))}};function St(r){let e=[X.A];return r==null?e:Array.isArray(r)?r.length===0?e:r:[r]}var hn={};T(hn,{base10:()=>Za});var Za=ge({prefix:"9",name:"base10",alphabet:"0123456789"});var dn={};T(dn,{base16:()=>ec,base16upper:()=>tc});var ec=C({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),tc=C({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var pn={};T(pn,{base2:()=>rc});var rc=C({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var mn={};T(mn,{base256emoji:()=>ac});var Ji=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}"),nc=Ji.reduce((r,e,t)=>(r[t]=e,r),[]),ic=Ji.reduce((r,e,t)=>{let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);return r[n]=t,r},[]);function oc(r){return r.reduce((e,t)=>(e+=nc[t],e),"")}function sc(r){let e=[];for(let t of r){let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);let i=ic[n];if(i==null)throw new Error(`Non-base256emoji character: ${t}`);e.push(i)}return new Uint8Array(e)}var ac=De({prefix:"\u{1F680}",name:"base256emoji",encode:oc,decode:sc});var gn={};T(gn,{base36:()=>ue,base36upper:()=>cc});var ue=ge({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),cc=ge({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var yn={};T(yn,{base8:()=>uc});var uc=C({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var wn={};T(wn,{identity:()=>lc});var lc=De({prefix:"\0",name:"identity",encode:r=>$i(r),decode:r=>Fi(r)});var Ct={};T(Ct,{code:()=>bn,decode:()=>mc,encode:()=>pc,name:()=>dc});var fc=new TextEncoder,hc=new TextDecoder,dc="json",bn=512;function pc(r){return fc.encode(JSON.stringify(r))}function mc(r){return JSON.parse(hc.decode(r))}var Tt={};T(Tt,{code:()=>xn,decode:()=>wc,encode:()=>yc,name:()=>gc});var gc="raw",xn=85;function yc(r){return Y(r)}function wc(r){return Y(r)}var vn={};T(vn,{identity:()=>Nt});var bc=Zi,Yi=128,xc=127,Ec=~xc,vc=Math.pow(2,31);function Zi(r,e,t){e=e||[],t=t||0;for(var n=t;r>=vc;)e[t++]=r&255|Yi,r/=128;for(;r&Ec;)e[t++]=r&255|Yi,r>>>=7;return e[t]=r|0,Zi.bytes=t-n+1,e}var _c=En,kc=128,Xi=127;function En(r,n){var t=0,n=n||0,i=0,o=n,s,a=r.length;do{if(o>=a)throw En.bytes=0,new RangeError("Could not decode varint");s=r[o++],t+=i<28?(s&Xi)<<i:(s&Xi)*Math.pow(2,i),i+=7}while(s>=kc);return En.bytes=o-n,t}var Ac=Math.pow(2,7),Ic=Math.pow(2,14),Sc=Math.pow(2,21),Cc=Math.pow(2,28),Tc=Math.pow(2,35),Lc=Math.pow(2,42),Nc=Math.pow(2,49),Pc=Math.pow(2,56),Dc=Math.pow(2,63),Rc=function(r){return r<Ac?1:r<Ic?2:r<Sc?3:r<Cc?4:r<Tc?5:r<Lc?6:r<Nc?7:r<Pc?8:r<Dc?9:10},Uc={encode:bc,decode:_c,encodingLength:Rc},Bc=Uc,Ze=Bc;function et(r,e=0){return[Ze.decode(r,e),Ze.decode.bytes]}function Re(r,e,t=0){return Ze.encode(r,e,t),e}function Ue(r){return Ze.encodingLength(r)}function Fe(r,e){let t=e.byteLength,n=Ue(r),i=n+Ue(t),o=new Uint8Array(i+t);return Re(r,o,0),Re(t,o,n),o.set(e,i),new Be(r,t,e,o)}function eo(r){let e=Y(r),[t,n]=et(e),[i,o]=et(e.subarray(n)),s=e.subarray(n+o);if(s.byteLength!==i)throw new Error("Incorrect length");return new Be(t,i,s,e)}function to(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&Bi(r.bytes,t.bytes)}}var Be=class{code;size;digest;bytes;constructor(e,t,n,i){this.code=e,this.size=t,this.digest=n,this.bytes=i}};var ro=0,Fc="identity",no=Y;function $c(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 Fe(ro,no(r))}var Nt={code:ro,name:Fc,encode:no,digest:$c};var An={};T(An,{sha256:()=>Pt,sha512:()=>Dt});var Oc=20;function kn({name:r,code:e,encode:t,minDigestLength:n,maxDigestLength:i}){return new _n(r,e,t,n,i)}var _n=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,n,i,o){this.name=e,this.code=t,this.encode=n,this.minDigestLength=i??Oc,this.maxDigestLength=o}digest(e,t){if(t?.truncate!=null){if(t.truncate<this.minDigestLength)throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`);if(this.maxDigestLength!=null&&t.truncate>this.maxDigestLength)throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`)}if(e instanceof Uint8Array){let n=this.encode(e);return n instanceof Uint8Array?io(n,this.code,t?.truncate):n.then(i=>io(i,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}};function io(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 Fe(e,r)}function so(r){return async e=>new Uint8Array(await crypto.subtle.digest(r,e))}var Pt=kn({name:"sha2-256",code:18,encode:so("SHA-256")}),Dt=kn({name:"sha2-512",code:19,encode:so("SHA-512")});function ao(r,e){let{bytes:t,version:n}=r;switch(n){case 0:return zc(t,In(r),e??K.encoder);default:return qc(t,In(r),e??ye.encoder)}}var co=new WeakMap;function In(r){let e=co.get(r);if(e==null){let t=new Map;return co.set(r,t),t}return e}var k=class r{code;version;multihash;bytes;"/";constructor(e,t,n,i){this.code=t,this.version=e,this.multihash=n,this.bytes=i,this["/"]=i}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!==rt)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==jc)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=Fe(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&&to(e.multihash,n.multihash)}toString(e){return ao(this,e)}toJSON(){return{"/":ao(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(e){if(e==null)return null;let t=e;if(t instanceof r)return t;if(t["/"]!=null&&t["/"]===t.bytes||t.asCID===t){let{version:n,code:i,multihash:o,bytes:s}=t;return new r(n,i,o,s??uo(n,i,o.bytes))}else if(t[Vc]===!0){let{version:n,multihash:i,code:o}=t,s=eo(i);return r.create(n,o,s)}else return null}static create(e,t,n){if(typeof t!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(e){case 0:{if(t!==rt)throw new Error(`Version 0 CID must use dag-pb (code: ${rt}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let i=uo(e,t,n.bytes);return new r(e,t,n,i)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,rt,e)}static createV1(e,t){return r.create(1,e,t)}static decode(e){let[t,n]=r.decodeFirst(e);if(n.length!==0)throw new Error("Incorrect length");return t}static decodeFirst(e){let t=r.inspectBytes(e),n=t.size-t.multihashSize,i=Y(e.subarray(n,n+t.multihashSize));if(i.byteLength!==t.multihashSize)throw new Error("Incorrect length");let o=i.subarray(t.multihashSize-t.digestSize),s=new Be(t.multihashCode,t.digestSize,o,i);return[t.version===0?r.createV0(s):r.createV1(t.codec,s),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[l,m]=et(e.subarray(t));return t+=m,l},i=n(),o=rt;if(i===18?(i=0,t=0):o=n(),i!==0&&i!==1)throw new RangeError(`Invalid CID version ${i}`);let s=t,a=n(),u=n(),h=t+u,f=h-s;return{version:i,codec:o,multihashCode:a,digestSize:u,multihashSize:f,size:h}}static parse(e,t){let[n,i]=Mc(e,t),o=r.decode(i);if(o.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return In(o).set(n,e),o}};function Mc(r,e){switch(r[0]){case"Q":{let t=e??K;return[K.prefix,t.decode(`${K.prefix}${r}`)]}case K.prefix:{let t=e??K;return[K.prefix,t.decode(r)]}case ye.prefix:{let t=e??ye;return[ye.prefix,t.decode(r)]}case ue.prefix:{let t=e??ue;return[ue.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 zc(r,e,t){let{prefix:n}=t;if(n!==K.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let i=e.get(n);if(i==null){let o=t.encode(r).slice(1);return e.set(n,o),o}else return i}function qc(r,e,t){let{prefix:n}=t,i=e.get(n);if(i==null){let o=t.encode(r);return e.set(n,o),o}else return i}var rt=112,jc=18;function uo(r,e,t){let n=Ue(r),i=n+Ue(e),o=new Uint8Array(i+t.byteLength);return Re(r,o,0),Re(e,o,n),o.set(t,i),o}var Vc=Symbol.for("@ipld/js-cid/CID");var Sn={...wn,...pn,...yn,...hn,...dn,...nn,...gn,...on,...sn,...mn},wh={...An,...vn};function lo(r=0){return new Uint8Array(r)}function Rt(r=0){return new Uint8Array(r)}function ho(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var fo=ho("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),Cn=ho("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=Rt(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),Hc={utf8:fo,"utf-8":fo,hex:Sn.base16,latin1:Cn,ascii:Cn,binary:Cn,...Sn},Ut=Hc;function be(r,e="utf8"){let t=Ut[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.encoder.encode(r).substring(1)}var Tn=60;function Bt(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??Tn,data:e.data instanceof Uint8Array?be(e.data):e.data}))}}var Kc=4;function Ln(r,e={}){let t=new Xe({concurrency:e.queryConcurrency??Kc});return async(n,i={})=>{let o=i?.logger?.forComponent("dns:dns-json-over-https"),s=new URLSearchParams;s.set("name",n),St(i.types).forEach(u=>{s.append("type",X[u])}),i.onProgress?.(new v("dns:query",n)),o?.("GET %s",`${r}?${s}`);let a=await t.add(async()=>{let u=await fetch(`${r}?${s}`,{headers:{accept:"application/dns-json"},signal:i?.signal});if(o?.("GET %s %d",u.url,u.status),u.status!==200)throw new Error(`Unexpected HTTP status: ${u.status} - ${u.statusText}`);let h=Bt(await u.json());return i.onProgress?.(new v("dns:response",h)),h},{signal:i.signal});if(a==null)throw new Error("No DNS response received");return a}}function po(){return[Ln("https://cloudflare-dns.com/dns-query"),Ln("https://dns.google/resolve")]}var yo=Pi(go(),1);var Nn=class{lru;constructor(e){this.lru=(0,yo.default)(e)}get(e,t){let n=!0,i=[];for(let o of t){let s=this.getAnswers(e,o);if(s.length===0){n=!1;break}i.push(...s)}if(n)return Bt({answers:i})}getAnswers(e,t){let n=`${e.toLowerCase()}-${t}`,i=this.lru.get(n);if(i!=null){let o=i.filter(s=>s.expires>Date.now()).map(({expires:s,value:a})=>({...a,TTL:Math.round((s-Date.now())/1e3),type:X[a.type]}));return o.length===0&&this.lru.remove(n),o}return[]}add(e,t){let n=`${e.toLowerCase()}-${t.type}`,i=this.lru.get(n)??[];i.push({expires:Date.now()+(t.TTL??Tn)*1e3,value:t}),this.lru.set(n,i)}remove(e,t){let n=`${e.toLowerCase()}-${t}`;this.lru.remove(n)}clear(){this.lru.clear()}};function wo(r){return new Nn(r)}var Wc=1e3,Ft=class{resolvers;cache;logger;constructor(e){this.resolvers={},this.cache=wo(e.cacheSize??Wc),this.logger=e.logger,Object.entries(e.resolvers??{}).forEach(([t,n])=>{Array.isArray(n)||(n=[n]),t.endsWith(".")||(t=`${t}.`),this.resolvers[t]=n}),this.resolvers["."]==null&&(this.resolvers["."]=po())}async query(e,t={}){let n=St(t.types),i=t.cached!==!1?this.cache.get(e,n):void 0;if(i!=null)return t.onProgress?.(new v("dns:cache",i)),i;let o=`${e.split(".").pop()}.`,s=(this.resolvers[o]??this.resolvers["."]).sort(()=>Math.random()>.5?-1:1),a=[];for(let u of s){if(t.signal?.aborted===!0)break;try{let h=await u(e,{...t,logger:this.logger,types:n});for(let f of h.Answer)this.cache.add(e,f);return h}catch(h){a.push(h),t.onProgress?.(new v("dns:error",h))}}throw new At(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 bo(r={}){return new Ft(r)}function Gc(r){return r[Symbol.asyncIterator]!=null}function Qc(r){if(Gc(r))return(async()=>{for await(let e of r);})();for(let e of r);}var xo=Qc;function _e(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 Pn(r,e){e==null&&(e=r.reduce((i,o)=>i+o.length,0));let t=Rt(e),n=0;for(let i of r)t.set(i,n),n+=i.length;return t}function F(r,e="utf8"){let t=Ut[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.decoder.decode(`${t.prefix}${r}`)}var Dn={32:16777619n,64:1099511628211n,128:309485009821345068724781371n,256:374144419156711147060143317175368453031918731002211n,512:35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759n,1024:5016456510113118655434598811035278955030765345404790744303017523831112055108147451509157692220295382716162651878526895249385292291816524375083746691371804094271873160484737966720260389217684476157468082573n},Eo={32:2166136261n,64:14695981039346656037n,128:144066263297769815596495629667062367629n,256:100029257958052580907070968620625704837092796014241193945225284501741471925557n,512:9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785n,1024:14197795064947621068722070641403218320880622795441933960878474914617582723252296732303717722150864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915n},vo=new globalThis.TextEncoder;function Jc(r,e){let t=Dn[e],n=Eo[e];for(let i=0;i<r.length;i++)n^=BigInt(r[i]),n=BigInt.asUintN(e,n*t);return n}function Yc(r,e,t){if(t.length===0)throw new Error("The `utf8Buffer` option must have a length greater than zero");let n=Dn[e],i=Eo[e],o=r;for(;o.length>0;){let s=vo.encodeInto(o,t);o=o.slice(s.read);for(let a=0;a<s.written;a++)i^=BigInt(t[a]),i=BigInt.asUintN(e,i*n)}return i}function Rn(r,{size:e=32,utf8Buffer:t}={}){if(!Dn[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 Yc(r,e,t);r=vo.encode(r)}return Jc(r,e)}var nt={hash:r=>Number(Rn(r,{size:32})),hashV:(r,e)=>Xc(nt.hash(r,e))};function Xc(r){let e=r.toString(16);return e.length%2===1&&(e=`0${e}`),F(e,"base16")}var Un=64,Z=class{fp;h;seed;constructor(e,t,n,i=2){if(i>Un)throw new TypeError("Invalid Fingerprint Size");let o=t.hashV(e,n),s=lo(i);for(let a=0;a<s.length;a++)s[a]=o[a];s.length===0&&(s[0]=7),this.fp=s,this.h=t,this.seed=n}hash(){return this.h.hash(this.fp,this.seed)}equals(e){return e?.fp instanceof Uint8Array?_e(this.fp,e.fp):!1}};function ke(r,e){return Math.floor(Math.random()*(e-r))+r}var Ae=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=ke(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 Zc=500,it=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??nt,this.seed=e.seed??ke(0,Math.pow(2,10))}add(e){typeof e=="string"&&(e=F(e));let t=new Z(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,i=(n^t.hash())%this.filterSize;if(this.buckets[n]==null&&(this.buckets[n]=new Ae(this.bucketSize)),this.buckets[i]==null&&(this.buckets[i]=new Ae(this.bucketSize)),this.buckets[n].add(t)||this.buckets[i].add(t))return this.count++,!0;let o=[n,i],s=o[ke(0,o.length-1)];this.buckets[s]==null&&(this.buckets[s]=new Ae(this.bucketSize));for(let a=0;a<Zc;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 Ae(this.bucketSize)),this.buckets[s].add(u)))return this.count++,!0}return!1}has(e){typeof e=="string"&&(e=F(e));let t=new Z(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,i=this.buckets[n]?.has(t)??!1;if(i)return i;let o=(n^t.hash())%this.filterSize;return this.buckets[o]?.has(t)??!1}remove(e){typeof e=="string"&&(e=F(e));let t=new Z(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,i=this.buckets[n]?.remove(t)??!1;if(i)return this.count--,i;let o=(n^t.hash())%this.filterSize,s=this.buckets[o]?.remove(t)??!1;return s&&this.count--,s}get reliable(){return Math.floor(100*(this.count/this.filterSize))<=90}},eu={1:.5,2:.84,4:.95,8:.98};function tu(r=.001){return r>.002?2:r>1e-5?4:8}function _o(r,e=.001){let t=tu(e),n=eu[t],i=Math.round(r/n),o=Math.min(Math.ceil(Math.log2(1/e)+Math.log2(2*t)),Un);return{filterSize:i,bucketSize:t,fingerprintSize:o}}var $t=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??nt,this.seed=e.seed??ke(0,Math.pow(2,10)),this.filterSeries=[new it({filterSize:this.filterSize,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed})]}add(e){if(typeof e=="string"&&(e=F(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 it({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=F(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=F(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 Bn(r,e=.001,t){return new $t({..._o(r,e),...t??{}})}function $(){let r={};return r.promise=new Promise((e,t)=>{r.resolve=e,r.reject=t}),r}var Ot=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}},$e=class{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new Ot(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 Ot(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 Fn=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}};function Mt(r={}){return ru(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 ru(r,e){e=e??{};let t=e.onEnd,n=new $e,i,o,s,a=$(),u=async()=>{try{return n.isEmpty()?s?{done:!0}:await new Promise((w,x)=>{o=I=>{o=null,n.push(I);try{w(r(n))}catch(S){x(S)}return i}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=$()})}},h=w=>o!=null?o(w):(n.push(w),i),f=w=>(n=new $e,o!=null?o({error:w}):(n.push({error:w}),i)),l=w=>{if(s)return i;if(e?.objectMode!==!0&&w?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return h({done:!1,value:w})},m=w=>s?i:(s=!0,w!=null?f(w):h({done:!0})),y=()=>(n=new $e,m(),{done:!0}),b=w=>(m(w),{done:!0});if(i={[Symbol.asyncIterator](){return this},next:u,return:y,throw:b,push:l,end:m,get readableLength(){return n.size},onEmpty:async w=>{let x=w?.signal;if(x?.throwIfAborted(),n.isEmpty())return;let I,S;x!=null&&(I=new Promise((D,N)=>{S=()=>{N(new Fn)},x.addEventListener("abort",S)}));try{await Promise.race([a.promise,I])}finally{S!=null&&x!=null&&x?.removeEventListener("abort",S)}}},t==null)return i;let _=i;return i={[Symbol.asyncIterator](){return this},next(){return _.next()},throw(w){return _.throw(w),t!=null&&(t(w),t=void 0),{done:!0}},return(){return _.return(),t!=null&&(t(),t=void 0),{done:!0}},push:l,end(w){return _.end(w),t!=null&&(t(w),t=void 0),i},get readableLength(){return _.readableLength},onEmpty:w=>_.onEmpty(w)},i}var nu=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 iu(r,e,t){let n,i=new Promise((o,s)=>{if(t={rejectionEvents:["error"],multiArgs:!1,rejectionMultiArgs:!1,resolveImmediately:!1,...t},!(t.count>=0&&(t.count===Number.POSITIVE_INFINITY||Number.isInteger(t.count))))throw new TypeError("The `count` option should be at least 0 or more");t.signal?.throwIfAborted();let a=[e].flat(),u=[],{addListener:h,removeListener:f}=nu(r),l=async(...y)=>{let b=t.multiArgs?y:y[0];if(t.filter)try{if(!await t.filter(b))return}catch(_){n(),s(_);return}u.push(b),t.count===u.length&&(n(),o(u))},m=(...y)=>{n(),s(t.rejectionMultiArgs?y:y[0])};n=()=>{for(let y of a)f(y,l);for(let y of t.rejectionEvents)a.includes(y)||f(y,m)};for(let y of a)h(y,l);for(let y of t.rejectionEvents)a.includes(y)||h(y,m);t.signal&&t.signal.addEventListener("abort",()=>{m(t.signal.reason)},{once:!0}),t.resolveImmediately&&o(u)});if(i.cancel=n,typeof t.timeout=="number"){let o=Je(i,{milliseconds:t.timeout});return o.cancel=()=>{n(),o.clear()},o}return i}function zt(r,e,t){typeof t=="function"&&(t={filter:t}),t={...t,count:1,resolveImmediately:!1};let n=iu(r,e,t),i=n.then(o=>o[0]);return i.cancel=n.cancel,i}function $n(r,e){let t,n=function(){let i=function(){t=void 0,r()};clearTimeout(t),t=setTimeout(i,e)};return n.start=()=>{},n.stop=()=>{clearTimeout(t)},n}var qt=class extends Error{static name="QueueFullError";constructor(e="The queue was full"){super(e),this.name="QueueFullError"}};function ou(r){return r.reason}async function le(r,e,t){if(e==null)return r;let n=t?.translateError??ou;if(e.aborted)return r.catch(()=>{}),Promise.reject(n(e));let i;try{return await Promise.race([r,new Promise((o,s)=>{i=()=>{s(n(e))},e.addEventListener("abort",i)})])}finally{i!=null&&e.removeEventListener("abort",i)}}var jt=class{deferred;signal;constructor(e){this.signal=e,this.deferred=$(),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 Vt=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 jt(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 le(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 O=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=$n(this.emitEmpty.bind(this),1),this.emitIdle=$n(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 qt;let n=new Vt(e,t);return this.enqueue(n),this.safeDispatchEvent("add"),this.tryToStartAnother(),n.join(t).then(i=>(this.safeDispatchEvent("completed",{detail:i}),this.safeDispatchEvent("success",{detail:{job:n,result:i}}),i)).catch(i=>{if(n.status==="queued"){for(let o=0;o<this.queue.length;o++)if(this.queue[o]===n){this.queue.splice(o,1);break}}throw this.safeDispatchEvent("failure",{detail:{job:n,error:i}}),i})}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(e=>{e.abort(new J)}),this.clear()}async onEmpty(e){this.size!==0&&await zt(this,"empty",e)}async onSizeLessThan(e,t){this.size<e||await zt(this,"next",{...t,filter:()=>this.size<e})}async onIdle(e){this.pending===0&&this.size===0||await zt(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=Mt({objectMode:!0}),n=u=>{u!=null?this.abort():this.clear(),t.end(u)},i=u=>{u.detail!=null&&t.push(u.detail)},o=u=>{n(u.detail.error)},s=()=>{n()},a=()=>{n(new J("Queue aborted"))};this.addEventListener("completed",i),this.addEventListener("failure",o),this.addEventListener("idle",s),e?.signal?.addEventListener("abort",a);try{yield*t}finally{this.removeEventListener("completed",i),this.removeEventListener("failure",o),this.removeEventListener("idle",s),e?.signal?.removeEventListener("abort",a),n()}}};function ie(r){let e=new globalThis.AbortController;function t(){let o=r.filter(s=>s?.aborted===!0).map(s=>s?.reason).pop();e.abort(o);for(let s of r)s?.removeEventListener!=null&&s.removeEventListener("abort",t)}for(let o of r){if(o?.aborted===!0){t();break}o?.addEventListener!=null&&o.addEventListener("abort",t)}function n(){for(let o of r)o?.removeEventListener!=null&&o.removeEventListener("abort",t)}let i=e.signal;return i.clear=n,i}var On=class{readNext;haveNext;ended;nextResult;error;constructor(){this.ended=!1,this.readNext=$(),this.haveNext=$()}[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=$(),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=$(),await le(this.readNext.promise,t?.signal,t)}};function ko(){return new On}function au(r){return r[Symbol.asyncIterator]!=null}async function cu(r,e,t){try{await Promise.all(r.map(async n=>{for await(let i of n)await e.push(i,{signal:t}),t.throwIfAborted()})),await e.end(void 0,{signal:t})}catch(n){await e.end(n,{signal:t}).catch(()=>{})}}async function*uu(r){let e=new AbortController,t=ko();cu(r,t,e.signal).catch(()=>{});try{yield*t}finally{e.abort()}}function*lu(r){for(let e of r)yield*e}function fu(...r){let e=[];for(let t of r)au(t)||e.push(t);return e.length===r.length?lu(e):uu(r)}var Ht=fu;var hu=["Object","RegExp","Date","Error","Map","Set","WeakMap","WeakSet","ArrayBuffer","SharedArrayBuffer","DataView","Promise","URL","HTMLElement","Int8Array","Uint8ClampedArray","Int16Array","Uint16Array","Int32Array","Uint32Array","Float32Array","Float64Array","BigInt64Array","BigUint64Array"];function Mn(r){if(r===null)return"null";if(r===void 0)return"undefined";if(r===!0||r===!1)return"boolean";let e=typeof r;if(e==="string"||e==="number"||e==="bigint"||e==="symbol")return e;if(e==="function")return"Function";if(Array.isArray(r))return"Array";if(r instanceof Uint8Array)return"Uint8Array";if(r.constructor===Object)return"Object";let t=du(r);return t||"Object"}function du(r){let e=Object.prototype.toString.call(r).slice(8,-1);if(hu.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}static equals(e,t){return e===t||e.major===t.major&&e.name===t.name}};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 d=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 ot=globalThis.process&&!globalThis.process.browser&&globalThis.Buffer&&typeof globalThis.Buffer.isBuffer=="function",pu=new TextEncoder;function Kt(r){return ot&&globalThis.Buffer.isBuffer(r)}function Ie(r){return r instanceof Uint8Array?Kt(r)?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):r:Uint8Array.from(r)}var mu=24,gu=200,Oe=ot?r=>r.length>=mu?globalThis.Buffer.from(r):Ao(r):r=>r.length>=gu?pu.encode(r):Ao(r),oe=r=>Uint8Array.from(r),So=ot?(r,e,t)=>Kt(r)?new Uint8Array(r.subarray(e,t)):r.slice(e,t):(r,e,t)=>r.slice(e,t),Co=ot?(r,e)=>(r=r.map(t=>t instanceof Uint8Array?t:globalThis.Buffer.from(t)),Ie(globalThis.Buffer.concat(r,e))):(r,e)=>{let t=new Uint8Array(e),n=0;for(let i of r)n+i.length>t.length&&(i=i.subarray(0,t.length-n)),t.set(i,n),n+=i.length;return t},To=ot?r=>globalThis.Buffer.allocUnsafe(r):r=>new Uint8Array(r);function Wt(r,e){if(Kt(r)&&Kt(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 Ao(r){let e=[],t=0;for(let n=0;n<r.length;n++){let i=r.charCodeAt(n);i<128?e[t++]=i:i<2048?(e[t++]=i>>6|192,e[t++]=i&63|128):(i&64512)===55296&&n+1<r.length&&(r.charCodeAt(n+1)&64512)===56320?(i=65536+((i&1023)<<10)+(r.charCodeAt(++n)&1023),e[t++]=i>>18|240,e[t++]=i>>12&63|128,e[t++]=i>>6&63|128,e[t++]=i&63|128):(i>=55296&&i<=57343&&(i=65533),e[t++]=i>>12|224,e[t++]=i>>6&63|128,e[t++]=i&63|128)}return e}var Io=4096;function Lo(r){let e=r.length;if(e<=Io)return String.fromCharCode.apply(String,r);let t="",n=0;for(;n<e;)t+=String.fromCharCode.apply(String,r.slice(n,n+=Io));return t}var yu=256,st=class{constructor(e=yu){this.chunkSize=e,this.cursor=0,this.maxCursor=-1,this.chunks=[],this._initReuseChunk=null}reset(){this.cursor=0,this.maxCursor=-1,this.chunks.length&&(this.chunks=[]),this._initReuseChunk!==null&&(this.chunks.push(this._initReuseChunk),this.maxCursor=this._initReuseChunk.length-1)}push(e){let t=this.chunks[this.chunks.length-1];if(this.cursor+e.length<=this.maxCursor+1){let i=t.length-(this.maxCursor-this.cursor)-1;t.set(e,i)}else{if(t){let i=t.length-(this.maxCursor-this.cursor)-1;i<t.length&&(this.chunks[this.chunks.length-1]=t.subarray(0,i),this.maxCursor=this.cursor-1)}e.length<64&&e.length<this.chunkSize?(t=To(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=So(n,0,this.cursor)}else t=Co(this.chunks,this.cursor);return e&&this.reset(),t}},Gt=class{constructor(e){this.dest=e,this.cursor=0,this.chunks=[e]}reset(){this.cursor=0}push(e){if(this.cursor+e.length>this.dest.length)throw new Error("write out of bounds, destination buffer is too small");this.dest.set(e,this.cursor),this.cursor+=e.length}toBytes(e=!1){let t=this.dest.subarray(0,this.cursor);return e&&this.reset(),t}};var g="CBOR decode error:",se="CBOR encode error:",at=[];at[23]=1;at[24]=2;at[25]=3;at[26]=5;at[27]=9;function fe(r,e,t){if(r.length-e<t)throw new Error(`${g} not enough data for type`)}var L=[24,256,65536,4294967296,BigInt("18446744073709551616")];function M(r,e,t){fe(r,e,1);let n=r[e];if(t.strict===!0&&n<L[0])throw new Error(`${g} integer encoded in more bytes than necessary (strict decode)`);return n}function z(r,e,t){fe(r,e,2);let n=r[e]<<8|r[e+1];if(t.strict===!0&&n<L[1])throw new Error(`${g} integer encoded in more bytes than necessary (strict decode)`);return n}function q(r,e,t){fe(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(`${g} integer encoded in more bytes than necessary (strict decode)`);return n}function j(r,e,t){fe(r,e,8);let n=r[e]*16777216+(r[e+1]<<16)+(r[e+2]<<8)+r[e+3],i=r[e+4]*16777216+(r[e+5]<<16)+(r[e+6]<<8)+r[e+7],o=(BigInt(n)<<BigInt(32))+BigInt(i);if(t.strict===!0&&o<L[3])throw new Error(`${g} integer encoded in more bytes than necessary (strict decode)`);if(o<=Number.MAX_SAFE_INTEGER)return Number(o);if(t.allowBigInt===!0)return o;throw new Error(`${g} integers outside of the safe integer range are not supported`)}function No(r,e,t,n){return new d(c.uint,M(r,e+1,n),2)}function Po(r,e,t,n){return new d(c.uint,z(r,e+1,n),3)}function Do(r,e,t,n){return new d(c.uint,q(r,e+1,n),5)}function Ro(r,e,t,n){return new d(c.uint,j(r,e+1,n),9)}function W(r,e){return A(r,0,e.value)}function A(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 i=[e|27,0,0,0,0,0,0,0],o=Number(n&BigInt(4294967295)),s=Number(n>>BigInt(32)&BigInt(4294967295));i[8]=o&255,o=o>>8,i[7]=o&255,o=o>>8,i[6]=o&255,o=o>>8,i[5]=o&255,i[4]=s&255,s=s>>8,i[3]=s&255,s=s>>8,i[2]=s&255,s=s>>8,i[1]=s&255,r.push(i)}else throw new Error(`${g} encountered BigInt larger than allowable range`)}}W.encodedSize=function(e){return A.encodedSize(e.value)};A.encodedSize=function(e){return e<L[0]?1:e<L[1]?2:e<L[2]?3:e<L[3]?5:9};W.compareTokens=function(e,t){return e.value<t.value?-1:e.value>t.value?1:0};function Uo(r,e,t,n){return new d(c.negint,-1-M(r,e+1,n),2)}function Bo(r,e,t,n){return new d(c.negint,-1-z(r,e+1,n),3)}function Fo(r,e,t,n){return new d(c.negint,-1-q(r,e+1,n),5)}var zn=BigInt(-1),$o=BigInt(1);function Oo(r,e,t,n){let i=j(r,e+1,n);if(typeof i!="bigint"){let o=-1-i;if(o>=Number.MIN_SAFE_INTEGER)return new d(c.negint,o,9)}if(n.allowBigInt!==!0)throw new Error(`${g} integers outside of the safe integer range are not supported`);return new d(c.negint,zn-BigInt(i),9)}function Qt(r,e){let t=e.value,n=typeof t=="bigint"?t*zn-$o:t*-1-1;A(r,e.type.majorEncoded,n)}Qt.encodedSize=function(e){let t=e.value,n=typeof t=="bigint"?t*zn-$o:t*-1-1;return n<L[0]?1:n<L[1]?2:n<L[2]?3:n<L[3]?5:9};Qt.compareTokens=function(e,t){return e.value<t.value?1:e.value>t.value?-1:0};function ct(r,e,t,n){fe(r,e,t+n);let i=r.slice(e+t,e+t+n);return new d(c.bytes,i,t+n)}function Mo(r,e,t,n){return ct(r,e,1,t)}function zo(r,e,t,n){return ct(r,e,2,M(r,e+1,n))}function qo(r,e,t,n){return ct(r,e,3,z(r,e+1,n))}function jo(r,e,t,n){return ct(r,e,5,q(r,e+1,n))}function Vo(r,e,t,n){let i=j(r,e+1,n);if(typeof i=="bigint")throw new Error(`${g} 64-bit integer bytes lengths not supported`);return ct(r,e,9,i)}function Jt(r){return r.encodedBytes===void 0&&(r.encodedBytes=c.equals(r.type,c.string)?Oe(r.value):r.value),r.encodedBytes}function Me(r,e){let t=Jt(e);A(r,e.type.majorEncoded,t.length),r.push(t)}Me.encodedSize=function(e){let t=Jt(e);return A.encodedSize(t.length)+t.length};Me.compareTokens=function(e,t){return bu(Jt(e),Jt(t))};function bu(r,e){return r.length<e.length?-1:r.length>e.length?1:Wt(r,e)}var Ho=new TextDecoder,Eu=32;function vu(r,e,t){if(t-e<Eu){let i="";for(let o=e;o<t;o++){let s=r[o];if(s&128)return Ho.decode(r.subarray(e,t));i+=String.fromCharCode(s)}return i}return Ho.decode(r.subarray(e,t))}function ut(r,e,t,n,i){let o=t+n;fe(r,e,o);let s=new d(c.string,vu(r,e+t,e+o),o);return i.retainStringBytes===!0&&(s.byteValue=r.slice(e+t,e+o)),s}function Ko(r,e,t,n){return ut(r,e,1,t,n)}function Wo(r,e,t,n){return ut(r,e,2,M(r,e+1,n),n)}function Go(r,e,t,n){return ut(r,e,3,z(r,e+1,n),n)}function Qo(r,e,t,n){return ut(r,e,5,q(r,e+1,n),n)}function Jo(r,e,t,n){let i=j(r,e+1,n);if(typeof i=="bigint")throw new Error(`${g} 64-bit integer string lengths not supported`);return ut(r,e,9,i,n)}var Yo=Me;function ze(r,e,t,n){return new d(c.array,n,t)}function Xo(r,e,t,n){return ze(r,e,1,t)}function Zo(r,e,t,n){return ze(r,e,2,M(r,e+1,n))}function es(r,e,t,n){return ze(r,e,3,z(r,e+1,n))}function ts(r,e,t,n){return ze(r,e,5,q(r,e+1,n))}function rs(r,e,t,n){let i=j(r,e+1,n);if(typeof i=="bigint")throw new Error(`${g} 64-bit integer array lengths not supported`);return ze(r,e,9,i)}function ns(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${g} indefinite length items not allowed`);return ze(r,e,1,1/0)}function Yt(r,e){A(r,c.array.majorEncoded,e.value)}Yt.compareTokens=W.compareTokens;Yt.encodedSize=function(e){return A.encodedSize(e.value)};function qe(r,e,t,n){return new d(c.map,n,t)}function is(r,e,t,n){return qe(r,e,1,t)}function os(r,e,t,n){return qe(r,e,2,M(r,e+1,n))}function ss(r,e,t,n){return qe(r,e,3,z(r,e+1,n))}function as(r,e,t,n){return qe(r,e,5,q(r,e+1,n))}function cs(r,e,t,n){let i=j(r,e+1,n);if(typeof i=="bigint")throw new Error(`${g} 64-bit integer map lengths not supported`);return qe(r,e,9,i)}function us(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${g} indefinite length items not allowed`);return qe(r,e,1,1/0)}function Xt(r,e){A(r,c.map.majorEncoded,e.value)}Xt.compareTokens=W.compareTokens;Xt.encodedSize=function(e){return A.encodedSize(e.value)};function ls(r,e,t,n){return new d(c.tag,t,1)}function fs(r,e,t,n){return new d(c.tag,M(r,e+1,n),2)}function hs(r,e,t,n){return new d(c.tag,z(r,e+1,n),3)}function ds(r,e,t,n){return new d(c.tag,q(r,e+1,n),5)}function ps(r,e,t,n){return new d(c.tag,j(r,e+1,n),9)}function Zt(r,e){A(r,c.tag.majorEncoded,e.value)}Zt.compareTokens=W.compareTokens;Zt.encodedSize=function(e){return A.encodedSize(e.value)};var qn=20,jn=21,Vn=22,Hn=23;function ms(r,e,t,n){if(n.allowUndefined===!1)throw new Error(`${g} undefined values are not supported`);return n.coerceUndefinedToNull===!0?new d(c.null,null,1):new d(c.undefined,void 0,1)}function gs(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${g} indefinite length items not allowed`);return new d(c.break,void 0,1)}function Kn(r,e,t){if(t){if(t.allowNaN===!1&&Number.isNaN(r))throw new Error(`${g} NaN values are not supported`);if(t.allowInfinity===!1&&(r===1/0||r===-1/0))throw new Error(`${g} Infinity values are not supported`)}return new d(c.float,r,e)}function ys(r,e,t,n){return Kn(Wn(r,e+1),3,n)}function ws(r,e,t,n){return Kn(Gn(r,e+1),5,n)}function bs(r,e,t,n){return Kn(_s(r,e+1),9,n)}function lt(r,e,t){let n=e.value;if(n===!1)r.push([c.float.majorEncoded|qn]);else if(n===!0)r.push([c.float.majorEncoded|jn]);else if(n===null)r.push([c.float.majorEncoded|Vn]);else if(n===void 0)r.push([c.float.majorEncoded|Hn]);else{let i,o=!1;(!t||t.float64!==!0)&&(Es(n),i=Wn(ee,1),n===i||Number.isNaN(n)?(ee[0]=249,r.push(ee.slice(0,3)),o=!0):(vs(n),i=Gn(ee,1),n===i&&(ee[0]=250,r.push(ee.slice(0,5)),o=!0))),o||(Su(n),i=_s(ee,1),ee[0]=251,r.push(ee.slice(0,9)))}}lt.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){Es(n);let i=Wn(ee,1);if(n===i||Number.isNaN(n))return 3;if(vs(n),i=Gn(ee,1),n===i)return 5}return 9};var xs=new ArrayBuffer(9),G=new DataView(xs,1),ee=new Uint8Array(xs,0);function Es(r){if(r===1/0)G.setUint16(0,31744,!1);else if(r===-1/0)G.setUint16(0,64512,!1);else if(Number.isNaN(r))G.setUint16(0,32256,!1);else{G.setFloat32(0,r);let e=G.getUint32(0),t=(e&2139095040)>>23,n=e&8388607;if(t===255)G.setUint16(0,31744,!1);else if(t===0)G.setUint16(0,(r&2147483648)>>16|n>>13,!1);else{let i=t-127;i<-24?G.setUint16(0,0):i<-14?G.setUint16(0,(e&2147483648)>>16|1<<24+i,!1):G.setUint16(0,(e&2147483648)>>16|i+15<<10|n>>13,!1)}}}function Wn(r,e){if(r.length-e<2)throw new Error(`${g} not enough data for float16`);let t=(r[e]<<8)+r[e+1];if(t===31744)return 1/0;if(t===64512)return-1/0;if(t===32256)return NaN;let n=t>>10&31,i=t&1023,o;return n===0?o=i*2**-24:n!==31?o=(i+1024)*2**(n-25):o=i===0?1/0:NaN,t&32768?-o:o}function vs(r){G.setFloat32(0,r,!1)}function Gn(r,e){if(r.length-e<4)throw new Error(`${g} not enough data for float32`);let t=(r.byteOffset||0)+e;return new DataView(r.buffer,t,4).getFloat32(0,!1)}function Su(r){G.setFloat64(0,r,!1)}function _s(r,e){if(r.length-e<8)throw new Error(`${g} not enough data for float64`);let t=(r.byteOffset||0)+e;return new DataView(r.buffer,t,8).getFloat64(0,!1)}lt.compareTokens=W.compareTokens;function E(r,e,t){throw new Error(`${g} encountered invalid minor (${t}) for major ${r[e]>>>5}`)}function er(r){return()=>{throw new Error(`${g} ${r}`)}}var p=[];for(let r=0;r<=23;r++)p[r]=E;p[24]=No;p[25]=Po;p[26]=Do;p[27]=Ro;p[28]=E;p[29]=E;p[30]=E;p[31]=E;for(let r=32;r<=55;r++)p[r]=E;p[56]=Uo;p[57]=Bo;p[58]=Fo;p[59]=Oo;p[60]=E;p[61]=E;p[62]=E;p[63]=E;for(let r=64;r<=87;r++)p[r]=Mo;p[88]=zo;p[89]=qo;p[90]=jo;p[91]=Vo;p[92]=E;p[93]=E;p[94]=E;p[95]=er("indefinite length bytes/strings are not supported");for(let r=96;r<=119;r++)p[r]=Ko;p[120]=Wo;p[121]=Go;p[122]=Qo;p[123]=Jo;p[124]=E;p[125]=E;p[126]=E;p[127]=er("indefinite length bytes/strings are not supported");for(let r=128;r<=151;r++)p[r]=Xo;p[152]=Zo;p[153]=es;p[154]=ts;p[155]=rs;p[156]=E;p[157]=E;p[158]=E;p[159]=ns;for(let r=160;r<=183;r++)p[r]=is;p[184]=os;p[185]=ss;p[186]=as;p[187]=cs;p[188]=E;p[189]=E;p[190]=E;p[191]=us;for(let r=192;r<=215;r++)p[r]=ls;p[216]=fs;p[217]=hs;p[218]=ds;p[219]=ps;p[220]=E;p[221]=E;p[222]=E;p[223]=E;for(let r=224;r<=243;r++)p[r]=er("simple values are not supported");p[244]=E;p[245]=E;p[246]=E;p[247]=ms;p[248]=er("simple values are not supported");p[249]=ys;p[250]=ws;p[251]=bs;p[252]=E;p[253]=E;p[254]=E;p[255]=gs;var te=[];for(let r=0;r<24;r++)te[r]=new d(c.uint,r,1);for(let r=-1;r>=-24;r--)te[31-r]=new d(c.negint,r,1);te[64]=new d(c.bytes,new Uint8Array(0),1);te[96]=new d(c.string,"",1);te[128]=new d(c.array,0,1);te[160]=new d(c.map,0,1);te[244]=new d(c.false,!1,1);te[245]=new d(c.true,!0,1);te[246]=new d(c.null,null,1);function Qn(r){switch(r.type){case c.false:return oe([244]);case c.true:return oe([245]);case c.null:return oe([246]);case c.bytes:return r.value.length?void 0:oe([64]);case c.string:return r.value===""?oe([96]):void 0;case c.array:return r.value===0?oe([128]):void 0;case c.map:return r.value===0?oe([160]):void 0;case c.uint:return r.value<24?oe([Number(r.value)]):void 0;case c.negint:if(r.value>=-24)return oe([31-Number(r.value)])}}var Tu={float64:!1,mapSorter:Pu,quickEncodeToken:Qn},Cs=Object.freeze({float64:!0,mapSorter:Du,quickEncodeToken:Qn});function Lu(){let r=[];return r[c.uint.major]=W,r[c.negint.major]=Qt,r[c.bytes.major]=Me,r[c.string.major]=Yo,r[c.array.major]=Yt,r[c.map.major]=Xt,r[c.tag.major]=Zt,r[c.float.major]=lt,r}var je=Lu(),tr=new st,ht=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(`${se} object contains circular references`);return new r(t,e)}},xe={null:new d(c.null,null),undefined:new d(c.undefined,void 0),true:new d(c.true,!0),false:new d(c.false,!1),emptyArray:new d(c.array,0),emptyMap:new d(c.map,0)},ae={number(r,e,t,n){return!Number.isInteger(r)||!Number.isSafeInteger(r)?new d(c.float,r):r>=0?new d(c.uint,r):new d(c.negint,r)},bigint(r,e,t,n){return r>=BigInt(0)?new d(c.uint,r):new d(c.negint,r)},Uint8Array(r,e,t,n){return new d(c.bytes,r)},string(r,e,t,n){return new d(c.string,r)},boolean(r,e,t,n){return r?xe.true:xe.false},null(r,e,t,n){return xe.null},undefined(r,e,t,n){return xe.undefined},ArrayBuffer(r,e,t,n){return new d(c.bytes,new Uint8Array(r))},DataView(r,e,t,n){return new d(c.bytes,new Uint8Array(r.buffer,r.byteOffset,r.byteLength))},Array(r,e,t,n){if(!r.length)return t.addBreakTokens===!0?[xe.emptyArray,new d(c.break)]:xe.emptyArray;n=ht.createCheck(n,r);let i=[],o=0;for(let s of r)i[o++]=rr(s,t,n);return t.addBreakTokens?[new d(c.array,r.length),i,new d(c.break)]:[new d(c.array,r.length),i]},Object(r,e,t,n){let i=e!=="Object",o=i?r.keys():Object.keys(r),s=i?r.size:o.length,a;if(s){a=new Array(s),n=ht.createCheck(n,r);let u=!i&&t.ignoreUndefinedProperties,h=0;for(let f of o){let l=i?r.get(f):r[f];u&&l===void 0||(a[h++]=[rr(f,t,n),rr(l,t,n)])}h<s&&(a.length=h)}return a?.length?(Nu(a,t),t.addBreakTokens?[new d(c.map,a.length),a,new d(c.break)]:[new d(c.map,a.length),a]):t.addBreakTokens===!0?[xe.emptyMap,new d(c.break)]:xe.emptyMap}};ae.Map=ae.Object;ae.Buffer=ae.Uint8Array;for(let r of"Uint8Clamped Uint16 Uint32 Int8 Int16 Int32 BigUint64 BigInt64 Float32 Float64".split(" "))ae[`${r}Array`]=ae.DataView;function rr(r,e={},t){let n=Mn(r),i=e&&e.typeEncoders&&e.typeEncoders[n]||ae[n];if(typeof i=="function"){let s=i(r,n,e,t);if(s!=null)return s}let o=ae[n];if(!o)throw new Error(`${se} unsupported type: ${n}`);return o(r,n,e,t)}function Nu(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 i=t.type.major,o=je[i].compareTokens(t,n);return o===0&&console.warn("WARNING: complex key types used, CBOR key sorting guarantees are gone"),o}function Du(r,e){if(r[0]instanceof d&&e[0]instanceof d){let t=r[0],n=e[0];return t._keyBytes||(t._keyBytes=ks(t.value)),n._keyBytes||(n._keyBytes=ks(n.value)),Wt(t._keyBytes,n._keyBytes)}throw new Error("rfc8949MapSorter: complex key types are not supported yet")}function ks(r){return nr(r,je,Cs)}function ft(r,e,t,n){if(Array.isArray(e))for(let i of e)ft(r,i,t,n);else t[e.type.major](r,e,n)}var As=c.uint.majorEncoded,Is=c.negint.majorEncoded,Ru=c.bytes.majorEncoded,Uu=c.string.majorEncoded,Ss=c.array.majorEncoded,Bu=c.float.majorEncoded|qn,Fu=c.float.majorEncoded|jn,$u=c.float.majorEncoded|Vn,Ou=c.float.majorEncoded|Hn,Mu=BigInt(-1),zu=BigInt(1);function qu(r){return r.addBreakTokens!==!0}function Ts(r,e,t,n){let i=Mn(e),o=t.typeEncoders&&t.typeEncoders[i];if(o){let s=o(e,i,t,n);if(s!=null){ft(r,s,je,t);return}}switch(i){case"null":r.push([$u]);return;case"undefined":r.push([Ou]);return;case"boolean":r.push([e?Fu:Bu]);return;case"number":!Number.isInteger(e)||!Number.isSafeInteger(e)?lt(r,new d(c.float,e),t):e>=0?A(r,As,e):A(r,Is,e*-1-1);return;case"bigint":e>=BigInt(0)?A(r,As,e):A(r,Is,e*Mu-zu);return;case"string":{let s=Oe(e);A(r,Uu,s.length),r.push(s);return}case"Uint8Array":A(r,Ru,e.length),r.push(e);return;case"Array":if(!e.length){r.push([Ss]);return}n=ht.createCheck(n,e),A(r,Ss,e.length);for(let s of e)Ts(r,s,t,n);return;case"Object":case"Map":{let s=ae.Object(e,i,t,n);ft(r,s,je,t)}return;default:{let s=ae[i];if(!s)throw new Error(`${se} unsupported type: ${i}`);let a=s(e,i,t,n);ft(r,a,je,t)}}}function nr(r,e,t,n){let i=n instanceof Uint8Array,o=i?new Gt(n):tr,s=rr(r,t);if(!Array.isArray(s)&&t.quickEncodeToken){let a=t.quickEncodeToken(s);if(a)return i?(o.push(a),o.toBytes()):a;let u=e[s.type.major];if(u.encodedSize){let h=u.encodedSize(s,t);if(i||(o=new st(h)),u(o,s,t),o.chunks.length!==1)throw new Error(`Unexpected error: pre-calculated length for ${s} was wrong`);return i?o.toBytes():Ie(o.chunks[0])}}return o.reset(),ft(o,s,e,t),o.toBytes(!0)}function Ce(r,e){return e=Object.assign({},Tu,e),qu(e)?(tr.reset(),Ts(tr,r,e,void 0),tr.toBytes(!0)):nr(r,je,e)}var ju={strict:!1,allowIndefinite:!0,allowUndefined:!0,allowBigInt:!0},ir=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(`${g} no decoder for major type ${e>>>5} (byte 0x${e.toString(16).padStart(2,"0")})`);let i=e&31;t=n(this.data,this._pos,i,this.options)}return this._pos+=t.encodedLength,t}},dt=Symbol.for("DONE"),or=Symbol.for("BREAK");function Vu(r,e,t){let n=[];for(let i=0;i<r.value;i++){let o=Ve(e,t);if(o===or){if(r.value===1/0)break;throw new Error(`${g} got unexpected break to lengthed array`)}if(o===dt)throw new Error(`${g} found array but not enough entries (got ${i}, expected ${r.value})`);n[i]=o}return n}function Hu(r,e,t){let n=t.useMaps===!0,i=t.rejectDuplicateMapKeys===!0,o=n?void 0:{},s=n?new Map:void 0;for(let a=0;a<r.value;a++){let u=Ve(e,t);if(u===or){if(r.value===1/0)break;throw new Error(`${g} got unexpected break to lengthed map`)}if(u===dt)throw new Error(`${g} found map but not enough entries (got ${a} [no key], expected ${r.value})`);if(!n&&typeof u!="string")throw new Error(`${g} non-string keys not supported (got ${typeof u})`);if(i&&(n&&s.has(u)||!n&&Object.hasOwn(o,u)))throw new Error(`${g} found repeat map key "${u}"`);let h=Ve(e,t);if(h===dt)throw new Error(`${g} found map but not enough entries (got ${a} [no value], expected ${r.value})`);n?s.set(u,h):o[u]=h}return n?s:o}function Ve(r,e){if(r.done())return dt;let t=r.next();if(c.equals(t.type,c.break))return or;if(t.type.terminal)return t.value;if(c.equals(t.type,c.array))return Vu(t,r,e);if(c.equals(t.type,c.map))return Hu(t,r,e);if(c.equals(t.type,c.tag)){if(e.tags&&typeof e.tags[t.value]=="function"){let n=Ve(r,e);return e.tags[t.value](n)}throw new Error(`${g} tag not supported (${t.value})`)}throw new Error("unsupported")}function Jn(r,e){if(!(r instanceof Uint8Array))throw new Error(`${g} data to decode must be a Uint8Array`);e=Object.assign({},ju,e);let t=Ie(r),n=e.tokenizer||new ir(t,e),i=Ve(n,e);if(i===dt)throw new Error(`${g} did not find any content to decode`);if(i===or)throw new Error(`${g} got unexpected break`);return[i,r.subarray(n.pos())]}function re(r,e){let[t,n]=Jn(r,e);if(n.length>0)throw new Error(`${g} too many terminals, data makes no sense`);return t}var sr=class extends O{has(e){return this.find(e)!=null}find(e){return this.queue.find(t=>e.equals(t.options.peerId))}};var he="/",Ns=new TextEncoder().encode(he),ar=Ns[0],de=class r{_buf;constructor(e,t){if(typeof e=="string")this._buf=F(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]!==ar)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(he))}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=Ns),this._buf[0]!==ar){let e=new Uint8Array(this._buf.byteLength+1);e.fill(ar,0,1),e.set(this._buf,1),this._buf=e}for(;this._buf.byteLength>1&&this._buf[this._buf.byteLength-1]===ar;)this._buf=this._buf.subarray(0,-1)}less(e){let t=this.list(),n=e.list();for(let i=0;i<t.length;i++){if(n.length<i+1)return!1;let o=t[i],s=n[i];if(o<s)return!0;if(o>s)return!1}return t.length<n.length}reverse(){return r.withNamespaces(this.list().slice().reverse())}namespaces(){return this.list()}baseNamespace(){let e=this.namespaces();return e[e.length-1]}list(){return this.toString().split(he).slice(1)}type(){return Ku(this.baseNamespace())}name(){return Wu(this.baseNamespace())}instance(e){return new r(this.toString()+":"+e)}path(){let e=this.parent().toString();return e.endsWith(he)||(e+=he),e+=this.type(),new r(e)}parent(){let e=this.list();return e.length===1?new r(he):new r(e.slice(0,-1).join(he))}child(e){return this.toString()===he?e:e.toString()===he?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(),...Gu(e.map(t=>t.namespaces()))])}};function Ku(r){let e=r.split(":");return e.length<2?"":e.slice(0,-1).join(":")}function Wu(r){let e=r.split(":");return e[e.length-1]}function Gu(r){return[].concat(...r)}function Qu(r){return r[Symbol.asyncIterator]!=null}function Ju(r){if(Qu(r))return(async()=>{let n=new Uint8Array(0);for await(let i of r)n=Pn([n,i],n.length+i.length);return n})();let e=[],t=0;for(let n of r)e.push(n),t+=n.byteLength;return Pn(e,t)}var cr=Ju;function ur({enumerable:r=!0,configurable:e=!1}={}){return{enumerable:r,configurable:e,writable:!1}}function*Yu(r,e){if(e!=null&&typeof e=="object")if(Array.isArray(e))for(let[t,n]of e.entries()){let i=[...r,t],o=k.asCID(n);o!=null?yield[i.join("/"),o]:typeof n=="object"&&(yield*Yn(n,i))}else{let t=k.asCID(e);t!=null?yield[r.join("/"),t]:yield*Yn(e,r)}}function*Yn(r,e){if(r==null||r instanceof Uint8Array)return;let t=k.asCID(r);t!=null&&(yield[e.join("/"),t]);for(let[n,i]of Object.entries(r)){let o=[...e,n];yield*Yu(o,i)}}function*Xu(r,e){if(Array.isArray(e))for(let[t,n]of e.entries()){let i=[...r,t];yield i.join("/"),typeof n=="object"&&k.asCID(n)==null&&(yield*Xn(n,i))}else yield*Xn(e,r)}function*Xn(r,e){if(!(r==null||typeof r!="object"))for(let[t,n]of Object.entries(r)){let i=[...e,t];yield i.join("/"),n!=null&&!(n instanceof Uint8Array)&&typeof n=="object"&&k.asCID(n)==null&&(yield*Xu(i,n))}}function Zu(r,e){let t=r;for(let[n,i]of e.entries()){if(t=t[i],t==null)throw new Error(`Object has no property at ${e.slice(0,n+1).map(s=>`[${JSON.stringify(s)}]`).join("")}`);let o=k.asCID(t);if(o!=null)return{value:o,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:ur(),bytes:ur(),value:ur(),asBlock:ur()})}links(){return Yn(this.value,[])}tree(){return Xn(this.value,[])}get(e="/"){return Zu(this.value,e.split("/").filter(Boolean))}};function lr({bytes:r,cid:e,value:t,codec:n}){let i=t!==void 0?t:n?.decode(r);if(i===void 0)throw new Error('Missing required argument, must either provide "value" or "codec"');return new Zn({cid:e,bytes:r,value:i})}var fr=class extends Error{static name="AlreadyPinnedError";name="AlreadyPinnedError"},pt=class extends Error{static name="BlockPinnedError";name="BlockPinnedError"},hr=class extends Error{static name="InvalidDatastoreVersionError";name="InvalidDatastoreVersionError"},dr=class extends Error{static name="InvalidConfigurationError";name="InvalidConfigurationError"},pr=class extends AggregateError{static name="GetFailedError";name="GetFailedError"},mr=class extends AggregateError{static name="LoadBlockFailedError";name="LoadBlockFailedError"},mt=class extends Error{static name="BlockNotFoundWhileOfflineError";name="BlockNotFoundWhileOfflineError"};var Rs="/pin/",Ps="/pinned-block/",ei=ue,Ds=1;function gr(r){return r.version===0&&(r=r.toV1()),new de(`${Rs}${r.toString(ei)}`)}var yr=class{datastore;blockstore;getCodec;constructor(e,t,n){this.datastore=e,this.blockstore=t,this.getCodec=n}async*add(e,t={}){let n=gr(e);if(await this.datastore.has(n))throw new fr("Already pinned");let i=Math.round(t.depth??1/0);if(i<0)throw new Pe("Depth must be greater than or equal to 0");let o=new O({concurrency:Ds});for await(let a of this.#e(e,o,{...t,depth:i}))await this.#i(a,u=>u.pinnedBy.find(h=>_e(h,e.bytes))!=null?!1:(u.pinCount++,u.pinnedBy.push(e.bytes),!0),t),yield a;let s={depth:i,metadata:t.metadata??{}};await this.datastore.put(n,Ce(s),t)}async*#e(e,t,n){if(n.depth===-1)return;let i=await this.getCodec(e.code),o=await cr(this.blockstore.get(e,n)),s=lr({bytes:o,cid:e,codec:i});yield e;for(let[,a]of s.links())yield*await t.add(async()=>this.#e(a,t,{...n,depth:n.depth-1}))}async#i(e,t,n){let i=new de(`${Ps}${ei.encode(e.multihash.bytes)}`),o={pinCount:0,pinnedBy:[]};try{o=re(await this.datastore.get(i,n))}catch(a){if(a.name!=="NotFoundError")throw a}if(t(o)){if(o.pinCount===0&&await this.datastore.has(i)){await this.datastore.delete(i);return}await this.datastore.put(i,Ce(o),n),n.onProgress?.(new v("helia:pin:add",e))}}async*rm(e,t={}){let n=gr(e),i=await this.datastore.get(n,t),o=re(i);await this.datastore.delete(n,t);let s=new O({concurrency:Ds});for await(let a of this.#e(e,s,{...t,depth:o.depth}))await this.#i(a,u=>(u.pinCount--,u.pinnedBy=u.pinnedBy.filter(h=>_e(h,e.bytes)),!0),{...t,depth:o.depth}),yield a}async*ls(e={}){for await(let{key:t,value:n}of this.datastore.query({prefix:Rs+(e.cid!=null?`${e.cid.toString(ue)}`:"")},e)){let i=k.parse(t.toString().substring(5),ue),o=re(n);yield{cid:i,...o}}}async isPinned(e,t={}){let n=new de(`${Ps}${ei.encode(e.multihash.bytes)}`);return this.datastore.has(n,t)}async get(e,t){let n=gr(e),i=await this.datastore.get(n,t);return re(i)}async setMetadata(e,t,n){let i=gr(e),o=await this.datastore.get(i,n),s=re(o);s.metadata=t??{},await this.datastore.put(i,Ce(s),n)}};var wr=class extends Error{static name="InsufficientProvidersError";constructor(e="Insufficient providers found"){super(e),this.name="InsufficientProvidersError"}},Te=class extends Error{static name="NoRoutersAvailableError";constructor(e="No routers available"){super(e),this.name="NoRoutersAvailableError"}},br=class extends Error{static name="UnknownHashAlgorithmError";constructor(e="Unknown hash algorithm"){super(e),this.name="UnknownHashAlgorithmError"}},xr=class extends Error{static name="UnknownCodecError";constructor(e="Unknown codec"){super(e),this.name="UnknownCodecError"}};var el=5,Er=class{log;routers;providerLookupConcurrency;constructor(e,t){this.log=e.logger.forComponent("helia:routing"),this.routers=t.routers??[],this.providerLookupConcurrency=t.providerLookupConcurrency??el,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 pe(...this.routers)}async stop(){await me(...this.routers)}async*findProviders(e,t={}){if(this.routers.length===0)throw new Te("No content routers available");let n=new sr({concurrency:this.providerLookupConcurrency}),i=0,o=[],s=this,a=0;this.log("findProviders for %c start using routers %s",e,this.routers.map(h=>h.toString()).join(", "));let u=Le(this.routers,"findProviders").map(async function*(h){let f=0;try{for await(let l of h.findProviders(e,t))f++,yield l}catch(l){o.push(l)}finally{s.log("router %s found %d providers for %c",h,f,e),a++,a===u.length&&n.size===0&&n.emitIdle()}});for await(let h of Ht(n.toGenerator(),...u))if(h!=null){if(h.multiaddrs.length===0){if(n.find(h.id)!=null)continue;n.add(async()=>{try{let f=await this.findPeer(h.id,t);return f.multiaddrs.length===0?null:{...f,protocols:h.protocols,routing:h.routing}}catch(f){return this.log.error("could not load multiaddrs for peer %p - %e",h.id,f),null}},{peerId:h.id,signal:t.signal}).catch(f=>{this.log.error("could not load multiaddrs for peer %p - %e",h.id,f)});continue}i++,yield h}this.log("findProviders finished, found %d providers for %c",i,e)}async provide(e,t={}){if(this.routers.length===0)throw new Te("No content routers available");await Promise.all(Le(this.routers,"provide").map(async n=>{await n.provide(e,t)}))}async cancelReprovide(e,t={}){await Promise.all(Le(this.routers,"cancelReprovide").map(async n=>{await n.cancelReprovide(e,t)}))}async put(e,t,n){await Promise.all(Le(this.routers,"put").map(async i=>{await i.put(e,t,n)}))}async get(e,t){let n=[],i;try{i=await Promise.any(Le(this.routers,"get").map(async o=>{try{return await o.get(e,t)}catch(s){this.log("router %s failed with %e",o,s),n.push(s)}}))}catch{}if(i==null)throw new pr(n,`Failed to get value key ${be(e,"base58btc")}`);return i}async findPeer(e,t){if(this.routers.length===0)throw new Te("No peer routers available");let n=this,i=Ht(...Le(this.routers,"findPeer").map(o=>(async function*(){try{yield await o.findPeer(e,t)}catch(s){n.log.error(s)}})()));for await(let o of i)if(o!=null)return o;throw new Et("Could not find peer in routing")}async*getClosestPeers(e,t={}){if(this.routers.length===0)throw new Te("No peer routers available");for await(let n of Ht(...Le(this.routers,"getClosestPeers").map(i=>i.getClosestPeers(e,t))))n!=null&&(yield n)}};function Le(r,e){return r.filter(t=>t[e]!=null)}var V=class extends Error{static name="AbortError";name="AbortError";constructor(e="The operation was aborted",...t){super(e,...t)}};async function vr(r,e,t,n){let i=new V(n?.errorMessage);n?.errorCode!=null&&(i.code=n.errorCode);let o=n?.errorEvent??"error";return t?.aborted===!0?Promise.reject(i):new Promise((s,a)=>{function u(){ri(t,"abort",l),ri(r,e,h),ri(r,o,f)}let h=m=>{try{if(n?.filter?.(m)===!1)return}catch(y){u(),a(y);return}u(),s(m)},f=m=>{if(u(),m instanceof Error){a(m);return}a(m.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.`))},l=()=>{u(),a(i)};ti(t,"abort",l),ti(r,e,h),ti(r,o,f)})}function ti(r,e,t){r!=null&&(Us(r)?r.addEventListener(e,t):r.addListener(e,t))}function ri(r,e,t){r!=null&&(Us(r)?r.removeEventListener(e,t):r.removeListener(e,t))}function Us(r){return typeof r.addEventListener=="function"&&typeof r.removeEventListener=="function"}var _r=class extends Error{static name="QueueFullError";constructor(e="The queue was full"){super(e),this.name="QueueFullError"}};var kr=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 V)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function tl(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var Ar=class{id;fn;options;recipients;status;timeline;controller;constructor(e,t){this.id=tl(),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 V),this.cleanup())}async join(e={}){let t=new kr(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 le(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 ni(r,e){let t,n=function(){let i=function(){t=void 0,r()};clearTimeout(t),t=setTimeout(i,e)};return n.start=()=>{},n.stop=()=>{clearTimeout(t)},n}var gt=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=ni(this.emitEmpty.bind(this),1),this.emitIdle=ni(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 _r;let n=new Ar(e,t);return this.enqueue(n),this.safeDispatchEvent("add"),this.autoStart&&this.tryToStartAnother(),n.join(t).then(i=>(this.safeDispatchEvent("success",{detail:{job:n,result:i}}),i)).catch(i=>{if(n.status==="queued"){for(let o=0;o<this.queue.length;o++)if(this.queue[o]===n){this.queue.splice(o,1);break}}throw this.safeDispatchEvent("failure",{detail:{job:n,error:i}}),i})}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(e=>{e.abort(new V)}),this.clear()}async onEmpty(e){this.size!==0&&await vr(this,"empty",e?.signal)}async onSizeLessThan(e,t){this.size<e||await vr(this,"next",t?.signal,{filter:()=>this.size<e})}async onIdle(e){this.pending===0&&this.size===0||await vr(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=Mt({objectMode:!0}),n=u=>{u!=null?this.abort():this.clear(),t.end(u)},i=u=>{u.detail!=null&&t.push(u.detail.result)},o=u=>{n(u.detail.error)},s=()=>{n()},a=()=>{n(new V("Queue aborted"))};this.addEventListener("success",i),this.addEventListener("failure",o),this.addEventListener("idle",s),e?.signal?.addEventListener("abort",a);try{yield*t}finally{this.removeEventListener("success",i),this.removeEventListener("failure",o),this.removeEventListener("idle",s),e?.signal?.removeEventListener("abort",a),n()}}};var Ir="lock:worker:request-read",Sr="lock:worker:abort-read-request",Cr="lock:worker:release-read",Tr="lock:master:grant-read",Lr="lock:master:error-read",Nr="lock:worker:request-write",Pr="lock:worker:abort-write-request",Dr="lock:worker:release-write",Rr="lock:master:grant-write",Ur="lock:master:error-write",Br="lock:worker:finalize",Fr="mortice",Bs={singleProcess:!1};var ii=(r,e,t,n,i,o,s,a,u)=>h=>{if(h.data==null)return;let f={type:h.data.type,name:h.data.name,identifier:h.data.identifier};f.type===i&&r.safeDispatchEvent(t,{detail:{name:f.name,identifier:f.identifier,handler:async()=>{e.postMessage({type:u,name:f.name,identifier:f.identifier}),await new Promise(l=>{let m=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===f.identifier&&(e.removeEventListener("message",m),l())};e.addEventListener("message",m)})},onError:l=>{e.postMessage({type:s,name:f.name,identifier:f.identifier,error:{message:l.message,name:l.name,stack:l.stack}})}}}),f.type===o&&r.safeDispatchEvent(n,{detail:{name:f.name,identifier:f.identifier}}),f.type===Br&&r.safeDispatchEvent("finalizeRequest",{detail:{name:f.name}})};var Fs=(r=10)=>Math.random().toString().substring(2,r+2);var $r=class{name;channel;constructor(e){this.name=e,this.channel=new BroadcastChannel(Fr)}readLock(e){return this.sendRequest(Ir,Sr,Tr,Lr,Cr,e)}writeLock(e){return this.sendRequest(Nr,Pr,Rr,Ur,Dr,e)}finalize(){this.channel.postMessage({type:Br,name:this.name}),this.channel.close()}async sendRequest(e,t,n,i,o,s){s?.signal?.throwIfAborted();let a=Fs();return this.channel.postMessage({type:e,identifier:a,name:this.name}),new Promise((u,h)=>{let f=()=>{this.channel.postMessage({type:t,identifier:a,name:this.name})};s?.signal?.addEventListener("abort",f,{once:!0});let l=m=>{if(m.data?.identifier===a&&(m.data?.type===n&&(this.channel.removeEventListener("message",l),s?.signal?.removeEventListener("abort",f),u(()=>{this.channel.postMessage({type:o,identifier:a,name:this.name})})),m.data.type===i)){this.channel.removeEventListener("message",l),s?.signal?.removeEventListener("abort",f);let y=new Error;m.data.error!=null&&(y.message=m.data.error.message,y.name=m.data.error.name,y.stack=m.data.error.stack),h(y)}};this.channel.addEventListener("message",l)})}};var $s=r=>{if(r=Object.assign({},Bs,r),!!globalThis.document||r.singleProcess){let t=new BroadcastChannel(Fr),n=new H;return t.addEventListener("message",ii(n,t,"requestReadLock","abortReadLockRequest",Ir,Sr,Lr,Cr,Tr)),t.addEventListener("message",ii(n,t,"requestWriteLock","abortWriteLockRequest",Nr,Pr,Ur,Dr,Rr)),n}return new $r(r.name)};var Ne=new Map,yt;function Os(r){return typeof r?.readLock=="function"&&typeof r?.writeLock=="function"}function rl(r){if(yt==null&&(yt=$s(r),!Os(yt))){let e=yt;e.addEventListener("requestReadLock",t=>{let n=t.detail.name,i=t.detail.identifier,o=Ne.get(n);if(o==null)return;let s=new AbortController,a=u=>{u.detail.name!==n||u.detail.identifier!==i||s.abort()};e.addEventListener("abortReadLockRequest",a),o.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,i=t.detail.identifier,o=Ne.get(n);if(o==null)return;let s=new AbortController,a=u=>{u.detail.name!==n||u.detail.identifier!==i||s.abort()};e.addEventListener("abortWriteLockRequest",a),o.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,i=Ne.get(n);i?.finalize()})}return yt}async function oi(r,e){let t,n,i=new Promise((s,a)=>{t=s,n=a}),o=()=>{n(new V)};return e?.signal?.addEventListener("abort",o,{once:!0}),r.add(async()=>{await new Promise(s=>{t(()=>{e?.signal?.removeEventListener("abort",o),s()})})},{signal:e?.signal}).catch(s=>{n(s)}),i}var Ms=(r,e)=>{let t=Ne.get(r);if(t!=null)return t;let n=rl(e);if(Os(n))return t=n,Ne.set(r,t),t;let i=new gt({concurrency:1}),o;return t={async readLock(s){if(o!=null)return oi(o,s);o=new gt({concurrency:e.concurrency,autoStart:!1});let a=o,u=oi(o,s);return i.add(async()=>{a.start(),await a.onIdle().then(()=>{o===a&&(o=null)})}),u},async writeLock(s){return o=null,oi(i,s)},finalize:()=>{Ne.delete(r)},queue:i},Ne.set(r,t),e.autoFinalize===!0&&i.addEventListener("idle",()=>{t.finalize()},{once:!0}),t};var nl={name:"lock",concurrency:1/0,singleProcess:!1,autoFinalize:!1};function si(r){let e=Object.assign({},nl,r);return Ms(e.name,e)}var Or=class{lock;child;pins;started;constructor(e,t,n={}){this.child=e,this.pins=t,this.lock=si({singleProcess:n.holdGcLock}),this.started=!1}isStarted(){return this.started}async start(){await pe(this.child),this.started=!0}async stop(){await me(this.child),this.started=!1}unwrap(){return this.child}async put(e,t,n={}){n?.signal?.throwIfAborted();let i=await this.lock.readLock();try{return await this.child.put(e,t,n)}finally{i()}}async*putMany(e,t={}){t?.signal?.throwIfAborted();let n=await this.lock.readLock();try{yield*this.child.putMany(e,t)}finally{n()}}async*get(e,t={}){t?.signal?.throwIfAborted();let n=await this.lock.readLock();try{yield*this.child.get(e,t)}finally{n()}}async*getMany(e,t={}){t?.signal?.throwIfAborted();let n=await this.lock.readLock();try{yield*this.child.getMany(e,t)}finally{n()}}async delete(e,t={}){t?.signal?.throwIfAborted();let n=await this.lock.writeLock();try{if(await this.pins.isPinned(e))throw new pt("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 i=this;yield*this.child.deleteMany((async function*(){for await(let o of e){if(await i.pins.isPinned(o))throw new pt("Block was pinned - please unpin and try again");yield o}})(),t)}finally{n()}}async has(e,t={}){t?.signal?.throwIfAborted();let n=await this.lock.readLock();try{return await this.child.has(e,t)}finally{n()}}async*getAll(e={}){e?.signal?.throwIfAborted();let t=await this.lock.readLock();try{yield*this.child.getAll(e)}finally{t()}}createSession(e,t){return t?.signal?.throwIfAborted(),this.child.createSession(e,t)}};var ai=new de("/version"),zs=1;async function qs(r){if(!await r.has(ai)){await r.put(ai,F(`${zs}`));return}let e=await r.get(ai),t=be(e);if(parseInt(t,10)!==zs)throw new hr("Invalid datastore version, a datastore migration may be required")}var li={};T(li,{code:()=>ui,decode:()=>dl,decodeOptions:()=>ll,encode:()=>hl,encodeOptions:()=>cl,name:()=>fl,toByteView:()=>Vs});var js=42;function Vs(r){return r instanceof ArrayBuffer?new Uint8Array(r,0,r.byteLength):r}function il(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 d(c.tag,js),new d(c.bytes,t)]}function ol(){throw new Error("`undefined` is not supported by the IPLD Data Model and cannot be encoded")}function sl(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 al(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 ci={float64:!0,typeEncoders:{Map:al,Object:il,undefined:ol,number:sl}},cl={...ci,typeEncoders:{...ci.typeEncoders}};function ul(r){if(r[0]!==0)throw new Error("Invalid CID for CBOR tag 42; expected leading 0x00");return k.decode(r.subarray(1))}var Mr={allowIndefinite:!1,coerceUndefinedToNull:!0,allowNaN:!1,allowInfinity:!1,allowBigInt:!0,strict:!0,useMaps:!1,rejectDuplicateMapKeys:!0,tags:[]};Mr.tags[js]=ul;var ll={...Mr,tags:Mr.tags.slice()},fl="dag-cbor",ui=113,hl=r=>Ce(r,ci),dl=r=>re(Vs(r),Mr);var yi={};T(yi,{code:()=>gi,decode:()=>Ks,encode:()=>Hs,format:()=>kl,name:()=>_l,parse:()=>Il,stringify:()=>kl});var fi=class extends Array{constructor(){super(),this.inRecursive=[]}prefix(e){let t=this.inRecursive[this.inRecursive.length-1];t&&(c.equals(t.type,c.array)&&(t.elements++,t.elements!==1&&e.push([44])),c.equals(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),i=[];for(let o=0;o<n.length;o++)i[o]=n.charCodeAt(o);e.push(i)}[c.negint.major](e,t){this[c.uint.major](e,t)}[c.bytes.major](e,t){throw new Error(`${se} unsupported type: Uint8Array`)}[c.string.major](e,t){this.prefix(e);let n=Oe(JSON.stringify(t.value));e.push(n.length>32?Ie(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(c.equals(s.type,c.array))e.push([93]);else if(c.equals(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(`${se} unsupported type: undefined`);if(this.prefix(e),t.type.name==="true"){e.push([116,114,117,101]);return}else if(t.type.name==="false"){e.push([102,97,108,115,101]);return}else if(t.type.name==="null"){e.push([110,117,108,108]);return}let n=String(t.value),i=[],o=!1;for(let s=0;s<n.length;s++)i[s]=n.charCodeAt(s),!o&&(i[s]===46||i[s]===101||i[s]===69)&&(o=!0);o||(i.push(46),i.push(48)),e.push(i)}};function pl(r,e){if(Array.isArray(r[0])||Array.isArray(e[0]))throw new Error(`${se} 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(`${se} non-string map keys are not supported`);if(t<n)return-1;if(t>n)return 1;throw new Error(`${se} unexpected duplicate map keys, this is not supported`)}var ml={addBreakTokens:!0,mapSorter:pl};function hi(r,e){return e=Object.assign({},ml,e),nr(r,new fi,e)}var He=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(`${g} 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(`${g} unexpected token at position ${this._pos}, expected to find '${String.fromCharCode(...e)}'`)}parseNumber(){let e=this._pos,t=!1,n=!1,i=a=>{for(;!this.done();){let 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 d(c.uint,0,this._pos-e);if(i([48,49,50,51,52,53,54,55,56,57]),t&&this._pos===e+1)throw new Error(`${g} unexpected token at position ${this._pos}`);if(!this.done()&&this.ch()===46){if(n)throw new Error(`${g} unexpected token at position ${this._pos}`);n=!0,this._pos++,i([48,49,50,51,52,53,54,55,56,57])}!this.done()&&(this.ch()===101||this.ch()===69)&&(n=!0,this._pos++,!this.done()&&(this.ch()===43||this.ch()===45)&&this._pos++,i([48,49,50,51,52,53,54,55,56,57]));let o=String.fromCharCode.apply(null,this.data.subarray(e,this._pos)),s=parseFloat(o);return n?new d(c.float,s,this._pos-e):this.options.allowBigInt!==!0||Number.isSafeInteger(s)?new d(s>=0?c.uint:c.negint,s,this._pos-e):new d(s>=0?c.uint:c.negint,BigInt(o),this._pos-e)}parseString(){if(this.ch()!==34)throw new Error(`${g} unexpected character at position ${this._pos}; this shouldn't happen`);this._pos++;for(let o=this._pos,s=0;o<this.data.length&&s<65536;o++,s++){let a=this.data[o];if(a===92||a<32||a>=128)break;if(a===34){let u=String.fromCharCode.apply(null,this.data.subarray(this._pos,o));return this._pos=o+1,new d(c.string,u,s)}}let e=this._pos,t=[],n=()=>{if(this._pos+4>=this.data.length)throw new Error(`${g} unexpected end of unicode escape sequence at position ${this._pos}`);let o=0;for(let s=0;s<4;s++){let a=this.ch();if(a>=48&&a<=57)a-=48;else if(a>=97&&a<=102)a=a-97+10;else if(a>=65&&a<=70)a=a-65+10;else throw new Error(`${g} unexpected unicode escape character at position ${this._pos}`);o=o*16+a,this._pos++}return o},i=()=>{let o=this.ch(),s=null,a=o>239?4:o>223?3:o>191?2:1;if(this._pos+a>this.data.length)throw new Error(`${g} unexpected unicode sequence at position ${this._pos}`);let u,h,f,l;switch(a){case 1:o<128&&(s=o);break;case 2:u=this.data[this._pos+1],(u&192)===128&&(l=(o&31)<<6|u&63,l>127&&(s=l));break;case 3:u=this.data[this._pos+1],h=this.data[this._pos+2],(u&192)===128&&(h&192)===128&&(l=(o&15)<<12|(u&63)<<6|h&63,l>2047&&(l<55296||l>57343)&&(s=l));break;case 4:u=this.data[this._pos+1],h=this.data[this._pos+2],f=this.data[this._pos+3],(u&192)===128&&(h&192)===128&&(f&192)===128&&(l=(o&15)<<18|(u&63)<<12|(h&63)<<6|f&63,l>65535&&l<1114112&&(s=l))}s===null?(s=65533,a=1):s>65535&&(s-=65536,t.push(s>>>10&1023|55296),s=56320|s&1023),t.push(s),this._pos+=a};for(;!this.done();){let o=this.ch(),s;switch(o){case 92:if(this._pos++,this.done())throw new Error(`${g} 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(`${g} unexpected string escape character at position ${this._pos}`)}break;case 34:return this._pos++,new d(c.string,Lo(t),this._pos-e);default:if(o<32)throw new Error(`${g} invalid control character at position ${this._pos}`);o<128?(t.push(o),this._pos++):i()}}throw new Error(`${g} unexpected end of string at position ${this._pos}`)}parseValue(){switch(this.ch()){case 123:return this.modeStack.push("obj-start"),this._pos++,new d(c.map,1/0,1);case 91:return this.modeStack.push("array-start"),this._pos++,new d(c.array,1/0,1);case 34:return this.parseString();case 110:return this.expect([110,117,108,108]),new d(c.null,null,4);case 102:return this.expect([102,97,108,115,101]),new d(c.false,!1,5);case 116:return this.expect([116,114,117,101]),new d(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(`${g} 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 d(c.break,void 0,1);if(this.ch()!==44)throw new Error(`${g} 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 d(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 d(c.break,void 0,1);if(this.ch()!==44)throw new Error(`${g} 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 d(c.break,void 0,1);let e=this.parseString();if(this.skipWhitespace(),this.ch()!==58)throw new Error(`${g} 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(`${g} unexpected parse state at position ${this._pos}; this shouldn't happen`)}}};function di(r,e){return e=Object.assign({tokenizer:new He(r,e)},e),re(r,e)}function yl(r){return r instanceof ArrayBuffer?new Uint8Array(r,0,r.byteLength):r}function wl(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 d(c.map,1/0,1),new d(c.string,"/",1),new d(c.string,t,t.length),new d(c.break,void 0,1)]}function zr(r){let e=we.encode(r).slice(1);return[new d(c.map,1/0,1),new d(c.string,"/",1),new d(c.map,1/0,1),new d(c.string,"bytes",5),new d(c.string,e,e.length),new d(c.break,void 0,1),new d(c.break,void 0,1)]}function ne(r){return zr(new Uint8Array(r.buffer,r.byteOffset,r.byteLength))}function bl(r){return zr(new Uint8Array(r))}function xl(){throw new Error("`undefined` is not supported by the IPLD Data Model and cannot be encoded")}function El(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 vl={typeEncoders:{Object:wl,Buffer:zr,Uint8Array:zr,Int8Array:ne,Uint16Array:ne,Int16Array:ne,Uint32Array:ne,Int32Array:ne,Float32Array:ne,Float64Array:ne,Uint8ClampedArray:ne,BigInt64Array:ne,BigUint64Array:ne,DataView:ne,ArrayBuffer:bl,undefined:xl,number:El}},pi=class extends He{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(c.equals(e.type,c.map)){let t=this._next();if(c.equals(t.type,c.string)&&t.value==="/"){let n=this._next();if(c.equals(n.type,c.string)){let i=this._next();if(!c.equals(i.type,c.break))throw new Error("Invalid encoded CID form");return this.tokenBuffer.push(n),new d(c.tag,42,0)}if(c.equals(n.type,c.map)){let i=this._next();if(c.equals(i.type,c.string)&&i.value==="bytes"){let o=this._next();if(c.equals(o.type,c.string)){for(let a=0;a<2;a++){let u=this._next();if(!c.equals(u.type,c.break))throw new Error("Invalid encoded Bytes form")}let s=we.decode(`m${o.value}`);return new d(c.bytes,s,o.value.length)}this.tokenBuffer.push(o)}this.tokenBuffer.push(i)}this.tokenBuffer.push(n)}this.tokenBuffer.push(t)}return e}},mi={allowIndefinite:!1,allowUndefined:!1,allowNaN:!1,allowInfinity:!1,allowBigInt:!0,strict:!0,useMaps:!1,rejectDuplicateMapKeys:!0,tags:[]};mi.tags[42]=k.parse;var _l="dag-json",gi=297,Hs=r=>hi(r,vl),Ks=r=>{let e=yl(r),t=Object.assign(mi,{tokenizer:new pi(e,mi)});return di(e,t)},kl=r=>Al.decode(Hs(r));var Al=new TextDecoder,Il=r=>Ks(Sl.encode(r)),Sl=new TextEncoder;var _i={};T(_i,{code:()=>vi,createLink:()=>ra,createNode:()=>ta,decode:()=>Ml,encode:()=>Ol,name:()=>$l,prepare:()=>xi,validate:()=>Ei});var Cl=new TextDecoder;function wi(r,e){let t=0;for(let n=0;;n+=7){if(n>=64)throw new Error("protobuf: varint overflow");if(e>=r.length)throw new Error("protobuf: unexpected end of data");let i=r[e++];if(t+=n<28?(i&127)<<n:(i&127)*2**n,i<128)break}return[t,e]}function qr(r,e){let t;[t,e]=wi(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 Ws(r,e){let t;return[t,e]=wi(r,e),[t&7,t>>3,e]}function Tl(r){let e={},t=r.length,n=0;for(;n<t;){let i,o;if([i,o,n]=Ws(r,n),o===1){if(e.Hash)throw new Error("protobuf: (PBLink) duplicate Hash section");if(i!==2)throw new Error(`protobuf: (PBLink) wrong wireType (${i}) for Hash`);if(e.Name!==void 0)throw new Error("protobuf: (PBLink) invalid order, found Name before Hash");if(e.Tsize!==void 0)throw new Error("protobuf: (PBLink) invalid order, found Tsize before Hash");[e.Hash,n]=qr(r,n)}else if(o===2){if(e.Name!==void 0)throw new Error("protobuf: (PBLink) duplicate Name section");if(i!==2)throw new Error(`protobuf: (PBLink) wrong wireType (${i}) for Name`);if(e.Tsize!==void 0)throw new Error("protobuf: (PBLink) invalid order, found Tsize before Name");let s;[s,n]=qr(r,n),e.Name=Cl.decode(s)}else if(o===3){if(e.Tsize!==void 0)throw new Error("protobuf: (PBLink) duplicate Tsize section");if(i!==0)throw new Error(`protobuf: (PBLink) wrong wireType (${i}) for Tsize`);[e.Tsize,n]=wi(r,n)}else throw new Error(`protobuf: (PBLink) invalid fieldNumber, expected 1, 2 or 3, got ${o}`)}if(n>t)throw new Error("protobuf: (PBLink) unexpected end of data");return e}function Gs(r){let e=r.length,t=0,n,i=!1,o;for(;t<e;){let a,u;if([a,u,t]=Ws(r,t),a!==2)throw new Error(`protobuf: (PBNode) invalid wireType, expected 2, got ${a}`);if(u===1){if(o)throw new Error("protobuf: (PBNode) duplicate Data section");[o,t]=qr(r,t),n&&(i=!0)}else if(u===2){if(i)throw new Error("protobuf: (PBNode) duplicate Links section");n||(n=[]);let h;[h,t]=qr(r,t),n.push(Tl(h))}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 o&&(s.Data=o),s.Links=n||[],s}var Js=new TextEncoder,Qs=2**32,Ll=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=wt(e,t,r.Tsize)-1,e[t]=24}if(typeof r.Name=="string"){let n=Js.encode(r.Name);t-=n.length,e.set(n,t),t=wt(e,t,n.length)-1,e[t]=18}return r.Hash&&(t-=r.Hash.length,e.set(r.Hash,t),t=wt(e,t,r.Hash.length)-1,e[t]=10),e.length-t}function Ys(r){let e=Dl(r),t=new Uint8Array(e),n=e;if(r.Data&&(n-=r.Data.length,t.set(r.Data,n),n=wt(t,n,r.Data.length)-1,t[n]=10),r.Links)for(let i=r.Links.length-1;i>=0;i--){let o=Nl(r.Links[i],t.subarray(0,n));n-=o,n=wt(t,n,o)-1,t[n]=18}return t}function Pl(r){let e=0;if(r.Hash){let t=r.Hash.length;e+=1+t+Ke(t)}if(typeof r.Name=="string"){let t=Js.encode(r.Name).length;e+=1+t+Ke(t)}return typeof r.Tsize=="number"&&(e+=1+Ke(r.Tsize)),e}function Dl(r){let e=0;if(r.Data){let t=r.Data.length;e+=1+t+Ke(t)}if(r.Links)for(let t of r.Links){let n=Pl(t);e+=1+n+Ke(n)}return e}function wt(r,e,t){e-=Ke(t);let n=e;for(;t>=Ll;)r[e++]=t&127|128,t/=128;for(;t>=128;)r[e++]=t&127|128,t>>>=7;return r[e]=t,n}function Ke(r){return r%2===0&&r++,Math.floor((Rl(r)+6)/7)}function Rl(r){let e=0;return r>=Qs&&(r=Math.floor(r/Qs),e=32),r>=65536&&(r>>>=16,e+=16),r>=256&&(r>>>=8,e+=8),e+Ul[r]}var Ul=[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 Bl=["Data","Links"],Fl=["Hash","Name","Tsize"],bi=new TextEncoder;function Zs(r,e){if(r===e)return 0;let t=r.Name?bi.encode(r.Name):[],n=e.Name?bi.encode(e.Name):[],i=t.length,o=n.length;for(let s=0,a=Math.min(i,o);s<a;++s)if(t[s]!==n[s]){i=t[s],o=n[s];break}return i<o?-1:o<i?1:0}function Xs(r,e){return!Object.keys(r).some(t=>!e.includes(t))}function ea(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 xi(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=bi.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(ea),e.Links.sort(Zs);else throw new TypeError("Invalid DAG-PB form");else e.Links=[];return e}function Ei(r){if(!r||typeof r!="object"||Array.isArray(r)||r instanceof Uint8Array||r["/"]&&r["/"]===r.bytes)throw new TypeError("Invalid DAG-PB form");if(!Xs(r,Bl))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(!Xs(t,Fl))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&&Zs(t,r.Links[e-1])===-1)throw new TypeError("Invalid DAG-PB form (links must be sorted by Name bytes)")}}function ta(r,e=[]){return xi({Data:r,Links:e})}function ra(r,e,t){return ea({Hash:t,Name:r,Tsize:e})}function na(r){return r instanceof ArrayBuffer?new Uint8Array(r,0,r.byteLength):r}var $l="dag-pb",vi=112;function Ol(r){Ei(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),Ys(e)}function Ml(r){let e=na(r),t=Gs(e),n={};return t.Data&&(n.Data=t.Data),t.Links&&(n.Links=t.Links.map(i=>{let o={};try{o.Hash=k.decode(i.Hash)}catch{}if(!o.Hash)throw new Error("Invalid Hash field found in link, expected CID");return i.Name!==void 0&&(o.Name=i.Name),i.Tsize!==void 0&&(o.Tsize=i.Tsize),o})),n}function We(r){return r?.then!=null}function ia(r=[],e){let t={[vi]:_i,[xn]:Tt,[ui]:li,[gi]:yi,[bn]:Ct};return r.forEach(n=>{t[n.code]=n}),async n=>{let i=t[n];if(i==null&&e!=null){let o=e(n);We(o)?i=await o:i=o,t[i.code]=i}if(i!=null)return i;throw new xr(`Could not load codec for ${n}`)}}function oa(r=[],e){let t={[Pt.code]:Pt,[Dt.code]:Dt,[Nt.code]:Nt};return r.forEach(n=>{t[n.code]=n}),async n=>{let i=t[n];if(i==null&&e!=null){let o=e(n);We(o)?i=await o:i=o,t[i.code]=i}if(i!=null)return i;throw new br(`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 jr=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 Vr=class{has(e,t){return Promise.reject(new Error(".has is not implemented"))}put(e,t,n){return Promise.reject(new Error(".put is not implemented"))}async*putMany(e,t){for await(let{cid:n,bytes:i}of e)await this.put(n,i,t),yield n}get(e,t){throw new Error(".get is not implemented")}async*getMany(e,t){for await(let n of e)yield{cid:n,bytes:this.get(n,t)}}delete(e,t){return Promise.reject(new Error(".delete is not implemented"))}async*deleteMany(e,t){for await(let n of e)await this.delete(n,t),yield n}async*getAll(e){throw new Error(".getAll is not implemented")}};var Hr=0,Ge=class extends Error{static name="IdentityHashDigestTooLongError";name="IdentityHashDigestTooLongError"},Kr=class extends Vr{child;maxDigestLength;constructor(e,t){super(),this.child=e,this.maxDigestLength=t?.maxDigestLength}put(e,t,n){if(e.multihash.code===Hr){if(this.maxDigestLength!=null&&e.multihash.digest.byteLength>this.maxDigestLength)throw new Ge(`Identity digest too long - ${e.multihash.digest.byteLength} > this.maxDigestLength`);return n?.signal?.throwIfAborted(),e}return this.child==null?(n?.signal?.throwIfAborted(),e):this.child.put(e,t,n)}async*get(e,t){if(e.multihash.code===Hr){if(this.maxDigestLength!=null&&e.multihash.digest.byteLength>this.maxDigestLength)throw new Ge(`Identity digest too long - ${e.multihash.digest.byteLength} > this.maxDigestLength`);t?.signal?.throwIfAborted(),yield e.multihash.digest;return}if(this.child==null)throw t?.signal?.throwIfAborted(),new jr;yield*this.child.get(e,t)}has(e,t){if(e.multihash.code===Hr){if(this.maxDigestLength!=null&&e.multihash.digest.byteLength>this.maxDigestLength)throw new Ge(`Identity digest too long - ${e.multihash.digest.byteLength} > this.maxDigestLength`);return t?.signal?.throwIfAborted(),!0}return this.child==null?(t?.signal?.throwIfAborted(),!1):this.child.has(e,t)}delete(e,t){if(e.code===Hr){if(this.maxDigestLength!=null&&e.multihash.digest.byteLength>this.maxDigestLength)throw new Ge(`Identity digest too long - ${e.multihash.digest.byteLength} > this.maxDigestLength`);t?.signal?.throwIfAborted();return}if(this.child!=null)return this.child.delete(e,t)}async*getAll(e){this.child!=null&&(yield*this.child.getAll(e)),e?.signal?.throwIfAborted()}};function zl(r){let[e,t]=r[Symbol.asyncIterator]!=null?[r[Symbol.asyncIterator](),Symbol.asyncIterator]:[r[Symbol.iterator](),Symbol.iterator],n=[];return{peek:()=>e.next(),push:i=>{n.push(i)},next:()=>n.length>0?{done:!1,value:n.shift()}:e.next(),[t](){return this}}}var Wr=zl;function ql(r){return r[Symbol.asyncIterator]!=null}function jl(r,e){let t=0;if(ql(r))return(async function*(){for await(let u of r)await e(u,t++)&&(yield u)})();let n=Wr(r),{value:i,done:o}=n.next();if(o===!0)return(function*(){})();let s=e(i,t++);if(typeof s.then=="function")return(async function*(){await s&&(yield i);for(let u of n)await e(u,t++)&&(yield u)})();let a=e;return(function*(){s===!0&&(yield i);for(let u of n)a(u,t++)&&(yield u)})()}var Gr=jl;function Vl(r){return r[Symbol.asyncIterator]!=null}function sa(r){return r?.then!=null}function Hl(r,e){let t=0;if(Vl(r))return(async function*(){for await(let u of r){let h=e(u,t++);sa(h)&&await h,yield u}})();let n=Wr(r),{value:i,done:o}=n.next();if(o===!0)return(function*(){})();let s=e(i,t++);if(typeof s?.then=="function")return(async function*(){await s,yield i;for(let u of n){let h=e(u,t++);sa(h)&&await h,yield u}})();let a=e;return(function*(){yield i;for(let u of n)a(u,t++),yield u})()}var ki=Hl;var Wl=128,Qr=class{child;getHasher;log;logger;components;constructor(e,t={}){this.log=e.logger.forComponent("helia:networked-storage"),this.logger=e.logger,this.components=e,this.child=new Kr(e.blockstore,{maxDigestLength:t.maxIdentityHashDigestLength??Wl}),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 i=>i.announce?.(e,n))),n.onProgress?.(new v("blocks:put:blockstore:put",e)),this.child.put(e,t,n))}async*putMany(e,t={}){let n=Gr(e,async({cid:o})=>{let s=await this.child.has(o,t);return s&&t.onProgress?.(new v("blocks:put-many:duplicate",o)),!s}),i=ki(n,async({cid:o})=>{t.onProgress?.(new v("blocks:put-many:providers:notify",o)),await Promise.all(this.components.blockBrokers.map(async s=>s.announce?.(o,t)))});t.onProgress?.(new v("blocks:put-many:blockstore:put-many")),yield*this.child.putMany(i,t)}async*get(e,t={}){let n=await this.child.has(e,t),i=t.offline===!0;if(!n){if(i)throw new mt("The block was present in the blockstore and the node is running offline so cannot fetch it");let o=await this.getHasher(e.multihash.code);t?.signal?.throwIfAborted(),t.onProgress?.(new v("blocks:get:providers:get",e));let s=await aa(e,this.components.blockBrokers,o,{...t,log:this.log});t.onProgress?.(new v("blocks:get:blockstore:put",e)),await this.child.put(e,s,t),t.onProgress?.(new v("blocks:get:providers:notify",e)),await Promise.all(this.components.blockBrokers.map(async a=>a.announce?.(e,t))),yield s;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(ki(e,async n=>{let i=await this.child.has(n,t),o=t.offline===!0;if(!i){if(o)throw new mt("The block was present in the blockstore and the node is running offline so cannot fetch it");let s=await this.getHasher(n.multihash.code);t?.signal?.throwIfAborted(),t.onProgress?.(new v("blocks:get-many:providers:get",n));let a=await aa(n,this.components.blockBrokers,s,{...t,log:this.log});t.onProgress?.(new v("blocks:get-many:blockstore:put",n)),await this.child.put(n,a,t),t.onProgress?.(new v("blocks:get-many:providers:notify",n)),await Promise.all(this.components.blockBrokers.map(async u=>u.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)}},Jr=class extends Qr{started;constructor(e,t={}){super(e,t),this.started=!1}isStarted(){return this.started}async start(){await pe(this.child,...this.components.blockBrokers),this.started=!0}async stop(){await me(this.child,...this.components.blockBrokers),this.started=!1}unwrap(){return this.child}createSession(e,t){let n=this.components.blockBrokers.map(i=>i.createSession==null?i:i.createSession(t));return new Ai({blockstore:this.child,blockBrokers:n,getHasher:this.getHasher,logger:this.logger},{root:e})}},Ai=class extends Qr{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 i=ie([this.closeController.signal,n.signal]);try{return await super.put(e,t,{...n,signal:i})}finally{i.clear()}}async*putMany(e,t={}){let n=ie([this.closeController.signal,t.signal]);try{yield*super.putMany(e,{...t,signal:n})}finally{n.clear()}}async*get(e,t={}){let n=ie([this.closeController.signal,t.signal]);try{yield*super.get(e,{...t,signal:n})}finally{n.clear()}}async*getMany(e,t={}){let n=ie([this.closeController.signal,t.signal]);try{yield*super.getMany(e,{...t,signal:n})}finally{n.clear()}}async delete(e,t={}){let n=ie([this.closeController.signal,t.signal]);try{await super.delete(e,{...t,signal:n})}finally{n.clear()}}async*deleteMany(e,t={}){let n=ie([this.closeController.signal,t.signal]);try{yield*super.deleteMany(e,{...t,signal:n})}finally{n.clear()}}async has(e,t={}){let n=ie([this.closeController.signal,t.signal]);try{return await super.has(e,{...t,signal:n})}finally{n.clear()}}async*getAll(e={}){let t=ie([this.closeController.signal,e.signal]);try{yield*super.getAll({...e,signal:t})}finally{t.clear()}}};function Gl(r){return typeof r.retrieve=="function"}var Ql=(r,e)=>{if(e==null)throw new Pe(`No hasher configured for multihash code 0x${r.multihash.code.toString(16)}, please configure one. You can look up which hash this is at https://github.com/multiformats/multicodec/blob/master/table.csv`);return async t=>{let n,i=e.digest(t,{truncate:r.multihash.digest.byteLength});if(We(i)?n=await i:n=i,!_e(n.digest,r.multihash.digest))throw new vt("Hash of downloaded block did not match multihash from passed CID")}};async function aa(r,e,t,n){let i=Ql(r,t),o=new AbortController,s=ie([o.signal,n.signal]);o.signal;let a=[];for(let u of e)Gl(u)&&a.push(u);if(a.length===0)throw new dr(`No block brokers capable of retrieving blocks are configured, the CID ${r} cannot be fetched from the network`);try{return await Promise.any(a.map(async u=>{try{let h=!1,f=await u.retrieve(r,{...n,signal:s,validateFn:async l=>{await i(l),n.signal?.throwIfAborted(),h=!0}});return h||(await i(f),n.signal?.throwIfAborted()),f}catch(h){throw n.log.error("could not retrieve verified block for %c - %e",r,h),h}}))}catch(u){throw new mr(u.errors,`Failed to load block for ${r}`)}finally{o.abort(),s.clear()}}var Yr=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=Bn(this.maxProviders),this.initialProviders=t.providers??[]}async retrieve(e,t={}){let n=we.encode(e.multihash.bytes),i=this.requests.get(n);if(i!=null)return this.log("join existing request for %c",e),i.observers++,i.promise;let o=$(),s={promise:o.promise,observers:1};if(this.requests.set(n,s),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));try{await le(this.initialPeerSearchComplete,t.signal),l&&this.log("found initial session peers for %c",e)}catch(m){throw l&&this.log("failed to find initial session peers for %c - %e",e,m),this.requests.delete(n),s.observers>1&&o.reject(m),m}}let a=!1,u=new O({concurrency:this.maxProviders});u.addEventListener("failure",l=>{this.log.error("error querying provider %s, evicting from session - %e",l.detail.job.options.provider,l.detail.error),this.evict(l.detail.job.options.provider)}),u.addEventListener("success",l=>{a=!0,o.resolve(l.detail.result)}),u.addEventListener("idle",()=>{if(a){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 m=this.providers[Math.floor(Math.random()*this.providers.length)];this.evict(m)}await this.findProviders(e,this.minProviders,t),this.log("found new providers re-retrieving %c",e),this.requests.delete(n),o.resolve(await this.retrieve(e,t))}).catch(l=>{this.log.error("could not find new providers for %c - %e",e,l),o.reject(l)})});let h=l=>{u.add(async()=>this.queryProvider(e,l.detail,t),{provider:l.detail}).catch(m=>{t.signal?.aborted!==!0&&this.log.error("error retrieving session block for %c - %e",e,m)})};this.addEventListener("provider",h),Promise.all([...this.providers].map(async l=>u.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",e,l)});let f=()=>{o.reject(new J(t.signal?.reason??"Session aborted")),u.abort()};t.signal?.addEventListener("abort",f);try{return await le(o.promise,t.signal)}finally{this.removeEventListener("provider",h),t.signal?.removeEventListener("abort",f),u.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 i=$(),o=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(;o<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",o,this.maxProviders),this.providers.push(a),this.safeDispatchEvent("provider",{detail:a}),o++,o===t&&(this.log("session is ready"),i.resolve()),this.providers.length===this.maxProviders)){this.log("found max session peers",o);break}}if(o<this.maxProviders)for await(let s of this.findNewProviders(e,n)){if(o===this.maxProviders||n.signal?.aborted===!0)break;if(!this.hasProvider(s)&&(this.log("found %d/%d new providers",o,this.maxProviders),this.providers.push(s),this.safeDispatchEvent("provider",{detail:s}),o++,o===t&&(this.log("session is ready"),i.resolve()),this.providers.length===this.maxProviders)){this.log("found max session peers",o);break}}if(this.log("found %d/%d new session peers",o,this.maxProviders),o<t)throw new wr(`Found ${o} of ${t} ${this.name} providers for ${e}`)}).catch(s=>{this.log.error("error searching routing for potential session peers for %c - %e",e,s),i.reject(s)}),i.promise}};function ca(r){return e=>new Ii(e,r)}function ua(r){return e=>new Si(e,r)}function la(r){return e=>new Ci(e,r)}var bt=class{components;constructor(e,t={}){this.components=e}async*walk(e,t){let n=this.getQueue(),i=Gr(n.toGenerator(t),a=>a!=null),o=!1,s=async a=>{let u=a.cid,h=await cr(this.components.blockstore.get(u,a)),f=lr({cid:u,bytes:h,codec:await this.components.getCodec(u.code)});for(let[,l]of f.links())t?.includeChild?.(l,f)!==!1&&n.add(s,{...a,cid:l,depth:a.depth+1,path:[...a.path,l]}).catch(m=>{o||i.throw(m)});return{block:f,depth:a.depth,path:a.path}};n.add(s,{...t,cid:e,depth:0,path:[e]}).catch(a=>{o||i.throw(a)});try{yield*i}finally{o=!0,n.abort()}}},Ii=class extends bt{getQueue(){return new O({concurrency:1,sort:(e,t)=>e.options.depth===t.options.depth?0:e.options.depth<t.options.depth?1:-1})}},Si=class extends bt{getQueue(){return new O({concurrency:1,sort:(e,t)=>e.options.depth===t.options.depth?0:e.options.depth<t.options.depth?-1:1})}},Ci=class extends bt{getQueue(){return new O({concurrency:1})}};var Ti=class{libp2p;blockstore;datastore;events;pins;logger;routing;getCodec;getHasher;dns;metrics;log;constructor(e){this.logger=e.logger??Hi(),this.log=this.logger.forComponent("helia"),this.getHasher=oa(e.hashers,e.loadHasher),this.getCodec=ia(e.codecs,e.loadCodec),this.dns=e.dns??bo(),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 Er(t,{routers:(e.routers??[]).flatMap(i=>{typeof i=="function"&&(i=i(t));let o=[i],s=Xl(i);s!=null&&o.push(s);let a=Zl(i);return a!=null&&o.push(a),o}),providerLookupConcurrency:e.providerLookupConcurrency});let n=new Jr(t,e);this.pins=new yr(e.datastore,n,this.getCodec),this.blockstore=new Or(n,this.pins,{holdGcLock:e.holdGcLock??!0}),this.datastore=e.datastore,t.blockBrokers=e.blockBrokers.map(i=>i(t))}async start(){await qs(this.datastore),await pe(this.blockstore,this.datastore,this.routing,this.libp2p),this.events.dispatchEvent(new CustomEvent("start",{detail:this}))}async stop(){await me(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,i=this.blockstore.unwrap();this.log("gc start"),await xo(i.deleteMany((async function*(){for await(let{cid:o}of i.getAll())try{if(await n.pins.isPinned(o,e))continue;yield o,e.onProgress?.(new v("helia:gc:deleted",o))}catch(s){n.log.error("error during gc - %e",s),e.onProgress?.(new v("helia:gc:error",s))}})()))}finally{t()}this.log("gc finished")}};function Xl(r){return r?.[Di]}function Zl(r){return r?.[Ri]}return ya(ef);})();
3
13
  return HeliaUtils}));
4
14
  //# sourceMappingURL=index.min.js.map