@helia/utils 2.5.2-6f8165b5 → 2.5.2-73a28eda

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,5 @@
1
1
  (function (root, factory) {(typeof module === 'object' && module.exports) ? module.exports = factory() : root.HeliaUtils = factory()}(typeof self !== 'undefined' ? self : this, function () {
2
- "use strict";var HeliaUtils=(()=>{var Au=Object.create;var Zt=Object.defineProperty;var Su=Object.getOwnPropertyDescriptor;var Iu=Object.getOwnPropertyNames;var ku=Object.getPrototypeOf,Tu=Object.prototype.hasOwnProperty;var Yi=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),_=(r,e)=>{for(var t in e)Zt(r,t,{get:e[t],enumerable:!0})},Zi=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Iu(e))!Tu.call(r,o)&&o!==t&&Zt(r,o,{get:()=>e[o],enumerable:!(n=Su(e,o))||n.enumerable});return r};var es=(r,e,t)=>(t=r!=null?Au(ku(r)):{},Zi(e||!r||!r.__esModule?Zt(t,"default",{value:r,enumerable:!0}):t,r)),Lu=r=>Zi(Zt({},"__esModule",{value:!0}),r);var is=Yi((Nm,Nn)=>{"use strict";var Pu=Object.prototype.hasOwnProperty,M="~";function bt(){}Object.create&&(bt.prototype=Object.create(null),new bt().__proto__||(M=!1));function Nu(r,e,t){this.fn=r,this.context=e,this.once=t||!1}function os(r,e,t,n,o){if(typeof t!="function")throw new TypeError("The listener must be a function");var i=new Nu(t,n||r,o),s=M?M+e:e;return r._events[s]?r._events[s].fn?r._events[s]=[r._events[s],i]:r._events[s].push(i):(r._events[s]=i,r._eventsCount++),r}function nr(r,e){--r._eventsCount===0?r._events=new bt:delete r._events[e]}function O(){this._events=new bt,this._eventsCount=0}O.prototype.eventNames=function(){var e=[],t,n;if(this._eventsCount===0)return e;for(n in t=this._events)Pu.call(t,n)&&e.push(M?n.slice(1):n);return Object.getOwnPropertySymbols?e.concat(Object.getOwnPropertySymbols(t)):e};O.prototype.listeners=function(e){var t=M?M+e:e,n=this._events[t];if(!n)return[];if(n.fn)return[n.fn];for(var o=0,i=n.length,s=new Array(i);o<i;o++)s[o]=n[o].fn;return s};O.prototype.listenerCount=function(e){var t=M?M+e:e,n=this._events[t];return n?n.fn?1:n.length:0};O.prototype.emit=function(e,t,n,o,i,s){var a=M?M+e:e;if(!this._events[a])return!1;var c=this._events[a],l=arguments.length,f,p;if(c.fn){switch(c.once&&this.removeListener(e,c.fn,void 0,!0),l){case 1:return c.fn.call(c.context),!0;case 2:return c.fn.call(c.context,t),!0;case 3:return c.fn.call(c.context,t,n),!0;case 4:return c.fn.call(c.context,t,n,o),!0;case 5:return c.fn.call(c.context,t,n,o,i),!0;case 6:return c.fn.call(c.context,t,n,o,i,s),!0}for(p=1,f=new Array(l-1);p<l;p++)f[p-1]=arguments[p];c.fn.apply(c.context,f)}else{var m=c.length,b;for(p=0;p<m;p++)switch(c[p].once&&this.removeListener(e,c[p].fn,void 0,!0),l){case 1:c[p].fn.call(c[p].context);break;case 2:c[p].fn.call(c[p].context,t);break;case 3:c[p].fn.call(c[p].context,t,n);break;case 4:c[p].fn.call(c[p].context,t,n,o);break;default:if(!f)for(b=1,f=new Array(l-1);b<l;b++)f[b-1]=arguments[b];c[p].fn.apply(c[p].context,f)}}return!0};O.prototype.on=function(e,t,n){return os(this,e,t,n,!1)};O.prototype.once=function(e,t,n){return os(this,e,t,n,!0)};O.prototype.removeListener=function(e,t,n,o){var i=M?M+e:e;if(!this._events[i])return this;if(!t)return nr(this,i),this;var s=this._events[i];if(s.fn)s.fn===t&&(!o||s.once)&&(!n||s.context===n)&&nr(this,i);else{for(var a=0,c=[],l=s.length;a<l;a++)(s[a].fn!==t||o&&!s[a].once||n&&s[a].context!==n)&&c.push(s[a]);c.length?this._events[i]=c.length===1?c[0]:c:nr(this,i)}return this};O.prototype.removeAllListeners=function(e){var t;return e?(t=M?M+e:e,this._events[t]&&nr(this,t)):(this._events=new bt,this._eventsCount=0),this};O.prototype.off=O.prototype.removeListener;O.prototype.addListener=O.prototype.on;O.prefixed=M;O.EventEmitter=O;typeof Nn<"u"&&(Nn.exports=O)});var Us=Yi((Qg,Ns)=>{Ns.exports=function(r){if(!r)throw Error("hashlru must have a max value, of type number, greater than 0");var e=0,t=Object.create(null),n=Object.create(null);function o(i,s){t[i]=s,e++,e>=r&&(e=0,n=t,t=Object.create(null))}return{has:function(i){return t[i]!==void 0||n[i]!==void 0},remove:function(i){t[i]!==void 0&&(t[i]=void 0),n[i]!==void 0&&(n[i]=void 0)},get:function(i){var s=t[i];if(s!==void 0)return s;if((s=n[i])!==void 0)return o(i,s),s},set:function(i,s){t[i]!==void 0?t[i]=s:o(i,s)},clear:function(){t=Object.create(null),n=Object.create(null)}}}});var Am={};_(Am,{AbstractSession:()=>Pn,Helia:()=>Xi,breadthFirstWalker:()=>vu,depthFirstWalker:()=>Eu,naturalOrderWalker:()=>_u});var ts=Symbol.for("@libp2p/content-routing");var X=class extends Error{static name="AbortError";constructor(e="The operation was aborted"){super(e),this.name="AbortError"}};var Oe=class extends Error{static name="InvalidParametersError";constructor(e="Invalid parameters"){super(e),this.name="InvalidParametersError"}};var er=class extends Error{static name="NotFoundError";constructor(e="Not found"){super(e),this.name="NotFoundError"}};var tr=class extends Error{static name="InvalidMultihashError";constructor(e="Invalid Multihash"){super(e),this.name="InvalidMultihashError"}};var rs=Symbol.for("@libp2p/peer-routing");function ns(r){return r!=null&&typeof r.start=="function"&&typeof r.stop=="function"}async function be(...r){let e=[];for(let t of r)ns(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 xe(...r){let e=[];for(let t of r)ns(t)&&e.push(t);await Promise.all(e.map(async t=>{t.beforeStop!=null&&await t.beforeStop()})),await Promise.all(e.map(async t=>{await t.stop()})),await Promise.all(e.map(async t=>{t.afterStop!=null&&await t.afterStop()}))}function Cu(r){return typeof r?.handleEvent=="function"}function Du(r){return(r!==!0&&r!==!1&&r?.once)??!1}var G=class extends EventTarget{#e=new Map;constructor(){super()}listenerCount(e){let t=this.#e.get(e);return t==null?0:t.length}addEventListener(e,t,n){let o=Du(n);super.addEventListener(e,s=>{if(o){let a=this.#e.get(s.type);a!=null&&(a=a.filter(({callback:c})=>c!==t),this.#e.set(s.type,a))}Cu(t)?t.handleEvent(s):t(s)},n);let i=this.#e.get(e);i==null&&(i=[],this.#e.set(e,i)),i.push({callback:t,once:o})}removeEventListener(e,t,n){super.removeEventListener(e.toString(),t??null,n);let o=this.#e.get(e);o!=null&&(o=o.filter(({callback:i})=>i!==t),this.#e.set(e,o))}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 rr=class extends AggregateError{static name="DNSQueryFailedError";name="DNSQueryFailedError"};var Un=es(is(),1);var Rn=class r extends Error{name="TimeoutError";constructor(e,t){super(e,t),Error.captureStackTrace?.(this,r)}},ss=r=>r.reason??new DOMException("This operation was aborted.","AbortError");function xt(r,e){let{milliseconds:t,fallback:n,message:o,customTimers:i={setTimeout,clearTimeout},signal:s}=e,a,c,f=new Promise((p,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(ss(s));return}if(s&&(c=()=>{m(ss(s))},s.addEventListener("abort",c,{once:!0})),r.then(p,m),t===Number.POSITIVE_INFINITY)return;let b=new Rn;a=i.setTimeout.call(void 0,()=>{if(n){try{p(n())}catch(d){m(d)}return}typeof r.cancel=="function"&&r.cancel(),o===!1?p():o instanceof Error?m(o):(b.message=o??`Promise timed out after ${t} milliseconds`,m(b))},t)}).finally(()=>{f.clear(),c&&s&&s.removeEventListener("abort",c)});return f.clear=()=>{i.clearTimeout.call(void 0,a),a=void 0},f}function Bn(r,e,t){let n=0,o=r.length;for(;o>0;){let i=Math.trunc(o/2),s=n+i;t(r[s],e)<=0?(n=++s,o-=i+1):o=i}return n}var Uu=100,Me=class{#e=[];#t=0;enqueue(e,t){let{priority:n=0,id:o}=t??{},{size:i}=this,s={priority:n,id:o,run:e};if(i===0){this.#e.length=0,this.#t=0,this.#e.push(s);return}if(this.#e.at(-1).priority>=n){this.#e.push(s);return}this.#i();let a=Bn(this.#e,s,(c,l)=>l.priority-c.priority);this.#e.splice(a,0,s)}setPriority(e,t){let n=this.#e.findIndex((i,s)=>s>=this.#t&&i.id===e);if(n===-1)throw new ReferenceError(`No promise function with the id "${e}" exists in the queue.`);let[o]=this.#e.splice(n,1);this.enqueue(o.run,{priority:t,id:e})}remove(e){let t=this.#e.findIndex((n,o)=>o<this.#t?!1:typeof e=="string"?n.id===e:n.run===e);t!==-1&&this.#e.splice(t,1)}dequeue(){if(this.#t===this.#e.length)return;let e=this.#e[this.#t];return this.#t++,this.#t===this.#e.length?(this.#e.length=0,this.#t=0):this.#t>Uu&&this.#t>this.#e.length/2&&this.#i(),e?.run}filter(e){let t=[];for(let n=this.#t;n<this.#e.length;n++){let o=this.#e[n];o.priority===e.priority&&t.push(o.run)}return t}get size(){return this.#e.length-this.#t}#i(){this.#t!==0&&(this.#e.splice(0,this.#t),this.#t=0)}};var Et=class extends Un.default{#e;#t;#i=0;#d;#m=!1;#b=!1;#c;#k=0;#x=0;#u;#l;#a;#s=[];#o=0;#r;#T;#n=0;#g;#f;#N=1n;#y=new Map;#E=new Set;timeout;constructor(e){if(super(),e={carryoverIntervalCount:!1,intervalCap:Number.POSITIVE_INFINITY,interval:0,concurrency:Number.POSITIVE_INFINITY,autoStart:!0,queueClass:Me,strict:!1,...e},!(typeof e.intervalCap=="number"&&e.intervalCap>=1))throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${e.intervalCap?.toString()??""}\` (${typeof e.intervalCap})`);if(e.interval===void 0||!(Number.isFinite(e.interval)&&e.interval>=0))throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${e.interval?.toString()??""}\` (${typeof e.interval})`);if(e.strict&&e.interval===0)throw new TypeError("The `strict` option requires a non-zero `interval`");if(e.strict&&e.intervalCap===Number.POSITIVE_INFINITY)throw new TypeError("The `strict` option requires a finite `intervalCap`");if(this.#e=e.carryoverIntervalCount??e.carryoverConcurrencyCount??!1,this.#t=e.intervalCap===Number.POSITIVE_INFINITY||e.interval===0,this.#d=e.intervalCap,this.#c=e.interval,this.#a=e.strict,this.#r=new e.queueClass,this.#T=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.#F()}#v(e){for(;this.#o<this.#s.length;){let n=this.#s[this.#o];if(n!==void 0&&e-n>=this.#c)this.#o++;else break}(this.#o>100&&this.#o>this.#s.length/2||this.#o===this.#s.length)&&(this.#s=this.#s.slice(this.#o),this.#o=0)}#U(e){this.#a?this.#s.push(e):this.#i++}#R(){this.#a?this.#s.length>this.#o&&this.#s.pop():this.#i>0&&this.#i--}#_(){return this.#s.length-this.#o}get#B(){return this.#t?!0:this.#a?this.#_()<this.#d:this.#i<this.#d}get#z(){return this.#n<this.#g}#O(){this.#n--,this.#n===0&&this.emit("pendingZero"),this.#w(),this.emit("next")}#M(){this.#l=void 0,this.#D(),this.#C()}#$(e){if(this.#a){if(this.#v(e),this.#_()>=this.#d){let n=this.#s[this.#o],o=this.#c-(e-n);return this.#A(o),!0}return!1}if(this.#u===void 0){let t=this.#k-e;if(t<0){if(this.#x>0){let n=e-this.#x;if(n<this.#c)return this.#A(this.#c-n),!0}this.#i=this.#e?this.#n:0}else return this.#A(t),!0}return!1}#A(e){this.#l===void 0&&(this.#l=setTimeout(()=>{this.#M()},e))}#S(){this.#u&&(clearInterval(this.#u),this.#u=void 0)}#L(){this.#l&&(clearTimeout(this.#l),this.#l=void 0)}#w(){if(this.#r.size===0){if(this.#S(),this.emit("empty"),this.#n===0){if(this.#L(),this.#a&&this.#o>0){let t=Date.now();this.#v(t)}this.emit("idle")}return!1}let e=!1;if(!this.#f){let t=Date.now(),n=!this.#$(t);if(this.#B&&this.#z){let o=this.#r.dequeue();this.#t||(this.#U(t),this.#p()),this.emit("active"),o(),n&&this.#C(),e=!0}}return e}#C(){this.#t||this.#u!==void 0||this.#a||(this.#u=setInterval(()=>{this.#D()},this.#c),this.#k=Date.now()+this.#c)}#D(){this.#a||(this.#i===0&&this.#n===0&&this.#u&&this.#S(),this.#i=this.#e?this.#n:0),this.#I(),this.#p()}#I(){for(;this.#w(););}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.#I()}setPriority(e,t){if(typeof t!="number"||!Number.isFinite(t))throw new TypeError(`Expected \`priority\` to be a finite number, got \`${t}\` (${typeof t})`);this.#r.setPriority(e,t)}async add(e,t={}){return t={timeout:this.timeout,...t,id:t.id??(this.#N++).toString()},new Promise((n,o)=>{let i=Symbol(`task-${t.id}`),s=()=>{},a=async()=>{s(),this.#n++,this.#y.set(i,{id:t.id,priority:t.priority??0,startTime:Date.now(),timeout:t.timeout});let l;try{try{t.signal?.throwIfAborted()}catch(m){throw this.#q(),this.#y.delete(i),m}this.#x=Date.now();let f=e({signal:t.signal});if(t.timeout&&(f=xt(Promise.resolve(f),{milliseconds:t.timeout,message:`Task timed out after ${t.timeout}ms (queue has ${this.#n} running, ${this.#r.size} waiting)`})),t.signal){let{signal:m}=t;f=Promise.race([f,new Promise((b,d)=>{l=()=>{d(m.reason)},m.addEventListener("abort",l,{once:!0})})])}let p=await f;n(p),this.emit("completed",p)}catch(f){o(f),this.emit("error",f)}finally{l&&t.signal?.removeEventListener("abort",l),this.#y.delete(i),queueMicrotask(()=>{this.#O()})}};this.#r.enqueue(a,t);let c=()=>{if(this.#r instanceof Me){this.#r.remove(a);return}this.#r.remove?.(t.id)};if(t.signal){let{signal:l}=t,f=()=>{s(),c(),o(l.reason),this.#w(),this.emit("next")};if(s=()=>{l.removeEventListener("abort",f),this.#E.delete(s)},l.aborted){f();return}l.addEventListener("abort",f,{once:!0}),this.#E.add(s)}this.emit("add"),this.#w()})}async addAll(e,t){return Promise.all(e.map(async n=>this.add(n,t)))}start(){return this.#f?(this.#f=!1,this.#I(),this):this}pause(){this.#f=!0}clear(){for(let e of this.#E)e();this.#r=new this.#T,this.#S(),this.#P(),this.emit("empty"),this.#n===0&&(this.#L(),this.emit("idle")),this.emit("next")}async onEmpty(){this.#r.size!==0&&await this.#h("empty")}async onSizeLessThan(e){this.#r.size<e||await this.#h("next",()=>this.#r.size<e)}async onIdle(){this.#n===0&&this.#r.size===0||await this.#h("idle")}async onPendingZero(){this.#n!==0&&await this.#h("pendingZero")}async onRateLimit(){this.isRateLimited||await this.#h("rateLimit")}async onRateLimitCleared(){this.isRateLimited&&await this.#h("rateLimitCleared")}onError(){return new Promise((e,t)=>{let n=o=>{this.off("error",n),t(o)};this.on("error",n)})}async#h(e,t){return new Promise(n=>{let o=()=>{t&&!t()||(this.off(e,o),n())};this.on(e,o)})}get size(){return this.#r.size}sizeBy(e){return this.#r.filter(e).length}get pending(){return this.#n}get isPaused(){return this.#f}#F(){this.#t||(this.on("add",()=>{this.#r.size>0&&this.#p()}),this.on("next",()=>{this.#p()}))}#p(){this.#t||this.#b||(this.#b=!0,queueMicrotask(()=>{this.#b=!1,this.#P()}))}#q(){this.#t||(this.#R(),this.#p())}#P(){let e=this.#m;if(this.#t||this.#r.size===0){e&&(this.#m=!1,this.emit("rateLimitCleared"));return}let t;if(this.#a){let o=Date.now();this.#v(o),t=this.#_()}else t=this.#i;let n=t>=this.#d;n!==e&&(this.#m=n,this.emit(n?"rateLimit":"rateLimitCleared"))}get isRateLimited(){return this.#m}get isSaturated(){return this.#n===this.#g&&this.#r.size>0||this.isRateLimited&&this.#r.size>0}get runningTasks(){return[...this.#y.values()].map(e=>({...e,timeoutRemaining:e.timeout?Math.max(0,e.startTime+e.timeout-Date.now()):void 0}))}};function or(r){let e=[Y.A];return r==null?e:Array.isArray(r)?r.length===0?e:r:[r]}var Fn={};_(Fn,{base10:()=>Fu});var Km=new Uint8Array(0);function as(r,e){if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return!1;return!0}function de(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 cs(r){return new TextEncoder().encode(r)}function us(r){return new TextDecoder().decode(r)}function Ru(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),n=0;n<t.length;n++)t[n]=255;for(var o=0;o<r.length;o++){var i=r.charAt(o),s=i.charCodeAt(0);if(t[s]!==255)throw new TypeError(i+" is ambiguous");t[s]=o}var a=r.length,c=r.charAt(0),l=Math.log(a)/Math.log(256),f=Math.log(256)/Math.log(a);function p(d){if(d instanceof Uint8Array||(ArrayBuffer.isView(d)?d=new Uint8Array(d.buffer,d.byteOffset,d.byteLength):Array.isArray(d)&&(d=Uint8Array.from(d))),!(d instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(d.length===0)return"";for(var w=0,x=0,v=0,I=d.length;v!==I&&d[v]===0;)v++,w++;for(var A=(I-v)*f+1>>>0,S=new Uint8Array(A);v!==I;){for(var T=d[v],D=0,k=A-1;(T!==0||D<x)&&k!==-1;k--,D++)T+=256*S[k]>>>0,S[k]=T%a>>>0,T=T/a>>>0;if(T!==0)throw new Error("Non-zero carry");x=D,v++}for(var C=A-x;C!==A&&S[C]===0;)C++;for(var $=c.repeat(w);C<A;++C)$+=r.charAt(S[C]);return $}function m(d){if(typeof d!="string")throw new TypeError("Expected String");if(d.length===0)return new Uint8Array;var w=0;if(d[w]!==" "){for(var x=0,v=0;d[w]===c;)x++,w++;for(var I=(d.length-w)*l+1>>>0,A=new Uint8Array(I);d[w];){var S=t[d.charCodeAt(w)];if(S===255)return;for(var T=0,D=I-1;(S!==0||T<v)&&D!==-1;D--,T++)S+=a*A[D]>>>0,A[D]=S%256>>>0,S=S/256>>>0;if(S!==0)throw new Error("Non-zero carry");v=T,w++}if(d[w]!==" "){for(var k=I-v;k!==I&&A[k]===0;)k++;for(var C=new Uint8Array(x+(I-k)),$=x;k!==I;)C[$++]=A[k++];return C}}}function b(d){var w=m(d);if(w)return w;throw new Error(`Non-${e} character`)}return{encode:p,decodeUnsafe:m,decode:b}}var Bu=Ru,zu=Bu,fs=zu;var zn=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")}},On=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,n){this.name=e,this.prefix=t;let o=t.codePointAt(0);if(o===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=o,this.baseDecode=n}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return hs(this,e)}},Mn=class{decoders;constructor(e){this.decoders=e}or(e){return hs(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 hs(r,e){return new Mn({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var $n=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,n,o){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=o,this.encoder=new zn(e,t,n),this.decoder=new On(e,t,o)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function $e({name:r,prefix:e,encode:t,decode:n}){return new $n(r,e,t,n)}function Ee({name:r,prefix:e,alphabet:t}){let{encode:n,decode:o}=fs(t,r);return $e({prefix:e,name:r,encode:n,decode:i=>de(o(i))})}function Ou(r,e,t,n){let o=r.length;for(;r[o-1]==="=";)--o;let i=new Uint8Array(o*t/8|0),s=0,a=0,c=0;for(let l=0;l<o;++l){let f=e[r[l]];if(f===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<t|f,s+=t,s>=8&&(s-=8,i[c++]=255&a>>s)}if(s>=t||(255&a<<8-s)!==0)throw new SyntaxError("Unexpected end of data");return i}function Mu(r,e,t){let n=e[e.length-1]==="=",o=(1<<t)-1,i="",s=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],s+=8;s>t;)s-=t,i+=e[o&a>>s];if(s!==0&&(i+=e[o&a<<t-s]),n)for(;(i.length*t&7)!==0;)i+="=";return i}function $u(r){let e={};for(let t=0;t<r.length;++t)e[r[t]]=t;return e}function U({name:r,prefix:e,bitsPerChar:t,alphabet:n}){let o=$u(n);return $e({prefix:e,name:r,encode(i){return Mu(i,n,t)},decode(i){return Ou(i,o,t,r)}})}var Fu=Ee({prefix:"9",name:"base10",alphabet:"0123456789"});var qn={};_(qn,{base16:()=>qu,base16upper:()=>ju});var qu=U({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),ju=U({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var jn={};_(jn,{base2:()=>Vu});var Vu=U({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var Vn={};_(Vn,{base256emoji:()=>Qu});var ds=Array.from("\u{1F680}\u{1FA90}\u2604\u{1F6F0}\u{1F30C}\u{1F311}\u{1F312}\u{1F313}\u{1F314}\u{1F315}\u{1F316}\u{1F317}\u{1F318}\u{1F30D}\u{1F30F}\u{1F30E}\u{1F409}\u2600\u{1F4BB}\u{1F5A5}\u{1F4BE}\u{1F4BF}\u{1F602}\u2764\u{1F60D}\u{1F923}\u{1F60A}\u{1F64F}\u{1F495}\u{1F62D}\u{1F618}\u{1F44D}\u{1F605}\u{1F44F}\u{1F601}\u{1F525}\u{1F970}\u{1F494}\u{1F496}\u{1F499}\u{1F622}\u{1F914}\u{1F606}\u{1F644}\u{1F4AA}\u{1F609}\u263A\u{1F44C}\u{1F917}\u{1F49C}\u{1F614}\u{1F60E}\u{1F607}\u{1F339}\u{1F926}\u{1F389}\u{1F49E}\u270C\u2728\u{1F937}\u{1F631}\u{1F60C}\u{1F338}\u{1F64C}\u{1F60B}\u{1F497}\u{1F49A}\u{1F60F}\u{1F49B}\u{1F642}\u{1F493}\u{1F929}\u{1F604}\u{1F600}\u{1F5A4}\u{1F603}\u{1F4AF}\u{1F648}\u{1F447}\u{1F3B6}\u{1F612}\u{1F92D}\u2763\u{1F61C}\u{1F48B}\u{1F440}\u{1F62A}\u{1F611}\u{1F4A5}\u{1F64B}\u{1F61E}\u{1F629}\u{1F621}\u{1F92A}\u{1F44A}\u{1F973}\u{1F625}\u{1F924}\u{1F449}\u{1F483}\u{1F633}\u270B\u{1F61A}\u{1F61D}\u{1F634}\u{1F31F}\u{1F62C}\u{1F643}\u{1F340}\u{1F337}\u{1F63B}\u{1F613}\u2B50\u2705\u{1F97A}\u{1F308}\u{1F608}\u{1F918}\u{1F4A6}\u2714\u{1F623}\u{1F3C3}\u{1F490}\u2639\u{1F38A}\u{1F498}\u{1F620}\u261D\u{1F615}\u{1F33A}\u{1F382}\u{1F33B}\u{1F610}\u{1F595}\u{1F49D}\u{1F64A}\u{1F639}\u{1F5E3}\u{1F4AB}\u{1F480}\u{1F451}\u{1F3B5}\u{1F91E}\u{1F61B}\u{1F534}\u{1F624}\u{1F33C}\u{1F62B}\u26BD\u{1F919}\u2615\u{1F3C6}\u{1F92B}\u{1F448}\u{1F62E}\u{1F646}\u{1F37B}\u{1F343}\u{1F436}\u{1F481}\u{1F632}\u{1F33F}\u{1F9E1}\u{1F381}\u26A1\u{1F31E}\u{1F388}\u274C\u270A\u{1F44B}\u{1F630}\u{1F928}\u{1F636}\u{1F91D}\u{1F6B6}\u{1F4B0}\u{1F353}\u{1F4A2}\u{1F91F}\u{1F641}\u{1F6A8}\u{1F4A8}\u{1F92C}\u2708\u{1F380}\u{1F37A}\u{1F913}\u{1F619}\u{1F49F}\u{1F331}\u{1F616}\u{1F476}\u{1F974}\u25B6\u27A1\u2753\u{1F48E}\u{1F4B8}\u2B07\u{1F628}\u{1F31A}\u{1F98B}\u{1F637}\u{1F57A}\u26A0\u{1F645}\u{1F61F}\u{1F635}\u{1F44E}\u{1F932}\u{1F920}\u{1F927}\u{1F4CC}\u{1F535}\u{1F485}\u{1F9D0}\u{1F43E}\u{1F352}\u{1F617}\u{1F911}\u{1F30A}\u{1F92F}\u{1F437}\u260E\u{1F4A7}\u{1F62F}\u{1F486}\u{1F446}\u{1F3A4}\u{1F647}\u{1F351}\u2744\u{1F334}\u{1F4A3}\u{1F438}\u{1F48C}\u{1F4CD}\u{1F940}\u{1F922}\u{1F445}\u{1F4A1}\u{1F4A9}\u{1F450}\u{1F4F8}\u{1F47B}\u{1F910}\u{1F92E}\u{1F3BC}\u{1F975}\u{1F6A9}\u{1F34E}\u{1F34A}\u{1F47C}\u{1F48D}\u{1F4E3}\u{1F942}"),Ku=ds.reduce((r,e,t)=>(r[t]=e,r),[]),Hu=ds.reduce((r,e,t)=>{let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);return r[n]=t,r},[]);function Wu(r){return r.reduce((e,t)=>(e+=Ku[t],e),"")}function Gu(r){let e=[];for(let t of r){let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);let o=Hu[n];if(o==null)throw new Error(`Non-base256emoji character: ${t}`);e.push(o)}return new Uint8Array(e)}var Qu=$e({prefix:"\u{1F680}",name:"base256emoji",encode:Wu,decode:Gu});var Kn={};_(Kn,{base32:()=>Fe,base32hex:()=>Zu,base32hexpad:()=>tl,base32hexpadupper:()=>rl,base32hexupper:()=>el,base32pad:()=>Xu,base32padupper:()=>Yu,base32upper:()=>Ju,base32z:()=>nl});var Fe=U({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Ju=U({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Xu=U({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Yu=U({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Zu=U({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),el=U({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),tl=U({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),rl=U({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),nl=U({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Hn={};_(Hn,{base36:()=>vt,base36upper:()=>ol});var vt=Ee({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),ol=Ee({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var Wn={};_(Wn,{base58btc:()=>se,base58flickr:()=>il});var se=Ee({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),il=Ee({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var Gn={};_(Gn,{base64:()=>sl,base64pad:()=>al,base64url:()=>cl,base64urlpad:()=>ul});var sl=U({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),al=U({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),cl=U({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),ul=U({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var Qn={};_(Qn,{base8:()=>ll});var ll=U({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var Jn={};_(Jn,{identity:()=>fl});var fl=$e({prefix:"\0",name:"identity",encode:r=>us(r),decode:r=>cs(r)});var ag=new TextEncoder,cg=new TextDecoder;var Yn={};_(Yn,{identity:()=>Ul});var pl=gs,ps=128,ml=127,gl=~ml,yl=Math.pow(2,31);function gs(r,e,t){e=e||[],t=t||0;for(var n=t;r>=yl;)e[t++]=r&255|ps,r/=128;for(;r&gl;)e[t++]=r&255|ps,r>>>=7;return e[t]=r|0,gs.bytes=t-n+1,e}var wl=Xn,bl=128,ms=127;function Xn(r,n){var t=0,n=n||0,o=0,i=n,s,a=r.length;do{if(i>=a)throw Xn.bytes=0,new RangeError("Could not decode varint");s=r[i++],t+=o<28?(s&ms)<<o:(s&ms)*Math.pow(2,o),o+=7}while(s>=bl);return Xn.bytes=i-n,t}var xl=Math.pow(2,7),El=Math.pow(2,14),vl=Math.pow(2,21),_l=Math.pow(2,28),Al=Math.pow(2,35),Sl=Math.pow(2,42),Il=Math.pow(2,49),kl=Math.pow(2,56),Tl=Math.pow(2,63),Ll=function(r){return r<xl?1:r<El?2:r<vl?3:r<_l?4:r<Al?5:r<Sl?6:r<Il?7:r<kl?8:r<Tl?9:10},Cl={encode:pl,decode:wl,encodingLength:Ll},Dl=Cl,_t=Dl;function At(r,e=0){return[_t.decode(r,e),_t.decode.bytes]}function qe(r,e,t=0){return _t.encode(r,e,t),e}function je(r){return _t.encodingLength(r)}function Ke(r,e){let t=e.byteLength,n=je(r),o=n+je(t),i=new Uint8Array(o+t);return qe(r,i,0),qe(t,i,n),i.set(e,o),new Ve(r,t,e,i)}function ys(r){let e=de(r),[t,n]=At(e),[o,i]=At(e.subarray(n)),s=e.subarray(n+i);if(s.byteLength!==o)throw new Error("Incorrect length");return new Ve(t,o,s,e)}function ws(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&as(r.bytes,t.bytes)}}var Ve=class{code;size;digest;bytes;constructor(e,t,n,o){this.code=e,this.size=t,this.digest=n,this.bytes=o}};var bs=0,Pl="identity",xs=de;function Nl(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 Ke(bs,xs(r))}var Ul={code:bs,name:Pl,encode:xs,digest:Nl};var to={};_(to,{sha256:()=>Bl,sha512:()=>zl});var Rl=20;function eo({name:r,code:e,encode:t,minDigestLength:n,maxDigestLength:o}){return new Zn(r,e,t,n,o)}var Zn=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,n,o,i){this.name=e,this.code=t,this.encode=n,this.minDigestLength=o??Rl,this.maxDigestLength=i}digest(e,t){if(t?.truncate!=null){if(t.truncate<this.minDigestLength)throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`);if(this.maxDigestLength!=null&&t.truncate>this.maxDigestLength)throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`)}if(e instanceof Uint8Array){let n=this.encode(e);return n instanceof Uint8Array?Es(n,this.code,t?.truncate):n.then(o=>Es(o,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}};function Es(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 Ke(e,r)}function _s(r){return async e=>new Uint8Array(await crypto.subtle.digest(r,e))}var Bl=eo({name:"sha2-256",code:18,encode:_s("SHA-256")}),zl=eo({name:"sha2-512",code:19,encode:_s("SHA-512")});function As(r,e){let{bytes:t,version:n}=r;return n===0?Ml(t,ro(r),e??se.encoder):$l(t,ro(r),e??Fe.encoder)}var Ss=new WeakMap;function ro(r){let e=Ss.get(r);if(e==null){let t=new Map;return Ss.set(r,t),t}return e}var sr=class r{code;version;multihash;bytes;"/";constructor(e,t,n,o){this.code=t,this.version=e,this.multihash=n,this.bytes=o,this["/"]=o}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:e,multihash:t}=this;if(e!==It)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==Fl)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=Ke(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&&ws(e.multihash,n.multihash)}toString(e){return As(this,e)}toJSON(){return{"/":As(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(e){if(e==null)return null;let t=e;if(t instanceof r)return t;if(t["/"]!=null&&t["/"]===t.bytes||t.asCID===t){let{version:n,code:o,multihash:i,bytes:s}=t;return new r(n,o,i,s??Is(n,o,i.bytes))}else if(t[ql]===!0){let{version:n,multihash:o,code:i}=t,s=ys(o);return r.create(n,i,s)}else return null}static create(e,t,n){if(typeof t!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(e){case 0:{if(t!==It)throw new Error(`Version 0 CID must use dag-pb (code: ${It}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let o=Is(e,t,n.bytes);return new r(e,t,n,o)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,It,e)}static createV1(e,t){return r.create(1,e,t)}static decode(e){let[t,n]=r.decodeFirst(e);if(n.length!==0)throw new Error("Incorrect length");return t}static decodeFirst(e){let t=r.inspectBytes(e),n=t.size-t.multihashSize,o=de(e.subarray(n,n+t.multihashSize));if(o.byteLength!==t.multihashSize)throw new Error("Incorrect length");let i=o.subarray(t.multihashSize-t.digestSize),s=new Ve(t.multihashCode,t.digestSize,i,o);return[t.version===0?r.createV0(s):r.createV1(t.codec,s),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[p,m]=At(e.subarray(t));return t+=m,p},o=n(),i=It;if(o===18?(o=0,t=0):i=n(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);let s=t,a=n(),c=n(),l=t+c,f=l-s;return{version:o,codec:i,multihashCode:a,digestSize:c,multihashSize:f,size:l}}static parse(e,t){let[n,o]=Ol(e,t),i=r.decode(o);if(i.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return ro(i).set(n,e),i}};function Ol(r,e){switch(r[0]){case"Q":{let t=e??se;return[se.prefix,t.decode(`${se.prefix}${r}`)]}case se.prefix:{let t=e??se;return[se.prefix,t.decode(r)]}case Fe.prefix:{let t=e??Fe;return[Fe.prefix,t.decode(r)]}case vt.prefix:{let t=e??vt;return[vt.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 Ml(r,e,t){let{prefix:n}=t;if(n!==se.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let o=e.get(n);if(o==null){let i=t.encode(r).slice(1);return e.set(n,i),i}else return o}function $l(r,e,t){let{prefix:n}=t,o=e.get(n);if(o==null){let i=t.encode(r);return e.set(n,i),i}else return o}var It=112,Fl=18;function Is(r,e,t){let n=je(r),o=n+je(e),i=new Uint8Array(o+t.byteLength);return qe(r,i,0),qe(e,i,n),i.set(t,o),i}var ql=Symbol.for("@ipld/js-cid/CID");var no={...Jn,...jn,...Qn,...Fn,...qn,...Kn,...Hn,...Wn,...Gn,...Vn},Cg={...to,...Yn};function ks(r=0){return new Uint8Array(r)}function Ls(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var Ts=Ls("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),oo=Ls("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=ks(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),jl={utf8:Ts,"utf-8":Ts,hex:no.base16,latin1:oo,ascii:oo,binary:oo,...no},Cs=jl;function Ds(r,e="utf8"){let t=Cs[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.encoder.encode(r).substring(1)}var io=60;function ar(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:Y[e.type]})),Answer:(r.Answer??r.answers??[]).map(e=>({name:e.name,type:Y[e.type],TTL:e.TTL??e.ttl??io,data:e.data instanceof Uint8Array?Ds(e.data):e.data}))}}var Vl=4;function so(r,e={}){let t=new Et({concurrency:e.queryConcurrency??Vl});return async(n,o={})=>{let i=o?.logger?.forComponent("dns:dns-json-over-https"),s=new URLSearchParams;s.set("name",n),or(o.types).forEach(c=>{s.append("type",Y[c])}),o.onProgress?.(new E("dns:query",n)),i?.("GET %s",`${r}?${s}`);let a=await t.add(async()=>{let c=await fetch(`${r}?${s}`,{headers:{accept:"application/dns-json"},signal:o?.signal});if(i?.("GET %s %d",c.url,c.status),c.status!==200)throw new Error(`Unexpected HTTP status: ${c.status} - ${c.statusText}`);let l=ar(await c.json());return o.onProgress?.(new E("dns:response",l)),l},{signal:o.signal});if(a==null)throw new Error("No DNS response received");return a}}function Ps(){return[so("https://cloudflare-dns.com/dns-query"),so("https://dns.google/resolve")]}var Rs=es(Us(),1);var ao=class{lru;constructor(e){this.lru=(0,Rs.default)(e)}get(e,t){let n=!0,o=[];for(let i of t){let s=this.getAnswers(e,i);if(s.length===0){n=!1;break}o.push(...s)}if(n)return ar({answers:o})}getAnswers(e,t){let n=`${e.toLowerCase()}-${t}`,o=this.lru.get(n);if(o!=null){let i=o.filter(s=>s.expires>Date.now()).map(({expires:s,value:a})=>({...a,TTL:Math.round((s-Date.now())/1e3),type:Y[a.type]}));return i.length===0&&this.lru.remove(n),i}return[]}add(e,t){let n=`${e.toLowerCase()}-${t.type}`,o=this.lru.get(n)??[];o.push({expires:Date.now()+(t.TTL??io)*1e3,value:t}),this.lru.set(n,o)}remove(e,t){let n=`${e.toLowerCase()}-${t}`;this.lru.remove(n)}clear(){this.lru.clear()}};function Bs(r){return new ao(r)}var Kl=1e3,cr=class{resolvers;cache;logger;constructor(e){this.resolvers={},this.cache=Bs(e.cacheSize??Kl),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["."]=Ps())}async query(e,t={}){let n=or(t.types),o=t.cached!==!1?this.cache.get(e,n):void 0;if(o!=null)return t.onProgress?.(new E("dns:cache",o)),o;let i=`${e.split(".").pop()}.`,s=(this.resolvers[i]??this.resolvers["."]).sort(()=>Math.random()>.5?-1:1),a=[];for(let c of s){if(t.signal?.aborted===!0)break;try{let l=await c(e,{...t,logger:this.logger,types:n});for(let f of l.Answer)this.cache.add(e,f);return l}catch(l){a.push(l),t.onProgress?.(new E("dns:error",l))}}throw new rr(a,`DNS lookup of ${e} ${n} failed`)}};var Y;(function(r){r[r.A=1]="A",r[r.CNAME=5]="CNAME",r[r.TXT=16]="TXT",r[r.AAAA=28]="AAAA"})(Y||(Y={}));function zs(r={}){return new cr(r)}function Hl(r){return r[Symbol.asyncIterator]!=null}function Wl(r){if(Hl(r))return(async()=>{for await(let e of r);})();for(let e of r);}var Os=Wl;function Ms(r=0){return new Uint8Array(r)}function $s(r=0){return new Uint8Array(r)}function Fs(r,e){if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return!1;return!0}var ho={};_(ho,{base10:()=>ef});var ly=new Uint8Array(0);function qs(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 pe(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 js(r){return new TextEncoder().encode(r)}function Vs(r){return new TextDecoder().decode(r)}function Gl(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),n=0;n<t.length;n++)t[n]=255;for(var o=0;o<r.length;o++){var i=r.charAt(o),s=i.charCodeAt(0);if(t[s]!==255)throw new TypeError(i+" is ambiguous");t[s]=o}var a=r.length,c=r.charAt(0),l=Math.log(a)/Math.log(256),f=Math.log(256)/Math.log(a);function p(d){if(d instanceof Uint8Array||(ArrayBuffer.isView(d)?d=new Uint8Array(d.buffer,d.byteOffset,d.byteLength):Array.isArray(d)&&(d=Uint8Array.from(d))),!(d instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(d.length===0)return"";for(var w=0,x=0,v=0,I=d.length;v!==I&&d[v]===0;)v++,w++;for(var A=(I-v)*f+1>>>0,S=new Uint8Array(A);v!==I;){for(var T=d[v],D=0,k=A-1;(T!==0||D<x)&&k!==-1;k--,D++)T+=256*S[k]>>>0,S[k]=T%a>>>0,T=T/a>>>0;if(T!==0)throw new Error("Non-zero carry");x=D,v++}for(var C=A-x;C!==A&&S[C]===0;)C++;for(var $=c.repeat(w);C<A;++C)$+=r.charAt(S[C]);return $}function m(d){if(typeof d!="string")throw new TypeError("Expected String");if(d.length===0)return new Uint8Array;var w=0;if(d[w]!==" "){for(var x=0,v=0;d[w]===c;)x++,w++;for(var I=(d.length-w)*l+1>>>0,A=new Uint8Array(I);d[w];){var S=t[d.charCodeAt(w)];if(S===255)return;for(var T=0,D=I-1;(S!==0||T<v)&&D!==-1;D--,T++)S+=a*A[D]>>>0,A[D]=S%256>>>0,S=S/256>>>0;if(S!==0)throw new Error("Non-zero carry");v=T,w++}if(d[w]!==" "){for(var k=I-v;k!==I&&A[k]===0;)k++;for(var C=new Uint8Array(x+(I-k)),$=x;k!==I;)C[$++]=A[k++];return C}}}function b(d){var w=m(d);if(w)return w;throw new Error(`Non-${e} character`)}return{encode:p,decodeUnsafe:m,decode:b}}var Ql=Gl,Jl=Ql,Hs=Jl;var co=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")}},uo=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,n){this.name=e,this.prefix=t;let o=t.codePointAt(0);if(o===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=o,this.baseDecode=n}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return Ws(this,e)}},lo=class{decoders;constructor(e){this.decoders=e}or(e){return Ws(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 Ws(r,e){return new lo({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var fo=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,n,o){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=o,this.encoder=new co(e,t,n),this.decoder=new uo(e,t,o)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function He({name:r,prefix:e,encode:t,decode:n}){return new fo(r,e,t,n)}function ve({name:r,prefix:e,alphabet:t}){let{encode:n,decode:o}=Hs(t,r);return He({prefix:e,name:r,encode:n,decode:i=>pe(o(i))})}function Xl(r,e,t,n){let o=r.length;for(;r[o-1]==="=";)--o;let i=new Uint8Array(o*t/8|0),s=0,a=0,c=0;for(let l=0;l<o;++l){let f=e[r[l]];if(f===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<t|f,s+=t,s>=8&&(s-=8,i[c++]=255&a>>s)}if(s>=t||(255&a<<8-s)!==0)throw new SyntaxError("Unexpected end of data");return i}function Yl(r,e,t){let n=e[e.length-1]==="=",o=(1<<t)-1,i="",s=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],s+=8;s>t;)s-=t,i+=e[o&a>>s];if(s!==0&&(i+=e[o&a<<t-s]),n)for(;(i.length*t&7)!==0;)i+="=";return i}function Zl(r){let e={};for(let t=0;t<r.length;++t)e[r[t]]=t;return e}function R({name:r,prefix:e,bitsPerChar:t,alphabet:n}){let o=Zl(n);return He({prefix:e,name:r,encode(i){return Yl(i,n,t)},decode(i){return Xl(i,o,t,r)}})}var ef=ve({prefix:"9",name:"base10",alphabet:"0123456789"});var po={};_(po,{base16:()=>tf,base16upper:()=>rf});var tf=R({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),rf=R({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var mo={};_(mo,{base2:()=>nf});var nf=R({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var go={};_(go,{base256emoji:()=>uf});var Gs=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}"),of=Gs.reduce((r,e,t)=>(r[t]=e,r),[]),sf=Gs.reduce((r,e,t)=>{let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);return r[n]=t,r},[]);function af(r){return r.reduce((e,t)=>(e+=of[t],e),"")}function cf(r){let e=[];for(let t of r){let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);let o=sf[n];if(o==null)throw new Error(`Non-base256emoji character: ${t}`);e.push(o)}return new Uint8Array(e)}var uf=He({prefix:"\u{1F680}",name:"base256emoji",encode:af,decode:cf});var yo={};_(yo,{base32:()=>We,base32hex:()=>df,base32hexpad:()=>mf,base32hexpadupper:()=>gf,base32hexupper:()=>pf,base32pad:()=>ff,base32padupper:()=>hf,base32upper:()=>lf,base32z:()=>yf});var We=R({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),lf=R({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),ff=R({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),hf=R({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),df=R({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),pf=R({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),mf=R({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),gf=R({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),yf=R({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var wo={};_(wo,{base36:()=>kt,base36upper:()=>wf});var kt=ve({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),wf=ve({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var bo={};_(bo,{base58btc:()=>ae,base58flickr:()=>bf});var ae=ve({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),bf=ve({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var xo={};_(xo,{base64:()=>xf,base64pad:()=>Ef,base64url:()=>vf,base64urlpad:()=>_f});var xf=R({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Ef=R({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),vf=R({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),_f=R({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var Eo={};_(Eo,{base8:()=>Af});var Af=R({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var vo={};_(vo,{identity:()=>Sf});var Sf=He({prefix:"\0",name:"identity",encode:r=>Vs(r),decode:r=>js(r)});var Iy=new TextEncoder,ky=new TextDecoder;var Ao={};_(Ao,{identity:()=>Gf});var Tf=Xs,Qs=128,Lf=127,Cf=~Lf,Df=Math.pow(2,31);function Xs(r,e,t){e=e||[],t=t||0;for(var n=t;r>=Df;)e[t++]=r&255|Qs,r/=128;for(;r&Cf;)e[t++]=r&255|Qs,r>>>=7;return e[t]=r|0,Xs.bytes=t-n+1,e}var Pf=_o,Nf=128,Js=127;function _o(r,n){var t=0,n=n||0,o=0,i=n,s,a=r.length;do{if(i>=a)throw _o.bytes=0,new RangeError("Could not decode varint");s=r[i++],t+=o<28?(s&Js)<<o:(s&Js)*Math.pow(2,o),o+=7}while(s>=Nf);return _o.bytes=i-n,t}var Uf=Math.pow(2,7),Rf=Math.pow(2,14),Bf=Math.pow(2,21),zf=Math.pow(2,28),Of=Math.pow(2,35),Mf=Math.pow(2,42),$f=Math.pow(2,49),Ff=Math.pow(2,56),qf=Math.pow(2,63),jf=function(r){return r<Uf?1:r<Rf?2:r<Bf?3:r<zf?4:r<Of?5:r<Mf?6:r<$f?7:r<Ff?8:r<qf?9:10},Vf={encode:Tf,decode:Pf,encodingLength:jf},Kf=Vf,Tt=Kf;function Lt(r,e=0){return[Tt.decode(r,e),Tt.decode.bytes]}function Ge(r,e,t=0){return Tt.encode(r,e,t),e}function Qe(r){return Tt.encodingLength(r)}function Xe(r,e){let t=e.byteLength,n=Qe(r),o=n+Qe(t),i=new Uint8Array(o+t);return Ge(r,i,0),Ge(t,i,n),i.set(e,o),new Je(r,t,e,i)}function Ys(r){let e=pe(r),[t,n]=Lt(e),[o,i]=Lt(e.subarray(n)),s=e.subarray(n+i);if(s.byteLength!==o)throw new Error("Incorrect length");return new Je(t,o,s,e)}function Zs(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&qs(r.bytes,t.bytes)}}var Je=class{code;size;digest;bytes;constructor(e,t,n,o){this.code=e,this.size=t,this.digest=n,this.bytes=o}};var ea=0,Hf="identity",ta=pe;function Wf(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 Xe(ea,ta(r))}var Gf={code:ea,name:Hf,encode:ta,digest:Wf};var ko={};_(ko,{sha256:()=>Jf,sha512:()=>Xf});var Qf=20;function Io({name:r,code:e,encode:t,minDigestLength:n,maxDigestLength:o}){return new So(r,e,t,n,o)}var So=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,n,o,i){this.name=e,this.code=t,this.encode=n,this.minDigestLength=o??Qf,this.maxDigestLength=i}digest(e,t){if(t?.truncate!=null){if(t.truncate<this.minDigestLength)throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`);if(this.maxDigestLength!=null&&t.truncate>this.maxDigestLength)throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`)}if(e instanceof Uint8Array){let n=this.encode(e);return n instanceof Uint8Array?ra(n,this.code,t?.truncate):n.then(o=>ra(o,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}};function ra(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 Xe(e,r)}function oa(r){return async e=>new Uint8Array(await crypto.subtle.digest(r,e))}var Jf=Io({name:"sha2-256",code:18,encode:oa("SHA-256")}),Xf=Io({name:"sha2-512",code:19,encode:oa("SHA-512")});function ia(r,e){let{bytes:t,version:n}=r;return n===0?Zf(t,To(r),e??ae.encoder):eh(t,To(r),e??We.encoder)}var sa=new WeakMap;function To(r){let e=sa.get(r);if(e==null){let t=new Map;return sa.set(r,t),t}return e}var lr=class r{code;version;multihash;bytes;"/";constructor(e,t,n,o){this.code=t,this.version=e,this.multihash=n,this.bytes=o,this["/"]=o}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:e,multihash:t}=this;if(e!==Dt)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==th)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=Xe(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&&Zs(e.multihash,n.multihash)}toString(e){return ia(this,e)}toJSON(){return{"/":ia(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(e){if(e==null)return null;let t=e;if(t instanceof r)return t;if(t["/"]!=null&&t["/"]===t.bytes||t.asCID===t){let{version:n,code:o,multihash:i,bytes:s}=t;return new r(n,o,i,s??aa(n,o,i.bytes))}else if(t[rh]===!0){let{version:n,multihash:o,code:i}=t,s=Ys(o);return r.create(n,i,s)}else return null}static create(e,t,n){if(typeof t!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(e){case 0:{if(t!==Dt)throw new Error(`Version 0 CID must use dag-pb (code: ${Dt}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let o=aa(e,t,n.bytes);return new r(e,t,n,o)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,Dt,e)}static createV1(e,t){return r.create(1,e,t)}static decode(e){let[t,n]=r.decodeFirst(e);if(n.length!==0)throw new Error("Incorrect length");return t}static decodeFirst(e){let t=r.inspectBytes(e),n=t.size-t.multihashSize,o=pe(e.subarray(n,n+t.multihashSize));if(o.byteLength!==t.multihashSize)throw new Error("Incorrect length");let i=o.subarray(t.multihashSize-t.digestSize),s=new Je(t.multihashCode,t.digestSize,i,o);return[t.version===0?r.createV0(s):r.createV1(t.codec,s),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[p,m]=Lt(e.subarray(t));return t+=m,p},o=n(),i=Dt;if(o===18?(o=0,t=0):i=n(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);let s=t,a=n(),c=n(),l=t+c,f=l-s;return{version:o,codec:i,multihashCode:a,digestSize:c,multihashSize:f,size:l}}static parse(e,t){let[n,o]=Yf(e,t),i=r.decode(o);if(i.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return To(i).set(n,e),i}};function Yf(r,e){switch(r[0]){case"Q":{let t=e??ae;return[ae.prefix,t.decode(`${ae.prefix}${r}`)]}case ae.prefix:{let t=e??ae;return[ae.prefix,t.decode(r)]}case We.prefix:{let t=e??We;return[We.prefix,t.decode(r)]}case kt.prefix:{let t=e??kt;return[kt.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 Zf(r,e,t){let{prefix:n}=t;if(n!==ae.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let o=e.get(n);if(o==null){let i=t.encode(r).slice(1);return e.set(n,i),i}else return o}function eh(r,e,t){let{prefix:n}=t,o=e.get(n);if(o==null){let i=t.encode(r);return e.set(n,i),i}else return o}var Dt=112,th=18;function aa(r,e,t){let n=Qe(r),o=n+Qe(e),i=new Uint8Array(o+t.byteLength);return Ge(r,i,0),Ge(e,i,n),i.set(t,o),i}var rh=Symbol.for("@ipld/js-cid/CID");var Lo={...vo,...mo,...Eo,...ho,...po,...yo,...wo,...bo,...xo,...go},Qy={...ko,...Ao};function ua(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var ca=ua("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),Co=ua("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=$s(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),nh={utf8:ca,"utf-8":ca,hex:Lo.base16,latin1:Co,ascii:Co,binary:Co,...Lo},la=nh;function ce(r,e="utf8"){let t=la[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.decoder.decode(`${t.prefix}${r}`)}var Do={32:16777619n,64:1099511628211n,128:309485009821345068724781371n,256:374144419156711147060143317175368453031918731002211n,512:35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759n,1024:5016456510113118655434598811035278955030765345404790744303017523831112055108147451509157692220295382716162651878526895249385292291816524375083746691371804094271873160484737966720260389217684476157468082573n},fa={32:2166136261n,64:14695981039346656037n,128:144066263297769815596495629667062367629n,256:100029257958052580907070968620625704837092796014241193945225284501741471925557n,512:9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785n,1024:14197795064947621068722070641403218320880622795441933960878474914617582723252296732303717722150864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915n},ha=new globalThis.TextEncoder;function oh(r,e){let t=Do[e],n=fa[e];for(let o=0;o<r.length;o++)n^=BigInt(r[o]),n=BigInt.asUintN(e,n*t);return n}function ih(r,e,t){if(t.length===0)throw new Error("The `utf8Buffer` option must have a length greater than zero");let n=Do[e],o=fa[e],i=r;for(;i.length>0;){let s=ha.encodeInto(i,t);i=i.slice(s.read);for(let a=0;a<s.written;a++)o^=BigInt(t[a]),o=BigInt.asUintN(e,o*n)}return o}function Po(r,{size:e=32,utf8Buffer:t}={}){if(!Do[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 ih(r,e,t);r=ha.encode(r)}return oh(r,e)}var Pt={hash:r=>Number(Po(r,{size:32})),hashV:(r,e)=>sh(Pt.hash(r,e))};function sh(r){let e=r.toString(16);return e.length%2===1&&(e=`0${e}`),ce(e,"base16")}var No=64,Z=class{fp;h;seed;constructor(e,t,n,o=2){if(o>No)throw new TypeError("Invalid Fingerprint Size");let i=t.hashV(e,n),s=Ms(o);for(let a=0;a<s.length;a++)s[a]=i[a];s.length===0&&(s[0]=7),this.fp=s,this.h=t,this.seed=n}hash(){return this.h.hash(this.fp,this.seed)}equals(e){return e?.fp instanceof Uint8Array?Fs(this.fp,e.fp):!1}};function Te(r,e){return Math.floor(Math.random()*(e-r))+r}var Le=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=Te(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 ah=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??Pt,this.seed=e.seed??Te(0,Math.pow(2,10))}add(e){typeof e=="string"&&(e=ce(e));let t=new Z(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,o=(n^t.hash())%this.filterSize;if(this.buckets[n]==null&&(this.buckets[n]=new Le(this.bucketSize)),this.buckets[o]==null&&(this.buckets[o]=new Le(this.bucketSize)),this.buckets[n].add(t)||this.buckets[o].add(t))return this.count++,!0;let i=[n,o],s=i[Te(0,i.length-1)];this.buckets[s]==null&&(this.buckets[s]=new Le(this.bucketSize));for(let a=0;a<ah;a++){let c=this.buckets[s].swap(t);if(c!=null&&(s=(s^c.hash())%this.filterSize,this.buckets[s]==null&&(this.buckets[s]=new Le(this.bucketSize)),this.buckets[s].add(c)))return this.count++,!0}return!1}has(e){typeof e=="string"&&(e=ce(e));let t=new Z(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,o=this.buckets[n]?.has(t)??!1;if(o)return o;let i=(n^t.hash())%this.filterSize;return this.buckets[i]?.has(t)??!1}remove(e){typeof e=="string"&&(e=ce(e));let t=new Z(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,o=this.buckets[n]?.remove(t)??!1;if(o)return this.count--,o;let i=(n^t.hash())%this.filterSize,s=this.buckets[i]?.remove(t)??!1;return s&&this.count--,s}get reliable(){return Math.floor(100*(this.count/this.filterSize))<=90}},ch={1:.5,2:.84,4:.95,8:.98};function uh(r=.001){return r>.002?2:r>1e-5?4:8}function da(r,e=.001){let t=uh(e),n=ch[t],o=Math.round(r/n),i=Math.min(Math.ceil(Math.log2(1/e)+Math.log2(2*t)),No);return{filterSize:o,bucketSize:t,fingerprintSize:i}}var fr=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??Pt,this.seed=e.seed??Te(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=ce(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=ce(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=ce(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 hr(r,e=.001,t){return new fr({...da(r,e),...t??{}})}function Ut(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 dr(r=0){return new Uint8Array(r)}function lh(r){return r?.buffer instanceof ArrayBuffer}function pa(r){if(lh(r))return r;let e=r.slice();return new Uint8Array(e.buffer,0,e.byteLength)}function Uo(r,e){e==null&&(e=r.reduce((o,i)=>o+i.length,0));let t=dr(e),n=0;for(let o of r)t.set(o,n),n+=o.length;return pa(t)}var $o={};_($o,{base10:()=>wh});var Pw=new Uint8Array(0);function ma(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 ee(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return Ce(r);if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return Ce(new Uint8Array(r.buffer,r.byteOffset,r.byteLength));throw new Error("Unknown type, must be binary type")}function ga(r){return new TextEncoder().encode(r)}function ya(r){return new TextDecoder().decode(r)}function fh(r){return r?.buffer instanceof ArrayBuffer}function Ce(r){return fh(r)?r:r.slice()}function hh(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),n=0;n<t.length;n++)t[n]=255;for(var o=0;o<r.length;o++){var i=r.charAt(o),s=i.charCodeAt(0);if(t[s]!==255)throw new TypeError(i+" is ambiguous");t[s]=o}var a=r.length,c=r.charAt(0),l=Math.log(a)/Math.log(256),f=Math.log(256)/Math.log(a);function p(d){if(d instanceof Uint8Array||(ArrayBuffer.isView(d)?d=new Uint8Array(d.buffer,d.byteOffset,d.byteLength):Array.isArray(d)&&(d=Uint8Array.from(d))),!(d instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(d.length===0)return"";for(var w=0,x=0,v=0,I=d.length;v!==I&&d[v]===0;)v++,w++;for(var A=(I-v)*f+1>>>0,S=new Uint8Array(A);v!==I;){for(var T=d[v],D=0,k=A-1;(T!==0||D<x)&&k!==-1;k--,D++)T+=256*S[k]>>>0,S[k]=T%a>>>0,T=T/a>>>0;if(T!==0)throw new Error("Non-zero carry");x=D,v++}for(var C=A-x;C!==A&&S[C]===0;)C++;for(var $=c.repeat(w);C<A;++C)$+=r.charAt(S[C]);return $}function m(d){if(typeof d!="string")throw new TypeError("Expected String");if(d.length===0)return new Uint8Array;var w=0;if(d[w]!==" "){for(var x=0,v=0;d[w]===c;)x++,w++;for(var I=(d.length-w)*l+1>>>0,A=new Uint8Array(I);d[w];){var S=t[d.charCodeAt(w)];if(S===255)return;for(var T=0,D=I-1;(S!==0||T<v)&&D!==-1;D--,T++)S+=a*A[D]>>>0,A[D]=S%256>>>0,S=S/256>>>0;if(S!==0)throw new Error("Non-zero carry");v=T,w++}if(d[w]!==" "){for(var k=I-v;k!==I&&A[k]===0;)k++;for(var C=new Uint8Array(x+(I-k)),$=x;k!==I;)C[$++]=A[k++];return C}}}function b(d){var w=m(d);if(w)return w;throw new Error(`Non-${e} character`)}return{encode:p,decodeUnsafe:m,decode:b}}var dh=hh,ph=dh,wa=ph;var Bo=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")}},zo=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,n){this.name=e,this.prefix=t;let o=t.codePointAt(0);if(o===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=o,this.baseDecode=n}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return ba(this,e)}},Oo=class{decoders;constructor(e){this.decoders=e}or(e){return ba(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 ba(r,e){return new Oo({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var Mo=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,n,o){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=o,this.encoder=new Bo(e,t,n),this.decoder=new zo(e,t,o)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function Ye({name:r,prefix:e,encode:t,decode:n}){return new Mo(r,e,t,n)}function _e({name:r,prefix:e,alphabet:t}){let{encode:n,decode:o}=wa(t,r);return Ye({prefix:e,name:r,encode:n,decode:i=>ee(o(i))})}function mh(r,e,t,n){let o=r.length;for(;r[o-1]==="=";)--o;let i=new Uint8Array(o*t/8|0),s=0,a=0,c=0;for(let l=0;l<o;++l){let f=e[r[l]];if(f===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<t|f,s+=t,s>=8&&(s-=8,i[c++]=255&a>>s)}if(s>=t||(255&a<<8-s)!==0)throw new SyntaxError("Unexpected end of data");return i}function gh(r,e,t){let n=e[e.length-1]==="=",o=(1<<t)-1,i="",s=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],s+=8;s>t;)s-=t,i+=e[o&a>>s];if(s!==0&&(i+=e[o&a<<t-s]),n)for(;(i.length*t&7)!==0;)i+="=";return i}function yh(r){let e={};for(let t=0;t<r.length;++t)e[r[t]]=t;return e}function B({name:r,prefix:e,bitsPerChar:t,alphabet:n}){let o=yh(n);return Ye({prefix:e,name:r,encode(i){return gh(i,n,t)},decode(i){return mh(i,o,t,r)}})}var wh=_e({prefix:"9",name:"base10",alphabet:"0123456789"});var Fo={};_(Fo,{base16:()=>bh,base16upper:()=>xh});var bh=B({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),xh=B({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var qo={};_(qo,{base2:()=>Eh});var Eh=B({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var jo={};_(jo,{base256emoji:()=>Ih});var xa=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}"),vh=xa.reduce((r,e,t)=>(r[t]=e,r),[]),_h=xa.reduce((r,e,t)=>{let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);return r[n]=t,r},[]);function Ah(r){return r.reduce((e,t)=>(e+=vh[t],e),"")}function Sh(r){let e=[];for(let t of r){let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);let o=_h[n];if(o==null)throw new Error(`Non-base256emoji character: ${t}`);e.push(o)}return new Uint8Array(e)}var Ih=Ye({prefix:"\u{1F680}",name:"base256emoji",encode:Ah,decode:Sh});var Vo={};_(Vo,{base32:()=>Ze,base32hex:()=>Ch,base32hexpad:()=>Ph,base32hexpadupper:()=>Nh,base32hexupper:()=>Dh,base32pad:()=>Th,base32padupper:()=>Lh,base32upper:()=>kh,base32z:()=>Uh});var Ze=B({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),kh=B({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Th=B({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Lh=B({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Ch=B({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Dh=B({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Ph=B({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Nh=B({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Uh=B({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Ko={};_(Ko,{base36:()=>me,base36upper:()=>Rh});var me=_e({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Rh=_e({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var Ho={};_(Ho,{base58btc:()=>ue,base58flickr:()=>Bh});var ue=_e({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Bh=_e({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var Wo={};_(Wo,{base64:()=>et,base64pad:()=>zh,base64url:()=>Oh,base64urlpad:()=>Mh});var et=B({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),zh=B({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Oh=B({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Mh=B({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var Go={};_(Go,{base8:()=>$h});var $h=B({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var Qo={};_(Qo,{identity:()=>Fh});var Fh=Ye({prefix:"\0",name:"identity",encode:r=>ya(r),decode:r=>ga(r)});var pr={};_(pr,{code:()=>Jo,decode:()=>Hh,encode:()=>Kh,name:()=>Vh});var qh=new TextEncoder,jh=new TextDecoder,Vh="json",Jo=512;function Kh(r){return qh.encode(JSON.stringify(r))}function Hh(r){return JSON.parse(jh.decode(r))}var mr={};_(mr,{code:()=>Xo,decode:()=>Qh,encode:()=>Gh,name:()=>Wh});var Wh="raw",Xo=85;function Gh(r){return ee(r)}function Qh(r){return ee(r)}var Zo={};_(Zo,{identity:()=>yr});var Jh=_a,Ea=128,Xh=127,Yh=~Xh,Zh=Math.pow(2,31);function _a(r,e,t){e=e||[],t=t||0;for(var n=t;r>=Zh;)e[t++]=r&255|Ea,r/=128;for(;r&Yh;)e[t++]=r&255|Ea,r>>>=7;return e[t]=r|0,_a.bytes=t-n+1,e}var ed=Yo,td=128,va=127;function Yo(r,n){var t=0,n=n||0,o=0,i=n,s,a=r.length;do{if(i>=a)throw Yo.bytes=0,new RangeError("Could not decode varint");s=r[i++],t+=o<28?(s&va)<<o:(s&va)*Math.pow(2,o),o+=7}while(s>=td);return Yo.bytes=i-n,t}var rd=Math.pow(2,7),nd=Math.pow(2,14),od=Math.pow(2,21),id=Math.pow(2,28),sd=Math.pow(2,35),ad=Math.pow(2,42),cd=Math.pow(2,49),ud=Math.pow(2,56),ld=Math.pow(2,63),fd=function(r){return r<rd?1:r<nd?2:r<od?3:r<id?4:r<sd?5:r<ad?6:r<cd?7:r<ud?8:r<ld?9:10},hd={encode:Jh,decode:ed,encodingLength:fd},dd=hd,Rt=dd;function Bt(r,e=0){return[Rt.decode(r,e),Rt.decode.bytes]}function tt(r,e,t=0){return Rt.encode(r,e,t),e}function rt(r){return Rt.encodingLength(r)}function ot(r,e){let t=e.byteLength,n=rt(r),o=n+rt(t),i=new Uint8Array(o+t);return tt(r,i,0),tt(t,i,n),i.set(e,o),new nt(r,t,e,i)}function Aa(r){let e=ee(r),[t,n]=Bt(e),[o,i]=Bt(e.subarray(n)),s=e.subarray(n+i);if(s.byteLength!==o)throw new Error("Incorrect length");return new nt(t,o,s,e)}function Sa(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&ma(r.bytes,t.bytes)}}var nt=class{code;size;digest;bytes;constructor(e,t,n,o){this.code=e,this.size=t,this.digest=Ce(n),this.bytes=Ce(o)}};var Ia=0,pd="identity",ka=ee;function md(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 ot(Ia,ka(r))}var yr={code:Ia,name:pd,encode:ka,digest:md};var ri={};_(ri,{sha256:()=>wr,sha512:()=>br});var gd=20;function ti({name:r,code:e,encode:t,minDigestLength:n,maxDigestLength:o}){return new ei(r,e,t,n,o)}var ei=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,n,o,i){this.name=e,this.code=t,this.encode=n,this.minDigestLength=o??gd,this.maxDigestLength=i}digest(e,t){if(t?.truncate!=null){if(t.truncate<this.minDigestLength)throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`);if(this.maxDigestLength!=null&&t.truncate>this.maxDigestLength)throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`)}if(e instanceof Uint8Array){let n=this.encode(e);return n instanceof Uint8Array?Ta(n,this.code,t?.truncate):n.then(o=>Ta(o,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}};function Ta(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 ot(e,r)}function Ca(r){return async e=>new Uint8Array(await crypto.subtle.digest(r,e))}var wr=ti({name:"sha2-256",code:18,encode:Ca("SHA-256")}),br=ti({name:"sha2-512",code:19,encode:Ca("SHA-512")});function Da(r,e){let{bytes:t,version:n}=r;return n===0?wd(t,ni(r),e??ue.encoder):bd(t,ni(r),e??Ze.encoder)}var Pa=new WeakMap;function ni(r){let e=Pa.get(r);if(e==null){let t=new Map;return Pa.set(r,t),t}return e}var P=class r{code;version;multihash;bytes;"/";constructor(e,t,n,o){this.code=t,this.version=e,this.multihash=n,this.bytes=Ce(o),this["/"]=this.bytes}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:e,multihash:t}=this;if(e!==Ot)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==xd)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=ot(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&&Sa(e.multihash,n.multihash)}toString(e){return Da(this,e)}toJSON(){return{"/":Da(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(e){if(e==null)return null;let t=e;if(t instanceof r)return t;if(t["/"]!=null&&t["/"]===t.bytes||t.asCID===t){let{version:n,code:o,multihash:i,bytes:s}=t;return new r(n,o,i,s??Na(n,o,i.bytes))}else if(t[Ed]===!0){let{version:n,multihash:o,code:i}=t,s=Aa(o);return r.create(n,i,s)}else return null}static create(e,t,n){if(typeof t!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(e){case 0:{if(t!==Ot)throw new Error(`Version 0 CID must use dag-pb (code: ${Ot}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let o=Na(e,t,n.bytes);return new r(e,t,n,o)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,Ot,e)}static createV1(e,t){return r.create(1,e,t)}static decode(e){let[t,n]=r.decodeFirst(e);if(n.length!==0)throw new Error("Incorrect length");return t}static decodeFirst(e){let t=r.inspectBytes(e),n=t.size-t.multihashSize,o=ee(e.subarray(n,n+t.multihashSize));if(o.byteLength!==t.multihashSize)throw new Error("Incorrect length");let i=o.subarray(t.multihashSize-t.digestSize),s=new nt(t.multihashCode,t.digestSize,i,o);return[t.version===0?r.createV0(s):r.createV1(t.codec,s),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[p,m]=Bt(e.subarray(t));return t+=m,p},o=n(),i=Ot;if(o===18?(o=0,t=0):i=n(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);let s=t,a=n(),c=n(),l=t+c,f=l-s;return{version:o,codec:i,multihashCode:a,digestSize:c,multihashSize:f,size:l}}static parse(e,t){let[n,o]=yd(e,t),i=r.decode(o);if(i.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return ni(i).set(n,e),i}};function yd(r,e){switch(r[0]){case"Q":{let t=e??ue;return[ue.prefix,t.decode(`${ue.prefix}${r}`)]}case ue.prefix:{let t=e??ue;return[ue.prefix,t.decode(r)]}case Ze.prefix:{let t=e??Ze;return[Ze.prefix,t.decode(r)]}case me.prefix:{let t=e??me;return[me.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 wd(r,e,t){let{prefix:n}=t;if(n!==ue.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let o=e.get(n);if(o==null){let i=t.encode(r).slice(1);return e.set(n,i),i}else return o}function bd(r,e,t){let{prefix:n}=t,o=e.get(n);if(o==null){let i=t.encode(r);return e.set(n,i),i}else return o}var Ot=112,xd=18;function Na(r,e,t){let n=rt(r),o=n+rt(e),i=new Uint8Array(o+t.byteLength);return tt(r,i,0),tt(e,i,n),i.set(t,o),i}var Ed=Symbol.for("@ipld/js-cid/CID");var oi={...Qo,...qo,...Go,...$o,...Fo,...Vo,...Ko,...Ho,...Wo,...jo},mb={...ri,...Zo};function Ra(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var Ua=Ra("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),ii=Ra("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=dr(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),vd={utf8:Ua,"utf-8":Ua,hex:oi.base16,latin1:ii,ascii:ii,binary:ii,...oi},xr=vd;function Er(r,e="utf8"){let t=xr[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.decoder.decode(`${t.prefix}${r}`)}function it(r,e="utf8"){let t=xr[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.encoder.encode(r).substring(1)}function F(){let r={};return r.promise=new Promise((e,t)=>{r.resolve=e,r.reject=t}),r}var vr=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}},st=class{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new vr(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 vr(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 si=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}};function _r(r={}){return _d(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 _d(r,e){e=e??{};let t=e.onEnd,n=new st,o,i,s,a=F(),c=async()=>{try{return n.isEmpty()?s?{done:!0}:await new Promise((x,v)=>{i=I=>{i=null,n.push(I);try{x(r(n))}catch(A){v(A)}return o}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=F()})}},l=x=>i!=null?i(x):(n.push(x),o),f=x=>(n=new st,i!=null?i({error:x}):(n.push({error:x}),o)),p=x=>{if(s)return o;if(e?.objectMode!==!0&&x?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return l({done:!1,value:x})},m=x=>s?o:(s=!0,x!=null?f(x):l({done:!0})),b=()=>(n=new st,m(),{done:!0}),d=x=>(m(x),{done:!0});if(o={[Symbol.asyncIterator](){return this},next:c,return:b,throw:d,push:p,end:m,get readableLength(){return n.size},onEmpty:async x=>{let v=x?.signal;if(v?.throwIfAborted(),n.isEmpty())return;let I,A;v!=null&&(I=new Promise((S,T)=>{A=()=>{T(new si)},v.addEventListener("abort",A)}));try{await Promise.race([a.promise,I])}finally{A!=null&&v!=null&&v?.removeEventListener("abort",A)}}},t==null)return o;let w=o;return o={[Symbol.asyncIterator](){return this},next(){return w.next()},throw(x){return w.throw(x),t!=null&&(t(x),t=void 0),{done:!0}},return(){return w.return(),t!=null&&(t(),t=void 0),{done:!0}},push:p,end(x){return w.end(x),t!=null&&(t(x),t=void 0),o},get readableLength(){return w.readableLength},onEmpty:x=>w.onEmpty(x)},o}var Ad=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 Sd(r,e,t){let n,o=new Promise((i,s)=>{if(t={rejectionEvents:["error"],multiArgs:!1,rejectionMultiArgs:!1,resolveImmediately:!1,...t},!(t.count>=0&&(t.count===Number.POSITIVE_INFINITY||Number.isInteger(t.count))))throw new TypeError("The `count` option should be at least 0 or more");t.signal?.throwIfAborted();let a=[e].flat(),c=[],{addListener:l,removeListener:f}=Ad(r),p=async(...b)=>{let d=t.multiArgs?b:b[0];if(t.filter)try{if(!await t.filter(d))return}catch(w){n(),s(w);return}c.push(d),t.count===c.length&&(n(),i(c))},m=(...b)=>{n(),s(t.rejectionMultiArgs?b:b[0])};n=()=>{for(let b of a)f(b,p);for(let b of t.rejectionEvents)a.includes(b)||f(b,m)};for(let b of a)l(b,p);for(let b of t.rejectionEvents)a.includes(b)||l(b,m);t.signal&&t.signal.addEventListener("abort",()=>{m(t.signal.reason)},{once:!0}),t.resolveImmediately&&i(c)});if(o.cancel=n,typeof t.timeout=="number"){let i=xt(o,{milliseconds:t.timeout});return i.cancel=()=>{n(),i.clear()},i}return o}function Ar(r,e,t){typeof t=="function"&&(t={filter:t}),t={...t,count:1,resolveImmediately:!1};let n=Sd(r,e,t),o=n.then(i=>i[0]);return o.cancel=n.cancel,o}function ai(r,e){let t,n=function(){let o=function(){t=void 0,r()};clearTimeout(t),t=setTimeout(o,e)};return n.start=()=>{},n.stop=()=>{clearTimeout(t)},n}var Sr=class extends Error{static name="QueueFullError";constructor(e="The queue was full"){super(e),this.name="QueueFullError"}};function Id(r){return r.reason}async function Ae(r,e,t){if(e==null)return r;let n=t?.translateError??Id;if(e.aborted)return r.catch(()=>{}),Promise.reject(n(e));let o;try{return await Promise.race([r,new Promise((i,s)=>{o=()=>{s(n(e))},e.addEventListener("abort",o)})])}finally{o!=null&&e.removeEventListener("abort",o)}}var Ir=class{deferred;signal;onProgress;constructor(e){this.signal=e?.signal,this.onProgress=e?.onProgress,this.deferred=F(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new X)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function kd(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var kr=class{id;fn;options;recipients;status;timeline;controller;dispatchingProgress;constructor(e,t){this.id=kd(),this.status="queued",this.fn=e,this.options=t,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,this.controller.signal,this.dispatchingProgress=!1,this.onAbort=this.onAbort.bind(this)}abort(e){this.controller.abort(e)}onAbort(){this.recipients.reduce((t,n)=>t&&n.signal?.aborted===!0,!0)&&(this.controller.abort(new X),this.cleanup())}async join(e){let t=new Ir(e);return this.recipients.push(t),e?.signal?.addEventListener("abort",this.onAbort),t.deferred.promise}async run(){this.status="running",this.timeline.started=Date.now();try{this.controller.signal.throwIfAborted();let e=await Ae(this.fn({...this.options??{},signal:this.controller.signal,onProgress:t=>{if(!this.dispatchingProgress){this.dispatchingProgress=!0;try{this.recipients.forEach(n=>{n.onProgress?.(t)})}finally{this.dispatchingProgress=!1}}}}),this.controller.signal);this.recipients.forEach(t=>{t.deferred.resolve(e)}),this.status="complete"}catch(e){this.recipients.forEach(t=>{t.deferred.reject(e)}),this.status="errored"}finally{this.timeline.finished=Date.now(),this.cleanup()}}cleanup(){this.recipients.forEach(e=>{e.cleanup(),e.signal?.removeEventListener("abort",this.onAbort)})}};var q=class extends G{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=ai(this.emitEmpty.bind(this),1),this.emitIdle=ai(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 Sr;let n=new kr(e,t);this.enqueue(n),this.safeDispatchEvent("add");let o=n.join(t).then(i=>(this.safeDispatchEvent("completed",{detail:i}),this.safeDispatchEvent("success",{detail:{job:n,result:i}}),i)).catch(i=>{if(n.status==="queued"){for(let s=0;s<this.queue.length;s++)if(this.queue[s]===n){this.queue.splice(s,1);break}}throw this.safeDispatchEvent("failure",{detail:{job:n,error:i}}),i});return this.tryToStartAnother(),o}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(e=>{e.abort(new X)}),this.clear()}async onEmpty(e){this.size!==0&&await Ar(this,"empty",e)}async onSizeLessThan(e,t){this.size<e||await Ar(this,"next",{...t,filter:()=>this.size<e})}async onIdle(e){this.pending===0&&this.size===0||await Ar(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=_r({objectMode:!0}),n=c=>{c!=null?this.abort():this.clear(),t.end(c)},o=c=>{c.detail!=null&&t.push(c.detail)},i=c=>{n(c.detail.error)},s=()=>{n()},a=()=>{n(new X("Queue aborted"))};this.addEventListener("completed",o),this.addEventListener("failure",i),this.addEventListener("idle",s),e?.signal?.addEventListener("abort",a);try{yield*t}finally{this.removeEventListener("completed",o),this.removeEventListener("failure",i),this.removeEventListener("idle",s),e?.signal?.removeEventListener("abort",a),n()}}};function te(r){let e=new globalThis.AbortController;function t(){let i=r.filter(s=>s?.aborted===!0).map(s=>s?.reason).pop();e.abort(i);for(let s of r)s?.removeEventListener!=null&&s.removeEventListener("abort",t)}for(let i of r){if(i?.aborted===!0){t();break}i?.addEventListener!=null&&i.addEventListener("abort",t)}function n(){for(let i of r)i?.removeEventListener!=null&&i.removeEventListener("abort",t)}let o=e.signal;return o.clear=n,o}var ci=class{readNext;haveNext;ended;nextResult;error;constructor(){this.ended=!1,this.readNext=F(),this.haveNext=F()}[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=F(),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=F(),await Ae(this.readNext.promise,t?.signal,t)}};function Ba(){return new ci}function Td(r){return r[Symbol.asyncIterator]!=null}async function Ld(r,e,t){try{await Promise.all(r.map(async n=>{for await(let o of n)await e.push(o,{signal:t}),t.throwIfAborted()})),await e.end(void 0,{signal:t})}catch(n){await e.end(n,{signal:t}).catch(()=>{})}}async function*Cd(r){let e=new AbortController,t=Ba();Ld(r,t,e.signal).catch(()=>{});try{yield*t}finally{e.abort()}}function*Dd(r){for(let e of r)yield*e}function Pd(...r){let e=[];for(let t of r)Td(t)||e.push(t);return e.length===r.length?Dd(e):Cd(r)}var Tr=Pd;var Nd=["Object","RegExp","Date","Error","Map","Set","WeakMap","WeakSet","ArrayBuffer","SharedArrayBuffer","DataView","Promise","URL","HTMLElement","Int8Array","Uint8ClampedArray","Int16Array","Uint16Array","Int32Array","Uint32Array","Float32Array","Float64Array","BigInt64Array","BigUint64Array","Tagged"];function ui(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=Ud(r);return t||"Object"}function Ud(r){let e=Object.prototype.toString.call(r).slice(8,-1);if(Nd.includes(e))return e}var u=class{constructor(e,t,n){this.major=e,this.majorEncoded=e<<5,this.name=t,this.terminal=n}toString(){return`Type[${this.major}].${this.name}`}compare(e){return this.major<e.major?-1:this.major>e.major?1:0}static equals(e,t){return e===t||e.major===t.major&&e.name===t.name}};u.uint=new u(0,"uint",!0);u.negint=new u(1,"negint",!0);u.bytes=new u(2,"bytes",!0);u.string=new u(3,"string",!0);u.array=new u(4,"array",!1);u.map=new u(5,"map",!1);u.tag=new u(6,"tag",!1);u.float=new u(7,"float",!0);u.false=new u(7,"false",!0);u.true=new u(7,"true",!0);u.null=new u(7,"null",!0);u.undefined=new u(7,"undefined",!0);u.break=new u(7,"break",!0);var h=class{constructor(e,t,n){this.type=e,this.value=t,this.encodedLength=n,this.encodedBytes=void 0,this.byteValue=void 0}toString(){return`Token[${this.type}].${this.value}`}};var Mt=globalThis.process&&!globalThis.process.browser&&globalThis.Buffer&&typeof globalThis.Buffer.isBuffer=="function",Rd=new TextEncoder;function Lr(r){return Mt&&globalThis.Buffer.isBuffer(r)}function De(r){return r instanceof Uint8Array?Lr(r)?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):r:Uint8Array.from(r)}var Bd=24,zd=200,at=Mt?r=>r.length>=Bd?globalThis.Buffer.from(r):za(r):r=>r.length>=zd?Rd.encode(r):za(r),le=r=>Uint8Array.from(r),Ma=Mt?(r,e,t)=>Lr(r)?new Uint8Array(r.subarray(e,t)):r.slice(e,t):(r,e,t)=>r.slice(e,t),$a=Mt?(r,e)=>(r=r.map(t=>t instanceof Uint8Array?t:globalThis.Buffer.from(t)),De(globalThis.Buffer.concat(r,e))):(r,e)=>{let t=new Uint8Array(e),n=0;for(let o of r)n+o.length>t.length&&(o=o.subarray(0,t.length-n)),t.set(o,n),n+=o.length;return t},Fa=Mt?r=>globalThis.Buffer.allocUnsafe(r):r=>new Uint8Array(r);function Cr(r,e){if(Lr(r)&&Lr(e))return r.compare(e);for(let t=0;t<r.length;t++)if(r[t]!==e[t])return r[t]<e[t]?-1:1;return 0}function za(r){let e=[],t=0;for(let n=0;n<r.length;n++){let o=r.charCodeAt(n);o<128?e[t++]=o:o<2048?(e[t++]=o>>6|192,e[t++]=o&63|128):(o&64512)===55296&&n+1<r.length&&(r.charCodeAt(n+1)&64512)===56320?(o=65536+((o&1023)<<10)+(r.charCodeAt(++n)&1023),e[t++]=o>>18|240,e[t++]=o>>12&63|128,e[t++]=o>>6&63|128,e[t++]=o&63|128):(o>=55296&&o<=57343&&(o=65533),e[t++]=o>>12|224,e[t++]=o>>6&63|128,e[t++]=o&63|128)}return e}var Oa=4096;function qa(r){let e=r.length;if(e<=Oa)return String.fromCharCode.apply(String,r);let t="",n=0;for(;n<e;)t+=String.fromCharCode.apply(String,r.slice(n,n+=Oa));return t}var Od=256,$t=class{constructor(e=Od){this.chunkSize=e,this.cursor=0,this.maxCursor=-1,this.chunks=[],this._initReuseChunk=null}reset(){this.cursor=0,this.maxCursor=-1,this.chunks.length&&(this.chunks=[]),this._initReuseChunk!==null&&(this.chunks.push(this._initReuseChunk),this.maxCursor=this._initReuseChunk.length-1)}push(e){let t=this.chunks[this.chunks.length-1];if(this.cursor+e.length<=this.maxCursor+1){let o=t.length-(this.maxCursor-this.cursor)-1;t.set(e,o)}else{if(t){let o=t.length-(this.maxCursor-this.cursor)-1;o<t.length&&(this.chunks[this.chunks.length-1]=t.subarray(0,o),this.maxCursor=this.cursor-1)}e.length<64&&e.length<this.chunkSize?(t=Fa(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=Ma(n,0,this.cursor)}else t=$a(this.chunks,this.cursor);return e&&this.reset(),t}},Dr=class{constructor(e){this.dest=e,this.cursor=0,this.chunks=[e]}reset(){this.cursor=0}push(e){if(this.cursor+e.length>this.dest.length)throw new Error("write out of bounds, destination buffer is too small");this.dest.set(e,this.cursor),this.cursor+=e.length}toBytes(e=!1){let t=this.dest.subarray(0,this.cursor);return e&&this.reset(),t}};var y="CBOR decode error:",fe="CBOR encode error:",Ft=[];Ft[23]=1;Ft[24]=2;Ft[25]=3;Ft[26]=5;Ft[27]=9;function ge(r,e,t){if(r.length-e<t)throw new Error(`${y} not enough data for type`)}var z=[24,256,65536,4294967296,BigInt("18446744073709551616")];function j(r,e,t){ge(r,e,1);let n=r[e];if(t.strict===!0&&n<z[0])throw new Error(`${y} integer encoded in more bytes than necessary (strict decode)`);return n}function V(r,e,t){ge(r,e,2);let n=r[e]<<8|r[e+1];if(t.strict===!0&&n<z[1])throw new Error(`${y} integer encoded in more bytes than necessary (strict decode)`);return n}function K(r,e,t){ge(r,e,4);let n=r[e]*16777216+(r[e+1]<<16)+(r[e+2]<<8)+r[e+3];if(t.strict===!0&&n<z[2])throw new Error(`${y} integer encoded in more bytes than necessary (strict decode)`);return n}function H(r,e,t){ge(r,e,8);let n=r[e]*16777216+(r[e+1]<<16)+(r[e+2]<<8)+r[e+3],o=r[e+4]*16777216+(r[e+5]<<16)+(r[e+6]<<8)+r[e+7],i=(BigInt(n)<<BigInt(32))+BigInt(o);if(t.strict===!0&&i<z[3])throw new Error(`${y} integer encoded in more bytes than necessary (strict decode)`);if(i<=Number.MAX_SAFE_INTEGER)return Number(i);if(t.allowBigInt===!0)return i;throw new Error(`${y} integers outside of the safe integer range are not supported`)}function ja(r,e,t,n){return new h(u.uint,j(r,e+1,n),2)}function Va(r,e,t,n){return new h(u.uint,V(r,e+1,n),3)}function Ka(r,e,t,n){return new h(u.uint,K(r,e+1,n),5)}function Ha(r,e,t,n){return new h(u.uint,H(r,e+1,n),9)}function Q(r,e){return N(r,0,e.value)}function N(r,e,t){if(t<z[0]){let n=Number(t);r.push([e|n])}else if(t<z[1]){let n=Number(t);r.push([e|24,n])}else if(t<z[2]){let n=Number(t);r.push([e|25,n>>>8,n&255])}else if(t<z[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<z[4]){let o=[e|27,0,0,0,0,0,0,0],i=Number(n&BigInt(4294967295)),s=Number(n>>BigInt(32)&BigInt(4294967295));o[8]=i&255,i=i>>8,o[7]=i&255,i=i>>8,o[6]=i&255,i=i>>8,o[5]=i&255,o[4]=s&255,s=s>>8,o[3]=s&255,s=s>>8,o[2]=s&255,s=s>>8,o[1]=s&255,r.push(o)}else throw new Error(`${y} encountered BigInt larger than allowable range`)}}Q.encodedSize=function(e){return N.encodedSize(e.value)};N.encodedSize=function(e){return e<z[0]?1:e<z[1]?2:e<z[2]?3:e<z[3]?5:9};Q.compareTokens=function(e,t){return e.value<t.value?-1:e.value>t.value?1:0};function Wa(r,e,t,n){return new h(u.negint,-1-j(r,e+1,n),2)}function Ga(r,e,t,n){return new h(u.negint,-1-V(r,e+1,n),3)}function Qa(r,e,t,n){return new h(u.negint,-1-K(r,e+1,n),5)}var li=BigInt(-1),Ja=BigInt(1);function Xa(r,e,t,n){let o=H(r,e+1,n);if(typeof o!="bigint"){let i=-1-o;if(i>=Number.MIN_SAFE_INTEGER)return new h(u.negint,i,9)}if(n.allowBigInt!==!0)throw new Error(`${y} integers outside of the safe integer range are not supported`);return new h(u.negint,li-BigInt(o),9)}function Pr(r,e){let t=e.value,n=typeof t=="bigint"?t*li-Ja:t*-1-1;N(r,e.type.majorEncoded,n)}Pr.encodedSize=function(e){let t=e.value,n=typeof t=="bigint"?t*li-Ja:t*-1-1;return n<z[0]?1:n<z[1]?2:n<z[2]?3:n<z[3]?5:9};Pr.compareTokens=function(e,t){return e.value<t.value?1:e.value>t.value?-1:0};function qt(r,e,t,n){ge(r,e,t+n);let o=r.slice(e+t,e+t+n);return new h(u.bytes,o,t+n)}function Ya(r,e,t,n){return qt(r,e,1,t)}function Za(r,e,t,n){return qt(r,e,2,j(r,e+1,n))}function ec(r,e,t,n){return qt(r,e,3,V(r,e+1,n))}function tc(r,e,t,n){return qt(r,e,5,K(r,e+1,n))}function rc(r,e,t,n){let o=H(r,e+1,n);if(typeof o=="bigint")throw new Error(`${y} 64-bit integer bytes lengths not supported`);return qt(r,e,9,o)}function Nr(r){return r.encodedBytes===void 0&&(r.encodedBytes=u.equals(r.type,u.string)?at(r.value):r.value),r.encodedBytes}function ct(r,e){let t=Nr(e);N(r,e.type.majorEncoded,t.length),r.push(t)}ct.encodedSize=function(e){let t=Nr(e);return N.encodedSize(t.length)+t.length};ct.compareTokens=function(e,t){return $d(Nr(e),Nr(t))};function $d(r,e){return r.length<e.length?-1:r.length>e.length?1:Cr(r,e)}var nc=new TextDecoder,qd=32;function jd(r,e,t){if(t-e<qd){let o="";for(let i=e;i<t;i++){let s=r[i];if(s&128)return nc.decode(r.subarray(e,t));o+=String.fromCharCode(s)}return o}return nc.decode(r.subarray(e,t))}function jt(r,e,t,n,o){let i=t+n;ge(r,e,i);let s=new h(u.string,jd(r,e+t,e+i),i);return o.retainStringBytes===!0&&(s.byteValue=r.slice(e+t,e+i)),s}function oc(r,e,t,n){return jt(r,e,1,t,n)}function ic(r,e,t,n){return jt(r,e,2,j(r,e+1,n),n)}function sc(r,e,t,n){return jt(r,e,3,V(r,e+1,n),n)}function ac(r,e,t,n){return jt(r,e,5,K(r,e+1,n),n)}function cc(r,e,t,n){let o=H(r,e+1,n);if(typeof o=="bigint")throw new Error(`${y} 64-bit integer string lengths not supported`);return jt(r,e,9,o,n)}var uc=ct;function ut(r,e,t,n){return new h(u.array,n,t)}function lc(r,e,t,n){return ut(r,e,1,t)}function fc(r,e,t,n){return ut(r,e,2,j(r,e+1,n))}function hc(r,e,t,n){return ut(r,e,3,V(r,e+1,n))}function dc(r,e,t,n){return ut(r,e,5,K(r,e+1,n))}function pc(r,e,t,n){let o=H(r,e+1,n);if(typeof o=="bigint")throw new Error(`${y} 64-bit integer array lengths not supported`);return ut(r,e,9,o)}function mc(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${y} indefinite length items not allowed`);return ut(r,e,1,1/0)}function Ur(r,e){N(r,u.array.majorEncoded,e.value)}Ur.compareTokens=Q.compareTokens;Ur.encodedSize=function(e){return N.encodedSize(e.value)};function lt(r,e,t,n){return new h(u.map,n,t)}function gc(r,e,t,n){return lt(r,e,1,t)}function yc(r,e,t,n){return lt(r,e,2,j(r,e+1,n))}function wc(r,e,t,n){return lt(r,e,3,V(r,e+1,n))}function bc(r,e,t,n){return lt(r,e,5,K(r,e+1,n))}function xc(r,e,t,n){let o=H(r,e+1,n);if(typeof o=="bigint")throw new Error(`${y} 64-bit integer map lengths not supported`);return lt(r,e,9,o)}function Ec(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${y} indefinite length items not allowed`);return lt(r,e,1,1/0)}function Rr(r,e){N(r,u.map.majorEncoded,e.value)}Rr.compareTokens=Q.compareTokens;Rr.encodedSize=function(e){return N.encodedSize(e.value)};function vc(r,e,t,n){return new h(u.tag,t,1)}function _c(r,e,t,n){return new h(u.tag,j(r,e+1,n),2)}function Ac(r,e,t,n){return new h(u.tag,V(r,e+1,n),3)}function Sc(r,e,t,n){return new h(u.tag,K(r,e+1,n),5)}function Ic(r,e,t,n){return new h(u.tag,H(r,e+1,n),9)}function Br(r,e){N(r,u.tag.majorEncoded,e.value)}Br.compareTokens=Q.compareTokens;Br.encodedSize=function(e){return N.encodedSize(e.value)};var fi=20,hi=21,di=22,pi=23;function kc(r,e,t,n){if(n.allowUndefined===!1)throw new Error(`${y} undefined values are not supported`);return n.coerceUndefinedToNull===!0?new h(u.null,null,1):new h(u.undefined,void 0,1)}function Tc(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${y} indefinite length items not allowed`);return new h(u.break,void 0,1)}function mi(r,e,t){if(t){if(t.allowNaN===!1&&Number.isNaN(r))throw new Error(`${y} NaN values are not supported`);if(t.allowInfinity===!1&&(r===1/0||r===-1/0))throw new Error(`${y} Infinity values are not supported`)}return new h(u.float,r,e)}function Lc(r,e,t,n){return mi(gi(r,e+1),3,n)}function Cc(r,e,t,n){return mi(yi(r,e+1),5,n)}function Dc(r,e,t,n){return mi(Rc(r,e+1),9,n)}function Vt(r,e,t){let n=e.value;if(n===!1)r.push([u.float.majorEncoded|fi]);else if(n===!0)r.push([u.float.majorEncoded|hi]);else if(n===null)r.push([u.float.majorEncoded|di]);else if(n===void 0)r.push([u.float.majorEncoded|pi]);else{let o,i=!1;(!t||t.float64!==!0)&&(Nc(n),o=gi(re,1),n===o||Number.isNaN(n)?(re[0]=249,r.push(re.slice(0,3)),i=!0):(Uc(n),o=yi(re,1),n===o&&(re[0]=250,r.push(re.slice(0,5)),i=!0))),i||(Gd(n),o=Rc(re,1),re[0]=251,r.push(re.slice(0,9)))}}Vt.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){Nc(n);let o=gi(re,1);if(n===o||Number.isNaN(n))return 3;if(Uc(n),o=yi(re,1),n===o)return 5}return 9};var Pc=new ArrayBuffer(9),J=new DataView(Pc,1),re=new Uint8Array(Pc,0);function Nc(r){if(r===1/0)J.setUint16(0,31744,!1);else if(r===-1/0)J.setUint16(0,64512,!1);else if(Number.isNaN(r))J.setUint16(0,32256,!1);else{J.setFloat32(0,r);let e=J.getUint32(0),t=(e&2139095040)>>23,n=e&8388607;if(t===255)J.setUint16(0,31744,!1);else if(t===0)J.setUint16(0,(e&2147483648)>>16|n>>13,!1);else{let o=t-127;o<-24?J.setUint16(0,0):o<-14?J.setUint16(0,(e&2147483648)>>16|1<<24+o,!1):J.setUint16(0,(e&2147483648)>>16|o+15<<10|n>>13,!1)}}}function gi(r,e){if(r.length-e<2)throw new Error(`${y} not enough data for float16`);let t=(r[e]<<8)+r[e+1];if(t===31744)return 1/0;if(t===64512)return-1/0;if(t===32256)return NaN;let n=t>>10&31,o=t&1023,i;return n===0?i=o*2**-24:n!==31?i=(o+1024)*2**(n-25):i=o===0?1/0:NaN,t&32768?-i:i}function Uc(r){J.setFloat32(0,r,!1)}function yi(r,e){if(r.length-e<4)throw new Error(`${y} not enough data for float32`);let t=(r.byteOffset||0)+e;return new DataView(r.buffer,t,4).getFloat32(0,!1)}function Gd(r){J.setFloat64(0,r,!1)}function Rc(r,e){if(r.length-e<8)throw new Error(`${y} not enough data for float64`);let t=(r.byteOffset||0)+e;return new DataView(r.buffer,t,8).getFloat64(0,!1)}Vt.compareTokens=Q.compareTokens;function L(r,e,t){throw new Error(`${y} encountered invalid minor (${t}) for major ${r[e]>>>5}`)}function zr(r){return()=>{throw new Error(`${y} ${r}`)}}var g=[];for(let r=0;r<=23;r++)g[r]=L;g[24]=ja;g[25]=Va;g[26]=Ka;g[27]=Ha;g[28]=L;g[29]=L;g[30]=L;g[31]=L;for(let r=32;r<=55;r++)g[r]=L;g[56]=Wa;g[57]=Ga;g[58]=Qa;g[59]=Xa;g[60]=L;g[61]=L;g[62]=L;g[63]=L;for(let r=64;r<=87;r++)g[r]=Ya;g[88]=Za;g[89]=ec;g[90]=tc;g[91]=rc;g[92]=L;g[93]=L;g[94]=L;g[95]=zr("indefinite length bytes/strings are not supported");for(let r=96;r<=119;r++)g[r]=oc;g[120]=ic;g[121]=sc;g[122]=ac;g[123]=cc;g[124]=L;g[125]=L;g[126]=L;g[127]=zr("indefinite length bytes/strings are not supported");for(let r=128;r<=151;r++)g[r]=lc;g[152]=fc;g[153]=hc;g[154]=dc;g[155]=pc;g[156]=L;g[157]=L;g[158]=L;g[159]=mc;for(let r=160;r<=183;r++)g[r]=gc;g[184]=yc;g[185]=wc;g[186]=bc;g[187]=xc;g[188]=L;g[189]=L;g[190]=L;g[191]=Ec;for(let r=192;r<=215;r++)g[r]=vc;g[216]=_c;g[217]=Ac;g[218]=Sc;g[219]=Ic;g[220]=L;g[221]=L;g[222]=L;g[223]=L;for(let r=224;r<=243;r++)g[r]=zr("simple values are not supported");g[244]=L;g[245]=L;g[246]=L;g[247]=kc;g[248]=zr("simple values are not supported");g[249]=Lc;g[250]=Cc;g[251]=Dc;g[252]=L;g[253]=L;g[254]=L;g[255]=Tc;var ne=[];for(let r=0;r<24;r++)ne[r]=new h(u.uint,r,1);for(let r=-1;r>=-24;r--)ne[31-r]=new h(u.negint,r,1);ne[64]=new h(u.bytes,new Uint8Array(0),1);ne[96]=new h(u.string,"",1);ne[128]=new h(u.array,0,1);ne[160]=new h(u.map,0,1);ne[244]=new h(u.false,!1,1);ne[245]=new h(u.true,!0,1);ne[246]=new h(u.null,null,1);function wi(r){switch(r.type){case u.false:return le([244]);case u.true:return le([245]);case u.null:return le([246]);case u.bytes:return r.value.length?void 0:le([64]);case u.string:return r.value===""?le([96]):void 0;case u.array:return r.value===0?le([128]):void 0;case u.map:return r.value===0?le([160]):void 0;case u.uint:return r.value<24?le([Number(r.value)]):void 0;case u.negint:if(r.value>=-24)return le([31-Number(r.value)])}}var Jd={float64:!1,mapSorter:Zd,quickEncodeToken:wi},$c=Object.freeze({float64:!0,mapSorter:ep,quickEncodeToken:wi});function Xd(){let r=[];return r[u.uint.major]=Q,r[u.negint.major]=Pr,r[u.bytes.major]=ct,r[u.string.major]=uc,r[u.array.major]=Ur,r[u.map.major]=Rr,r[u.tag.major]=Br,r[u.float.major]=Vt,r}var ht=Xd(),Or=new $t,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(`${fe} object contains circular references`);return new r(t,e)}},Se={null:new h(u.null,null),undefined:new h(u.undefined,void 0),true:new h(u.true,!0),false:new h(u.false,!1),emptyArray:new h(u.array,0),emptyMap:new h(u.map,0)},he={number(r,e,t,n){return!Number.isInteger(r)||!Number.isSafeInteger(r)?new h(u.float,r):r>=0?new h(u.uint,r):new h(u.negint,r)},bigint(r,e,t,n){return r>=BigInt(0)?new h(u.uint,r):new h(u.negint,r)},Uint8Array(r,e,t,n){return new h(u.bytes,r)},string(r,e,t,n){return new h(u.string,r)},boolean(r,e,t,n){return r?Se.true:Se.false},null(r,e,t,n){return Se.null},undefined(r,e,t,n){return Se.undefined},ArrayBuffer(r,e,t,n){return new h(u.bytes,new Uint8Array(r))},DataView(r,e,t,n){return new h(u.bytes,new Uint8Array(r.buffer,r.byteOffset,r.byteLength))},Array(r,e,t,n){if(!r.length)return t.addBreakTokens===!0?[Se.emptyArray,new h(u.break)]:Se.emptyArray;n=Ht.createCheck(n,r);let o=[],i=0;for(let s of r)o[i++]=ft(s,t,n);return t.addBreakTokens?[new h(u.array,r.length),o,new h(u.break)]:[new h(u.array,r.length),o]},Object(r,e,t,n){let o=e!=="Object",i=o?r.keys():Object.keys(r),s=o?r.size:i.length,a;if(s){a=new Array(s),n=Ht.createCheck(n,r);let c=!o&&t.ignoreUndefinedProperties,l=0;for(let f of i){let p=o?r.get(f):r[f];c&&p===void 0||(a[l++]=[ft(f,t,n),ft(p,t,n)])}l<s&&(a.length=l)}return a?.length?(Yd(a,t),t.addBreakTokens?[new h(u.map,a.length),a,new h(u.break)]:[new h(u.map,a.length),a]):t.addBreakTokens===!0?[Se.emptyMap,new h(u.break)]:Se.emptyMap},Tagged(r,e,t,n){return[new h(u.tag,r.tag),ft(r.value,t,n)]}};he.Map=he.Object;he.Buffer=he.Uint8Array;for(let r of"Uint8Clamped Uint16 Uint32 Int8 Int16 Int32 BigUint64 BigInt64 Float32 Float64".split(" "))he[`${r}Array`]=he.DataView;function ft(r,e={},t){let n=ui(r),o=e&&e.typeEncoders&&e.typeEncoders[n]||he[n];if(typeof o=="function"){let s=o(r,n,e,t);if(s!=null)return s}let i=he[n];if(!i)throw new Error(`${fe} unsupported type: ${n}`);return i(r,n,e,t)}function Yd(r,e){e.mapSorter&&r.sort(e.mapSorter)}function Zd(r,e){let t=Array.isArray(r[0])?r[0][0]:r[0],n=Array.isArray(e[0])?e[0][0]:e[0];if(t.type!==n.type)return t.type.compare(n.type);let o=t.type.major,i=ht[o].compareTokens(t,n);return i===0&&console.warn("WARNING: complex key types used, CBOR key sorting guarantees are gone"),i}function ep(r,e){if(r[0]instanceof h&&e[0]instanceof h){let t=r[0],n=e[0];return t._keyBytes||(t._keyBytes=Bc(t.value)),n._keyBytes||(n._keyBytes=Bc(n.value)),Cr(t._keyBytes,n._keyBytes)}throw new Error("rfc8949MapSorter: complex key types are not supported yet")}function Bc(r){return Mr(r,ht,$c)}function Kt(r,e,t,n){if(Array.isArray(e))for(let o of e)Kt(r,o,t,n);else t[e.type.major](r,e,n)}var zc=u.uint.majorEncoded,Oc=u.negint.majorEncoded,tp=u.bytes.majorEncoded,rp=u.string.majorEncoded,Mc=u.array.majorEncoded,np=u.float.majorEncoded|fi,op=u.float.majorEncoded|hi,ip=u.float.majorEncoded|di,sp=u.float.majorEncoded|pi,ap=BigInt(-1),cp=BigInt(1);function up(r){return r.addBreakTokens!==!0}function Fc(r,e,t,n){let o=ui(e),i=t.typeEncoders&&t.typeEncoders[o];if(i){let s=i(e,o,t,n);if(s!=null){Kt(r,s,ht,t);return}}switch(o){case"null":r.push([ip]);return;case"undefined":r.push([sp]);return;case"boolean":r.push([e?op:np]);return;case"number":!Number.isInteger(e)||!Number.isSafeInteger(e)?Vt(r,new h(u.float,e),t):e>=0?N(r,zc,e):N(r,Oc,e*-1-1);return;case"bigint":e>=BigInt(0)?N(r,zc,e):N(r,Oc,e*ap-cp);return;case"string":{let s=at(e);N(r,rp,s.length),r.push(s);return}case"Uint8Array":N(r,tp,e.length),r.push(e);return;case"Array":if(!e.length){r.push([Mc]);return}n=Ht.createCheck(n,e),N(r,Mc,e.length);for(let s of e)Fc(r,s,t,n);return;case"Object":case"Map":{let s=he.Object(e,o,t,n);Kt(r,s,ht,t)}return;default:{let s=he[o];if(!s)throw new Error(`${fe} unsupported type: ${o}`);let a=s(e,o,t,n);Kt(r,a,ht,t)}}}function Mr(r,e,t,n){let o=n instanceof Uint8Array,i=o?new Dr(n):Or,s=ft(r,t);if(!Array.isArray(s)&&t.quickEncodeToken){let a=t.quickEncodeToken(s);if(a)return o?(i.push(a),i.toBytes()):a;let c=e[s.type.major];if(c.encodedSize){let l=c.encodedSize(s,t);if(o||(i=new $t(l)),c(i,s,t),i.chunks.length!==1)throw new Error(`Unexpected error: pre-calculated length for ${s} was wrong`);return o?i.toBytes():De(i.chunks[0])}}return i.reset(),Kt(i,s,e,t),i.toBytes(!0)}function Ne(r,e){return e=Object.assign({},Jd,e),up(e)?(Or.reset(),Fc(Or,r,e,void 0),Or.toBytes(!0)):Mr(r,ht,e)}var lp={strict:!1,allowIndefinite:!0,allowUndefined:!0,allowBigInt:!0},$r=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=ne[e];if(t===void 0){let n=g[e];if(!n)throw new Error(`${y} no decoder for major type ${e>>>5} (byte 0x${e.toString(16).padStart(2,"0")})`);let o=e&31;t=n(this.data,this._pos,o,this.options)}return this._pos+=t.encodedLength,t}},Ie=Symbol.for("DONE"),dt=Symbol.for("BREAK");function fp(r,e,t){let n=[];for(let o=0;o<r.value;o++){let i=ke(e,t);if(i===dt){if(r.value===1/0)break;throw new Error(`${y} got unexpected break to lengthed array`)}if(i===Ie)throw new Error(`${y} found array but not enough entries (got ${o}, expected ${r.value})`);n[o]=i}return n}function hp(r,e,t){let n=t.useMaps===!0,o=t.rejectDuplicateMapKeys===!0,i=n?void 0:{},s=n?new Map:void 0;for(let a=0;a<r.value;a++){let c=ke(e,t);if(c===dt){if(r.value===1/0)break;throw new Error(`${y} got unexpected break to lengthed map`)}if(c===Ie)throw new Error(`${y} found map but not enough entries (got ${a} [no key], expected ${r.value})`);if(!n&&typeof c!="string")throw new Error(`${y} non-string keys not supported (got ${typeof c})`);if(o&&(n&&s.has(c)||!n&&Object.hasOwn(i,c)))throw new Error(`${y} found repeat map key "${c}"`);let l=ke(e,t);if(l===Ie)throw new Error(`${y} found map but not enough entries (got ${a} [no value], expected ${r.value})`);n?s.set(c,l):i[c]=l}return n?s:i}function*dp(r,e,t){for(let n=0;n<r.value;n++){let o=ke(e,t);if(o===dt){if(r.value===1/0)break;throw new Error(`${y} got unexpected break to lengthed map`)}if(o===Ie)throw new Error(`${y} found map but not enough entries (got ${n} [no key], expected ${r.value})`);let i=ke(e,t);if(i===Ie)throw new Error(`${y} found map but not enough entries (got ${n} [no value], expected ${r.value})`);yield[o,i]}}function pp(r,e){let t=!1,n=function(){if(t)throw new Error(`${y} tag decode() may only be called once`);t=!0;let o=ke(r,e);if(o===Ie)throw new Error(`${y} tag content missing`);if(o===dt)throw new Error(`${y} got unexpected break in tag content`);return o};return n.entries=function(){if(t)throw new Error(`${y} tag decode() may only be called once`);t=!0;let o=r.next();if(!u.equals(o.type,u.map))throw new Error(`${y} entries() requires map content, got ${o.type.name}`);let i=[];for(let s of dp(o,r,e))i.push(s);return i},Object.defineProperty(n,"_called",{get(){return t},enumerable:!1}),n}function ke(r,e){if(r.done())return Ie;let t=r.next();if(u.equals(t.type,u.break))return dt;if(t.type.terminal)return t.value;if(u.equals(t.type,u.array))return fp(t,r,e);if(u.equals(t.type,u.map))return hp(t,r,e);if(u.equals(t.type,u.tag)){if(e.tags&&typeof e.tags[t.value]=="function"){let n=pp(r,e),o=e.tags[t.value](n);if(!n._called)throw new Error(`${y} tag decoder must call decode() or entries()`);return o}throw new Error(`${y} tag not supported (${t.value})`)}throw new Error("unsupported")}function bi(r,e){if(!(r instanceof Uint8Array))throw new Error(`${y} data to decode must be a Uint8Array`);e=Object.assign({},lp,e);let t=De(r),n=e.tokenizer||new $r(t,e),o=ke(n,e);if(o===Ie)throw new Error(`${y} did not find any content to decode`);if(o===dt)throw new Error(`${y} got unexpected break`);return[o,r.subarray(n.pos())]}function oe(r,e){let[t,n]=bi(r,e);if(n.length>0)throw new Error(`${y} too many terminals, data makes no sense`);return t}var Fr=class r{constructor(e,t){if(typeof e!="number"||!Number.isInteger(e)||e<0)throw new TypeError("Tagged: tag must be a non-negative integer");this.tag=e,this.value=t}static decoder(e){return t=>new r(e,t())}static preserve(...e){let t={};for(let n of e)t[n]=r.decoder(n);return t}};Object.defineProperty(Fr.prototype,Symbol.toStringTag,{value:"Tagged"});var qr=class extends q{has(e){return this.find(e)!=null}find(e){return this.queue.find(t=>e.equals(t.options.peerId))}};var ye="/",jc=new TextEncoder().encode(ye),jr=jc[0],we=class r{_buf;constructor(e,t){if(typeof e=="string")this._buf=Er(e);else if(e instanceof Uint8Array)this._buf=e;else throw new Error("Invalid key, should be String of Uint8Array");if(t==null&&(t=!0),t&&this.clean(),this._buf.byteLength===0||this._buf[0]!==jr)throw new Error("Invalid key")}toString(e="utf8"){return it(this._buf,e)}uint8Array(){return this._buf}get[Symbol.toStringTag](){return`Key(${this.toString()})`}static withNamespaces(e){return new r(e.join(ye))}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=jc),this._buf[0]!==jr){let e=new Uint8Array(this._buf.byteLength+1);e.fill(jr,0,1),e.set(this._buf,1),this._buf=e}for(;this._buf.byteLength>1&&this._buf[this._buf.byteLength-1]===jr;)this._buf=this._buf.subarray(0,-1)}less(e){let t=this.list(),n=e.list();for(let o=0;o<t.length;o++){if(n.length<o+1)return!1;let i=t[o],s=n[o];if(i<s)return!0;if(i>s)return!1}return t.length<n.length}reverse(){return r.withNamespaces(this.list().slice().reverse())}namespaces(){return this.list()}baseNamespace(){let e=this.namespaces();return e[e.length-1]}list(){return this.toString().split(ye).slice(1)}type(){return mp(this.baseNamespace())}name(){return gp(this.baseNamespace())}instance(e){return new r(this.toString()+":"+e)}path(){let e=this.parent().toString();return e.endsWith(ye)||(e+=ye),e+=this.type(),new r(e)}parent(){let e=this.list();return e.length===1?new r(ye):new r(e.slice(0,-1).join(ye))}child(e){return this.toString()===ye?e:e.toString()===ye?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(),...yp(e.map(t=>t.namespaces()))])}};function mp(r){let e=r.split(":");return e.length<2?"":e.slice(0,-1).join(":")}function gp(r){let e=r.split(":");return e[e.length-1]}function yp(r){return[].concat(...r)}function wp(r){return r[Symbol.asyncIterator]!=null}function bp(r){if(wp(r))return(async()=>{let n=new Uint8Array(0);for await(let o of r)n=Uo([n,o],n.length+o.length);return n})();let e=[],t=0;for(let n of r)e.push(n),t+=n.byteLength;return Uo(e,t)}var Vr=bp;function Kr({enumerable:r=!0,configurable:e=!1}={}){return{enumerable:r,configurable:e,writable:!1}}function*xp(r,e){if(e!=null&&typeof e=="object")if(Array.isArray(e))for(let[t,n]of e.entries()){let o=[...r,t],i=P.asCID(n);i!=null?yield[o.join("/"),i]:typeof n=="object"&&(yield*xi(n,o))}else{let t=P.asCID(e);t!=null?yield[r.join("/"),t]:yield*xi(e,r)}}function*xi(r,e){if(r==null||r instanceof Uint8Array)return;let t=P.asCID(r);t!=null&&(yield[e.join("/"),t]);for(let[n,o]of Object.entries(r)){let i=[...e,n];yield*xp(i,o)}}function*Ep(r,e){if(Array.isArray(e))for(let[t,n]of e.entries()){let o=[...r,t];yield o.join("/"),typeof n=="object"&&P.asCID(n)==null&&(yield*Ei(n,o))}else yield*Ei(e,r)}function*Ei(r,e){if(!(r==null||typeof r!="object"))for(let[t,n]of Object.entries(r)){let o=[...e,t];yield o.join("/"),n!=null&&!(n instanceof Uint8Array)&&typeof n=="object"&&P.asCID(n)==null&&(yield*Ep(o,n))}}function vp(r,e){let t=r;for(let[n,o]of e.entries()){if(t=t[o],t==null)throw new Error(`Object has no property at ${e.slice(0,n+1).map(s=>`[${JSON.stringify(s)}]`).join("")}`);let i=P.asCID(t);if(i!=null)return{value:i,remaining:e.slice(n+1).join("/")}}return{value:t}}var vi=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:Kr(),bytes:Kr(),value:Kr(),asBlock:Kr()})}links(){return xi(this.value,[])}tree(){return Ei(this.value,[])}get(e="/"){return vp(this.value,e.split("/").filter(Boolean))}};function Hr({bytes:r,cid:e,value:t,codec:n}){let o=t!==void 0?t:n?.decode(r);if(o===void 0)throw new Error('Missing required argument, must either provide "value" or "codec"');return new vi({cid:e,bytes:r,value:o})}var Wr=class extends Error{static name="AlreadyPinnedError";name="AlreadyPinnedError"},Wt=class extends Error{static name="BlockPinnedError";name="BlockPinnedError"},Gr=class extends Error{static name="InvalidDatastoreVersionError";name="InvalidDatastoreVersionError"},Ue=class extends Error{static name="InvalidConfigurationError";name="InvalidConfigurationError"},Qr=class extends AggregateError{static name="GetFailedError";name="GetFailedError"},Jr=class extends AggregateError{static name="LoadBlockFailedError";name="LoadBlockFailedError"},Gt=class extends Error{static name="BlockNotFoundWhileOfflineError";name="BlockNotFoundWhileOfflineError"};var Hc="/pin/",Vc="/pinned-block/",_i=me,Kc=1;function Xr(r){return r.version===0&&(r=r.toV1()),new we(`${Hc}${r.toString(_i)}`)}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=Xr(e);if(await this.datastore.has(n))throw new Wr("Already pinned");let o=Math.round(t.depth??1/0);if(o<0)throw new Oe("Depth must be greater than or equal to 0");let i=new q({concurrency:Kc});for await(let a of this.#e(e,i,{...t,depth:o}))await this.#t(a,c=>c.pinnedBy.find(l=>Ut(l,e.bytes))!=null?!1:(c.pinCount++,c.pinnedBy.push(e.bytes),!0),t),yield a;let s={depth:o,metadata:t.metadata??{}};await this.datastore.put(n,Ne(s),t)}async*#e(e,t,n){if(n.depth===-1)return;let o=await this.getCodec(e.code),i=await Vr(this.blockstore.get(e,n)),s=Hr({bytes:i,cid:e,codec:o});yield e;for(let[,a]of s.links())yield*await t.add(async()=>this.#e(a,t,{...n,depth:n.depth-1}))}async#t(e,t,n){let o=new we(`${Vc}${_i.encode(e.multihash.bytes)}`),i={pinCount:0,pinnedBy:[]};try{i=oe(await this.datastore.get(o,n))}catch(a){if(a.name!=="NotFoundError")throw a}if(t(i)){if(i.pinCount===0&&await this.datastore.has(o)){await this.datastore.delete(o);return}await this.datastore.put(o,Ne(i),n),n.onProgress?.(new E("helia:pin:add",e))}}async*rm(e,t={}){let n=Xr(e),o=await this.datastore.get(n,t),i=oe(o);await this.datastore.delete(n,t);let s=new q({concurrency:Kc});for await(let a of this.#e(e,s,{...t,depth:i.depth}))await this.#t(a,c=>(c.pinCount--,c.pinnedBy=c.pinnedBy.filter(l=>Ut(l,e.bytes)),!0),{...t,depth:i.depth}),yield a}async*ls(e={}){for await(let{key:t,value:n}of this.datastore.query({prefix:Hc+(e.cid!=null?`${e.cid.toString(me)}`:"")},e)){let o=P.parse(t.toString().substring(5),me),i=oe(n);yield{cid:o,...i}}}async isPinned(e,t={}){let n=new we(`${Vc}${_i.encode(e.multihash.bytes)}`);return this.datastore.has(n,t)}async get(e,t){let n=Xr(e),o=await this.datastore.get(n,t);return oe(o)}async setMetadata(e,t,n){let o=Xr(e),i=await this.datastore.get(o,n),s=oe(i);s.metadata=t??{},await this.datastore.put(o,Ne(s),n)}};var Zr=class extends Error{static name="InsufficientProvidersError";constructor(e="Insufficient providers found"){super(e),this.name="InsufficientProvidersError"}},Re=class extends Error{static name="NoRoutersAvailableError";constructor(e="No routers available"){super(e),this.name="NoRoutersAvailableError"}},en=class extends Error{static name="UnknownHashAlgorithmError";constructor(e="Unknown hash algorithm"){super(e),this.name="UnknownHashAlgorithmError"}},tn=class extends Error{static name="UnknownCodecError";constructor(e="Unknown codec"){super(e),this.name="UnknownCodecError"}};var _p=5,rn=class{name;log;routers;providerLookupConcurrency;constructor(e,t){this.name="helia",this.log=e.logger.forComponent("helia:routing"),this.routers=t.routers??[],this.providerLookupConcurrency=t.providerLookupConcurrency??_p,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 be(...this.routers)}async stop(){await xe(...this.routers)}async*findProviders(e,t={}){if(this.routers.length===0)throw new Re("No content routers available");let n=new qr({concurrency:this.providerLookupConcurrency}),o=0,i=[],s=this,a=0;this.log("findProviders for %c start using routers %s",e,this.routers.map(l=>l.toString()).join(", "));let c=Be(this.routers,"findProviders").map(async function*(l){let f=0;t?.onProgress?.(new E("helia:routing:find-providers:start",{routing:l.name,cid:e}));try{for await(let p of l.findProviders(e,t))f++,t?.onProgress?.(new E("helia:routing:find-providers:provider",{routing:l.name,cid:e,provider:p})),yield p}catch(p){i.push(p)}finally{s.log("router %s found %d providers for %c",l,f,e),t?.onProgress?.(new E("helia:routing:find-providers:end",{routing:l.name,cid:e,found:f})),a++,a===c.length&&n.size===0&&n.emitIdle()}});for await(let l of Tr(n.toGenerator(),...c))if(l!=null){if(l.multiaddrs.length===0){if(n.find(l.id)!=null)continue;n.add(async()=>{try{let f=await this.findPeer(l.id,t);return f.multiaddrs.length===0?null:{...f,protocols:l.protocols,routing:l.routing}}catch(f){return this.log.error("could not load multiaddrs for peer %p - %e",l.id,f),null}},{peerId:l.id,signal:t.signal}).catch(f=>{this.log.error("could not load multiaddrs for peer %p - %e",l.id,f)});continue}o++,yield l}this.log("findProviders finished, found %d providers for %c",o,e)}async provide(e,t={}){if(this.routers.length===0)throw new Re("No content routers available");await Promise.all(Be(this.routers,"provide").map(async n=>{t?.onProgress?.(new E("helia:routing:provide:start",{routing:n.name,cid:e})),await n.provide(e,t),t?.onProgress?.(new E("helia:routing:provide:end",{routing:n.name,cid:e}))}))}async cancelReprovide(e,t={}){await Promise.all(Be(this.routers,"cancelReprovide").map(async n=>{t?.onProgress?.(new E("helia:routing:cancel-reprovide:start",{routing:n.name,cid:e})),await n.cancelReprovide(e,t),t?.onProgress?.(new E("helia:routing:cancel-reprovide:end",{routing:n.name,cid:e}))}))}async put(e,t,n){await Promise.all(Be(this.routers,"put").map(async o=>{n?.onProgress?.(new E("helia:routing:put:start",{routing:o.name,key:e,value:t})),await o.put(e,t,n),n?.onProgress?.(new E("helia:routing:put:end",{routing:o.name,key:e,value:t}))}))}async get(e,t){let n=[],o;try{o=await Promise.any(Be(this.routers,"get").map(async i=>{t?.onProgress?.(new E("helia:routing:get:start",{routing:i.name,key:e}));try{return await i.get(e,t)}catch(s){this.log("router %s failed with %e",i,s),n.push(s)}finally{t?.onProgress?.(new E("helia:routing:get:end",{routing:i.name,key:e}))}}))}catch{}if(o==null)throw new Qr(n,`Failed to get value key ${it(e,"base58btc")}`);return o}async findPeer(e,t){if(this.routers.length===0)throw new Re("No peer routers available");let n=this,o=Tr(...Be(this.routers,"findPeer").map(i=>(async function*(){t?.onProgress?.(new E("helia:routing:find-peer:start",{routing:i.name,peerId:e}));try{yield await i.findPeer(e,t)}catch(s){n.log.error(s)}finally{t?.onProgress?.(new E("helia:routing:find-peer:end",{routing:i.name,peerId:e}))}})()));for await(let i of o)if(i!=null)return i;throw new er("Could not find peer in routing")}async*getClosestPeers(e,t={}){if(this.routers.length===0)throw new Re("No peer routers available");for await(let n of Tr(...Be(this.routers,"getClosestPeers").map(async function*(o){t?.onProgress?.(new E("helia:routing:get-closest-peers:start",{routing:o.name,key:e}));try{yield*o.getClosestPeers(e,t)}finally{t?.onProgress?.(new E("helia:routing:get-closest-peers:end",{routing:o.name,key:e}))}})))n!=null&&(yield n)}};function Be(r,e){return r.filter(t=>t[e]!=null)}var W=class extends Error{static name="AbortError";name="AbortError";constructor(e="The operation was aborted",...t){super(e,...t)}};async function nn(r,e,t,n){let o=new W(n?.errorMessage);n?.errorCode!=null&&(o.code=n.errorCode);let i=n?.errorEvent??"error";return t?.aborted===!0?Promise.reject(o):new Promise((s,a)=>{function c(){Si(t,"abort",p),Si(r,e,l),Si(r,i,f)}let l=m=>{try{if(n?.filter?.(m)===!1)return}catch(b){c(),a(b);return}c(),s(m)},f=m=>{if(c(),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.`))},p=()=>{c(),a(o)};Ai(t,"abort",p),Ai(r,e,l),Ai(r,i,f)})}function Ai(r,e,t){r!=null&&(Wc(r)?r.addEventListener(e,t):r.addListener(e,t))}function Si(r,e,t){r!=null&&(Wc(r)?r.removeEventListener(e,t):r.removeListener(e,t))}function Wc(r){return typeof r.addEventListener=="function"&&typeof r.removeEventListener=="function"}var on=class extends Error{static name="QueueFullError";constructor(e="The queue was full"){super(e),this.name="QueueFullError"}};var sn=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 W)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function Ap(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var an=class{id;fn;options;recipients;status;timeline;controller;constructor(e,t){this.id=Ap(),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 sn(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 Ae(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 Ii(r,e){let t,n=function(){let o=function(){t=void 0,r()};clearTimeout(t),t=setTimeout(o,e)};return n.start=()=>{},n.stop=()=>{clearTimeout(t)},n}var Qt=class extends G{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=Ii(this.emitEmpty.bind(this),1),this.emitIdle=Ii(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 on;let n=new an(e,t);return this.enqueue(n),this.safeDispatchEvent("add"),this.autoStart&&this.tryToStartAnother(),n.join(t).then(o=>(this.safeDispatchEvent("success",{detail:{job:n,result:o}}),o)).catch(o=>{if(n.status==="queued"){for(let i=0;i<this.queue.length;i++)if(this.queue[i]===n){this.queue.splice(i,1);break}}throw this.safeDispatchEvent("failure",{detail:{job:n,error:o}}),o})}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(e=>{e.abort(new W)}),this.clear()}async onEmpty(e){this.size!==0&&await nn(this,"empty",e?.signal)}async onSizeLessThan(e,t){this.size<e||await nn(this,"next",t?.signal,{filter:()=>this.size<e})}async onIdle(e){this.pending===0&&this.size===0||await nn(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=_r({objectMode:!0}),n=c=>{c!=null?this.abort():this.clear(),t.end(c)},o=c=>{c.detail!=null&&t.push(c.detail.result)},i=c=>{n(c.detail.error)},s=()=>{n()},a=()=>{n(new W("Queue aborted"))};this.addEventListener("success",o),this.addEventListener("failure",i),this.addEventListener("idle",s),e?.signal?.addEventListener("abort",a);try{yield*t}finally{this.removeEventListener("success",o),this.removeEventListener("failure",i),this.removeEventListener("idle",s),e?.signal?.removeEventListener("abort",a),n()}}};var cn="lock:worker:request-read",un="lock:worker:abort-read-request",ln="lock:worker:release-read",fn="lock:master:grant-read",hn="lock:master:error-read",dn="lock:worker:request-write",pn="lock:worker:abort-write-request",mn="lock:worker:release-write",gn="lock:master:grant-write",yn="lock:master:error-write",wn="lock:worker:finalize",bn="mortice",Gc={singleProcess:!1};var ki=(r,e,t,n,o,i,s,a,c)=>l=>{if(l.data==null)return;let f={type:l.data.type,name:l.data.name,identifier:l.data.identifier};f.type===o&&r.safeDispatchEvent(t,{detail:{name:f.name,identifier:f.identifier,handler:async()=>{e.postMessage({type:c,name:f.name,identifier:f.identifier}),await new Promise(p=>{let m=b=>{if(b?.data==null)return;let d={type:b.data.type,name:b.data.name,identifier:b.data.identifier};d.type===a&&d.identifier===f.identifier&&(e.removeEventListener("message",m),p())};e.addEventListener("message",m)})},onError:p=>{e.postMessage({type:s,name:f.name,identifier:f.identifier,error:{message:p.message,name:p.name,stack:p.stack}})}}}),f.type===i&&r.safeDispatchEvent(n,{detail:{name:f.name,identifier:f.identifier}}),f.type===wn&&r.safeDispatchEvent("finalizeRequest",{detail:{name:f.name}})};var Qc=(r=10)=>Math.random().toString().substring(2,r+2);var xn=class{name;channel;constructor(e){this.name=e,this.channel=new BroadcastChannel(bn)}readLock(e){return this.sendRequest(cn,un,fn,hn,ln,e)}writeLock(e){return this.sendRequest(dn,pn,gn,yn,mn,e)}finalize(){this.channel.postMessage({type:wn,name:this.name}),this.channel.close()}async sendRequest(e,t,n,o,i,s){s?.signal?.throwIfAborted();let a=Qc();return this.channel.postMessage({type:e,identifier:a,name:this.name}),new Promise((c,l)=>{let f=()=>{this.channel.postMessage({type:t,identifier:a,name:this.name})};s?.signal?.addEventListener("abort",f,{once:!0});let p=m=>{if(m.data?.identifier===a&&(m.data?.type===n&&(this.channel.removeEventListener("message",p),s?.signal?.removeEventListener("abort",f),c(()=>{this.channel.postMessage({type:i,identifier:a,name:this.name})})),m.data.type===o)){this.channel.removeEventListener("message",p),s?.signal?.removeEventListener("abort",f);let b=new Error;m.data.error!=null&&(b.message=m.data.error.message,b.name=m.data.error.name,b.stack=m.data.error.stack),l(b)}};this.channel.addEventListener("message",p)})}};var Jc=r=>{if(r=Object.assign({},Gc,r),!!globalThis.document||r.singleProcess){let t=new BroadcastChannel(bn),n=new G;return t.addEventListener("message",ki(n,t,"requestReadLock","abortReadLockRequest",cn,un,hn,ln,fn)),t.addEventListener("message",ki(n,t,"requestWriteLock","abortWriteLockRequest",dn,pn,yn,mn,gn)),n}return new xn(r.name)};var ze=new Map,Jt;function Xc(r){return typeof r?.readLock=="function"&&typeof r?.writeLock=="function"}function Sp(r){if(Jt==null&&(Jt=Jc(r),!Xc(Jt))){let e=Jt;e.addEventListener("requestReadLock",t=>{let n=t.detail.name,o=t.detail.identifier,i=ze.get(n);if(i==null)return;let s=new AbortController,a=c=>{c.detail.name!==n||c.detail.identifier!==o||s.abort()};e.addEventListener("abortReadLockRequest",a),i.readLock({signal:s.signal}).then(async c=>{await t.detail.handler().finally(()=>{c()})}).catch(c=>{t.detail.onError(c)}).finally(()=>{e.removeEventListener("abortReadLockRequest",a)})}),e.addEventListener("requestWriteLock",t=>{let n=t.detail.name,o=t.detail.identifier,i=ze.get(n);if(i==null)return;let s=new AbortController,a=c=>{c.detail.name!==n||c.detail.identifier!==o||s.abort()};e.addEventListener("abortWriteLockRequest",a),i.writeLock({signal:s.signal}).then(async c=>{await t.detail.handler().finally(()=>{c()})}).catch(c=>{t.detail.onError(c)}).finally(()=>{e.removeEventListener("abortWriteLockRequest",a)})}),e.addEventListener("finalizeRequest",t=>{let n=t.detail.name,o=ze.get(n);o?.finalize()})}return Jt}async function Ti(r,e){let t,n,o=new Promise((s,a)=>{t=s,n=a}),i=()=>{n(new W)};return e?.signal?.addEventListener("abort",i,{once:!0}),r.add(async()=>{await new Promise(s=>{t(()=>{e?.signal?.removeEventListener("abort",i),s()})})},{signal:e?.signal}).catch(s=>{n(s)}),o}var Yc=(r,e)=>{let t=ze.get(r);if(t!=null)return t;let n=Sp(e);if(Xc(n))return t=n,ze.set(r,t),t;let o=new Qt({concurrency:1}),i;return t={async readLock(s){if(i!=null)return Ti(i,s);i=new Qt({concurrency:e.concurrency,autoStart:!1});let a=i,c=Ti(i,s);return o.add(async()=>{a.start(),await a.onIdle().then(()=>{i===a&&(i=null)})}),c},async writeLock(s){return i=null,Ti(o,s)},finalize:()=>{ze.delete(r)},queue:o},ze.set(r,t),e.autoFinalize===!0&&o.addEventListener("idle",()=>{t.finalize()},{once:!0}),t};var Ip={name:"lock",concurrency:1/0,singleProcess:!1,autoFinalize:!1};function Li(r){let e=Object.assign({},Ip,r);return Yc(e.name,e)}var En=class{lock;child;pins;routing;started;constructor(e,t,n,o={}){this.child=e,this.pins=t,this.routing=n,this.lock=Li({singleProcess:o.holdGcLock}),this.started=!1}isStarted(){return this.started}async start(){await be(this.child),this.started=!0}async stop(){await xe(this.child),this.started=!1}unwrap(){return this.child}async put(e,t,n={}){n?.signal?.throwIfAborted();let o=await this.lock.readLock();try{return await this.child.put(e,t,n)}finally{o()}}async*putMany(e,t={}){t?.signal?.throwIfAborted();let n=await this.lock.readLock();try{yield*this.child.putMany(e,t)}finally{n()}}async*get(e,t={}){t?.signal?.throwIfAborted();let n=await this.lock.readLock();try{yield*this.child.get(e,t)}finally{n()}}async*getMany(e,t={}){t?.signal?.throwIfAborted();let n=await this.lock.readLock();try{yield*this.child.getMany(e,t)}finally{n()}}async delete(e,t={}){t?.signal?.throwIfAborted();let n=await this.lock.writeLock();try{if(await this.pins.isPinned(e))throw new Wt("Block was pinned - please unpin and try again");await this.routing.cancelReprovide(e,t),await this.child.delete(e,t)}finally{n()}}async*deleteMany(e,t={}){t?.signal?.throwIfAborted();let n=await this.lock.writeLock();try{let o=this;yield*this.child.deleteMany((async function*(){for await(let i of e){if(await o.pins.isPinned(i))throw new Wt("Block was pinned - please unpin and try again");await o.routing.cancelReprovide(i,t),yield i}})(),t)}finally{n()}}async has(e,t={}){t?.signal?.throwIfAborted();let n=await this.lock.readLock();try{return await this.child.has(e,t)}finally{n()}}async*getAll(e={}){e?.signal?.throwIfAborted();let t=await this.lock.readLock();try{yield*this.child.getAll(e)}finally{t()}}createSession(e,t){return t?.signal?.throwIfAborted(),this.child.createSession(e,t)}};var Ci=new we("/version"),Zc=1;async function eu(r){if(!await r.has(Ci)){await r.put(Ci,Er(`${Zc}`));return}let e=await r.get(Ci),t=it(e);if(parseInt(t,10)!==Zc)throw new Gr("Invalid datastore version, a datastore migration may be required")}var Ui={};_(Ui,{code:()=>Ni,decode:()=>Bp,decodeOptions:()=>Np,encode:()=>Rp,encodeOptions:()=>Dp,name:()=>Up,toByteView:()=>ru});var tu=42;function ru(r){return r instanceof ArrayBuffer?new Uint8Array(r,0,r.byteLength):r}function kp(r){if(r.asCID!==r&&r["/"]!==r.bytes)return null;let e=P.asCID(r);if(!e)return null;let t=new Uint8Array(e.bytes.byteLength+1);return t.set(e.bytes,1),[new h(u.tag,tu),new h(u.bytes,t)]}function Tp(){throw new Error("`undefined` is not supported by the IPLD Data Model and cannot be encoded")}function Lp(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 Cp(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 Di={float64:!0,typeEncoders:{Map:Cp,Object:kp,undefined:Tp,number:Lp}},Dp={...Di,typeEncoders:{...Di.typeEncoders}};function Pp(r){let e=r();if(e[0]!==0)throw new Error("Invalid CID for CBOR tag 42; expected leading 0x00");return P.decode(e.subarray(1))}var Pi={allowIndefinite:!1,coerceUndefinedToNull:!0,allowNaN:!1,allowInfinity:!1,allowBigInt:!0,strict:!0,useMaps:!1,rejectDuplicateMapKeys:!0,tags:{[tu]:Pp}},Np={...Pi,tags:{...Pi.tags}},Up="dag-cbor",Ni=113,Rp=r=>Ne(r,Di),Bp=r=>oe(ru(r),Pi);var $i={};_($i,{code:()=>Mi,decode:()=>iu,encode:()=>ou,format:()=>Wp,name:()=>Hp,parse:()=>Qp,stringify:()=>Wp});var Ri=class extends Array{constructor(){super(),this.inRecursive=[]}prefix(e){let t=this.inRecursive[this.inRecursive.length-1];t&&(u.equals(t.type,u.array)&&(t.elements++,t.elements!==1&&e.push([44])),u.equals(t.type,u.map)&&(t.elements++,t.elements!==1&&(t.elements%2===1?e.push([44]):e.push([58]))))}[u.uint.major](e,t){this.prefix(e);let n=String(t.value),o=[];for(let i=0;i<n.length;i++)o[i]=n.charCodeAt(i);e.push(o)}[u.negint.major](e,t){this[u.uint.major](e,t)}[u.bytes.major](e,t){throw new Error(`${fe} unsupported type: Uint8Array`)}[u.string.major](e,t){this.prefix(e);let n=at(JSON.stringify(t.value));e.push(n.length>32?De(n):n)}[u.array.major](e,t){this.prefix(e),this.inRecursive.push({type:u.array,elements:0}),e.push([91])}[u.map.major](e,t){this.prefix(e),this.inRecursive.push({type:u.map,elements:0}),e.push([123])}[u.tag.major](e,t){}[u.float.major](e,t){if(t.type.name==="break"){let s=this.inRecursive.pop();if(s){if(u.equals(s.type,u.array))e.push([93]);else if(u.equals(s.type,u.map))e.push([125]);else throw new Error("Unexpected recursive type; this should not happen!");return}throw new Error("Unexpected break; this should not happen!")}if(t.value===void 0)throw new Error(`${fe} unsupported type: undefined`);if(this.prefix(e),t.type.name==="true"){e.push([116,114,117,101]);return}else if(t.type.name==="false"){e.push([102,97,108,115,101]);return}else if(t.type.name==="null"){e.push([110,117,108,108]);return}let n=String(t.value),o=[],i=!1;for(let s=0;s<n.length;s++)o[s]=n.charCodeAt(s),!i&&(o[s]===46||o[s]===101||o[s]===69)&&(i=!0);i||(o.push(46),o.push(48)),e.push(o)}};function zp(r,e){if(Array.isArray(r[0])||Array.isArray(e[0]))throw new Error(`${fe} complex map keys are not supported`);let t=r[0],n=e[0];if(t.type!==u.string||n.type!==u.string)throw new Error(`${fe} non-string map keys are not supported`);if(t<n)return-1;if(t>n)return 1;throw new Error(`${fe} unexpected duplicate map keys, this is not supported`)}var Op={addBreakTokens:!0,mapSorter:zp};function Bi(r,e){return e=Object.assign({},Op,e),Mr(r,new Ri,e)}var pt=class{constructor(e,t={}){this._pos=0,this.data=e,this.options=t,this.modeStack=["value"],this.lastToken=""}pos(){return this._pos}done(){return this._pos>=this.data.length}ch(){return this.data[this._pos]}currentMode(){return this.modeStack[this.modeStack.length-1]}skipWhitespace(){let e=this.ch();for(;e===32||e===9||e===13||e===10;)e=this.data[++this._pos]}expect(e){if(this.data.length-this._pos<e.length)throw new Error(`${y} unexpected end of input at position ${this._pos}`);for(let t=0;t<e.length;t++)if(this.data[this._pos++]!==e[t])throw new Error(`${y} unexpected token at position ${this._pos}, expected to find '${String.fromCharCode(...e)}'`)}parseNumber(){let e=this._pos,t=!1,n=!1,o=a=>{for(;!this.done();){let c=this.ch();if(a.includes(c))this._pos++;else break}};if(this.ch()===45&&(t=!0,this._pos++),this.ch()===48)if(this._pos++,this.ch()===46)this._pos++,n=!0;else return new h(u.uint,0,this._pos-e);if(o([48,49,50,51,52,53,54,55,56,57]),t&&this._pos===e+1)throw new Error(`${y} unexpected token at position ${this._pos}`);if(!this.done()&&this.ch()===46){if(n)throw new Error(`${y} unexpected token at position ${this._pos}`);n=!0,this._pos++,o([48,49,50,51,52,53,54,55,56,57])}!this.done()&&(this.ch()===101||this.ch()===69)&&(n=!0,this._pos++,!this.done()&&(this.ch()===43||this.ch()===45)&&this._pos++,o([48,49,50,51,52,53,54,55,56,57]));let i=String.fromCharCode.apply(null,this.data.subarray(e,this._pos)),s=parseFloat(i);return n?new h(u.float,s,this._pos-e):this.options.allowBigInt!==!0||Number.isSafeInteger(s)?new h(s>=0?u.uint:u.negint,s,this._pos-e):new h(s>=0?u.uint:u.negint,BigInt(i),this._pos-e)}parseString(){if(this.ch()!==34)throw new Error(`${y} unexpected character at position ${this._pos}; this shouldn't happen`);this._pos++;for(let i=this._pos,s=0;i<this.data.length&&s<65536;i++,s++){let a=this.data[i];if(a===92||a<32||a>=128)break;if(a===34){let c=String.fromCharCode.apply(null,this.data.subarray(this._pos,i));return this._pos=i+1,new h(u.string,c,s)}}let e=this._pos,t=[],n=()=>{if(this._pos+4>=this.data.length)throw new Error(`${y} unexpected end of unicode escape sequence at position ${this._pos}`);let i=0;for(let s=0;s<4;s++){let a=this.ch();if(a>=48&&a<=57)a-=48;else if(a>=97&&a<=102)a=a-97+10;else if(a>=65&&a<=70)a=a-65+10;else throw new Error(`${y} unexpected unicode escape character at position ${this._pos}`);i=i*16+a,this._pos++}return i},o=()=>{let i=this.ch(),s=null,a=i>239?4:i>223?3:i>191?2:1;if(this._pos+a>this.data.length)throw new Error(`${y} unexpected unicode sequence at position ${this._pos}`);let c,l,f,p;switch(a){case 1:i<128&&(s=i);break;case 2:c=this.data[this._pos+1],(c&192)===128&&(p=(i&31)<<6|c&63,p>127&&(s=p));break;case 3:c=this.data[this._pos+1],l=this.data[this._pos+2],(c&192)===128&&(l&192)===128&&(p=(i&15)<<12|(c&63)<<6|l&63,p>2047&&(p<55296||p>57343)&&(s=p));break;case 4:c=this.data[this._pos+1],l=this.data[this._pos+2],f=this.data[this._pos+3],(c&192)===128&&(l&192)===128&&(f&192)===128&&(p=(i&15)<<18|(c&63)<<12|(l&63)<<6|f&63,p>65535&&p<1114112&&(s=p))}s===null?(s=65533,a=1):s>65535&&(s-=65536,t.push(s>>>10&1023|55296),s=56320|s&1023),t.push(s),this._pos+=a};for(;!this.done();){let i=this.ch(),s;switch(i){case 92:if(this._pos++,this.done())throw new Error(`${y} unexpected string termination at position ${this._pos}`);switch(s=this.ch(),this._pos++,s){case 34:case 39:case 92:case 47:t.push(s);break;case 98:t.push(8);break;case 116:t.push(9);break;case 110:t.push(10);break;case 102:t.push(12);break;case 114:t.push(13);break;case 117:t.push(n());break;default:throw new Error(`${y} unexpected string escape character at position ${this._pos}`)}break;case 34:return this._pos++,new h(u.string,qa(t),this._pos-e);default:if(i<32)throw new Error(`${y} invalid control character at position ${this._pos}`);i<128?(t.push(i),this._pos++):o()}}throw new Error(`${y} unexpected end of string at position ${this._pos}`)}parseValue(){switch(this.ch()){case 123:return this.modeStack.push("obj-start"),this._pos++,new h(u.map,1/0,1);case 91:return this.modeStack.push("array-start"),this._pos++,new h(u.array,1/0,1);case 34:return this.parseString();case 110:return this.expect([110,117,108,108]),new h(u.null,null,4);case 102:return this.expect([102,97,108,115,101]),new h(u.false,!1,5);case 116:return this.expect([116,114,117,101]),new h(u.true,!0,4);case 45:case 48:case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:return this.parseNumber();default:throw new Error(`${y} unexpected character at position ${this._pos}`)}}next(){switch(this.skipWhitespace(),this.currentMode()){case"value":return this.modeStack.pop(),this.parseValue();case"array-value":{if(this.modeStack.pop(),this.ch()===93)return this._pos++,this.skipWhitespace(),new h(u.break,void 0,1);if(this.ch()!==44)throw new Error(`${y} unexpected character at position ${this._pos}, was expecting array delimiter but found '${String.fromCharCode(this.ch())}'`);return this._pos++,this.modeStack.push("array-value"),this.skipWhitespace(),this.parseValue()}case"array-start":return this.modeStack.pop(),this.ch()===93?(this._pos++,this.skipWhitespace(),new h(u.break,void 0,1)):(this.modeStack.push("array-value"),this.skipWhitespace(),this.parseValue());case"obj-key":if(this.ch()===125)return this.modeStack.pop(),this._pos++,this.skipWhitespace(),new h(u.break,void 0,1);if(this.ch()!==44)throw new Error(`${y} unexpected character at position ${this._pos}, was expecting object delimiter but found '${String.fromCharCode(this.ch())}'`);this._pos++,this.skipWhitespace();case"obj-start":{if(this.modeStack.pop(),this.ch()===125)return this._pos++,this.skipWhitespace(),new h(u.break,void 0,1);let e=this.parseString();if(this.skipWhitespace(),this.ch()!==58)throw new Error(`${y} unexpected character at position ${this._pos}, was expecting key/value delimiter ':' but found '${String.fromCharCode(this.ch())}'`);return this._pos++,this.modeStack.push("obj-value"),e}case"obj-value":return this.modeStack.pop(),this.modeStack.push("obj-key"),this.skipWhitespace(),this.parseValue();default:throw new Error(`${y} unexpected parse state at position ${this._pos}; this shouldn't happen`)}}};function zi(r,e){return e=Object.assign({tokenizer:new pt(r,e)},e),oe(r,e)}function $p(r){return r instanceof ArrayBuffer?new Uint8Array(r,0,r.byteLength):r}function Fp(r){if(r.asCID!==r&&r["/"]!==r.bytes)return null;let e=P.asCID(r);if(!e)return null;let t=e.toString();return[new h(u.map,1/0,1),new h(u.string,"/",1),new h(u.string,t,t.length),new h(u.break,void 0,1)]}function vn(r){let e=et.encode(r).slice(1);return[new h(u.map,1/0,1),new h(u.string,"/",1),new h(u.map,1/0,1),new h(u.string,"bytes",5),new h(u.string,e,e.length),new h(u.break,void 0,1),new h(u.break,void 0,1)]}function ie(r){return vn(new Uint8Array(r.buffer,r.byteOffset,r.byteLength))}function qp(r){return vn(new Uint8Array(r))}function jp(){throw new Error("`undefined` is not supported by the IPLD Data Model and cannot be encoded")}function Vp(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 Kp={typeEncoders:{Object:Fp,Buffer:vn,Uint8Array:vn,Int8Array:ie,Uint16Array:ie,Int16Array:ie,Uint32Array:ie,Int32Array:ie,Float32Array:ie,Float64Array:ie,Uint8ClampedArray:ie,BigInt64Array:ie,BigUint64Array:ie,DataView:ie,ArrayBuffer:qp,undefined:jp,number:Vp}},Oi=class extends pt{constructor(e,t){super(e,t),this.tokenBuffer=[]}done(){return this.tokenBuffer.length===0&&super.done()}_next(){return this.tokenBuffer.length>0?this.tokenBuffer.pop():super.next()}next(){let e=this._next();if(u.equals(e.type,u.map)){let t=this._next();if(u.equals(t.type,u.string)&&t.value==="/"){let n=this._next();if(u.equals(n.type,u.string)){let o=this._next();if(!u.equals(o.type,u.break))throw new Error("Invalid encoded CID form");return this.tokenBuffer.push(n),new h(u.tag,42,0)}if(u.equals(n.type,u.map)){let o=this._next();if(u.equals(o.type,u.string)&&o.value==="bytes"){let i=this._next();if(u.equals(i.type,u.string)){for(let a=0;a<2;a++){let c=this._next();if(!u.equals(c.type,u.break))throw new Error("Invalid encoded Bytes form")}let s=et.decode(`m${i.value}`);return new h(u.bytes,s,i.value.length)}this.tokenBuffer.push(i)}this.tokenBuffer.push(o)}this.tokenBuffer.push(n)}this.tokenBuffer.push(t)}return e}},nu={allowIndefinite:!1,allowUndefined:!1,allowNaN:!1,allowInfinity:!1,allowBigInt:!0,strict:!0,useMaps:!1,rejectDuplicateMapKeys:!0,tags:{42:r=>P.parse(r())}},Hp="dag-json",Mi=297,ou=r=>Bi(r,Kp),iu=r=>{let e=$p(r),t=Object.assign(nu,{tokenizer:new Oi(e,nu)});return zi(e,t)},Wp=r=>Gp.decode(ou(r));var Gp=new TextDecoder,Qp=r=>iu(Jp.encode(r)),Jp=new TextEncoder;var Hi={};_(Hi,{code:()=>Ki,createLink:()=>mu,createNode:()=>pu,decode:()=>um,encode:()=>cm,name:()=>am,prepare:()=>ji,validate:()=>Vi});var Xp=new TextDecoder;function Fi(r,e){let t=0;for(let n=0;;n+=7){if(n>=64)throw new Error("protobuf: varint overflow");if(e>=r.length)throw new Error("protobuf: unexpected end of data");let o=r[e++];if(t+=n<28?(o&127)<<n:(o&127)*2**n,o<128)break}return[t,e]}function _n(r,e){let t;[t,e]=Fi(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 su(r,e){let t;return[t,e]=Fi(r,e),[t&7,t>>3,e]}function Yp(r){let e={},t=r.length,n=0;for(;n<t;){let o,i;if([o,i,n]=su(r,n),i===1){if(e.Hash)throw new Error("protobuf: (PBLink) duplicate Hash section");if(o!==2)throw new Error(`protobuf: (PBLink) wrong wireType (${o}) for Hash`);if(e.Name!==void 0)throw new Error("protobuf: (PBLink) invalid order, found Name before Hash");if(e.Tsize!==void 0)throw new Error("protobuf: (PBLink) invalid order, found Tsize before Hash");[e.Hash,n]=_n(r,n)}else if(i===2){if(e.Name!==void 0)throw new Error("protobuf: (PBLink) duplicate Name section");if(o!==2)throw new Error(`protobuf: (PBLink) wrong wireType (${o}) for Name`);if(e.Tsize!==void 0)throw new Error("protobuf: (PBLink) invalid order, found Tsize before Name");let s;[s,n]=_n(r,n),e.Name=Xp.decode(s)}else if(i===3){if(e.Tsize!==void 0)throw new Error("protobuf: (PBLink) duplicate Tsize section");if(o!==0)throw new Error(`protobuf: (PBLink) wrong wireType (${o}) for Tsize`);[e.Tsize,n]=Fi(r,n)}else throw new Error(`protobuf: (PBLink) invalid fieldNumber, expected 1, 2 or 3, got ${i}`)}if(n>t)throw new Error("protobuf: (PBLink) unexpected end of data");return e}function au(r){let e=r.length,t=0,n,o=!1,i;for(;t<e;){let a,c;if([a,c,t]=su(r,t),a!==2)throw new Error(`protobuf: (PBNode) invalid wireType, expected 2, got ${a}`);if(c===1){if(i)throw new Error("protobuf: (PBNode) duplicate Data section");[i,t]=_n(r,t),n&&(o=!0)}else if(c===2){if(o)throw new Error("protobuf: (PBNode) duplicate Links section");n||(n=[]);let l;[l,t]=_n(r,t),n.push(Yp(l))}else throw new Error(`protobuf: (PBNode) invalid fieldNumber, expected 1 or 2, got ${c}`)}if(t>e)throw new Error("protobuf: (PBNode) unexpected end of data");let s={};return i&&(s.Data=i),s.Links=n||[],s}var uu=new TextEncoder,cu=2**32,Zp=2**31;function em(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=Xt(e,t,r.Tsize)-1,e[t]=24}if(typeof r.Name=="string"){let n=uu.encode(r.Name);t-=n.length,e.set(n,t),t=Xt(e,t,n.length)-1,e[t]=18}return r.Hash&&(t-=r.Hash.length,e.set(r.Hash,t),t=Xt(e,t,r.Hash.length)-1,e[t]=10),e.length-t}function lu(r){let e=rm(r),t=new Uint8Array(e),n=e;if(r.Data&&(n-=r.Data.length,t.set(r.Data,n),n=Xt(t,n,r.Data.length)-1,t[n]=10),r.Links)for(let o=r.Links.length-1;o>=0;o--){let i=em(r.Links[o],t.subarray(0,n));n-=i,n=Xt(t,n,i)-1,t[n]=18}return t}function tm(r){let e=0;if(r.Hash){let t=r.Hash.length;e+=1+t+mt(t)}if(typeof r.Name=="string"){let t=uu.encode(r.Name).length;e+=1+t+mt(t)}return typeof r.Tsize=="number"&&(e+=1+mt(r.Tsize)),e}function rm(r){let e=0;if(r.Data){let t=r.Data.length;e+=1+t+mt(t)}if(r.Links)for(let t of r.Links){let n=tm(t);e+=1+n+mt(n)}return e}function Xt(r,e,t){e-=mt(t);let n=e;for(;t>=Zp;)r[e++]=t&127|128,t/=128;for(;t>=128;)r[e++]=t&127|128,t>>>=7;return r[e]=t,n}function mt(r){return r%2===0&&r++,Math.floor((nm(r)+6)/7)}function nm(r){let e=0;return r>=cu&&(r=Math.floor(r/cu),e=32),r>=65536&&(r>>>=16,e+=16),r>=256&&(r>>>=8,e+=8),e+om[r]}var om=[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 im=["Data","Links"],sm=["Hash","Name","Tsize"],qi=new TextEncoder;function hu(r,e){if(r===e)return 0;let t=r.Name?qi.encode(r.Name):[],n=e.Name?qi.encode(e.Name):[],o=t.length,i=n.length;for(let s=0,a=Math.min(o,i);s<a;++s)if(t[s]!==n[s]){o=t[s],i=n[s];break}return o<i?-1:i<o?1:0}function fu(r,e){return!Object.keys(r).some(t=>!e.includes(t))}function du(r){if(typeof r.asCID=="object"){let t=P.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=P.asCID(r.Hash);try{t||(typeof r.Hash=="string"?t=P.parse(r.Hash):r.Hash instanceof Uint8Array&&(t=P.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 ji(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=qi.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(du),e.Links.sort(hu);else throw new TypeError("Invalid DAG-PB form");else e.Links=[];return e}function Vi(r){if(!r||typeof r!="object"||Array.isArray(r)||r instanceof Uint8Array||r["/"]&&r["/"]===r.bytes)throw new TypeError("Invalid DAG-PB form");if(!fu(r,im))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(!fu(t,sm))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&&hu(t,r.Links[e-1])===-1)throw new TypeError("Invalid DAG-PB form (links must be sorted by Name bytes)")}}function pu(r,e=[]){return ji({Data:r,Links:e})}function mu(r,e,t){return du({Hash:t,Name:r,Tsize:e})}function gu(r){return r instanceof ArrayBuffer?new Uint8Array(r,0,r.byteLength):r}var am="dag-pb",Ki=112;function cm(r){Vi(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),lu(e)}function um(r){let e=gu(r),t=au(e),n={};return t.Data&&(n.Data=t.Data),t.Links&&(n.Links=t.Links.map(o=>{let i={};try{i.Hash=P.decode(o.Hash)}catch{}if(!i.Hash)throw new Error("Invalid Hash field found in link, expected CID");return o.Name!==void 0&&(i.Name=o.Name),o.Tsize!==void 0&&(i.Tsize=o.Tsize),i})),n}function gt(r){return r?.then!=null}function yu(r=[],e){let t={[Ki]:Hi,[Xo]:mr,[Ni]:Ui,[Mi]:$i,[Jo]:pr};return r.forEach(n=>{t[n.code]=n}),async n=>{let o=t[n];if(o==null&&e!=null){let i=e(n);gt(i)?o=await i:o=i,t[o.code]=o}if(o!=null)return o;throw new tn(`Could not load codec for ${n}`)}}function wu(r=[],e){let t={[wr.code]:wr,[br.code]:br,[yr.code]:yr};return r.forEach(n=>{t[n.code]=n}),async n=>{let o=t[n];if(o==null&&e!=null){let i=e(n);gt(i)?o=await i:o=i,t[o.code]=o}if(o!=null)return o;throw new en(`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 An=class r extends Error{static name="NotFoundError";name=r.name;static code="ERR_NOT_FOUND";code=r.code;constructor(e="Not Found"){super(e)}};var Sn=class{has(e,t){return Promise.reject(new Error(".has is not implemented"))}put(e,t,n){return Promise.reject(new Error(".put is not implemented"))}async*putMany(e,t){for await(let{cid:n,bytes:o}of e)await this.put(n,o,t),yield n}get(e,t){throw new Error(".get is not implemented")}async*getMany(e,t){for await(let n of e)yield{cid:n,bytes:this.get(n,t)}}delete(e,t){return Promise.reject(new Error(".delete is not implemented"))}async*deleteMany(e,t){for await(let n of e)await this.delete(n,t),yield n}async*getAll(e){throw new Error(".getAll is not implemented")}};var In=0,yt=class extends Error{static name="IdentityHashDigestTooLongError";name="IdentityHashDigestTooLongError"},kn=class extends Sn{child;maxDigestLength;constructor(e,t){super(),this.child=e,this.maxDigestLength=t?.maxDigestLength}put(e,t,n){if(e.multihash.code===In){if(this.maxDigestLength!=null&&e.multihash.digest.byteLength>this.maxDigestLength)throw new yt(`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===In){if(this.maxDigestLength!=null&&e.multihash.digest.byteLength>this.maxDigestLength)throw new yt(`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 An;yield*this.child.get(e,t)}has(e,t){if(e.multihash.code===In){if(this.maxDigestLength!=null&&e.multihash.digest.byteLength>this.maxDigestLength)throw new yt(`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===In){if(this.maxDigestLength!=null&&e.multihash.digest.byteLength>this.maxDigestLength)throw new yt(`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 lm(r){let[e,t]=r[Symbol.asyncIterator]!=null?[r[Symbol.asyncIterator](),Symbol.asyncIterator]:[r[Symbol.iterator](),Symbol.iterator],n=[];return{peek:()=>e.next(),push:o=>{n.push(o)},next:()=>n.length>0?{done:!1,value:n.shift()}:e.next(),[t](){return this}}}var Tn=lm;function fm(r){return r[Symbol.asyncIterator]!=null}function hm(r,e){let t=0;if(fm(r))return(async function*(){for await(let c of r)await e(c,t++)&&(yield c)})();let n=Tn(r),{value:o,done:i}=n.next();if(i===!0)return(function*(){})();let s=e(o,t++);if(typeof s.then=="function")return(async function*(){await s&&(yield o);for(let c of n)await e(c,t++)&&(yield c)})();let a=e;return(function*(){s===!0&&(yield o);for(let c of n)a(c,t++)&&(yield c)})()}var Ln=hm;function dm(r){return r[Symbol.asyncIterator]!=null}function bu(r){return r?.then!=null}function pm(r,e){let t=0;if(dm(r))return(async function*(){for await(let c of r){let l=e(c,t++);bu(l)&&await l,yield c}})();let n=Tn(r),{value:o,done:i}=n.next();if(i===!0)return(function*(){})();let s=e(o,t++);if(typeof s?.then=="function")return(async function*(){await s,yield o;for(let c of n){let l=e(c,t++);bu(l)&&await l,yield c}})();let a=e;return(function*(){yield o;for(let c of n)a(c,t++),yield c})()}var Wi=pm;var gm=128,wt=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 kn(e.blockstore,{maxDigestLength:t.maxIdentityHashDigestLength??gm}),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 o=>o.announce?.(e,n))),n.onProgress?.(new E("blocks:put:blockstore:put",e)),this.child.put(e,t,n))}async*putMany(e,t={}){let n=Ln(e,async({cid:i})=>{let s=await this.child.has(i,t);return s&&t.onProgress?.(new E("blocks:put-many:duplicate",i)),!s}),o=Wi(n,async({cid:i})=>{t.onProgress?.(new E("blocks:put-many:providers:notify",i)),await Promise.all(this.blockBrokers.map(async s=>s.announce?.(i,t)))});t.onProgress?.(new E("blocks:put-many:blockstore:put-many")),yield*this.child.putMany(o,t)}async*get(e,t={}){let n=await this.child.has(e,t),o=t.offline===!0;if(!n){if(o)throw new Gt("The block was present in the blockstore and the node is running offline so cannot fetch it");let i=await this.getHasher(e.multihash.code);t?.signal?.throwIfAborted(),t.onProgress?.(new E("blocks:get:providers:get",e));let s=await xu(e,this.blockBrokers,i,{...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 a=>a.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(Wi(e,async n=>{let o=await this.child.has(n,t),i=t.offline===!0;if(!o){if(i)throw new Gt("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 a=await xu(n,this.blockBrokers,s,{...t,log:this.log});t.onProgress?.(new E("blocks:get-many:blockstore:put",n)),await this.child.put(n,a,t),t.onProgress?.(new E("blocks:get-many:providers:notify",n)),await Promise.all(this.blockBrokers.map(async c=>c.announce?.(n,t)))}}))}async delete(e,t={}){t.onProgress?.(new 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 xu(r,e,t,n){let o=wm(r,t),i=new AbortController,s=te([i.signal,n.signal]);i.signal;let a=[];for(let c of e)ym(c)&&a.push(c);if(a.length===0)throw new Ue(`No block brokers capable of retrieving blocks are configured, the CID ${r} cannot be fetched from the network`);try{return await Promise.any(a.map(async c=>{try{let l=!1,f=await c.retrieve(r,{...n,signal:s,validateFn:async p=>{await o(p),n.signal?.throwIfAborted(),l=!0}});return l||(await o(f),n.signal?.throwIfAborted()),f}catch(l){throw n.log.error("could not retrieve verified block for %c from %s - %e",r,c.name,l),l}}))}catch(c){throw new Jr(c.errors,`Failed to load block for ${r}`)}finally{i.abort(),s.clear()}}function ym(r){return typeof r.retrieve=="function"}var wm=(r,e)=>{if(e==null)throw new Oe(`No hasher configured for multihash code 0x${r.multihash.code.toString(16)}, please configure one. You can look up which hash this is at https://github.com/multiformats/multicodec/blob/master/table.csv`);return async t=>{let n,o=e.digest(t,{truncate:r.multihash.digest.byteLength});if(gt(o)?n=await o:n=o,!Ut(n.digest,r.multihash.digest))throw new tr("Hash of downloaded block did not match multihash from passed CID")}};var Cn=class extends wt{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 o=te([this.closeController.signal,n.signal]);try{return await super.put(e,t,{...n,signal:o})}finally{o.clear()}}async*putMany(e,t={}){let n=te([this.closeController.signal,t.signal]);try{yield*super.putMany(e,{...t,signal:n})}finally{n.clear()}}async*get(e,t={}){let n=te([this.closeController.signal,t.signal]);try{yield*super.get(e,{...t,signal:n})}finally{n.clear()}}async*getMany(e,t={}){let n=te([this.closeController.signal,t.signal]);try{yield*super.getMany(e,{...t,signal:n})}finally{n.clear()}}async delete(e,t={}){let n=te([this.closeController.signal,t.signal]);try{await super.delete(e,{...t,signal:n})}finally{n.clear()}}async*deleteMany(e,t={}){let n=te([this.closeController.signal,t.signal]);try{yield*super.deleteMany(e,{...t,signal:n})}finally{n.clear()}}async has(e,t={}){let n=te([this.closeController.signal,t.signal]);try{return await super.has(e,{...t,signal:n})}finally{n.clear()}}async*getAll(e={}){let t=te([this.closeController.signal,e.signal]);try{yield*super.getAll({...e,signal:t})}finally{t.clear()}}};var Dn=class extends wt{started;constructor(e,t={}){super(e,t),this.started=!1}isStarted(){return this.started}async start(){await be(this.child,...this.blockBrokers),this.started=!0}async stop(){await xe(this.child,...this.blockBrokers),this.started=!1}unwrap(){return this.child}createSession(e,t){if(this.blockBrokers.length===0)throw new Ue("No block brokers configured");let n=this.blockBrokers.map(o=>o.createSession?.(t)).filter(o=>o!=null);if(n.length===0)throw new Ue(`No configured block brokers support sessions - tried ${this.blockBrokers.map(o=>o.name).join(", ")}`);return new Cn({blockstore:this.child,blockBrokers:n,getHasher:this.getHasher,logger:this.logger},{root:e})}};var Pn=class extends G{initialPeerSearchComplete;requests;logName;log;logger;minProviders;maxProviders;providers;evictionFilter;initialProviders;cidPeerFilterSize;constructor(e,t){super(),this.logName=t.name,this.logger=e.logger,this.log=e.logger.forComponent(this.logName),this.requests=new Map,this.minProviders=t.minProviders??1,this.maxProviders=t.maxProviders??5,this.cidPeerFilterSize=t.cidPeerFilterSize??100,this.providers=[],this.evictionFilter=hr(this.maxProviders),this.initialProviders=[...t.providers??[]]}async retrieve(e,t={}){let n=et.encode(e.multihash.bytes),o=this.requests.get(n);if(o!=null)return this.log("join existing request for %c",e),o.observers++,o.promise;let i=F(),s={promise:i.promise,observers:1,queryFilter:hr(this.cidPeerFilterSize)};this.requests.set(n,s);let a=!1;this.initialPeerSearchComplete==null&&(a=!0,this.log=this.logger.forComponent(`${this.logName}:${e}`),this.initialPeerSearchComplete=this.findProviders(e,this.minProviders,t));let c=!1,l=new q({concurrency:this.maxProviders});l.addEventListener("failure",m=>{this.log.error("error querying provider %s, evicting from session - %e",m.detail.job.options.provider,m.detail.error),this.evict(m.detail.job.options.provider)}),l.addEventListener("success",m=>{c=!0,i.resolve(m.detail.result)}),l.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 m=0;m<this.minProviders&&this.providers.length!==0;m++){let b=this.providers[Math.floor(Math.random()*this.providers.length)];this.evict(b)}await this.findProviders(e,this.minProviders,t),this.log("found new providers re-retrieving %c",e),this.requests.delete(n),i.resolve(await this.retrieve(e,t))}).catch(m=>{this.log.error("could not find new providers for %c - %e",e,m),i.reject(m)})});let f=m=>{let b=this.toFilterKey(m.detail);s.queryFilter.has(b)||(s.queryFilter.add(b),this.emitFoundProviderProgressEvent(e,m.detail,t),l.add(async()=>this.queryProvider(e,m.detail,t),{provider:m.detail}).catch(d=>{t.signal?.aborted!==!0&&this.log.error("error retrieving session block for %c - %e",e,d)}))};if(this.addEventListener("provider",f),a)try{await Ae(this.initialPeerSearchComplete,t.signal),a&&this.log("found initial session peers for %c",e)}catch(m){throw a&&this.log("failed to find initial session peers for %c - %e",e,m),this.requests.delete(n),s.observers>1&&i.reject(m),m}Promise.all([...this.providers].filter(m=>{let b=this.toFilterKey(m),d=s.queryFilter.has(b);return d||s.queryFilter.add(this.toFilterKey(m)),!d}).map(async m=>l.add(async()=>this.queryProvider(e,m,t),{provider:m}))).catch(m=>{t.signal?.aborted!==!0&&this.log.error("error retrieving session block for %c - %e",e,m)});let p=()=>{i.reject(new X(t.signal?.reason??"Session aborted")),l.abort()};t.signal?.addEventListener("abort",p);try{return await i.promise}finally{this.removeEventListener("provider",f),t.signal?.removeEventListener("abort",p),l.clear(),this.requests.delete(n)}}evict(e){this.evictionFilter.add(this.toFilterKey(e));let t=this.providers.findIndex(n=>this.equals(n,e));t!==-1&&this.providers.splice(t,1)}isEvicted(e){return this.evictionFilter.has(this.toFilterKey(e))}hasProvider(e){return!!(this.providers.find(t=>this.equals(t,e))!=null||this.isEvicted(e))}async addPeer(e,t){let n=await this.convertToProvider(e,"manually-added",t);n==null||this.hasProvider(n)||(this.providers.push(n),this.safeDispatchEvent("provider",{detail:n}))}async findProviders(e,t,n){let o=F(),i=0;return Promise.resolve().then(async()=>{this.log("finding %d-%d new provider(s) for %c - %d initial providers",t,this.maxProviders,e,this.initialProviders.length);let s=this,a=async function*(){for(;s.initialProviders.length>0;){let l=s.initialProviders.pop();if(l==null)continue;let f=await s.convertToProvider(l,"manual",n);f!=null&&(yield f)}},c=async function*(){yield*a(),yield*s.findNewProviders(e,n)};for await(let l of c()){if(this.providers.length===this.maxProviders||n.signal?.aborted===!0)break;if(!this.hasProvider(l)&&(this.log("found %d providers, %d in session",i,this.providers.length),this.providers.push(l),this.safeDispatchEvent("provider",{detail:l}),i++,this.providers.length===t&&(this.log("session is ready with %d peer(s), new peers present",this.providers.length),o.resolve()),this.providers.length===this.maxProviders)){this.log("found max session peers %d",this.providers.length);break}}if(this.log("found %d new session peers while trying to find %d, %d in session",i,t,this.providers.length),this.providers.length<t)throw new Zr(`Found ${i} of ${t} ${this.name} providers for ${e}, ${this.providers.length} in session after evictions`)}).catch(s=>{this.log.error("error searching routing for potential session peers for %c - %e",e,s),o.reject(s)}),o.promise}};function Eu(r){return e=>new Gi(e,r)}function vu(r){return e=>new Qi(e,r)}function _u(r){return e=>new Ji(e,r)}var Yt=class{components;constructor(e,t={}){this.components=e}async*walk(e,t){let n=this.getQueue(),o=Ln(n.toGenerator(t),a=>a!=null),i=!1,s=async a=>{let c=a.cid,l=await Vr(this.components.blockstore.get(c,a)),f=Hr({cid:c,bytes:l,codec:await this.components.getCodec(c.code)});for(let[,p]of f.links())t?.includeChild?.(p,f)!==!1&&n.add(s,{...a,cid:p,depth:a.depth+1,path:[...a.path,p]}).catch(m=>{i||o.throw(m)});return{block:f,depth:a.depth,path:a.path}};n.add(s,{...t,cid:e,depth:0,path:[e]}).catch(a=>{i||o.throw(a)});try{yield*o}finally{i=!0,n.abort()}}},Gi=class extends Yt{getQueue(){return new q({concurrency:1,sort:(e,t)=>e.options.depth===t.options.depth?0:e.options.depth<t.options.depth?1:-1})}},Qi=class extends Yt{getQueue(){return new q({concurrency:1,sort:(e,t)=>e.options.depth===t.options.depth?0:e.options.depth<t.options.depth?-1:1})}},Ji=class extends Yt{getQueue(){return new q({concurrency:1})}};var Xi=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=wu(e.hashers,e.loadHasher),this.getCodec=yu(e.codecs,e.loadCodec),this.dns=e.dns??zs(),this.metrics=e.metrics,this.libp2p=e.libp2p,this.events=new G;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 rn(t,{routers:(e.routers??[]).flatMap(o=>{typeof o=="function"&&(o=o(t));let i=[o],s=vm(o);s!=null&&i.push(s);let a=_m(o);return a!=null&&i.push(a),i}),providerLookupConcurrency:e.providerLookupConcurrency}),t.blockBrokers=e.blockBrokers.map(o=>o(t));let n=new Dn(t,e);this.pins=new Yr(e.datastore,n,this.getCodec),this.blockstore=new En(n,this.pins,this.routing,{holdGcLock:e.holdGcLock??!0}),this.datastore=e.datastore}async start(){await eu(this.datastore),await be(this.blockstore,this.datastore,this.routing,this.libp2p),this.events.dispatchEvent(new CustomEvent("start",{detail:this}))}async stop(){await xe(this.blockstore,this.datastore,this.routing,this.libp2p),this.events.dispatchEvent(new CustomEvent("stop",{detail:this}))}async gc(e={}){let t=await this.blockstore.lock.writeLock();try{let n=this,o=this.blockstore.unwrap();this.log("gc start"),await Os(o.deleteMany((async function*(){for await(let{cid:i}of o.getAll())try{if(await n.pins.isPinned(i,e))continue;yield i,e.onProgress?.(new E("helia:gc:deleted",i))}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 vm(r){return r?.[ts]}function _m(r){return r?.[rs]}return Lu(Am);})();
2
+ "use strict";var HeliaUtils=(()=>{var du=Object.create;var fr=Object.defineProperty;var pu=Object.getOwnPropertyDescriptor;var mu=Object.getOwnPropertyNames;var gu=Object.getPrototypeOf,yu=Object.prototype.hasOwnProperty;var rt=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),D=(r,e)=>{for(var t in e)fr(r,t,{get:e[t],enumerable:!0})},Xo=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of mu(e))!yu.call(r,i)&&i!==t&&fr(r,i,{get:()=>e[i],enumerable:!(n=pu(e,i))||n.enumerable});return r};var ri=(r,e,t)=>(t=r!=null?du(gu(r)):{},Xo(e||!r||!r.__esModule?fr(t,"default",{value:r,enumerable:!0}):t,r)),wu=r=>Xo(fr({},"__esModule",{value:!0}),r);var Us=rt((Bm,Bs)=>{"use strict";function Vl(r){return r>=55296&&r<=56319}function Hl(r){return r>=56320&&r<=57343}Bs.exports=function(e,t,n){if(typeof t!="string")throw new Error("Input must be string");for(var i=t.length,o=0,s,a,c=0;c<i;c+=1){if(s=t.charCodeAt(c),a=t[c],Vl(s)&&Hl(t.charCodeAt(c+1))&&(c+=1,a+=t[c]),o+=e(a),o===n)return t.slice(0,c+1);if(o>n)return t.slice(0,c-a.length+1)}return t}});var Ms=rt((Um,Os)=>{"use strict";function Wl(r){return r>=55296&&r<=56319}function Gl(r){return r>=56320&&r<=57343}Os.exports=function(e){if(typeof e!="string")throw new Error("Input must be string");for(var t=e.length,n=0,i=null,o=null,s=0;s<t;s++)i=e.charCodeAt(s),Gl(i)?o!=null&&Wl(o)?n+=1:n+=3:i<=127?n+=1:i>=128&&i<=2047?n+=2:i>=2048&&i<=65535&&(n+=3),o=i;return n}});var $s=rt((Om,Fs)=>{"use strict";var Jl=Us(),Ql=Ms();Fs.exports=Jl.bind(null,Ql)});var qs=rt((Mm,Ks)=>{"use strict";var Yl=$s(),Xl=/[\/\?<>\\:\*\|"]/g,Zl=/[\x00-\x1f\x80-\x9f]/g,eh=/^\.+$/,th=/^(con|prn|aux|nul|com[0-9]|lpt[0-9])(\..*)?$/i;function rh(r,e){for(var t=r.length;t>0&&(r[t-1]==="."||r[t-1]===" ");)t--;return t<r.length?r.slice(0,t)+e:r}function zs(r,e){if(typeof r!="string")throw new Error("Input must be string");var t=r.replace(Xl,e).replace(Zl,e).replace(eh,e).replace(th,e);return t=rh(t,e),Yl(t,255)}Ks.exports=function(r,e){var t=e&&e.replacement||"",n=zs(r,t);return t===""?n:zs(n,"")}});var da=rt((ny,Ji)=>{"use strict";var Fh=Object.prototype.hasOwnProperty,q="~";function Ht(){}Object.create&&(Ht.prototype=Object.create(null),new Ht().__proto__||(q=!1));function $h(r,e,t){this.fn=r,this.context=e,this.once=t||!1}function fa(r,e,t,n,i){if(typeof t!="function")throw new TypeError("The listener must be a function");var o=new $h(t,n||r,i),s=q?q+e:e;return r._events[s]?r._events[s].fn?r._events[s]=[r._events[s],o]:r._events[s].push(o):(r._events[s]=o,r._eventsCount++),r}function Fr(r,e){--r._eventsCount===0?r._events=new Ht:delete r._events[e]}function U(){this._events=new Ht,this._eventsCount=0}U.prototype.eventNames=function(){var e=[],t,n;if(this._eventsCount===0)return e;for(n in t=this._events)Fh.call(t,n)&&e.push(q?n.slice(1):n);return Object.getOwnPropertySymbols?e.concat(Object.getOwnPropertySymbols(t)):e};U.prototype.listeners=function(e){var t=q?q+e:e,n=this._events[t];if(!n)return[];if(n.fn)return[n.fn];for(var i=0,o=n.length,s=new Array(o);i<o;i++)s[i]=n[i].fn;return s};U.prototype.listenerCount=function(e){var t=q?q+e:e,n=this._events[t];return n?n.fn?1:n.length:0};U.prototype.emit=function(e,t,n,i,o,s){var a=q?q+e:e;if(!this._events[a])return!1;var c=this._events[a],l=arguments.length,h,f;if(c.fn){switch(c.once&&this.removeListener(e,c.fn,void 0,!0),l){case 1:return c.fn.call(c.context),!0;case 2:return c.fn.call(c.context,t),!0;case 3:return c.fn.call(c.context,t,n),!0;case 4:return c.fn.call(c.context,t,n,i),!0;case 5:return c.fn.call(c.context,t,n,i,o),!0;case 6:return c.fn.call(c.context,t,n,i,o,s),!0}for(f=1,h=new Array(l-1);f<l;f++)h[f-1]=arguments[f];c.fn.apply(c.context,h)}else{var d=c.length,y;for(f=0;f<d;f++)switch(c[f].once&&this.removeListener(e,c[f].fn,void 0,!0),l){case 1:c[f].fn.call(c[f].context);break;case 2:c[f].fn.call(c[f].context,t);break;case 3:c[f].fn.call(c[f].context,t,n);break;case 4:c[f].fn.call(c[f].context,t,n,i);break;default:if(!h)for(y=1,h=new Array(l-1);y<l;y++)h[y-1]=arguments[y];c[f].fn.apply(c[f].context,h)}}return!0};U.prototype.on=function(e,t,n){return fa(this,e,t,n,!1)};U.prototype.once=function(e,t,n){return fa(this,e,t,n,!0)};U.prototype.removeListener=function(e,t,n,i){var o=q?q+e:e;if(!this._events[o])return this;if(!t)return Fr(this,o),this;var s=this._events[o];if(s.fn)s.fn===t&&(!i||s.once)&&(!n||s.context===n)&&Fr(this,o);else{for(var a=0,c=[],l=s.length;a<l;a++)(s[a].fn!==t||i&&!s[a].once||n&&s[a].context!==n)&&c.push(s[a]);c.length?this._events[o]=c.length===1?c[0]:c:Fr(this,o)}return this};U.prototype.removeAllListeners=function(e){var t;return e?(t=q?q+e:e,this._events[t]&&Fr(this,t)):(this._events=new Ht,this._eventsCount=0),this};U.prototype.off=U.prototype.removeListener;U.prototype.addListener=U.prototype.on;U.prefixed=q;U.EventEmitter=U;typeof Ji<"u"&&(Ji.exports=U)});var ya=rt((Sy,ga)=>{ga.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 Yd={};D(Yd,{AbstractSession:()=>ti,Helia:()=>Yo,breadthFirstWalker:()=>hu,depthFirstWalker:()=>lu,naturalOrderWalker:()=>fu});function ce(r=0){return new Uint8Array(r)}function W(r=0){return new Uint8Array(r)}var bu=Math.pow(2,7),xu=Math.pow(2,14),Eu=Math.pow(2,21),Zo=Math.pow(2,28),es=Math.pow(2,35),ts=Math.pow(2,42),rs=Math.pow(2,49),M=128,Pe=127;function Tt(r){if(r<bu)return 1;if(r<xu)return 2;if(r<Eu)return 3;if(r<Zo)return 4;if(r<es)return 5;if(r<ts)return 6;if(r<rs)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function ns(r,e,t=0){switch(Tt(r)){case 8:e[t++]=r&255|M,r/=128;case 7:e[t++]=r&255|M,r/=128;case 6:e[t++]=r&255|M,r/=128;case 5:e[t++]=r&255|M,r/=128;case 4:e[t++]=r&255|M,r>>>=7;case 3:e[t++]=r&255|M,r>>>=7;case 2:e[t++]=r&255|M,r>>>=7;case 1:{e[t++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return e}function is(r,e){let t=r[e],n=0;if(n+=t&Pe,t<M||(t=r[e+1],n+=(t&Pe)<<7,t<M)||(t=r[e+2],n+=(t&Pe)<<14,t<M)||(t=r[e+3],n+=(t&Pe)<<21,t<M)||(t=r[e+4],n+=(t&Pe)*Zo,t<M)||(t=r[e+5],n+=(t&Pe)*es,t<M)||(t=r[e+6],n+=(t&Pe)*ts,t<M)||(t=r[e+7],n+=(t&Pe)*rs,t<M))return n;throw new RangeError("Could not decode varint")}function vu(r){return r.buffer instanceof ArrayBuffer}function L(r){return vu(r)?r:r.slice()}var ni=new Float32Array([-0]),Ne=new Uint8Array(ni.buffer);function os(r,e,t){ni[0]=r,e[t]=Ne[0],e[t+1]=Ne[1],e[t+2]=Ne[2],e[t+3]=Ne[3]}function ss(r,e){return Ne[0]=r[e],Ne[1]=r[e+1],Ne[2]=r[e+2],Ne[3]=r[e+3],ni[0]}var ii=new Float64Array([-0]),R=new Uint8Array(ii.buffer);function as(r,e,t){ii[0]=r,e[t]=R[0],e[t+1]=R[1],e[t+2]=R[2],e[t+3]=R[3],e[t+4]=R[4],e[t+5]=R[5],e[t+6]=R[6],e[t+7]=R[7]}function cs(r,e){return R[0]=r[e],R[1]=r[e+1],R[2]=r[e+2],R[3]=r[e+3],R[4]=r[e+4],R[5]=r[e+5],R[6]=r[e+6],R[7]=r[e+7],ii[0]}var _u=BigInt(Number.MAX_SAFE_INTEGER),Au=BigInt(Number.MIN_SAFE_INTEGER),G=class r{lo;hi;constructor(e,t){this.lo=e|0,this.hi=t|0}toNumber(e=!1){if(!e&&this.hi>>>31>0){let t=~this.lo+1>>>0,n=~this.hi>>>0;return t===0&&(n=n+1>>>0),-(t+n*4294967296)}return this.lo+this.hi*4294967296}toBigInt(e=!1){if(e)return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n);if(this.hi>>>31){let t=~this.lo+1>>>0,n=~this.hi>>>0;return t===0&&(n=n+1>>>0),-(BigInt(t)+(BigInt(n)<<32n))}return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n)}toString(e=!1){return this.toBigInt(e).toString()}zzEncode(){let e=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^e)>>>0,this.lo=(this.lo<<1^e)>>>0,this}zzDecode(){let e=-(this.lo&1);return this.lo=((this.lo>>>1|this.hi<<31)^e)>>>0,this.hi=(this.hi>>>1^e)>>>0,this}length(){let e=this.lo,t=(this.lo>>>28|this.hi<<4)>>>0,n=this.hi>>>24;return n===0?t===0?e<16384?e<128?1:2:e<2097152?3:4:t<16384?t<128?5:6:t<2097152?7:8:n<128?9:10}static fromBigInt(e){if(e===0n)return je;if(e<_u&&e>Au)return this.fromNumber(Number(e));let t=e<0n;t&&(e=-e);let n=e>>32n,i=e-(n<<32n);return t&&(n=~n|0n,i=~i|0n,++i>us&&(i=0n,++n>us&&(n=0n))),new r(Number(i),Number(n))}static fromNumber(e){if(e===0)return je;let t=e<0;t&&(e=-e);let n=e>>>0,i=(e-n)/4294967296>>>0;return t&&(i=~i>>>0,n=~n>>>0,++n>4294967295&&(n=0,++i>4294967295&&(i=0))),new r(n,i)}static from(e){return typeof e=="number"?r.fromNumber(e):typeof e=="bigint"?r.fromBigInt(e):typeof e=="string"?r.fromBigInt(BigInt(e)):e.low!=null||e.high!=null?new r(e.low>>>0,e.high>>>0):je}},je=new G(0,0);je.toBigInt=function(){return 0n};je.zzEncode=je.zzDecode=function(){return this};je.length=function(){return 1};var us=4294967296n;function ls(r){let e=0,t=0;for(let n=0;n<r.length;++n)t=r.charCodeAt(n),t<128?e+=1:t<2048?e+=2:(t&64512)===55296&&(r.charCodeAt(n+1)&64512)===56320?(++n,e+=4):e+=3;return e}function hs(r,e,t){if(t-e<1)return"";let i,o=[],s=0,a;for(;e<t;)a=r[e++],a<128?o[s++]=a:a>191&&a<224?o[s++]=(a&31)<<6|r[e++]&63:a>239&&a<365?(a=((a&7)<<18|(r[e++]&63)<<12|(r[e++]&63)<<6|r[e++]&63)-65536,o[s++]=55296+(a>>10),o[s++]=56320+(a&1023)):o[s++]=(a&15)<<12|(r[e++]&63)<<6|r[e++]&63,s>8191&&((i??(i=[])).push(String.fromCharCode.apply(String,o)),s=0);return i!=null?(s>0&&i.push(String.fromCharCode.apply(String,o.slice(0,s))),i.join("")):String.fromCharCode.apply(String,o.slice(0,s))}function oi(r,e,t){let n=t,i,o;for(let s=0;s<r.length;++s)i=r.charCodeAt(s),i<128?e[t++]=i:i<2048?(e[t++]=i>>6|192,e[t++]=i&63|128):(i&64512)===55296&&((o=r.charCodeAt(s+1))&64512)===56320?(i=65536+((i&1023)<<10)+(o&1023),++s,e[t++]=i>>18|240,e[t++]=i>>12&63|128,e[t++]=i>>6&63|128,e[t++]=i&63|128):(e[t++]=i>>12|224,e[t++]=i>>6&63|128,e[t++]=i&63|128);return t-n}function ue(r,e){return RangeError(`index out of range: ${r.pos} + ${e??1} > ${r.len}`)}function dr(r,e){return(r[e-4]|r[e-3]<<8|r[e-2]<<16|r[e-1]<<24)>>>0}var si=class{buf;pos;len;_slice=Uint8Array.prototype.subarray;constructor(e){this.buf=L(e),this.pos=0,this.len=e.length}uint32(){let e=4294967295;if(e=(this.buf[this.pos]&127)>>>0,this.buf[this.pos++]<128||(e=(e|(this.buf[this.pos]&127)<<7)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<14)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<21)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&15)<<28)>>>0,this.buf[this.pos++]<128))return e;if((this.pos+=5)>this.len)throw this.pos=this.len,ue(this,10);return e}int32(){return this.uint32()|0}sint32(){let e=this.uint32();return e>>>1^-(e&1)|0}bool(){return this.uint32()!==0}fixed32(){if(this.pos+4>this.len)throw ue(this,4);return dr(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw ue(this,4);return dr(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw ue(this,4);let e=ss(this.buf,this.pos);return this.pos+=4,e}double(){if(this.pos+8>this.len)throw ue(this,4);let e=cs(this.buf,this.pos);return this.pos+=8,e}bytes(){let e=this.uint32(),t=this.pos,n=this.pos+e;if(n>this.len)throw ue(this,e);return this.pos+=e,t===n?new Uint8Array(0):this.buf.subarray(t,n)}string(){let e=this.bytes();return hs(e,0,e.length)}skip(e){if(typeof e=="number"){if(this.pos+e>this.len)throw ue(this,e);this.pos+=e}else do if(this.pos>=this.len)throw ue(this);while((this.buf[this.pos++]&128)!==0);return this}skipType(e){switch(e){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;(e=this.uint32()&7)!==4;)this.skipType(e);break;case 5:this.skip(4);break;default:throw Error(`invalid wire type ${e} at offset ${this.pos}`)}return this}readLongVarint(){let e=new G(0,0),t=0;if(this.len-this.pos>4){for(;t<4;++t)if(e.lo=(e.lo|(this.buf[this.pos]&127)<<t*7)>>>0,this.buf[this.pos++]<128)return e;if(e.lo=(e.lo|(this.buf[this.pos]&127)<<28)>>>0,e.hi=(e.hi|(this.buf[this.pos]&127)>>4)>>>0,this.buf[this.pos++]<128)return e;t=0}else{for(;t<3;++t){if(this.pos>=this.len)throw ue(this);if(e.lo=(e.lo|(this.buf[this.pos]&127)<<t*7)>>>0,this.buf[this.pos++]<128)return e}return e.lo=(e.lo|(this.buf[this.pos++]&127)<<t*7)>>>0,e}if(this.len-this.pos>4){for(;t<5;++t)if(e.hi=(e.hi|(this.buf[this.pos]&127)<<t*7+3)>>>0,this.buf[this.pos++]<128)return e}else for(;t<5;++t){if(this.pos>=this.len)throw ue(this);if(e.hi=(e.hi|(this.buf[this.pos]&127)<<t*7+3)>>>0,this.buf[this.pos++]<128)return e}throw Error("invalid varint encoding")}readFixed64(){if(this.pos+8>this.len)throw ue(this,8);let e=dr(this.buf,this.pos+=4),t=dr(this.buf,this.pos+=4);return new G(e,t)}int64(){return this.readLongVarint().toBigInt()}int64Number(){return this.readLongVarint().toNumber()}int64String(){return this.readLongVarint().toString()}uint64(){return this.readLongVarint().toBigInt(!0)}uint64Number(){let e=is(this.buf,this.pos);return this.pos+=Tt(e),e}uint64String(){return this.readLongVarint().toString(!0)}sint64(){return this.readLongVarint().zzDecode().toBigInt()}sint64Number(){return this.readLongVarint().zzDecode().toNumber()}sint64String(){return this.readLongVarint().zzDecode().toString()}fixed64(){return this.readFixed64().toBigInt()}fixed64Number(){return this.readFixed64().toNumber()}fixed64String(){return this.readFixed64().toString()}sfixed64(){return this.readFixed64().toBigInt()}sfixed64Number(){return this.readFixed64().toNumber()}sfixed64String(){return this.readFixed64().toString()}};function Lt(r){return new si(r instanceof Uint8Array?r:r.subarray())}function pr(r,e,t){let n=Lt(r);return e.decode(n,void 0,t)}var fi={};D(fi,{base10:()=>Pu});var fp=new Uint8Array(0);function ds(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 le(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return Ve(r);if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return Ve(new Uint8Array(r.buffer,r.byteOffset,r.byteLength));throw new Error("Unknown type, must be binary type")}function ps(r){return new TextEncoder().encode(r)}function ms(r){return new TextDecoder().decode(r)}function ku(r){return r?.buffer instanceof ArrayBuffer}function Ve(r){return ku(r)?r:r.slice()}function Su(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),n=0;n<t.length;n++)t[n]=255;for(var i=0;i<r.length;i++){var o=r.charAt(i),s=o.charCodeAt(0);if(t[s]!==255)throw new TypeError(o+" is ambiguous");t[s]=i}var a=r.length,c=r.charAt(0),l=Math.log(a)/Math.log(256),h=Math.log(256)/Math.log(a);function f(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,E=0,C=0,O=w.length;C!==O&&w[C]===0;)C++,k++;for(var N=(O-C)*h+1>>>0,H=new Uint8Array(N);C!==O;){for(var te=w[C],De=0,ae=N-1;(te!==0||De<E)&&ae!==-1;ae--,De++)te+=256*H[ae]>>>0,H[ae]=te%a>>>0,te=te/a>>>0;if(te!==0)throw new Error("Non-zero carry");E=De,C++}for(var Ie=N-E;Ie!==N&&H[Ie]===0;)Ie++;for(var hr=c.repeat(k);Ie<N;++Ie)hr+=r.charAt(H[Ie]);return hr}function d(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 E=0,C=0;w[k]===c;)E++,k++;for(var O=(w.length-k)*l+1>>>0,N=new Uint8Array(O);w[k];){var H=t[w.charCodeAt(k)];if(H===255)return;for(var te=0,De=O-1;(H!==0||te<C)&&De!==-1;De--,te++)H+=a*N[De]>>>0,N[De]=H%256>>>0,H=H/256>>>0;if(H!==0)throw new Error("Non-zero carry");C=te,k++}if(w[k]!==" "){for(var ae=O-C;ae!==O&&N[ae]===0;)ae++;for(var Ie=new Uint8Array(E+(O-ae)),hr=E;ae!==O;)Ie[hr++]=N[ae++];return Ie}}}function y(w){var k=d(w);if(k)return k;throw new Error(`Non-${e} character`)}return{encode:f,decodeUnsafe:d,decode:y}}var Iu=Su,Tu=Iu,gs=Tu;var ci=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")}},ui=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 ys(this,e)}},li=class{decoders;constructor(e){this.decoders=e}or(e){return ys(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 ys(r,e){return new li({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var hi=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 ci(e,t,n),this.decoder=new ui(e,t,i)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function nt({name:r,prefix:e,encode:t,decode:n}){return new hi(r,e,t,n)}function Re({name:r,prefix:e,alphabet:t}){let{encode:n,decode:i}=gs(t,r);return nt({prefix:e,name:r,encode:n,decode:o=>le(i(o))})}function Lu(r,e,t,n){let i=r.length;for(;r[i-1]==="=";)--i;let o=new Uint8Array(i*t/8|0),s=0,a=0,c=0;for(let l=0;l<i;++l){let h=e[r[l]];if(h===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<t|h,s+=t,s>=8&&(s-=8,o[c++]=255&a>>s)}if(s>=t||(255&a<<8-s)!==0)throw new SyntaxError("Unexpected end of data");return o}function Cu(r,e,t){let n=e[e.length-1]==="=",i=(1<<t)-1,o="",s=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],s+=8;s>t;)s-=t,o+=e[i&a>>s];if(s!==0&&(o+=e[i&a<<t-s]),n)for(;(o.length*t&7)!==0;)o+="=";return o}function Du(r){let e={};for(let t=0;t<r.length;++t)e[r[t]]=t;return e}function T({name:r,prefix:e,bitsPerChar:t,alphabet:n}){let i=Du(n);return nt({prefix:e,name:r,encode(o){return Cu(o,n,t)},decode(o){return Lu(o,i,t,r)}})}var Pu=Re({prefix:"9",name:"base10",alphabet:"0123456789"});var di={};D(di,{base16:()=>Nu,base16upper:()=>Ru});var Nu=T({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),Ru=T({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var pi={};D(pi,{base2:()=>Bu});var Bu=T({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var mi={};D(mi,{base256emoji:()=>$u});var ws=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}"),Uu=ws.reduce((r,e,t)=>(r[t]=e,r),[]),Ou=ws.reduce((r,e,t)=>{let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);return r[n]=t,r},[]);function Mu(r){return r.reduce((e,t)=>(e+=Uu[t],e),"")}function Fu(r){let e=[];for(let t of r){let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);let i=Ou[n];if(i==null)throw new Error(`Non-base256emoji character: ${t}`);e.push(i)}return new Uint8Array(e)}var $u=nt({prefix:"\u{1F680}",name:"base256emoji",encode:Mu,decode:Fu});var gi={};D(gi,{base32:()=>it,base32hex:()=>ju,base32hexpad:()=>Hu,base32hexpadupper:()=>Wu,base32hexupper:()=>Vu,base32pad:()=>Ku,base32padupper:()=>qu,base32upper:()=>zu,base32z:()=>Gu});var it=T({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),zu=T({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Ku=T({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),qu=T({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),ju=T({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Vu=T({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Hu=T({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Wu=T({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Gu=T({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var yi={};D(yi,{base36:()=>he,base36upper:()=>Ju});var he=Re({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Ju=Re({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var wi={};D(wi,{base58btc:()=>B,base58flickr:()=>Qu});var B=Re({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Qu=Re({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var bi={};D(bi,{base64:()=>fe,base64pad:()=>Yu,base64url:()=>b,base64urlpad:()=>Xu});var fe=T({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Yu=T({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),b=T({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Xu=T({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var xi={};D(xi,{base8:()=>Zu});var Zu=T({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var Ei={};D(Ei,{identity:()=>el});var el=nt({prefix:"\0",name:"identity",encode:r=>ms(r),decode:r=>ps(r)});var mr={};D(mr,{code:()=>vi,decode:()=>ol,encode:()=>il,name:()=>nl});var tl=new TextEncoder,rl=new TextDecoder,nl="json",vi=512;function il(r){return tl.encode(JSON.stringify(r))}function ol(r){return JSON.parse(rl.decode(r))}var gr={};D(gr,{code:()=>_i,decode:()=>cl,encode:()=>al,name:()=>sl});var sl="raw",_i=85;function al(r){return le(r)}function cl(r){return le(r)}var ki={};D(ki,{identity:()=>Be});var ul=Es,bs=128,ll=127,hl=~ll,fl=Math.pow(2,31);function Es(r,e,t){e=e||[],t=t||0;for(var n=t;r>=fl;)e[t++]=r&255|bs,r/=128;for(;r&hl;)e[t++]=r&255|bs,r>>>=7;return e[t]=r|0,Es.bytes=t-n+1,e}var dl=Ai,pl=128,xs=127;function Ai(r,n){var t=0,n=n||0,i=0,o=n,s,a=r.length;do{if(o>=a)throw Ai.bytes=0,new RangeError("Could not decode varint");s=r[o++],t+=i<28?(s&xs)<<i:(s&xs)*Math.pow(2,i),i+=7}while(s>=pl);return Ai.bytes=o-n,t}var ml=Math.pow(2,7),gl=Math.pow(2,14),yl=Math.pow(2,21),wl=Math.pow(2,28),bl=Math.pow(2,35),xl=Math.pow(2,42),El=Math.pow(2,49),vl=Math.pow(2,56),_l=Math.pow(2,63),Al=function(r){return r<ml?1:r<gl?2:r<yl?3:r<wl?4:r<bl?5:r<xl?6:r<El?7:r<vl?8:r<_l?9:10},kl={encode:ul,decode:dl,encodingLength:Al},Sl=kl,Ct=Sl;function Dt(r,e=0){return[Ct.decode(r,e),Ct.decode.bytes]}function ot(r,e,t=0){return Ct.encode(r,e,t),e}function st(r){return Ct.encodingLength(r)}function ct(r,e){let t=e.byteLength,n=st(r),i=n+st(t),o=new Uint8Array(i+t);return ot(r,o,0),ot(t,o,n),o.set(e,i),new at(r,t,e,o)}function vs(r){let e=le(r),[t,n]=Dt(e),[i,o]=Dt(e.subarray(n)),s=e.subarray(n+o);if(s.byteLength!==i)throw new Error("Incorrect length");return new at(t,i,s,e)}function _s(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&ds(r.bytes,t.bytes)}}var at=class{code;size;digest;bytes;constructor(e,t,n,i){this.code=e,this.size=t,this.digest=Ve(n),this.bytes=Ve(i)}};var As=0,Il="identity",ks=le;function Tl(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 ct(As,ks(r))}var Be={code:As,name:Il,encode:ks,digest:Tl};var Ti={};D(Ti,{sha256:()=>Ue,sha512:()=>wr});var Ll=20;function Ii({name:r,code:e,encode:t,minDigestLength:n,maxDigestLength:i}){return new Si(r,e,t,n,i)}var Si=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,n,i,o){this.name=e,this.code=t,this.encode=n,this.minDigestLength=i??Ll,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?Ss(n,this.code,t?.truncate):n.then(i=>Ss(i,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}};function Ss(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 ct(e,r)}function Ts(r){return async e=>new Uint8Array(await crypto.subtle.digest(r,e))}var Ue=Ii({name:"sha2-256",code:18,encode:Ts("SHA-256")}),wr=Ii({name:"sha2-512",code:19,encode:Ts("SHA-512")});function Ls(r,e){let{bytes:t,version:n}=r;return n===0?Dl(t,Li(r),e??B.encoder):Pl(t,Li(r),e??it.encoder)}var Cs=new WeakMap;function Li(r){let e=Cs.get(r);if(e==null){let t=new Map;return Cs.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=Ve(i),this["/"]=this.bytes}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:e,multihash:t}=this;if(e!==Nt)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==Nl)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=ct(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&&_s(e.multihash,n.multihash)}toString(e){return Ls(this,e)}toJSON(){return{"/":Ls(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??Ds(n,i,o.bytes))}else if(t[Rl]===!0){let{version:n,multihash:i,code:o}=t,s=vs(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!==Nt)throw new Error(`Version 0 CID must use dag-pb (code: ${Nt}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let i=Ds(e,t,n.bytes);return new r(e,t,n,i)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,Nt,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=le(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 at(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[f,d]=Dt(e.subarray(t));return t+=d,f},i=n(),o=Nt;if(i===18?(i=0,t=0):o=n(),i!==0&&i!==1)throw new RangeError(`Invalid CID version ${i}`);let s=t,a=n(),c=n(),l=t+c,h=l-s;return{version:i,codec:o,multihashCode:a,digestSize:c,multihashSize:h,size:l}}static parse(e,t){let[n,i]=Cl(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 Li(o).set(n,e),o}};function Cl(r,e){switch(r[0]){case"Q":{let t=e??B;return[B.prefix,t.decode(`${B.prefix}${r}`)]}case B.prefix:{let t=e??B;return[B.prefix,t.decode(r)]}case it.prefix:{let t=e??it;return[it.prefix,t.decode(r)]}case he.prefix:{let t=e??he;return[he.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 Dl(r,e,t){let{prefix:n}=t;if(n!==B.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 Pl(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 Nt=112,Nl=18;function Ds(r,e,t){let n=st(r),i=n+st(e),o=new Uint8Array(i+t.byteLength);return ot(r,o,0),ot(e,o,n),o.set(t,i),o}var Rl=Symbol.for("@ipld/js-cid/CID");var Ci={...Ei,...pi,...xi,...fi,...di,...gi,...yi,...wi,...bi,...mi},Jp={...Ti,...ki};function Ns(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var Ps=Ns("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),Di=Ns("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=W(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),Bl={utf8:Ps,"utf-8":Ps,hex:Ci.base16,latin1:Di,ascii:Di,binary:Di,...Ci},br=Bl;function I(r,e="utf8"){let t=br[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.decoder.decode(`${t.prefix}${r}`)}function Pi(r){let e=r??8192,t=e>>>1,n,i=e;return function(s){if(s<1||s>t)return W(s);i+s>e&&(n=W(e),i=0);let a=n.subarray(i,i+=s);return(i&7)!==0&&(i=(i|7)+1),a}}var He=class{fn;len;next;val;constructor(e,t,n){this.fn=e,this.len=t,this.next=void 0,this.val=n}};function Ni(){}var Bi=class{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}},Ul=Pi();function Ol(r){return globalThis.Buffer!=null?W(r):Ul(r)}var Bt=class{len;head;tail;states;constructor(){this.len=0,this.head=new He(Ni,0,0),this.tail=this.head,this.states=null}_push(e,t,n){return this.tail=this.tail.next=new He(e,t,n),this.len+=t,this}uint32(e){return this.len+=(this.tail=this.tail.next=new Ui((e=e>>>0)<128?1:e<16384?2:e<2097152?3:e<268435456?4:5,e)).len,this}int32(e){return e<0?this._push(xr,10,G.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){let t=G.fromBigInt(e);return this._push(xr,t.length(),t)}uint64Number(e){return this._push(ns,Tt(e),e)}uint64String(e){return this.uint64(BigInt(e))}int64(e){return this.uint64(e)}int64Number(e){return this.uint64Number(e)}int64String(e){return this.uint64String(e)}sint64(e){let t=G.fromBigInt(e).zzEncode();return this._push(xr,t.length(),t)}sint64Number(e){let t=G.fromNumber(e).zzEncode();return this._push(xr,t.length(),t)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(Ri,1,e?1:0)}fixed32(e){return this._push(Rt,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){let t=G.fromBigInt(e);return this._push(Rt,4,t.lo)._push(Rt,4,t.hi)}fixed64Number(e){let t=G.fromNumber(e);return this._push(Rt,4,t.lo)._push(Rt,4,t.hi)}fixed64String(e){return this.fixed64(BigInt(e))}sfixed64(e){return this.fixed64(e)}sfixed64Number(e){return this.fixed64Number(e)}sfixed64String(e){return this.fixed64String(e)}float(e){return this._push(os,4,e)}double(e){return this._push(as,8,e)}bytes(e){let t=e.length>>>0;return t===0?this._push(Ri,1,0):this.uint32(t)._push(Fl,t,e)}string(e){let t=ls(e);return t!==0?this.uint32(t)._push(oi,t,e):this._push(Ri,1,0)}fork(){return this.states=new Bi(this),this.head=this.tail=new He(Ni,0,0),this.len=0,this}reset(){return this.states!=null?(this.head=this.states.head,this.tail=this.states.tail,this.len=this.states.len,this.states=this.states.next):(this.head=this.tail=new He(Ni,0,0),this.len=0),this}ldelim(){let e=this.head,t=this.tail,n=this.len;return this.reset().uint32(n),n!==0&&(this.tail.next=e.next,this.tail=t,this.len+=n),this}finish(){let e=this.head.next,t=Ol(this.len),n=0;for(;e!=null;)e.fn(e.val,t,n),n+=e.len,e=e.next;return t}};function Ri(r,e,t){e[t]=r&255}function Ml(r,e,t){for(;r>127;)e[t++]=r&127|128,r>>>=7;e[t]=r}var Ui=class extends He{next;constructor(e,t){super(Ml,e,t),this.next=void 0}};function xr(r,e,t){for(;r.hi!==0;)e[t++]=r.lo&127|128,r.lo=(r.lo>>>7|r.hi<<25)>>>0,r.hi>>>=7;for(;r.lo>127;)e[t++]=r.lo&127|128,r.lo=r.lo>>>7;e[t++]=r.lo}function Rt(r,e,t){e[t]=r&255,e[t+1]=r>>>8&255,e[t+2]=r>>>16&255,e[t+3]=r>>>24}function Fl(r,e,t){e.set(r,t)}globalThis.Buffer!=null&&(Bt.prototype.bytes=function(r){let e=r.length>>>0;return this.uint32(e),e>0&&this._push($l,e,r),this},Bt.prototype.string=function(r){let e=globalThis.Buffer.byteLength(r);return this.uint32(e),e>0&&this._push(zl,e,r),this});function $l(r,e,t){e.set(r,t)}function zl(r,e,t){r.length<40?oi(r,e,t):e.utf8Write!=null?e.utf8Write(r,t):e.set(I(r),t)}function Oi(){return new Bt}function Er(r,e){let t=Oi();return e.encode(r,t,{lengthDelimited:!1}),t.finish()}function*vr(r,e,t){let n=Lt(r);yield*e.stream(n,void 0,"$",t)}var _r={VARINT:0,BIT64:1,LENGTH_DELIMITED:2,START_GROUP:3,END_GROUP:4,BIT32:5};function Ar(r,e,t,n,i){return{name:r,type:e,encode:t,decode:n,stream:i}}function Mi(r){function e(o){if(r[o.toString()]==null)throw new Error("Invalid enum value");return r[o]}let t=function(s,a){let c=e(s);a.int32(c)},n=function(s){let a=s.int32();return e(a)},i=function*(s){let a=s.int32();yield e(a)};return Ar("enum",_r.VARINT,t,n,i)}function kr(r,e,t){return Ar("message",_r.LENGTH_DELIMITED,r,e,t)}var Sr;(function(r){r.RSA="RSA",r.Ed25519="Ed25519",r.secp256k1="secp256k1",r.ECDSA="ECDSA"})(Sr||(Sr={}));var Fi;(function(r){r[r.RSA=0]="RSA",r[r.Ed25519=1]="Ed25519",r[r.secp256k1=2]="secp256k1",r[r.ECDSA=3]="ECDSA"})(Fi||(Fi={}));(function(r){r.codec=()=>Mi(Fi)})(Sr||(Sr={}));var j;(function(r){let e;r.codec=()=>(e==null&&(e=kr((o,s,a={})=>{a.lengthDelimited!==!1&&s.fork(),o.Type!=null&&(s.uint32(8),s.int32(o.Type)),o.Data!=null&&(s.uint32(18),s.bytes(o.Data)),a.lengthDelimited!==!1&&s.ldelim()},(o,s,a={})=>{let c={},l=s==null?o.len:o.pos+s;for(;o.pos<l;){let h=o.uint32();switch(h>>>3){case 1:{c.Type=o.int32();break}case 2:{c.Data=o.bytes();break}default:{o.skipType(h&7);break}}}return c},function*(o,s,a,c={}){let l=s==null?o.len:o.pos+s;for(;o.pos<l;){let h=o.uint32();switch(h>>>3){case 1:{yield{field:`${a}.Type`,value:o.int32()};break}case 2:{yield{field:`${a}.Data`,value:o.bytes()};break}default:{o.skipType(h&7);break}}}})),e);function t(o){return Er(o,r.codec())}r.encode=t;function n(o,s){return pr(o,r.codec(),s)}r.decode=n;function i(o,s){return vr(o,r.codec(),s)}r.stream=i})(j||(j={}));var F;(function(r){let e;r.codec=()=>(e==null&&(e=kr((o,s,a={})=>{a.lengthDelimited!==!1&&s.fork(),o.Type!=null&&(s.uint32(8),s.int32(o.Type)),o.Data!=null&&(s.uint32(18),s.bytes(o.Data)),a.lengthDelimited!==!1&&s.ldelim()},(o,s,a={})=>{let c={},l=s==null?o.len:o.pos+s;for(;o.pos<l;){let h=o.uint32();switch(h>>>3){case 1:{c.Type=o.int32();break}case 2:{c.Data=o.bytes();break}default:{o.skipType(h&7);break}}}return c},function*(o,s,a,c={}){let l=s==null?o.len:o.pos+s;for(;o.pos<l;){let h=o.uint32();switch(h>>>3){case 1:{yield{field:`${a}.Type`,value:o.int32()};break}case 2:{yield{field:`${a}.Data`,value:o.bytes()};break}default:{o.skipType(h&7);break}}}})),e);function t(o){return Er(o,r.codec())}r.encode=t;function n(o,s){return pr(o,r.codec(),s)}r.decode=n;function i(o,s){return vr(o,r.codec(),s)}r.stream=i})(F||(F={}));function re(r,e="utf8"){let t=br[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.encoder.encode(r).substring(1)}var Te="/",Rs=new TextEncoder().encode(Te),Ir=Rs[0],ne=class r{_buf;constructor(e,t){if(typeof e=="string")this._buf=I(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]!==Ir)throw new Error("Invalid key")}toString(e="utf8"){return re(this._buf,e)}uint8Array(){return this._buf}get[Symbol.toStringTag](){return`Key(${this.toString()})`}static withNamespaces(e){return new r(e.join(Te))}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=Rs),this._buf[0]!==Ir){let e=new Uint8Array(this._buf.byteLength+1);e.fill(Ir,0,1),e.set(this._buf,1),this._buf=e}for(;this._buf.byteLength>1&&this._buf[this._buf.byteLength-1]===Ir;)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(Te).slice(1)}type(){return Kl(this.baseNamespace())}name(){return ql(this.baseNamespace())}instance(e){return new r(this.toString()+":"+e)}path(){let e=this.parent().toString();return e.endsWith(Te)||(e+=Te),e+=this.type(),new r(e)}parent(){let e=this.list();return e.length===1?new r(Te):new r(e.slice(0,-1).join(Te))}child(e){return this.toString()===Te?e:e.toString()===Te?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(),...jl(e.map(t=>t.namespaces()))])}};function Kl(r){let e=r.split(":");return e.length<2?"":e.slice(0,-1).join(":")}function ql(r){let e=r.split(":");return e[e.length-1]}function jl(r){return[].concat(...r)}var sa=ri(qs(),1);function nh(r){return r?.buffer instanceof ArrayBuffer}function js(r){if(nh(r))return r;let e=r.slice();return new Uint8Array(e.buffer,0,e.byteLength)}function de(r,e){e==null&&(e=r.reduce((i,o)=>i+o.length,0));let t=W(e),n=0;for(let i of r)t.set(i,n),n+=i.length;return js(t)}var $=class extends Error{static name="InvalidParametersError";name="InvalidParametersError"},Ut=class extends Error{static name="DecryptionFailedError";name="DecryptionFailedError"};function Le(r,e){if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return!1;return!0}var Hs=Symbol.for("@achingbrain/uint8arraylist");function Vs(r,e){if(e==null||e<0)throw new RangeError("index is out of bounds");let t=0;for(let n of r){let i=t+n.byteLength;if(e<i)return{buf:n,index:e-t};t=i}throw new RangeError("index is out of bounds")}function Tr(r){return!!r?.[Hs]}var z=class r{bufs;length;[Hs]=!0;constructor(...e){this.bufs=[],this.length=0,e.length>0&&this.appendAll(e)}*[Symbol.iterator](){yield*this.bufs}get byteLength(){return this.length}append(...e){this.appendAll(e)}appendAll(e){let t=0;for(let n of e)if(n instanceof Uint8Array)t+=n.byteLength,this.bufs.push(n);else if(Tr(n)){t+=n.byteLength;for(let i of n.bufs)this.bufs.push(i)}else throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");this.length+=t}prepend(...e){this.prependAll(e)}prependAll(e){let t=0;for(let n of e.reverse())if(n instanceof Uint8Array)t+=n.byteLength,this.bufs.unshift(n);else if(Tr(n))t+=n.byteLength,this.bufs.unshift(...n.bufs);else throw new Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");this.length+=t}get(e){let t=Vs(this.bufs,e);return t.buf[t.index]}set(e,t){let n=Vs(this.bufs,e);n.buf[n.index]=t}write(e,t=0){if(e instanceof Uint8Array)for(let n=0;n<e.length;n++)this.set(t+n,e[n]);else if(Tr(e))for(let n=0;n<e.length;n++)this.set(t+n,e.get(n));else throw new Error("Could not write value, must be an Uint8Array or a Uint8ArrayList")}consume(e){if(e=Math.trunc(e),!(Number.isNaN(e)||e<=0)){if(e===this.byteLength){this.bufs=[],this.length=0;return}for(;this.bufs.length>0;)if(e>=this.bufs[0].byteLength)e-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift();else{this.bufs[0]=this.bufs[0].subarray(e),this.length-=e;break}}}slice(e,t){let{bufs:n,length:i}=this._subList(e,t);return de(n,i)}subarray(e,t){let{bufs:n,length:i}=this._subList(e,t);return n.length===1?n[0]:de(n,i)}sublist(e,t){let{bufs:n,length:i}=this._subList(e,t),o=new r;return o.length=i,o.bufs=n,o}_subList(e,t){if(e=e??0,t=t??this.length,e<0&&(e=this.length+e),t<0&&(t=this.length+t),e<0||t>this.length)throw new RangeError("index is out of bounds");if(e===t)return{bufs:[],length:0};if(e===0&&t===this.length)return{bufs:[...this.bufs],length:this.length};let n=[],i=0;for(let o=0;o<this.bufs.length;o++){let s=this.bufs[o],a=i,c=a+s.byteLength;if(i=c,e>=c)continue;let l=e>=a&&e<c,h=t>a&&t<=c;if(l&&h){if(e===a&&t===c){n.push(s);break}let f=e-a;n.push(s.subarray(f,f+(t-e)));break}if(l){if(e===0){n.push(s);continue}n.push(s.subarray(e-a));continue}if(h){if(t===c){n.push(s);break}n.push(s.subarray(0,t-a));break}n.push(s)}return{bufs:n,length:t-e}}indexOf(e,t=0){if(!Tr(e)&&!(e instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');let n=e instanceof Uint8Array?e:e.subarray();if(t=Number(t??0),isNaN(t)&&(t=0),t<0&&(t=this.length+t),t<0&&(t=0),e.length===0)return t>this.length?this.length:t;let i=n.byteLength;if(i===0)throw new TypeError("search must be at least 1 byte long");let o=256,s=new Int32Array(o);for(let f=0;f<o;f++)s[f]=-1;for(let f=0;f<i;f++)s[n[f]]=f;let a=s,c=this.byteLength-n.byteLength,l=n.byteLength-1,h;for(let f=t;f<=c;f+=h){h=0;for(let d=l;d>=0;d--){let y=this.get(f+d);if(n[d]!==y){h=Math.max(1,d-a[y]);break}}if(h===0)return f}return-1}getInt8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getInt8(0)}setInt8(e,t){let n=W(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt8(0,t),this.write(n,e)}getInt16(e,t){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt16(0,t)}setInt16(e,t,n){let i=ce(2);new DataView(i.buffer,i.byteOffset,i.byteLength).setInt16(0,t,n),this.write(i,e)}getInt32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt32(0,t)}setInt32(e,t,n){let i=ce(4);new DataView(i.buffer,i.byteOffset,i.byteLength).setInt32(0,t,n),this.write(i,e)}getBigInt64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigInt64(0,t)}setBigInt64(e,t,n){let i=ce(8);new DataView(i.buffer,i.byteOffset,i.byteLength).setBigInt64(0,t,n),this.write(i,e)}getUint8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getUint8(0)}setUint8(e,t){let n=W(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint8(0,t),this.write(n,e)}getUint16(e,t){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint16(0,t)}setUint16(e,t,n){let i=ce(2);new DataView(i.buffer,i.byteOffset,i.byteLength).setUint16(0,t,n),this.write(i,e)}getUint32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint32(0,t)}setUint32(e,t,n){let i=ce(4);new DataView(i.buffer,i.byteOffset,i.byteLength).setUint32(0,t,n),this.write(i,e)}getBigUint64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigUint64(0,t)}setBigUint64(e,t,n){let i=ce(8);new DataView(i.buffer,i.byteOffset,i.byteLength).setBigUint64(0,t,n),this.write(i,e)}getFloat32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat32(0,t)}setFloat32(e,t,n){let i=ce(4);new DataView(i.buffer,i.byteOffset,i.byteLength).setFloat32(0,t,n),this.write(i,e)}getFloat64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat64(0,t)}setFloat64(e,t,n){let i=ce(8);new DataView(i.buffer,i.byteOffset,i.byteLength).setFloat64(0,t,n),this.write(i,e)}equals(e){if(e==null||!(e instanceof r)||e.bufs.length!==this.bufs.length)return!1;for(let t=0;t<this.bufs.length;t++)if(!Le(this.bufs[t],e.bufs[t]))return!1;return!0}static fromUint8Arrays(e,t){let n=new r;return n.bufs=e,t==null&&(t=e.reduce((i,o)=>i+o.byteLength,0)),n.length=t,n}};var ih=parseInt("11111",2),$i=parseInt("10000000",2),oh=parseInt("01111111",2),Ws={0:Ot,1:Ot,2:sh,3:uh,4:lh,5:ch,6:ah,16:Ot,22:Ot,48:Ot};function pe(r,e={offset:0}){let t=r[e.offset]&ih;if(e.offset++,Ws[t]!=null)return Ws[t](r,e);throw new Error("No decoder for tag 0x"+t.toString(16).padStart(2,"0"))}function Mt(r,e){let t=0;if((r[e.offset]&$i)===$i){let n=r[e.offset]&oh,i="0x";e.offset++;for(let o=0;o<n;o++,e.offset++)i+=r[e.offset].toString(16).padStart(2,"0");t=parseInt(i,16)}else t=r[e.offset],e.offset++;return t}function Ot(r,e){Mt(r,e);let t=[];for(;!(e.offset>=r.byteLength);){let n=pe(r,e);if(n===null)break;t.push(n)}return t}function sh(r,e){let t=Mt(r,e),n=e.offset,i=e.offset+t,o=[];for(let s=n;s<i;s++)s===n&&r[s]===0||o.push(r[s]);return e.offset+=t,Uint8Array.from(o)}function ah(r,e){let t=Mt(r,e),n=e.offset+t,i=r[e.offset];e.offset++;let o=0,s=0;i<40?(o=0,s=i):i<80?(o=1,s=i-40):(o=2,s=i-80);let a=`${o}.${s}`,c=[];for(;e.offset<n;){let l=r[e.offset];if(e.offset++,c.push(l&127),l<128){c.reverse();let h=0;for(let f=0;f<c.length;f++)h+=c[f]<<f*7;a+=`.${h}`,c=[]}}return a}function ch(r,e){return e.offset++,null}function uh(r,e){let t=Mt(r,e),n=r[e.offset];e.offset++;let i=r.subarray(e.offset,e.offset+t-1);if(e.offset+=t,n!==0)throw new Error("Unused bits in bit string is unimplemented");return i}function lh(r,e){let t=Mt(r,e),n=r.subarray(e.offset,e.offset+t);return e.offset+=t,n}function hh(r){let e=r.toString(16);e.length%2===1&&(e="0"+e);let t=new z;for(let n=0;n<e.length;n+=2)t.append(Uint8Array.from([parseInt(`${e[n]}${e[n+1]}`,16)]));return t}function Lr(r){if(r.byteLength<128)return Uint8Array.from([r.byteLength]);let e=hh(r.byteLength);return new z(Uint8Array.from([e.byteLength|$i]),e)}function K(r){let e=new z,t=128;return(r.subarray()[0]&t)===t&&e.append(Uint8Array.from([0])),e.append(r),new z(Uint8Array.from([2]),Lr(e),e)}function Ft(r){let e=Uint8Array.from([0]),t=new z(e,r);return new z(Uint8Array.from([3]),Lr(t),t)}function Gs(r){return new z(Uint8Array.from([4]),Lr(r),r)}function me(r,e=48){let t=new z;for(let n of r)t.append(L(n.subarray()));return new z(Uint8Array.from([e]),Lr(t),t)}var A=class extends Error{static name="InvalidParametersError";name="InvalidParametersError"};var fh=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),dh=Uint8Array.from([6,5,43,129,4,0,34]),ph=Uint8Array.from([6,5,43,129,4,0,35]),Js={ext:!0,kty:"EC",crv:"P-256"},Qs={ext:!0,kty:"EC",crv:"P-384"},Ys={ext:!0,kty:"EC",crv:"P-521"},ut=32,lt=48,ht=66,$t=class{type="ECDSA";code=3;jwk;constructor(e){this.jwk=e}toMultihash(){return Be.digest(this.toProtobuf())}toCID(){return v.createV1(114,this.toMultihash())}toString(){return B.encode(this.toMultihash().bytes).substring(1)}toJWK(){return JSON.parse(JSON.stringify(this.jwk))}toProtobuf(){return j.encode({Type:this.code,Data:wh(this.jwk)})}async verify(e,t,n){let i=await crypto.subtle.importKey("jwk",this.jwk,{name:"ECDSA",namedCurve:this.jwk.crv??"P-256"},!1,["verify"]),o=await crypto.subtle.verify({name:"ECDSA",hash:{name:"SHA-256"}},i,L(t),L(e));return n?.signal?.throwIfAborted(),o}},Cr=class{type="ECDSA";code=3;jwk;publicKey;constructor(e,t){this.jwk=e,this.publicKey=t}toProtobuf(){return F.encode({Type:this.code,Data:bh(this.jwk)})}toJWK(){return JSON.parse(JSON.stringify(this.jwk))}async sign(e,t){let n=await crypto.subtle.importKey("jwk",this.jwk,{name:"ECDSA",namedCurve:this.jwk.crv??"P-256"},!0,["sign"]),i=await crypto.subtle.sign({name:"ECDSA",hash:{name:"SHA-256"}},n,L(e));return t?.signal?.throwIfAborted(),new Uint8Array(i,0,i.byteLength)}},zi=class{type="ECDSA";code=3;async generatePrivateKey(e){let t=e?.curve??"P-256",n=await crypto.subtle.generateKey({name:"ECDSA",namedCurve:t},!0,["sign","verify"]),i=await crypto.subtle.exportKey("jwk",n.privateKey),o=await crypto.subtle.exportKey("jwk",n.publicKey);return e?.signal?.throwIfAborted(),new Cr(i,new $t(o))}async publicKeyFromProtobuf(e,t){let n=j.decode(e);if(n.Data==null)throw new A("Data field was missing from protobuf");if(n.Type!==this.code)throw new A("Incorrect Type field in protobuf");t?.signal?.throwIfAborted();let i=yh(n.Data);return new $t(i)}async privateKeyFromProtobuf(e,t){let n=F.decode(e);if(n.Data==null)throw new A("Data field was missing from protobuf");if(n.Type!==this.code)throw new A("Incorrect Type field in protobuf");let i=gh(n.Data),o=mh(i);return t?.signal?.throwIfAborted(),new Cr(i,new $t(o))}};function Ki(){return new zi}function mh(r){return{crv:r.crv,ext:!0,key_ops:["verify"],kty:"EC",x:r.x,y:r.y}}function gh(r){let e=pe(r),t=e[1],n=b.baseEncode(t),i=e[2][1][0],o=1,s,a;if(t.byteLength===ut)return s=b.baseEncode(i.subarray(o,o+ut)),a=b.baseEncode(i.subarray(o+ut)),{...Js,key_ops:["sign"],d:n,x:s,y:a};if(t.byteLength===lt)return s=b.baseEncode(i.subarray(o,o+lt)),a=b.baseEncode(i.subarray(o+lt)),{...Qs,key_ops:["sign"],d:n,x:s,y:a};if(t.byteLength===ht)return s=b.baseEncode(i.subarray(o,o+ht)),a=b.baseEncode(i.subarray(o+ht)),{...Ys,key_ops:["sign"],d:n,x:s,y:a};throw new A(`Private key length was wrong length, got ${t.byteLength}, expected 32, 48 or 66`)}function yh(r){let t=pe(r)[1][1][0],n=1,i,o;if(t.byteLength===ut*2+1)return i=b.baseEncode(t.subarray(n,n+ut)),o=b.baseEncode(t.subarray(n+ut)),{...Js,key_ops:["verify"],x:i,y:o};if(t.byteLength===lt*2+1)return i=b.baseEncode(t.subarray(n,n+lt)),o=b.baseEncode(t.subarray(n+lt)),{...Qs,key_ops:["verify"],x:i,y:o};if(t.byteLength===ht*2+1)return i=b.baseEncode(t.subarray(n,n+ht)),o=b.baseEncode(t.subarray(n+ht)),{...Ys,key_ops:["verify"],x:i,y:o};throw new A(`coordinates were wrong length, got ${t.byteLength}, expected 65, 97 or 133`)}function wh(r){return me([K(Uint8Array.from([1])),me([Xs(r.crv)],160),me([Ft(new z(Uint8Array.from([4]),b.baseDecode(r.x??""),b.baseDecode(r.y??"")))],161)]).subarray()}function bh(r){return me([K(Uint8Array.from([1])),Gs(b.baseDecode(r.d??"")),me([Xs(r.crv)],160),me([Ft(new z(Uint8Array.from([4]),b.baseDecode(r.x??""),b.baseDecode(r.y??"")))],161)]).subarray()}function Xs(r){if(r==="P-256")return fh;if(r==="P-384")return dh;if(r==="P-521")return ph;throw new A(`Invalid curve ${r}`)}var xh=32,zt=class{type="Ed25519";code=1;jwk;constructor(e){this.jwk=e}toMultihash(){return Be.digest(this.toProtobuf())}toCID(){return v.createV1(114,this.toMultihash())}toString(){return B.encode(this.toMultihash().bytes).substring(1)}toJWK(){return JSON.parse(JSON.stringify(this.jwk))}toProtobuf(){return j.encode({Type:this.code,Data:b.baseDecode(this.jwk.x??"")})}async verify(e,t,n){let i=await crypto.subtle.importKey("jwk",this.jwk,{name:"Ed25519"},!1,["verify"]),o=await crypto.subtle.verify({name:"Ed25519"},i,L(t),L(e));return n?.signal?.throwIfAborted(),o}},Dr=class{type="Ed25519";code=1;jwk;publicKey;constructor(e,t){this.jwk=e,this.publicKey=t}toProtobuf(){return F.encode({Type:this.code,Data:de([b.baseDecode(this.jwk.d??""),b.baseDecode(this.jwk.x??"")],64)})}toJWK(){return JSON.parse(JSON.stringify(this.jwk))}async sign(e,t){let n=await crypto.subtle.importKey("jwk",this.jwk,{name:"Ed25519"},!0,["sign"]),i=await crypto.subtle.sign({name:"Ed25519"},n,L(e));return t?.signal?.throwIfAborted(),new Uint8Array(i,0,i.byteLength)}},qi=class{type="Ed25519";code=1;async generatePrivateKey(e){let t=await crypto.subtle.generateKey("Ed25519",!0,["sign","verify"]),n=await crypto.subtle.exportKey("jwk",t.privateKey),i=await crypto.subtle.exportKey("jwk",t.publicKey);return e?.signal?.throwIfAborted(),new Dr(n,new zt(i))}async publicKeyFromProtobuf(e,t){let n=j.decode(e);if(n.Data==null)throw new A("Data field was missing from protobuf");if(n.Type!==this.code)throw new A("Incorrect Type field in protobuf");t?.signal?.throwIfAborted();let i=Ah(n.Data);return new zt(i)}async privateKeyFromProtobuf(e,t){let n=F.decode(e);if(n.Data==null)throw new A("Data field was missing from protobuf");if(n.Type!==this.code)throw new A("Incorrect Type field in protobuf");let i=await Eh(n.Data,t),o=_h(i);return new Dr(i,new zt(o))}};function ji(){return new qi}async function Eh(r,e){let t=r.subarray(0,xh),n=vh(t),i=await crypto.subtle.importKey("pkcs8",n,{name:"Ed25519"},!0,["sign"]),o=await crypto.subtle.exportKey("jwk",i);return e?.signal?.throwIfAborted(),o}var Zs=Uint8Array.from([48,46,2,1,0,48,5,6,3,43,101,112,4,34,4]);function vh(r){return de([Zs,Uint8Array.from([r.byteLength]),r],Zs.byteLength+1+r.byteLength)}function _h(r){return{alg:"Ed25519",crv:"Ed25519",ext:!0,key_ops:["verify"],kty:"OKP",x:r.x}}function Ah(r){return{alg:"Ed25519",crv:"Ed25519",ext:!0,key_ops:["verify"],kty:"OKP",x:b.baseEncode(r)}}var Wi=8192,Kt=class{type="RSA";code=0;_raw;digest;jwk;constructor(e,t){if(ta(e)>Wi)throw new A("Key size is too large");this.jwk=e,this.digest=t}toMultihash(){return this.digest}toCID(){return v.createV1(114,this.toMultihash())}toString(){return this.toCID().toString(he)}toProtobuf(){return Ch(this.code,this.jwk)}toJWK(){return JSON.parse(JSON.stringify(this.jwk))}async verify(e,t,n){let i=await crypto.subtle.importKey("jwk",this.jwk,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]),o=await crypto.subtle.verify({name:"RSASSA-PKCS1-v1_5"},i,L(t),L(e));return n?.signal?.throwIfAborted(),o}},Pr=class{type="RSA";code=0;publicKey;jwk;constructor(e,t){if(ta(e)>Wi)throw new A("Key size is too large");this.jwk=e,this.publicKey=t}toProtobuf(){return Dh(this.code,this.jwk)}toJWK(){return JSON.parse(JSON.stringify(this.jwk))}async sign(e,t){let n=await crypto.subtle.importKey("jwk",this.jwk,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]),i=await crypto.subtle.sign({name:"RSASSA-PKCS1-v1_5"},n,L(e));return t?.signal?.throwIfAborted(),new Uint8Array(i,0,i.byteLength)}},Hi=class{type="RSA";code=0;async generatePrivateKey(e){let t=e?.bits??2048;if(t>Wi)throw new A("Key size is too large");let n=await crypto.subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:t,publicExponent:new Uint8Array([1,0,1]),hash:{name:"SHA-256"}},!0,["sign","verify"]),i=await crypto.subtle.exportKey("jwk",n.privateKey),o=await crypto.subtle.exportKey("jwk",n.publicKey),s=await Vi(i);return e?.signal?.throwIfAborted(),new Pr(i,new Kt(o,s))}async publicKeyFromProtobuf(e,t){let n=j.decode(e);if(n.Data==null)throw new A("Data field was missing from protobuf");if(n.Type!==this.code)throw new A("Incorrect Type field in protobuf");let i=Th(n.Data),o=await Vi(i);return t?.signal?.throwIfAborted(),new Kt(i,o)}async privateKeyFromProtobuf(e,t){let n=F.decode(e);if(n.Data==null)throw new A("Data field was missing from protobuf");if(n.Type!==this.code)throw new A("Incorrect Type field in protobuf");let i=pe(n.Data),o=kh(i),s=Lh(o),a=await Vi(s);return t?.signal?.throwIfAborted(),new Pr(o,new Kt(s,a))}};function qt(){return new Hi}function kh(r){return{alg:"RS256",kty:"RSA",n:b.baseEncode(r[1]),e:b.baseEncode(r[2]),ext:!0,key_ops:["sign"],d:b.baseEncode(r[3]),p:b.baseEncode(r[4]),q:b.baseEncode(r[5]),dp:b.baseEncode(r[6]),dq:b.baseEncode(r[7]),qi:b.baseEncode(r[8])}}function Sh(r){if(r.n==null||r.e==null||r.d==null||r.p==null||r.q==null||r.dp==null||r.dq==null||r.qi==null)throw new A("JWK was missing components");return me([K(Uint8Array.from([0])),K(b.baseDecode(r.n)),K(b.baseDecode(r.e)),K(b.baseDecode(r.d)),K(b.baseDecode(r.p)),K(b.baseDecode(r.q)),K(b.baseDecode(r.dp)),K(b.baseDecode(r.dq)),K(b.baseDecode(r.qi))]).subarray()}var Ih=Uint8Array.from([48,13,6,9,42,134,72,134,247,13,1,1,1,5,0]);function ea(r){if(r.n==null||r.e==null)throw new A("JWK public key was missing components");return me([Ih,Ft(me([K(b.baseDecode(r.n)),K(b.baseDecode(r.e))]))]).subarray()}function Th(r){let e=pe(r);if(e.length<2||e[0]?.[0]!=="1.2.840.113549.1.1.1")throw new Error("PKIX certificate was invalid");let t=pe(e[1]);return{kty:"RSA",n:b.baseEncode(t[0]),e:b.baseEncode(t[1])}}function Lh(r){return{key_ops:["verify"],ext:!0,alg:"RS256",kty:"RSA",n:r.n,e:"AQAB"}}function ta(r){if(r.kty!=="RSA")throw new A("Invalid key type");if(r.n==null)throw new A("Invalid key modulus");return b.baseDecode(r.n).length*8}async function Vi(r){let e=j.encode({Type:0,Data:ea(r)});return Ue.digest(e)}function Ch(r,e){return j.encode({Type:r,Data:ea(e)})}function Dh(r,e){return F.encode({Type:r,Data:Sh(e)})}async function na(r,e,t){r=r.replaceAll("-----BEGIN ENCRYPTED PRIVATE KEY-----",""),r=r.replaceAll("-----END ENCRYPTED PRIVATE KEY-----",""),r=r.replaceAll("\r",""),r=r.replaceAll(`
3
+ `,"");let n=fe.decode(`m${r}`),i=pe(n),o=i[0][1][0][1][0],s=ra(i[0][1][0][1][1]),a=ra(i[0][1][0][1][2]),c=i[0][1][0][1][4][1],l=i[0][1][0][1][4][2],h=await e.decrypt(o,c,l,{iterations:s,keyLength:a*8,hash:"SHA-512",algorithm:"AES-CBC",signal:t?.signal}),d=pe(h)[2],y=F.encode({Type:0,Data:d});return qt().privateKeyFromProtobuf(y)}function ra(r){if(r.length===0)return 0;let e=[...r].map(t=>t.toString(16).padStart(2,"0")).join("");return parseInt(e,16)}var Ph="/pkcs8/",aa="/info/",Nh=Symbol.for("@libp2p/service-capabilities"),jt={iterations:1e4,salt:I("you should override this value with a crypto secure random number"),hash:"SHA-512",algorithm:"AES-GCM"},ft={iterations:32767,saltLength:16,ivLength:12,hash:"SHA-256",keyLength:128,algorithm:"AES-GCM"},Gi=20,Nr={minKeyLength:112/8,minSaltLength:128/8,minIterations:1e3},ia={"SHA-256":128,"SHA-384":192,"SHA-512":256};function Vt(r){return r==null||typeof r!="string"?!1:r===(0,sa.default)(r.trim())&&r.length>0}function dt(r){return new ne(Ph+r)}function Rr(r){return new ne(aa+r)}async function Rh(r,e){let t=r.toProtobuf(),n=await Ue.digest(t);return e?.signal?.throwIfAborted(),B.encode(n.bytes).substring(1)}function Bh(r){if(typeof r=="string")return I(r);if(r instanceof Uint8Array)return L(r)}var Br=class{components;self;cipher;salt;keychainDekOptions;privateKeyDekOptions;constructor(e,t={}){if(this.components=e,this.self=t.selfKey??"self",this.salt=Bh(t.salt)??jt.salt,this.keychainDekOptions={iterations:t.iterations??jt.iterations,hash:t.hash??jt.hash,keyLength:ia[t.hash??jt.hash],algorithm:jt.algorithm},this.privateKeyDekOptions={iterations:ft.iterations,hash:ft.hash,saltLength:ft.saltLength,ivLength:ft.ivLength,keyLength:ft.keyLength,algorithm:ft.algorithm},t.password!=null&&t.password.length<Gi)throw new Error("password must be least 20 characters");if(this.salt.byteLength!=null&&this.salt.byteLength<Nr.minSaltLength)throw new Error(`salt must be least ${Nr.minSaltLength} bytes`);if(t.iterations!=null&&t.iterations<Nr.minIterations)throw new Error(`iterations must be least ${Nr.minIterations}`);if(ia[this.keychainDekOptions.hash]==null)throw new $("Unsupported hash");this.cipher=oa(t.password??"",this.salt,this.keychainDekOptions,this.privateKeyDekOptions)}[Nh]=["@ipshipyard/keychain"];async generateKey(e,t){let i=await(await this.components.getCrypto(t?.type??"Ed25519",t)).generatePrivateKey(t);return this.importKey(e,i,t)}async importKey(e,t,n){if(!Vt(e))throw new $(`Invalid key name '${e}'`);if(t==null)throw new $("Key is required");if(await this.components.datastore.has(dt(e),n))throw new $(`Key '${e}' already exists`);let o=this.components.datastore.batch();return await this._importKey(e,t,this.cipher,o,n),await o.commit(n),t}async _importKey(e,t,n,i,o){let s=t.toProtobuf(),a=await n.encrypt(s),c=de([a.salt,a.iv,a.cipherText],a.salt.byteLength+a.iv.byteLength+a.cipherText.byteLength),l=fe.encode(c),h={name:e,id:await Rh(t,o)};i.put(dt(e),I(l)),i.put(Rr(e),I(JSON.stringify(h)))}async exportKey(e,t){if(!Vt(e))throw new $(`Invalid key name '${e}'`);return this._exportKey(e,this.cipher,t)}async _exportKey(e,t,n){let i=await this.components.datastore.get(dt(e),n),o=re(i),s;if(o.includes("BEGIN ENCRYPTED PRIVATE KEY"))return na(o,t,n);try{let a=fe.decode(o),c=a.subarray(0,16),l=a.subarray(16,28),h=a.subarray(28),f=await t.decrypt(c,l,h,n),d=F.decode(f);if(d.Type==null)throw new Ut("Unknown key type");return s=await this.components.getCrypto(d.Type,n),await s.privateKeyFromProtobuf(f)}catch(a){throw a.name==="OperationError"?new Ut(a.message):a}}async removeKey(e,t){if(!Vt(e)||e===this.self)throw new $(`Invalid key name '${e}'`);let n=this.components.datastore.batch();n.delete(dt(e)),n.delete(Rr(e)),await n.commit(t)}async*listKeys(e){let t={prefix:aa};for await(let n of this.components.datastore.query(t,e))yield JSON.parse(re(n.value))}async renameKey(e,t,n){if(!Vt(e)||e===this.self)throw new $(`Invalid old key name '${e}'`);if(!Vt(t)||t===this.self)throw new $(`Invalid new key name '${t}'`);let i=dt(e),o=dt(t),s=Rr(e),a=Rr(t);if(await this.components.datastore.has(o,n))throw new $(`Key '${t}' already exists`);let l=await this.components.datastore.get(i,n),h=await this.components.datastore.get(s,n),f=JSON.parse(re(h));f.name=t;let d=this.components.datastore.batch();d.put(o,l),d.put(a,I(JSON.stringify(f))),d.delete(i),d.delete(s),await d.commit(n)}async rotateKeychainPass(e,t){if(typeof e!="string")throw new $(`Invalid new pass type '${typeof e}'`);if(e.length<Gi)throw new $(`Invalid pass length ${e.length}, must be at least ${Gi}`);let n=this.cipher,i=this.cipher=oa(e,this.salt,this.keychainDekOptions,this.privateKeyDekOptions),o=this.components.datastore.batch();for await(let s of this.listKeys(t)){let a=await this._exportKey(s.name,n);await this._importKey(s.name,a,i,o,t)}await o.commit(t)}async loadPublicKeyFromProtobuf(e,t){let n=j.decode(e);if(n.Type==null)throw new $("Protobuf was missing Type");return(await this.components.getCrypto(n.Type,t)).publicKeyFromProtobuf(e,t)}},Uh={alg:"A128GCM",ext:!0,k:"scm9jmO_4BJAgdwWGVulLg",key_ops:["encrypt","decrypt"],kty:"oct"};function oa(r,e,t,n){let i;async function o(l,h,f,d){let y,w=I(l),k=await crypto.subtle.importKey("raw",w,{name:"PBKDF2"},!1,["deriveKey"]);try{y=await crypto.subtle.deriveKey({name:"PBKDF2",salt:L(h),iterations:d.iterations,hash:{name:d.hash}},k,{name:d.algorithm??"AES-GCM",length:d.keyLength},!0,f)}catch(E){if(l==="")y=await crypto.subtle.importKey("jwk",Uh,{name:d.algorithm??"AES-GCM"},!0,f);else throw E}return y}async function s(){if(r==="")return r;let l=await o(r,e,["encrypt","decrypt"],t);return(await crypto.subtle.exportKey("jwk",l)).k??""}async function a(l,h){i==null&&(i=await s());let f=crypto.getRandomValues(new Uint8Array(n.saltLength)),d=crypto.getRandomValues(new Uint8Array(n.ivLength)),y=await o(i,f,["encrypt"],n),w=await crypto.subtle.encrypt({name:"AES-GCM",iv:d},y,l);return h?.signal?.throwIfAborted(),{salt:f,iv:d,cipherText:new Uint8Array(w)}}async function c(l,h,f,d){i==null&&(i=await s());let y=await o(i,l,["decrypt"],{iterations:d?.iterations??n.iterations,keyLength:d?.keyLength??n.keyLength,hash:d?.hash??n.hash,algorithm:d?.algorithm??"AES-GCM"}),w=await crypto.subtle.decrypt({name:d?.algorithm??"AES-GCM",iv:L(h)},y,L(f));return d?.signal?.throwIfAborted(),new Uint8Array(w)}return{encrypt:a,decrypt:c}}function ca(r){return e=>new Br(e,r)}var ua=Symbol.for("@libp2p/content-routing");var ge=class extends Error{static name="AbortError";constructor(e="The operation was aborted"){super(e),this.name="AbortError"}};var pt=class extends Error{static name="InvalidParametersError";constructor(e="Invalid parameters"){super(e),this.name="InvalidParametersError"}};var Ur=class extends Error{static name="NotFoundError";constructor(e="Not found"){super(e),this.name="NotFoundError"}};var Or=class extends Error{static name="InvalidMultihashError";constructor(e="Invalid Multihash"){super(e),this.name="InvalidMultihashError"}};var la=Symbol.for("@libp2p/peer-routing");function ha(r){return r!=null&&typeof r.start=="function"&&typeof r.stop=="function"}async function Oe(...r){let e=[];for(let t of r)ha(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)ha(t)&&e.push(t);await Promise.all(e.map(async t=>{t.beforeStop!=null&&await t.beforeStop()})),await Promise.all(e.map(async t=>{await t.stop()})),await Promise.all(e.map(async t=>{t.afterStop!=null&&await t.afterStop()}))}function Oh(r){return typeof r?.handleEvent=="function"}function Mh(r){return(r!==!0&&r!==!1&&r?.once)??!1}var ie=class extends EventTarget{#e=new Map;constructor(){super()}listenerCount(e){let t=this.#e.get(e);return t==null?0:t.length}addEventListener(e,t,n){let i=Mh(n);super.addEventListener(e,s=>{if(i){let a=this.#e.get(s.type);a!=null&&(a=a.filter(({callback:c})=>c!==t),this.#e.set(s.type,a))}Oh(t)?t.handleEvent(s):t(s)},n);let o=this.#e.get(e);o==null&&(o=[],this.#e.set(e,o)),o.push({callback:t,once:i})}removeEventListener(e,t,n){super.removeEventListener(e.toString(),t??null,n);let i=this.#e.get(e);i!=null&&(i=i.filter(({callback:o})=>o!==t),this.#e.set(e,i))}safeDispatchEvent(e,t={}){return this.dispatchEvent(new CustomEvent(e,t))}};var x=class extends Event{type;detail;constructor(e,t){super(e),this.type=e,this.detail=t}};var Mr=class extends AggregateError{static name="DNSQueryFailedError";name="DNSQueryFailedError"};var Qi=ri(da(),1);var Yi=class r extends Error{name="TimeoutError";constructor(e,t){super(e,t),Error.captureStackTrace?.(this,r)}},pa=r=>r.reason??new DOMException("This operation was aborted.","AbortError");function Wt(r,e){let{milliseconds:t,fallback:n,message:i,customTimers:o={setTimeout,clearTimeout},signal:s}=e,a,c,h=new Promise((f,d)=>{if(typeof t!="number"||Math.sign(t)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${t}\``);if(s?.aborted){d(pa(s));return}if(s&&(c=()=>{d(pa(s))},s.addEventListener("abort",c,{once:!0})),r.then(f,d),t===Number.POSITIVE_INFINITY)return;let y=new Yi;a=o.setTimeout.call(void 0,()=>{if(n){try{f(n())}catch(w){d(w)}return}typeof r.cancel=="function"&&r.cancel(),i===!1?f():i instanceof Error?d(i):(y.message=i??`Promise timed out after ${t} milliseconds`,d(y))},t)}).finally(()=>{h.clear(),c&&s&&s.removeEventListener("abort",c)});return h.clear=()=>{o.clearTimeout.call(void 0,a),a=void 0},h}function Xi(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 zh=100,mt=class{#e=[];#t=0;enqueue(e,t){let{priority:n=0,id:i}=t??{},{size:o}=this,s={priority:n,id:i,run:e};if(o===0){this.#e.length=0,this.#t=0,this.#e.push(s);return}if(this.#e.at(-1).priority>=n){this.#e.push(s);return}this.#o();let a=Xi(this.#e,s,(c,l)=>l.priority-c.priority);this.#e.splice(a,0,s)}setPriority(e,t){let n=this.#e.findIndex((o,s)=>s>=this.#t&&o.id===e);if(n===-1)throw new ReferenceError(`No promise function with the id "${e}" exists in the queue.`);let[i]=this.#e.splice(n,1);this.enqueue(i.run,{priority:t,id:e})}remove(e){let t=this.#e.findIndex((n,i)=>i<this.#t?!1:typeof e=="string"?n.id===e:n.run===e);t!==-1&&this.#e.splice(t,1)}dequeue(){if(this.#t===this.#e.length)return;let e=this.#e[this.#t];return this.#t++,this.#t===this.#e.length?(this.#e.length=0,this.#t=0):this.#t>zh&&this.#t>this.#e.length/2&&this.#o(),e?.run}filter(e){let t=[];for(let n=this.#t;n<this.#e.length;n++){let i=this.#e[n];i.priority===e.priority&&t.push(i.run)}return t}get size(){return this.#e.length-this.#t}#o(){this.#t!==0&&(this.#e.splice(0,this.#t),this.#t=0)}};var Gt=class extends Qi.default{#e;#t;#o=0;#d;#m=!1;#b=!1;#c;#I=0;#x=0;#u;#l;#a;#s=[];#i=0;#r;#T;#n=0;#g;#h;#N=1n;#y=new Map;#E=new Set;timeout;constructor(e){if(super(),e={carryoverIntervalCount:!1,intervalCap:Number.POSITIVE_INFINITY,interval:0,concurrency:Number.POSITIVE_INFINITY,autoStart:!0,queueClass:mt,strict:!1,...e},!(typeof e.intervalCap=="number"&&e.intervalCap>=1))throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${e.intervalCap?.toString()??""}\` (${typeof e.intervalCap})`);if(e.interval===void 0||!(Number.isFinite(e.interval)&&e.interval>=0))throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${e.interval?.toString()??""}\` (${typeof e.interval})`);if(e.strict&&e.interval===0)throw new TypeError("The `strict` option requires a non-zero `interval`");if(e.strict&&e.intervalCap===Number.POSITIVE_INFINITY)throw new TypeError("The `strict` option requires a finite `intervalCap`");if(this.#e=e.carryoverIntervalCount??e.carryoverConcurrencyCount??!1,this.#t=e.intervalCap===Number.POSITIVE_INFINITY||e.interval===0,this.#d=e.intervalCap,this.#c=e.interval,this.#a=e.strict,this.#r=new e.queueClass,this.#T=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.#h=e.autoStart===!1,this.#z()}#v(e){for(;this.#i<this.#s.length;){let n=this.#s[this.#i];if(n!==void 0&&e-n>=this.#c)this.#i++;else break}(this.#i>100&&this.#i>this.#s.length/2||this.#i===this.#s.length)&&(this.#s=this.#s.slice(this.#i),this.#i=0)}#R(e){this.#a?this.#s.push(e):this.#o++}#B(){this.#a?this.#s.length>this.#i&&this.#s.pop():this.#o>0&&this.#o--}#_(){return this.#s.length-this.#i}get#U(){return this.#t?!0:this.#a?this.#_()<this.#d:this.#o<this.#d}get#O(){return this.#n<this.#g}#M(){this.#n--,this.#n===0&&this.emit("pendingZero"),this.#w(),this.emit("next")}#F(){this.#l=void 0,this.#D(),this.#C()}#$(e){if(this.#a){if(this.#v(e),this.#_()>=this.#d){let n=this.#s[this.#i],i=this.#c-(e-n);return this.#A(i),!0}return!1}if(this.#u===void 0){let t=this.#I-e;if(t<0){if(this.#x>0){let n=e-this.#x;if(n<this.#c)return this.#A(this.#c-n),!0}this.#o=this.#e?this.#n:0}else return this.#A(t),!0}return!1}#A(e){this.#l===void 0&&(this.#l=setTimeout(()=>{this.#F()},e))}#k(){this.#u&&(clearInterval(this.#u),this.#u=void 0)}#L(){this.#l&&(clearTimeout(this.#l),this.#l=void 0)}#w(){if(this.#r.size===0){if(this.#k(),this.emit("empty"),this.#n===0){if(this.#L(),this.#a&&this.#i>0){let t=Date.now();this.#v(t)}this.emit("idle")}return!1}let e=!1;if(!this.#h){let t=Date.now(),n=!this.#$(t);if(this.#U&&this.#O){let i=this.#r.dequeue();this.#t||(this.#R(t),this.#p()),this.emit("active"),i(),n&&this.#C(),e=!0}}return e}#C(){this.#t||this.#u!==void 0||this.#a||(this.#u=setInterval(()=>{this.#D()},this.#c),this.#I=Date.now()+this.#c)}#D(){this.#a||(this.#o===0&&this.#n===0&&this.#u&&this.#k(),this.#o=this.#e?this.#n:0),this.#S(),this.#p()}#S(){for(;this.#w(););}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.#S()}setPriority(e,t){if(typeof t!="number"||!Number.isFinite(t))throw new TypeError(`Expected \`priority\` to be a finite number, got \`${t}\` (${typeof t})`);this.#r.setPriority(e,t)}async add(e,t={}){return t={timeout:this.timeout,...t,id:t.id??(this.#N++).toString()},new Promise((n,i)=>{let o=Symbol(`task-${t.id}`),s=()=>{},a=async()=>{s(),this.#n++,this.#y.set(o,{id:t.id,priority:t.priority??0,startTime:Date.now(),timeout:t.timeout});let l;try{try{t.signal?.throwIfAborted()}catch(d){throw this.#K(),this.#y.delete(o),d}this.#x=Date.now();let h=e({signal:t.signal});if(t.timeout&&(h=Wt(Promise.resolve(h),{milliseconds:t.timeout,message:`Task timed out after ${t.timeout}ms (queue has ${this.#n} running, ${this.#r.size} waiting)`})),t.signal){let{signal:d}=t;h=Promise.race([h,new Promise((y,w)=>{l=()=>{w(d.reason)},d.addEventListener("abort",l,{once:!0})})])}let f=await h;n(f),this.emit("completed",f)}catch(h){i(h),this.emit("error",h)}finally{l&&t.signal?.removeEventListener("abort",l),this.#y.delete(o),queueMicrotask(()=>{this.#M()})}};this.#r.enqueue(a,t);let c=()=>{if(this.#r instanceof mt){this.#r.remove(a);return}this.#r.remove?.(t.id)};if(t.signal){let{signal:l}=t,h=()=>{s(),c(),i(l.reason),this.#w(),this.emit("next")};if(s=()=>{l.removeEventListener("abort",h),this.#E.delete(s)},l.aborted){h();return}l.addEventListener("abort",h,{once:!0}),this.#E.add(s)}this.emit("add"),this.#w()})}async addAll(e,t){return Promise.all(e.map(async n=>this.add(n,t)))}start(){return this.#h?(this.#h=!1,this.#S(),this):this}pause(){this.#h=!0}clear(){for(let e of this.#E)e();this.#r=new this.#T,this.#k(),this.#P(),this.emit("empty"),this.#n===0&&(this.#L(),this.emit("idle")),this.emit("next")}async onEmpty(){this.#r.size!==0&&await this.#f("empty")}async onSizeLessThan(e){this.#r.size<e||await this.#f("next",()=>this.#r.size<e)}async onIdle(){this.#n===0&&this.#r.size===0||await this.#f("idle")}async onPendingZero(){this.#n!==0&&await this.#f("pendingZero")}async onRateLimit(){this.isRateLimited||await this.#f("rateLimit")}async onRateLimitCleared(){this.isRateLimited&&await this.#f("rateLimitCleared")}onError(){return new Promise((e,t)=>{let n=i=>{this.off("error",n),t(i)};this.on("error",n)})}async#f(e,t){return new Promise(n=>{let i=()=>{t&&!t()||(this.off(e,i),n())};this.on(e,i)})}get size(){return this.#r.size}sizeBy(e){return this.#r.filter(e).length}get pending(){return this.#n}get isPaused(){return this.#h}#z(){this.#t||(this.on("add",()=>{this.#r.size>0&&this.#p()}),this.on("next",()=>{this.#p()}))}#p(){this.#t||this.#b||(this.#b=!0,queueMicrotask(()=>{this.#b=!1,this.#P()}))}#K(){this.#t||(this.#B(),this.#p())}#P(){let e=this.#m;if(this.#t||this.#r.size===0){e&&(this.#m=!1,this.emit("rateLimitCleared"));return}let t;if(this.#a){let i=Date.now();this.#v(i),t=this.#_()}else t=this.#o;let n=t>=this.#d;n!==e&&(this.#m=n,this.emit(n?"rateLimit":"rateLimitCleared"))}get isRateLimited(){return this.#m}get isSaturated(){return this.#n===this.#g&&this.#r.size>0||this.isRateLimited&&this.#r.size>0}get runningTasks(){return[...this.#y.values()].map(e=>({...e,timeoutRemaining:e.timeout?Math.max(0,e.startTime+e.timeout-Date.now()):void 0}))}};function $r(r){let e=[ye.A];return r==null?e:Array.isArray(r)?r.length===0?e:r:[r]}var Zi=60;function zr(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:ye[e.type]})),Answer:(r.Answer??r.answers??[]).map(e=>({name:e.name,type:ye[e.type],TTL:e.TTL??e.ttl??Zi,data:e.data instanceof Uint8Array?re(e.data):e.data}))}}var Kh=4;function eo(r,e={}){let t=new Gt({concurrency:e.queryConcurrency??Kh});return async(n,i={})=>{let o=i?.logger?.forComponent("dns:dns-json-over-https"),s=new URLSearchParams;s.set("name",n),$r(i.types).forEach(c=>{s.append("type",ye[c])}),i.onProgress?.(new x("dns:query",n)),o?.("GET %s",`${r}?${s}`);let a=await t.add(async()=>{let c=await fetch(`${r}?${s}`,{headers:{accept:"application/dns-json"},signal:i?.signal});if(o?.("GET %s %d",c.url,c.status),c.status!==200)throw new Error(`Unexpected HTTP status: ${c.status} - ${c.statusText}`);let l=zr(await c.json());return i.onProgress?.(new x("dns:response",l)),l},{signal:i.signal});if(a==null)throw new Error("No DNS response received");return a}}function ma(){return[eo("https://cloudflare-dns.com/dns-query"),eo("https://dns.google/resolve")]}var wa=ri(ya(),1);var to=class{lru;constructor(e){this.lru=(0,wa.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 zr({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:ye[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??Zi)*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 ba(r){return new to(r)}var qh=1e3,Kr=class{resolvers;cache;logger;constructor(e){this.resolvers={},this.cache=ba(e.cacheSize??qh),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["."]=ma())}async query(e,t={}){let n=$r(t.types),i=t.cached!==!1?this.cache.get(e,n):void 0;if(i!=null)return t.onProgress?.(new x("dns:cache",i)),i;let o=`${e.split(".").pop()}.`,s=(this.resolvers[o]??this.resolvers["."]).sort(()=>Math.random()>.5?-1:1),a=[];for(let c of s){if(t.signal?.aborted===!0)break;try{let l=await c(e,{...t,logger:this.logger,types:n});for(let h of l.Answer)this.cache.add(e,h);return l}catch(l){a.push(l),t.onProgress?.(new x("dns:error",l))}}throw new Mr(a,`DNS lookup of ${e} ${n} failed`)}};var ye;(function(r){r[r.A=1]="A",r[r.CNAME=5]="CNAME",r[r.TXT=16]="TXT",r[r.AAAA=28]="AAAA"})(ye||(ye={}));function xa(r={}){return new Kr(r)}function jh(r){return r[Symbol.asyncIterator]!=null}function Vh(r){if(jh(r))return(async()=>{for await(let e of r);})();for(let e of r);}var Ea=Vh;var ro={32:16777619n,64:1099511628211n,128:309485009821345068724781371n,256:374144419156711147060143317175368453031918731002211n,512:35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759n,1024:5016456510113118655434598811035278955030765345404790744303017523831112055108147451509157692220295382716162651878526895249385292291816524375083746691371804094271873160484737966720260389217684476157468082573n},va={32:2166136261n,64:14695981039346656037n,128:144066263297769815596495629667062367629n,256:100029257958052580907070968620625704837092796014241193945225284501741471925557n,512:9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785n,1024:14197795064947621068722070641403218320880622795441933960878474914617582723252296732303717722150864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915n},_a=new globalThis.TextEncoder;function Hh(r,e){let t=ro[e],n=va[e];for(let i=0;i<r.length;i++)n^=BigInt(r[i]),n=BigInt.asUintN(e,n*t);return n}function Wh(r,e,t){if(t.length===0)throw new Error("The `utf8Buffer` option must have a length greater than zero");let n=ro[e],i=va[e],o=r;for(;o.length>0;){let s=_a.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 no(r,{size:e=32,utf8Buffer:t}={}){if(!ro[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 Wh(r,e,t);r=_a.encode(r)}return Hh(r,e)}var Jt={hash:r=>Number(no(r,{size:32})),hashV:(r,e)=>Gh(Jt.hash(r,e))};function Gh(r){let e=r.toString(16);return e.length%2===1&&(e=`0${e}`),I(e,"base16")}var io=64,we=class{fp;h;seed;constructor(e,t,n,i=2){if(i>io)throw new TypeError("Invalid Fingerprint Size");let o=t.hashV(e,n),s=ce(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?Le(this.fp,e.fp):!1}};function We(r,e){return Math.floor(Math.random()*(e-r))+r}var Ge=class{contents;constructor(e){this.contents=new Array(e).fill(null)}has(e){if(!(e instanceof we))throw new TypeError("Invalid Fingerprint");return this.contents.some(t=>e.equals(t))}add(e){if(!(e instanceof we))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 we))throw new TypeError("Invalid Fingerprint");let t=We(0,this.contents.length-1),n=this.contents[t];return this.contents[t]=e,n}remove(e){if(!(e instanceof we))throw new TypeError("Invalid Fingerprint");let t=this.contents.findIndex(n=>e.equals(n));return t>-1?(this.contents[t]=null,!0):!1}};var Jh=500,Qt=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??Jt,this.seed=e.seed??We(0,Math.pow(2,10))}add(e){typeof e=="string"&&(e=I(e));let t=new we(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 Ge(this.bucketSize)),this.buckets[i]==null&&(this.buckets[i]=new Ge(this.bucketSize)),this.buckets[n].add(t)||this.buckets[i].add(t))return this.count++,!0;let o=[n,i],s=o[We(0,o.length-1)];this.buckets[s]==null&&(this.buckets[s]=new Ge(this.bucketSize));for(let a=0;a<Jh;a++){let c=this.buckets[s].swap(t);if(c!=null&&(s=(s^c.hash())%this.filterSize,this.buckets[s]==null&&(this.buckets[s]=new Ge(this.bucketSize)),this.buckets[s].add(c)))return this.count++,!0}return!1}has(e){typeof e=="string"&&(e=I(e));let t=new we(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=I(e));let t=new we(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}},Qh={1:.5,2:.84,4:.95,8:.98};function Yh(r=.001){return r>.002?2:r>1e-5?4:8}function Aa(r,e=.001){let t=Yh(e),n=Qh[t],i=Math.round(r/n),o=Math.min(Math.ceil(Math.log2(1/e)+Math.log2(2*t)),io);return{filterSize:i,bucketSize:t,fingerprintSize:o}}var qr=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??Jt,this.seed=e.seed??We(0,Math.pow(2,10)),this.filterSeries=[new Qt({filterSize:this.filterSize,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed})]}add(e){if(typeof e=="string"&&(e=I(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 Qt({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=I(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=I(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 jr(r,e=.001,t){return new qr({...Aa(r,e),...t??{}})}function V(){let r={};return r.promise=new Promise((e,t)=>{r.resolve=e,r.reject=t}),r}var Vr=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}},gt=class{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new Vr(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 Vr(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 oo=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}};function Hr(r={}){return Xh(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 Xh(r,e){e=e??{};let t=e.onEnd,n=new gt,i,o,s,a=V(),c=async()=>{try{return n.isEmpty()?s?{done:!0}:await new Promise((E,C)=>{o=O=>{o=null,n.push(O);try{E(r(n))}catch(N){C(N)}return i}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=V()})}},l=E=>o!=null?o(E):(n.push(E),i),h=E=>(n=new gt,o!=null?o({error:E}):(n.push({error:E}),i)),f=E=>{if(s)return i;if(e?.objectMode!==!0&&E?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return l({done:!1,value:E})},d=E=>s?i:(s=!0,E!=null?h(E):l({done:!0})),y=()=>(n=new gt,d(),{done:!0}),w=E=>(d(E),{done:!0});if(i={[Symbol.asyncIterator](){return this},next:c,return:y,throw:w,push:f,end:d,get readableLength(){return n.size},onEmpty:async E=>{let C=E?.signal;if(C?.throwIfAborted(),n.isEmpty())return;let O,N;C!=null&&(O=new Promise((H,te)=>{N=()=>{te(new oo)},C.addEventListener("abort",N)}));try{await Promise.race([a.promise,O])}finally{N!=null&&C!=null&&C?.removeEventListener("abort",N)}}},t==null)return i;let k=i;return i={[Symbol.asyncIterator](){return this},next(){return k.next()},throw(E){return k.throw(E),t!=null&&(t(E),t=void 0),{done:!0}},return(){return k.return(),t!=null&&(t(),t=void 0),{done:!0}},push:f,end(E){return k.end(E),t!=null&&(t(E),t=void 0),i},get readableLength(){return k.readableLength},onEmpty:E=>k.onEmpty(E)},i}var Zh=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 ef(r,e,t){let n,i=new Promise((o,s)=>{if(t={rejectionEvents:["error"],multiArgs:!1,rejectionMultiArgs:!1,resolveImmediately:!1,...t},!(t.count>=0&&(t.count===Number.POSITIVE_INFINITY||Number.isInteger(t.count))))throw new TypeError("The `count` option should be at least 0 or more");t.signal?.throwIfAborted();let a=[e].flat(),c=[],{addListener:l,removeListener:h}=Zh(r),f=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}c.push(w),t.count===c.length&&(n(),o(c))},d=(...y)=>{n(),s(t.rejectionMultiArgs?y:y[0])};n=()=>{for(let y of a)h(y,f);for(let y of t.rejectionEvents)a.includes(y)||h(y,d)};for(let y of a)l(y,f);for(let y of t.rejectionEvents)a.includes(y)||l(y,d);t.signal&&t.signal.addEventListener("abort",()=>{d(t.signal.reason)},{once:!0}),t.resolveImmediately&&o(c)});if(i.cancel=n,typeof t.timeout=="number"){let o=Wt(i,{milliseconds:t.timeout});return o.cancel=()=>{n(),o.clear()},o}return i}function Wr(r,e,t){typeof t=="function"&&(t={filter:t}),t={...t,count:1,resolveImmediately:!1};let n=ef(r,e,t),i=n.then(o=>o[0]);return i.cancel=n.cancel,i}function so(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 Gr=class extends Error{static name="QueueFullError";constructor(e="The queue was full"){super(e),this.name="QueueFullError"}};function tf(r){return r.reason}async function Fe(r,e,t){if(e==null)return r;let n=t?.translateError??tf;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 Jr=class{deferred;signal;onProgress;constructor(e){this.signal=e?.signal,this.onProgress=e?.onProgress,this.deferred=V(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new ge)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function rf(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var Qr=class{id;fn;options;recipients;status;timeline;controller;dispatchingProgress;constructor(e,t){this.id=rf(),this.status="queued",this.fn=e,this.options=t,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,this.controller.signal,this.dispatchingProgress=!1,this.onAbort=this.onAbort.bind(this)}abort(e){this.controller.abort(e)}onAbort(){this.recipients.reduce((t,n)=>t&&n.signal?.aborted===!0,!0)&&(this.controller.abort(new ge),this.cleanup())}async join(e){let t=new Jr(e);return this.recipients.push(t),e?.signal?.addEventListener("abort",this.onAbort),t.deferred.promise}async run(){this.status="running",this.timeline.started=Date.now();try{this.controller.signal.throwIfAborted();let e=await Fe(this.fn({...this.options??{},signal:this.controller.signal,onProgress:t=>{if(!this.dispatchingProgress){this.dispatchingProgress=!0;try{this.recipients.forEach(n=>{n.onProgress?.(t)})}finally{this.dispatchingProgress=!1}}}}),this.controller.signal);this.recipients.forEach(t=>{t.deferred.resolve(e)}),this.status="complete"}catch(e){this.recipients.forEach(t=>{t.deferred.reject(e)}),this.status="errored"}finally{this.timeline.finished=Date.now(),this.cleanup()}}cleanup(){this.recipients.forEach(e=>{e.cleanup(),e.signal?.removeEventListener("abort",this.onAbort)})}};var J=class extends ie{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=so(this.emitEmpty.bind(this),1),this.emitIdle=so(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 Gr;let n=new Qr(e,t);this.enqueue(n),this.safeDispatchEvent("add");let i=n.join(t).then(o=>(this.safeDispatchEvent("completed",{detail:o}),this.safeDispatchEvent("success",{detail:{job:n,result:o}}),o)).catch(o=>{if(n.status==="queued"){for(let s=0;s<this.queue.length;s++)if(this.queue[s]===n){this.queue.splice(s,1);break}}throw this.safeDispatchEvent("failure",{detail:{job:n,error:o}}),o});return this.tryToStartAnother(),i}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(e=>{e.abort(new ge)}),this.clear()}async onEmpty(e){this.size!==0&&await Wr(this,"empty",e)}async onSizeLessThan(e,t){this.size<e||await Wr(this,"next",{...t,filter:()=>this.size<e})}async onIdle(e){this.pending===0&&this.size===0||await Wr(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=Hr({objectMode:!0}),n=c=>{c!=null?this.abort():this.clear(),t.end(c)},i=c=>{c.detail!=null&&t.push(c.detail)},o=c=>{n(c.detail.error)},s=()=>{n()},a=()=>{n(new ge("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 be(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 ao=class{readNext;haveNext;ended;nextResult;error;constructor(){this.ended=!1,this.readNext=V(),this.haveNext=V()}[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=V(),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=V(),await Fe(this.readNext.promise,t?.signal,t)}};function ka(){return new ao}function nf(r){return r[Symbol.asyncIterator]!=null}async function of(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*sf(r){let e=new AbortController,t=ka();of(r,t,e.signal).catch(()=>{});try{yield*t}finally{e.abort()}}function*af(r){for(let e of r)yield*e}function cf(...r){let e=[];for(let t of r)nf(t)||e.push(t);return e.length===r.length?af(e):sf(r)}var Yr=cf;var uf=["Object","RegExp","Date","Error","Map","Set","WeakMap","WeakSet","ArrayBuffer","SharedArrayBuffer","DataView","Promise","URL","HTMLElement","Int8Array","Uint8ClampedArray","Int16Array","Uint16Array","Int32Array","Uint32Array","Float32Array","Float64Array","BigInt64Array","BigUint64Array","Tagged"];function co(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=lf(r);return t||"Object"}function lf(r){let e=Object.prototype.toString.call(r).slice(8,-1);if(uf.includes(e))return e}var u=class{constructor(e,t,n){this.major=e,this.majorEncoded=e<<5,this.name=t,this.terminal=n}toString(){return`Type[${this.major}].${this.name}`}compare(e){return this.major<e.major?-1:this.major>e.major?1:0}static equals(e,t){return e===t||e.major===t.major&&e.name===t.name}};u.uint=new u(0,"uint",!0);u.negint=new u(1,"negint",!0);u.bytes=new u(2,"bytes",!0);u.string=new u(3,"string",!0);u.array=new u(4,"array",!1);u.map=new u(5,"map",!1);u.tag=new u(6,"tag",!1);u.float=new u(7,"float",!0);u.false=new u(7,"false",!0);u.true=new u(7,"true",!0);u.null=new u(7,"null",!0);u.undefined=new u(7,"undefined",!0);u.break=new u(7,"break",!0);var p=class{constructor(e,t,n){this.type=e,this.value=t,this.encodedLength=n,this.encodedBytes=void 0,this.byteValue=void 0}toString(){return`Token[${this.type}].${this.value}`}};var Yt=globalThis.process&&!globalThis.process.browser&&globalThis.Buffer&&typeof globalThis.Buffer.isBuffer=="function",hf=new TextEncoder;function Xr(r){return Yt&&globalThis.Buffer.isBuffer(r)}function Je(r){return r instanceof Uint8Array?Xr(r)?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):r:Uint8Array.from(r)}var ff=24,df=200,yt=Yt?r=>r.length>=ff?globalThis.Buffer.from(r):Sa(r):r=>r.length>=df?hf.encode(r):Sa(r),Ae=r=>Uint8Array.from(r),Ta=Yt?(r,e,t)=>Xr(r)?new Uint8Array(r.subarray(e,t)):r.slice(e,t):(r,e,t)=>r.slice(e,t),La=Yt?(r,e)=>(r=r.map(t=>t instanceof Uint8Array?t:globalThis.Buffer.from(t)),Je(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},Ca=Yt?r=>globalThis.Buffer.allocUnsafe(r):r=>new Uint8Array(r);function Zr(r,e){if(Xr(r)&&Xr(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 Sa(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 Ia=4096;function Da(r){let e=r.length;if(e<=Ia)return String.fromCharCode.apply(String,r);let t="",n=0;for(;n<e;)t+=String.fromCharCode.apply(String,r.slice(n,n+=Ia));return t}var pf=256,Xt=class{constructor(e=pf){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=Ca(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=Ta(n,0,this.cursor)}else t=La(this.chunks,this.cursor);return e&&this.reset(),t}},en=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:",ke="CBOR encode error:",Zt=[];Zt[23]=1;Zt[24]=2;Zt[25]=3;Zt[26]=5;Zt[27]=9;function Ce(r,e,t){if(r.length-e<t)throw new Error(`${g} not enough data for type`)}var P=[24,256,65536,4294967296,BigInt("18446744073709551616")];function Q(r,e,t){Ce(r,e,1);let n=r[e];if(t.strict===!0&&n<P[0])throw new Error(`${g} integer encoded in more bytes than necessary (strict decode)`);return n}function Y(r,e,t){Ce(r,e,2);let n=r[e]<<8|r[e+1];if(t.strict===!0&&n<P[1])throw new Error(`${g} integer encoded in more bytes than necessary (strict decode)`);return n}function X(r,e,t){Ce(r,e,4);let n=r[e]*16777216+(r[e+1]<<16)+(r[e+2]<<8)+r[e+3];if(t.strict===!0&&n<P[2])throw new Error(`${g} integer encoded in more bytes than necessary (strict decode)`);return n}function Z(r,e,t){Ce(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<P[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 Pa(r,e,t,n){return new p(u.uint,Q(r,e+1,n),2)}function Na(r,e,t,n){return new p(u.uint,Y(r,e+1,n),3)}function Ra(r,e,t,n){return new p(u.uint,X(r,e+1,n),5)}function Ba(r,e,t,n){return new p(u.uint,Z(r,e+1,n),9)}function oe(r,e){return S(r,0,e.value)}function S(r,e,t){if(t<P[0]){let n=Number(t);r.push([e|n])}else if(t<P[1]){let n=Number(t);r.push([e|24,n])}else if(t<P[2]){let n=Number(t);r.push([e|25,n>>>8,n&255])}else if(t<P[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<P[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`)}}oe.encodedSize=function(e){return S.encodedSize(e.value)};S.encodedSize=function(e){return e<P[0]?1:e<P[1]?2:e<P[2]?3:e<P[3]?5:9};oe.compareTokens=function(e,t){return e.value<t.value?-1:e.value>t.value?1:0};function Ua(r,e,t,n){return new p(u.negint,-1-Q(r,e+1,n),2)}function Oa(r,e,t,n){return new p(u.negint,-1-Y(r,e+1,n),3)}function Ma(r,e,t,n){return new p(u.negint,-1-X(r,e+1,n),5)}var uo=BigInt(-1),Fa=BigInt(1);function $a(r,e,t,n){let i=Z(r,e+1,n);if(typeof i!="bigint"){let o=-1-i;if(o>=Number.MIN_SAFE_INTEGER)return new p(u.negint,o,9)}if(n.allowBigInt!==!0)throw new Error(`${g} integers outside of the safe integer range are not supported`);return new p(u.negint,uo-BigInt(i),9)}function tn(r,e){let t=e.value,n=typeof t=="bigint"?t*uo-Fa:t*-1-1;S(r,e.type.majorEncoded,n)}tn.encodedSize=function(e){let t=e.value,n=typeof t=="bigint"?t*uo-Fa:t*-1-1;return n<P[0]?1:n<P[1]?2:n<P[2]?3:n<P[3]?5:9};tn.compareTokens=function(e,t){return e.value<t.value?1:e.value>t.value?-1:0};function er(r,e,t,n){Ce(r,e,t+n);let i=r.slice(e+t,e+t+n);return new p(u.bytes,i,t+n)}function za(r,e,t,n){return er(r,e,1,t)}function Ka(r,e,t,n){return er(r,e,2,Q(r,e+1,n))}function qa(r,e,t,n){return er(r,e,3,Y(r,e+1,n))}function ja(r,e,t,n){return er(r,e,5,X(r,e+1,n))}function Va(r,e,t,n){let i=Z(r,e+1,n);if(typeof i=="bigint")throw new Error(`${g} 64-bit integer bytes lengths not supported`);return er(r,e,9,i)}function rn(r){return r.encodedBytes===void 0&&(r.encodedBytes=u.equals(r.type,u.string)?yt(r.value):r.value),r.encodedBytes}function wt(r,e){let t=rn(e);S(r,e.type.majorEncoded,t.length),r.push(t)}wt.encodedSize=function(e){let t=rn(e);return S.encodedSize(t.length)+t.length};wt.compareTokens=function(e,t){return gf(rn(e),rn(t))};function gf(r,e){return r.length<e.length?-1:r.length>e.length?1:Zr(r,e)}var Ha=new TextDecoder,wf=32;function bf(r,e,t){if(t-e<wf){let i="";for(let o=e;o<t;o++){let s=r[o];if(s&128)return Ha.decode(r.subarray(e,t));i+=String.fromCharCode(s)}return i}return Ha.decode(r.subarray(e,t))}function tr(r,e,t,n,i){let o=t+n;Ce(r,e,o);let s=new p(u.string,bf(r,e+t,e+o),o);return i.retainStringBytes===!0&&(s.byteValue=r.slice(e+t,e+o)),s}function Wa(r,e,t,n){return tr(r,e,1,t,n)}function Ga(r,e,t,n){return tr(r,e,2,Q(r,e+1,n),n)}function Ja(r,e,t,n){return tr(r,e,3,Y(r,e+1,n),n)}function Qa(r,e,t,n){return tr(r,e,5,X(r,e+1,n),n)}function Ya(r,e,t,n){let i=Z(r,e+1,n);if(typeof i=="bigint")throw new Error(`${g} 64-bit integer string lengths not supported`);return tr(r,e,9,i,n)}var Xa=wt;function bt(r,e,t,n){return new p(u.array,n,t)}function Za(r,e,t,n){return bt(r,e,1,t)}function ec(r,e,t,n){return bt(r,e,2,Q(r,e+1,n))}function tc(r,e,t,n){return bt(r,e,3,Y(r,e+1,n))}function rc(r,e,t,n){return bt(r,e,5,X(r,e+1,n))}function nc(r,e,t,n){let i=Z(r,e+1,n);if(typeof i=="bigint")throw new Error(`${g} 64-bit integer array lengths not supported`);return bt(r,e,9,i)}function ic(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${g} indefinite length items not allowed`);return bt(r,e,1,1/0)}function nn(r,e){S(r,u.array.majorEncoded,e.value)}nn.compareTokens=oe.compareTokens;nn.encodedSize=function(e){return S.encodedSize(e.value)};function xt(r,e,t,n){return new p(u.map,n,t)}function oc(r,e,t,n){return xt(r,e,1,t)}function sc(r,e,t,n){return xt(r,e,2,Q(r,e+1,n))}function ac(r,e,t,n){return xt(r,e,3,Y(r,e+1,n))}function cc(r,e,t,n){return xt(r,e,5,X(r,e+1,n))}function uc(r,e,t,n){let i=Z(r,e+1,n);if(typeof i=="bigint")throw new Error(`${g} 64-bit integer map lengths not supported`);return xt(r,e,9,i)}function lc(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${g} indefinite length items not allowed`);return xt(r,e,1,1/0)}function on(r,e){S(r,u.map.majorEncoded,e.value)}on.compareTokens=oe.compareTokens;on.encodedSize=function(e){return S.encodedSize(e.value)};function hc(r,e,t,n){return new p(u.tag,t,1)}function fc(r,e,t,n){return new p(u.tag,Q(r,e+1,n),2)}function dc(r,e,t,n){return new p(u.tag,Y(r,e+1,n),3)}function pc(r,e,t,n){return new p(u.tag,X(r,e+1,n),5)}function mc(r,e,t,n){return new p(u.tag,Z(r,e+1,n),9)}function sn(r,e){S(r,u.tag.majorEncoded,e.value)}sn.compareTokens=oe.compareTokens;sn.encodedSize=function(e){return S.encodedSize(e.value)};var lo=20,ho=21,fo=22,po=23;function gc(r,e,t,n){if(n.allowUndefined===!1)throw new Error(`${g} undefined values are not supported`);return n.coerceUndefinedToNull===!0?new p(u.null,null,1):new p(u.undefined,void 0,1)}function yc(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${g} indefinite length items not allowed`);return new p(u.break,void 0,1)}function mo(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 p(u.float,r,e)}function wc(r,e,t,n){return mo(go(r,e+1),3,n)}function bc(r,e,t,n){return mo(yo(r,e+1),5,n)}function xc(r,e,t,n){return mo(Ac(r,e+1),9,n)}function rr(r,e,t){let n=e.value;if(n===!1)r.push([u.float.majorEncoded|lo]);else if(n===!0)r.push([u.float.majorEncoded|ho]);else if(n===null)r.push([u.float.majorEncoded|fo]);else if(n===void 0)r.push([u.float.majorEncoded|po]);else{let i,o=!1;(!t||t.float64!==!0)&&(vc(n),i=go(xe,1),n===i||Number.isNaN(n)?(xe[0]=249,r.push(xe.slice(0,3)),o=!0):(_c(n),i=yo(xe,1),n===i&&(xe[0]=250,r.push(xe.slice(0,5)),o=!0))),o||(Af(n),i=Ac(xe,1),xe[0]=251,r.push(xe.slice(0,9)))}}rr.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){vc(n);let i=go(xe,1);if(n===i||Number.isNaN(n))return 3;if(_c(n),i=yo(xe,1),n===i)return 5}return 9};var Ec=new ArrayBuffer(9),se=new DataView(Ec,1),xe=new Uint8Array(Ec,0);function vc(r){if(r===1/0)se.setUint16(0,31744,!1);else if(r===-1/0)se.setUint16(0,64512,!1);else if(Number.isNaN(r))se.setUint16(0,32256,!1);else{se.setFloat32(0,r);let e=se.getUint32(0),t=(e&2139095040)>>23,n=e&8388607;if(t===255)se.setUint16(0,31744,!1);else if(t===0)se.setUint16(0,(e&2147483648)>>16|n>>13,!1);else{let i=t-127;i<-24?se.setUint16(0,0):i<-14?se.setUint16(0,(e&2147483648)>>16|1<<24+i,!1):se.setUint16(0,(e&2147483648)>>16|i+15<<10|n>>13,!1)}}}function go(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 _c(r){se.setFloat32(0,r,!1)}function yo(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 Af(r){se.setFloat64(0,r,!1)}function Ac(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)}rr.compareTokens=oe.compareTokens;function _(r,e,t){throw new Error(`${g} encountered invalid minor (${t}) for major ${r[e]>>>5}`)}function an(r){return()=>{throw new Error(`${g} ${r}`)}}var m=[];for(let r=0;r<=23;r++)m[r]=_;m[24]=Pa;m[25]=Na;m[26]=Ra;m[27]=Ba;m[28]=_;m[29]=_;m[30]=_;m[31]=_;for(let r=32;r<=55;r++)m[r]=_;m[56]=Ua;m[57]=Oa;m[58]=Ma;m[59]=$a;m[60]=_;m[61]=_;m[62]=_;m[63]=_;for(let r=64;r<=87;r++)m[r]=za;m[88]=Ka;m[89]=qa;m[90]=ja;m[91]=Va;m[92]=_;m[93]=_;m[94]=_;m[95]=an("indefinite length bytes/strings are not supported");for(let r=96;r<=119;r++)m[r]=Wa;m[120]=Ga;m[121]=Ja;m[122]=Qa;m[123]=Ya;m[124]=_;m[125]=_;m[126]=_;m[127]=an("indefinite length bytes/strings are not supported");for(let r=128;r<=151;r++)m[r]=Za;m[152]=ec;m[153]=tc;m[154]=rc;m[155]=nc;m[156]=_;m[157]=_;m[158]=_;m[159]=ic;for(let r=160;r<=183;r++)m[r]=oc;m[184]=sc;m[185]=ac;m[186]=cc;m[187]=uc;m[188]=_;m[189]=_;m[190]=_;m[191]=lc;for(let r=192;r<=215;r++)m[r]=hc;m[216]=fc;m[217]=dc;m[218]=pc;m[219]=mc;m[220]=_;m[221]=_;m[222]=_;m[223]=_;for(let r=224;r<=243;r++)m[r]=an("simple values are not supported");m[244]=_;m[245]=_;m[246]=_;m[247]=gc;m[248]=an("simple values are not supported");m[249]=wc;m[250]=bc;m[251]=xc;m[252]=_;m[253]=_;m[254]=_;m[255]=yc;var Ee=[];for(let r=0;r<24;r++)Ee[r]=new p(u.uint,r,1);for(let r=-1;r>=-24;r--)Ee[31-r]=new p(u.negint,r,1);Ee[64]=new p(u.bytes,new Uint8Array(0),1);Ee[96]=new p(u.string,"",1);Ee[128]=new p(u.array,0,1);Ee[160]=new p(u.map,0,1);Ee[244]=new p(u.false,!1,1);Ee[245]=new p(u.true,!0,1);Ee[246]=new p(u.null,null,1);function wo(r){switch(r.type){case u.false:return Ae([244]);case u.true:return Ae([245]);case u.null:return Ae([246]);case u.bytes:return r.value.length?void 0:Ae([64]);case u.string:return r.value===""?Ae([96]):void 0;case u.array:return r.value===0?Ae([128]):void 0;case u.map:return r.value===0?Ae([160]):void 0;case u.uint:return r.value<24?Ae([Number(r.value)]):void 0;case u.negint:if(r.value>=-24)return Ae([31-Number(r.value)])}}var Sf={float64:!1,mapSorter:Lf,quickEncodeToken:wo},Lc=Object.freeze({float64:!0,mapSorter:Cf,quickEncodeToken:wo});function If(){let r=[];return r[u.uint.major]=oe,r[u.negint.major]=tn,r[u.bytes.major]=wt,r[u.string.major]=Xa,r[u.array.major]=nn,r[u.map.major]=on,r[u.tag.major]=sn,r[u.float.major]=rr,r}var vt=If(),cn=new Xt,ir=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(`${ke} object contains circular references`);return new r(t,e)}},$e={null:new p(u.null,null),undefined:new p(u.undefined,void 0),true:new p(u.true,!0),false:new p(u.false,!1),emptyArray:new p(u.array,0),emptyMap:new p(u.map,0)},Se={number(r,e,t,n){return!Number.isInteger(r)||!Number.isSafeInteger(r)?new p(u.float,r):r>=0?new p(u.uint,r):new p(u.negint,r)},bigint(r,e,t,n){return r>=BigInt(0)?new p(u.uint,r):new p(u.negint,r)},Uint8Array(r,e,t,n){return new p(u.bytes,r)},string(r,e,t,n){return new p(u.string,r)},boolean(r,e,t,n){return r?$e.true:$e.false},null(r,e,t,n){return $e.null},undefined(r,e,t,n){return $e.undefined},ArrayBuffer(r,e,t,n){return new p(u.bytes,new Uint8Array(r))},DataView(r,e,t,n){return new p(u.bytes,new Uint8Array(r.buffer,r.byteOffset,r.byteLength))},Array(r,e,t,n){if(!r.length)return t.addBreakTokens===!0?[$e.emptyArray,new p(u.break)]:$e.emptyArray;n=ir.createCheck(n,r);let i=[],o=0;for(let s of r)i[o++]=Et(s,t,n);return t.addBreakTokens?[new p(u.array,r.length),i,new p(u.break)]:[new p(u.array,r.length),i]},Object(r,e,t,n){let i=e!=="Object",o=i?r.keys():Object.keys(r),s=i?r.size:o.length,a;if(s){a=new Array(s),n=ir.createCheck(n,r);let c=!i&&t.ignoreUndefinedProperties,l=0;for(let h of o){let f=i?r.get(h):r[h];c&&f===void 0||(a[l++]=[Et(h,t,n),Et(f,t,n)])}l<s&&(a.length=l)}return a?.length?(Tf(a,t),t.addBreakTokens?[new p(u.map,a.length),a,new p(u.break)]:[new p(u.map,a.length),a]):t.addBreakTokens===!0?[$e.emptyMap,new p(u.break)]:$e.emptyMap},Tagged(r,e,t,n){return[new p(u.tag,r.tag),Et(r.value,t,n)]}};Se.Map=Se.Object;Se.Buffer=Se.Uint8Array;for(let r of"Uint8Clamped Uint16 Uint32 Int8 Int16 Int32 BigUint64 BigInt64 Float32 Float64".split(" "))Se[`${r}Array`]=Se.DataView;function Et(r,e={},t){let n=co(r),i=e&&e.typeEncoders&&e.typeEncoders[n]||Se[n];if(typeof i=="function"){let s=i(r,n,e,t);if(s!=null)return s}let o=Se[n];if(!o)throw new Error(`${ke} unsupported type: ${n}`);return o(r,n,e,t)}function Tf(r,e){e.mapSorter&&r.sort(e.mapSorter)}function Lf(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=vt[i].compareTokens(t,n);return o===0&&console.warn("WARNING: complex key types used, CBOR key sorting guarantees are gone"),o}function Cf(r,e){if(r[0]instanceof p&&e[0]instanceof p){let t=r[0],n=e[0];return t._keyBytes||(t._keyBytes=kc(t.value)),n._keyBytes||(n._keyBytes=kc(n.value)),Zr(t._keyBytes,n._keyBytes)}throw new Error("rfc8949MapSorter: complex key types are not supported yet")}function kc(r){return un(r,vt,Lc)}function nr(r,e,t,n){if(Array.isArray(e))for(let i of e)nr(r,i,t,n);else t[e.type.major](r,e,n)}var Sc=u.uint.majorEncoded,Ic=u.negint.majorEncoded,Df=u.bytes.majorEncoded,Pf=u.string.majorEncoded,Tc=u.array.majorEncoded,Nf=u.float.majorEncoded|lo,Rf=u.float.majorEncoded|ho,Bf=u.float.majorEncoded|fo,Uf=u.float.majorEncoded|po,Of=BigInt(-1),Mf=BigInt(1);function Ff(r){return r.addBreakTokens!==!0}function Cc(r,e,t,n){let i=co(e),o=t.typeEncoders&&t.typeEncoders[i];if(o){let s=o(e,i,t,n);if(s!=null){nr(r,s,vt,t);return}}switch(i){case"null":r.push([Bf]);return;case"undefined":r.push([Uf]);return;case"boolean":r.push([e?Rf:Nf]);return;case"number":!Number.isInteger(e)||!Number.isSafeInteger(e)?rr(r,new p(u.float,e),t):e>=0?S(r,Sc,e):S(r,Ic,e*-1-1);return;case"bigint":e>=BigInt(0)?S(r,Sc,e):S(r,Ic,e*Of-Mf);return;case"string":{let s=yt(e);S(r,Pf,s.length),r.push(s);return}case"Uint8Array":S(r,Df,e.length),r.push(e);return;case"Array":if(!e.length){r.push([Tc]);return}n=ir.createCheck(n,e),S(r,Tc,e.length);for(let s of e)Cc(r,s,t,n);return;case"Object":case"Map":{let s=Se.Object(e,i,t,n);nr(r,s,vt,t)}return;default:{let s=Se[i];if(!s)throw new Error(`${ke} unsupported type: ${i}`);let a=s(e,i,t,n);nr(r,a,vt,t)}}}function un(r,e,t,n){let i=n instanceof Uint8Array,o=i?new en(n):cn,s=Et(r,t);if(!Array.isArray(s)&&t.quickEncodeToken){let a=t.quickEncodeToken(s);if(a)return i?(o.push(a),o.toBytes()):a;let c=e[s.type.major];if(c.encodedSize){let l=c.encodedSize(s,t);if(i||(o=new Xt(l)),c(o,s,t),o.chunks.length!==1)throw new Error(`Unexpected error: pre-calculated length for ${s} was wrong`);return i?o.toBytes():Je(o.chunks[0])}}return o.reset(),nr(o,s,e,t),o.toBytes(!0)}function Ye(r,e){return e=Object.assign({},Sf,e),Ff(e)?(cn.reset(),Cc(cn,r,e,void 0),cn.toBytes(!0)):un(r,vt,e)}var $f={strict:!1,allowIndefinite:!0,allowUndefined:!0,allowBigInt:!0},ln=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=Ee[e];if(t===void 0){let n=m[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}},ze=Symbol.for("DONE"),_t=Symbol.for("BREAK");function zf(r,e,t){let n=[];for(let i=0;i<r.value;i++){let o=Ke(e,t);if(o===_t){if(r.value===1/0)break;throw new Error(`${g} got unexpected break to lengthed array`)}if(o===ze)throw new Error(`${g} found array but not enough entries (got ${i}, expected ${r.value})`);n[i]=o}return n}function Kf(r,e,t){let n=t.useMaps===!0,i=t.rejectDuplicateMapKeys===!0,o=n?void 0:{},s=n?new Map:void 0;for(let a=0;a<r.value;a++){let c=Ke(e,t);if(c===_t){if(r.value===1/0)break;throw new Error(`${g} got unexpected break to lengthed map`)}if(c===ze)throw new Error(`${g} found map but not enough entries (got ${a} [no key], expected ${r.value})`);if(!n&&typeof c!="string")throw new Error(`${g} non-string keys not supported (got ${typeof c})`);if(i&&(n&&s.has(c)||!n&&Object.hasOwn(o,c)))throw new Error(`${g} found repeat map key "${c}"`);let l=Ke(e,t);if(l===ze)throw new Error(`${g} found map but not enough entries (got ${a} [no value], expected ${r.value})`);n?s.set(c,l):o[c]=l}return n?s:o}function*qf(r,e,t){for(let n=0;n<r.value;n++){let i=Ke(e,t);if(i===_t){if(r.value===1/0)break;throw new Error(`${g} got unexpected break to lengthed map`)}if(i===ze)throw new Error(`${g} found map but not enough entries (got ${n} [no key], expected ${r.value})`);let o=Ke(e,t);if(o===ze)throw new Error(`${g} found map but not enough entries (got ${n} [no value], expected ${r.value})`);yield[i,o]}}function jf(r,e){let t=!1,n=function(){if(t)throw new Error(`${g} tag decode() may only be called once`);t=!0;let i=Ke(r,e);if(i===ze)throw new Error(`${g} tag content missing`);if(i===_t)throw new Error(`${g} got unexpected break in tag content`);return i};return n.entries=function(){if(t)throw new Error(`${g} tag decode() may only be called once`);t=!0;let i=r.next();if(!u.equals(i.type,u.map))throw new Error(`${g} entries() requires map content, got ${i.type.name}`);let o=[];for(let s of qf(i,r,e))o.push(s);return o},Object.defineProperty(n,"_called",{get(){return t},enumerable:!1}),n}function Ke(r,e){if(r.done())return ze;let t=r.next();if(u.equals(t.type,u.break))return _t;if(t.type.terminal)return t.value;if(u.equals(t.type,u.array))return zf(t,r,e);if(u.equals(t.type,u.map))return Kf(t,r,e);if(u.equals(t.type,u.tag)){if(e.tags&&typeof e.tags[t.value]=="function"){let n=jf(r,e),i=e.tags[t.value](n);if(!n._called)throw new Error(`${g} tag decoder must call decode() or entries()`);return i}throw new Error(`${g} tag not supported (${t.value})`)}throw new Error("unsupported")}function bo(r,e){if(!(r instanceof Uint8Array))throw new Error(`${g} data to decode must be a Uint8Array`);e=Object.assign({},$f,e);let t=Je(r),n=e.tokenizer||new ln(t,e),i=Ke(n,e);if(i===ze)throw new Error(`${g} did not find any content to decode`);if(i===_t)throw new Error(`${g} got unexpected break`);return[i,r.subarray(n.pos())]}function ve(r,e){let[t,n]=bo(r,e);if(n.length>0)throw new Error(`${g} too many terminals, data makes no sense`);return t}var hn=class r{constructor(e,t){if(typeof e!="number"||!Number.isInteger(e)||e<0)throw new TypeError("Tagged: tag must be a non-negative integer");this.tag=e,this.value=t}static decoder(e){return t=>new r(e,t())}static preserve(...e){let t={};for(let n of e)t[n]=r.decoder(n);return t}};Object.defineProperty(hn.prototype,Symbol.toStringTag,{value:"Tagged"});var fn=class extends J{has(e){return this.find(e)!=null}find(e){return this.queue.find(t=>e.equals(t.options.peerId))}};function Vf(r){return r[Symbol.asyncIterator]!=null}function Hf(r){if(Vf(r))return(async()=>{let n=new Uint8Array(0);for await(let i of r)n=de([n,i],n.length+i.length);return n})();let e=[],t=0;for(let n of r)e.push(n),t+=n.byteLength;return de(e,t)}var dn=Hf;function pn({enumerable:r=!0,configurable:e=!1}={}){return{enumerable:r,configurable:e,writable:!1}}function*Wf(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*xo(n,i))}else{let t=v.asCID(e);t!=null?yield[r.join("/"),t]:yield*xo(e,r)}}function*xo(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*Wf(o,i)}}function*Gf(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*Eo(n,i))}else yield*Eo(e,r)}function*Eo(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*Gf(i,n))}}function Jf(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 vo=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:pn(),bytes:pn(),value:pn(),asBlock:pn()})}links(){return xo(this.value,[])}tree(){return Eo(this.value,[])}get(e="/"){return Jf(this.value,e.split("/").filter(Boolean))}};function mn({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 vo({cid:e,bytes:r,value:i})}var gn=class extends Error{static name="AlreadyPinnedError";name="AlreadyPinnedError"},or=class extends Error{static name="BlockPinnedError";name="BlockPinnedError"},yn=class extends Error{static name="InvalidDatastoreVersionError";name="InvalidDatastoreVersionError"},Xe=class extends Error{static name="InvalidConfigurationError";name="InvalidConfigurationError"},wn=class extends AggregateError{static name="GetFailedError";name="GetFailedError"},bn=class extends AggregateError{static name="LoadBlockFailedError";name="LoadBlockFailedError"},sr=class extends Error{static name="BlockNotFoundWhileOfflineError";name="BlockNotFoundWhileOfflineError"};var Rc="/pin/",Pc="/pinned-block/",_o=he,Nc=1;function xn(r){return r.version===0&&(r=r.toV1()),new ne(`${Rc}${r.toString(_o)}`)}var En=class{datastore;blockstore;getCodec;constructor(e,t,n){this.datastore=e,this.blockstore=t,this.getCodec=n}async*add(e,t={}){let n=xn(e);if(await this.datastore.has(n))throw new gn("Already pinned");let i=Math.round(t.depth??1/0);if(i<0)throw new pt("Depth must be greater than or equal to 0");let o=new J({concurrency:Nc});for await(let a of this.#e(e,o,{...t,depth:i}))await this.#t(a,c=>c.pinnedBy.find(l=>Le(l,e.bytes))!=null?!1:(c.pinCount++,c.pinnedBy.push(e.bytes),!0),t),yield a;let s={depth:i,metadata:t.metadata??{}};await this.datastore.put(n,Ye(s),t)}async*#e(e,t,n){if(n.depth===-1)return;let i=await this.getCodec(e.code),o=await dn(this.blockstore.get(e,n)),s=mn({bytes:o,cid:e,codec:i});yield e;for(let[,a]of s.links())yield*await t.add(async()=>this.#e(a,t,{...n,depth:n.depth-1}))}async#t(e,t,n){let i=new ne(`${Pc}${_o.encode(e.multihash.bytes)}`),o={pinCount:0,pinnedBy:[]};try{o=ve(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,Ye(o),n),n.onProgress?.(new x("helia:pin:add",e))}}async*rm(e,t={}){let n=xn(e),i=await this.datastore.get(n,t),o=ve(i);await this.datastore.delete(n,t);let s=new J({concurrency:Nc});for await(let a of this.#e(e,s,{...t,depth:o.depth}))await this.#t(a,c=>(c.pinCount--,c.pinnedBy=c.pinnedBy.filter(l=>Le(l,e.bytes)),!0),{...t,depth:o.depth}),yield a}async*ls(e={}){for await(let{key:t,value:n}of this.datastore.query({prefix:Rc+(e.cid!=null?`${e.cid.toString(he)}`:"")},e)){let i=v.parse(t.toString().substring(5),he),o=ve(n);yield{cid:i,...o}}}async isPinned(e,t={}){let n=new ne(`${Pc}${_o.encode(e.multihash.bytes)}`);return this.datastore.has(n,t)}async get(e,t){let n=xn(e),i=await this.datastore.get(n,t);return ve(i)}async setMetadata(e,t,n){let i=xn(e),o=await this.datastore.get(i,n),s=ve(o);s.metadata=t??{},await this.datastore.put(i,Ye(s),n)}};var vn=class extends Error{static name="InsufficientProvidersError";constructor(e="Insufficient providers found"){super(e),this.name="InsufficientProvidersError"}},Ze=class extends Error{static name="NoRoutersAvailableError";constructor(e="No routers available"){super(e),this.name="NoRoutersAvailableError"}},_n=class extends Error{static name="UnknownHashAlgorithmError";constructor(e="Unknown hash algorithm"){super(e),this.name="UnknownHashAlgorithmError"}},An=class extends Error{static name="UnknownCodecError";constructor(e="Unknown codec"){super(e),this.name="UnknownCodecError"}};var kn=class extends Error{static name="UnknownCryptoError";name="UnknownCryptoError"};var Qf=5,Sn=class{name;log;routers;providerLookupConcurrency;constructor(e,t){this.name="helia",this.log=e.logger.forComponent("helia:routing"),this.routers=t.routers??[],this.providerLookupConcurrency=t.providerLookupConcurrency??Qf,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 Oe(...this.routers)}async stop(){await Me(...this.routers)}async*findProviders(e,t={}){if(this.routers.length===0)throw new Ze("No content routers available");let n=new fn({concurrency:this.providerLookupConcurrency}),i=0,o=[],s=this,a=0;this.log("findProviders for %c start using routers %s",e,this.routers.map(l=>l.toString()).join(", "));let c=et(this.routers,"findProviders").map(async function*(l){let h=0;t?.onProgress?.(new x("helia:routing:find-providers:start",{routing:l.name,cid:e}));try{for await(let f of l.findProviders(e,t))h++,t?.onProgress?.(new x("helia:routing:find-providers:provider",{routing:l.name,cid:e,provider:f})),yield f}catch(f){o.push(f)}finally{s.log("router %s found %d providers for %c",l,h,e),t?.onProgress?.(new x("helia:routing:find-providers:end",{routing:l.name,cid:e,found:h})),a++,a===c.length&&n.size===0&&n.emitIdle()}});for await(let l of Yr(n.toGenerator(),...c))if(l!=null){if(l.multiaddrs.length===0){if(n.find(l.id)!=null)continue;n.add(async()=>{try{let h=await this.findPeer(l.id,t);return h.multiaddrs.length===0?null:{...h,protocols:l.protocols,routing:l.routing}}catch(h){return this.log.error("could not load multiaddrs for peer %p - %e",l.id,h),null}},{peerId:l.id,signal:t.signal}).catch(h=>{this.log.error("could not load multiaddrs for peer %p - %e",l.id,h)});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 Ze("No content routers available");await Promise.all(et(this.routers,"provide").map(async n=>{t?.onProgress?.(new x("helia:routing:provide:start",{routing:n.name,cid:e})),await n.provide(e,t),t?.onProgress?.(new x("helia:routing:provide:end",{routing:n.name,cid:e}))}))}async cancelReprovide(e,t={}){await Promise.all(et(this.routers,"cancelReprovide").map(async n=>{t?.onProgress?.(new x("helia:routing:cancel-reprovide:start",{routing:n.name,cid:e})),await n.cancelReprovide(e,t),t?.onProgress?.(new x("helia:routing:cancel-reprovide:end",{routing:n.name,cid:e}))}))}async put(e,t,n){await Promise.all(et(this.routers,"put").map(async i=>{n?.onProgress?.(new x("helia:routing:put:start",{routing:i.name,key:e,value:t})),await i.put(e,t,n),n?.onProgress?.(new x("helia:routing:put:end",{routing:i.name,key:e,value:t}))}))}async get(e,t){let n=[],i;try{i=await Promise.any(et(this.routers,"get").map(async o=>{t?.onProgress?.(new x("helia:routing:get:start",{routing:o.name,key:e}));try{return await o.get(e,t)}catch(s){this.log("router %s failed with %e",o,s),n.push(s)}finally{t?.onProgress?.(new x("helia:routing:get:end",{routing:o.name,key:e}))}}))}catch{}if(i==null)throw new wn(n,`Failed to get value key ${re(e,"base58btc")}`);return i}async findPeer(e,t){if(this.routers.length===0)throw new Ze("No peer routers available");let n=this,i=Yr(...et(this.routers,"findPeer").map(o=>(async function*(){t?.onProgress?.(new x("helia:routing:find-peer:start",{routing:o.name,peerId:e}));try{yield await o.findPeer(e,t)}catch(s){n.log.error(s)}finally{t?.onProgress?.(new x("helia:routing:find-peer:end",{routing:o.name,peerId:e}))}})()));for await(let o of i)if(o!=null)return o;throw new Ur("Could not find peer in routing")}async*getClosestPeers(e,t={}){if(this.routers.length===0)throw new Ze("No peer routers available");for await(let n of Yr(...et(this.routers,"getClosestPeers").map(async function*(i){t?.onProgress?.(new x("helia:routing:get-closest-peers:start",{routing:i.name,key:e}));try{yield*i.getClosestPeers(e,t)}finally{t?.onProgress?.(new x("helia:routing:get-closest-peers:end",{routing:i.name,key:e}))}})))n!=null&&(yield n)}};function et(r,e){return r.filter(t=>t[e]!=null)}var ee=class extends Error{static name="AbortError";name="AbortError";constructor(e="The operation was aborted",...t){super(e,...t)}};async function In(r,e,t,n){let i=new ee(n?.errorMessage);n?.errorCode!=null&&(i.code=n.errorCode);let o=n?.errorEvent??"error";return t?.aborted===!0?Promise.reject(i):new Promise((s,a)=>{function c(){ko(t,"abort",f),ko(r,e,l),ko(r,o,h)}let l=d=>{try{if(n?.filter?.(d)===!1)return}catch(y){c(),a(y);return}c(),s(d)},h=d=>{if(c(),d instanceof Error){a(d);return}a(d.detail??n?.error??new Error(`The "${n?.errorEvent}" event was emitted but the event had no '.detail' field. Pass an 'error' option to race-event to change this message.`))},f=()=>{c(),a(i)};Ao(t,"abort",f),Ao(r,e,l),Ao(r,o,h)})}function Ao(r,e,t){r!=null&&(Bc(r)?r.addEventListener(e,t):r.addListener(e,t))}function ko(r,e,t){r!=null&&(Bc(r)?r.removeEventListener(e,t):r.removeListener(e,t))}function Bc(r){return typeof r.addEventListener=="function"&&typeof r.removeEventListener=="function"}var Tn=class extends Error{static name="QueueFullError";constructor(e="The queue was full"){super(e),this.name="QueueFullError"}};var Ln=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 ee)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function Yf(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var Cn=class{id;fn;options;recipients;status;timeline;controller;constructor(e,t){this.id=Yf(),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 ee),this.cleanup())}async join(e={}){let t=new Ln(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 Fe(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 So(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 ar=class extends ie{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=So(this.emitEmpty.bind(this),1),this.emitIdle=So(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 Tn;let n=new Cn(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 ee)}),this.clear()}async onEmpty(e){this.size!==0&&await In(this,"empty",e?.signal)}async onSizeLessThan(e,t){this.size<e||await In(this,"next",t?.signal,{filter:()=>this.size<e})}async onIdle(e){this.pending===0&&this.size===0||await In(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=Hr({objectMode:!0}),n=c=>{c!=null?this.abort():this.clear(),t.end(c)},i=c=>{c.detail!=null&&t.push(c.detail.result)},o=c=>{n(c.detail.error)},s=()=>{n()},a=()=>{n(new ee("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 Dn="lock:worker:request-read",Pn="lock:worker:abort-read-request",Nn="lock:worker:release-read",Rn="lock:master:grant-read",Bn="lock:master:error-read",Un="lock:worker:request-write",On="lock:worker:abort-write-request",Mn="lock:worker:release-write",Fn="lock:master:grant-write",$n="lock:master:error-write",zn="lock:worker:finalize",Kn="mortice",Uc={singleProcess:!1};var Io=(r,e,t,n,i,o,s,a,c)=>l=>{if(l.data==null)return;let h={type:l.data.type,name:l.data.name,identifier:l.data.identifier};h.type===i&&r.safeDispatchEvent(t,{detail:{name:h.name,identifier:h.identifier,handler:async()=>{e.postMessage({type:c,name:h.name,identifier:h.identifier}),await new Promise(f=>{let d=y=>{if(y?.data==null)return;let w={type:y.data.type,name:y.data.name,identifier:y.data.identifier};w.type===a&&w.identifier===h.identifier&&(e.removeEventListener("message",d),f())};e.addEventListener("message",d)})},onError:f=>{e.postMessage({type:s,name:h.name,identifier:h.identifier,error:{message:f.message,name:f.name,stack:f.stack}})}}}),h.type===o&&r.safeDispatchEvent(n,{detail:{name:h.name,identifier:h.identifier}}),h.type===zn&&r.safeDispatchEvent("finalizeRequest",{detail:{name:h.name}})};var Oc=(r=10)=>Math.random().toString().substring(2,r+2);var qn=class{name;channel;constructor(e){this.name=e,this.channel=new BroadcastChannel(Kn)}readLock(e){return this.sendRequest(Dn,Pn,Rn,Bn,Nn,e)}writeLock(e){return this.sendRequest(Un,On,Fn,$n,Mn,e)}finalize(){this.channel.postMessage({type:zn,name:this.name}),this.channel.close()}async sendRequest(e,t,n,i,o,s){s?.signal?.throwIfAborted();let a=Oc();return this.channel.postMessage({type:e,identifier:a,name:this.name}),new Promise((c,l)=>{let h=()=>{this.channel.postMessage({type:t,identifier:a,name:this.name})};s?.signal?.addEventListener("abort",h,{once:!0});let f=d=>{if(d.data?.identifier===a&&(d.data?.type===n&&(this.channel.removeEventListener("message",f),s?.signal?.removeEventListener("abort",h),c(()=>{this.channel.postMessage({type:o,identifier:a,name:this.name})})),d.data.type===i)){this.channel.removeEventListener("message",f),s?.signal?.removeEventListener("abort",h);let y=new Error;d.data.error!=null&&(y.message=d.data.error.message,y.name=d.data.error.name,y.stack=d.data.error.stack),l(y)}};this.channel.addEventListener("message",f)})}};var Mc=r=>{if(r=Object.assign({},Uc,r),!!globalThis.document||r.singleProcess){let t=new BroadcastChannel(Kn),n=new ie;return t.addEventListener("message",Io(n,t,"requestReadLock","abortReadLockRequest",Dn,Pn,Bn,Nn,Rn)),t.addEventListener("message",Io(n,t,"requestWriteLock","abortWriteLockRequest",Un,On,$n,Mn,Fn)),n}return new qn(r.name)};var tt=new Map,cr;function Fc(r){return typeof r?.readLock=="function"&&typeof r?.writeLock=="function"}function Xf(r){if(cr==null&&(cr=Mc(r),!Fc(cr))){let e=cr;e.addEventListener("requestReadLock",t=>{let n=t.detail.name,i=t.detail.identifier,o=tt.get(n);if(o==null)return;let s=new AbortController,a=c=>{c.detail.name!==n||c.detail.identifier!==i||s.abort()};e.addEventListener("abortReadLockRequest",a),o.readLock({signal:s.signal}).then(async c=>{await t.detail.handler().finally(()=>{c()})}).catch(c=>{t.detail.onError(c)}).finally(()=>{e.removeEventListener("abortReadLockRequest",a)})}),e.addEventListener("requestWriteLock",t=>{let n=t.detail.name,i=t.detail.identifier,o=tt.get(n);if(o==null)return;let s=new AbortController,a=c=>{c.detail.name!==n||c.detail.identifier!==i||s.abort()};e.addEventListener("abortWriteLockRequest",a),o.writeLock({signal:s.signal}).then(async c=>{await t.detail.handler().finally(()=>{c()})}).catch(c=>{t.detail.onError(c)}).finally(()=>{e.removeEventListener("abortWriteLockRequest",a)})}),e.addEventListener("finalizeRequest",t=>{let n=t.detail.name,i=tt.get(n);i?.finalize()})}return cr}async function To(r,e){let t,n,i=new Promise((s,a)=>{t=s,n=a}),o=()=>{n(new ee)};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 $c=(r,e)=>{let t=tt.get(r);if(t!=null)return t;let n=Xf(e);if(Fc(n))return t=n,tt.set(r,t),t;let i=new ar({concurrency:1}),o;return t={async readLock(s){if(o!=null)return To(o,s);o=new ar({concurrency:e.concurrency,autoStart:!1});let a=o,c=To(o,s);return i.add(async()=>{a.start(),await a.onIdle().then(()=>{o===a&&(o=null)})}),c},async writeLock(s){return o=null,To(i,s)},finalize:()=>{tt.delete(r)},queue:i},tt.set(r,t),e.autoFinalize===!0&&i.addEventListener("idle",()=>{t.finalize()},{once:!0}),t};var Zf={name:"lock",concurrency:1/0,singleProcess:!1,autoFinalize:!1};function Lo(r){let e=Object.assign({},Zf,r);return $c(e.name,e)}var jn=class{lock;child;pins;routing;started;constructor(e,t,n,i={}){this.child=e,this.pins=t,this.routing=n,this.lock=Lo({singleProcess:i.holdGcLock}),this.started=!1}isStarted(){return this.started}async start(){await Oe(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 or("Block was pinned - please unpin and try again");await this.routing.cancelReprovide(e,t),await this.child.delete(e,t)}finally{n()}}async*deleteMany(e,t={}){t?.signal?.throwIfAborted();let n=await this.lock.writeLock();try{let i=this;yield*this.child.deleteMany((async function*(){for await(let o of e){if(await i.pins.isPinned(o))throw new or("Block was pinned - please unpin and try again");await i.routing.cancelReprovide(o,t),yield o}})(),t)}finally{n()}}async has(e,t={}){t?.signal?.throwIfAborted();let n=await this.lock.readLock();try{return await this.child.has(e,t)}finally{n()}}async*getAll(e={}){e?.signal?.throwIfAborted();let t=await this.lock.readLock();try{yield*this.child.getAll(e)}finally{t()}}createSession(e,t){return t?.signal?.throwIfAborted(),this.child.createSession(e,t)}};var Co=new ne("/version"),zc=1;async function Kc(r){if(!await r.has(Co)){await r.put(Co,I(`${zc}`));return}let e=await r.get(Co),t=re(e);if(parseInt(t,10)!==zc)throw new yn("Invalid datastore version, a datastore migration may be required")}var Ro={};D(Ro,{code:()=>No,decode:()=>ud,decodeOptions:()=>sd,encode:()=>cd,encodeOptions:()=>id,name:()=>ad,toByteView:()=>jc});var qc=42;function jc(r){return r instanceof ArrayBuffer?new Uint8Array(r,0,r.byteLength):r}function ed(r){if(r.asCID!==r&&r["/"]!==r.bytes)return null;let e=v.asCID(r);if(!e)return null;let t=new Uint8Array(e.bytes.byteLength+1);return t.set(e.bytes,1),[new p(u.tag,qc),new p(u.bytes,t)]}function td(){throw new Error("`undefined` is not supported by the IPLD Data Model and cannot be encoded")}function rd(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 nd(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 Do={float64:!0,typeEncoders:{Map:nd,Object:ed,undefined:td,number:rd}},id={...Do,typeEncoders:{...Do.typeEncoders}};function od(r){let e=r();if(e[0]!==0)throw new Error("Invalid CID for CBOR tag 42; expected leading 0x00");return v.decode(e.subarray(1))}var Po={allowIndefinite:!1,coerceUndefinedToNull:!0,allowNaN:!1,allowInfinity:!1,allowBigInt:!0,strict:!0,useMaps:!1,rejectDuplicateMapKeys:!0,tags:{[qc]:od}},sd={...Po,tags:{...Po.tags}},ad="dag-cbor",No=113,cd=r=>Ye(r,Do),ud=r=>ve(jc(r),Po);var $o={};D($o,{code:()=>Fo,decode:()=>Wc,encode:()=>Hc,format:()=>xd,name:()=>bd,parse:()=>vd,stringify:()=>xd});var Bo=class extends Array{constructor(){super(),this.inRecursive=[]}prefix(e){let t=this.inRecursive[this.inRecursive.length-1];t&&(u.equals(t.type,u.array)&&(t.elements++,t.elements!==1&&e.push([44])),u.equals(t.type,u.map)&&(t.elements++,t.elements!==1&&(t.elements%2===1?e.push([44]):e.push([58]))))}[u.uint.major](e,t){this.prefix(e);let n=String(t.value),i=[];for(let o=0;o<n.length;o++)i[o]=n.charCodeAt(o);e.push(i)}[u.negint.major](e,t){this[u.uint.major](e,t)}[u.bytes.major](e,t){throw new Error(`${ke} unsupported type: Uint8Array`)}[u.string.major](e,t){this.prefix(e);let n=yt(JSON.stringify(t.value));e.push(n.length>32?Je(n):n)}[u.array.major](e,t){this.prefix(e),this.inRecursive.push({type:u.array,elements:0}),e.push([91])}[u.map.major](e,t){this.prefix(e),this.inRecursive.push({type:u.map,elements:0}),e.push([123])}[u.tag.major](e,t){}[u.float.major](e,t){if(t.type.name==="break"){let s=this.inRecursive.pop();if(s){if(u.equals(s.type,u.array))e.push([93]);else if(u.equals(s.type,u.map))e.push([125]);else throw new Error("Unexpected recursive type; this should not happen!");return}throw new Error("Unexpected break; this should not happen!")}if(t.value===void 0)throw new Error(`${ke} 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 ld(r,e){if(Array.isArray(r[0])||Array.isArray(e[0]))throw new Error(`${ke} complex map keys are not supported`);let t=r[0],n=e[0];if(t.type!==u.string||n.type!==u.string)throw new Error(`${ke} non-string map keys are not supported`);if(t<n)return-1;if(t>n)return 1;throw new Error(`${ke} unexpected duplicate map keys, this is not supported`)}var hd={addBreakTokens:!0,mapSorter:ld};function Uo(r,e){return e=Object.assign({},hd,e),un(r,new Bo,e)}var At=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 c=this.ch();if(a.includes(c))this._pos++;else break}};if(this.ch()===45&&(t=!0,this._pos++),this.ch()===48)if(this._pos++,this.ch()===46)this._pos++,n=!0;else return new p(u.uint,0,this._pos-e);if(i([48,49,50,51,52,53,54,55,56,57]),t&&this._pos===e+1)throw new Error(`${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 p(u.float,s,this._pos-e):this.options.allowBigInt!==!0||Number.isSafeInteger(s)?new p(s>=0?u.uint:u.negint,s,this._pos-e):new p(s>=0?u.uint:u.negint,BigInt(o),this._pos-e)}parseString(){if(this.ch()!==34)throw new Error(`${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 c=String.fromCharCode.apply(null,this.data.subarray(this._pos,o));return this._pos=o+1,new p(u.string,c,s)}}let e=this._pos,t=[],n=()=>{if(this._pos+4>=this.data.length)throw new Error(`${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 c,l,h,f;switch(a){case 1:o<128&&(s=o);break;case 2:c=this.data[this._pos+1],(c&192)===128&&(f=(o&31)<<6|c&63,f>127&&(s=f));break;case 3:c=this.data[this._pos+1],l=this.data[this._pos+2],(c&192)===128&&(l&192)===128&&(f=(o&15)<<12|(c&63)<<6|l&63,f>2047&&(f<55296||f>57343)&&(s=f));break;case 4:c=this.data[this._pos+1],l=this.data[this._pos+2],h=this.data[this._pos+3],(c&192)===128&&(l&192)===128&&(h&192)===128&&(f=(o&15)<<18|(c&63)<<12|(l&63)<<6|h&63,f>65535&&f<1114112&&(s=f))}s===null?(s=65533,a=1):s>65535&&(s-=65536,t.push(s>>>10&1023|55296),s=56320|s&1023),t.push(s),this._pos+=a};for(;!this.done();){let 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 p(u.string,Da(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 p(u.map,1/0,1);case 91:return this.modeStack.push("array-start"),this._pos++,new p(u.array,1/0,1);case 34:return this.parseString();case 110:return this.expect([110,117,108,108]),new p(u.null,null,4);case 102:return this.expect([102,97,108,115,101]),new p(u.false,!1,5);case 116:return this.expect([116,114,117,101]),new p(u.true,!0,4);case 45:case 48:case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:return this.parseNumber();default:throw new Error(`${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 p(u.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 p(u.break,void 0,1)):(this.modeStack.push("array-value"),this.skipWhitespace(),this.parseValue());case"obj-key":if(this.ch()===125)return this.modeStack.pop(),this._pos++,this.skipWhitespace(),new p(u.break,void 0,1);if(this.ch()!==44)throw new Error(`${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 p(u.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 Oo(r,e){return e=Object.assign({tokenizer:new At(r,e)},e),ve(r,e)}function dd(r){return r instanceof ArrayBuffer?new Uint8Array(r,0,r.byteLength):r}function pd(r){if(r.asCID!==r&&r["/"]!==r.bytes)return null;let e=v.asCID(r);if(!e)return null;let t=e.toString();return[new p(u.map,1/0,1),new p(u.string,"/",1),new p(u.string,t,t.length),new p(u.break,void 0,1)]}function Vn(r){let e=fe.encode(r).slice(1);return[new p(u.map,1/0,1),new p(u.string,"/",1),new p(u.map,1/0,1),new p(u.string,"bytes",5),new p(u.string,e,e.length),new p(u.break,void 0,1),new p(u.break,void 0,1)]}function _e(r){return Vn(new Uint8Array(r.buffer,r.byteOffset,r.byteLength))}function md(r){return Vn(new Uint8Array(r))}function gd(){throw new Error("`undefined` is not supported by the IPLD Data Model and cannot be encoded")}function yd(r){if(Number.isNaN(r))throw new Error("`NaN` is not supported by the IPLD Data Model and cannot be encoded");if(r===1/0||r===-1/0)throw new Error("`Infinity` and `-Infinity` is not supported by the IPLD Data Model and cannot be encoded");return null}var wd={typeEncoders:{Object:pd,Buffer:Vn,Uint8Array:Vn,Int8Array:_e,Uint16Array:_e,Int16Array:_e,Uint32Array:_e,Int32Array:_e,Float32Array:_e,Float64Array:_e,Uint8ClampedArray:_e,BigInt64Array:_e,BigUint64Array:_e,DataView:_e,ArrayBuffer:md,undefined:gd,number:yd}},Mo=class extends At{constructor(e,t){super(e,t),this.tokenBuffer=[]}done(){return this.tokenBuffer.length===0&&super.done()}_next(){return this.tokenBuffer.length>0?this.tokenBuffer.pop():super.next()}next(){let e=this._next();if(u.equals(e.type,u.map)){let t=this._next();if(u.equals(t.type,u.string)&&t.value==="/"){let n=this._next();if(u.equals(n.type,u.string)){let i=this._next();if(!u.equals(i.type,u.break))throw new Error("Invalid encoded CID form");return this.tokenBuffer.push(n),new p(u.tag,42,0)}if(u.equals(n.type,u.map)){let i=this._next();if(u.equals(i.type,u.string)&&i.value==="bytes"){let o=this._next();if(u.equals(o.type,u.string)){for(let a=0;a<2;a++){let c=this._next();if(!u.equals(c.type,u.break))throw new Error("Invalid encoded Bytes form")}let s=fe.decode(`m${o.value}`);return new p(u.bytes,s,o.value.length)}this.tokenBuffer.push(o)}this.tokenBuffer.push(i)}this.tokenBuffer.push(n)}this.tokenBuffer.push(t)}return e}},Vc={allowIndefinite:!1,allowUndefined:!1,allowNaN:!1,allowInfinity:!1,allowBigInt:!0,strict:!0,useMaps:!1,rejectDuplicateMapKeys:!0,tags:{42:r=>v.parse(r())}},bd="dag-json",Fo=297,Hc=r=>Uo(r,wd),Wc=r=>{let e=dd(r),t=Object.assign(Vc,{tokenizer:new Mo(e,Vc)});return Oo(e,t)},xd=r=>Ed.decode(Hc(r));var Ed=new TextDecoder,vd=r=>Wc(_d.encode(r)),_d=new TextEncoder;var Ho={};D(Ho,{code:()=>Vo,createLink:()=>nu,createNode:()=>ru,decode:()=>Ud,encode:()=>Bd,name:()=>Rd,prepare:()=>qo,validate:()=>jo});var Ad=new TextDecoder;function zo(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 Hn(r,e){let t;[t,e]=zo(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 Gc(r,e){let t;return[t,e]=zo(r,e),[t&7,t>>3,e]}function kd(r){let e={},t=r.length,n=0;for(;n<t;){let i,o;if([i,o,n]=Gc(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]=Hn(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]=Hn(r,n),e.Name=Ad.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]=zo(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 Jc(r){let e=r.length,t=0,n,i=!1,o;for(;t<e;){let a,c;if([a,c,t]=Gc(r,t),a!==2)throw new Error(`protobuf: (PBNode) invalid wireType, expected 2, got ${a}`);if(c===1){if(o)throw new Error("protobuf: (PBNode) duplicate Data section");[o,t]=Hn(r,t),n&&(i=!0)}else if(c===2){if(i)throw new Error("protobuf: (PBNode) duplicate Links section");n||(n=[]);let l;[l,t]=Hn(r,t),n.push(kd(l))}else throw new Error(`protobuf: (PBNode) invalid fieldNumber, expected 1 or 2, got ${c}`)}if(t>e)throw new Error("protobuf: (PBNode) unexpected end of data");let s={};return o&&(s.Data=o),s.Links=n||[],s}var Yc=new TextEncoder,Qc=2**32,Sd=2**31;function Id(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=ur(e,t,r.Tsize)-1,e[t]=24}if(typeof r.Name=="string"){let n=Yc.encode(r.Name);t-=n.length,e.set(n,t),t=ur(e,t,n.length)-1,e[t]=18}return r.Hash&&(t-=r.Hash.length,e.set(r.Hash,t),t=ur(e,t,r.Hash.length)-1,e[t]=10),e.length-t}function Xc(r){let e=Ld(r),t=new Uint8Array(e),n=e;if(r.Data&&(n-=r.Data.length,t.set(r.Data,n),n=ur(t,n,r.Data.length)-1,t[n]=10),r.Links)for(let i=r.Links.length-1;i>=0;i--){let o=Id(r.Links[i],t.subarray(0,n));n-=o,n=ur(t,n,o)-1,t[n]=18}return t}function Td(r){let e=0;if(r.Hash){let t=r.Hash.length;e+=1+t+kt(t)}if(typeof r.Name=="string"){let t=Yc.encode(r.Name).length;e+=1+t+kt(t)}return typeof r.Tsize=="number"&&(e+=1+kt(r.Tsize)),e}function Ld(r){let e=0;if(r.Data){let t=r.Data.length;e+=1+t+kt(t)}if(r.Links)for(let t of r.Links){let n=Td(t);e+=1+n+kt(n)}return e}function ur(r,e,t){e-=kt(t);let n=e;for(;t>=Sd;)r[e++]=t&127|128,t/=128;for(;t>=128;)r[e++]=t&127|128,t>>>=7;return r[e]=t,n}function kt(r){return r%2===0&&r++,Math.floor((Cd(r)+6)/7)}function Cd(r){let e=0;return r>=Qc&&(r=Math.floor(r/Qc),e=32),r>=65536&&(r>>>=16,e+=16),r>=256&&(r>>>=8,e+=8),e+Dd[r]}var Dd=[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 Pd=["Data","Links"],Nd=["Hash","Name","Tsize"],Ko=new TextEncoder;function eu(r,e){if(r===e)return 0;let t=r.Name?Ko.encode(r.Name):[],n=e.Name?Ko.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 Zc(r,e){return!Object.keys(r).some(t=>!e.includes(t))}function tu(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 qo(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=Ko.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(tu),e.Links.sort(eu);else throw new TypeError("Invalid DAG-PB form");else e.Links=[];return e}function jo(r){if(!r||typeof r!="object"||Array.isArray(r)||r instanceof Uint8Array||r["/"]&&r["/"]===r.bytes)throw new TypeError("Invalid DAG-PB form");if(!Zc(r,Pd))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(!Zc(t,Nd))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&&eu(t,r.Links[e-1])===-1)throw new TypeError("Invalid DAG-PB form (links must be sorted by Name bytes)")}}function ru(r,e=[]){return qo({Data:r,Links:e})}function nu(r,e,t){return tu({Hash:t,Name:r,Tsize:e})}function iu(r){return r instanceof ArrayBuffer?new Uint8Array(r,0,r.byteLength):r}var Rd="dag-pb",Vo=112;function Bd(r){jo(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),Xc(e)}function Ud(r){let e=iu(r),t=Jc(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 qe(r){return r?.then!=null}function ou(r=[],e){let t={[Vo]:Ho,[_i]:gr,[No]:Ro,[Fo]:$o,[vi]:mr};return r.forEach(n=>{t[n.code]=n}),async n=>{let i=t[n];if(i==null&&e!=null){let o=e(n);qe(o)?i=await o:i=o,t[i.code]=i}if(i!=null)return i;throw new An(`Could not load codec for ${n}`)}}function su(r=[],e){let t={};return r=[Ki(),ji(),qt(),...r],r.forEach(n=>{t[n.type]=n,t[n.code]=n}),async n=>{let i=t[n];if(i==null&&e!=null){let o=e(n);qe(o)?i=await o:i=o,t[i.type]=i,t[i.code]=i}if(i!=null)return i;throw new kn(`Could not load crypto for ${i}`)}}function au(r=[],e){let t={[Ue.code]:Ue,[wr.code]:wr,[Be.code]:Be};return r.forEach(n=>{t[n.code]=n}),async n=>{let i=t[n];if(i==null&&e!=null){let o=e(n);qe(o)?i=await o:i=o,t[i.code]=i}if(i!=null)return i;throw new _n(`No hasher configured for multihash code 0x${n.toString(16)}, please configure one. You can look up which hash this is at https://github.com/multiformats/multicodec/blob/master/table.csv`)}}var Wn=class r extends Error{static name="NotFoundError";name=r.name;static code="ERR_NOT_FOUND";code=r.code;constructor(e="Not Found"){super(e)}};var Gn=class{has(e,t){return Promise.reject(new Error(".has is not implemented"))}put(e,t,n){return Promise.reject(new Error(".put is not implemented"))}async*putMany(e,t){for await(let{cid:n,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 Jn=0,St=class extends Error{static name="IdentityHashDigestTooLongError";name="IdentityHashDigestTooLongError"},Qn=class extends Gn{child;maxDigestLength;constructor(e,t){super(),this.child=e,this.maxDigestLength=t?.maxDigestLength}put(e,t,n){if(e.multihash.code===Jn){if(this.maxDigestLength!=null&&e.multihash.digest.byteLength>this.maxDigestLength)throw new St(`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===Jn){if(this.maxDigestLength!=null&&e.multihash.digest.byteLength>this.maxDigestLength)throw new St(`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 Wn;yield*this.child.get(e,t)}has(e,t){if(e.multihash.code===Jn){if(this.maxDigestLength!=null&&e.multihash.digest.byteLength>this.maxDigestLength)throw new St(`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===Jn){if(this.maxDigestLength!=null&&e.multihash.digest.byteLength>this.maxDigestLength)throw new St(`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 Od(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 Yn=Od;function Md(r){return r[Symbol.asyncIterator]!=null}function Fd(r,e){let t=0;if(Md(r))return(async function*(){for await(let c of r)await e(c,t++)&&(yield c)})();let n=Yn(r),{value:i,done:o}=n.next();if(o===!0)return(function*(){})();let s=e(i,t++);if(typeof s.then=="function")return(async function*(){await s&&(yield i);for(let c of n)await e(c,t++)&&(yield c)})();let a=e;return(function*(){s===!0&&(yield i);for(let c of n)a(c,t++)&&(yield c)})()}var Xn=Fd;function $d(r){return r[Symbol.asyncIterator]!=null}function cu(r){return r?.then!=null}function zd(r,e){let t=0;if($d(r))return(async function*(){for await(let c of r){let l=e(c,t++);cu(l)&&await l,yield c}})();let n=Yn(r),{value:i,done:o}=n.next();if(o===!0)return(function*(){})();let s=e(i,t++);if(typeof s?.then=="function")return(async function*(){await s,yield i;for(let c of n){let l=e(c,t++);cu(l)&&await l,yield c}})();let a=e;return(function*(){yield i;for(let c of n)a(c,t++),yield c})()}var Wo=zd;var qd=128,It=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 Qn(e.blockstore,{maxDigestLength:t.maxIdentityHashDigestLength??qd}),this.getHasher=e.getHasher}async put(e,t,n={}){return await this.child.has(e,n)?(n.onProgress?.(new x("blocks:put:duplicate",e)),e):(n.onProgress?.(new x("blocks:put:providers:notify",e)),await Promise.all(this.blockBrokers.map(async i=>i.announce?.(e,n))),n.onProgress?.(new x("blocks:put:blockstore:put",e)),this.child.put(e,t,n))}async*putMany(e,t={}){let n=Xn(e,async({cid:o})=>{let s=await this.child.has(o,t);return s&&t.onProgress?.(new x("blocks:put-many:duplicate",o)),!s}),i=Wo(n,async({cid:o})=>{t.onProgress?.(new x("blocks:put-many:providers:notify",o)),await Promise.all(this.blockBrokers.map(async s=>s.announce?.(o,t)))});t.onProgress?.(new x("blocks:put-many:blockstore:put-many")),yield*this.child.putMany(i,t)}async*get(e,t={}){let n=await this.child.has(e,t),i=t.offline===!0;if(!n){if(i)throw new sr("The block was present in the blockstore and the node is running offline so cannot fetch it");let o=await this.getHasher(e.multihash.code);t?.signal?.throwIfAborted(),t.onProgress?.(new x("blocks:get:providers:get",e));let s=await uu(e,this.blockBrokers,o,{...t,log:this.log});t.onProgress?.(new x("blocks:get:blockstore:put",e)),await this.child.put(e,s,t),t.onProgress?.(new x("blocks:get:providers:notify",e)),await Promise.all(this.blockBrokers.map(async a=>a.announce?.(e,t))),yield s;return}t.onProgress?.(new x("blocks:get:blockstore:get",e)),yield*this.child.get(e,t)}async*getMany(e,t={}){t.onProgress?.(new x("blocks:get-many:blockstore:get-many")),yield*this.child.getMany(Wo(e,async n=>{let i=await this.child.has(n,t),o=t.offline===!0;if(!i){if(o)throw new sr("The block was present in the blockstore and the node is running offline so cannot fetch it");let s=await this.getHasher(n.multihash.code);t?.signal?.throwIfAborted(),t.onProgress?.(new x("blocks:get-many:providers:get",n));let a=await uu(n,this.blockBrokers,s,{...t,log:this.log});t.onProgress?.(new x("blocks:get-many:blockstore:put",n)),await this.child.put(n,a,t),t.onProgress?.(new x("blocks:get-many:providers:notify",n)),await Promise.all(this.blockBrokers.map(async c=>c.announce?.(n,t)))}}))}async delete(e,t={}){t.onProgress?.(new x("blocks:delete:blockstore:delete",e)),await this.child.delete(e,t)}async*deleteMany(e,t={}){t.onProgress?.(new x("blocks:delete-many:blockstore:delete-many")),yield*this.child.deleteMany((async function*(){for await(let n of e)yield n})(),t)}async has(e,t={}){return this.child.has(e,t)}async*getAll(e={}){e.onProgress?.(new x("blocks:get-all:blockstore:get-many")),yield*this.child.getAll(e)}};async function uu(r,e,t,n){let i=Vd(r,t),o=new AbortController,s=be([o.signal,n.signal]);o.signal;let a=[];for(let c of e)jd(c)&&a.push(c);if(a.length===0)throw new Xe(`No block brokers capable of retrieving blocks are configured, the CID ${r} cannot be fetched from the network`);try{return await Promise.any(a.map(async c=>{try{let l=!1,h=await c.retrieve(r,{...n,signal:s,validateFn:async f=>{await i(f),n.signal?.throwIfAborted(),l=!0}});return l||(await i(h),n.signal?.throwIfAborted()),h}catch(l){throw n.log.error("could not retrieve verified block for %c from %s - %e",r,c.name,l),l}}))}catch(c){throw new bn(c.errors,`Failed to load block for ${r}`)}finally{o.abort(),s.clear()}}function jd(r){return typeof r.retrieve=="function"}var Vd=(r,e)=>{if(e==null)throw new pt(`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(qe(i)?n=await i:n=i,!Le(n.digest,r.multihash.digest))throw new Or("Hash of downloaded block did not match multihash from passed CID")}};var Zn=class extends It{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=be([this.closeController.signal,n.signal]);try{return await super.put(e,t,{...n,signal:i})}finally{i.clear()}}async*putMany(e,t={}){let n=be([this.closeController.signal,t.signal]);try{yield*super.putMany(e,{...t,signal:n})}finally{n.clear()}}async*get(e,t={}){let n=be([this.closeController.signal,t.signal]);try{yield*super.get(e,{...t,signal:n})}finally{n.clear()}}async*getMany(e,t={}){let n=be([this.closeController.signal,t.signal]);try{yield*super.getMany(e,{...t,signal:n})}finally{n.clear()}}async delete(e,t={}){let n=be([this.closeController.signal,t.signal]);try{await super.delete(e,{...t,signal:n})}finally{n.clear()}}async*deleteMany(e,t={}){let n=be([this.closeController.signal,t.signal]);try{yield*super.deleteMany(e,{...t,signal:n})}finally{n.clear()}}async has(e,t={}){let n=be([this.closeController.signal,t.signal]);try{return await super.has(e,{...t,signal:n})}finally{n.clear()}}async*getAll(e={}){let t=be([this.closeController.signal,e.signal]);try{yield*super.getAll({...e,signal:t})}finally{t.clear()}}};var ei=class extends It{started;constructor(e,t={}){super(e,t),this.started=!1}isStarted(){return this.started}async start(){await Oe(this.child,...this.blockBrokers),this.started=!0}async stop(){await Me(this.child,...this.blockBrokers),this.started=!1}unwrap(){return this.child}createSession(e,t){if(this.blockBrokers.length===0)throw new Xe("No block brokers configured");let n=this.blockBrokers.map(i=>i.createSession?.(t)).filter(i=>i!=null);if(n.length===0)throw new Xe(`No configured block brokers support sessions - tried ${this.blockBrokers.map(i=>i.name).join(", ")}`);return new Zn({blockstore:this.child,blockBrokers:n,getHasher:this.getHasher,logger:this.logger},{root:e})}};var ti=class extends ie{initialPeerSearchComplete;requests;logName;log;logger;minProviders;maxProviders;providers;evictionFilter;initialProviders;cidPeerFilterSize;constructor(e,t){super(),this.logName=t.name,this.logger=e.logger,this.log=e.logger.forComponent(this.logName),this.requests=new Map,this.minProviders=t.minProviders??1,this.maxProviders=t.maxProviders??5,this.cidPeerFilterSize=t.cidPeerFilterSize??100,this.providers=[],this.evictionFilter=jr(this.maxProviders),this.initialProviders=[...t.providers??[]]}async retrieve(e,t={}){let n=fe.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=V(),s={promise:o.promise,observers:1,queryFilter:jr(this.cidPeerFilterSize)};this.requests.set(n,s);let a=!1;this.initialPeerSearchComplete==null&&(a=!0,this.log=this.logger.forComponent(`${this.logName}:${e}`),this.initialPeerSearchComplete=this.findProviders(e,this.minProviders,t));let c=!1,l=new J({concurrency:this.maxProviders});l.addEventListener("failure",d=>{this.log.error("error querying provider %s, evicting from session - %e",d.detail.job.options.provider,d.detail.error),this.evict(d.detail.job.options.provider)}),l.addEventListener("success",d=>{c=!0,o.resolve(d.detail.result)}),l.addEventListener("idle",()=>{if(c){this.log.trace("session idle, found block");return}if(t.signal?.aborted===!0){this.log.trace("session idle, signal aborted");return}Promise.resolve().then(async()=>{this.log("no session peers had block for for %c, finding new providers",e);for(let d=0;d<this.minProviders&&this.providers.length!==0;d++){let y=this.providers[Math.floor(Math.random()*this.providers.length)];this.evict(y)}await this.findProviders(e,this.minProviders,t),this.log("found new providers re-retrieving %c",e),this.requests.delete(n),o.resolve(await this.retrieve(e,t))}).catch(d=>{this.log.error("could not find new providers for %c - %e",e,d),o.reject(d)})});let h=d=>{let y=this.toFilterKey(d.detail);s.queryFilter.has(y)||(s.queryFilter.add(y),this.emitFoundProviderProgressEvent(e,d.detail,t),l.add(async()=>this.queryProvider(e,d.detail,t),{provider:d.detail}).catch(w=>{t.signal?.aborted!==!0&&this.log.error("error retrieving session block for %c - %e",e,w)}))};if(this.addEventListener("provider",h),a)try{await Fe(this.initialPeerSearchComplete,t.signal),a&&this.log("found initial session peers for %c",e)}catch(d){throw a&&this.log("failed to find initial session peers for %c - %e",e,d),this.requests.delete(n),s.observers>1&&o.reject(d),d}Promise.all([...this.providers].filter(d=>{let y=this.toFilterKey(d),w=s.queryFilter.has(y);return w||s.queryFilter.add(this.toFilterKey(d)),!w}).map(async d=>l.add(async()=>this.queryProvider(e,d,t),{provider:d}))).catch(d=>{t.signal?.aborted!==!0&&this.log.error("error retrieving session block for %c - %e",e,d)});let f=()=>{o.reject(new ge(t.signal?.reason??"Session aborted")),l.abort()};t.signal?.addEventListener("abort",f);try{return await o.promise}finally{this.removeEventListener("provider",h),t.signal?.removeEventListener("abort",f),l.clear(),this.requests.delete(n)}}evict(e){this.evictionFilter.add(this.toFilterKey(e));let t=this.providers.findIndex(n=>this.equals(n,e));t!==-1&&this.providers.splice(t,1)}isEvicted(e){return this.evictionFilter.has(this.toFilterKey(e))}hasProvider(e){return!!(this.providers.find(t=>this.equals(t,e))!=null||this.isEvicted(e))}async addPeer(e,t){let n=await this.convertToProvider(e,"manually-added",t);n==null||this.hasProvider(n)||(this.providers.push(n),this.safeDispatchEvent("provider",{detail:n}))}async findProviders(e,t,n){let i=V(),o=0;return Promise.resolve().then(async()=>{this.log("finding %d-%d new provider(s) for %c - %d initial providers",t,this.maxProviders,e,this.initialProviders.length);let s=this,a=async function*(){for(;s.initialProviders.length>0;){let l=s.initialProviders.pop();if(l==null)continue;let h=await s.convertToProvider(l,"manual",n);h!=null&&(yield h)}},c=async function*(){yield*a(),yield*s.findNewProviders(e,n)};for await(let l of c()){if(this.providers.length===this.maxProviders||n.signal?.aborted===!0)break;if(!this.hasProvider(l)&&(this.log("found %d providers, %d in session",o,this.providers.length),this.providers.push(l),this.safeDispatchEvent("provider",{detail:l}),o++,this.providers.length===t&&(this.log("session is ready with %d peer(s), new peers present",this.providers.length),i.resolve()),this.providers.length===this.maxProviders)){this.log("found max session peers %d",this.providers.length);break}}if(this.log("found %d new session peers while trying to find %d, %d in session",o,t,this.providers.length),this.providers.length<t)throw new vn(`Found ${o} of ${t} ${this.name} providers for ${e}, ${this.providers.length} in session after evictions`)}).catch(s=>{this.log.error("error searching routing for potential session peers for %c - %e",e,s),i.reject(s)}),i.promise}};function lu(r){return e=>new Go(e,r)}function hu(r){return e=>new Jo(e,r)}function fu(r){return e=>new Qo(e,r)}var lr=class{components;constructor(e,t={}){this.components=e}async*walk(e,t){let n=this.getQueue(),i=Xn(n.toGenerator(t),a=>a!=null),o=!1,s=async a=>{let c=a.cid,l=await dn(this.components.blockstore.get(c,a)),h=mn({cid:c,bytes:l,codec:await this.components.getCodec(c.code)});for(let[,f]of h.links())t?.includeChild?.(f,h)!==!1&&n.add(s,{...a,cid:f,depth:a.depth+1,path:[...a.path,f]}).catch(d=>{o||i.throw(d)});return{block:h,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()}}},Go=class extends lr{getQueue(){return new J({concurrency:1,sort:(e,t)=>e.options.depth===t.options.depth?0:e.options.depth<t.options.depth?1:-1})}},Jo=class extends lr{getQueue(){return new J({concurrency:1,sort:(e,t)=>e.options.depth===t.options.depth?0:e.options.depth<t.options.depth?-1:1})}},Qo=class extends lr{getQueue(){return new J({concurrency:1})}};var Yo=class{libp2p;blockstore;datastore;events;pins;logger;routing;getCodec;getHasher;getCrypto;dns;keychain;metrics;log;constructor(e){this.logger=e.logger??e.libp2p.logger,this.log=this.logger.forComponent("helia"),this.getHasher=au(e.hashers,e.loadHasher),this.getCodec=ou(e.codecs,e.loadCodec),this.getCrypto=su(e.cryptos,e.loadCrypto),this.dns=e.dns??xa(),this.metrics=e.metrics,this.libp2p=e.libp2p,this.events=new ie;let t={blockstore:e.blockstore,datastore:e.datastore,logger:this.logger,libp2p:this.libp2p,blockBrokers:[],getHasher:this.getHasher,getCodec:this.getCodec,getCrypto:this.getCrypto,dns:this.dns,metrics:this.metrics,...e.components??{}};this.keychain=t.keychain=ca()(t),this.routing=t.routing=new Sn(t,{routers:(e.routers??[]).flatMap(i=>{typeof i=="function"&&(i=i(t));let o=[i],s=Jd(i);s!=null&&o.push(s);let a=Qd(i);return a!=null&&o.push(a),o}),providerLookupConcurrency:e.providerLookupConcurrency}),t.blockBrokers=e.blockBrokers.map(i=>i(t));let n=new ei(t,e);this.pins=new En(e.datastore,n,this.getCodec),this.blockstore=new jn(n,this.pins,this.routing,{holdGcLock:e.holdGcLock??!0}),this.datastore=e.datastore}async start(){await Kc(this.datastore),await Oe(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 Ea(i.deleteMany((async function*(){for await(let{cid:o}of i.getAll())try{if(await n.pins.isPinned(o,e))continue;yield o,e.onProgress?.(new x("helia:gc:deleted",o))}catch(s){n.log.error("error during gc - %e",s),e.onProgress?.(new x("helia:gc:error",s))}})()))}finally{t()}this.log("gc finished")}};function Jd(r){return r?.[ua]}function Qd(r){return r?.[la]}return wu(Yd);})();
3
4
  return HeliaUtils}));
4
5
  //# sourceMappingURL=index.min.js.map