@helia/http 3.1.2-eb1908b3 → 3.1.3-35b081c7
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 +1 -1
- package/dist/index.min.js.map +3 -3
- package/package.json +5 -5
package/dist/index.min.js
CHANGED
|
@@ -10,7 +10,7 @@ ${e}`)}`:n!=null?`${n.split(`
|
|
|
10
10
|
${e}`)}`:t!=null?`${t}`:`${r.toString()}`}function tB(r){return r instanceof AggregateError||r?.name==="AggregateError"&&Array.isArray(r.errors)}function f1(r,e=""){if(tB(r)){let t=u1(r,e);return r.errors.length>0?(e=`${e} `,t+=`
|
|
11
11
|
${e}${r.errors.map(n=>`${f1(n,`${e}`)}`).join(`
|
|
12
12
|
${e}`)}`):t+=`
|
|
13
|
-
${e}[Error list was empty]`,t.trim()}return u1(r,e)}Pt.formatters.e=r=>r==null?"undefined":f1(r);function rB(r){let e=()=>{};return e.enabled=!1,e.color="",e.diff=0,e.log=()=>{},e.namespace=r,e.destroy=()=>!0,e.extend=()=>e,e}function Cs(r){return{forComponent(e){return ur(e,r)}}}function ur(r,e){let t=rB(`${r}:trace`);return Pt.enabled(`${r}:trace`)&&Pt.names.map(n=>n.toString()).find(n=>n.includes(":trace"))!=null&&(t=Pt(`${r}:trace`,e)),Object.assign(Pt(r,e),{error:Pt(`${r}:error`,e),trace:t,newScope:n=>ur(`${r}:${n}`,e)})}function l1(r){if(r!=null&&(r=r.trim(),r.length!==0))return r}var Bs=class extends $r{has(e){return this.find(e)!=null}find(e){return this.queue.find(t=>e.equals(t.options.peerId))}};var ff=class extends $r{constructor(e={}){super({...e,sort:(t,n)=>t.options.priority>n.options.priority?-1:t.options.priority<n.options.priority?1:0})}};var df=class{memoryStorage;points;duration;blockDuration;keyPrefix;constructor(e={}){this.points=e.points??4,this.duration=e.duration??1,this.blockDuration=e.blockDuration??0,this.keyPrefix=e.keyPrefix??"rlflx",this.memoryStorage=new Dy}consume(e,t=1,n={}){let o=this.getKey(e),i=this._getKeySecDuration(n),s=this.memoryStorage.incrby(o,t,i);if(s.remainingPoints=Math.max(this.points-s.consumedPoints,0),s.consumedPoints>this.points)throw this.blockDuration>0&&s.consumedPoints<=this.points+t&&(s=this.memoryStorage.set(o,s.consumedPoints,this.blockDuration)),new Vl("Rate limit exceeded",s);return s}penalty(e,t=1,n={}){let o=this.getKey(e),i=this._getKeySecDuration(n),s=this.memoryStorage.incrby(o,t,i);return s.remainingPoints=Math.max(this.points-s.consumedPoints,0),s}reward(e,t=1,n={}){let o=this.getKey(e),i=this._getKeySecDuration(n),s=this.memoryStorage.incrby(o,-t,i);return s.remainingPoints=Math.max(this.points-s.consumedPoints,0),s}block(e,t){let n=t*1e3,o=this.points+1;return this.memoryStorage.set(this.getKey(e),o,t),{remainingPoints:0,msBeforeNext:n===0?-1:n,consumedPoints:o,isFirstInDuration:!1}}set(e,t,n=0){let o=(n>=0?n:this.duration)*1e3;return this.memoryStorage.set(this.getKey(e),t,n),{remainingPoints:0,msBeforeNext:o===0?-1:o,consumedPoints:t,isFirstInDuration:!1}}get(e){let t=this.memoryStorage.get(this.getKey(e));return t!=null&&(t.remainingPoints=Math.max(this.points-t.consumedPoints,0)),t}delete(e){this.memoryStorage.delete(this.getKey(e))}_getKeySecDuration(e){return e?.customDuration!=null&&e.customDuration>=0?e.customDuration:this.duration}getKey(e){return this.keyPrefix.length>0?`${this.keyPrefix}:${e}`:e}parseKey(e){return e.substring(this.keyPrefix.length)}},Dy=class{storage;constructor(){this.storage=new Map}incrby(e,t,n){let o=this.storage.get(e);if(o!=null){let i=o.expiresAt!=null?o.expiresAt.getTime()-new Date().getTime():-1;return o.expiresAt==null||i>0?(o.value+=t,{remainingPoints:0,msBeforeNext:i,consumedPoints:o.value,isFirstInDuration:!1}):this.set(e,t,n)}return this.set(e,t,n)}set(e,t,n){let o=n*1e3,i=this.storage.get(e);i!=null&&clearTimeout(i.timeoutId);let s={value:t,expiresAt:o>0?new Date(Date.now()+o):void 0};return this.storage.set(e,s),o>0&&(s.timeoutId=setTimeout(()=>{this.storage.delete(e)},o),s.timeoutId.unref!=null&&s.timeoutId.unref()),{remainingPoints:0,msBeforeNext:o===0?-1:o,consumedPoints:s.value,isFirstInDuration:!0}}get(e){let t=this.storage.get(e);if(t!=null)return{remainingPoints:0,msBeforeNext:t.expiresAt!=null?t.expiresAt.getTime()-new Date().getTime():-1,consumedPoints:t.value,isFirstInDuration:!1}}delete(e){let t=this.storage.get(e);return t!=null?(t.timeoutId!=null&&clearTimeout(t.timeoutId),this.storage.delete(e),!0):!1}};var Ry=class extends Map{metric;constructor(e){super();let{name:t,metrics:n}=e;this.metric=n.registerMetric(t),this.updateComponentMetric()}set(e,t){return super.set(e,t),this.updateComponentMetric(),this}delete(e){let t=super.delete(e);return this.updateComponentMetric(),t}clear(){super.clear(),this.updateComponentMetric()}updateComponentMetric(){this.metric.update(this.size)}};function xt(r){let{name:e,metrics:t}=r,n;return t!=null?n=new Ry({name:e,metrics:t}):n=new Map,n}function nB(r){return r[Symbol.asyncIterator]!=null}function oB(r){if(nB(r))return(async()=>{for await(let e of r);})();for(let e of r);}var yc=oB;function iB(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 Ns=iB;function sB(r){return r[Symbol.asyncIterator]!=null}function aB(r,e){let t=0;if(sB(r))return(async function*(){for await(let c of r)yield e(c,t++)})();let n=Ns(r),{value:o,done:i}=n.next();if(i===!0)return(function*(){})();let s=e(o,t++);if(typeof s.then=="function")return(async function*(){yield await s;for(let c of n)yield e(c,t++)})();let a=e;return(function*(){yield s;for(let c of n)yield a(c,t++)})()}var hf=aB;function cB(r){return r[Symbol.asyncIterator]!=null}function uB(r,e){return cB(r)?(async function*(){let t=0;if(!(e<1)){for await(let n of r)if(yield n,t++,t===e)return}})():(function*(){let t=0;if(!(e<1)){for(let n of r)if(yield n,t++,t===e)return}})()}var pf=uB;var Ft=class extends Error{static name="AbortError";name="AbortError";constructor(e="The operation was aborted",...t){super(e,...t)}};async function mf(r,e,t,n){let o=new Ft(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(){Oy(t,"abort",f),Oy(r,e,u),Oy(r,i,l)}let u=d=>{try{if(n?.filter?.(d)===!1)return}catch(h){c(),a(h);return}c(),s(d)},l=d=>{if(c(),d instanceof Error){a(d);return}a(d.detail??n?.error??new Error(`The "${n?.errorEvent}" event was emitted but the event had no '.detail' field. Pass an 'error' option to race-event to change this message.`))},f=()=>{c(),a(o)};Uy(t,"abort",f),Uy(r,e,u),Uy(r,i,l)})}function Uy(r,e,t){r!=null&&(d1(r)?r.addEventListener(e,t):r.addListener(e,t))}function Oy(r,e,t){r!=null&&(d1(r)?r.removeEventListener(e,t):r.removeListener(e,t))}function d1(r){return typeof r.addEventListener=="function"&&typeof r.removeEventListener=="function"}var h1=Symbol.for("nodejs.util.inspect.custom"),lB=114,wc=class{type;multihash;publicKey;string;constructor(e){this.type=e.type,this.multihash=e.multihash,Object.defineProperty(this,"string",{enumerable:!1,writable:!0})}get[Symbol.toStringTag](){return`PeerId(${this.toString()})`}[Qu]=!0;toString(){return this.string==null&&(this.string=ke.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return Q.createV1(lB,this.multihash)}toJSON(){return this.toString()}equals(e){if(e==null)return!1;if(e instanceof Uint8Array)return ce(this.multihash.bytes,e);if(typeof e=="string")return this.toString()===e;if(e?.toMultihash()?.bytes!=null)return ce(this.multihash.bytes,e.toMultihash().bytes);throw new Error("not valid Id")}[h1](){return`PeerId(${this.toString()})`}},bc=class extends wc{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}},xc=class extends wc{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.publicKey}},Ec=class extends wc{type="secp256k1";publicKey;constructor(e){super({...e,type:"secp256k1"}),this.publicKey=e.publicKey}},fB=2336,vc=class{type="url";multihash;publicKey;url;constructor(e){this.url=e.toString(),this.multihash=Ve.digest(L(this.url))}[h1](){return`PeerId(${this.url})`}[Qu]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return Q.createV1(fB,this.toMultihash())}toJSON(){return this.toString()}equals(e){return e==null?!1:(e instanceof Uint8Array&&(e=j(e)),e.toString()===this.toString())}};var dB=114,p1=2336;function lr(r,e){let t;if(r.charAt(0)==="1"||r.charAt(0)==="Q")t=Ct(ke.decode(`z${r}`));else{if(r.startsWith("k51qzi5uqu5")||r.startsWith("kzwfwjn5ji4")||r.startsWith("k2k4r8")||r.startsWith("bafz"))return Bn(Q.parse(r));if(e==null)throw new T('Please pass a multibase decoder for strings that do not start with "1" or "Q"');t=Ct(e.decode(r))}return po(t)}function My(r){if(r.type==="Ed25519")return new xc({multihash:r.toCID().multihash,publicKey:r});if(r.type==="secp256k1")return new Ec({multihash:r.toCID().multihash,publicKey:r});if(r.type==="RSA")return new bc({multihash:r.toCID().multihash,publicKey:r});throw new Sr}function m1(r){return My(r.publicKey)}function po(r){if(pB(r))return new bc({multihash:r});if(hB(r))try{let e=Pl(r);if(e.type==="Ed25519")return new xc({multihash:r,publicKey:e});if(e.type==="secp256k1")return new Ec({multihash:r,publicKey:e})}catch{let t=j(r.digest);return new vc(new URL(t))}throw new Wn("Supplied PeerID Multihash is invalid")}function Bn(r){if(r?.multihash==null||r.version==null||r.version===1&&r.code!==dB&&r.code!==p1)throw new ju("Supplied PeerID CID is invalid");if(r.code===p1){let e=j(r.multihash.digest);return new vc(new URL(e))}return po(r.multihash)}function hB(r){return r.code===Ve.code}function pB(r){return r.code===Ir.code}function mi(r,e){let t={[Symbol.iterator]:()=>t,next:()=>{let n=r.next(),o=n.value;return n.done===!0||o==null?{done:!0,value:void 0}:{done:!1,value:e(o)}}};return t}function gf(r){let e=Ct(ke.decode(`z${r}`));return po(e)}var fr=class{map;constructor(e){if(this.map=new Map,e!=null)for(let[t,n]of e.entries())this.map.set(t.toString(),{key:t,value:n})}[Symbol.iterator](){return this.entries()}clear(){this.map.clear()}delete(e){return this.map.delete(e.toString())}entries(){return mi(this.map.entries(),e=>[e[1].key,e[1].value])}forEach(e){this.map.forEach((t,n)=>{e(t.value,t.key,this)})}get(e){return this.map.get(e.toString())?.value}has(e){return this.map.has(e.toString())}set(e,t){this.map.set(e.toString(),{key:e,value:t})}keys(){return mi(this.map.values(),e=>e.key)}values(){return mi(this.map.values(),e=>e.value)}get size(){return this.map.size}};var gi=class r{set;constructor(e){if(this.set=new Set,e!=null)for(let t of e)this.set.add(t.toString())}get size(){return this.set.size}[Symbol.iterator](){return this.values()}add(e){this.set.add(e.toString())}clear(){this.set.clear()}delete(e){this.set.delete(e.toString())}entries(){return mi(this.set.entries(),e=>{let t=gf(e[0]);return[t,t]})}forEach(e){this.set.forEach(t=>{let n=gf(t);e(n,n,this)})}has(e){return this.set.has(e.toString())}values(){return mi(this.set.values(),e=>gf(e))}intersection(e){let t=new r;for(let n of e)this.has(n)&&t.add(n);return t}difference(e){let t=new r;for(let n of this)e.has(n)||t.add(n);return t}union(e){let t=new r;for(let n of e)t.add(n);for(let n of this)t.add(n);return t}};var Fy=class extends fr{metric;constructor(e){super();let{name:t,metrics:n}=e;this.metric=n.registerMetric(t),this.updateComponentMetric()}set(e,t){return super.set(e,t),this.updateComponentMetric(),this}delete(e){let t=super.delete(e);return this.updateComponentMetric(),t}clear(){super.clear(),this.updateComponentMetric()}updateComponentMetric(){this.metric.update(this.size)}};function $y(r){let{name:e,metrics:t}=r,n;return t!=null?n=new Fy({name:e,metrics:t}):n=new fr,n}function mB(r){return r[Symbol.asyncIterator]!=null}function gB(r){if(mB(r))return(async()=>{let n=new Uint8Array(0);for await(let o of r)n=je([n,o],n.length+o.length);return n})();let e=[],t=0;for(let n of r)e.push(n),t+=n.byteLength;return je(e,t)}var g1=gB;var yf=class extends AggregateError{static name="DNSQueryFailedError";name="DNSQueryFailedError"};var Ky=Ro(w1(),1);function qy(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 Ps=class{#e=[];enqueue(e,t){let{priority:n=0,id:o}=t??{},i={priority:n,id:o,run:e};if(this.size===0||this.#e[this.size-1].priority>=n){this.#e.push(i);return}let s=qy(this.#e,i,(a,c)=>c.priority-a.priority);this.#e.splice(s,0,i)}setPriority(e,t){let n=this.#e.findIndex(i=>i.id===e);if(n===-1)throw new ReferenceError(`No promise function with the id "${e}" exists in the queue.`);let[o]=this.#e.splice(n,1);this.enqueue(o.run,{priority:t,id:e})}remove(e){let t=this.#e.findIndex(n=>typeof e=="string"?n.id===e:n.run===e);t!==-1&&this.#e.splice(t,1)}dequeue(){return this.#e.shift()?.run}filter(e){return this.#e.filter(t=>t.priority===e.priority).map(t=>t.run)}get size(){return this.#e.length}};var yi=class extends Ky.default{#e;#t;#r=0;#a;#c=!1;#m=!1;#l;#I=0;#x=0;#f;#d;#u;#s=[];#i=0;#n;#T;#o=0;#y;#h;#L=1n;#w=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:Ps,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.#a=e.intervalCap,this.#l=e.interval,this.#u=e.strict,this.#n=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.#V()}#v(e){for(;this.#i<this.#s.length;){let n=this.#s[this.#i];if(n!==void 0&&e-n>=this.#l)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)}#D(e){this.#u?this.#s.push(e):this.#r++}#R(){this.#u?this.#s.length>this.#i&&this.#s.pop():this.#r>0&&this.#r--}#A(){return this.#s.length-this.#i}get#U(){return this.#t?!0:this.#u?this.#A()<this.#a:this.#r<this.#a}get#O(){return this.#o<this.#y}#M(){this.#o--,this.#o===0&&this.emit("pendingZero"),this.#b(),this.emit("next")}#F(){this.#d=void 0,this.#N(),this.#B()}#$(e){if(this.#u){if(this.#v(e),this.#A()>=this.#a){let n=this.#s[this.#i],o=this.#l-(e-n);return this.#S(o),!0}return!1}if(this.#f===void 0){let t=this.#I-e;if(t<0){if(this.#x>0){let n=e-this.#x;if(n<this.#l)return this.#S(this.#l-n),!0}this.#r=this.#e?this.#o:0}else return this.#S(t),!0}return!1}#S(e){this.#d===void 0&&(this.#d=setTimeout(()=>{this.#F()},e))}#k(){this.#f&&(clearInterval(this.#f),this.#f=void 0)}#C(){this.#d&&(clearTimeout(this.#d),this.#d=void 0)}#b(){if(this.#n.size===0){if(this.#k(),this.emit("empty"),this.#o===0){if(this.#C(),this.#u&&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 o=this.#n.dequeue();this.#t||(this.#D(t),this.#g()),this.emit("active"),o(),n&&this.#B(),e=!0}}return e}#B(){this.#t||this.#f!==void 0||this.#u||(this.#f=setInterval(()=>{this.#N()},this.#l),this.#I=Date.now()+this.#l)}#N(){this.#u||(this.#r===0&&this.#o===0&&this.#f&&this.#k(),this.#r=this.#e?this.#o:0),this.#_(),this.#g()}#_(){for(;this.#b(););}get concurrency(){return this.#y}set concurrency(e){if(!(typeof e=="number"&&e>=1))throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${e}\` (${typeof e})`);this.#y=e,this.#_()}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.#n.setPriority(e,t)}async add(e,t={}){return t={timeout:this.timeout,...t,id:t.id??(this.#L++).toString()},new Promise((n,o)=>{let i=Symbol(`task-${t.id}`),s=()=>{},a=async()=>{s(),this.#o++,this.#w.set(i,{id:t.id,priority:t.priority??0,startTime:Date.now(),timeout:t.timeout});let u;try{try{t.signal?.throwIfAborted()}catch(d){throw this.#K(),this.#w.delete(i),d}this.#x=Date.now();let l=e({signal:t.signal});if(t.timeout&&(l=ui(Promise.resolve(l),{milliseconds:t.timeout,message:`Task timed out after ${t.timeout}ms (queue has ${this.#o} running, ${this.#n.size} waiting)`})),t.signal){let{signal:d}=t;l=Promise.race([l,new Promise((h,m)=>{u=()=>{m(d.reason)},d.addEventListener("abort",u,{once:!0})})])}let f=await l;n(f),this.emit("completed",f)}catch(l){o(l),this.emit("error",l)}finally{u&&t.signal?.removeEventListener("abort",u),this.#w.delete(i),queueMicrotask(()=>{this.#M()})}};this.#n.enqueue(a,t);let c=()=>{if(this.#n instanceof Ps){this.#n.remove(a);return}this.#n.remove?.(t.id)};if(t.signal){let{signal:u}=t,l=()=>{s(),c(),o(u.reason),this.#b(),this.emit("next")};if(s=()=>{u.removeEventListener("abort",l),this.#E.delete(s)},u.aborted){l();return}u.addEventListener("abort",l,{once:!0}),this.#E.add(s)}this.emit("add"),this.#b()})}async addAll(e,t){return Promise.all(e.map(async n=>this.add(n,t)))}start(){return this.#h?(this.#h=!1,this.#_(),this):this}pause(){this.#h=!0}clear(){for(let e of this.#E)e();this.#n=new this.#T,this.#k(),this.#P(),this.emit("empty"),this.#o===0&&(this.#C(),this.emit("idle")),this.emit("next")}async onEmpty(){this.#n.size!==0&&await this.#p("empty")}async onSizeLessThan(e){this.#n.size<e||await this.#p("next",()=>this.#n.size<e)}async onIdle(){this.#o===0&&this.#n.size===0||await this.#p("idle")}async onPendingZero(){this.#o!==0&&await this.#p("pendingZero")}async onRateLimit(){this.isRateLimited||await this.#p("rateLimit")}async onRateLimitCleared(){this.isRateLimited&&await this.#p("rateLimitCleared")}onError(){return new Promise((e,t)=>{let n=o=>{this.off("error",n),t(o)};this.on("error",n)})}async#p(e,t){return new Promise(n=>{let o=()=>{t&&!t()||(this.off(e,o),n())};this.on(e,o)})}get size(){return this.#n.size}sizeBy(e){return this.#n.filter(e).length}get pending(){return this.#o}get isPaused(){return this.#h}#V(){this.#t||(this.on("add",()=>{this.#n.size>0&&this.#g()}),this.on("next",()=>{this.#g()}))}#g(){this.#t||this.#m||(this.#m=!0,queueMicrotask(()=>{this.#m=!1,this.#P()}))}#K(){this.#t||(this.#R(),this.#g())}#P(){let e=this.#c;if(this.#t||this.#n.size===0){e&&(this.#c=!1,this.emit("rateLimitCleared"));return}let t;if(this.#u){let o=Date.now();this.#v(o),t=this.#A()}else t=this.#r;let n=t>=this.#a;n!==e&&(this.#c=n,this.emit(n?"rateLimit":"rateLimitCleared"))}get isRateLimited(){return this.#c}get isSaturated(){return this.#o===this.#y&&this.#n.size>0||this.isRateLimited&&this.#n.size>0}get runningTasks(){return[...this.#w.values()].map(e=>({...e}))}};function bf(r){let e=[$t.A];return r==null?e:Array.isArray(r)?r.length===0?e:r:[r]}var Hy=60;function xf(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:$t[e.type]})),Answer:(r.Answer??r.answers??[]).map(e=>({name:e.name,type:$t[e.type],TTL:e.TTL??e.ttl??Hy,data:e.data instanceof Uint8Array?j(e.data):e.data}))}}var bB=4;function zy(r,e={}){let t=new yi({concurrency:e.queryConcurrency??bB});return async(n,o={})=>{let i=o?.logger?.forComponent("dns:dns-json-over-https"),s=new URLSearchParams;s.set("name",n),bf(o.types).forEach(c=>{s.append("type",$t[c])}),o.onProgress?.(new $("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 u=xf(await c.json());return o.onProgress?.(new $("dns:response",u)),u},{signal:o.signal});if(a==null)throw new Error("No DNS response received");return a}}function b1(){return[zy("https://cloudflare-dns.com/dns-query"),zy("https://dns.google/resolve")]}var v1=Ro(E1(),1);var jy=class{lru;constructor(e){this.lru=(0,v1.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 xf({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:$t[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??Hy)*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 A1(r){return new jy(r)}var xB=1e3,Ef=class{resolvers;cache;logger;constructor(e){this.resolvers={},this.cache=A1(e.cacheSize??xB),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["."]=b1())}async query(e,t={}){let n=bf(t.types),o=t.cached!==!1?this.cache.get(e,n):void 0;if(o!=null)return t.onProgress?.(new $("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 u=await c(e,{...t,logger:this.logger,types:n});for(let l of u.Answer)this.cache.add(e,l);return u}catch(u){a.push(u),t.onProgress?.(new $("dns:error",u))}}throw new yf(a,`DNS lookup of ${e} ${n} failed`)}};var $t;(function(r){r[r.A=1]="A",r[r.CNAME=5]="CNAME",r[r.TXT=16]="TXT",r[r.AAAA=28]="AAAA"})($t||($t={}));function vf(r={}){return new Ef(r)}var EB=["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 Gy(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=vB(r);return t||"Object"}function vB(r){let e=Object.prototype.toString.call(r).slice(8,-1);if(EB.includes(e))return e}var E=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}};E.uint=new E(0,"uint",!0);E.negint=new E(1,"negint",!0);E.bytes=new E(2,"bytes",!0);E.string=new E(3,"string",!0);E.array=new E(4,"array",!1);E.map=new E(5,"map",!1);E.tag=new E(6,"tag",!1);E.float=new E(7,"float",!0);E.false=new E(7,"false",!0);E.true=new E(7,"true",!0);E.null=new E(7,"null",!0);E.undefined=new E(7,"undefined",!0);E.break=new E(7,"break",!0);var z=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 Sc=globalThis.process&&!globalThis.process.browser&&globalThis.Buffer&&typeof globalThis.Buffer.isBuffer=="function",AB=new TextEncoder;function Af(r){return Sc&&globalThis.Buffer.isBuffer(r)}function kc(r){return r instanceof Uint8Array?Af(r)?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):r:Uint8Array.from(r)}var SB=24,kB=200,Sf=Sc?r=>r.length>=SB?globalThis.Buffer.from(r):S1(r):r=>r.length>=kB?AB.encode(r):S1(r),hn=r=>Uint8Array.from(r),k1=Sc?(r,e,t)=>Af(r)?new Uint8Array(r.subarray(e,t)):r.slice(e,t):(r,e,t)=>r.slice(e,t),_1=Sc?(r,e)=>(r=r.map(t=>t instanceof Uint8Array?t:globalThis.Buffer.from(t)),kc(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},I1=Sc?r=>globalThis.Buffer.allocUnsafe(r):r=>new Uint8Array(r);function kf(r,e){if(Af(r)&&Af(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 S1(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 _B=256,_c=class{constructor(e=_B){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=I1(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=k1(n,0,this.cursor)}else t=_1(this.chunks,this.cursor);return e&&this.reset(),t}},_f=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 te="CBOR decode error:",If="CBOR encode error:",Ic=[];Ic[23]=1;Ic[24]=2;Ic[25]=3;Ic[26]=5;Ic[27]=9;function Nn(r,e,t){if(r.length-e<t)throw new Error(`${te} not enough data for type`)}var et=[24,256,65536,4294967296,BigInt("18446744073709551616")];function Vt(r,e,t){Nn(r,e,1);let n=r[e];if(t.strict===!0&&n<et[0])throw new Error(`${te} integer encoded in more bytes than necessary (strict decode)`);return n}function Kt(r,e,t){Nn(r,e,2);let n=r[e]<<8|r[e+1];if(t.strict===!0&&n<et[1])throw new Error(`${te} integer encoded in more bytes than necessary (strict decode)`);return n}function qt(r,e,t){Nn(r,e,4);let n=r[e]*16777216+(r[e+1]<<16)+(r[e+2]<<8)+r[e+3];if(t.strict===!0&&n<et[2])throw new Error(`${te} integer encoded in more bytes than necessary (strict decode)`);return n}function Ht(r,e,t){Nn(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<et[3])throw new Error(`${te} 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(`${te} integers outside of the safe integer range are not supported`)}function T1(r,e,t,n){return new z(E.uint,Vt(r,e+1,n),2)}function C1(r,e,t,n){return new z(E.uint,Kt(r,e+1,n),3)}function B1(r,e,t,n){return new z(E.uint,qt(r,e+1,n),5)}function N1(r,e,t,n){return new z(E.uint,Ht(r,e+1,n),9)}function dr(r,e){return Te(r,0,e.value)}function Te(r,e,t){if(t<et[0]){let n=Number(t);r.push([e|n])}else if(t<et[1]){let n=Number(t);r.push([e|24,n])}else if(t<et[2]){let n=Number(t);r.push([e|25,n>>>8,n&255])}else if(t<et[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<et[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(`${te} encountered BigInt larger than allowable range`)}}dr.encodedSize=function(e){return Te.encodedSize(e.value)};Te.encodedSize=function(e){return e<et[0]?1:e<et[1]?2:e<et[2]?3:e<et[3]?5:9};dr.compareTokens=function(e,t){return e.value<t.value?-1:e.value>t.value?1:0};function P1(r,e,t,n){return new z(E.negint,-1-Vt(r,e+1,n),2)}function L1(r,e,t,n){return new z(E.negint,-1-Kt(r,e+1,n),3)}function D1(r,e,t,n){return new z(E.negint,-1-qt(r,e+1,n),5)}var Wy=BigInt(-1),R1=BigInt(1);function U1(r,e,t,n){let o=Ht(r,e+1,n);if(typeof o!="bigint"){let i=-1-o;if(i>=Number.MIN_SAFE_INTEGER)return new z(E.negint,i,9)}if(n.allowBigInt!==!0)throw new Error(`${te} integers outside of the safe integer range are not supported`);return new z(E.negint,Wy-BigInt(o),9)}function Tf(r,e){let t=e.value,n=typeof t=="bigint"?t*Wy-R1:t*-1-1;Te(r,e.type.majorEncoded,n)}Tf.encodedSize=function(e){let t=e.value,n=typeof t=="bigint"?t*Wy-R1:t*-1-1;return n<et[0]?1:n<et[1]?2:n<et[2]?3:n<et[3]?5:9};Tf.compareTokens=function(e,t){return e.value<t.value?1:e.value>t.value?-1:0};function Tc(r,e,t,n){Nn(r,e,t+n);let o=r.slice(e+t,e+t+n);return new z(E.bytes,o,t+n)}function O1(r,e,t,n){return Tc(r,e,1,t)}function M1(r,e,t,n){return Tc(r,e,2,Vt(r,e+1,n))}function F1(r,e,t,n){return Tc(r,e,3,Kt(r,e+1,n))}function $1(r,e,t,n){return Tc(r,e,5,qt(r,e+1,n))}function V1(r,e,t,n){let o=Ht(r,e+1,n);if(typeof o=="bigint")throw new Error(`${te} 64-bit integer bytes lengths not supported`);return Tc(r,e,9,o)}function Cf(r){return r.encodedBytes===void 0&&(r.encodedBytes=E.equals(r.type,E.string)?Sf(r.value):r.value),r.encodedBytes}function Ls(r,e){let t=Cf(e);Te(r,e.type.majorEncoded,t.length),r.push(t)}Ls.encodedSize=function(e){let t=Cf(e);return Te.encodedSize(t.length)+t.length};Ls.compareTokens=function(e,t){return TB(Cf(e),Cf(t))};function TB(r,e){return r.length<e.length?-1:r.length>e.length?1:kf(r,e)}var K1=new TextDecoder,BB=32;function NB(r,e,t){if(t-e<BB){let o="";for(let i=e;i<t;i++){let s=r[i];if(s&128)return K1.decode(r.subarray(e,t));o+=String.fromCharCode(s)}return o}return K1.decode(r.subarray(e,t))}function Cc(r,e,t,n,o){let i=t+n;Nn(r,e,i);let s=new z(E.string,NB(r,e+t,e+i),i);return o.retainStringBytes===!0&&(s.byteValue=r.slice(e+t,e+i)),s}function q1(r,e,t,n){return Cc(r,e,1,t,n)}function H1(r,e,t,n){return Cc(r,e,2,Vt(r,e+1,n),n)}function z1(r,e,t,n){return Cc(r,e,3,Kt(r,e+1,n),n)}function j1(r,e,t,n){return Cc(r,e,5,qt(r,e+1,n),n)}function G1(r,e,t,n){let o=Ht(r,e+1,n);if(typeof o=="bigint")throw new Error(`${te} 64-bit integer string lengths not supported`);return Cc(r,e,9,o,n)}var W1=Ls;function Ds(r,e,t,n){return new z(E.array,n,t)}function Y1(r,e,t,n){return Ds(r,e,1,t)}function X1(r,e,t,n){return Ds(r,e,2,Vt(r,e+1,n))}function Z1(r,e,t,n){return Ds(r,e,3,Kt(r,e+1,n))}function J1(r,e,t,n){return Ds(r,e,5,qt(r,e+1,n))}function Q1(r,e,t,n){let o=Ht(r,e+1,n);if(typeof o=="bigint")throw new Error(`${te} 64-bit integer array lengths not supported`);return Ds(r,e,9,o)}function ev(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${te} indefinite length items not allowed`);return Ds(r,e,1,1/0)}function Bf(r,e){Te(r,E.array.majorEncoded,e.value)}Bf.compareTokens=dr.compareTokens;Bf.encodedSize=function(e){return Te.encodedSize(e.value)};function Rs(r,e,t,n){return new z(E.map,n,t)}function tv(r,e,t,n){return Rs(r,e,1,t)}function rv(r,e,t,n){return Rs(r,e,2,Vt(r,e+1,n))}function nv(r,e,t,n){return Rs(r,e,3,Kt(r,e+1,n))}function ov(r,e,t,n){return Rs(r,e,5,qt(r,e+1,n))}function iv(r,e,t,n){let o=Ht(r,e+1,n);if(typeof o=="bigint")throw new Error(`${te} 64-bit integer map lengths not supported`);return Rs(r,e,9,o)}function sv(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${te} indefinite length items not allowed`);return Rs(r,e,1,1/0)}function Nf(r,e){Te(r,E.map.majorEncoded,e.value)}Nf.compareTokens=dr.compareTokens;Nf.encodedSize=function(e){return Te.encodedSize(e.value)};function av(r,e,t,n){return new z(E.tag,t,1)}function cv(r,e,t,n){return new z(E.tag,Vt(r,e+1,n),2)}function uv(r,e,t,n){return new z(E.tag,Kt(r,e+1,n),3)}function lv(r,e,t,n){return new z(E.tag,qt(r,e+1,n),5)}function fv(r,e,t,n){return new z(E.tag,Ht(r,e+1,n),9)}function Pf(r,e){Te(r,E.tag.majorEncoded,e.value)}Pf.compareTokens=dr.compareTokens;Pf.encodedSize=function(e){return Te.encodedSize(e.value)};var Yy=20,Xy=21,Zy=22,Jy=23;function dv(r,e,t,n){if(n.allowUndefined===!1)throw new Error(`${te} undefined values are not supported`);return n.coerceUndefinedToNull===!0?new z(E.null,null,1):new z(E.undefined,void 0,1)}function hv(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${te} indefinite length items not allowed`);return new z(E.break,void 0,1)}function Qy(r,e,t){if(t){if(t.allowNaN===!1&&Number.isNaN(r))throw new Error(`${te} NaN values are not supported`);if(t.allowInfinity===!1&&(r===1/0||r===-1/0))throw new Error(`${te} Infinity values are not supported`)}return new z(E.float,r,e)}function pv(r,e,t,n){return Qy(e0(r,e+1),3,n)}function mv(r,e,t,n){return Qy(t0(r,e+1),5,n)}function gv(r,e,t,n){return Qy(xv(r,e+1),9,n)}function Bc(r,e,t){let n=e.value;if(n===!1)r.push([E.float.majorEncoded|Yy]);else if(n===!0)r.push([E.float.majorEncoded|Xy]);else if(n===null)r.push([E.float.majorEncoded|Zy]);else if(n===void 0)r.push([E.float.majorEncoded|Jy]);else{let o,i=!1;(!t||t.float64!==!0)&&(wv(n),o=e0(Kr,1),n===o||Number.isNaN(n)?(Kr[0]=249,r.push(Kr.slice(0,3)),i=!0):(bv(n),o=t0(Kr,1),n===o&&(Kr[0]=250,r.push(Kr.slice(0,5)),i=!0))),i||(UB(n),o=xv(Kr,1),Kr[0]=251,r.push(Kr.slice(0,9)))}}Bc.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){wv(n);let o=e0(Kr,1);if(n===o||Number.isNaN(n))return 3;if(bv(n),o=t0(Kr,1),n===o)return 5}return 9};var yv=new ArrayBuffer(9),hr=new DataView(yv,1),Kr=new Uint8Array(yv,0);function wv(r){if(r===1/0)hr.setUint16(0,31744,!1);else if(r===-1/0)hr.setUint16(0,64512,!1);else if(Number.isNaN(r))hr.setUint16(0,32256,!1);else{hr.setFloat32(0,r);let e=hr.getUint32(0),t=(e&2139095040)>>23,n=e&8388607;if(t===255)hr.setUint16(0,31744,!1);else if(t===0)hr.setUint16(0,(e&2147483648)>>16|n>>13,!1);else{let o=t-127;o<-24?hr.setUint16(0,0):o<-14?hr.setUint16(0,(e&2147483648)>>16|1<<24+o,!1):hr.setUint16(0,(e&2147483648)>>16|o+15<<10|n>>13,!1)}}}function e0(r,e){if(r.length-e<2)throw new Error(`${te} 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 bv(r){hr.setFloat32(0,r,!1)}function t0(r,e){if(r.length-e<4)throw new Error(`${te} not enough data for float32`);let t=(r.byteOffset||0)+e;return new DataView(r.buffer,t,4).getFloat32(0,!1)}function UB(r){hr.setFloat64(0,r,!1)}function xv(r,e){if(r.length-e<8)throw new Error(`${te} not enough data for float64`);let t=(r.byteOffset||0)+e;return new DataView(r.buffer,t,8).getFloat64(0,!1)}Bc.compareTokens=dr.compareTokens;function ye(r,e,t){throw new Error(`${te} encountered invalid minor (${t}) for major ${r[e]>>>5}`)}function Lf(r){return()=>{throw new Error(`${te} ${r}`)}}var R=[];for(let r=0;r<=23;r++)R[r]=ye;R[24]=T1;R[25]=C1;R[26]=B1;R[27]=N1;R[28]=ye;R[29]=ye;R[30]=ye;R[31]=ye;for(let r=32;r<=55;r++)R[r]=ye;R[56]=P1;R[57]=L1;R[58]=D1;R[59]=U1;R[60]=ye;R[61]=ye;R[62]=ye;R[63]=ye;for(let r=64;r<=87;r++)R[r]=O1;R[88]=M1;R[89]=F1;R[90]=$1;R[91]=V1;R[92]=ye;R[93]=ye;R[94]=ye;R[95]=Lf("indefinite length bytes/strings are not supported");for(let r=96;r<=119;r++)R[r]=q1;R[120]=H1;R[121]=z1;R[122]=j1;R[123]=G1;R[124]=ye;R[125]=ye;R[126]=ye;R[127]=Lf("indefinite length bytes/strings are not supported");for(let r=128;r<=151;r++)R[r]=Y1;R[152]=X1;R[153]=Z1;R[154]=J1;R[155]=Q1;R[156]=ye;R[157]=ye;R[158]=ye;R[159]=ev;for(let r=160;r<=183;r++)R[r]=tv;R[184]=rv;R[185]=nv;R[186]=ov;R[187]=iv;R[188]=ye;R[189]=ye;R[190]=ye;R[191]=sv;for(let r=192;r<=215;r++)R[r]=av;R[216]=cv;R[217]=uv;R[218]=lv;R[219]=fv;R[220]=ye;R[221]=ye;R[222]=ye;R[223]=ye;for(let r=224;r<=243;r++)R[r]=Lf("simple values are not supported");R[244]=ye;R[245]=ye;R[246]=ye;R[247]=dv;R[248]=Lf("simple values are not supported");R[249]=pv;R[250]=mv;R[251]=gv;R[252]=ye;R[253]=ye;R[254]=ye;R[255]=hv;var qr=[];for(let r=0;r<24;r++)qr[r]=new z(E.uint,r,1);for(let r=-1;r>=-24;r--)qr[31-r]=new z(E.negint,r,1);qr[64]=new z(E.bytes,new Uint8Array(0),1);qr[96]=new z(E.string,"",1);qr[128]=new z(E.array,0,1);qr[160]=new z(E.map,0,1);qr[244]=new z(E.false,!1,1);qr[245]=new z(E.true,!0,1);qr[246]=new z(E.null,null,1);function r0(r){switch(r.type){case E.false:return hn([244]);case E.true:return hn([245]);case E.null:return hn([246]);case E.bytes:return r.value.length?void 0:hn([64]);case E.string:return r.value===""?hn([96]):void 0;case E.array:return r.value===0?hn([128]):void 0;case E.map:return r.value===0?hn([160]):void 0;case E.uint:return r.value<24?hn([Number(r.value)]):void 0;case E.negint:if(r.value>=-24)return hn([31-Number(r.value)])}}var MB={float64:!1,mapSorter:VB,quickEncodeToken:r0},kv=Object.freeze({float64:!0,mapSorter:KB,quickEncodeToken:r0});function FB(){let r=[];return r[E.uint.major]=dr,r[E.negint.major]=Tf,r[E.bytes.major]=Ls,r[E.string.major]=W1,r[E.array.major]=Bf,r[E.map.major]=Nf,r[E.tag.major]=Pf,r[E.float.major]=Bc,r}var Os=FB(),Df=new _c,Pc=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(`${If} object contains circular references`);return new r(t,e)}},mo={null:new z(E.null,null),undefined:new z(E.undefined,void 0),true:new z(E.true,!0),false:new z(E.false,!1),emptyArray:new z(E.array,0),emptyMap:new z(E.map,0)},pn={number(r,e,t,n){return!Number.isInteger(r)||!Number.isSafeInteger(r)?new z(E.float,r):r>=0?new z(E.uint,r):new z(E.negint,r)},bigint(r,e,t,n){return r>=BigInt(0)?new z(E.uint,r):new z(E.negint,r)},Uint8Array(r,e,t,n){return new z(E.bytes,r)},string(r,e,t,n){return new z(E.string,r)},boolean(r,e,t,n){return r?mo.true:mo.false},null(r,e,t,n){return mo.null},undefined(r,e,t,n){return mo.undefined},ArrayBuffer(r,e,t,n){return new z(E.bytes,new Uint8Array(r))},DataView(r,e,t,n){return new z(E.bytes,new Uint8Array(r.buffer,r.byteOffset,r.byteLength))},Array(r,e,t,n){if(!r.length)return t.addBreakTokens===!0?[mo.emptyArray,new z(E.break)]:mo.emptyArray;n=Pc.createCheck(n,r);let o=[],i=0;for(let s of r)o[i++]=Us(s,t,n);return t.addBreakTokens?[new z(E.array,r.length),o,new z(E.break)]:[new z(E.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=Pc.createCheck(n,r);let c=!o&&t.ignoreUndefinedProperties,u=0;for(let l of i){let f=o?r.get(l):r[l];c&&f===void 0||(a[u++]=[Us(l,t,n),Us(f,t,n)])}u<s&&(a.length=u)}return a?.length?($B(a,t),t.addBreakTokens?[new z(E.map,a.length),a,new z(E.break)]:[new z(E.map,a.length),a]):t.addBreakTokens===!0?[mo.emptyMap,new z(E.break)]:mo.emptyMap},Tagged(r,e,t,n){return[new z(E.tag,r.tag),Us(r.value,t,n)]}};pn.Map=pn.Object;pn.Buffer=pn.Uint8Array;for(let r of"Uint8Clamped Uint16 Uint32 Int8 Int16 Int32 BigUint64 BigInt64 Float32 Float64".split(" "))pn[`${r}Array`]=pn.DataView;function Us(r,e={},t){let n=Gy(r),o=e&&e.typeEncoders&&e.typeEncoders[n]||pn[n];if(typeof o=="function"){let s=o(r,n,e,t);if(s!=null)return s}let i=pn[n];if(!i)throw new Error(`${If} unsupported type: ${n}`);return i(r,n,e,t)}function $B(r,e){e.mapSorter&&r.sort(e.mapSorter)}function VB(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=Os[o].compareTokens(t,n);return i===0&&console.warn("WARNING: complex key types used, CBOR key sorting guarantees are gone"),i}function KB(r,e){if(r[0]instanceof z&&e[0]instanceof z){let t=r[0],n=e[0];return t._keyBytes||(t._keyBytes=Ev(t.value)),n._keyBytes||(n._keyBytes=Ev(n.value)),kf(t._keyBytes,n._keyBytes)}throw new Error("rfc8949MapSorter: complex key types are not supported yet")}function Ev(r){return Iv(r,Os,kv)}function Nc(r,e,t,n){if(Array.isArray(e))for(let o of e)Nc(r,o,t,n);else t[e.type.major](r,e,n)}var vv=E.uint.majorEncoded,Av=E.negint.majorEncoded,qB=E.bytes.majorEncoded,HB=E.string.majorEncoded,Sv=E.array.majorEncoded,zB=E.float.majorEncoded|Yy,jB=E.float.majorEncoded|Xy,GB=E.float.majorEncoded|Zy,WB=E.float.majorEncoded|Jy,YB=BigInt(-1),XB=BigInt(1);function ZB(r){return r.addBreakTokens!==!0}function _v(r,e,t,n){let o=Gy(e),i=t.typeEncoders&&t.typeEncoders[o];if(i){let s=i(e,o,t,n);if(s!=null){Nc(r,s,Os,t);return}}switch(o){case"null":r.push([GB]);return;case"undefined":r.push([WB]);return;case"boolean":r.push([e?jB:zB]);return;case"number":!Number.isInteger(e)||!Number.isSafeInteger(e)?Bc(r,new z(E.float,e),t):e>=0?Te(r,vv,e):Te(r,Av,e*-1-1);return;case"bigint":e>=BigInt(0)?Te(r,vv,e):Te(r,Av,e*YB-XB);return;case"string":{let s=Sf(e);Te(r,HB,s.length),r.push(s);return}case"Uint8Array":Te(r,qB,e.length),r.push(e);return;case"Array":if(!e.length){r.push([Sv]);return}n=Pc.createCheck(n,e),Te(r,Sv,e.length);for(let s of e)_v(r,s,t,n);return;case"Object":case"Map":{let s=pn.Object(e,o,t,n);Nc(r,s,Os,t)}return;default:{let s=pn[o];if(!s)throw new Error(`${If} unsupported type: ${o}`);let a=s(e,o,t,n);Nc(r,a,Os,t)}}}function Iv(r,e,t,n){let o=n instanceof Uint8Array,i=o?new _f(n):Df,s=Us(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 u=c.encodedSize(s,t);if(o||(i=new _c(u)),c(i,s,t),i.chunks.length!==1)throw new Error(`Unexpected error: pre-calculated length for ${s} was wrong`);return o?i.toBytes():kc(i.chunks[0])}}return i.reset(),Nc(i,s,e,t),i.toBytes(!0)}function Lc(r,e){return e=Object.assign({},MB,e),ZB(e)?(Df.reset(),_v(Df,r,e,void 0),Df.toBytes(!0)):Iv(r,Os,e)}var JB={strict:!1,allowIndefinite:!0,allowUndefined:!0,allowBigInt:!0},Rf=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=qr[e];if(t===void 0){let n=R[e];if(!n)throw new Error(`${te} 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}},go=Symbol.for("DONE"),Ms=Symbol.for("BREAK");function QB(r,e,t){let n=[];for(let o=0;o<r.value;o++){let i=yo(e,t);if(i===Ms){if(r.value===1/0)break;throw new Error(`${te} got unexpected break to lengthed array`)}if(i===go)throw new Error(`${te} found array but not enough entries (got ${o}, expected ${r.value})`);n[o]=i}return n}function e4(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=yo(e,t);if(c===Ms){if(r.value===1/0)break;throw new Error(`${te} got unexpected break to lengthed map`)}if(c===go)throw new Error(`${te} found map but not enough entries (got ${a} [no key], expected ${r.value})`);if(!n&&typeof c!="string")throw new Error(`${te} non-string keys not supported (got ${typeof c})`);if(o&&(n&&s.has(c)||!n&&Object.hasOwn(i,c)))throw new Error(`${te} found repeat map key "${c}"`);let u=yo(e,t);if(u===go)throw new Error(`${te} found map but not enough entries (got ${a} [no value], expected ${r.value})`);n?s.set(c,u):i[c]=u}return n?s:i}function*t4(r,e,t){for(let n=0;n<r.value;n++){let o=yo(e,t);if(o===Ms){if(r.value===1/0)break;throw new Error(`${te} got unexpected break to lengthed map`)}if(o===go)throw new Error(`${te} found map but not enough entries (got ${n} [no key], expected ${r.value})`);let i=yo(e,t);if(i===go)throw new Error(`${te} found map but not enough entries (got ${n} [no value], expected ${r.value})`);yield[o,i]}}function r4(r,e){let t=!1,n=function(){if(t)throw new Error(`${te} tag decode() may only be called once`);t=!0;let o=yo(r,e);if(o===go)throw new Error(`${te} tag content missing`);if(o===Ms)throw new Error(`${te} got unexpected break in tag content`);return o};return n.entries=function(){if(t)throw new Error(`${te} tag decode() may only be called once`);t=!0;let o=r.next();if(!E.equals(o.type,E.map))throw new Error(`${te} entries() requires map content, got ${o.type.name}`);let i=[];for(let s of t4(o,r,e))i.push(s);return i},Object.defineProperty(n,"_called",{get(){return t},enumerable:!1}),n}function yo(r,e){if(r.done())return go;let t=r.next();if(E.equals(t.type,E.break))return Ms;if(t.type.terminal)return t.value;if(E.equals(t.type,E.array))return QB(t,r,e);if(E.equals(t.type,E.map))return e4(t,r,e);if(E.equals(t.type,E.tag)){if(e.tags&&typeof e.tags[t.value]=="function"){let n=r4(r,e),o=e.tags[t.value](n);if(!n._called)throw new Error(`${te} tag decoder must call decode() or entries()`);return o}throw new Error(`${te} tag not supported (${t.value})`)}throw new Error("unsupported")}function Tv(r,e){if(!(r instanceof Uint8Array))throw new Error(`${te} data to decode must be a Uint8Array`);e=Object.assign({},JB,e);let t=kc(r),n=e.tokenizer||new Rf(t,e),o=yo(n,e);if(o===go)throw new Error(`${te} did not find any content to decode`);if(o===Ms)throw new Error(`${te} got unexpected break`);return[o,r.subarray(n.pos())]}function bi(r,e){let[t,n]=Tv(r,e);if(n.length>0)throw new Error(`${te} too many terminals, data makes no sense`);return t}var Uf=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(Uf.prototype,Symbol.toStringTag,{value:"Tagged"});var Pn="/",Cv=new TextEncoder().encode(Pn),Of=Cv[0],Le=class r{_buf;constructor(e,t){if(typeof e=="string")this._buf=L(e);else if(e instanceof Uint8Array)this._buf=e;else throw new Error("Invalid key, should be String of Uint8Array");if(t==null&&(t=!0),t&&this.clean(),this._buf.byteLength===0||this._buf[0]!==Of)throw new Error("Invalid key")}toString(e="utf8"){return j(this._buf,e)}uint8Array(){return this._buf}get[Symbol.toStringTag](){return`Key(${this.toString()})`}static withNamespaces(e){return new r(e.join(Pn))}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=Cv),this._buf[0]!==Of){let e=new Uint8Array(this._buf.byteLength+1);e.fill(Of,0,1),e.set(this._buf,1),this._buf=e}for(;this._buf.byteLength>1&&this._buf[this._buf.byteLength-1]===Of;)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(Pn).slice(1)}type(){return o4(this.baseNamespace())}name(){return i4(this.baseNamespace())}instance(e){return new r(this.toString()+":"+e)}path(){let e=this.parent().toString();return e.endsWith(Pn)||(e+=Pn),e+=this.type(),new r(e)}parent(){let e=this.list();return e.length===1?new r(Pn):new r(e.slice(0,-1).join(Pn))}child(e){return this.toString()===Pn?e:e.toString()===Pn?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(),...s4(e.map(t=>t.namespaces()))])}};function o4(r){let e=r.split(":");return e.length<2?"":e.slice(0,-1).join(":")}function i4(r){let e=r.split(":");return e[e.length-1]}function s4(r){return[].concat(...r)}function Mf({enumerable:r=!0,configurable:e=!1}={}){return{enumerable:r,configurable:e,writable:!1}}function*a4(r,e){if(e!=null&&typeof e=="object")if(Array.isArray(e))for(let[t,n]of e.entries()){let o=[...r,t],i=Q.asCID(n);i!=null?yield[o.join("/"),i]:typeof n=="object"&&(yield*n0(n,o))}else{let t=Q.asCID(e);t!=null?yield[r.join("/"),t]:yield*n0(e,r)}}function*n0(r,e){if(r==null||r instanceof Uint8Array)return;let t=Q.asCID(r);t!=null&&(yield[e.join("/"),t]);for(let[n,o]of Object.entries(r)){let i=[...e,n];yield*a4(i,o)}}function*c4(r,e){if(Array.isArray(e))for(let[t,n]of e.entries()){let o=[...r,t];yield o.join("/"),typeof n=="object"&&Q.asCID(n)==null&&(yield*o0(n,o))}else yield*o0(e,r)}function*o0(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"&&Q.asCID(n)==null&&(yield*c4(o,n))}}function u4(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=Q.asCID(t);if(i!=null)return{value:i,remaining:e.slice(n+1).join("/")}}return{value:t}}var i0=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:Mf(),bytes:Mf(),value:Mf(),asBlock:Mf()})}links(){return n0(this.value,[])}tree(){return o0(this.value,[])}get(e="/"){return u4(this.value,e.split("/").filter(Boolean))}};function Bv({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 i0({cid:e,bytes:r,value:o})}var Ff=class extends Error{static name="AlreadyPinnedError";name="AlreadyPinnedError"},Dc=class extends Error{static name="BlockPinnedError";name="BlockPinnedError"},$f=class extends Error{static name="InvalidDatastoreVersionError";name="InvalidDatastoreVersionError"},xi=class extends Error{static name="InvalidConfigurationError";name="InvalidConfigurationError"},Vf=class extends AggregateError{static name="GetFailedError";name="GetFailedError"},Kf=class extends AggregateError{static name="LoadBlockFailedError";name="LoadBlockFailedError"},Rc=class extends Error{static name="BlockNotFoundWhileOfflineError";name="BlockNotFoundWhileOfflineError"};var Lv="/pin/",Nv="/pinned-block/",s0=on,Pv=1;function qf(r){return r.version===0&&(r=r.toV1()),new Le(`${Lv}${r.toString(s0)}`)}var Hf=class{datastore;blockstore;getCodec;constructor(e,t,n){this.datastore=e,this.blockstore=t,this.getCodec=n}async*add(e,t={}){let n=qf(e);if(await this.datastore.has(n))throw new Ff("Already pinned");let o=Math.round(t.depth??1/0);if(o<0)throw new T("Depth must be greater than or equal to 0");let i=new $r({concurrency:Pv});for await(let a of this.#e(e,i,{...t,depth:o}))await this.#t(a,c=>c.pinnedBy.find(u=>ce(u,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,Lc(s),t)}async*#e(e,t,n){if(n.depth===-1)return;let o=await this.getCodec(e.code),i=await g1(this.blockstore.get(e,n)),s=Bv({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 Le(`${Nv}${s0.encode(e.multihash.bytes)}`),i={pinCount:0,pinnedBy:[]};try{i=bi(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,Lc(i),n),n.onProgress?.(new $("helia:pin:add",e))}}async*rm(e,t={}){let n=qf(e),o=await this.datastore.get(n,t),i=bi(o);await this.datastore.delete(n,t);let s=new $r({concurrency:Pv});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(u=>ce(u,e.bytes)),!0),{...t,depth:i.depth}),yield a}async*ls(e={}){for await(let{key:t,value:n}of this.datastore.query({prefix:Lv+(e.cid!=null?`${e.cid.toString(on)}`:"")},e)){let o=Q.parse(t.toString().substring(5),on),i=bi(n);yield{cid:o,...i}}}async isPinned(e,t={}){let n=new Le(`${Nv}${s0.encode(e.multihash.bytes)}`);return this.datastore.has(n,t)}async get(e,t){let n=qf(e),o=await this.datastore.get(n,t);return bi(o)}async setMetadata(e,t,n){let o=qf(e),i=await this.datastore.get(o,n),s=bi(i);s.metadata=t??{},await this.datastore.put(o,Lc(s),n)}};var a0=1,c0=5,u0=100;var Uc=class extends Error{static name="InsufficientProvidersError";constructor(e="Insufficient providers found"){super(e),this.name="InsufficientProvidersError"}},wo=class extends Error{static name="NoRoutersAvailableError";constructor(e="No routers available"){super(e),this.name="NoRoutersAvailableError"}},Oc=class extends Error{static name="UnknownHashAlgorithmError";constructor(e="Unknown hash algorithm"){super(e),this.name="UnknownHashAlgorithmError"}},Mc=class extends Error{static name="UnknownCodecError";constructor(e="Unknown codec"){super(e),this.name="UnknownCodecError"}},l0=class extends Error{static name="InvalidCodecError";constructor(e="Invalid codec"){super(e),this.name="InvalidCodecError"}};var l4=5,zf=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??l4,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 rn(...this.routers)}async stop(){await nn(...this.routers)}async*findProviders(e,t={}){if(this.routers.length===0)throw new wo("No content routers available");let n=new Bs({concurrency:this.providerLookupConcurrency}),o=0,i=[],s=this,a=0;this.log("findProviders for %c start using routers %s",e,this.routers.map(u=>u.toString()).join(", "));let c=Ei(this.routers,"findProviders").map(async function*(u){let l=0;t?.onProgress?.(new $("helia:routing:find-providers:start",{routing:u.name,cid:e}));try{for await(let f of u.findProviders(e,t))l++,t?.onProgress?.(new $("helia:routing:find-providers:provider",{routing:u.name,cid:e,provider:f})),yield f}catch(f){i.push(f)}finally{s.log("router %s found %d providers for %c",u,l,e),t?.onProgress?.(new $("helia:routing:find-providers:end",{routing:u.name,cid:e,found:l})),a++,a===c.length&&n.size===0&&n.emitIdle()}});for await(let u of cr(n.toGenerator(),...c))if(u!=null){if(u.multiaddrs.length===0){if(n.find(u.id)!=null)continue;n.add(async()=>{try{let l=await this.findPeer(u.id,t);return l.multiaddrs.length===0?null:{...l,protocols:u.protocols,routing:u.routing}}catch(l){return this.log.error("could not load multiaddrs for peer %p - %e",u.id,l),null}},{peerId:u.id,signal:t.signal}).catch(l=>{this.log.error("could not load multiaddrs for peer %p - %e",u.id,l)});continue}o++,yield u}this.log("findProviders finished, found %d providers for %c",o,e)}async provide(e,t={}){if(this.routers.length===0)throw new wo("No content routers available");await Promise.all(Ei(this.routers,"provide").map(async n=>{t?.onProgress?.(new $("helia:routing:provide:start",{routing:n.name,cid:e})),await n.provide(e,t),t?.onProgress?.(new $("helia:routing:provide:end",{routing:n.name,cid:e}))}))}async cancelReprovide(e,t={}){await Promise.all(Ei(this.routers,"cancelReprovide").map(async n=>{t?.onProgress?.(new $("helia:routing:cancel-reprovide:start",{routing:n.name,cid:e})),await n.cancelReprovide(e,t),t?.onProgress?.(new $("helia:routing:cancel-reprovide:end",{routing:n.name,cid:e}))}))}async put(e,t,n){await Promise.all(Ei(this.routers,"put").map(async o=>{n?.onProgress?.(new $("helia:routing:put:start",{routing:o.name,key:e,value:t})),await o.put(e,t,n),n?.onProgress?.(new $("helia:routing:put:end",{routing:o.name,key:e,value:t}))}))}async get(e,t){let n=[],o;try{o=await Promise.any(Ei(this.routers,"get").map(async i=>{t?.onProgress?.(new $("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 $("helia:routing:get:end",{routing:i.name,key:e}))}}))}catch{}if(o==null)throw new Vf(n,`Failed to get value key ${j(e,"base58btc")}`);return o}async findPeer(e,t){if(this.routers.length===0)throw new wo("No peer routers available");let n=this,o=cr(...Ei(this.routers,"findPeer").map(i=>(async function*(){t?.onProgress?.(new $("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 $("helia:routing:find-peer:end",{routing:i.name,peerId:e}))}})()));for await(let i of o)if(i!=null)return i;throw new He("Could not find peer in routing")}async*getClosestPeers(e,t={}){if(this.routers.length===0)throw new wo("No peer routers available");for await(let n of cr(...Ei(this.routers,"getClosestPeers").map(async function*(o){t?.onProgress?.(new $("helia:routing:get-closest-peers:start",{routing:o.name,key:e}));try{yield*o.getClosestPeers(e,t)}finally{t?.onProgress?.(new $("helia:routing:get-closest-peers:end",{routing:o.name,key:e}))}})))n!=null&&(yield n)}};function Ei(r,e){return r.filter(t=>t[e]!=null)}var jf=class extends Error{static name="QueueFullError";constructor(e="The queue was full"){super(e),this.name="QueueFullError"}};var Gf=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 Ft)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function f4(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var Wf=class{id;fn;options;recipients;status;timeline;controller;constructor(e,t){this.id=f4(),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 Ft),this.cleanup())}async join(e={}){let t=new Gf(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 kt(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 f0(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 Fc=class extends ze{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=f0(this.emitEmpty.bind(this),1),this.emitIdle=f0(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 jf;let n=new Wf(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 Ft)}),this.clear()}async onEmpty(e){this.size!==0&&await mf(this,"empty",e?.signal)}async onSizeLessThan(e,t){this.size<e||await mf(this,"next",t?.signal,{filter:()=>this.size<e})}async onIdle(e){this.pending===0&&this.size===0||await mf(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=xs({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 Ft("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 Yf="lock:worker:request-read",Xf="lock:worker:abort-read-request",Zf="lock:worker:release-read",Jf="lock:master:grant-read",Qf="lock:master:error-read",ed="lock:worker:request-write",td="lock:worker:abort-write-request",rd="lock:worker:release-write",nd="lock:master:grant-write",od="lock:master:error-write",id="lock:worker:finalize",sd="mortice",Dv={singleProcess:!1};var d0=(r,e,t,n,o,i,s,a,c)=>u=>{if(u.data==null)return;let l={type:u.data.type,name:u.data.name,identifier:u.data.identifier};l.type===o&&r.safeDispatchEvent(t,{detail:{name:l.name,identifier:l.identifier,handler:async()=>{e.postMessage({type:c,name:l.name,identifier:l.identifier}),await new Promise(f=>{let d=h=>{if(h?.data==null)return;let m={type:h.data.type,name:h.data.name,identifier:h.data.identifier};m.type===a&&m.identifier===l.identifier&&(e.removeEventListener("message",d),f())};e.addEventListener("message",d)})},onError:f=>{e.postMessage({type:s,name:l.name,identifier:l.identifier,error:{message:f.message,name:f.name,stack:f.stack}})}}}),l.type===i&&r.safeDispatchEvent(n,{detail:{name:l.name,identifier:l.identifier}}),l.type===id&&r.safeDispatchEvent("finalizeRequest",{detail:{name:l.name}})};var Rv=(r=10)=>Math.random().toString().substring(2,r+2);var ad=class{name;channel;constructor(e){this.name=e,this.channel=new BroadcastChannel(sd)}readLock(e){return this.sendRequest(Yf,Xf,Jf,Qf,Zf,e)}writeLock(e){return this.sendRequest(ed,td,nd,od,rd,e)}finalize(){this.channel.postMessage({type:id,name:this.name}),this.channel.close()}async sendRequest(e,t,n,o,i,s){s?.signal?.throwIfAborted();let a=Rv();return this.channel.postMessage({type:e,identifier:a,name:this.name}),new Promise((c,u)=>{let l=()=>{this.channel.postMessage({type:t,identifier:a,name:this.name})};s?.signal?.addEventListener("abort",l,{once:!0});let f=d=>{if(d.data?.identifier===a&&(d.data?.type===n&&(this.channel.removeEventListener("message",f),s?.signal?.removeEventListener("abort",l),c(()=>{this.channel.postMessage({type:i,identifier:a,name:this.name})})),d.data.type===o)){this.channel.removeEventListener("message",f),s?.signal?.removeEventListener("abort",l);let h=new Error;d.data.error!=null&&(h.message=d.data.error.message,h.name=d.data.error.name,h.stack=d.data.error.stack),u(h)}};this.channel.addEventListener("message",f)})}};var Uv=r=>{if(r=Object.assign({},Dv,r),!!globalThis.document||r.singleProcess){let t=new BroadcastChannel(sd),n=new ze;return t.addEventListener("message",d0(n,t,"requestReadLock","abortReadLockRequest",Yf,Xf,Qf,Zf,Jf)),t.addEventListener("message",d0(n,t,"requestWriteLock","abortWriteLockRequest",ed,td,od,rd,nd)),n}return new ad(r.name)};var vi=new Map,$c;function Ov(r){return typeof r?.readLock=="function"&&typeof r?.writeLock=="function"}function d4(r){if($c==null&&($c=Uv(r),!Ov($c))){let e=$c;e.addEventListener("requestReadLock",t=>{let n=t.detail.name,o=t.detail.identifier,i=vi.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=vi.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=vi.get(n);o?.finalize()})}return $c}async function h0(r,e){let t,n,o=new Promise((s,a)=>{t=s,n=a}),i=()=>{n(new Ft)};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 Mv=(r,e)=>{let t=vi.get(r);if(t!=null)return t;let n=d4(e);if(Ov(n))return t=n,vi.set(r,t),t;let o=new Fc({concurrency:1}),i;return t={async readLock(s){if(i!=null)return h0(i,s);i=new Fc({concurrency:e.concurrency,autoStart:!1});let a=i,c=h0(i,s);return o.add(async()=>{a.start(),await a.onIdle().then(()=>{i===a&&(i=null)})}),c},async writeLock(s){return i=null,h0(o,s)},finalize:()=>{vi.delete(r)},queue:o},vi.set(r,t),e.autoFinalize===!0&&o.addEventListener("idle",()=>{t.finalize()},{once:!0}),t};var h4={name:"lock",concurrency:1/0,singleProcess:!1,autoFinalize:!1};function Vc(r){let e=Object.assign({},h4,r);return Mv(e.name,e)}var cd=class{lock;child;pins;started;constructor(e,t,n={}){this.child=e,this.pins=t,this.lock=Vc({singleProcess:n.holdGcLock}),this.started=!1}isStarted(){return this.started}async start(){await rn(this.child),this.started=!0}async stop(){await nn(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 Dc("Block was pinned - please unpin and try again");await this.child.delete(e,t)}finally{n()}}async*deleteMany(e,t={}){t?.signal?.throwIfAborted();let n=await this.lock.writeLock();try{let o=this;yield*this.child.deleteMany((async function*(){for await(let i of e){if(await o.pins.isPinned(i))throw new Dc("Block was pinned - please unpin and try again");yield i}})(),t)}finally{n()}}async has(e,t={}){t?.signal?.throwIfAborted();let n=await this.lock.readLock();try{return await this.child.has(e,t)}finally{n()}}async*getAll(e={}){e?.signal?.throwIfAborted();let t=await this.lock.readLock();try{yield*this.child.getAll(e)}finally{t()}}createSession(e,t){return t?.signal?.throwIfAborted(),this.child.createSession(e,t)}};var p0=new Le("/version"),Fv=1;async function $v(r){if(!await r.has(p0)){await r.put(p0,L(`${Fv}`));return}let e=await r.get(p0),t=j(e);if(parseInt(t,10)!==Fv)throw new $f("Invalid datastore version, a datastore migration may be required")}var B0={};Me(B0,{code:()=>C0,decode:()=>sN,decodeOptions:()=>nN,encode:()=>iN,encodeOptions:()=>tN,name:()=>oN,toByteView:()=>G2});var p4=["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 m0(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=m4(r);return t||"Object"}function m4(r){let e=Object.prototype.toString.call(r).slice(8,-1);if(p4.includes(e))return e}var x=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}};x.uint=new x(0,"uint",!0);x.negint=new x(1,"negint",!0);x.bytes=new x(2,"bytes",!0);x.string=new x(3,"string",!0);x.array=new x(4,"array",!1);x.map=new x(5,"map",!1);x.tag=new x(6,"tag",!1);x.float=new x(7,"float",!0);x.false=new x(7,"false",!0);x.true=new x(7,"true",!0);x.null=new x(7,"null",!0);x.undefined=new x(7,"undefined",!0);x.break=new x(7,"break",!0);var K=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 Kc=globalThis.process&&!globalThis.process.browser&&globalThis.Buffer&&typeof globalThis.Buffer.isBuffer=="function",g4=new TextEncoder;function ud(r){return Kc&&globalThis.Buffer.isBuffer(r)}function qc(r){return r instanceof Uint8Array?ud(r)?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):r:Uint8Array.from(r)}var y4=24,w4=200,ld=Kc?r=>r.length>=y4?globalThis.Buffer.from(r):Vv(r):r=>r.length>=w4?g4.encode(r):Vv(r),mn=r=>Uint8Array.from(r),Kv=Kc?(r,e,t)=>ud(r)?new Uint8Array(r.subarray(e,t)):r.slice(e,t):(r,e,t)=>r.slice(e,t),qv=Kc?(r,e)=>(r=r.map(t=>t instanceof Uint8Array?t:globalThis.Buffer.from(t)),qc(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},Hv=Kc?r=>globalThis.Buffer.allocUnsafe(r):r=>new Uint8Array(r);function fd(r,e){if(ud(r)&&ud(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 Vv(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 b4=256,Hc=class{constructor(e=b4){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=Hv(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=Kv(n,0,this.cursor)}else t=qv(this.chunks,this.cursor);return e&&this.reset(),t}},dd=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 re="CBOR decode error:",hd="CBOR encode error:",zc=[];zc[23]=1;zc[24]=2;zc[25]=3;zc[26]=5;zc[27]=9;function Ln(r,e,t){if(r.length-e<t)throw new Error(`${re} not enough data for type`)}var tt=[24,256,65536,4294967296,BigInt("18446744073709551616")];function zt(r,e,t){Ln(r,e,1);let n=r[e];if(t.strict===!0&&n<tt[0])throw new Error(`${re} integer encoded in more bytes than necessary (strict decode)`);return n}function jt(r,e,t){Ln(r,e,2);let n=r[e]<<8|r[e+1];if(t.strict===!0&&n<tt[1])throw new Error(`${re} integer encoded in more bytes than necessary (strict decode)`);return n}function Gt(r,e,t){Ln(r,e,4);let n=r[e]*16777216+(r[e+1]<<16)+(r[e+2]<<8)+r[e+3];if(t.strict===!0&&n<tt[2])throw new Error(`${re} integer encoded in more bytes than necessary (strict decode)`);return n}function Wt(r,e,t){Ln(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<tt[3])throw new Error(`${re} 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(`${re} integers outside of the safe integer range are not supported`)}function zv(r,e,t,n){return new K(x.uint,zt(r,e+1,n),2)}function jv(r,e,t,n){return new K(x.uint,jt(r,e+1,n),3)}function Gv(r,e,t,n){return new K(x.uint,Gt(r,e+1,n),5)}function Wv(r,e,t,n){return new K(x.uint,Wt(r,e+1,n),9)}function pr(r,e){return Ce(r,0,e.value)}function Ce(r,e,t){if(t<tt[0]){let n=Number(t);r.push([e|n])}else if(t<tt[1]){let n=Number(t);r.push([e|24,n])}else if(t<tt[2]){let n=Number(t);r.push([e|25,n>>>8,n&255])}else if(t<tt[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<tt[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(`${re} encountered BigInt larger than allowable range`)}}pr.encodedSize=function(e){return Ce.encodedSize(e.value)};Ce.encodedSize=function(e){return e<tt[0]?1:e<tt[1]?2:e<tt[2]?3:e<tt[3]?5:9};pr.compareTokens=function(e,t){return e.value<t.value?-1:e.value>t.value?1:0};function Yv(r,e,t,n){return new K(x.negint,-1-zt(r,e+1,n),2)}function Xv(r,e,t,n){return new K(x.negint,-1-jt(r,e+1,n),3)}function Zv(r,e,t,n){return new K(x.negint,-1-Gt(r,e+1,n),5)}var g0=BigInt(-1),Jv=BigInt(1);function Qv(r,e,t,n){let o=Wt(r,e+1,n);if(typeof o!="bigint"){let i=-1-o;if(i>=Number.MIN_SAFE_INTEGER)return new K(x.negint,i,9)}if(n.allowBigInt!==!0)throw new Error(`${re} integers outside of the safe integer range are not supported`);return new K(x.negint,g0-BigInt(o),9)}function pd(r,e){let t=e.value,n=typeof t=="bigint"?t*g0-Jv:t*-1-1;Ce(r,e.type.majorEncoded,n)}pd.encodedSize=function(e){let t=e.value,n=typeof t=="bigint"?t*g0-Jv:t*-1-1;return n<tt[0]?1:n<tt[1]?2:n<tt[2]?3:n<tt[3]?5:9};pd.compareTokens=function(e,t){return e.value<t.value?1:e.value>t.value?-1:0};function jc(r,e,t,n){Ln(r,e,t+n);let o=r.slice(e+t,e+t+n);return new K(x.bytes,o,t+n)}function e2(r,e,t,n){return jc(r,e,1,t)}function t2(r,e,t,n){return jc(r,e,2,zt(r,e+1,n))}function r2(r,e,t,n){return jc(r,e,3,jt(r,e+1,n))}function n2(r,e,t,n){return jc(r,e,5,Gt(r,e+1,n))}function o2(r,e,t,n){let o=Wt(r,e+1,n);if(typeof o=="bigint")throw new Error(`${re} 64-bit integer bytes lengths not supported`);return jc(r,e,9,o)}function md(r){return r.encodedBytes===void 0&&(r.encodedBytes=x.equals(r.type,x.string)?ld(r.value):r.value),r.encodedBytes}function Fs(r,e){let t=md(e);Ce(r,e.type.majorEncoded,t.length),r.push(t)}Fs.encodedSize=function(e){let t=md(e);return Ce.encodedSize(t.length)+t.length};Fs.compareTokens=function(e,t){return E4(md(e),md(t))};function E4(r,e){return r.length<e.length?-1:r.length>e.length?1:fd(r,e)}var i2=new TextDecoder,A4=32;function S4(r,e,t){if(t-e<A4){let o="";for(let i=e;i<t;i++){let s=r[i];if(s&128)return i2.decode(r.subarray(e,t));o+=String.fromCharCode(s)}return o}return i2.decode(r.subarray(e,t))}function Gc(r,e,t,n,o){let i=t+n;Ln(r,e,i);let s=new K(x.string,S4(r,e+t,e+i),i);return o.retainStringBytes===!0&&(s.byteValue=r.slice(e+t,e+i)),s}function s2(r,e,t,n){return Gc(r,e,1,t,n)}function a2(r,e,t,n){return Gc(r,e,2,zt(r,e+1,n),n)}function c2(r,e,t,n){return Gc(r,e,3,jt(r,e+1,n),n)}function u2(r,e,t,n){return Gc(r,e,5,Gt(r,e+1,n),n)}function l2(r,e,t,n){let o=Wt(r,e+1,n);if(typeof o=="bigint")throw new Error(`${re} 64-bit integer string lengths not supported`);return Gc(r,e,9,o,n)}var f2=Fs;function $s(r,e,t,n){return new K(x.array,n,t)}function d2(r,e,t,n){return $s(r,e,1,t)}function h2(r,e,t,n){return $s(r,e,2,zt(r,e+1,n))}function p2(r,e,t,n){return $s(r,e,3,jt(r,e+1,n))}function m2(r,e,t,n){return $s(r,e,5,Gt(r,e+1,n))}function g2(r,e,t,n){let o=Wt(r,e+1,n);if(typeof o=="bigint")throw new Error(`${re} 64-bit integer array lengths not supported`);return $s(r,e,9,o)}function y2(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${re} indefinite length items not allowed`);return $s(r,e,1,1/0)}function gd(r,e){Ce(r,x.array.majorEncoded,e.value)}gd.compareTokens=pr.compareTokens;gd.encodedSize=function(e){return Ce.encodedSize(e.value)};function Vs(r,e,t,n){return new K(x.map,n,t)}function w2(r,e,t,n){return Vs(r,e,1,t)}function b2(r,e,t,n){return Vs(r,e,2,zt(r,e+1,n))}function x2(r,e,t,n){return Vs(r,e,3,jt(r,e+1,n))}function E2(r,e,t,n){return Vs(r,e,5,Gt(r,e+1,n))}function v2(r,e,t,n){let o=Wt(r,e+1,n);if(typeof o=="bigint")throw new Error(`${re} 64-bit integer map lengths not supported`);return Vs(r,e,9,o)}function A2(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${re} indefinite length items not allowed`);return Vs(r,e,1,1/0)}function yd(r,e){Ce(r,x.map.majorEncoded,e.value)}yd.compareTokens=pr.compareTokens;yd.encodedSize=function(e){return Ce.encodedSize(e.value)};function S2(r,e,t,n){return new K(x.tag,t,1)}function k2(r,e,t,n){return new K(x.tag,zt(r,e+1,n),2)}function _2(r,e,t,n){return new K(x.tag,jt(r,e+1,n),3)}function I2(r,e,t,n){return new K(x.tag,Gt(r,e+1,n),5)}function T2(r,e,t,n){return new K(x.tag,Wt(r,e+1,n),9)}function wd(r,e){Ce(r,x.tag.majorEncoded,e.value)}wd.compareTokens=pr.compareTokens;wd.encodedSize=function(e){return Ce.encodedSize(e.value)};var y0=20,w0=21,b0=22,x0=23;function C2(r,e,t,n){if(n.allowUndefined===!1)throw new Error(`${re} undefined values are not supported`);return n.coerceUndefinedToNull===!0?new K(x.null,null,1):new K(x.undefined,void 0,1)}function B2(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${re} indefinite length items not allowed`);return new K(x.break,void 0,1)}function E0(r,e,t){if(t){if(t.allowNaN===!1&&Number.isNaN(r))throw new Error(`${re} NaN values are not supported`);if(t.allowInfinity===!1&&(r===1/0||r===-1/0))throw new Error(`${re} Infinity values are not supported`)}return new K(x.float,r,e)}function N2(r,e,t,n){return E0(v0(r,e+1),3,n)}function P2(r,e,t,n){return E0(A0(r,e+1),5,n)}function L2(r,e,t,n){return E0(O2(r,e+1),9,n)}function Wc(r,e,t){let n=e.value;if(n===!1)r.push([x.float.majorEncoded|y0]);else if(n===!0)r.push([x.float.majorEncoded|w0]);else if(n===null)r.push([x.float.majorEncoded|b0]);else if(n===void 0)r.push([x.float.majorEncoded|x0]);else{let o,i=!1;(!t||t.float64!==!0)&&(R2(n),o=v0(Hr,1),n===o||Number.isNaN(n)?(Hr[0]=249,r.push(Hr.slice(0,3)),i=!0):(U2(n),o=A0(Hr,1),n===o&&(Hr[0]=250,r.push(Hr.slice(0,5)),i=!0))),i||(C4(n),o=O2(Hr,1),Hr[0]=251,r.push(Hr.slice(0,9)))}}Wc.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){R2(n);let o=v0(Hr,1);if(n===o||Number.isNaN(n))return 3;if(U2(n),o=A0(Hr,1),n===o)return 5}return 9};var D2=new ArrayBuffer(9),mr=new DataView(D2,1),Hr=new Uint8Array(D2,0);function R2(r){if(r===1/0)mr.setUint16(0,31744,!1);else if(r===-1/0)mr.setUint16(0,64512,!1);else if(Number.isNaN(r))mr.setUint16(0,32256,!1);else{mr.setFloat32(0,r);let e=mr.getUint32(0),t=(e&2139095040)>>23,n=e&8388607;if(t===255)mr.setUint16(0,31744,!1);else if(t===0)mr.setUint16(0,(e&2147483648)>>16|n>>13,!1);else{let o=t-127;o<-24?mr.setUint16(0,0):o<-14?mr.setUint16(0,(e&2147483648)>>16|1<<24+o,!1):mr.setUint16(0,(e&2147483648)>>16|o+15<<10|n>>13,!1)}}}function v0(r,e){if(r.length-e<2)throw new Error(`${re} 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 U2(r){mr.setFloat32(0,r,!1)}function A0(r,e){if(r.length-e<4)throw new Error(`${re} not enough data for float32`);let t=(r.byteOffset||0)+e;return new DataView(r.buffer,t,4).getFloat32(0,!1)}function C4(r){mr.setFloat64(0,r,!1)}function O2(r,e){if(r.length-e<8)throw new Error(`${re} not enough data for float64`);let t=(r.byteOffset||0)+e;return new DataView(r.buffer,t,8).getFloat64(0,!1)}Wc.compareTokens=pr.compareTokens;function we(r,e,t){throw new Error(`${re} encountered invalid minor (${t}) for major ${r[e]>>>5}`)}function bd(r){return()=>{throw new Error(`${re} ${r}`)}}var U=[];for(let r=0;r<=23;r++)U[r]=we;U[24]=zv;U[25]=jv;U[26]=Gv;U[27]=Wv;U[28]=we;U[29]=we;U[30]=we;U[31]=we;for(let r=32;r<=55;r++)U[r]=we;U[56]=Yv;U[57]=Xv;U[58]=Zv;U[59]=Qv;U[60]=we;U[61]=we;U[62]=we;U[63]=we;for(let r=64;r<=87;r++)U[r]=e2;U[88]=t2;U[89]=r2;U[90]=n2;U[91]=o2;U[92]=we;U[93]=we;U[94]=we;U[95]=bd("indefinite length bytes/strings are not supported");for(let r=96;r<=119;r++)U[r]=s2;U[120]=a2;U[121]=c2;U[122]=u2;U[123]=l2;U[124]=we;U[125]=we;U[126]=we;U[127]=bd("indefinite length bytes/strings are not supported");for(let r=128;r<=151;r++)U[r]=d2;U[152]=h2;U[153]=p2;U[154]=m2;U[155]=g2;U[156]=we;U[157]=we;U[158]=we;U[159]=y2;for(let r=160;r<=183;r++)U[r]=w2;U[184]=b2;U[185]=x2;U[186]=E2;U[187]=v2;U[188]=we;U[189]=we;U[190]=we;U[191]=A2;for(let r=192;r<=215;r++)U[r]=S2;U[216]=k2;U[217]=_2;U[218]=I2;U[219]=T2;U[220]=we;U[221]=we;U[222]=we;U[223]=we;for(let r=224;r<=243;r++)U[r]=bd("simple values are not supported");U[244]=we;U[245]=we;U[246]=we;U[247]=C2;U[248]=bd("simple values are not supported");U[249]=N2;U[250]=P2;U[251]=L2;U[252]=we;U[253]=we;U[254]=we;U[255]=B2;var zr=[];for(let r=0;r<24;r++)zr[r]=new K(x.uint,r,1);for(let r=-1;r>=-24;r--)zr[31-r]=new K(x.negint,r,1);zr[64]=new K(x.bytes,new Uint8Array(0),1);zr[96]=new K(x.string,"",1);zr[128]=new K(x.array,0,1);zr[160]=new K(x.map,0,1);zr[244]=new K(x.false,!1,1);zr[245]=new K(x.true,!0,1);zr[246]=new K(x.null,null,1);function S0(r){switch(r.type){case x.false:return mn([244]);case x.true:return mn([245]);case x.null:return mn([246]);case x.bytes:return r.value.length?void 0:mn([64]);case x.string:return r.value===""?mn([96]):void 0;case x.array:return r.value===0?mn([128]):void 0;case x.map:return r.value===0?mn([160]):void 0;case x.uint:return r.value<24?mn([Number(r.value)]):void 0;case x.negint:if(r.value>=-24)return mn([31-Number(r.value)])}}var N4={float64:!1,mapSorter:D4,quickEncodeToken:S0},K2=Object.freeze({float64:!0,mapSorter:R4,quickEncodeToken:S0});function P4(){let r=[];return r[x.uint.major]=pr,r[x.negint.major]=pd,r[x.bytes.major]=Fs,r[x.string.major]=f2,r[x.array.major]=gd,r[x.map.major]=yd,r[x.tag.major]=wd,r[x.float.major]=Wc,r}var qs=P4(),xd=new Hc,Xc=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(`${hd} object contains circular references`);return new r(t,e)}},bo={null:new K(x.null,null),undefined:new K(x.undefined,void 0),true:new K(x.true,!0),false:new K(x.false,!1),emptyArray:new K(x.array,0),emptyMap:new K(x.map,0)},gn={number(r,e,t,n){return!Number.isInteger(r)||!Number.isSafeInteger(r)?new K(x.float,r):r>=0?new K(x.uint,r):new K(x.negint,r)},bigint(r,e,t,n){return r>=BigInt(0)?new K(x.uint,r):new K(x.negint,r)},Uint8Array(r,e,t,n){return new K(x.bytes,r)},string(r,e,t,n){return new K(x.string,r)},boolean(r,e,t,n){return r?bo.true:bo.false},null(r,e,t,n){return bo.null},undefined(r,e,t,n){return bo.undefined},ArrayBuffer(r,e,t,n){return new K(x.bytes,new Uint8Array(r))},DataView(r,e,t,n){return new K(x.bytes,new Uint8Array(r.buffer,r.byteOffset,r.byteLength))},Array(r,e,t,n){if(!r.length)return t.addBreakTokens===!0?[bo.emptyArray,new K(x.break)]:bo.emptyArray;n=Xc.createCheck(n,r);let o=[],i=0;for(let s of r)o[i++]=Ks(s,t,n);return t.addBreakTokens?[new K(x.array,r.length),o,new K(x.break)]:[new K(x.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=Xc.createCheck(n,r);let c=!o&&t.ignoreUndefinedProperties,u=0;for(let l of i){let f=o?r.get(l):r[l];c&&f===void 0||(a[u++]=[Ks(l,t,n),Ks(f,t,n)])}u<s&&(a.length=u)}return a?.length?(L4(a,t),t.addBreakTokens?[new K(x.map,a.length),a,new K(x.break)]:[new K(x.map,a.length),a]):t.addBreakTokens===!0?[bo.emptyMap,new K(x.break)]:bo.emptyMap},Tagged(r,e,t,n){return[new K(x.tag,r.tag),Ks(r.value,t,n)]}};gn.Map=gn.Object;gn.Buffer=gn.Uint8Array;for(let r of"Uint8Clamped Uint16 Uint32 Int8 Int16 Int32 BigUint64 BigInt64 Float32 Float64".split(" "))gn[`${r}Array`]=gn.DataView;function Ks(r,e={},t){let n=m0(r),o=e&&e.typeEncoders&&e.typeEncoders[n]||gn[n];if(typeof o=="function"){let s=o(r,n,e,t);if(s!=null)return s}let i=gn[n];if(!i)throw new Error(`${hd} unsupported type: ${n}`);return i(r,n,e,t)}function L4(r,e){e.mapSorter&&r.sort(e.mapSorter)}function D4(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=qs[o].compareTokens(t,n);return i===0&&console.warn("WARNING: complex key types used, CBOR key sorting guarantees are gone"),i}function R4(r,e){if(r[0]instanceof K&&e[0]instanceof K){let t=r[0],n=e[0];return t._keyBytes||(t._keyBytes=M2(t.value)),n._keyBytes||(n._keyBytes=M2(n.value)),fd(t._keyBytes,n._keyBytes)}throw new Error("rfc8949MapSorter: complex key types are not supported yet")}function M2(r){return H2(r,qs,K2)}function Yc(r,e,t,n){if(Array.isArray(e))for(let o of e)Yc(r,o,t,n);else t[e.type.major](r,e,n)}var F2=x.uint.majorEncoded,$2=x.negint.majorEncoded,U4=x.bytes.majorEncoded,O4=x.string.majorEncoded,V2=x.array.majorEncoded,M4=x.float.majorEncoded|y0,F4=x.float.majorEncoded|w0,$4=x.float.majorEncoded|b0,V4=x.float.majorEncoded|x0,K4=BigInt(-1),q4=BigInt(1);function H4(r){return r.addBreakTokens!==!0}function q2(r,e,t,n){let o=m0(e),i=t.typeEncoders&&t.typeEncoders[o];if(i){let s=i(e,o,t,n);if(s!=null){Yc(r,s,qs,t);return}}switch(o){case"null":r.push([$4]);return;case"undefined":r.push([V4]);return;case"boolean":r.push([e?F4:M4]);return;case"number":!Number.isInteger(e)||!Number.isSafeInteger(e)?Wc(r,new K(x.float,e),t):e>=0?Ce(r,F2,e):Ce(r,$2,e*-1-1);return;case"bigint":e>=BigInt(0)?Ce(r,F2,e):Ce(r,$2,e*K4-q4);return;case"string":{let s=ld(e);Ce(r,O4,s.length),r.push(s);return}case"Uint8Array":Ce(r,U4,e.length),r.push(e);return;case"Array":if(!e.length){r.push([V2]);return}n=Xc.createCheck(n,e),Ce(r,V2,e.length);for(let s of e)q2(r,s,t,n);return;case"Object":case"Map":{let s=gn.Object(e,o,t,n);Yc(r,s,qs,t)}return;default:{let s=gn[o];if(!s)throw new Error(`${hd} unsupported type: ${o}`);let a=s(e,o,t,n);Yc(r,a,qs,t)}}}function H2(r,e,t,n){let o=n instanceof Uint8Array,i=o?new dd(n):xd,s=Ks(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 u=c.encodedSize(s,t);if(o||(i=new Hc(u)),c(i,s,t),i.chunks.length!==1)throw new Error(`Unexpected error: pre-calculated length for ${s} was wrong`);return o?i.toBytes():qc(i.chunks[0])}}return i.reset(),Yc(i,s,e,t),i.toBytes(!0)}function k0(r,e){return e=Object.assign({},N4,e),H4(e)?(xd.reset(),q2(xd,r,e,void 0),xd.toBytes(!0)):H2(r,qs,e)}var z4={strict:!1,allowIndefinite:!0,allowUndefined:!0,allowBigInt:!0},Ed=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=zr[e];if(t===void 0){let n=U[e];if(!n)throw new Error(`${re} 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}},xo=Symbol.for("DONE"),Hs=Symbol.for("BREAK");function j4(r,e,t){let n=[];for(let o=0;o<r.value;o++){let i=Eo(e,t);if(i===Hs){if(r.value===1/0)break;throw new Error(`${re} got unexpected break to lengthed array`)}if(i===xo)throw new Error(`${re} found array but not enough entries (got ${o}, expected ${r.value})`);n[o]=i}return n}function G4(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=Eo(e,t);if(c===Hs){if(r.value===1/0)break;throw new Error(`${re} got unexpected break to lengthed map`)}if(c===xo)throw new Error(`${re} found map but not enough entries (got ${a} [no key], expected ${r.value})`);if(!n&&typeof c!="string")throw new Error(`${re} non-string keys not supported (got ${typeof c})`);if(o&&(n&&s.has(c)||!n&&Object.hasOwn(i,c)))throw new Error(`${re} found repeat map key "${c}"`);let u=Eo(e,t);if(u===xo)throw new Error(`${re} found map but not enough entries (got ${a} [no value], expected ${r.value})`);n?s.set(c,u):i[c]=u}return n?s:i}function*W4(r,e,t){for(let n=0;n<r.value;n++){let o=Eo(e,t);if(o===Hs){if(r.value===1/0)break;throw new Error(`${re} got unexpected break to lengthed map`)}if(o===xo)throw new Error(`${re} found map but not enough entries (got ${n} [no key], expected ${r.value})`);let i=Eo(e,t);if(i===xo)throw new Error(`${re} found map but not enough entries (got ${n} [no value], expected ${r.value})`);yield[o,i]}}function Y4(r,e){let t=!1,n=function(){if(t)throw new Error(`${re} tag decode() may only be called once`);t=!0;let o=Eo(r,e);if(o===xo)throw new Error(`${re} tag content missing`);if(o===Hs)throw new Error(`${re} got unexpected break in tag content`);return o};return n.entries=function(){if(t)throw new Error(`${re} tag decode() may only be called once`);t=!0;let o=r.next();if(!x.equals(o.type,x.map))throw new Error(`${re} entries() requires map content, got ${o.type.name}`);let i=[];for(let s of W4(o,r,e))i.push(s);return i},Object.defineProperty(n,"_called",{get(){return t},enumerable:!1}),n}function Eo(r,e){if(r.done())return xo;let t=r.next();if(x.equals(t.type,x.break))return Hs;if(t.type.terminal)return t.value;if(x.equals(t.type,x.array))return j4(t,r,e);if(x.equals(t.type,x.map))return G4(t,r,e);if(x.equals(t.type,x.tag)){if(e.tags&&typeof e.tags[t.value]=="function"){let n=Y4(r,e),o=e.tags[t.value](n);if(!n._called)throw new Error(`${re} tag decoder must call decode() or entries()`);return o}throw new Error(`${re} tag not supported (${t.value})`)}throw new Error("unsupported")}function z2(r,e){if(!(r instanceof Uint8Array))throw new Error(`${re} data to decode must be a Uint8Array`);e=Object.assign({},z4,e);let t=qc(r),n=e.tokenizer||new Ed(t,e),o=Eo(n,e);if(o===xo)throw new Error(`${re} did not find any content to decode`);if(o===Hs)throw new Error(`${re} got unexpected break`);return[o,r.subarray(n.pos())]}function _0(r,e){let[t,n]=z2(r,e);if(n.length>0)throw new Error(`${re} too many terminals, data makes no sense`);return t}var vd=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(vd.prototype,Symbol.toStringTag,{value:"Tagged"});var j2=42;function G2(r){return r instanceof ArrayBuffer?new Uint8Array(r,0,r.byteLength):r}function Z4(r){if(r.asCID!==r&&r["/"]!==r.bytes)return null;let e=Q.asCID(r);if(!e)return null;let t=new Uint8Array(e.bytes.byteLength+1);return t.set(e.bytes,1),[new K(x.tag,j2),new K(x.bytes,t)]}function J4(){throw new Error("`undefined` is not supported by the IPLD Data Model and cannot be encoded")}function Q4(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 eN(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 I0={float64:!0,typeEncoders:{Map:eN,Object:Z4,undefined:J4,number:Q4}},tN={...I0,typeEncoders:{...I0.typeEncoders}};function rN(r){let e=r();if(e[0]!==0)throw new Error("Invalid CID for CBOR tag 42; expected leading 0x00");return Q.decode(e.subarray(1))}var T0={allowIndefinite:!1,coerceUndefinedToNull:!0,allowNaN:!1,allowInfinity:!1,allowBigInt:!0,strict:!0,useMaps:!1,rejectDuplicateMapKeys:!0,tags:{[j2]:rN}},nN={...T0,tags:{...T0.tags}},oN="dag-cbor",C0=113,iN=r=>k0(r,I0),sN=r=>_0(G2(r),T0);var G0={};Me(G0,{code:()=>j0,decode:()=>eS,encode:()=>QA,format:()=>HN,name:()=>qN,parse:()=>jN,stringify:()=>HN});var aN=["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 W2(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=cN(r);return t||"Object"}function cN(r){let e=Object.prototype.toString.call(r).slice(8,-1);if(aN.includes(e))return e}var p=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}};p.uint=new p(0,"uint",!0);p.negint=new p(1,"negint",!0);p.bytes=new p(2,"bytes",!0);p.string=new p(3,"string",!0);p.array=new p(4,"array",!1);p.map=new p(5,"map",!1);p.tag=new p(6,"tag",!1);p.float=new p(7,"float",!0);p.false=new p(7,"false",!0);p.true=new p(7,"true",!0);p.null=new p(7,"null",!0);p.undefined=new p(7,"undefined",!0);p.break=new p(7,"break",!0);var B=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 Zc=globalThis.process&&!globalThis.process.browser&&globalThis.Buffer&&typeof globalThis.Buffer.isBuffer=="function",uN=new TextEncoder;function Ad(r){return Zc&&globalThis.Buffer.isBuffer(r)}function Si(r){return r instanceof Uint8Array?Ad(r)?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):r:Uint8Array.from(r)}var lN=24,fN=200,Jc=Zc?r=>r.length>=lN?globalThis.Buffer.from(r):Y2(r):r=>r.length>=fN?uN.encode(r):Y2(r),yn=r=>Uint8Array.from(r),Z2=Zc?(r,e,t)=>Ad(r)?new Uint8Array(r.subarray(e,t)):r.slice(e,t):(r,e,t)=>r.slice(e,t),J2=Zc?(r,e)=>(r=r.map(t=>t instanceof Uint8Array?t:globalThis.Buffer.from(t)),Si(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},Q2=Zc?r=>globalThis.Buffer.allocUnsafe(r):r=>new Uint8Array(r);function Sd(r,e){if(Ad(r)&&Ad(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 Y2(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 X2=4096;function eA(r){let e=r.length;if(e<=X2)return String.fromCharCode.apply(String,r);let t="",n=0;for(;n<e;)t+=String.fromCharCode.apply(String,r.slice(n,n+=X2));return t}var dN=256,Qc=class{constructor(e=dN){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=Q2(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=Z2(n,0,this.cursor)}else t=J2(this.chunks,this.cursor);return e&&this.reset(),t}},kd=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 H="CBOR decode error:",Dn="CBOR encode error:",eu=[];eu[23]=1;eu[24]=2;eu[25]=3;eu[26]=5;eu[27]=9;function Rn(r,e,t){if(r.length-e<t)throw new Error(`${H} not enough data for type`)}var rt=[24,256,65536,4294967296,BigInt("18446744073709551616")];function Yt(r,e,t){Rn(r,e,1);let n=r[e];if(t.strict===!0&&n<rt[0])throw new Error(`${H} integer encoded in more bytes than necessary (strict decode)`);return n}function Xt(r,e,t){Rn(r,e,2);let n=r[e]<<8|r[e+1];if(t.strict===!0&&n<rt[1])throw new Error(`${H} integer encoded in more bytes than necessary (strict decode)`);return n}function Zt(r,e,t){Rn(r,e,4);let n=r[e]*16777216+(r[e+1]<<16)+(r[e+2]<<8)+r[e+3];if(t.strict===!0&&n<rt[2])throw new Error(`${H} integer encoded in more bytes than necessary (strict decode)`);return n}function Jt(r,e,t){Rn(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<rt[3])throw new Error(`${H} integer encoded in more bytes than necessary (strict decode)`);if(i<=Number.MAX_SAFE_INTEGER)return Number(i);if(t.allowBigInt===!0)return i;throw new Error(`${H} integers outside of the safe integer range are not supported`)}function tA(r,e,t,n){return new B(p.uint,Yt(r,e+1,n),2)}function rA(r,e,t,n){return new B(p.uint,Xt(r,e+1,n),3)}function nA(r,e,t,n){return new B(p.uint,Zt(r,e+1,n),5)}function oA(r,e,t,n){return new B(p.uint,Jt(r,e+1,n),9)}function gr(r,e){return nt(r,0,e.value)}function nt(r,e,t){if(t<rt[0]){let n=Number(t);r.push([e|n])}else if(t<rt[1]){let n=Number(t);r.push([e|24,n])}else if(t<rt[2]){let n=Number(t);r.push([e|25,n>>>8,n&255])}else if(t<rt[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<rt[4]){let o=[e|27,0,0,0,0,0,0,0],i=Number(n&BigInt(4294967295)),s=Number(n>>BigInt(32)&BigInt(4294967295));o[8]=i&255,i=i>>8,o[7]=i&255,i=i>>8,o[6]=i&255,i=i>>8,o[5]=i&255,o[4]=s&255,s=s>>8,o[3]=s&255,s=s>>8,o[2]=s&255,s=s>>8,o[1]=s&255,r.push(o)}else throw new Error(`${H} encountered BigInt larger than allowable range`)}}gr.encodedSize=function(e){return nt.encodedSize(e.value)};nt.encodedSize=function(e){return e<rt[0]?1:e<rt[1]?2:e<rt[2]?3:e<rt[3]?5:9};gr.compareTokens=function(e,t){return e.value<t.value?-1:e.value>t.value?1:0};function iA(r,e,t,n){return new B(p.negint,-1-Yt(r,e+1,n),2)}function sA(r,e,t,n){return new B(p.negint,-1-Xt(r,e+1,n),3)}function aA(r,e,t,n){return new B(p.negint,-1-Zt(r,e+1,n),5)}var N0=BigInt(-1),cA=BigInt(1);function uA(r,e,t,n){let o=Jt(r,e+1,n);if(typeof o!="bigint"){let i=-1-o;if(i>=Number.MIN_SAFE_INTEGER)return new B(p.negint,i,9)}if(n.allowBigInt!==!0)throw new Error(`${H} integers outside of the safe integer range are not supported`);return new B(p.negint,N0-BigInt(o),9)}function _d(r,e){let t=e.value,n=typeof t=="bigint"?t*N0-cA:t*-1-1;nt(r,e.type.majorEncoded,n)}_d.encodedSize=function(e){let t=e.value,n=typeof t=="bigint"?t*N0-cA:t*-1-1;return n<rt[0]?1:n<rt[1]?2:n<rt[2]?3:n<rt[3]?5:9};_d.compareTokens=function(e,t){return e.value<t.value?1:e.value>t.value?-1:0};function tu(r,e,t,n){Rn(r,e,t+n);let o=r.slice(e+t,e+t+n);return new B(p.bytes,o,t+n)}function lA(r,e,t,n){return tu(r,e,1,t)}function fA(r,e,t,n){return tu(r,e,2,Yt(r,e+1,n))}function dA(r,e,t,n){return tu(r,e,3,Xt(r,e+1,n))}function hA(r,e,t,n){return tu(r,e,5,Zt(r,e+1,n))}function pA(r,e,t,n){let o=Jt(r,e+1,n);if(typeof o=="bigint")throw new Error(`${H} 64-bit integer bytes lengths not supported`);return tu(r,e,9,o)}function Id(r){return r.encodedBytes===void 0&&(r.encodedBytes=p.equals(r.type,p.string)?Jc(r.value):r.value),r.encodedBytes}function zs(r,e){let t=Id(e);nt(r,e.type.majorEncoded,t.length),r.push(t)}zs.encodedSize=function(e){let t=Id(e);return nt.encodedSize(t.length)+t.length};zs.compareTokens=function(e,t){return pN(Id(e),Id(t))};function pN(r,e){return r.length<e.length?-1:r.length>e.length?1:Sd(r,e)}var mA=new TextDecoder,gN=32;function yN(r,e,t){if(t-e<gN){let o="";for(let i=e;i<t;i++){let s=r[i];if(s&128)return mA.decode(r.subarray(e,t));o+=String.fromCharCode(s)}return o}return mA.decode(r.subarray(e,t))}function ru(r,e,t,n,o){let i=t+n;Rn(r,e,i);let s=new B(p.string,yN(r,e+t,e+i),i);return o.retainStringBytes===!0&&(s.byteValue=r.slice(e+t,e+i)),s}function gA(r,e,t,n){return ru(r,e,1,t,n)}function yA(r,e,t,n){return ru(r,e,2,Yt(r,e+1,n),n)}function wA(r,e,t,n){return ru(r,e,3,Xt(r,e+1,n),n)}function bA(r,e,t,n){return ru(r,e,5,Zt(r,e+1,n),n)}function xA(r,e,t,n){let o=Jt(r,e+1,n);if(typeof o=="bigint")throw new Error(`${H} 64-bit integer string lengths not supported`);return ru(r,e,9,o,n)}var EA=zs;function js(r,e,t,n){return new B(p.array,n,t)}function vA(r,e,t,n){return js(r,e,1,t)}function AA(r,e,t,n){return js(r,e,2,Yt(r,e+1,n))}function SA(r,e,t,n){return js(r,e,3,Xt(r,e+1,n))}function kA(r,e,t,n){return js(r,e,5,Zt(r,e+1,n))}function _A(r,e,t,n){let o=Jt(r,e+1,n);if(typeof o=="bigint")throw new Error(`${H} 64-bit integer array lengths not supported`);return js(r,e,9,o)}function IA(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${H} indefinite length items not allowed`);return js(r,e,1,1/0)}function Td(r,e){nt(r,p.array.majorEncoded,e.value)}Td.compareTokens=gr.compareTokens;Td.encodedSize=function(e){return nt.encodedSize(e.value)};function Gs(r,e,t,n){return new B(p.map,n,t)}function TA(r,e,t,n){return Gs(r,e,1,t)}function CA(r,e,t,n){return Gs(r,e,2,Yt(r,e+1,n))}function BA(r,e,t,n){return Gs(r,e,3,Xt(r,e+1,n))}function NA(r,e,t,n){return Gs(r,e,5,Zt(r,e+1,n))}function PA(r,e,t,n){let o=Jt(r,e+1,n);if(typeof o=="bigint")throw new Error(`${H} 64-bit integer map lengths not supported`);return Gs(r,e,9,o)}function LA(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${H} indefinite length items not allowed`);return Gs(r,e,1,1/0)}function Cd(r,e){nt(r,p.map.majorEncoded,e.value)}Cd.compareTokens=gr.compareTokens;Cd.encodedSize=function(e){return nt.encodedSize(e.value)};function DA(r,e,t,n){return new B(p.tag,t,1)}function RA(r,e,t,n){return new B(p.tag,Yt(r,e+1,n),2)}function UA(r,e,t,n){return new B(p.tag,Xt(r,e+1,n),3)}function OA(r,e,t,n){return new B(p.tag,Zt(r,e+1,n),5)}function MA(r,e,t,n){return new B(p.tag,Jt(r,e+1,n),9)}function Bd(r,e){nt(r,p.tag.majorEncoded,e.value)}Bd.compareTokens=gr.compareTokens;Bd.encodedSize=function(e){return nt.encodedSize(e.value)};var P0=20,L0=21,D0=22,R0=23;function FA(r,e,t,n){if(n.allowUndefined===!1)throw new Error(`${H} undefined values are not supported`);return n.coerceUndefinedToNull===!0?new B(p.null,null,1):new B(p.undefined,void 0,1)}function $A(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${H} indefinite length items not allowed`);return new B(p.break,void 0,1)}function U0(r,e,t){if(t){if(t.allowNaN===!1&&Number.isNaN(r))throw new Error(`${H} NaN values are not supported`);if(t.allowInfinity===!1&&(r===1/0||r===-1/0))throw new Error(`${H} Infinity values are not supported`)}return new B(p.float,r,e)}function VA(r,e,t,n){return U0(O0(r,e+1),3,n)}function KA(r,e,t,n){return U0(M0(r,e+1),5,n)}function qA(r,e,t,n){return U0(GA(r,e+1),9,n)}function Nd(r,e,t){let n=e.value;if(n===!1)r.push([p.float.majorEncoded|P0]);else if(n===!0)r.push([p.float.majorEncoded|L0]);else if(n===null)r.push([p.float.majorEncoded|D0]);else if(n===void 0)r.push([p.float.majorEncoded|R0]);else{let o,i=!1;(!t||t.float64!==!0)&&(zA(n),o=O0(jr,1),n===o||Number.isNaN(n)?(jr[0]=249,r.push(jr.slice(0,3)),i=!0):(jA(n),o=M0(jr,1),n===o&&(jr[0]=250,r.push(jr.slice(0,5)),i=!0))),i||(vN(n),o=GA(jr,1),jr[0]=251,r.push(jr.slice(0,9)))}}Nd.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){zA(n);let o=O0(jr,1);if(n===o||Number.isNaN(n))return 3;if(jA(n),o=M0(jr,1),n===o)return 5}return 9};var HA=new ArrayBuffer(9),yr=new DataView(HA,1),jr=new Uint8Array(HA,0);function zA(r){if(r===1/0)yr.setUint16(0,31744,!1);else if(r===-1/0)yr.setUint16(0,64512,!1);else if(Number.isNaN(r))yr.setUint16(0,32256,!1);else{yr.setFloat32(0,r);let e=yr.getUint32(0),t=(e&2139095040)>>23,n=e&8388607;if(t===255)yr.setUint16(0,31744,!1);else if(t===0)yr.setUint16(0,(e&2147483648)>>16|n>>13,!1);else{let o=t-127;o<-24?yr.setUint16(0,0):o<-14?yr.setUint16(0,(e&2147483648)>>16|1<<24+o,!1):yr.setUint16(0,(e&2147483648)>>16|o+15<<10|n>>13,!1)}}}function O0(r,e){if(r.length-e<2)throw new Error(`${H} not enough data for float16`);let t=(r[e]<<8)+r[e+1];if(t===31744)return 1/0;if(t===64512)return-1/0;if(t===32256)return NaN;let n=t>>10&31,o=t&1023,i;return n===0?i=o*2**-24:n!==31?i=(o+1024)*2**(n-25):i=o===0?1/0:NaN,t&32768?-i:i}function jA(r){yr.setFloat32(0,r,!1)}function M0(r,e){if(r.length-e<4)throw new Error(`${H} not enough data for float32`);let t=(r.byteOffset||0)+e;return new DataView(r.buffer,t,4).getFloat32(0,!1)}function vN(r){yr.setFloat64(0,r,!1)}function GA(r,e){if(r.length-e<8)throw new Error(`${H} not enough data for float64`);let t=(r.byteOffset||0)+e;return new DataView(r.buffer,t,8).getFloat64(0,!1)}Nd.compareTokens=gr.compareTokens;function be(r,e,t){throw new Error(`${H} encountered invalid minor (${t}) for major ${r[e]>>>5}`)}function Pd(r){return()=>{throw new Error(`${H} ${r}`)}}var O=[];for(let r=0;r<=23;r++)O[r]=be;O[24]=tA;O[25]=rA;O[26]=nA;O[27]=oA;O[28]=be;O[29]=be;O[30]=be;O[31]=be;for(let r=32;r<=55;r++)O[r]=be;O[56]=iA;O[57]=sA;O[58]=aA;O[59]=uA;O[60]=be;O[61]=be;O[62]=be;O[63]=be;for(let r=64;r<=87;r++)O[r]=lA;O[88]=fA;O[89]=dA;O[90]=hA;O[91]=pA;O[92]=be;O[93]=be;O[94]=be;O[95]=Pd("indefinite length bytes/strings are not supported");for(let r=96;r<=119;r++)O[r]=gA;O[120]=yA;O[121]=wA;O[122]=bA;O[123]=xA;O[124]=be;O[125]=be;O[126]=be;O[127]=Pd("indefinite length bytes/strings are not supported");for(let r=128;r<=151;r++)O[r]=vA;O[152]=AA;O[153]=SA;O[154]=kA;O[155]=_A;O[156]=be;O[157]=be;O[158]=be;O[159]=IA;for(let r=160;r<=183;r++)O[r]=TA;O[184]=CA;O[185]=BA;O[186]=NA;O[187]=PA;O[188]=be;O[189]=be;O[190]=be;O[191]=LA;for(let r=192;r<=215;r++)O[r]=DA;O[216]=RA;O[217]=UA;O[218]=OA;O[219]=MA;O[220]=be;O[221]=be;O[222]=be;O[223]=be;for(let r=224;r<=243;r++)O[r]=Pd("simple values are not supported");O[244]=be;O[245]=be;O[246]=be;O[247]=FA;O[248]=Pd("simple values are not supported");O[249]=VA;O[250]=KA;O[251]=qA;O[252]=be;O[253]=be;O[254]=be;O[255]=$A;var Gr=[];for(let r=0;r<24;r++)Gr[r]=new B(p.uint,r,1);for(let r=-1;r>=-24;r--)Gr[31-r]=new B(p.negint,r,1);Gr[64]=new B(p.bytes,new Uint8Array(0),1);Gr[96]=new B(p.string,"",1);Gr[128]=new B(p.array,0,1);Gr[160]=new B(p.map,0,1);Gr[244]=new B(p.false,!1,1);Gr[245]=new B(p.true,!0,1);Gr[246]=new B(p.null,null,1);function WA(r){switch(r.type){case p.false:return yn([244]);case p.true:return yn([245]);case p.null:return yn([246]);case p.bytes:return r.value.length?void 0:yn([64]);case p.string:return r.value===""?yn([96]):void 0;case p.array:return r.value===0?yn([128]):void 0;case p.map:return r.value===0?yn([160]):void 0;case p.uint:return r.value<24?yn([Number(r.value)]):void 0;case p.negint:if(r.value>=-24)return yn([31-Number(r.value)])}}var XA=Object.freeze({float64:!0,mapSorter:TN,quickEncodeToken:WA});function SN(){let r=[];return r[p.uint.major]=gr,r[p.negint.major]=_d,r[p.bytes.major]=zs,r[p.string.major]=EA,r[p.array.major]=Td,r[p.map.major]=Cd,r[p.tag.major]=Bd,r[p.float.major]=Nd,r}var kN=SN(),_N=new Qc,Ld=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(`${Dn} object contains circular references`);return new r(t,e)}},vo={null:new B(p.null,null),undefined:new B(p.undefined,void 0),true:new B(p.true,!0),false:new B(p.false,!1),emptyArray:new B(p.array,0),emptyMap:new B(p.map,0)},Ao={number(r,e,t,n){return!Number.isInteger(r)||!Number.isSafeInteger(r)?new B(p.float,r):r>=0?new B(p.uint,r):new B(p.negint,r)},bigint(r,e,t,n){return r>=BigInt(0)?new B(p.uint,r):new B(p.negint,r)},Uint8Array(r,e,t,n){return new B(p.bytes,r)},string(r,e,t,n){return new B(p.string,r)},boolean(r,e,t,n){return r?vo.true:vo.false},null(r,e,t,n){return vo.null},undefined(r,e,t,n){return vo.undefined},ArrayBuffer(r,e,t,n){return new B(p.bytes,new Uint8Array(r))},DataView(r,e,t,n){return new B(p.bytes,new Uint8Array(r.buffer,r.byteOffset,r.byteLength))},Array(r,e,t,n){if(!r.length)return t.addBreakTokens===!0?[vo.emptyArray,new B(p.break)]:vo.emptyArray;n=Ld.createCheck(n,r);let o=[],i=0;for(let s of r)o[i++]=Ws(s,t,n);return t.addBreakTokens?[new B(p.array,r.length),o,new B(p.break)]:[new B(p.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=Ld.createCheck(n,r);let c=!o&&t.ignoreUndefinedProperties,u=0;for(let l of i){let f=o?r.get(l):r[l];c&&f===void 0||(a[u++]=[Ws(l,t,n),Ws(f,t,n)])}u<s&&(a.length=u)}return a?.length?(IN(a,t),t.addBreakTokens?[new B(p.map,a.length),a,new B(p.break)]:[new B(p.map,a.length),a]):t.addBreakTokens===!0?[vo.emptyMap,new B(p.break)]:vo.emptyMap},Tagged(r,e,t,n){return[new B(p.tag,r.tag),Ws(r.value,t,n)]}};Ao.Map=Ao.Object;Ao.Buffer=Ao.Uint8Array;for(let r of"Uint8Clamped Uint16 Uint32 Int8 Int16 Int32 BigUint64 BigInt64 Float32 Float64".split(" "))Ao[`${r}Array`]=Ao.DataView;function Ws(r,e={},t){let n=W2(r),o=e&&e.typeEncoders&&e.typeEncoders[n]||Ao[n];if(typeof o=="function"){let s=o(r,n,e,t);if(s!=null)return s}let i=Ao[n];if(!i)throw new Error(`${Dn} unsupported type: ${n}`);return i(r,n,e,t)}function IN(r,e){e.mapSorter&&r.sort(e.mapSorter)}function TN(r,e){if(r[0]instanceof B&&e[0]instanceof B){let t=r[0],n=e[0];return t._keyBytes||(t._keyBytes=YA(t.value)),n._keyBytes||(n._keyBytes=YA(n.value)),Sd(t._keyBytes,n._keyBytes)}throw new Error("rfc8949MapSorter: complex key types are not supported yet")}function YA(r){return F0(r,kN,XA)}function ZA(r,e,t,n){if(Array.isArray(e))for(let o of e)ZA(r,o,t,n);else t[e.type.major](r,e,n)}var _z=p.uint.majorEncoded,Iz=p.negint.majorEncoded,Tz=p.bytes.majorEncoded,Cz=p.string.majorEncoded,Bz=p.array.majorEncoded,Nz=p.float.majorEncoded|P0,Pz=p.float.majorEncoded|L0,Lz=p.float.majorEncoded|D0,Dz=p.float.majorEncoded|R0,Rz=BigInt(-1),Uz=BigInt(1);function F0(r,e,t,n){let o=n instanceof Uint8Array,i=o?new kd(n):_N,s=Ws(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 u=c.encodedSize(s,t);if(o||(i=new Qc(u)),c(i,s,t),i.chunks.length!==1)throw new Error(`Unexpected error: pre-calculated length for ${s} was wrong`);return o?i.toBytes():Si(i.chunks[0])}}return i.reset(),ZA(i,s,e,t),i.toBytes(!0)}var CN={strict:!1,allowIndefinite:!0,allowUndefined:!0,allowBigInt:!0},Dd=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=Gr[e];if(t===void 0){let n=O[e];if(!n)throw new Error(`${H} no decoder for major type ${e>>>5} (byte 0x${e.toString(16).padStart(2,"0")})`);let o=e&31;t=n(this.data,this._pos,o,this.options)}return this._pos+=t.encodedLength,t}},So=Symbol.for("DONE"),Ys=Symbol.for("BREAK");function BN(r,e,t){let n=[];for(let o=0;o<r.value;o++){let i=ko(e,t);if(i===Ys){if(r.value===1/0)break;throw new Error(`${H} got unexpected break to lengthed array`)}if(i===So)throw new Error(`${H} found array but not enough entries (got ${o}, expected ${r.value})`);n[o]=i}return n}function NN(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=ko(e,t);if(c===Ys){if(r.value===1/0)break;throw new Error(`${H} got unexpected break to lengthed map`)}if(c===So)throw new Error(`${H} found map but not enough entries (got ${a} [no key], expected ${r.value})`);if(!n&&typeof c!="string")throw new Error(`${H} non-string keys not supported (got ${typeof c})`);if(o&&(n&&s.has(c)||!n&&Object.hasOwn(i,c)))throw new Error(`${H} found repeat map key "${c}"`);let u=ko(e,t);if(u===So)throw new Error(`${H} found map but not enough entries (got ${a} [no value], expected ${r.value})`);n?s.set(c,u):i[c]=u}return n?s:i}function*PN(r,e,t){for(let n=0;n<r.value;n++){let o=ko(e,t);if(o===Ys){if(r.value===1/0)break;throw new Error(`${H} got unexpected break to lengthed map`)}if(o===So)throw new Error(`${H} found map but not enough entries (got ${n} [no key], expected ${r.value})`);let i=ko(e,t);if(i===So)throw new Error(`${H} found map but not enough entries (got ${n} [no value], expected ${r.value})`);yield[o,i]}}function LN(r,e){let t=!1,n=function(){if(t)throw new Error(`${H} tag decode() may only be called once`);t=!0;let o=ko(r,e);if(o===So)throw new Error(`${H} tag content missing`);if(o===Ys)throw new Error(`${H} got unexpected break in tag content`);return o};return n.entries=function(){if(t)throw new Error(`${H} tag decode() may only be called once`);t=!0;let o=r.next();if(!p.equals(o.type,p.map))throw new Error(`${H} entries() requires map content, got ${o.type.name}`);let i=[];for(let s of PN(o,r,e))i.push(s);return i},Object.defineProperty(n,"_called",{get(){return t},enumerable:!1}),n}function ko(r,e){if(r.done())return So;let t=r.next();if(p.equals(t.type,p.break))return Ys;if(t.type.terminal)return t.value;if(p.equals(t.type,p.array))return BN(t,r,e);if(p.equals(t.type,p.map))return NN(t,r,e);if(p.equals(t.type,p.tag)){if(e.tags&&typeof e.tags[t.value]=="function"){let n=LN(r,e),o=e.tags[t.value](n);if(!n._called)throw new Error(`${H} tag decoder must call decode() or entries()`);return o}throw new Error(`${H} tag not supported (${t.value})`)}throw new Error("unsupported")}function $0(r,e){if(!(r instanceof Uint8Array))throw new Error(`${H} data to decode must be a Uint8Array`);e=Object.assign({},CN,e);let t=Si(r),n=e.tokenizer||new Dd(t,e),o=ko(n,e);if(o===So)throw new Error(`${H} did not find any content to decode`);if(o===Ys)throw new Error(`${H} got unexpected break`);return[o,r.subarray(n.pos())]}function V0(r,e){let[t,n]=$0(r,e);if(n.length>0)throw new Error(`${H} too many terminals, data makes no sense`);return t}var Rd=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(Rd.prototype,Symbol.toStringTag,{value:"Tagged"});var K0=class extends Array{constructor(){super(),this.inRecursive=[]}prefix(e){let t=this.inRecursive[this.inRecursive.length-1];t&&(p.equals(t.type,p.array)&&(t.elements++,t.elements!==1&&e.push([44])),p.equals(t.type,p.map)&&(t.elements++,t.elements!==1&&(t.elements%2===1?e.push([44]):e.push([58]))))}[p.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)}[p.negint.major](e,t){this[p.uint.major](e,t)}[p.bytes.major](e,t){throw new Error(`${Dn} unsupported type: Uint8Array`)}[p.string.major](e,t){this.prefix(e);let n=Jc(JSON.stringify(t.value));e.push(n.length>32?Si(n):n)}[p.array.major](e,t){this.prefix(e),this.inRecursive.push({type:p.array,elements:0}),e.push([91])}[p.map.major](e,t){this.prefix(e),this.inRecursive.push({type:p.map,elements:0}),e.push([123])}[p.tag.major](e,t){}[p.float.major](e,t){if(t.type.name==="break"){let s=this.inRecursive.pop();if(s){if(p.equals(s.type,p.array))e.push([93]);else if(p.equals(s.type,p.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(`${Dn} 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 DN(r,e){if(Array.isArray(r[0])||Array.isArray(e[0]))throw new Error(`${Dn} complex map keys are not supported`);let t=r[0],n=e[0];if(t.type!==p.string||n.type!==p.string)throw new Error(`${Dn} non-string map keys are not supported`);if(t<n)return-1;if(t>n)return 1;throw new Error(`${Dn} unexpected duplicate map keys, this is not supported`)}var RN={addBreakTokens:!0,mapSorter:DN};function q0(r,e){return e=Object.assign({},RN,e),F0(r,new K0,e)}var Xs=class{constructor(e,t={}){this._pos=0,this.data=e,this.options=t,this.modeStack=["value"],this.lastToken=""}pos(){return this._pos}done(){return this._pos>=this.data.length}ch(){return this.data[this._pos]}currentMode(){return this.modeStack[this.modeStack.length-1]}skipWhitespace(){let e=this.ch();for(;e===32||e===9||e===13||e===10;)e=this.data[++this._pos]}expect(e){if(this.data.length-this._pos<e.length)throw new Error(`${H} unexpected end of input at position ${this._pos}`);for(let t=0;t<e.length;t++)if(this.data[this._pos++]!==e[t])throw new Error(`${H} unexpected token at position ${this._pos}, expected to find '${String.fromCharCode(...e)}'`)}parseNumber(){let e=this._pos,t=!1,n=!1,o=a=>{for(;!this.done();){let c=this.ch();if(a.includes(c))this._pos++;else break}};if(this.ch()===45&&(t=!0,this._pos++),this.ch()===48)if(this._pos++,this.ch()===46)this._pos++,n=!0;else return new B(p.uint,0,this._pos-e);if(o([48,49,50,51,52,53,54,55,56,57]),t&&this._pos===e+1)throw new Error(`${H} unexpected token at position ${this._pos}`);if(!this.done()&&this.ch()===46){if(n)throw new Error(`${H} unexpected token at position ${this._pos}`);n=!0,this._pos++,o([48,49,50,51,52,53,54,55,56,57])}!this.done()&&(this.ch()===101||this.ch()===69)&&(n=!0,this._pos++,!this.done()&&(this.ch()===43||this.ch()===45)&&this._pos++,o([48,49,50,51,52,53,54,55,56,57]));let i=String.fromCharCode.apply(null,this.data.subarray(e,this._pos)),s=parseFloat(i);return n?new B(p.float,s,this._pos-e):this.options.allowBigInt!==!0||Number.isSafeInteger(s)?new B(s>=0?p.uint:p.negint,s,this._pos-e):new B(s>=0?p.uint:p.negint,BigInt(i),this._pos-e)}parseString(){if(this.ch()!==34)throw new Error(`${H} unexpected character at position ${this._pos}; this shouldn't happen`);this._pos++;for(let i=this._pos,s=0;i<this.data.length&&s<65536;i++,s++){let a=this.data[i];if(a===92||a<32||a>=128)break;if(a===34){let c=String.fromCharCode.apply(null,this.data.subarray(this._pos,i));return this._pos=i+1,new B(p.string,c,s)}}let e=this._pos,t=[],n=()=>{if(this._pos+4>=this.data.length)throw new Error(`${H} unexpected end of unicode escape sequence at position ${this._pos}`);let i=0;for(let s=0;s<4;s++){let a=this.ch();if(a>=48&&a<=57)a-=48;else if(a>=97&&a<=102)a=a-97+10;else if(a>=65&&a<=70)a=a-65+10;else throw new Error(`${H} unexpected unicode escape character at position ${this._pos}`);i=i*16+a,this._pos++}return i},o=()=>{let i=this.ch(),s=null,a=i>239?4:i>223?3:i>191?2:1;if(this._pos+a>this.data.length)throw new Error(`${H} unexpected unicode sequence at position ${this._pos}`);let c,u,l,f;switch(a){case 1:i<128&&(s=i);break;case 2:c=this.data[this._pos+1],(c&192)===128&&(f=(i&31)<<6|c&63,f>127&&(s=f));break;case 3:c=this.data[this._pos+1],u=this.data[this._pos+2],(c&192)===128&&(u&192)===128&&(f=(i&15)<<12|(c&63)<<6|u&63,f>2047&&(f<55296||f>57343)&&(s=f));break;case 4:c=this.data[this._pos+1],u=this.data[this._pos+2],l=this.data[this._pos+3],(c&192)===128&&(u&192)===128&&(l&192)===128&&(f=(i&15)<<18|(c&63)<<12|(u&63)<<6|l&63,f>65535&&f<1114112&&(s=f))}s===null?(s=65533,a=1):s>65535&&(s-=65536,t.push(s>>>10&1023|55296),s=56320|s&1023),t.push(s),this._pos+=a};for(;!this.done();){let i=this.ch(),s;switch(i){case 92:if(this._pos++,this.done())throw new Error(`${H} unexpected string termination at position ${this._pos}`);switch(s=this.ch(),this._pos++,s){case 34:case 39:case 92:case 47:t.push(s);break;case 98:t.push(8);break;case 116:t.push(9);break;case 110:t.push(10);break;case 102:t.push(12);break;case 114:t.push(13);break;case 117:t.push(n());break;default:throw new Error(`${H} unexpected string escape character at position ${this._pos}`)}break;case 34:return this._pos++,new B(p.string,eA(t),this._pos-e);default:if(i<32)throw new Error(`${H} invalid control character at position ${this._pos}`);i<128?(t.push(i),this._pos++):o()}}throw new Error(`${H} unexpected end of string at position ${this._pos}`)}parseValue(){switch(this.ch()){case 123:return this.modeStack.push("obj-start"),this._pos++,new B(p.map,1/0,1);case 91:return this.modeStack.push("array-start"),this._pos++,new B(p.array,1/0,1);case 34:return this.parseString();case 110:return this.expect([110,117,108,108]),new B(p.null,null,4);case 102:return this.expect([102,97,108,115,101]),new B(p.false,!1,5);case 116:return this.expect([116,114,117,101]),new B(p.true,!0,4);case 45:case 48:case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:return this.parseNumber();default:throw new Error(`${H} unexpected character at position ${this._pos}`)}}next(){switch(this.skipWhitespace(),this.currentMode()){case"value":return this.modeStack.pop(),this.parseValue();case"array-value":{if(this.modeStack.pop(),this.ch()===93)return this._pos++,this.skipWhitespace(),new B(p.break,void 0,1);if(this.ch()!==44)throw new Error(`${H} unexpected character at position ${this._pos}, was expecting array delimiter but found '${String.fromCharCode(this.ch())}'`);return this._pos++,this.modeStack.push("array-value"),this.skipWhitespace(),this.parseValue()}case"array-start":return this.modeStack.pop(),this.ch()===93?(this._pos++,this.skipWhitespace(),new B(p.break,void 0,1)):(this.modeStack.push("array-value"),this.skipWhitespace(),this.parseValue());case"obj-key":if(this.ch()===125)return this.modeStack.pop(),this._pos++,this.skipWhitespace(),new B(p.break,void 0,1);if(this.ch()!==44)throw new Error(`${H} unexpected character at position ${this._pos}, was expecting object delimiter but found '${String.fromCharCode(this.ch())}'`);this._pos++,this.skipWhitespace();case"obj-start":{if(this.modeStack.pop(),this.ch()===125)return this._pos++,this.skipWhitespace(),new B(p.break,void 0,1);let e=this.parseString();if(this.skipWhitespace(),this.ch()!==58)throw new Error(`${H} unexpected character at position ${this._pos}, was expecting key/value delimiter ':' but found '${String.fromCharCode(this.ch())}'`);return this._pos++,this.modeStack.push("obj-value"),e}case"obj-value":return this.modeStack.pop(),this.modeStack.push("obj-key"),this.skipWhitespace(),this.parseValue();default:throw new Error(`${H} unexpected parse state at position ${this._pos}; this shouldn't happen`)}}};function H0(r,e){return e=Object.assign({tokenizer:new Xs(r,e)},e),V0(r,e)}function ON(r){return r instanceof ArrayBuffer?new Uint8Array(r,0,r.byteLength):r}function MN(r){if(r.asCID!==r&&r["/"]!==r.bytes)return null;let e=Q.asCID(r);if(!e)return null;let t=e.toString();return[new B(p.map,1/0,1),new B(p.string,"/",1),new B(p.string,t,t.length),new B(p.break,void 0,1)]}function Ud(r){let e=yt.encode(r).slice(1);return[new B(p.map,1/0,1),new B(p.string,"/",1),new B(p.map,1/0,1),new B(p.string,"bytes",5),new B(p.string,e,e.length),new B(p.break,void 0,1),new B(p.break,void 0,1)]}function Wr(r){return Ud(new Uint8Array(r.buffer,r.byteOffset,r.byteLength))}function FN(r){return Ud(new Uint8Array(r))}function $N(){throw new Error("`undefined` is not supported by the IPLD Data Model and cannot be encoded")}function VN(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 KN={typeEncoders:{Object:MN,Buffer:Ud,Uint8Array:Ud,Int8Array:Wr,Uint16Array:Wr,Int16Array:Wr,Uint32Array:Wr,Int32Array:Wr,Float32Array:Wr,Float64Array:Wr,Uint8ClampedArray:Wr,BigInt64Array:Wr,BigUint64Array:Wr,DataView:Wr,ArrayBuffer:FN,undefined:$N,number:VN}},z0=class extends Xs{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(p.equals(e.type,p.map)){let t=this._next();if(p.equals(t.type,p.string)&&t.value==="/"){let n=this._next();if(p.equals(n.type,p.string)){let o=this._next();if(!p.equals(o.type,p.break))throw new Error("Invalid encoded CID form");return this.tokenBuffer.push(n),new B(p.tag,42,0)}if(p.equals(n.type,p.map)){let o=this._next();if(p.equals(o.type,p.string)&&o.value==="bytes"){let i=this._next();if(p.equals(i.type,p.string)){for(let a=0;a<2;a++){let c=this._next();if(!p.equals(c.type,p.break))throw new Error("Invalid encoded Bytes form")}let s=yt.decode(`m${i.value}`);return new B(p.bytes,s,i.value.length)}this.tokenBuffer.push(i)}this.tokenBuffer.push(o)}this.tokenBuffer.push(n)}this.tokenBuffer.push(t)}return e}},JA={allowIndefinite:!1,allowUndefined:!1,allowNaN:!1,allowInfinity:!1,allowBigInt:!0,strict:!0,useMaps:!1,rejectDuplicateMapKeys:!0,tags:{42:r=>Q.parse(r())}},qN="dag-json",j0=297,QA=r=>q0(r,KN),eS=r=>{let e=ON(r),t=Object.assign(JA,{tokenizer:new z0(e,JA)});return H0(e,t)},HN=r=>zN.decode(QA(r));var zN=new TextDecoder,jN=r=>eS(GN.encode(r)),GN=new TextEncoder;var Q0={};Me(Q0,{code:()=>J0,createLink:()=>lS,createNode:()=>uS,decode:()=>s3,encode:()=>i3,name:()=>o3,prepare:()=>X0,validate:()=>Z0});var WN=new TextDecoder;function W0(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 Od(r,e){let t;[t,e]=W0(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 tS(r,e){let t;return[t,e]=W0(r,e),[t&7,t>>3,e]}function YN(r){let e={},t=r.length,n=0;for(;n<t;){let o,i;if([o,i,n]=tS(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]=Od(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]=Od(r,n),e.Name=WN.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]=W0(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 rS(r){let e=r.length,t=0,n,o=!1,i;for(;t<e;){let a,c;if([a,c,t]=tS(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]=Od(r,t),n&&(o=!0)}else if(c===2){if(o)throw new Error("protobuf: (PBNode) duplicate Links section");n||(n=[]);let u;[u,t]=Od(r,t),n.push(YN(u))}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 oS=new TextEncoder,nS=2**32,XN=2**31;function ZN(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=nu(e,t,r.Tsize)-1,e[t]=24}if(typeof r.Name=="string"){let n=oS.encode(r.Name);t-=n.length,e.set(n,t),t=nu(e,t,n.length)-1,e[t]=18}return r.Hash&&(t-=r.Hash.length,e.set(r.Hash,t),t=nu(e,t,r.Hash.length)-1,e[t]=10),e.length-t}function iS(r){let e=QN(r),t=new Uint8Array(e),n=e;if(r.Data&&(n-=r.Data.length,t.set(r.Data,n),n=nu(t,n,r.Data.length)-1,t[n]=10),r.Links)for(let o=r.Links.length-1;o>=0;o--){let i=ZN(r.Links[o],t.subarray(0,n));n-=i,n=nu(t,n,i)-1,t[n]=18}return t}function JN(r){let e=0;if(r.Hash){let t=r.Hash.length;e+=1+t+Zs(t)}if(typeof r.Name=="string"){let t=oS.encode(r.Name).length;e+=1+t+Zs(t)}return typeof r.Tsize=="number"&&(e+=1+Zs(r.Tsize)),e}function QN(r){let e=0;if(r.Data){let t=r.Data.length;e+=1+t+Zs(t)}if(r.Links)for(let t of r.Links){let n=JN(t);e+=1+n+Zs(n)}return e}function nu(r,e,t){e-=Zs(t);let n=e;for(;t>=XN;)r[e++]=t&127|128,t/=128;for(;t>=128;)r[e++]=t&127|128,t>>>=7;return r[e]=t,n}function Zs(r){return r%2===0&&r++,Math.floor((e3(r)+6)/7)}function e3(r){let e=0;return r>=nS&&(r=Math.floor(r/nS),e=32),r>=65536&&(r>>>=16,e+=16),r>=256&&(r>>>=8,e+=8),e+t3[r]}var t3=[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 r3=["Data","Links"],n3=["Hash","Name","Tsize"],Y0=new TextEncoder;function aS(r,e){if(r===e)return 0;let t=r.Name?Y0.encode(r.Name):[],n=e.Name?Y0.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 sS(r,e){return!Object.keys(r).some(t=>!e.includes(t))}function cS(r){if(typeof r.asCID=="object"){let t=Q.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=Q.asCID(r.Hash);try{t||(typeof r.Hash=="string"?t=Q.parse(r.Hash):r.Hash instanceof Uint8Array&&(t=Q.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 X0(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=Y0.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(cS),e.Links.sort(aS);else throw new TypeError("Invalid DAG-PB form");else e.Links=[];return e}function Z0(r){if(!r||typeof r!="object"||Array.isArray(r)||r instanceof Uint8Array||r["/"]&&r["/"]===r.bytes)throw new TypeError("Invalid DAG-PB form");if(!sS(r,r3))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(!sS(t,n3))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&&aS(t,r.Links[e-1])===-1)throw new TypeError("Invalid DAG-PB form (links must be sorted by Name bytes)")}}function uS(r,e=[]){return X0({Data:r,Links:e})}function lS(r,e,t){return cS({Hash:t,Name:r,Tsize:e})}function fS(r){return r instanceof ArrayBuffer?new Uint8Array(r,0,r.byteLength):r}var o3="dag-pb",J0=112;function i3(r){Z0(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),iS(e)}function s3(r){let e=fS(r),t=rS(e),n={};return t.Data&&(n.Data=t.Data),t.Links&&(n.Links=t.Links.map(o=>{let i={};try{i.Hash=Q.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 Js(r){return r?.then!=null}function dS(r=[],e){let t={[J0]:Q0,[Vo]:ji,[C0]:B0,[j0]:G0,[Cm]:nl};return r.forEach(n=>{t[n.code]=n}),async n=>{let o=t[n];if(o==null&&e!=null){let i=e(n);Js(i)?o=await i:o=i,t[o.code]=o}if(o!=null)return o;throw new Mc(`Could not load codec for ${n}`)}}function hS(r=[],e){let t={[Ir.code]:Ir,[ol.code]:ol,[Ve.code]:Ve};return r.forEach(n=>{t[n.code]=n}),async n=>{let o=t[n];if(o==null&&e!=null){let i=e(n);Js(i)?o=await i:o=i,t[o.code]=o}if(o!=null)return o;throw new Oc(`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 wr=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 Un=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 Md=0,Qs=class extends Error{static name="IdentityHashDigestTooLongError";name="IdentityHashDigestTooLongError"},Fd=class extends Un{child;maxDigestLength;constructor(e,t){super(),this.child=e,this.maxDigestLength=t?.maxDigestLength}put(e,t,n){if(e.multihash.code===Md){if(this.maxDigestLength!=null&&e.multihash.digest.byteLength>this.maxDigestLength)throw new Qs(`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===Md){if(this.maxDigestLength!=null&&e.multihash.digest.byteLength>this.maxDigestLength)throw new Qs(`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 wr;yield*this.child.get(e,t)}has(e,t){if(e.multihash.code===Md){if(this.maxDigestLength!=null&&e.multihash.digest.byteLength>this.maxDigestLength)throw new Qs(`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===Md){if(this.maxDigestLength!=null&&e.multihash.digest.byteLength>this.maxDigestLength)throw new Qs(`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 a3(r){return r[Symbol.asyncIterator]!=null}function c3(r,e){let t=0;if(a3(r))return(async function*(){for await(let c of r)await e(c,t++)&&(yield c)})();let n=Ns(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 Yr=c3;function u3(r){return r[Symbol.asyncIterator]!=null}function pS(r){return r?.then!=null}function l3(r,e){let t=0;if(u3(r))return(async function*(){for await(let c of r){let u=e(c,t++);pS(u)&&await u,yield c}})();let n=Ns(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 u=e(c,t++);pS(u)&&await u,yield c}})();let a=e;return(function*(){yield o;for(let c of n)a(c,t++),yield c})()}var ew=l3;var f3=128,ea=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 Fd(e.blockstore,{maxDigestLength:t.maxIdentityHashDigestLength??f3}),this.getHasher=e.getHasher}async put(e,t,n={}){return await this.child.has(e,n)?(n.onProgress?.(new $("blocks:put:duplicate",e)),e):(n.onProgress?.(new $("blocks:put:providers:notify",e)),await Promise.all(this.blockBrokers.map(async o=>o.announce?.(e,n))),n.onProgress?.(new $("blocks:put:blockstore:put",e)),this.child.put(e,t,n))}async*putMany(e,t={}){let n=Yr(e,async({cid:i})=>{let s=await this.child.has(i,t);return s&&t.onProgress?.(new $("blocks:put-many:duplicate",i)),!s}),o=ew(n,async({cid:i})=>{t.onProgress?.(new $("blocks:put-many:providers:notify",i)),await Promise.all(this.blockBrokers.map(async s=>s.announce?.(i,t)))});t.onProgress?.(new $("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 Rc("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 $("blocks:get:providers:get",e));let s=await mS(e,this.blockBrokers,i,{...t,log:this.log});t.onProgress?.(new $("blocks:get:blockstore:put",e)),await this.child.put(e,s,t),t.onProgress?.(new $("blocks:get:providers:notify",e)),await Promise.all(this.blockBrokers.map(async a=>a.announce?.(e,t))),yield s;return}t.onProgress?.(new $("blocks:get:blockstore:get",e)),yield*this.child.get(e,t)}async*getMany(e,t={}){t.onProgress?.(new $("blocks:get-many:blockstore:get-many")),yield*this.child.getMany(ew(e,async n=>{let o=await this.child.has(n,t),i=t.offline===!0;if(!o){if(i)throw new Rc("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 $("blocks:get-many:providers:get",n));let a=await mS(n,this.blockBrokers,s,{...t,log:this.log});t.onProgress?.(new $("blocks:get-many:blockstore:put",n)),await this.child.put(n,a,t),t.onProgress?.(new $("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 $("blocks:delete:blockstore:delete",e)),await this.child.delete(e,t)}async*deleteMany(e,t={}){t.onProgress?.(new $("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 $("blocks:get-all:blockstore:get-many")),yield*this.child.getAll(e)}};async function mS(r,e,t,n){let o=h3(r,t),i=new AbortController,s=Ie([i.signal,n.signal]);i.signal;let a=[];for(let c of e)d3(c)&&a.push(c);if(a.length===0)throw new xi(`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 u=!1,l=await c.retrieve(r,{...n,signal:s,validateFn:async f=>{await o(f),n.signal?.throwIfAborted(),u=!0}});return u||(await o(l),n.signal?.throwIfAborted()),l}catch(u){throw n.log.error("could not retrieve verified block for %c from %s - %e",r,c.name,u),u}}))}catch(c){throw new Kf(c.errors,`Failed to load block for ${r}`)}finally{i.abort(),s.clear()}}function d3(r){return typeof r.retrieve=="function"}var h3=(r,e)=>{if(e==null)throw new T(`No hasher configured for multihash code 0x${r.multihash.code.toString(16)}, please configure one. You can look up which hash this is at https://github.com/multiformats/multicodec/blob/master/table.csv`);return async t=>{let n,o=e.digest(t,{truncate:r.multihash.digest.byteLength});if(Js(o)?n=await o:n=o,!ce(n.digest,r.multihash.digest))throw new Wn("Hash of downloaded block did not match multihash from passed CID")}};var $d=class extends ea{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=Ie([this.closeController.signal,n.signal]);try{return await super.put(e,t,{...n,signal:o})}finally{o.clear()}}async*putMany(e,t={}){let n=Ie([this.closeController.signal,t.signal]);try{yield*super.putMany(e,{...t,signal:n})}finally{n.clear()}}async*get(e,t={}){let n=Ie([this.closeController.signal,t.signal]);try{yield*super.get(e,{...t,signal:n})}finally{n.clear()}}async*getMany(e,t={}){let n=Ie([this.closeController.signal,t.signal]);try{yield*super.getMany(e,{...t,signal:n})}finally{n.clear()}}async delete(e,t={}){let n=Ie([this.closeController.signal,t.signal]);try{await super.delete(e,{...t,signal:n})}finally{n.clear()}}async*deleteMany(e,t={}){let n=Ie([this.closeController.signal,t.signal]);try{yield*super.deleteMany(e,{...t,signal:n})}finally{n.clear()}}async has(e,t={}){let n=Ie([this.closeController.signal,t.signal]);try{return await super.has(e,{...t,signal:n})}finally{n.clear()}}async*getAll(e={}){let t=Ie([this.closeController.signal,e.signal]);try{yield*super.getAll({...e,signal:t})}finally{t.clear()}}};var Vd=class extends ea{started;constructor(e,t={}){super(e,t),this.started=!1}isStarted(){return this.started}async start(){await rn(this.child,...this.blockBrokers),this.started=!0}async stop(){await nn(this.child,...this.blockBrokers),this.started=!1}unwrap(){return this.child}createSession(e,t){if(this.blockBrokers.length===0)throw new xi("No block brokers configured");let n=this.blockBrokers.map(o=>o.createSession?.(t)).filter(o=>o!=null);if(n.length===0)throw new xi(`No configured block brokers support sessions - tried ${this.blockBrokers.map(o=>o.name).join(", ")}`);return new $d({blockstore:this.child,blockBrokers:n,getHasher:this.getHasher,logger:this.logger},{root:e})}};var iu=class extends ze{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=uo(this.maxProviders),this.initialProviders=[...t.providers??[]]}async retrieve(e,t={}){let n=yt.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=ge(),s={promise:i.promise,observers:1,queryFilter:uo(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,u=new $r({concurrency:this.maxProviders});u.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)}),u.addEventListener("success",d=>{c=!0,i.resolve(d.detail.result)}),u.addEventListener("idle",()=>{if(c){this.log.trace("session idle, found block");return}if(t.signal?.aborted===!0){this.log.trace("session idle, signal aborted");return}Promise.resolve().then(async()=>{this.log("no session peers had block for for %c, finding new providers",e);for(let d=0;d<this.minProviders&&this.providers.length!==0;d++){let h=this.providers[Math.floor(Math.random()*this.providers.length)];this.evict(h)}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(d=>{this.log.error("could not find new providers for %c - %e",e,d),i.reject(d)})});let l=d=>{let h=this.toFilterKey(d.detail);s.queryFilter.has(h)||(s.queryFilter.add(h),this.emitFoundProviderProgressEvent(e,d.detail,t),u.add(async()=>this.queryProvider(e,d.detail,t),{provider:d.detail}).catch(m=>{t.signal?.aborted!==!0&&this.log.error("error retrieving session block for %c - %e",e,m)}))};if(this.addEventListener("provider",l),a)try{await kt(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&&i.reject(d),d}Promise.all([...this.providers].filter(d=>{let h=this.toFilterKey(d),m=s.queryFilter.has(h);return m||s.queryFilter.add(this.toFilterKey(d)),!m}).map(async d=>u.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=()=>{i.reject(new Rt(t.signal?.reason??"Session aborted")),u.abort()};t.signal?.addEventListener("abort",f);try{return await i.promise}finally{this.removeEventListener("provider",l),t.signal?.removeEventListener("abort",f),u.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=ge(),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 u=s.initialProviders.pop();if(u==null)continue;let l=await s.convertToProvider(u,"manual",n);l!=null&&(yield l)}},c=async function*(){yield*a(),yield*s.findNewProviders(e,n)};for await(let u of c()){if(this.providers.length===this.maxProviders||n.signal?.aborted===!0)break;if(!this.hasProvider(u)&&(this.log("found %d providers, %d in session",i,this.providers.length),this.providers.push(u),this.safeDispatchEvent("provider",{detail:u}),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 Uc(`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}};var Kd=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=hS(e.hashers,e.loadHasher),this.getCodec=dS(e.codecs,e.loadCodec),this.dns=e.dns??vf(),this.metrics=e.metrics,this.libp2p=e.libp2p,this.events=new ze;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 zf(t,{routers:(e.routers??[]).flatMap(o=>{typeof o=="function"&&(o=o(t));let i=[o],s=p3(o);s!=null&&i.push(s);let a=m3(o);return a!=null&&i.push(a),i}),providerLookupConcurrency:e.providerLookupConcurrency}),t.blockBrokers=e.blockBrokers.map(o=>o(t));let n=new Vd(t,e);this.pins=new Hf(e.datastore,n,this.getCodec),this.blockstore=new cd(n,this.pins,{holdGcLock:e.holdGcLock??!0}),this.datastore=e.datastore}async start(){await $v(this.datastore),await rn(this.blockstore,this.datastore,this.routing,this.libp2p),this.events.dispatchEvent(new CustomEvent("start",{detail:this}))}async stop(){await nn(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 yc(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 $("helia:gc:deleted",i))}catch(s){n.log.error("error during gc - %e",s),e.onProgress?.(new $("helia:gc:error",s))}})()))}finally{t()}this.log("gc finished")}};function p3(r){return r?.[Uo]}function m3(r){return r?.[Mo]}var g3=[6,53,56,54,55];function gS(r){return bS("sni",r)?.value}function yS(r){let e=bS("tcp",r)?.value;return e==null?"":`:${e}`}function bS(r,e){return e.find(t=>t.name===r)}function wS(r){return r.some(({code:e})=>e===448)}function Xr(r,e){let t=xS[r.name];if(t==null)throw new Error(`Can't interpret protocol ${r.name}`);let n=t(r,e);return r.code===41?`[${n}]`:n}var xS={ip4:(r,e)=>r.value,ip6:(r,e)=>e.length===0?r.value:`[${r.value}]`,tcp:(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");return`tcp://${Xr(t,e)}:${r.value}`},udp:(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");return`udp://${Xr(t,e)}:${r.value}`},dnsaddr:(r,e)=>r.value,dns4:(r,e)=>r.value,dns6:(r,e)=>r.value,dns:(r,e)=>r.value,ipfs:(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");return`${Xr(t,e)}`},p2p:(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");return`${Xr(t,e)}`},http:(r,e)=>{let t=wS(e),n=gS(e),o=yS(e);if(t&&n!=null)return`https://${n}${o}`;let i=t?"https://":"http://",s=e.pop();if(s==null)throw new Error("Unexpected end of multiaddr");let a=Xr(s,e);return a=a?.replace("tcp://",""),`${i}${a}`},"http-path":(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");let n=Xr(t,e),o=decodeURIComponent(r.value??"");return`${n}${o}`},tls:(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");return Xr(t,e)},sni:(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");return Xr(t,e)},https:(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");let n=Xr(t,e);return n=n?.replace("tcp://",""),`https://${n}`},ws:(r,e)=>{let t=wS(e),n=gS(e),o=yS(e);if(t&&n!=null)return`wss://${n}${o}`;let i=t?"wss://":"ws://",s=e.pop();if(s==null)throw new Error("Unexpected end of multiaddr");let a=Xr(s,e);return a=a?.replace("tcp://",""),`${i}${a}`},wss:(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");let n=Xr(t,e);return n=n?.replace("tcp://",""),`wss://${n}`}};function qd(r,e){let n=fe(r).getComponents(),o=n.pop();if(o==null)throw new Error("Unexpected end of multiaddr");let i=xS[o.name];if(i==null)throw new Error(`No interpreter found for ${o.name}`);let s=i(o,n)??"";return e?.assumeHttp!==!1&&g3.includes(o.code)&&(s=s.replace(/^.*:\/\//,""),o.value==="443"?s=`https://${s}`:s=`http://${s}`),(s.startsWith("http://")||s.startsWith("https://")||s.startsWith("ws://")||s.startsWith("wss://"))&&(s=new URL(s).toString(),s.endsWith("/")&&(s=s.substring(0,s.length-1))),s}var ES="[a-fA-F\\d:]",_o=r=>r&&r.includeBoundaries?`(?:(?<=\\s|^)(?=${ES})|(?<=${ES})(?=\\s|$))`:"",Zr="(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)(?:\\.(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)){3}",Ke="[a-fA-F\\d]{1,4}",Hd=`
|
|
13
|
+
${e}[Error list was empty]`,t.trim()}return u1(r,e)}Pt.formatters.e=r=>r==null?"undefined":f1(r);function rB(r){let e=()=>{};return e.enabled=!1,e.color="",e.diff=0,e.log=()=>{},e.namespace=r,e.destroy=()=>!0,e.extend=()=>e,e}function Cs(r){return{forComponent(e){return ur(e,r)}}}function ur(r,e){let t=rB(`${r}:trace`);return Pt.enabled(`${r}:trace`)&&Pt.names.map(n=>n.toString()).find(n=>n.includes(":trace"))!=null&&(t=Pt(`${r}:trace`,e)),Object.assign(Pt(r,e),{error:Pt(`${r}:error`,e),trace:t,newScope:n=>ur(`${r}:${n}`,e)})}function l1(r){if(r!=null&&(r=r.trim(),r.length!==0))return r}var Bs=class extends $r{has(e){return this.find(e)!=null}find(e){return this.queue.find(t=>e.equals(t.options.peerId))}};var ff=class extends $r{constructor(e={}){super({...e,sort:(t,n)=>t.options.priority>n.options.priority?-1:t.options.priority<n.options.priority?1:0})}};var df=class{memoryStorage;points;duration;blockDuration;keyPrefix;constructor(e={}){this.points=e.points??4,this.duration=e.duration??1,this.blockDuration=e.blockDuration??0,this.keyPrefix=e.keyPrefix??"rlflx",this.memoryStorage=new Dy}consume(e,t=1,n={}){let o=this.getKey(e),i=this._getKeySecDuration(n),s=this.memoryStorage.incrby(o,t,i);if(s.remainingPoints=Math.max(this.points-s.consumedPoints,0),s.consumedPoints>this.points)throw this.blockDuration>0&&s.consumedPoints<=this.points+t&&(s=this.memoryStorage.set(o,s.consumedPoints,this.blockDuration)),new Vl("Rate limit exceeded",s);return s}penalty(e,t=1,n={}){let o=this.getKey(e),i=this._getKeySecDuration(n),s=this.memoryStorage.incrby(o,t,i);return s.remainingPoints=Math.max(this.points-s.consumedPoints,0),s}reward(e,t=1,n={}){let o=this.getKey(e),i=this._getKeySecDuration(n),s=this.memoryStorage.incrby(o,-t,i);return s.remainingPoints=Math.max(this.points-s.consumedPoints,0),s}block(e,t){let n=t*1e3,o=this.points+1;return this.memoryStorage.set(this.getKey(e),o,t),{remainingPoints:0,msBeforeNext:n===0?-1:n,consumedPoints:o,isFirstInDuration:!1}}set(e,t,n=0){let o=(n>=0?n:this.duration)*1e3;return this.memoryStorage.set(this.getKey(e),t,n),{remainingPoints:0,msBeforeNext:o===0?-1:o,consumedPoints:t,isFirstInDuration:!1}}get(e){let t=this.memoryStorage.get(this.getKey(e));return t!=null&&(t.remainingPoints=Math.max(this.points-t.consumedPoints,0)),t}delete(e){this.memoryStorage.delete(this.getKey(e))}_getKeySecDuration(e){return e?.customDuration!=null&&e.customDuration>=0?e.customDuration:this.duration}getKey(e){return this.keyPrefix.length>0?`${this.keyPrefix}:${e}`:e}parseKey(e){return e.substring(this.keyPrefix.length)}},Dy=class{storage;constructor(){this.storage=new Map}incrby(e,t,n){let o=this.storage.get(e);if(o!=null){let i=o.expiresAt!=null?o.expiresAt.getTime()-new Date().getTime():-1;return o.expiresAt==null||i>0?(o.value+=t,{remainingPoints:0,msBeforeNext:i,consumedPoints:o.value,isFirstInDuration:!1}):this.set(e,t,n)}return this.set(e,t,n)}set(e,t,n){let o=n*1e3,i=this.storage.get(e);i!=null&&clearTimeout(i.timeoutId);let s={value:t,expiresAt:o>0?new Date(Date.now()+o):void 0};return this.storage.set(e,s),o>0&&(s.timeoutId=setTimeout(()=>{this.storage.delete(e)},o),s.timeoutId.unref!=null&&s.timeoutId.unref()),{remainingPoints:0,msBeforeNext:o===0?-1:o,consumedPoints:s.value,isFirstInDuration:!0}}get(e){let t=this.storage.get(e);if(t!=null)return{remainingPoints:0,msBeforeNext:t.expiresAt!=null?t.expiresAt.getTime()-new Date().getTime():-1,consumedPoints:t.value,isFirstInDuration:!1}}delete(e){let t=this.storage.get(e);return t!=null?(t.timeoutId!=null&&clearTimeout(t.timeoutId),this.storage.delete(e),!0):!1}};var Ry=class extends Map{metric;constructor(e){super();let{name:t,metrics:n}=e;this.metric=n.registerMetric(t),this.updateComponentMetric()}set(e,t){return super.set(e,t),this.updateComponentMetric(),this}delete(e){let t=super.delete(e);return this.updateComponentMetric(),t}clear(){super.clear(),this.updateComponentMetric()}updateComponentMetric(){this.metric.update(this.size)}};function xt(r){let{name:e,metrics:t}=r,n;return t!=null?n=new Ry({name:e,metrics:t}):n=new Map,n}function nB(r){return r[Symbol.asyncIterator]!=null}function oB(r){if(nB(r))return(async()=>{for await(let e of r);})();for(let e of r);}var yc=oB;function iB(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 Ns=iB;function sB(r){return r[Symbol.asyncIterator]!=null}function aB(r,e){let t=0;if(sB(r))return(async function*(){for await(let c of r)yield e(c,t++)})();let n=Ns(r),{value:o,done:i}=n.next();if(i===!0)return(function*(){})();let s=e(o,t++);if(typeof s.then=="function")return(async function*(){yield await s;for(let c of n)yield e(c,t++)})();let a=e;return(function*(){yield s;for(let c of n)yield a(c,t++)})()}var hf=aB;function cB(r){return r[Symbol.asyncIterator]!=null}function uB(r,e){return cB(r)?(async function*(){let t=0;if(!(e<1)){for await(let n of r)if(yield n,t++,t===e)return}})():(function*(){let t=0;if(!(e<1)){for(let n of r)if(yield n,t++,t===e)return}})()}var pf=uB;var Ft=class extends Error{static name="AbortError";name="AbortError";constructor(e="The operation was aborted",...t){super(e,...t)}};async function mf(r,e,t,n){let o=new Ft(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(){Oy(t,"abort",f),Oy(r,e,u),Oy(r,i,l)}let u=d=>{try{if(n?.filter?.(d)===!1)return}catch(h){c(),a(h);return}c(),s(d)},l=d=>{if(c(),d instanceof Error){a(d);return}a(d.detail??n?.error??new Error(`The "${n?.errorEvent}" event was emitted but the event had no '.detail' field. Pass an 'error' option to race-event to change this message.`))},f=()=>{c(),a(o)};Uy(t,"abort",f),Uy(r,e,u),Uy(r,i,l)})}function Uy(r,e,t){r!=null&&(d1(r)?r.addEventListener(e,t):r.addListener(e,t))}function Oy(r,e,t){r!=null&&(d1(r)?r.removeEventListener(e,t):r.removeListener(e,t))}function d1(r){return typeof r.addEventListener=="function"&&typeof r.removeEventListener=="function"}var h1=Symbol.for("nodejs.util.inspect.custom"),lB=114,wc=class{type;multihash;publicKey;string;constructor(e){this.type=e.type,this.multihash=e.multihash,Object.defineProperty(this,"string",{enumerable:!1,writable:!0})}get[Symbol.toStringTag](){return`PeerId(${this.toString()})`}[Qu]=!0;toString(){return this.string==null&&(this.string=ke.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return Q.createV1(lB,this.multihash)}toJSON(){return this.toString()}equals(e){if(e==null)return!1;if(e instanceof Uint8Array)return ce(this.multihash.bytes,e);if(typeof e=="string")return this.toString()===e;if(e?.toMultihash()?.bytes!=null)return ce(this.multihash.bytes,e.toMultihash().bytes);throw new Error("not valid Id")}[h1](){return`PeerId(${this.toString()})`}},bc=class extends wc{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}},xc=class extends wc{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.publicKey}},Ec=class extends wc{type="secp256k1";publicKey;constructor(e){super({...e,type:"secp256k1"}),this.publicKey=e.publicKey}},fB=2336,vc=class{type="url";multihash;publicKey;url;constructor(e){this.url=e.toString(),this.multihash=Ve.digest(L(this.url))}[h1](){return`PeerId(${this.url})`}[Qu]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return Q.createV1(fB,this.toMultihash())}toJSON(){return this.toString()}equals(e){return e==null?!1:(e instanceof Uint8Array&&(e=j(e)),e.toString()===this.toString())}};var dB=114,p1=2336;function lr(r,e){let t;if(r.charAt(0)==="1"||r.charAt(0)==="Q")t=Ct(ke.decode(`z${r}`));else{if(r.startsWith("k51qzi5uqu5")||r.startsWith("kzwfwjn5ji4")||r.startsWith("k2k4r8")||r.startsWith("bafz"))return Bn(Q.parse(r));if(e==null)throw new T('Please pass a multibase decoder for strings that do not start with "1" or "Q"');t=Ct(e.decode(r))}return po(t)}function My(r){if(r.type==="Ed25519")return new xc({multihash:r.toCID().multihash,publicKey:r});if(r.type==="secp256k1")return new Ec({multihash:r.toCID().multihash,publicKey:r});if(r.type==="RSA")return new bc({multihash:r.toCID().multihash,publicKey:r});throw new Sr}function m1(r){return My(r.publicKey)}function po(r){if(pB(r))return new bc({multihash:r});if(hB(r))try{let e=Pl(r);if(e.type==="Ed25519")return new xc({multihash:r,publicKey:e});if(e.type==="secp256k1")return new Ec({multihash:r,publicKey:e})}catch{let t=j(r.digest);return new vc(new URL(t))}throw new Wn("Supplied PeerID Multihash is invalid")}function Bn(r){if(r?.multihash==null||r.version==null||r.version===1&&r.code!==dB&&r.code!==p1)throw new ju("Supplied PeerID CID is invalid");if(r.code===p1){let e=j(r.multihash.digest);return new vc(new URL(e))}return po(r.multihash)}function hB(r){return r.code===Ve.code}function pB(r){return r.code===Ir.code}function mi(r,e){let t={[Symbol.iterator]:()=>t,next:()=>{let n=r.next(),o=n.value;return n.done===!0||o==null?{done:!0,value:void 0}:{done:!1,value:e(o)}}};return t}function gf(r){let e=Ct(ke.decode(`z${r}`));return po(e)}var fr=class{map;constructor(e){if(this.map=new Map,e!=null)for(let[t,n]of e.entries())this.map.set(t.toString(),{key:t,value:n})}[Symbol.iterator](){return this.entries()}clear(){this.map.clear()}delete(e){return this.map.delete(e.toString())}entries(){return mi(this.map.entries(),e=>[e[1].key,e[1].value])}forEach(e){this.map.forEach((t,n)=>{e(t.value,t.key,this)})}get(e){return this.map.get(e.toString())?.value}has(e){return this.map.has(e.toString())}set(e,t){this.map.set(e.toString(),{key:e,value:t})}keys(){return mi(this.map.values(),e=>e.key)}values(){return mi(this.map.values(),e=>e.value)}get size(){return this.map.size}};var gi=class r{set;constructor(e){if(this.set=new Set,e!=null)for(let t of e)this.set.add(t.toString())}get size(){return this.set.size}[Symbol.iterator](){return this.values()}add(e){this.set.add(e.toString())}clear(){this.set.clear()}delete(e){this.set.delete(e.toString())}entries(){return mi(this.set.entries(),e=>{let t=gf(e[0]);return[t,t]})}forEach(e){this.set.forEach(t=>{let n=gf(t);e(n,n,this)})}has(e){return this.set.has(e.toString())}values(){return mi(this.set.values(),e=>gf(e))}intersection(e){let t=new r;for(let n of e)this.has(n)&&t.add(n);return t}difference(e){let t=new r;for(let n of this)e.has(n)||t.add(n);return t}union(e){let t=new r;for(let n of e)t.add(n);for(let n of this)t.add(n);return t}};var Fy=class extends fr{metric;constructor(e){super();let{name:t,metrics:n}=e;this.metric=n.registerMetric(t),this.updateComponentMetric()}set(e,t){return super.set(e,t),this.updateComponentMetric(),this}delete(e){let t=super.delete(e);return this.updateComponentMetric(),t}clear(){super.clear(),this.updateComponentMetric()}updateComponentMetric(){this.metric.update(this.size)}};function $y(r){let{name:e,metrics:t}=r,n;return t!=null?n=new Fy({name:e,metrics:t}):n=new fr,n}function mB(r){return r[Symbol.asyncIterator]!=null}function gB(r){if(mB(r))return(async()=>{let n=new Uint8Array(0);for await(let o of r)n=je([n,o],n.length+o.length);return n})();let e=[],t=0;for(let n of r)e.push(n),t+=n.byteLength;return je(e,t)}var g1=gB;var yf=class extends AggregateError{static name="DNSQueryFailedError";name="DNSQueryFailedError"};var Ky=Ro(w1(),1);function qy(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 Ps=class{#e=[];enqueue(e,t){let{priority:n=0,id:o}=t??{},i={priority:n,id:o,run:e};if(this.size===0||this.#e[this.size-1].priority>=n){this.#e.push(i);return}let s=qy(this.#e,i,(a,c)=>c.priority-a.priority);this.#e.splice(s,0,i)}setPriority(e,t){let n=this.#e.findIndex(i=>i.id===e);if(n===-1)throw new ReferenceError(`No promise function with the id "${e}" exists in the queue.`);let[o]=this.#e.splice(n,1);this.enqueue(o.run,{priority:t,id:e})}remove(e){let t=this.#e.findIndex(n=>typeof e=="string"?n.id===e:n.run===e);t!==-1&&this.#e.splice(t,1)}dequeue(){return this.#e.shift()?.run}filter(e){return this.#e.filter(t=>t.priority===e.priority).map(t=>t.run)}get size(){return this.#e.length}};var yi=class extends Ky.default{#e;#t;#r=0;#a;#c=!1;#m=!1;#l;#I=0;#x=0;#f;#d;#u;#s=[];#i=0;#n;#T;#o=0;#y;#h;#L=1n;#w=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:Ps,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.#a=e.intervalCap,this.#l=e.interval,this.#u=e.strict,this.#n=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.#V()}#v(e){for(;this.#i<this.#s.length;){let n=this.#s[this.#i];if(n!==void 0&&e-n>=this.#l)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)}#D(e){this.#u?this.#s.push(e):this.#r++}#R(){this.#u?this.#s.length>this.#i&&this.#s.pop():this.#r>0&&this.#r--}#A(){return this.#s.length-this.#i}get#U(){return this.#t?!0:this.#u?this.#A()<this.#a:this.#r<this.#a}get#O(){return this.#o<this.#y}#M(){this.#o--,this.#o===0&&this.emit("pendingZero"),this.#b(),this.emit("next")}#F(){this.#d=void 0,this.#N(),this.#B()}#$(e){if(this.#u){if(this.#v(e),this.#A()>=this.#a){let n=this.#s[this.#i],o=this.#l-(e-n);return this.#S(o),!0}return!1}if(this.#f===void 0){let t=this.#I-e;if(t<0){if(this.#x>0){let n=e-this.#x;if(n<this.#l)return this.#S(this.#l-n),!0}this.#r=this.#e?this.#o:0}else return this.#S(t),!0}return!1}#S(e){this.#d===void 0&&(this.#d=setTimeout(()=>{this.#F()},e))}#k(){this.#f&&(clearInterval(this.#f),this.#f=void 0)}#C(){this.#d&&(clearTimeout(this.#d),this.#d=void 0)}#b(){if(this.#n.size===0){if(this.#k(),this.emit("empty"),this.#o===0){if(this.#C(),this.#u&&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 o=this.#n.dequeue();this.#t||(this.#D(t),this.#g()),this.emit("active"),o(),n&&this.#B(),e=!0}}return e}#B(){this.#t||this.#f!==void 0||this.#u||(this.#f=setInterval(()=>{this.#N()},this.#l),this.#I=Date.now()+this.#l)}#N(){this.#u||(this.#r===0&&this.#o===0&&this.#f&&this.#k(),this.#r=this.#e?this.#o:0),this.#_(),this.#g()}#_(){for(;this.#b(););}get concurrency(){return this.#y}set concurrency(e){if(!(typeof e=="number"&&e>=1))throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${e}\` (${typeof e})`);this.#y=e,this.#_()}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.#n.setPriority(e,t)}async add(e,t={}){return t={timeout:this.timeout,...t,id:t.id??(this.#L++).toString()},new Promise((n,o)=>{let i=Symbol(`task-${t.id}`),s=()=>{},a=async()=>{s(),this.#o++,this.#w.set(i,{id:t.id,priority:t.priority??0,startTime:Date.now(),timeout:t.timeout});let u;try{try{t.signal?.throwIfAborted()}catch(d){throw this.#K(),this.#w.delete(i),d}this.#x=Date.now();let l=e({signal:t.signal});if(t.timeout&&(l=ui(Promise.resolve(l),{milliseconds:t.timeout,message:`Task timed out after ${t.timeout}ms (queue has ${this.#o} running, ${this.#n.size} waiting)`})),t.signal){let{signal:d}=t;l=Promise.race([l,new Promise((h,m)=>{u=()=>{m(d.reason)},d.addEventListener("abort",u,{once:!0})})])}let f=await l;n(f),this.emit("completed",f)}catch(l){o(l),this.emit("error",l)}finally{u&&t.signal?.removeEventListener("abort",u),this.#w.delete(i),queueMicrotask(()=>{this.#M()})}};this.#n.enqueue(a,t);let c=()=>{if(this.#n instanceof Ps){this.#n.remove(a);return}this.#n.remove?.(t.id)};if(t.signal){let{signal:u}=t,l=()=>{s(),c(),o(u.reason),this.#b(),this.emit("next")};if(s=()=>{u.removeEventListener("abort",l),this.#E.delete(s)},u.aborted){l();return}u.addEventListener("abort",l,{once:!0}),this.#E.add(s)}this.emit("add"),this.#b()})}async addAll(e,t){return Promise.all(e.map(async n=>this.add(n,t)))}start(){return this.#h?(this.#h=!1,this.#_(),this):this}pause(){this.#h=!0}clear(){for(let e of this.#E)e();this.#n=new this.#T,this.#k(),this.#P(),this.emit("empty"),this.#o===0&&(this.#C(),this.emit("idle")),this.emit("next")}async onEmpty(){this.#n.size!==0&&await this.#p("empty")}async onSizeLessThan(e){this.#n.size<e||await this.#p("next",()=>this.#n.size<e)}async onIdle(){this.#o===0&&this.#n.size===0||await this.#p("idle")}async onPendingZero(){this.#o!==0&&await this.#p("pendingZero")}async onRateLimit(){this.isRateLimited||await this.#p("rateLimit")}async onRateLimitCleared(){this.isRateLimited&&await this.#p("rateLimitCleared")}onError(){return new Promise((e,t)=>{let n=o=>{this.off("error",n),t(o)};this.on("error",n)})}async#p(e,t){return new Promise(n=>{let o=()=>{t&&!t()||(this.off(e,o),n())};this.on(e,o)})}get size(){return this.#n.size}sizeBy(e){return this.#n.filter(e).length}get pending(){return this.#o}get isPaused(){return this.#h}#V(){this.#t||(this.on("add",()=>{this.#n.size>0&&this.#g()}),this.on("next",()=>{this.#g()}))}#g(){this.#t||this.#m||(this.#m=!0,queueMicrotask(()=>{this.#m=!1,this.#P()}))}#K(){this.#t||(this.#R(),this.#g())}#P(){let e=this.#c;if(this.#t||this.#n.size===0){e&&(this.#c=!1,this.emit("rateLimitCleared"));return}let t;if(this.#u){let o=Date.now();this.#v(o),t=this.#A()}else t=this.#r;let n=t>=this.#a;n!==e&&(this.#c=n,this.emit(n?"rateLimit":"rateLimitCleared"))}get isRateLimited(){return this.#c}get isSaturated(){return this.#o===this.#y&&this.#n.size>0||this.isRateLimited&&this.#n.size>0}get runningTasks(){return[...this.#w.values()].map(e=>({...e}))}};function bf(r){let e=[$t.A];return r==null?e:Array.isArray(r)?r.length===0?e:r:[r]}var Hy=60;function xf(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:$t[e.type]})),Answer:(r.Answer??r.answers??[]).map(e=>({name:e.name,type:$t[e.type],TTL:e.TTL??e.ttl??Hy,data:e.data instanceof Uint8Array?j(e.data):e.data}))}}var bB=4;function zy(r,e={}){let t=new yi({concurrency:e.queryConcurrency??bB});return async(n,o={})=>{let i=o?.logger?.forComponent("dns:dns-json-over-https"),s=new URLSearchParams;s.set("name",n),bf(o.types).forEach(c=>{s.append("type",$t[c])}),o.onProgress?.(new $("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 u=xf(await c.json());return o.onProgress?.(new $("dns:response",u)),u},{signal:o.signal});if(a==null)throw new Error("No DNS response received");return a}}function b1(){return[zy("https://cloudflare-dns.com/dns-query"),zy("https://dns.google/resolve")]}var v1=Ro(E1(),1);var jy=class{lru;constructor(e){this.lru=(0,v1.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 xf({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:$t[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??Hy)*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 A1(r){return new jy(r)}var xB=1e3,Ef=class{resolvers;cache;logger;constructor(e){this.resolvers={},this.cache=A1(e.cacheSize??xB),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["."]=b1())}async query(e,t={}){let n=bf(t.types),o=t.cached!==!1?this.cache.get(e,n):void 0;if(o!=null)return t.onProgress?.(new $("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 u=await c(e,{...t,logger:this.logger,types:n});for(let l of u.Answer)this.cache.add(e,l);return u}catch(u){a.push(u),t.onProgress?.(new $("dns:error",u))}}throw new yf(a,`DNS lookup of ${e} ${n} failed`)}};var $t;(function(r){r[r.A=1]="A",r[r.CNAME=5]="CNAME",r[r.TXT=16]="TXT",r[r.AAAA=28]="AAAA"})($t||($t={}));function vf(r={}){return new Ef(r)}var EB=["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 Gy(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=vB(r);return t||"Object"}function vB(r){let e=Object.prototype.toString.call(r).slice(8,-1);if(EB.includes(e))return e}var E=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}};E.uint=new E(0,"uint",!0);E.negint=new E(1,"negint",!0);E.bytes=new E(2,"bytes",!0);E.string=new E(3,"string",!0);E.array=new E(4,"array",!1);E.map=new E(5,"map",!1);E.tag=new E(6,"tag",!1);E.float=new E(7,"float",!0);E.false=new E(7,"false",!0);E.true=new E(7,"true",!0);E.null=new E(7,"null",!0);E.undefined=new E(7,"undefined",!0);E.break=new E(7,"break",!0);var z=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 Sc=globalThis.process&&!globalThis.process.browser&&globalThis.Buffer&&typeof globalThis.Buffer.isBuffer=="function",AB=new TextEncoder;function Af(r){return Sc&&globalThis.Buffer.isBuffer(r)}function kc(r){return r instanceof Uint8Array?Af(r)?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):r:Uint8Array.from(r)}var SB=24,kB=200,Sf=Sc?r=>r.length>=SB?globalThis.Buffer.from(r):S1(r):r=>r.length>=kB?AB.encode(r):S1(r),hn=r=>Uint8Array.from(r),k1=Sc?(r,e,t)=>Af(r)?new Uint8Array(r.subarray(e,t)):r.slice(e,t):(r,e,t)=>r.slice(e,t),_1=Sc?(r,e)=>(r=r.map(t=>t instanceof Uint8Array?t:globalThis.Buffer.from(t)),kc(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},I1=Sc?r=>globalThis.Buffer.allocUnsafe(r):r=>new Uint8Array(r);function kf(r,e){if(Af(r)&&Af(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 S1(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 _B=256,_c=class{constructor(e=_B){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=I1(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=k1(n,0,this.cursor)}else t=_1(this.chunks,this.cursor);return e&&this.reset(),t}},_f=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 te="CBOR decode error:",If="CBOR encode error:",Ic=[];Ic[23]=1;Ic[24]=2;Ic[25]=3;Ic[26]=5;Ic[27]=9;function Nn(r,e,t){if(r.length-e<t)throw new Error(`${te} not enough data for type`)}var et=[24,256,65536,4294967296,BigInt("18446744073709551616")];function Vt(r,e,t){Nn(r,e,1);let n=r[e];if(t.strict===!0&&n<et[0])throw new Error(`${te} integer encoded in more bytes than necessary (strict decode)`);return n}function Kt(r,e,t){Nn(r,e,2);let n=r[e]<<8|r[e+1];if(t.strict===!0&&n<et[1])throw new Error(`${te} integer encoded in more bytes than necessary (strict decode)`);return n}function qt(r,e,t){Nn(r,e,4);let n=r[e]*16777216+(r[e+1]<<16)+(r[e+2]<<8)+r[e+3];if(t.strict===!0&&n<et[2])throw new Error(`${te} integer encoded in more bytes than necessary (strict decode)`);return n}function Ht(r,e,t){Nn(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<et[3])throw new Error(`${te} 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(`${te} integers outside of the safe integer range are not supported`)}function T1(r,e,t,n){return new z(E.uint,Vt(r,e+1,n),2)}function C1(r,e,t,n){return new z(E.uint,Kt(r,e+1,n),3)}function B1(r,e,t,n){return new z(E.uint,qt(r,e+1,n),5)}function N1(r,e,t,n){return new z(E.uint,Ht(r,e+1,n),9)}function dr(r,e){return Te(r,0,e.value)}function Te(r,e,t){if(t<et[0]){let n=Number(t);r.push([e|n])}else if(t<et[1]){let n=Number(t);r.push([e|24,n])}else if(t<et[2]){let n=Number(t);r.push([e|25,n>>>8,n&255])}else if(t<et[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<et[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(`${te} encountered BigInt larger than allowable range`)}}dr.encodedSize=function(e){return Te.encodedSize(e.value)};Te.encodedSize=function(e){return e<et[0]?1:e<et[1]?2:e<et[2]?3:e<et[3]?5:9};dr.compareTokens=function(e,t){return e.value<t.value?-1:e.value>t.value?1:0};function P1(r,e,t,n){return new z(E.negint,-1-Vt(r,e+1,n),2)}function L1(r,e,t,n){return new z(E.negint,-1-Kt(r,e+1,n),3)}function D1(r,e,t,n){return new z(E.negint,-1-qt(r,e+1,n),5)}var Wy=BigInt(-1),R1=BigInt(1);function U1(r,e,t,n){let o=Ht(r,e+1,n);if(typeof o!="bigint"){let i=-1-o;if(i>=Number.MIN_SAFE_INTEGER)return new z(E.negint,i,9)}if(n.allowBigInt!==!0)throw new Error(`${te} integers outside of the safe integer range are not supported`);return new z(E.negint,Wy-BigInt(o),9)}function Tf(r,e){let t=e.value,n=typeof t=="bigint"?t*Wy-R1:t*-1-1;Te(r,e.type.majorEncoded,n)}Tf.encodedSize=function(e){let t=e.value,n=typeof t=="bigint"?t*Wy-R1:t*-1-1;return n<et[0]?1:n<et[1]?2:n<et[2]?3:n<et[3]?5:9};Tf.compareTokens=function(e,t){return e.value<t.value?1:e.value>t.value?-1:0};function Tc(r,e,t,n){Nn(r,e,t+n);let o=r.slice(e+t,e+t+n);return new z(E.bytes,o,t+n)}function O1(r,e,t,n){return Tc(r,e,1,t)}function M1(r,e,t,n){return Tc(r,e,2,Vt(r,e+1,n))}function F1(r,e,t,n){return Tc(r,e,3,Kt(r,e+1,n))}function $1(r,e,t,n){return Tc(r,e,5,qt(r,e+1,n))}function V1(r,e,t,n){let o=Ht(r,e+1,n);if(typeof o=="bigint")throw new Error(`${te} 64-bit integer bytes lengths not supported`);return Tc(r,e,9,o)}function Cf(r){return r.encodedBytes===void 0&&(r.encodedBytes=E.equals(r.type,E.string)?Sf(r.value):r.value),r.encodedBytes}function Ls(r,e){let t=Cf(e);Te(r,e.type.majorEncoded,t.length),r.push(t)}Ls.encodedSize=function(e){let t=Cf(e);return Te.encodedSize(t.length)+t.length};Ls.compareTokens=function(e,t){return TB(Cf(e),Cf(t))};function TB(r,e){return r.length<e.length?-1:r.length>e.length?1:kf(r,e)}var K1=new TextDecoder,BB=32;function NB(r,e,t){if(t-e<BB){let o="";for(let i=e;i<t;i++){let s=r[i];if(s&128)return K1.decode(r.subarray(e,t));o+=String.fromCharCode(s)}return o}return K1.decode(r.subarray(e,t))}function Cc(r,e,t,n,o){let i=t+n;Nn(r,e,i);let s=new z(E.string,NB(r,e+t,e+i),i);return o.retainStringBytes===!0&&(s.byteValue=r.slice(e+t,e+i)),s}function q1(r,e,t,n){return Cc(r,e,1,t,n)}function H1(r,e,t,n){return Cc(r,e,2,Vt(r,e+1,n),n)}function z1(r,e,t,n){return Cc(r,e,3,Kt(r,e+1,n),n)}function j1(r,e,t,n){return Cc(r,e,5,qt(r,e+1,n),n)}function G1(r,e,t,n){let o=Ht(r,e+1,n);if(typeof o=="bigint")throw new Error(`${te} 64-bit integer string lengths not supported`);return Cc(r,e,9,o,n)}var W1=Ls;function Ds(r,e,t,n){return new z(E.array,n,t)}function Y1(r,e,t,n){return Ds(r,e,1,t)}function X1(r,e,t,n){return Ds(r,e,2,Vt(r,e+1,n))}function Z1(r,e,t,n){return Ds(r,e,3,Kt(r,e+1,n))}function J1(r,e,t,n){return Ds(r,e,5,qt(r,e+1,n))}function Q1(r,e,t,n){let o=Ht(r,e+1,n);if(typeof o=="bigint")throw new Error(`${te} 64-bit integer array lengths not supported`);return Ds(r,e,9,o)}function ev(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${te} indefinite length items not allowed`);return Ds(r,e,1,1/0)}function Bf(r,e){Te(r,E.array.majorEncoded,e.value)}Bf.compareTokens=dr.compareTokens;Bf.encodedSize=function(e){return Te.encodedSize(e.value)};function Rs(r,e,t,n){return new z(E.map,n,t)}function tv(r,e,t,n){return Rs(r,e,1,t)}function rv(r,e,t,n){return Rs(r,e,2,Vt(r,e+1,n))}function nv(r,e,t,n){return Rs(r,e,3,Kt(r,e+1,n))}function ov(r,e,t,n){return Rs(r,e,5,qt(r,e+1,n))}function iv(r,e,t,n){let o=Ht(r,e+1,n);if(typeof o=="bigint")throw new Error(`${te} 64-bit integer map lengths not supported`);return Rs(r,e,9,o)}function sv(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${te} indefinite length items not allowed`);return Rs(r,e,1,1/0)}function Nf(r,e){Te(r,E.map.majorEncoded,e.value)}Nf.compareTokens=dr.compareTokens;Nf.encodedSize=function(e){return Te.encodedSize(e.value)};function av(r,e,t,n){return new z(E.tag,t,1)}function cv(r,e,t,n){return new z(E.tag,Vt(r,e+1,n),2)}function uv(r,e,t,n){return new z(E.tag,Kt(r,e+1,n),3)}function lv(r,e,t,n){return new z(E.tag,qt(r,e+1,n),5)}function fv(r,e,t,n){return new z(E.tag,Ht(r,e+1,n),9)}function Pf(r,e){Te(r,E.tag.majorEncoded,e.value)}Pf.compareTokens=dr.compareTokens;Pf.encodedSize=function(e){return Te.encodedSize(e.value)};var Yy=20,Xy=21,Zy=22,Jy=23;function dv(r,e,t,n){if(n.allowUndefined===!1)throw new Error(`${te} undefined values are not supported`);return n.coerceUndefinedToNull===!0?new z(E.null,null,1):new z(E.undefined,void 0,1)}function hv(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${te} indefinite length items not allowed`);return new z(E.break,void 0,1)}function Qy(r,e,t){if(t){if(t.allowNaN===!1&&Number.isNaN(r))throw new Error(`${te} NaN values are not supported`);if(t.allowInfinity===!1&&(r===1/0||r===-1/0))throw new Error(`${te} Infinity values are not supported`)}return new z(E.float,r,e)}function pv(r,e,t,n){return Qy(e0(r,e+1),3,n)}function mv(r,e,t,n){return Qy(t0(r,e+1),5,n)}function gv(r,e,t,n){return Qy(xv(r,e+1),9,n)}function Bc(r,e,t){let n=e.value;if(n===!1)r.push([E.float.majorEncoded|Yy]);else if(n===!0)r.push([E.float.majorEncoded|Xy]);else if(n===null)r.push([E.float.majorEncoded|Zy]);else if(n===void 0)r.push([E.float.majorEncoded|Jy]);else{let o,i=!1;(!t||t.float64!==!0)&&(wv(n),o=e0(Kr,1),n===o||Number.isNaN(n)?(Kr[0]=249,r.push(Kr.slice(0,3)),i=!0):(bv(n),o=t0(Kr,1),n===o&&(Kr[0]=250,r.push(Kr.slice(0,5)),i=!0))),i||(UB(n),o=xv(Kr,1),Kr[0]=251,r.push(Kr.slice(0,9)))}}Bc.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){wv(n);let o=e0(Kr,1);if(n===o||Number.isNaN(n))return 3;if(bv(n),o=t0(Kr,1),n===o)return 5}return 9};var yv=new ArrayBuffer(9),hr=new DataView(yv,1),Kr=new Uint8Array(yv,0);function wv(r){if(r===1/0)hr.setUint16(0,31744,!1);else if(r===-1/0)hr.setUint16(0,64512,!1);else if(Number.isNaN(r))hr.setUint16(0,32256,!1);else{hr.setFloat32(0,r);let e=hr.getUint32(0),t=(e&2139095040)>>23,n=e&8388607;if(t===255)hr.setUint16(0,31744,!1);else if(t===0)hr.setUint16(0,(e&2147483648)>>16|n>>13,!1);else{let o=t-127;o<-24?hr.setUint16(0,0):o<-14?hr.setUint16(0,(e&2147483648)>>16|1<<24+o,!1):hr.setUint16(0,(e&2147483648)>>16|o+15<<10|n>>13,!1)}}}function e0(r,e){if(r.length-e<2)throw new Error(`${te} 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 bv(r){hr.setFloat32(0,r,!1)}function t0(r,e){if(r.length-e<4)throw new Error(`${te} not enough data for float32`);let t=(r.byteOffset||0)+e;return new DataView(r.buffer,t,4).getFloat32(0,!1)}function UB(r){hr.setFloat64(0,r,!1)}function xv(r,e){if(r.length-e<8)throw new Error(`${te} not enough data for float64`);let t=(r.byteOffset||0)+e;return new DataView(r.buffer,t,8).getFloat64(0,!1)}Bc.compareTokens=dr.compareTokens;function ye(r,e,t){throw new Error(`${te} encountered invalid minor (${t}) for major ${r[e]>>>5}`)}function Lf(r){return()=>{throw new Error(`${te} ${r}`)}}var R=[];for(let r=0;r<=23;r++)R[r]=ye;R[24]=T1;R[25]=C1;R[26]=B1;R[27]=N1;R[28]=ye;R[29]=ye;R[30]=ye;R[31]=ye;for(let r=32;r<=55;r++)R[r]=ye;R[56]=P1;R[57]=L1;R[58]=D1;R[59]=U1;R[60]=ye;R[61]=ye;R[62]=ye;R[63]=ye;for(let r=64;r<=87;r++)R[r]=O1;R[88]=M1;R[89]=F1;R[90]=$1;R[91]=V1;R[92]=ye;R[93]=ye;R[94]=ye;R[95]=Lf("indefinite length bytes/strings are not supported");for(let r=96;r<=119;r++)R[r]=q1;R[120]=H1;R[121]=z1;R[122]=j1;R[123]=G1;R[124]=ye;R[125]=ye;R[126]=ye;R[127]=Lf("indefinite length bytes/strings are not supported");for(let r=128;r<=151;r++)R[r]=Y1;R[152]=X1;R[153]=Z1;R[154]=J1;R[155]=Q1;R[156]=ye;R[157]=ye;R[158]=ye;R[159]=ev;for(let r=160;r<=183;r++)R[r]=tv;R[184]=rv;R[185]=nv;R[186]=ov;R[187]=iv;R[188]=ye;R[189]=ye;R[190]=ye;R[191]=sv;for(let r=192;r<=215;r++)R[r]=av;R[216]=cv;R[217]=uv;R[218]=lv;R[219]=fv;R[220]=ye;R[221]=ye;R[222]=ye;R[223]=ye;for(let r=224;r<=243;r++)R[r]=Lf("simple values are not supported");R[244]=ye;R[245]=ye;R[246]=ye;R[247]=dv;R[248]=Lf("simple values are not supported");R[249]=pv;R[250]=mv;R[251]=gv;R[252]=ye;R[253]=ye;R[254]=ye;R[255]=hv;var qr=[];for(let r=0;r<24;r++)qr[r]=new z(E.uint,r,1);for(let r=-1;r>=-24;r--)qr[31-r]=new z(E.negint,r,1);qr[64]=new z(E.bytes,new Uint8Array(0),1);qr[96]=new z(E.string,"",1);qr[128]=new z(E.array,0,1);qr[160]=new z(E.map,0,1);qr[244]=new z(E.false,!1,1);qr[245]=new z(E.true,!0,1);qr[246]=new z(E.null,null,1);function r0(r){switch(r.type){case E.false:return hn([244]);case E.true:return hn([245]);case E.null:return hn([246]);case E.bytes:return r.value.length?void 0:hn([64]);case E.string:return r.value===""?hn([96]):void 0;case E.array:return r.value===0?hn([128]):void 0;case E.map:return r.value===0?hn([160]):void 0;case E.uint:return r.value<24?hn([Number(r.value)]):void 0;case E.negint:if(r.value>=-24)return hn([31-Number(r.value)])}}var MB={float64:!1,mapSorter:VB,quickEncodeToken:r0},kv=Object.freeze({float64:!0,mapSorter:KB,quickEncodeToken:r0});function FB(){let r=[];return r[E.uint.major]=dr,r[E.negint.major]=Tf,r[E.bytes.major]=Ls,r[E.string.major]=W1,r[E.array.major]=Bf,r[E.map.major]=Nf,r[E.tag.major]=Pf,r[E.float.major]=Bc,r}var Os=FB(),Df=new _c,Pc=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(`${If} object contains circular references`);return new r(t,e)}},mo={null:new z(E.null,null),undefined:new z(E.undefined,void 0),true:new z(E.true,!0),false:new z(E.false,!1),emptyArray:new z(E.array,0),emptyMap:new z(E.map,0)},pn={number(r,e,t,n){return!Number.isInteger(r)||!Number.isSafeInteger(r)?new z(E.float,r):r>=0?new z(E.uint,r):new z(E.negint,r)},bigint(r,e,t,n){return r>=BigInt(0)?new z(E.uint,r):new z(E.negint,r)},Uint8Array(r,e,t,n){return new z(E.bytes,r)},string(r,e,t,n){return new z(E.string,r)},boolean(r,e,t,n){return r?mo.true:mo.false},null(r,e,t,n){return mo.null},undefined(r,e,t,n){return mo.undefined},ArrayBuffer(r,e,t,n){return new z(E.bytes,new Uint8Array(r))},DataView(r,e,t,n){return new z(E.bytes,new Uint8Array(r.buffer,r.byteOffset,r.byteLength))},Array(r,e,t,n){if(!r.length)return t.addBreakTokens===!0?[mo.emptyArray,new z(E.break)]:mo.emptyArray;n=Pc.createCheck(n,r);let o=[],i=0;for(let s of r)o[i++]=Us(s,t,n);return t.addBreakTokens?[new z(E.array,r.length),o,new z(E.break)]:[new z(E.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=Pc.createCheck(n,r);let c=!o&&t.ignoreUndefinedProperties,u=0;for(let l of i){let f=o?r.get(l):r[l];c&&f===void 0||(a[u++]=[Us(l,t,n),Us(f,t,n)])}u<s&&(a.length=u)}return a?.length?($B(a,t),t.addBreakTokens?[new z(E.map,a.length),a,new z(E.break)]:[new z(E.map,a.length),a]):t.addBreakTokens===!0?[mo.emptyMap,new z(E.break)]:mo.emptyMap},Tagged(r,e,t,n){return[new z(E.tag,r.tag),Us(r.value,t,n)]}};pn.Map=pn.Object;pn.Buffer=pn.Uint8Array;for(let r of"Uint8Clamped Uint16 Uint32 Int8 Int16 Int32 BigUint64 BigInt64 Float32 Float64".split(" "))pn[`${r}Array`]=pn.DataView;function Us(r,e={},t){let n=Gy(r),o=e&&e.typeEncoders&&e.typeEncoders[n]||pn[n];if(typeof o=="function"){let s=o(r,n,e,t);if(s!=null)return s}let i=pn[n];if(!i)throw new Error(`${If} unsupported type: ${n}`);return i(r,n,e,t)}function $B(r,e){e.mapSorter&&r.sort(e.mapSorter)}function VB(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=Os[o].compareTokens(t,n);return i===0&&console.warn("WARNING: complex key types used, CBOR key sorting guarantees are gone"),i}function KB(r,e){if(r[0]instanceof z&&e[0]instanceof z){let t=r[0],n=e[0];return t._keyBytes||(t._keyBytes=Ev(t.value)),n._keyBytes||(n._keyBytes=Ev(n.value)),kf(t._keyBytes,n._keyBytes)}throw new Error("rfc8949MapSorter: complex key types are not supported yet")}function Ev(r){return Iv(r,Os,kv)}function Nc(r,e,t,n){if(Array.isArray(e))for(let o of e)Nc(r,o,t,n);else t[e.type.major](r,e,n)}var vv=E.uint.majorEncoded,Av=E.negint.majorEncoded,qB=E.bytes.majorEncoded,HB=E.string.majorEncoded,Sv=E.array.majorEncoded,zB=E.float.majorEncoded|Yy,jB=E.float.majorEncoded|Xy,GB=E.float.majorEncoded|Zy,WB=E.float.majorEncoded|Jy,YB=BigInt(-1),XB=BigInt(1);function ZB(r){return r.addBreakTokens!==!0}function _v(r,e,t,n){let o=Gy(e),i=t.typeEncoders&&t.typeEncoders[o];if(i){let s=i(e,o,t,n);if(s!=null){Nc(r,s,Os,t);return}}switch(o){case"null":r.push([GB]);return;case"undefined":r.push([WB]);return;case"boolean":r.push([e?jB:zB]);return;case"number":!Number.isInteger(e)||!Number.isSafeInteger(e)?Bc(r,new z(E.float,e),t):e>=0?Te(r,vv,e):Te(r,Av,e*-1-1);return;case"bigint":e>=BigInt(0)?Te(r,vv,e):Te(r,Av,e*YB-XB);return;case"string":{let s=Sf(e);Te(r,HB,s.length),r.push(s);return}case"Uint8Array":Te(r,qB,e.length),r.push(e);return;case"Array":if(!e.length){r.push([Sv]);return}n=Pc.createCheck(n,e),Te(r,Sv,e.length);for(let s of e)_v(r,s,t,n);return;case"Object":case"Map":{let s=pn.Object(e,o,t,n);Nc(r,s,Os,t)}return;default:{let s=pn[o];if(!s)throw new Error(`${If} unsupported type: ${o}`);let a=s(e,o,t,n);Nc(r,a,Os,t)}}}function Iv(r,e,t,n){let o=n instanceof Uint8Array,i=o?new _f(n):Df,s=Us(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 u=c.encodedSize(s,t);if(o||(i=new _c(u)),c(i,s,t),i.chunks.length!==1)throw new Error(`Unexpected error: pre-calculated length for ${s} was wrong`);return o?i.toBytes():kc(i.chunks[0])}}return i.reset(),Nc(i,s,e,t),i.toBytes(!0)}function Lc(r,e){return e=Object.assign({},MB,e),ZB(e)?(Df.reset(),_v(Df,r,e,void 0),Df.toBytes(!0)):Iv(r,Os,e)}var JB={strict:!1,allowIndefinite:!0,allowUndefined:!0,allowBigInt:!0},Rf=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=qr[e];if(t===void 0){let n=R[e];if(!n)throw new Error(`${te} 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}},go=Symbol.for("DONE"),Ms=Symbol.for("BREAK");function QB(r,e,t){let n=[];for(let o=0;o<r.value;o++){let i=yo(e,t);if(i===Ms){if(r.value===1/0)break;throw new Error(`${te} got unexpected break to lengthed array`)}if(i===go)throw new Error(`${te} found array but not enough entries (got ${o}, expected ${r.value})`);n[o]=i}return n}function e4(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=yo(e,t);if(c===Ms){if(r.value===1/0)break;throw new Error(`${te} got unexpected break to lengthed map`)}if(c===go)throw new Error(`${te} found map but not enough entries (got ${a} [no key], expected ${r.value})`);if(!n&&typeof c!="string")throw new Error(`${te} non-string keys not supported (got ${typeof c})`);if(o&&(n&&s.has(c)||!n&&Object.hasOwn(i,c)))throw new Error(`${te} found repeat map key "${c}"`);let u=yo(e,t);if(u===go)throw new Error(`${te} found map but not enough entries (got ${a} [no value], expected ${r.value})`);n?s.set(c,u):i[c]=u}return n?s:i}function*t4(r,e,t){for(let n=0;n<r.value;n++){let o=yo(e,t);if(o===Ms){if(r.value===1/0)break;throw new Error(`${te} got unexpected break to lengthed map`)}if(o===go)throw new Error(`${te} found map but not enough entries (got ${n} [no key], expected ${r.value})`);let i=yo(e,t);if(i===go)throw new Error(`${te} found map but not enough entries (got ${n} [no value], expected ${r.value})`);yield[o,i]}}function r4(r,e){let t=!1,n=function(){if(t)throw new Error(`${te} tag decode() may only be called once`);t=!0;let o=yo(r,e);if(o===go)throw new Error(`${te} tag content missing`);if(o===Ms)throw new Error(`${te} got unexpected break in tag content`);return o};return n.entries=function(){if(t)throw new Error(`${te} tag decode() may only be called once`);t=!0;let o=r.next();if(!E.equals(o.type,E.map))throw new Error(`${te} entries() requires map content, got ${o.type.name}`);let i=[];for(let s of t4(o,r,e))i.push(s);return i},Object.defineProperty(n,"_called",{get(){return t},enumerable:!1}),n}function yo(r,e){if(r.done())return go;let t=r.next();if(E.equals(t.type,E.break))return Ms;if(t.type.terminal)return t.value;if(E.equals(t.type,E.array))return QB(t,r,e);if(E.equals(t.type,E.map))return e4(t,r,e);if(E.equals(t.type,E.tag)){if(e.tags&&typeof e.tags[t.value]=="function"){let n=r4(r,e),o=e.tags[t.value](n);if(!n._called)throw new Error(`${te} tag decoder must call decode() or entries()`);return o}throw new Error(`${te} tag not supported (${t.value})`)}throw new Error("unsupported")}function Tv(r,e){if(!(r instanceof Uint8Array))throw new Error(`${te} data to decode must be a Uint8Array`);e=Object.assign({},JB,e);let t=kc(r),n=e.tokenizer||new Rf(t,e),o=yo(n,e);if(o===go)throw new Error(`${te} did not find any content to decode`);if(o===Ms)throw new Error(`${te} got unexpected break`);return[o,r.subarray(n.pos())]}function bi(r,e){let[t,n]=Tv(r,e);if(n.length>0)throw new Error(`${te} too many terminals, data makes no sense`);return t}var Uf=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(Uf.prototype,Symbol.toStringTag,{value:"Tagged"});var Pn="/",Cv=new TextEncoder().encode(Pn),Of=Cv[0],Le=class r{_buf;constructor(e,t){if(typeof e=="string")this._buf=L(e);else if(e instanceof Uint8Array)this._buf=e;else throw new Error("Invalid key, should be String of Uint8Array");if(t==null&&(t=!0),t&&this.clean(),this._buf.byteLength===0||this._buf[0]!==Of)throw new Error("Invalid key")}toString(e="utf8"){return j(this._buf,e)}uint8Array(){return this._buf}get[Symbol.toStringTag](){return`Key(${this.toString()})`}static withNamespaces(e){return new r(e.join(Pn))}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=Cv),this._buf[0]!==Of){let e=new Uint8Array(this._buf.byteLength+1);e.fill(Of,0,1),e.set(this._buf,1),this._buf=e}for(;this._buf.byteLength>1&&this._buf[this._buf.byteLength-1]===Of;)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(Pn).slice(1)}type(){return o4(this.baseNamespace())}name(){return i4(this.baseNamespace())}instance(e){return new r(this.toString()+":"+e)}path(){let e=this.parent().toString();return e.endsWith(Pn)||(e+=Pn),e+=this.type(),new r(e)}parent(){let e=this.list();return e.length===1?new r(Pn):new r(e.slice(0,-1).join(Pn))}child(e){return this.toString()===Pn?e:e.toString()===Pn?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(),...s4(e.map(t=>t.namespaces()))])}};function o4(r){let e=r.split(":");return e.length<2?"":e.slice(0,-1).join(":")}function i4(r){let e=r.split(":");return e[e.length-1]}function s4(r){return[].concat(...r)}function Mf({enumerable:r=!0,configurable:e=!1}={}){return{enumerable:r,configurable:e,writable:!1}}function*a4(r,e){if(e!=null&&typeof e=="object")if(Array.isArray(e))for(let[t,n]of e.entries()){let o=[...r,t],i=Q.asCID(n);i!=null?yield[o.join("/"),i]:typeof n=="object"&&(yield*n0(n,o))}else{let t=Q.asCID(e);t!=null?yield[r.join("/"),t]:yield*n0(e,r)}}function*n0(r,e){if(r==null||r instanceof Uint8Array)return;let t=Q.asCID(r);t!=null&&(yield[e.join("/"),t]);for(let[n,o]of Object.entries(r)){let i=[...e,n];yield*a4(i,o)}}function*c4(r,e){if(Array.isArray(e))for(let[t,n]of e.entries()){let o=[...r,t];yield o.join("/"),typeof n=="object"&&Q.asCID(n)==null&&(yield*o0(n,o))}else yield*o0(e,r)}function*o0(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"&&Q.asCID(n)==null&&(yield*c4(o,n))}}function u4(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=Q.asCID(t);if(i!=null)return{value:i,remaining:e.slice(n+1).join("/")}}return{value:t}}var i0=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:Mf(),bytes:Mf(),value:Mf(),asBlock:Mf()})}links(){return n0(this.value,[])}tree(){return o0(this.value,[])}get(e="/"){return u4(this.value,e.split("/").filter(Boolean))}};function Bv({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 i0({cid:e,bytes:r,value:o})}var Ff=class extends Error{static name="AlreadyPinnedError";name="AlreadyPinnedError"},Dc=class extends Error{static name="BlockPinnedError";name="BlockPinnedError"},$f=class extends Error{static name="InvalidDatastoreVersionError";name="InvalidDatastoreVersionError"},xi=class extends Error{static name="InvalidConfigurationError";name="InvalidConfigurationError"},Vf=class extends AggregateError{static name="GetFailedError";name="GetFailedError"},Kf=class extends AggregateError{static name="LoadBlockFailedError";name="LoadBlockFailedError"},Rc=class extends Error{static name="BlockNotFoundWhileOfflineError";name="BlockNotFoundWhileOfflineError"};var Lv="/pin/",Nv="/pinned-block/",s0=on,Pv=1;function qf(r){return r.version===0&&(r=r.toV1()),new Le(`${Lv}${r.toString(s0)}`)}var Hf=class{datastore;blockstore;getCodec;constructor(e,t,n){this.datastore=e,this.blockstore=t,this.getCodec=n}async*add(e,t={}){let n=qf(e);if(await this.datastore.has(n))throw new Ff("Already pinned");let o=Math.round(t.depth??1/0);if(o<0)throw new T("Depth must be greater than or equal to 0");let i=new $r({concurrency:Pv});for await(let a of this.#e(e,i,{...t,depth:o}))await this.#t(a,c=>c.pinnedBy.find(u=>ce(u,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,Lc(s),t)}async*#e(e,t,n){if(n.depth===-1)return;let o=await this.getCodec(e.code),i=await g1(this.blockstore.get(e,n)),s=Bv({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 Le(`${Nv}${s0.encode(e.multihash.bytes)}`),i={pinCount:0,pinnedBy:[]};try{i=bi(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,Lc(i),n),n.onProgress?.(new $("helia:pin:add",e))}}async*rm(e,t={}){let n=qf(e),o=await this.datastore.get(n,t),i=bi(o);await this.datastore.delete(n,t);let s=new $r({concurrency:Pv});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(u=>ce(u,e.bytes)),!0),{...t,depth:i.depth}),yield a}async*ls(e={}){for await(let{key:t,value:n}of this.datastore.query({prefix:Lv+(e.cid!=null?`${e.cid.toString(on)}`:"")},e)){let o=Q.parse(t.toString().substring(5),on),i=bi(n);yield{cid:o,...i}}}async isPinned(e,t={}){let n=new Le(`${Nv}${s0.encode(e.multihash.bytes)}`);return this.datastore.has(n,t)}async get(e,t){let n=qf(e),o=await this.datastore.get(n,t);return bi(o)}async setMetadata(e,t,n){let o=qf(e),i=await this.datastore.get(o,n),s=bi(i);s.metadata=t??{},await this.datastore.put(o,Lc(s),n)}};var a0=1,c0=5,u0=100;var Uc=class extends Error{static name="InsufficientProvidersError";constructor(e="Insufficient providers found"){super(e),this.name="InsufficientProvidersError"}},wo=class extends Error{static name="NoRoutersAvailableError";constructor(e="No routers available"){super(e),this.name="NoRoutersAvailableError"}},Oc=class extends Error{static name="UnknownHashAlgorithmError";constructor(e="Unknown hash algorithm"){super(e),this.name="UnknownHashAlgorithmError"}},Mc=class extends Error{static name="UnknownCodecError";constructor(e="Unknown codec"){super(e),this.name="UnknownCodecError"}},l0=class extends Error{static name="InvalidCodecError";constructor(e="Invalid codec"){super(e),this.name="InvalidCodecError"}};var l4=5,zf=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??l4,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 rn(...this.routers)}async stop(){await nn(...this.routers)}async*findProviders(e,t={}){if(this.routers.length===0)throw new wo("No content routers available");let n=new Bs({concurrency:this.providerLookupConcurrency}),o=0,i=[],s=this,a=0;this.log("findProviders for %c start using routers %s",e,this.routers.map(u=>u.toString()).join(", "));let c=Ei(this.routers,"findProviders").map(async function*(u){let l=0;t?.onProgress?.(new $("helia:routing:find-providers:start",{routing:u.name,cid:e}));try{for await(let f of u.findProviders(e,t))l++,t?.onProgress?.(new $("helia:routing:find-providers:provider",{routing:u.name,cid:e,provider:f})),yield f}catch(f){i.push(f)}finally{s.log("router %s found %d providers for %c",u,l,e),t?.onProgress?.(new $("helia:routing:find-providers:end",{routing:u.name,cid:e,found:l})),a++,a===c.length&&n.size===0&&n.emitIdle()}});for await(let u of cr(n.toGenerator(),...c))if(u!=null){if(u.multiaddrs.length===0){if(n.find(u.id)!=null)continue;n.add(async()=>{try{let l=await this.findPeer(u.id,t);return l.multiaddrs.length===0?null:{...l,protocols:u.protocols,routing:u.routing}}catch(l){return this.log.error("could not load multiaddrs for peer %p - %e",u.id,l),null}},{peerId:u.id,signal:t.signal}).catch(l=>{this.log.error("could not load multiaddrs for peer %p - %e",u.id,l)});continue}o++,yield u}this.log("findProviders finished, found %d providers for %c",o,e)}async provide(e,t={}){if(this.routers.length===0)throw new wo("No content routers available");await Promise.all(Ei(this.routers,"provide").map(async n=>{t?.onProgress?.(new $("helia:routing:provide:start",{routing:n.name,cid:e})),await n.provide(e,t),t?.onProgress?.(new $("helia:routing:provide:end",{routing:n.name,cid:e}))}))}async cancelReprovide(e,t={}){await Promise.all(Ei(this.routers,"cancelReprovide").map(async n=>{t?.onProgress?.(new $("helia:routing:cancel-reprovide:start",{routing:n.name,cid:e})),await n.cancelReprovide(e,t),t?.onProgress?.(new $("helia:routing:cancel-reprovide:end",{routing:n.name,cid:e}))}))}async put(e,t,n){await Promise.all(Ei(this.routers,"put").map(async o=>{n?.onProgress?.(new $("helia:routing:put:start",{routing:o.name,key:e,value:t})),await o.put(e,t,n),n?.onProgress?.(new $("helia:routing:put:end",{routing:o.name,key:e,value:t}))}))}async get(e,t){let n=[],o;try{o=await Promise.any(Ei(this.routers,"get").map(async i=>{t?.onProgress?.(new $("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 $("helia:routing:get:end",{routing:i.name,key:e}))}}))}catch{}if(o==null)throw new Vf(n,`Failed to get value key ${j(e,"base58btc")}`);return o}async findPeer(e,t){if(this.routers.length===0)throw new wo("No peer routers available");let n=this,o=cr(...Ei(this.routers,"findPeer").map(i=>(async function*(){t?.onProgress?.(new $("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 $("helia:routing:find-peer:end",{routing:i.name,peerId:e}))}})()));for await(let i of o)if(i!=null)return i;throw new He("Could not find peer in routing")}async*getClosestPeers(e,t={}){if(this.routers.length===0)throw new wo("No peer routers available");for await(let n of cr(...Ei(this.routers,"getClosestPeers").map(async function*(o){t?.onProgress?.(new $("helia:routing:get-closest-peers:start",{routing:o.name,key:e}));try{yield*o.getClosestPeers(e,t)}finally{t?.onProgress?.(new $("helia:routing:get-closest-peers:end",{routing:o.name,key:e}))}})))n!=null&&(yield n)}};function Ei(r,e){return r.filter(t=>t[e]!=null)}var jf=class extends Error{static name="QueueFullError";constructor(e="The queue was full"){super(e),this.name="QueueFullError"}};var Gf=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 Ft)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function f4(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var Wf=class{id;fn;options;recipients;status;timeline;controller;constructor(e,t){this.id=f4(),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 Ft),this.cleanup())}async join(e={}){let t=new Gf(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 kt(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 f0(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 Fc=class extends ze{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=f0(this.emitEmpty.bind(this),1),this.emitIdle=f0(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 jf;let n=new Wf(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 Ft)}),this.clear()}async onEmpty(e){this.size!==0&&await mf(this,"empty",e?.signal)}async onSizeLessThan(e,t){this.size<e||await mf(this,"next",t?.signal,{filter:()=>this.size<e})}async onIdle(e){this.pending===0&&this.size===0||await mf(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=xs({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 Ft("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 Yf="lock:worker:request-read",Xf="lock:worker:abort-read-request",Zf="lock:worker:release-read",Jf="lock:master:grant-read",Qf="lock:master:error-read",ed="lock:worker:request-write",td="lock:worker:abort-write-request",rd="lock:worker:release-write",nd="lock:master:grant-write",od="lock:master:error-write",id="lock:worker:finalize",sd="mortice",Dv={singleProcess:!1};var d0=(r,e,t,n,o,i,s,a,c)=>u=>{if(u.data==null)return;let l={type:u.data.type,name:u.data.name,identifier:u.data.identifier};l.type===o&&r.safeDispatchEvent(t,{detail:{name:l.name,identifier:l.identifier,handler:async()=>{e.postMessage({type:c,name:l.name,identifier:l.identifier}),await new Promise(f=>{let d=h=>{if(h?.data==null)return;let m={type:h.data.type,name:h.data.name,identifier:h.data.identifier};m.type===a&&m.identifier===l.identifier&&(e.removeEventListener("message",d),f())};e.addEventListener("message",d)})},onError:f=>{e.postMessage({type:s,name:l.name,identifier:l.identifier,error:{message:f.message,name:f.name,stack:f.stack}})}}}),l.type===i&&r.safeDispatchEvent(n,{detail:{name:l.name,identifier:l.identifier}}),l.type===id&&r.safeDispatchEvent("finalizeRequest",{detail:{name:l.name}})};var Rv=(r=10)=>Math.random().toString().substring(2,r+2);var ad=class{name;channel;constructor(e){this.name=e,this.channel=new BroadcastChannel(sd)}readLock(e){return this.sendRequest(Yf,Xf,Jf,Qf,Zf,e)}writeLock(e){return this.sendRequest(ed,td,nd,od,rd,e)}finalize(){this.channel.postMessage({type:id,name:this.name}),this.channel.close()}async sendRequest(e,t,n,o,i,s){s?.signal?.throwIfAborted();let a=Rv();return this.channel.postMessage({type:e,identifier:a,name:this.name}),new Promise((c,u)=>{let l=()=>{this.channel.postMessage({type:t,identifier:a,name:this.name})};s?.signal?.addEventListener("abort",l,{once:!0});let f=d=>{if(d.data?.identifier===a&&(d.data?.type===n&&(this.channel.removeEventListener("message",f),s?.signal?.removeEventListener("abort",l),c(()=>{this.channel.postMessage({type:i,identifier:a,name:this.name})})),d.data.type===o)){this.channel.removeEventListener("message",f),s?.signal?.removeEventListener("abort",l);let h=new Error;d.data.error!=null&&(h.message=d.data.error.message,h.name=d.data.error.name,h.stack=d.data.error.stack),u(h)}};this.channel.addEventListener("message",f)})}};var Uv=r=>{if(r=Object.assign({},Dv,r),!!globalThis.document||r.singleProcess){let t=new BroadcastChannel(sd),n=new ze;return t.addEventListener("message",d0(n,t,"requestReadLock","abortReadLockRequest",Yf,Xf,Qf,Zf,Jf)),t.addEventListener("message",d0(n,t,"requestWriteLock","abortWriteLockRequest",ed,td,od,rd,nd)),n}return new ad(r.name)};var vi=new Map,$c;function Ov(r){return typeof r?.readLock=="function"&&typeof r?.writeLock=="function"}function d4(r){if($c==null&&($c=Uv(r),!Ov($c))){let e=$c;e.addEventListener("requestReadLock",t=>{let n=t.detail.name,o=t.detail.identifier,i=vi.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=vi.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=vi.get(n);o?.finalize()})}return $c}async function h0(r,e){let t,n,o=new Promise((s,a)=>{t=s,n=a}),i=()=>{n(new Ft)};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 Mv=(r,e)=>{let t=vi.get(r);if(t!=null)return t;let n=d4(e);if(Ov(n))return t=n,vi.set(r,t),t;let o=new Fc({concurrency:1}),i;return t={async readLock(s){if(i!=null)return h0(i,s);i=new Fc({concurrency:e.concurrency,autoStart:!1});let a=i,c=h0(i,s);return o.add(async()=>{a.start(),await a.onIdle().then(()=>{i===a&&(i=null)})}),c},async writeLock(s){return i=null,h0(o,s)},finalize:()=>{vi.delete(r)},queue:o},vi.set(r,t),e.autoFinalize===!0&&o.addEventListener("idle",()=>{t.finalize()},{once:!0}),t};var h4={name:"lock",concurrency:1/0,singleProcess:!1,autoFinalize:!1};function Vc(r){let e=Object.assign({},h4,r);return Mv(e.name,e)}var cd=class{lock;child;pins;routing;started;constructor(e,t,n,o={}){this.child=e,this.pins=t,this.routing=n,this.lock=Vc({singleProcess:o.holdGcLock}),this.started=!1}isStarted(){return this.started}async start(){await rn(this.child),this.started=!0}async stop(){await nn(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 Dc("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 Dc("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 p0=new Le("/version"),Fv=1;async function $v(r){if(!await r.has(p0)){await r.put(p0,L(`${Fv}`));return}let e=await r.get(p0),t=j(e);if(parseInt(t,10)!==Fv)throw new $f("Invalid datastore version, a datastore migration may be required")}var B0={};Me(B0,{code:()=>C0,decode:()=>sN,decodeOptions:()=>nN,encode:()=>iN,encodeOptions:()=>tN,name:()=>oN,toByteView:()=>G2});var p4=["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 m0(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=m4(r);return t||"Object"}function m4(r){let e=Object.prototype.toString.call(r).slice(8,-1);if(p4.includes(e))return e}var x=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}};x.uint=new x(0,"uint",!0);x.negint=new x(1,"negint",!0);x.bytes=new x(2,"bytes",!0);x.string=new x(3,"string",!0);x.array=new x(4,"array",!1);x.map=new x(5,"map",!1);x.tag=new x(6,"tag",!1);x.float=new x(7,"float",!0);x.false=new x(7,"false",!0);x.true=new x(7,"true",!0);x.null=new x(7,"null",!0);x.undefined=new x(7,"undefined",!0);x.break=new x(7,"break",!0);var K=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 Kc=globalThis.process&&!globalThis.process.browser&&globalThis.Buffer&&typeof globalThis.Buffer.isBuffer=="function",g4=new TextEncoder;function ud(r){return Kc&&globalThis.Buffer.isBuffer(r)}function qc(r){return r instanceof Uint8Array?ud(r)?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):r:Uint8Array.from(r)}var y4=24,w4=200,ld=Kc?r=>r.length>=y4?globalThis.Buffer.from(r):Vv(r):r=>r.length>=w4?g4.encode(r):Vv(r),mn=r=>Uint8Array.from(r),Kv=Kc?(r,e,t)=>ud(r)?new Uint8Array(r.subarray(e,t)):r.slice(e,t):(r,e,t)=>r.slice(e,t),qv=Kc?(r,e)=>(r=r.map(t=>t instanceof Uint8Array?t:globalThis.Buffer.from(t)),qc(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},Hv=Kc?r=>globalThis.Buffer.allocUnsafe(r):r=>new Uint8Array(r);function fd(r,e){if(ud(r)&&ud(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 Vv(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 b4=256,Hc=class{constructor(e=b4){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=Hv(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=Kv(n,0,this.cursor)}else t=qv(this.chunks,this.cursor);return e&&this.reset(),t}},dd=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 re="CBOR decode error:",hd="CBOR encode error:",zc=[];zc[23]=1;zc[24]=2;zc[25]=3;zc[26]=5;zc[27]=9;function Ln(r,e,t){if(r.length-e<t)throw new Error(`${re} not enough data for type`)}var tt=[24,256,65536,4294967296,BigInt("18446744073709551616")];function zt(r,e,t){Ln(r,e,1);let n=r[e];if(t.strict===!0&&n<tt[0])throw new Error(`${re} integer encoded in more bytes than necessary (strict decode)`);return n}function jt(r,e,t){Ln(r,e,2);let n=r[e]<<8|r[e+1];if(t.strict===!0&&n<tt[1])throw new Error(`${re} integer encoded in more bytes than necessary (strict decode)`);return n}function Gt(r,e,t){Ln(r,e,4);let n=r[e]*16777216+(r[e+1]<<16)+(r[e+2]<<8)+r[e+3];if(t.strict===!0&&n<tt[2])throw new Error(`${re} integer encoded in more bytes than necessary (strict decode)`);return n}function Wt(r,e,t){Ln(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<tt[3])throw new Error(`${re} 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(`${re} integers outside of the safe integer range are not supported`)}function zv(r,e,t,n){return new K(x.uint,zt(r,e+1,n),2)}function jv(r,e,t,n){return new K(x.uint,jt(r,e+1,n),3)}function Gv(r,e,t,n){return new K(x.uint,Gt(r,e+1,n),5)}function Wv(r,e,t,n){return new K(x.uint,Wt(r,e+1,n),9)}function pr(r,e){return Ce(r,0,e.value)}function Ce(r,e,t){if(t<tt[0]){let n=Number(t);r.push([e|n])}else if(t<tt[1]){let n=Number(t);r.push([e|24,n])}else if(t<tt[2]){let n=Number(t);r.push([e|25,n>>>8,n&255])}else if(t<tt[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<tt[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(`${re} encountered BigInt larger than allowable range`)}}pr.encodedSize=function(e){return Ce.encodedSize(e.value)};Ce.encodedSize=function(e){return e<tt[0]?1:e<tt[1]?2:e<tt[2]?3:e<tt[3]?5:9};pr.compareTokens=function(e,t){return e.value<t.value?-1:e.value>t.value?1:0};function Yv(r,e,t,n){return new K(x.negint,-1-zt(r,e+1,n),2)}function Xv(r,e,t,n){return new K(x.negint,-1-jt(r,e+1,n),3)}function Zv(r,e,t,n){return new K(x.negint,-1-Gt(r,e+1,n),5)}var g0=BigInt(-1),Jv=BigInt(1);function Qv(r,e,t,n){let o=Wt(r,e+1,n);if(typeof o!="bigint"){let i=-1-o;if(i>=Number.MIN_SAFE_INTEGER)return new K(x.negint,i,9)}if(n.allowBigInt!==!0)throw new Error(`${re} integers outside of the safe integer range are not supported`);return new K(x.negint,g0-BigInt(o),9)}function pd(r,e){let t=e.value,n=typeof t=="bigint"?t*g0-Jv:t*-1-1;Ce(r,e.type.majorEncoded,n)}pd.encodedSize=function(e){let t=e.value,n=typeof t=="bigint"?t*g0-Jv:t*-1-1;return n<tt[0]?1:n<tt[1]?2:n<tt[2]?3:n<tt[3]?5:9};pd.compareTokens=function(e,t){return e.value<t.value?1:e.value>t.value?-1:0};function jc(r,e,t,n){Ln(r,e,t+n);let o=r.slice(e+t,e+t+n);return new K(x.bytes,o,t+n)}function e2(r,e,t,n){return jc(r,e,1,t)}function t2(r,e,t,n){return jc(r,e,2,zt(r,e+1,n))}function r2(r,e,t,n){return jc(r,e,3,jt(r,e+1,n))}function n2(r,e,t,n){return jc(r,e,5,Gt(r,e+1,n))}function o2(r,e,t,n){let o=Wt(r,e+1,n);if(typeof o=="bigint")throw new Error(`${re} 64-bit integer bytes lengths not supported`);return jc(r,e,9,o)}function md(r){return r.encodedBytes===void 0&&(r.encodedBytes=x.equals(r.type,x.string)?ld(r.value):r.value),r.encodedBytes}function Fs(r,e){let t=md(e);Ce(r,e.type.majorEncoded,t.length),r.push(t)}Fs.encodedSize=function(e){let t=md(e);return Ce.encodedSize(t.length)+t.length};Fs.compareTokens=function(e,t){return E4(md(e),md(t))};function E4(r,e){return r.length<e.length?-1:r.length>e.length?1:fd(r,e)}var i2=new TextDecoder,A4=32;function S4(r,e,t){if(t-e<A4){let o="";for(let i=e;i<t;i++){let s=r[i];if(s&128)return i2.decode(r.subarray(e,t));o+=String.fromCharCode(s)}return o}return i2.decode(r.subarray(e,t))}function Gc(r,e,t,n,o){let i=t+n;Ln(r,e,i);let s=new K(x.string,S4(r,e+t,e+i),i);return o.retainStringBytes===!0&&(s.byteValue=r.slice(e+t,e+i)),s}function s2(r,e,t,n){return Gc(r,e,1,t,n)}function a2(r,e,t,n){return Gc(r,e,2,zt(r,e+1,n),n)}function c2(r,e,t,n){return Gc(r,e,3,jt(r,e+1,n),n)}function u2(r,e,t,n){return Gc(r,e,5,Gt(r,e+1,n),n)}function l2(r,e,t,n){let o=Wt(r,e+1,n);if(typeof o=="bigint")throw new Error(`${re} 64-bit integer string lengths not supported`);return Gc(r,e,9,o,n)}var f2=Fs;function $s(r,e,t,n){return new K(x.array,n,t)}function d2(r,e,t,n){return $s(r,e,1,t)}function h2(r,e,t,n){return $s(r,e,2,zt(r,e+1,n))}function p2(r,e,t,n){return $s(r,e,3,jt(r,e+1,n))}function m2(r,e,t,n){return $s(r,e,5,Gt(r,e+1,n))}function g2(r,e,t,n){let o=Wt(r,e+1,n);if(typeof o=="bigint")throw new Error(`${re} 64-bit integer array lengths not supported`);return $s(r,e,9,o)}function y2(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${re} indefinite length items not allowed`);return $s(r,e,1,1/0)}function gd(r,e){Ce(r,x.array.majorEncoded,e.value)}gd.compareTokens=pr.compareTokens;gd.encodedSize=function(e){return Ce.encodedSize(e.value)};function Vs(r,e,t,n){return new K(x.map,n,t)}function w2(r,e,t,n){return Vs(r,e,1,t)}function b2(r,e,t,n){return Vs(r,e,2,zt(r,e+1,n))}function x2(r,e,t,n){return Vs(r,e,3,jt(r,e+1,n))}function E2(r,e,t,n){return Vs(r,e,5,Gt(r,e+1,n))}function v2(r,e,t,n){let o=Wt(r,e+1,n);if(typeof o=="bigint")throw new Error(`${re} 64-bit integer map lengths not supported`);return Vs(r,e,9,o)}function A2(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${re} indefinite length items not allowed`);return Vs(r,e,1,1/0)}function yd(r,e){Ce(r,x.map.majorEncoded,e.value)}yd.compareTokens=pr.compareTokens;yd.encodedSize=function(e){return Ce.encodedSize(e.value)};function S2(r,e,t,n){return new K(x.tag,t,1)}function k2(r,e,t,n){return new K(x.tag,zt(r,e+1,n),2)}function _2(r,e,t,n){return new K(x.tag,jt(r,e+1,n),3)}function I2(r,e,t,n){return new K(x.tag,Gt(r,e+1,n),5)}function T2(r,e,t,n){return new K(x.tag,Wt(r,e+1,n),9)}function wd(r,e){Ce(r,x.tag.majorEncoded,e.value)}wd.compareTokens=pr.compareTokens;wd.encodedSize=function(e){return Ce.encodedSize(e.value)};var y0=20,w0=21,b0=22,x0=23;function C2(r,e,t,n){if(n.allowUndefined===!1)throw new Error(`${re} undefined values are not supported`);return n.coerceUndefinedToNull===!0?new K(x.null,null,1):new K(x.undefined,void 0,1)}function B2(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${re} indefinite length items not allowed`);return new K(x.break,void 0,1)}function E0(r,e,t){if(t){if(t.allowNaN===!1&&Number.isNaN(r))throw new Error(`${re} NaN values are not supported`);if(t.allowInfinity===!1&&(r===1/0||r===-1/0))throw new Error(`${re} Infinity values are not supported`)}return new K(x.float,r,e)}function N2(r,e,t,n){return E0(v0(r,e+1),3,n)}function P2(r,e,t,n){return E0(A0(r,e+1),5,n)}function L2(r,e,t,n){return E0(O2(r,e+1),9,n)}function Wc(r,e,t){let n=e.value;if(n===!1)r.push([x.float.majorEncoded|y0]);else if(n===!0)r.push([x.float.majorEncoded|w0]);else if(n===null)r.push([x.float.majorEncoded|b0]);else if(n===void 0)r.push([x.float.majorEncoded|x0]);else{let o,i=!1;(!t||t.float64!==!0)&&(R2(n),o=v0(Hr,1),n===o||Number.isNaN(n)?(Hr[0]=249,r.push(Hr.slice(0,3)),i=!0):(U2(n),o=A0(Hr,1),n===o&&(Hr[0]=250,r.push(Hr.slice(0,5)),i=!0))),i||(C4(n),o=O2(Hr,1),Hr[0]=251,r.push(Hr.slice(0,9)))}}Wc.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){R2(n);let o=v0(Hr,1);if(n===o||Number.isNaN(n))return 3;if(U2(n),o=A0(Hr,1),n===o)return 5}return 9};var D2=new ArrayBuffer(9),mr=new DataView(D2,1),Hr=new Uint8Array(D2,0);function R2(r){if(r===1/0)mr.setUint16(0,31744,!1);else if(r===-1/0)mr.setUint16(0,64512,!1);else if(Number.isNaN(r))mr.setUint16(0,32256,!1);else{mr.setFloat32(0,r);let e=mr.getUint32(0),t=(e&2139095040)>>23,n=e&8388607;if(t===255)mr.setUint16(0,31744,!1);else if(t===0)mr.setUint16(0,(e&2147483648)>>16|n>>13,!1);else{let o=t-127;o<-24?mr.setUint16(0,0):o<-14?mr.setUint16(0,(e&2147483648)>>16|1<<24+o,!1):mr.setUint16(0,(e&2147483648)>>16|o+15<<10|n>>13,!1)}}}function v0(r,e){if(r.length-e<2)throw new Error(`${re} 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 U2(r){mr.setFloat32(0,r,!1)}function A0(r,e){if(r.length-e<4)throw new Error(`${re} not enough data for float32`);let t=(r.byteOffset||0)+e;return new DataView(r.buffer,t,4).getFloat32(0,!1)}function C4(r){mr.setFloat64(0,r,!1)}function O2(r,e){if(r.length-e<8)throw new Error(`${re} not enough data for float64`);let t=(r.byteOffset||0)+e;return new DataView(r.buffer,t,8).getFloat64(0,!1)}Wc.compareTokens=pr.compareTokens;function we(r,e,t){throw new Error(`${re} encountered invalid minor (${t}) for major ${r[e]>>>5}`)}function bd(r){return()=>{throw new Error(`${re} ${r}`)}}var U=[];for(let r=0;r<=23;r++)U[r]=we;U[24]=zv;U[25]=jv;U[26]=Gv;U[27]=Wv;U[28]=we;U[29]=we;U[30]=we;U[31]=we;for(let r=32;r<=55;r++)U[r]=we;U[56]=Yv;U[57]=Xv;U[58]=Zv;U[59]=Qv;U[60]=we;U[61]=we;U[62]=we;U[63]=we;for(let r=64;r<=87;r++)U[r]=e2;U[88]=t2;U[89]=r2;U[90]=n2;U[91]=o2;U[92]=we;U[93]=we;U[94]=we;U[95]=bd("indefinite length bytes/strings are not supported");for(let r=96;r<=119;r++)U[r]=s2;U[120]=a2;U[121]=c2;U[122]=u2;U[123]=l2;U[124]=we;U[125]=we;U[126]=we;U[127]=bd("indefinite length bytes/strings are not supported");for(let r=128;r<=151;r++)U[r]=d2;U[152]=h2;U[153]=p2;U[154]=m2;U[155]=g2;U[156]=we;U[157]=we;U[158]=we;U[159]=y2;for(let r=160;r<=183;r++)U[r]=w2;U[184]=b2;U[185]=x2;U[186]=E2;U[187]=v2;U[188]=we;U[189]=we;U[190]=we;U[191]=A2;for(let r=192;r<=215;r++)U[r]=S2;U[216]=k2;U[217]=_2;U[218]=I2;U[219]=T2;U[220]=we;U[221]=we;U[222]=we;U[223]=we;for(let r=224;r<=243;r++)U[r]=bd("simple values are not supported");U[244]=we;U[245]=we;U[246]=we;U[247]=C2;U[248]=bd("simple values are not supported");U[249]=N2;U[250]=P2;U[251]=L2;U[252]=we;U[253]=we;U[254]=we;U[255]=B2;var zr=[];for(let r=0;r<24;r++)zr[r]=new K(x.uint,r,1);for(let r=-1;r>=-24;r--)zr[31-r]=new K(x.negint,r,1);zr[64]=new K(x.bytes,new Uint8Array(0),1);zr[96]=new K(x.string,"",1);zr[128]=new K(x.array,0,1);zr[160]=new K(x.map,0,1);zr[244]=new K(x.false,!1,1);zr[245]=new K(x.true,!0,1);zr[246]=new K(x.null,null,1);function S0(r){switch(r.type){case x.false:return mn([244]);case x.true:return mn([245]);case x.null:return mn([246]);case x.bytes:return r.value.length?void 0:mn([64]);case x.string:return r.value===""?mn([96]):void 0;case x.array:return r.value===0?mn([128]):void 0;case x.map:return r.value===0?mn([160]):void 0;case x.uint:return r.value<24?mn([Number(r.value)]):void 0;case x.negint:if(r.value>=-24)return mn([31-Number(r.value)])}}var N4={float64:!1,mapSorter:D4,quickEncodeToken:S0},K2=Object.freeze({float64:!0,mapSorter:R4,quickEncodeToken:S0});function P4(){let r=[];return r[x.uint.major]=pr,r[x.negint.major]=pd,r[x.bytes.major]=Fs,r[x.string.major]=f2,r[x.array.major]=gd,r[x.map.major]=yd,r[x.tag.major]=wd,r[x.float.major]=Wc,r}var qs=P4(),xd=new Hc,Xc=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(`${hd} object contains circular references`);return new r(t,e)}},bo={null:new K(x.null,null),undefined:new K(x.undefined,void 0),true:new K(x.true,!0),false:new K(x.false,!1),emptyArray:new K(x.array,0),emptyMap:new K(x.map,0)},gn={number(r,e,t,n){return!Number.isInteger(r)||!Number.isSafeInteger(r)?new K(x.float,r):r>=0?new K(x.uint,r):new K(x.negint,r)},bigint(r,e,t,n){return r>=BigInt(0)?new K(x.uint,r):new K(x.negint,r)},Uint8Array(r,e,t,n){return new K(x.bytes,r)},string(r,e,t,n){return new K(x.string,r)},boolean(r,e,t,n){return r?bo.true:bo.false},null(r,e,t,n){return bo.null},undefined(r,e,t,n){return bo.undefined},ArrayBuffer(r,e,t,n){return new K(x.bytes,new Uint8Array(r))},DataView(r,e,t,n){return new K(x.bytes,new Uint8Array(r.buffer,r.byteOffset,r.byteLength))},Array(r,e,t,n){if(!r.length)return t.addBreakTokens===!0?[bo.emptyArray,new K(x.break)]:bo.emptyArray;n=Xc.createCheck(n,r);let o=[],i=0;for(let s of r)o[i++]=Ks(s,t,n);return t.addBreakTokens?[new K(x.array,r.length),o,new K(x.break)]:[new K(x.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=Xc.createCheck(n,r);let c=!o&&t.ignoreUndefinedProperties,u=0;for(let l of i){let f=o?r.get(l):r[l];c&&f===void 0||(a[u++]=[Ks(l,t,n),Ks(f,t,n)])}u<s&&(a.length=u)}return a?.length?(L4(a,t),t.addBreakTokens?[new K(x.map,a.length),a,new K(x.break)]:[new K(x.map,a.length),a]):t.addBreakTokens===!0?[bo.emptyMap,new K(x.break)]:bo.emptyMap},Tagged(r,e,t,n){return[new K(x.tag,r.tag),Ks(r.value,t,n)]}};gn.Map=gn.Object;gn.Buffer=gn.Uint8Array;for(let r of"Uint8Clamped Uint16 Uint32 Int8 Int16 Int32 BigUint64 BigInt64 Float32 Float64".split(" "))gn[`${r}Array`]=gn.DataView;function Ks(r,e={},t){let n=m0(r),o=e&&e.typeEncoders&&e.typeEncoders[n]||gn[n];if(typeof o=="function"){let s=o(r,n,e,t);if(s!=null)return s}let i=gn[n];if(!i)throw new Error(`${hd} unsupported type: ${n}`);return i(r,n,e,t)}function L4(r,e){e.mapSorter&&r.sort(e.mapSorter)}function D4(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=qs[o].compareTokens(t,n);return i===0&&console.warn("WARNING: complex key types used, CBOR key sorting guarantees are gone"),i}function R4(r,e){if(r[0]instanceof K&&e[0]instanceof K){let t=r[0],n=e[0];return t._keyBytes||(t._keyBytes=M2(t.value)),n._keyBytes||(n._keyBytes=M2(n.value)),fd(t._keyBytes,n._keyBytes)}throw new Error("rfc8949MapSorter: complex key types are not supported yet")}function M2(r){return H2(r,qs,K2)}function Yc(r,e,t,n){if(Array.isArray(e))for(let o of e)Yc(r,o,t,n);else t[e.type.major](r,e,n)}var F2=x.uint.majorEncoded,$2=x.negint.majorEncoded,U4=x.bytes.majorEncoded,O4=x.string.majorEncoded,V2=x.array.majorEncoded,M4=x.float.majorEncoded|y0,F4=x.float.majorEncoded|w0,$4=x.float.majorEncoded|b0,V4=x.float.majorEncoded|x0,K4=BigInt(-1),q4=BigInt(1);function H4(r){return r.addBreakTokens!==!0}function q2(r,e,t,n){let o=m0(e),i=t.typeEncoders&&t.typeEncoders[o];if(i){let s=i(e,o,t,n);if(s!=null){Yc(r,s,qs,t);return}}switch(o){case"null":r.push([$4]);return;case"undefined":r.push([V4]);return;case"boolean":r.push([e?F4:M4]);return;case"number":!Number.isInteger(e)||!Number.isSafeInteger(e)?Wc(r,new K(x.float,e),t):e>=0?Ce(r,F2,e):Ce(r,$2,e*-1-1);return;case"bigint":e>=BigInt(0)?Ce(r,F2,e):Ce(r,$2,e*K4-q4);return;case"string":{let s=ld(e);Ce(r,O4,s.length),r.push(s);return}case"Uint8Array":Ce(r,U4,e.length),r.push(e);return;case"Array":if(!e.length){r.push([V2]);return}n=Xc.createCheck(n,e),Ce(r,V2,e.length);for(let s of e)q2(r,s,t,n);return;case"Object":case"Map":{let s=gn.Object(e,o,t,n);Yc(r,s,qs,t)}return;default:{let s=gn[o];if(!s)throw new Error(`${hd} unsupported type: ${o}`);let a=s(e,o,t,n);Yc(r,a,qs,t)}}}function H2(r,e,t,n){let o=n instanceof Uint8Array,i=o?new dd(n):xd,s=Ks(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 u=c.encodedSize(s,t);if(o||(i=new Hc(u)),c(i,s,t),i.chunks.length!==1)throw new Error(`Unexpected error: pre-calculated length for ${s} was wrong`);return o?i.toBytes():qc(i.chunks[0])}}return i.reset(),Yc(i,s,e,t),i.toBytes(!0)}function k0(r,e){return e=Object.assign({},N4,e),H4(e)?(xd.reset(),q2(xd,r,e,void 0),xd.toBytes(!0)):H2(r,qs,e)}var z4={strict:!1,allowIndefinite:!0,allowUndefined:!0,allowBigInt:!0},Ed=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=zr[e];if(t===void 0){let n=U[e];if(!n)throw new Error(`${re} 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}},xo=Symbol.for("DONE"),Hs=Symbol.for("BREAK");function j4(r,e,t){let n=[];for(let o=0;o<r.value;o++){let i=Eo(e,t);if(i===Hs){if(r.value===1/0)break;throw new Error(`${re} got unexpected break to lengthed array`)}if(i===xo)throw new Error(`${re} found array but not enough entries (got ${o}, expected ${r.value})`);n[o]=i}return n}function G4(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=Eo(e,t);if(c===Hs){if(r.value===1/0)break;throw new Error(`${re} got unexpected break to lengthed map`)}if(c===xo)throw new Error(`${re} found map but not enough entries (got ${a} [no key], expected ${r.value})`);if(!n&&typeof c!="string")throw new Error(`${re} non-string keys not supported (got ${typeof c})`);if(o&&(n&&s.has(c)||!n&&Object.hasOwn(i,c)))throw new Error(`${re} found repeat map key "${c}"`);let u=Eo(e,t);if(u===xo)throw new Error(`${re} found map but not enough entries (got ${a} [no value], expected ${r.value})`);n?s.set(c,u):i[c]=u}return n?s:i}function*W4(r,e,t){for(let n=0;n<r.value;n++){let o=Eo(e,t);if(o===Hs){if(r.value===1/0)break;throw new Error(`${re} got unexpected break to lengthed map`)}if(o===xo)throw new Error(`${re} found map but not enough entries (got ${n} [no key], expected ${r.value})`);let i=Eo(e,t);if(i===xo)throw new Error(`${re} found map but not enough entries (got ${n} [no value], expected ${r.value})`);yield[o,i]}}function Y4(r,e){let t=!1,n=function(){if(t)throw new Error(`${re} tag decode() may only be called once`);t=!0;let o=Eo(r,e);if(o===xo)throw new Error(`${re} tag content missing`);if(o===Hs)throw new Error(`${re} got unexpected break in tag content`);return o};return n.entries=function(){if(t)throw new Error(`${re} tag decode() may only be called once`);t=!0;let o=r.next();if(!x.equals(o.type,x.map))throw new Error(`${re} entries() requires map content, got ${o.type.name}`);let i=[];for(let s of W4(o,r,e))i.push(s);return i},Object.defineProperty(n,"_called",{get(){return t},enumerable:!1}),n}function Eo(r,e){if(r.done())return xo;let t=r.next();if(x.equals(t.type,x.break))return Hs;if(t.type.terminal)return t.value;if(x.equals(t.type,x.array))return j4(t,r,e);if(x.equals(t.type,x.map))return G4(t,r,e);if(x.equals(t.type,x.tag)){if(e.tags&&typeof e.tags[t.value]=="function"){let n=Y4(r,e),o=e.tags[t.value](n);if(!n._called)throw new Error(`${re} tag decoder must call decode() or entries()`);return o}throw new Error(`${re} tag not supported (${t.value})`)}throw new Error("unsupported")}function z2(r,e){if(!(r instanceof Uint8Array))throw new Error(`${re} data to decode must be a Uint8Array`);e=Object.assign({},z4,e);let t=qc(r),n=e.tokenizer||new Ed(t,e),o=Eo(n,e);if(o===xo)throw new Error(`${re} did not find any content to decode`);if(o===Hs)throw new Error(`${re} got unexpected break`);return[o,r.subarray(n.pos())]}function _0(r,e){let[t,n]=z2(r,e);if(n.length>0)throw new Error(`${re} too many terminals, data makes no sense`);return t}var vd=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(vd.prototype,Symbol.toStringTag,{value:"Tagged"});var j2=42;function G2(r){return r instanceof ArrayBuffer?new Uint8Array(r,0,r.byteLength):r}function Z4(r){if(r.asCID!==r&&r["/"]!==r.bytes)return null;let e=Q.asCID(r);if(!e)return null;let t=new Uint8Array(e.bytes.byteLength+1);return t.set(e.bytes,1),[new K(x.tag,j2),new K(x.bytes,t)]}function J4(){throw new Error("`undefined` is not supported by the IPLD Data Model and cannot be encoded")}function Q4(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 eN(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 I0={float64:!0,typeEncoders:{Map:eN,Object:Z4,undefined:J4,number:Q4}},tN={...I0,typeEncoders:{...I0.typeEncoders}};function rN(r){let e=r();if(e[0]!==0)throw new Error("Invalid CID for CBOR tag 42; expected leading 0x00");return Q.decode(e.subarray(1))}var T0={allowIndefinite:!1,coerceUndefinedToNull:!0,allowNaN:!1,allowInfinity:!1,allowBigInt:!0,strict:!0,useMaps:!1,rejectDuplicateMapKeys:!0,tags:{[j2]:rN}},nN={...T0,tags:{...T0.tags}},oN="dag-cbor",C0=113,iN=r=>k0(r,I0),sN=r=>_0(G2(r),T0);var G0={};Me(G0,{code:()=>j0,decode:()=>eS,encode:()=>QA,format:()=>HN,name:()=>qN,parse:()=>jN,stringify:()=>HN});var aN=["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 W2(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=cN(r);return t||"Object"}function cN(r){let e=Object.prototype.toString.call(r).slice(8,-1);if(aN.includes(e))return e}var p=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}};p.uint=new p(0,"uint",!0);p.negint=new p(1,"negint",!0);p.bytes=new p(2,"bytes",!0);p.string=new p(3,"string",!0);p.array=new p(4,"array",!1);p.map=new p(5,"map",!1);p.tag=new p(6,"tag",!1);p.float=new p(7,"float",!0);p.false=new p(7,"false",!0);p.true=new p(7,"true",!0);p.null=new p(7,"null",!0);p.undefined=new p(7,"undefined",!0);p.break=new p(7,"break",!0);var B=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 Zc=globalThis.process&&!globalThis.process.browser&&globalThis.Buffer&&typeof globalThis.Buffer.isBuffer=="function",uN=new TextEncoder;function Ad(r){return Zc&&globalThis.Buffer.isBuffer(r)}function Si(r){return r instanceof Uint8Array?Ad(r)?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):r:Uint8Array.from(r)}var lN=24,fN=200,Jc=Zc?r=>r.length>=lN?globalThis.Buffer.from(r):Y2(r):r=>r.length>=fN?uN.encode(r):Y2(r),yn=r=>Uint8Array.from(r),Z2=Zc?(r,e,t)=>Ad(r)?new Uint8Array(r.subarray(e,t)):r.slice(e,t):(r,e,t)=>r.slice(e,t),J2=Zc?(r,e)=>(r=r.map(t=>t instanceof Uint8Array?t:globalThis.Buffer.from(t)),Si(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},Q2=Zc?r=>globalThis.Buffer.allocUnsafe(r):r=>new Uint8Array(r);function Sd(r,e){if(Ad(r)&&Ad(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 Y2(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 X2=4096;function eA(r){let e=r.length;if(e<=X2)return String.fromCharCode.apply(String,r);let t="",n=0;for(;n<e;)t+=String.fromCharCode.apply(String,r.slice(n,n+=X2));return t}var dN=256,Qc=class{constructor(e=dN){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=Q2(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=Z2(n,0,this.cursor)}else t=J2(this.chunks,this.cursor);return e&&this.reset(),t}},kd=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 H="CBOR decode error:",Dn="CBOR encode error:",eu=[];eu[23]=1;eu[24]=2;eu[25]=3;eu[26]=5;eu[27]=9;function Rn(r,e,t){if(r.length-e<t)throw new Error(`${H} not enough data for type`)}var rt=[24,256,65536,4294967296,BigInt("18446744073709551616")];function Yt(r,e,t){Rn(r,e,1);let n=r[e];if(t.strict===!0&&n<rt[0])throw new Error(`${H} integer encoded in more bytes than necessary (strict decode)`);return n}function Xt(r,e,t){Rn(r,e,2);let n=r[e]<<8|r[e+1];if(t.strict===!0&&n<rt[1])throw new Error(`${H} integer encoded in more bytes than necessary (strict decode)`);return n}function Zt(r,e,t){Rn(r,e,4);let n=r[e]*16777216+(r[e+1]<<16)+(r[e+2]<<8)+r[e+3];if(t.strict===!0&&n<rt[2])throw new Error(`${H} integer encoded in more bytes than necessary (strict decode)`);return n}function Jt(r,e,t){Rn(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<rt[3])throw new Error(`${H} integer encoded in more bytes than necessary (strict decode)`);if(i<=Number.MAX_SAFE_INTEGER)return Number(i);if(t.allowBigInt===!0)return i;throw new Error(`${H} integers outside of the safe integer range are not supported`)}function tA(r,e,t,n){return new B(p.uint,Yt(r,e+1,n),2)}function rA(r,e,t,n){return new B(p.uint,Xt(r,e+1,n),3)}function nA(r,e,t,n){return new B(p.uint,Zt(r,e+1,n),5)}function oA(r,e,t,n){return new B(p.uint,Jt(r,e+1,n),9)}function gr(r,e){return nt(r,0,e.value)}function nt(r,e,t){if(t<rt[0]){let n=Number(t);r.push([e|n])}else if(t<rt[1]){let n=Number(t);r.push([e|24,n])}else if(t<rt[2]){let n=Number(t);r.push([e|25,n>>>8,n&255])}else if(t<rt[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<rt[4]){let o=[e|27,0,0,0,0,0,0,0],i=Number(n&BigInt(4294967295)),s=Number(n>>BigInt(32)&BigInt(4294967295));o[8]=i&255,i=i>>8,o[7]=i&255,i=i>>8,o[6]=i&255,i=i>>8,o[5]=i&255,o[4]=s&255,s=s>>8,o[3]=s&255,s=s>>8,o[2]=s&255,s=s>>8,o[1]=s&255,r.push(o)}else throw new Error(`${H} encountered BigInt larger than allowable range`)}}gr.encodedSize=function(e){return nt.encodedSize(e.value)};nt.encodedSize=function(e){return e<rt[0]?1:e<rt[1]?2:e<rt[2]?3:e<rt[3]?5:9};gr.compareTokens=function(e,t){return e.value<t.value?-1:e.value>t.value?1:0};function iA(r,e,t,n){return new B(p.negint,-1-Yt(r,e+1,n),2)}function sA(r,e,t,n){return new B(p.negint,-1-Xt(r,e+1,n),3)}function aA(r,e,t,n){return new B(p.negint,-1-Zt(r,e+1,n),5)}var N0=BigInt(-1),cA=BigInt(1);function uA(r,e,t,n){let o=Jt(r,e+1,n);if(typeof o!="bigint"){let i=-1-o;if(i>=Number.MIN_SAFE_INTEGER)return new B(p.negint,i,9)}if(n.allowBigInt!==!0)throw new Error(`${H} integers outside of the safe integer range are not supported`);return new B(p.negint,N0-BigInt(o),9)}function _d(r,e){let t=e.value,n=typeof t=="bigint"?t*N0-cA:t*-1-1;nt(r,e.type.majorEncoded,n)}_d.encodedSize=function(e){let t=e.value,n=typeof t=="bigint"?t*N0-cA:t*-1-1;return n<rt[0]?1:n<rt[1]?2:n<rt[2]?3:n<rt[3]?5:9};_d.compareTokens=function(e,t){return e.value<t.value?1:e.value>t.value?-1:0};function tu(r,e,t,n){Rn(r,e,t+n);let o=r.slice(e+t,e+t+n);return new B(p.bytes,o,t+n)}function lA(r,e,t,n){return tu(r,e,1,t)}function fA(r,e,t,n){return tu(r,e,2,Yt(r,e+1,n))}function dA(r,e,t,n){return tu(r,e,3,Xt(r,e+1,n))}function hA(r,e,t,n){return tu(r,e,5,Zt(r,e+1,n))}function pA(r,e,t,n){let o=Jt(r,e+1,n);if(typeof o=="bigint")throw new Error(`${H} 64-bit integer bytes lengths not supported`);return tu(r,e,9,o)}function Id(r){return r.encodedBytes===void 0&&(r.encodedBytes=p.equals(r.type,p.string)?Jc(r.value):r.value),r.encodedBytes}function zs(r,e){let t=Id(e);nt(r,e.type.majorEncoded,t.length),r.push(t)}zs.encodedSize=function(e){let t=Id(e);return nt.encodedSize(t.length)+t.length};zs.compareTokens=function(e,t){return pN(Id(e),Id(t))};function pN(r,e){return r.length<e.length?-1:r.length>e.length?1:Sd(r,e)}var mA=new TextDecoder,gN=32;function yN(r,e,t){if(t-e<gN){let o="";for(let i=e;i<t;i++){let s=r[i];if(s&128)return mA.decode(r.subarray(e,t));o+=String.fromCharCode(s)}return o}return mA.decode(r.subarray(e,t))}function ru(r,e,t,n,o){let i=t+n;Rn(r,e,i);let s=new B(p.string,yN(r,e+t,e+i),i);return o.retainStringBytes===!0&&(s.byteValue=r.slice(e+t,e+i)),s}function gA(r,e,t,n){return ru(r,e,1,t,n)}function yA(r,e,t,n){return ru(r,e,2,Yt(r,e+1,n),n)}function wA(r,e,t,n){return ru(r,e,3,Xt(r,e+1,n),n)}function bA(r,e,t,n){return ru(r,e,5,Zt(r,e+1,n),n)}function xA(r,e,t,n){let o=Jt(r,e+1,n);if(typeof o=="bigint")throw new Error(`${H} 64-bit integer string lengths not supported`);return ru(r,e,9,o,n)}var EA=zs;function js(r,e,t,n){return new B(p.array,n,t)}function vA(r,e,t,n){return js(r,e,1,t)}function AA(r,e,t,n){return js(r,e,2,Yt(r,e+1,n))}function SA(r,e,t,n){return js(r,e,3,Xt(r,e+1,n))}function kA(r,e,t,n){return js(r,e,5,Zt(r,e+1,n))}function _A(r,e,t,n){let o=Jt(r,e+1,n);if(typeof o=="bigint")throw new Error(`${H} 64-bit integer array lengths not supported`);return js(r,e,9,o)}function IA(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${H} indefinite length items not allowed`);return js(r,e,1,1/0)}function Td(r,e){nt(r,p.array.majorEncoded,e.value)}Td.compareTokens=gr.compareTokens;Td.encodedSize=function(e){return nt.encodedSize(e.value)};function Gs(r,e,t,n){return new B(p.map,n,t)}function TA(r,e,t,n){return Gs(r,e,1,t)}function CA(r,e,t,n){return Gs(r,e,2,Yt(r,e+1,n))}function BA(r,e,t,n){return Gs(r,e,3,Xt(r,e+1,n))}function NA(r,e,t,n){return Gs(r,e,5,Zt(r,e+1,n))}function PA(r,e,t,n){let o=Jt(r,e+1,n);if(typeof o=="bigint")throw new Error(`${H} 64-bit integer map lengths not supported`);return Gs(r,e,9,o)}function LA(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${H} indefinite length items not allowed`);return Gs(r,e,1,1/0)}function Cd(r,e){nt(r,p.map.majorEncoded,e.value)}Cd.compareTokens=gr.compareTokens;Cd.encodedSize=function(e){return nt.encodedSize(e.value)};function DA(r,e,t,n){return new B(p.tag,t,1)}function RA(r,e,t,n){return new B(p.tag,Yt(r,e+1,n),2)}function UA(r,e,t,n){return new B(p.tag,Xt(r,e+1,n),3)}function OA(r,e,t,n){return new B(p.tag,Zt(r,e+1,n),5)}function MA(r,e,t,n){return new B(p.tag,Jt(r,e+1,n),9)}function Bd(r,e){nt(r,p.tag.majorEncoded,e.value)}Bd.compareTokens=gr.compareTokens;Bd.encodedSize=function(e){return nt.encodedSize(e.value)};var P0=20,L0=21,D0=22,R0=23;function FA(r,e,t,n){if(n.allowUndefined===!1)throw new Error(`${H} undefined values are not supported`);return n.coerceUndefinedToNull===!0?new B(p.null,null,1):new B(p.undefined,void 0,1)}function $A(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${H} indefinite length items not allowed`);return new B(p.break,void 0,1)}function U0(r,e,t){if(t){if(t.allowNaN===!1&&Number.isNaN(r))throw new Error(`${H} NaN values are not supported`);if(t.allowInfinity===!1&&(r===1/0||r===-1/0))throw new Error(`${H} Infinity values are not supported`)}return new B(p.float,r,e)}function VA(r,e,t,n){return U0(O0(r,e+1),3,n)}function KA(r,e,t,n){return U0(M0(r,e+1),5,n)}function qA(r,e,t,n){return U0(GA(r,e+1),9,n)}function Nd(r,e,t){let n=e.value;if(n===!1)r.push([p.float.majorEncoded|P0]);else if(n===!0)r.push([p.float.majorEncoded|L0]);else if(n===null)r.push([p.float.majorEncoded|D0]);else if(n===void 0)r.push([p.float.majorEncoded|R0]);else{let o,i=!1;(!t||t.float64!==!0)&&(zA(n),o=O0(jr,1),n===o||Number.isNaN(n)?(jr[0]=249,r.push(jr.slice(0,3)),i=!0):(jA(n),o=M0(jr,1),n===o&&(jr[0]=250,r.push(jr.slice(0,5)),i=!0))),i||(vN(n),o=GA(jr,1),jr[0]=251,r.push(jr.slice(0,9)))}}Nd.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){zA(n);let o=O0(jr,1);if(n===o||Number.isNaN(n))return 3;if(jA(n),o=M0(jr,1),n===o)return 5}return 9};var HA=new ArrayBuffer(9),yr=new DataView(HA,1),jr=new Uint8Array(HA,0);function zA(r){if(r===1/0)yr.setUint16(0,31744,!1);else if(r===-1/0)yr.setUint16(0,64512,!1);else if(Number.isNaN(r))yr.setUint16(0,32256,!1);else{yr.setFloat32(0,r);let e=yr.getUint32(0),t=(e&2139095040)>>23,n=e&8388607;if(t===255)yr.setUint16(0,31744,!1);else if(t===0)yr.setUint16(0,(e&2147483648)>>16|n>>13,!1);else{let o=t-127;o<-24?yr.setUint16(0,0):o<-14?yr.setUint16(0,(e&2147483648)>>16|1<<24+o,!1):yr.setUint16(0,(e&2147483648)>>16|o+15<<10|n>>13,!1)}}}function O0(r,e){if(r.length-e<2)throw new Error(`${H} not enough data for float16`);let t=(r[e]<<8)+r[e+1];if(t===31744)return 1/0;if(t===64512)return-1/0;if(t===32256)return NaN;let n=t>>10&31,o=t&1023,i;return n===0?i=o*2**-24:n!==31?i=(o+1024)*2**(n-25):i=o===0?1/0:NaN,t&32768?-i:i}function jA(r){yr.setFloat32(0,r,!1)}function M0(r,e){if(r.length-e<4)throw new Error(`${H} not enough data for float32`);let t=(r.byteOffset||0)+e;return new DataView(r.buffer,t,4).getFloat32(0,!1)}function vN(r){yr.setFloat64(0,r,!1)}function GA(r,e){if(r.length-e<8)throw new Error(`${H} not enough data for float64`);let t=(r.byteOffset||0)+e;return new DataView(r.buffer,t,8).getFloat64(0,!1)}Nd.compareTokens=gr.compareTokens;function be(r,e,t){throw new Error(`${H} encountered invalid minor (${t}) for major ${r[e]>>>5}`)}function Pd(r){return()=>{throw new Error(`${H} ${r}`)}}var O=[];for(let r=0;r<=23;r++)O[r]=be;O[24]=tA;O[25]=rA;O[26]=nA;O[27]=oA;O[28]=be;O[29]=be;O[30]=be;O[31]=be;for(let r=32;r<=55;r++)O[r]=be;O[56]=iA;O[57]=sA;O[58]=aA;O[59]=uA;O[60]=be;O[61]=be;O[62]=be;O[63]=be;for(let r=64;r<=87;r++)O[r]=lA;O[88]=fA;O[89]=dA;O[90]=hA;O[91]=pA;O[92]=be;O[93]=be;O[94]=be;O[95]=Pd("indefinite length bytes/strings are not supported");for(let r=96;r<=119;r++)O[r]=gA;O[120]=yA;O[121]=wA;O[122]=bA;O[123]=xA;O[124]=be;O[125]=be;O[126]=be;O[127]=Pd("indefinite length bytes/strings are not supported");for(let r=128;r<=151;r++)O[r]=vA;O[152]=AA;O[153]=SA;O[154]=kA;O[155]=_A;O[156]=be;O[157]=be;O[158]=be;O[159]=IA;for(let r=160;r<=183;r++)O[r]=TA;O[184]=CA;O[185]=BA;O[186]=NA;O[187]=PA;O[188]=be;O[189]=be;O[190]=be;O[191]=LA;for(let r=192;r<=215;r++)O[r]=DA;O[216]=RA;O[217]=UA;O[218]=OA;O[219]=MA;O[220]=be;O[221]=be;O[222]=be;O[223]=be;for(let r=224;r<=243;r++)O[r]=Pd("simple values are not supported");O[244]=be;O[245]=be;O[246]=be;O[247]=FA;O[248]=Pd("simple values are not supported");O[249]=VA;O[250]=KA;O[251]=qA;O[252]=be;O[253]=be;O[254]=be;O[255]=$A;var Gr=[];for(let r=0;r<24;r++)Gr[r]=new B(p.uint,r,1);for(let r=-1;r>=-24;r--)Gr[31-r]=new B(p.negint,r,1);Gr[64]=new B(p.bytes,new Uint8Array(0),1);Gr[96]=new B(p.string,"",1);Gr[128]=new B(p.array,0,1);Gr[160]=new B(p.map,0,1);Gr[244]=new B(p.false,!1,1);Gr[245]=new B(p.true,!0,1);Gr[246]=new B(p.null,null,1);function WA(r){switch(r.type){case p.false:return yn([244]);case p.true:return yn([245]);case p.null:return yn([246]);case p.bytes:return r.value.length?void 0:yn([64]);case p.string:return r.value===""?yn([96]):void 0;case p.array:return r.value===0?yn([128]):void 0;case p.map:return r.value===0?yn([160]):void 0;case p.uint:return r.value<24?yn([Number(r.value)]):void 0;case p.negint:if(r.value>=-24)return yn([31-Number(r.value)])}}var XA=Object.freeze({float64:!0,mapSorter:TN,quickEncodeToken:WA});function SN(){let r=[];return r[p.uint.major]=gr,r[p.negint.major]=_d,r[p.bytes.major]=zs,r[p.string.major]=EA,r[p.array.major]=Td,r[p.map.major]=Cd,r[p.tag.major]=Bd,r[p.float.major]=Nd,r}var kN=SN(),_N=new Qc,Ld=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(`${Dn} object contains circular references`);return new r(t,e)}},vo={null:new B(p.null,null),undefined:new B(p.undefined,void 0),true:new B(p.true,!0),false:new B(p.false,!1),emptyArray:new B(p.array,0),emptyMap:new B(p.map,0)},Ao={number(r,e,t,n){return!Number.isInteger(r)||!Number.isSafeInteger(r)?new B(p.float,r):r>=0?new B(p.uint,r):new B(p.negint,r)},bigint(r,e,t,n){return r>=BigInt(0)?new B(p.uint,r):new B(p.negint,r)},Uint8Array(r,e,t,n){return new B(p.bytes,r)},string(r,e,t,n){return new B(p.string,r)},boolean(r,e,t,n){return r?vo.true:vo.false},null(r,e,t,n){return vo.null},undefined(r,e,t,n){return vo.undefined},ArrayBuffer(r,e,t,n){return new B(p.bytes,new Uint8Array(r))},DataView(r,e,t,n){return new B(p.bytes,new Uint8Array(r.buffer,r.byteOffset,r.byteLength))},Array(r,e,t,n){if(!r.length)return t.addBreakTokens===!0?[vo.emptyArray,new B(p.break)]:vo.emptyArray;n=Ld.createCheck(n,r);let o=[],i=0;for(let s of r)o[i++]=Ws(s,t,n);return t.addBreakTokens?[new B(p.array,r.length),o,new B(p.break)]:[new B(p.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=Ld.createCheck(n,r);let c=!o&&t.ignoreUndefinedProperties,u=0;for(let l of i){let f=o?r.get(l):r[l];c&&f===void 0||(a[u++]=[Ws(l,t,n),Ws(f,t,n)])}u<s&&(a.length=u)}return a?.length?(IN(a,t),t.addBreakTokens?[new B(p.map,a.length),a,new B(p.break)]:[new B(p.map,a.length),a]):t.addBreakTokens===!0?[vo.emptyMap,new B(p.break)]:vo.emptyMap},Tagged(r,e,t,n){return[new B(p.tag,r.tag),Ws(r.value,t,n)]}};Ao.Map=Ao.Object;Ao.Buffer=Ao.Uint8Array;for(let r of"Uint8Clamped Uint16 Uint32 Int8 Int16 Int32 BigUint64 BigInt64 Float32 Float64".split(" "))Ao[`${r}Array`]=Ao.DataView;function Ws(r,e={},t){let n=W2(r),o=e&&e.typeEncoders&&e.typeEncoders[n]||Ao[n];if(typeof o=="function"){let s=o(r,n,e,t);if(s!=null)return s}let i=Ao[n];if(!i)throw new Error(`${Dn} unsupported type: ${n}`);return i(r,n,e,t)}function IN(r,e){e.mapSorter&&r.sort(e.mapSorter)}function TN(r,e){if(r[0]instanceof B&&e[0]instanceof B){let t=r[0],n=e[0];return t._keyBytes||(t._keyBytes=YA(t.value)),n._keyBytes||(n._keyBytes=YA(n.value)),Sd(t._keyBytes,n._keyBytes)}throw new Error("rfc8949MapSorter: complex key types are not supported yet")}function YA(r){return F0(r,kN,XA)}function ZA(r,e,t,n){if(Array.isArray(e))for(let o of e)ZA(r,o,t,n);else t[e.type.major](r,e,n)}var _z=p.uint.majorEncoded,Iz=p.negint.majorEncoded,Tz=p.bytes.majorEncoded,Cz=p.string.majorEncoded,Bz=p.array.majorEncoded,Nz=p.float.majorEncoded|P0,Pz=p.float.majorEncoded|L0,Lz=p.float.majorEncoded|D0,Dz=p.float.majorEncoded|R0,Rz=BigInt(-1),Uz=BigInt(1);function F0(r,e,t,n){let o=n instanceof Uint8Array,i=o?new kd(n):_N,s=Ws(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 u=c.encodedSize(s,t);if(o||(i=new Qc(u)),c(i,s,t),i.chunks.length!==1)throw new Error(`Unexpected error: pre-calculated length for ${s} was wrong`);return o?i.toBytes():Si(i.chunks[0])}}return i.reset(),ZA(i,s,e,t),i.toBytes(!0)}var CN={strict:!1,allowIndefinite:!0,allowUndefined:!0,allowBigInt:!0},Dd=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=Gr[e];if(t===void 0){let n=O[e];if(!n)throw new Error(`${H} no decoder for major type ${e>>>5} (byte 0x${e.toString(16).padStart(2,"0")})`);let o=e&31;t=n(this.data,this._pos,o,this.options)}return this._pos+=t.encodedLength,t}},So=Symbol.for("DONE"),Ys=Symbol.for("BREAK");function BN(r,e,t){let n=[];for(let o=0;o<r.value;o++){let i=ko(e,t);if(i===Ys){if(r.value===1/0)break;throw new Error(`${H} got unexpected break to lengthed array`)}if(i===So)throw new Error(`${H} found array but not enough entries (got ${o}, expected ${r.value})`);n[o]=i}return n}function NN(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=ko(e,t);if(c===Ys){if(r.value===1/0)break;throw new Error(`${H} got unexpected break to lengthed map`)}if(c===So)throw new Error(`${H} found map but not enough entries (got ${a} [no key], expected ${r.value})`);if(!n&&typeof c!="string")throw new Error(`${H} non-string keys not supported (got ${typeof c})`);if(o&&(n&&s.has(c)||!n&&Object.hasOwn(i,c)))throw new Error(`${H} found repeat map key "${c}"`);let u=ko(e,t);if(u===So)throw new Error(`${H} found map but not enough entries (got ${a} [no value], expected ${r.value})`);n?s.set(c,u):i[c]=u}return n?s:i}function*PN(r,e,t){for(let n=0;n<r.value;n++){let o=ko(e,t);if(o===Ys){if(r.value===1/0)break;throw new Error(`${H} got unexpected break to lengthed map`)}if(o===So)throw new Error(`${H} found map but not enough entries (got ${n} [no key], expected ${r.value})`);let i=ko(e,t);if(i===So)throw new Error(`${H} found map but not enough entries (got ${n} [no value], expected ${r.value})`);yield[o,i]}}function LN(r,e){let t=!1,n=function(){if(t)throw new Error(`${H} tag decode() may only be called once`);t=!0;let o=ko(r,e);if(o===So)throw new Error(`${H} tag content missing`);if(o===Ys)throw new Error(`${H} got unexpected break in tag content`);return o};return n.entries=function(){if(t)throw new Error(`${H} tag decode() may only be called once`);t=!0;let o=r.next();if(!p.equals(o.type,p.map))throw new Error(`${H} entries() requires map content, got ${o.type.name}`);let i=[];for(let s of PN(o,r,e))i.push(s);return i},Object.defineProperty(n,"_called",{get(){return t},enumerable:!1}),n}function ko(r,e){if(r.done())return So;let t=r.next();if(p.equals(t.type,p.break))return Ys;if(t.type.terminal)return t.value;if(p.equals(t.type,p.array))return BN(t,r,e);if(p.equals(t.type,p.map))return NN(t,r,e);if(p.equals(t.type,p.tag)){if(e.tags&&typeof e.tags[t.value]=="function"){let n=LN(r,e),o=e.tags[t.value](n);if(!n._called)throw new Error(`${H} tag decoder must call decode() or entries()`);return o}throw new Error(`${H} tag not supported (${t.value})`)}throw new Error("unsupported")}function $0(r,e){if(!(r instanceof Uint8Array))throw new Error(`${H} data to decode must be a Uint8Array`);e=Object.assign({},CN,e);let t=Si(r),n=e.tokenizer||new Dd(t,e),o=ko(n,e);if(o===So)throw new Error(`${H} did not find any content to decode`);if(o===Ys)throw new Error(`${H} got unexpected break`);return[o,r.subarray(n.pos())]}function V0(r,e){let[t,n]=$0(r,e);if(n.length>0)throw new Error(`${H} too many terminals, data makes no sense`);return t}var Rd=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(Rd.prototype,Symbol.toStringTag,{value:"Tagged"});var K0=class extends Array{constructor(){super(),this.inRecursive=[]}prefix(e){let t=this.inRecursive[this.inRecursive.length-1];t&&(p.equals(t.type,p.array)&&(t.elements++,t.elements!==1&&e.push([44])),p.equals(t.type,p.map)&&(t.elements++,t.elements!==1&&(t.elements%2===1?e.push([44]):e.push([58]))))}[p.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)}[p.negint.major](e,t){this[p.uint.major](e,t)}[p.bytes.major](e,t){throw new Error(`${Dn} unsupported type: Uint8Array`)}[p.string.major](e,t){this.prefix(e);let n=Jc(JSON.stringify(t.value));e.push(n.length>32?Si(n):n)}[p.array.major](e,t){this.prefix(e),this.inRecursive.push({type:p.array,elements:0}),e.push([91])}[p.map.major](e,t){this.prefix(e),this.inRecursive.push({type:p.map,elements:0}),e.push([123])}[p.tag.major](e,t){}[p.float.major](e,t){if(t.type.name==="break"){let s=this.inRecursive.pop();if(s){if(p.equals(s.type,p.array))e.push([93]);else if(p.equals(s.type,p.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(`${Dn} 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 DN(r,e){if(Array.isArray(r[0])||Array.isArray(e[0]))throw new Error(`${Dn} complex map keys are not supported`);let t=r[0],n=e[0];if(t.type!==p.string||n.type!==p.string)throw new Error(`${Dn} non-string map keys are not supported`);if(t<n)return-1;if(t>n)return 1;throw new Error(`${Dn} unexpected duplicate map keys, this is not supported`)}var RN={addBreakTokens:!0,mapSorter:DN};function q0(r,e){return e=Object.assign({},RN,e),F0(r,new K0,e)}var Xs=class{constructor(e,t={}){this._pos=0,this.data=e,this.options=t,this.modeStack=["value"],this.lastToken=""}pos(){return this._pos}done(){return this._pos>=this.data.length}ch(){return this.data[this._pos]}currentMode(){return this.modeStack[this.modeStack.length-1]}skipWhitespace(){let e=this.ch();for(;e===32||e===9||e===13||e===10;)e=this.data[++this._pos]}expect(e){if(this.data.length-this._pos<e.length)throw new Error(`${H} unexpected end of input at position ${this._pos}`);for(let t=0;t<e.length;t++)if(this.data[this._pos++]!==e[t])throw new Error(`${H} unexpected token at position ${this._pos}, expected to find '${String.fromCharCode(...e)}'`)}parseNumber(){let e=this._pos,t=!1,n=!1,o=a=>{for(;!this.done();){let c=this.ch();if(a.includes(c))this._pos++;else break}};if(this.ch()===45&&(t=!0,this._pos++),this.ch()===48)if(this._pos++,this.ch()===46)this._pos++,n=!0;else return new B(p.uint,0,this._pos-e);if(o([48,49,50,51,52,53,54,55,56,57]),t&&this._pos===e+1)throw new Error(`${H} unexpected token at position ${this._pos}`);if(!this.done()&&this.ch()===46){if(n)throw new Error(`${H} unexpected token at position ${this._pos}`);n=!0,this._pos++,o([48,49,50,51,52,53,54,55,56,57])}!this.done()&&(this.ch()===101||this.ch()===69)&&(n=!0,this._pos++,!this.done()&&(this.ch()===43||this.ch()===45)&&this._pos++,o([48,49,50,51,52,53,54,55,56,57]));let i=String.fromCharCode.apply(null,this.data.subarray(e,this._pos)),s=parseFloat(i);return n?new B(p.float,s,this._pos-e):this.options.allowBigInt!==!0||Number.isSafeInteger(s)?new B(s>=0?p.uint:p.negint,s,this._pos-e):new B(s>=0?p.uint:p.negint,BigInt(i),this._pos-e)}parseString(){if(this.ch()!==34)throw new Error(`${H} unexpected character at position ${this._pos}; this shouldn't happen`);this._pos++;for(let i=this._pos,s=0;i<this.data.length&&s<65536;i++,s++){let a=this.data[i];if(a===92||a<32||a>=128)break;if(a===34){let c=String.fromCharCode.apply(null,this.data.subarray(this._pos,i));return this._pos=i+1,new B(p.string,c,s)}}let e=this._pos,t=[],n=()=>{if(this._pos+4>=this.data.length)throw new Error(`${H} unexpected end of unicode escape sequence at position ${this._pos}`);let i=0;for(let s=0;s<4;s++){let a=this.ch();if(a>=48&&a<=57)a-=48;else if(a>=97&&a<=102)a=a-97+10;else if(a>=65&&a<=70)a=a-65+10;else throw new Error(`${H} unexpected unicode escape character at position ${this._pos}`);i=i*16+a,this._pos++}return i},o=()=>{let i=this.ch(),s=null,a=i>239?4:i>223?3:i>191?2:1;if(this._pos+a>this.data.length)throw new Error(`${H} unexpected unicode sequence at position ${this._pos}`);let c,u,l,f;switch(a){case 1:i<128&&(s=i);break;case 2:c=this.data[this._pos+1],(c&192)===128&&(f=(i&31)<<6|c&63,f>127&&(s=f));break;case 3:c=this.data[this._pos+1],u=this.data[this._pos+2],(c&192)===128&&(u&192)===128&&(f=(i&15)<<12|(c&63)<<6|u&63,f>2047&&(f<55296||f>57343)&&(s=f));break;case 4:c=this.data[this._pos+1],u=this.data[this._pos+2],l=this.data[this._pos+3],(c&192)===128&&(u&192)===128&&(l&192)===128&&(f=(i&15)<<18|(c&63)<<12|(u&63)<<6|l&63,f>65535&&f<1114112&&(s=f))}s===null?(s=65533,a=1):s>65535&&(s-=65536,t.push(s>>>10&1023|55296),s=56320|s&1023),t.push(s),this._pos+=a};for(;!this.done();){let i=this.ch(),s;switch(i){case 92:if(this._pos++,this.done())throw new Error(`${H} unexpected string termination at position ${this._pos}`);switch(s=this.ch(),this._pos++,s){case 34:case 39:case 92:case 47:t.push(s);break;case 98:t.push(8);break;case 116:t.push(9);break;case 110:t.push(10);break;case 102:t.push(12);break;case 114:t.push(13);break;case 117:t.push(n());break;default:throw new Error(`${H} unexpected string escape character at position ${this._pos}`)}break;case 34:return this._pos++,new B(p.string,eA(t),this._pos-e);default:if(i<32)throw new Error(`${H} invalid control character at position ${this._pos}`);i<128?(t.push(i),this._pos++):o()}}throw new Error(`${H} unexpected end of string at position ${this._pos}`)}parseValue(){switch(this.ch()){case 123:return this.modeStack.push("obj-start"),this._pos++,new B(p.map,1/0,1);case 91:return this.modeStack.push("array-start"),this._pos++,new B(p.array,1/0,1);case 34:return this.parseString();case 110:return this.expect([110,117,108,108]),new B(p.null,null,4);case 102:return this.expect([102,97,108,115,101]),new B(p.false,!1,5);case 116:return this.expect([116,114,117,101]),new B(p.true,!0,4);case 45:case 48:case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:return this.parseNumber();default:throw new Error(`${H} unexpected character at position ${this._pos}`)}}next(){switch(this.skipWhitespace(),this.currentMode()){case"value":return this.modeStack.pop(),this.parseValue();case"array-value":{if(this.modeStack.pop(),this.ch()===93)return this._pos++,this.skipWhitespace(),new B(p.break,void 0,1);if(this.ch()!==44)throw new Error(`${H} unexpected character at position ${this._pos}, was expecting array delimiter but found '${String.fromCharCode(this.ch())}'`);return this._pos++,this.modeStack.push("array-value"),this.skipWhitespace(),this.parseValue()}case"array-start":return this.modeStack.pop(),this.ch()===93?(this._pos++,this.skipWhitespace(),new B(p.break,void 0,1)):(this.modeStack.push("array-value"),this.skipWhitespace(),this.parseValue());case"obj-key":if(this.ch()===125)return this.modeStack.pop(),this._pos++,this.skipWhitespace(),new B(p.break,void 0,1);if(this.ch()!==44)throw new Error(`${H} unexpected character at position ${this._pos}, was expecting object delimiter but found '${String.fromCharCode(this.ch())}'`);this._pos++,this.skipWhitespace();case"obj-start":{if(this.modeStack.pop(),this.ch()===125)return this._pos++,this.skipWhitespace(),new B(p.break,void 0,1);let e=this.parseString();if(this.skipWhitespace(),this.ch()!==58)throw new Error(`${H} unexpected character at position ${this._pos}, was expecting key/value delimiter ':' but found '${String.fromCharCode(this.ch())}'`);return this._pos++,this.modeStack.push("obj-value"),e}case"obj-value":return this.modeStack.pop(),this.modeStack.push("obj-key"),this.skipWhitespace(),this.parseValue();default:throw new Error(`${H} unexpected parse state at position ${this._pos}; this shouldn't happen`)}}};function H0(r,e){return e=Object.assign({tokenizer:new Xs(r,e)},e),V0(r,e)}function ON(r){return r instanceof ArrayBuffer?new Uint8Array(r,0,r.byteLength):r}function MN(r){if(r.asCID!==r&&r["/"]!==r.bytes)return null;let e=Q.asCID(r);if(!e)return null;let t=e.toString();return[new B(p.map,1/0,1),new B(p.string,"/",1),new B(p.string,t,t.length),new B(p.break,void 0,1)]}function Ud(r){let e=yt.encode(r).slice(1);return[new B(p.map,1/0,1),new B(p.string,"/",1),new B(p.map,1/0,1),new B(p.string,"bytes",5),new B(p.string,e,e.length),new B(p.break,void 0,1),new B(p.break,void 0,1)]}function Wr(r){return Ud(new Uint8Array(r.buffer,r.byteOffset,r.byteLength))}function FN(r){return Ud(new Uint8Array(r))}function $N(){throw new Error("`undefined` is not supported by the IPLD Data Model and cannot be encoded")}function VN(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 KN={typeEncoders:{Object:MN,Buffer:Ud,Uint8Array:Ud,Int8Array:Wr,Uint16Array:Wr,Int16Array:Wr,Uint32Array:Wr,Int32Array:Wr,Float32Array:Wr,Float64Array:Wr,Uint8ClampedArray:Wr,BigInt64Array:Wr,BigUint64Array:Wr,DataView:Wr,ArrayBuffer:FN,undefined:$N,number:VN}},z0=class extends Xs{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(p.equals(e.type,p.map)){let t=this._next();if(p.equals(t.type,p.string)&&t.value==="/"){let n=this._next();if(p.equals(n.type,p.string)){let o=this._next();if(!p.equals(o.type,p.break))throw new Error("Invalid encoded CID form");return this.tokenBuffer.push(n),new B(p.tag,42,0)}if(p.equals(n.type,p.map)){let o=this._next();if(p.equals(o.type,p.string)&&o.value==="bytes"){let i=this._next();if(p.equals(i.type,p.string)){for(let a=0;a<2;a++){let c=this._next();if(!p.equals(c.type,p.break))throw new Error("Invalid encoded Bytes form")}let s=yt.decode(`m${i.value}`);return new B(p.bytes,s,i.value.length)}this.tokenBuffer.push(i)}this.tokenBuffer.push(o)}this.tokenBuffer.push(n)}this.tokenBuffer.push(t)}return e}},JA={allowIndefinite:!1,allowUndefined:!1,allowNaN:!1,allowInfinity:!1,allowBigInt:!0,strict:!0,useMaps:!1,rejectDuplicateMapKeys:!0,tags:{42:r=>Q.parse(r())}},qN="dag-json",j0=297,QA=r=>q0(r,KN),eS=r=>{let e=ON(r),t=Object.assign(JA,{tokenizer:new z0(e,JA)});return H0(e,t)},HN=r=>zN.decode(QA(r));var zN=new TextDecoder,jN=r=>eS(GN.encode(r)),GN=new TextEncoder;var Q0={};Me(Q0,{code:()=>J0,createLink:()=>lS,createNode:()=>uS,decode:()=>s3,encode:()=>i3,name:()=>o3,prepare:()=>X0,validate:()=>Z0});var WN=new TextDecoder;function W0(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 Od(r,e){let t;[t,e]=W0(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 tS(r,e){let t;return[t,e]=W0(r,e),[t&7,t>>3,e]}function YN(r){let e={},t=r.length,n=0;for(;n<t;){let o,i;if([o,i,n]=tS(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]=Od(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]=Od(r,n),e.Name=WN.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]=W0(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 rS(r){let e=r.length,t=0,n,o=!1,i;for(;t<e;){let a,c;if([a,c,t]=tS(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]=Od(r,t),n&&(o=!0)}else if(c===2){if(o)throw new Error("protobuf: (PBNode) duplicate Links section");n||(n=[]);let u;[u,t]=Od(r,t),n.push(YN(u))}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 oS=new TextEncoder,nS=2**32,XN=2**31;function ZN(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=nu(e,t,r.Tsize)-1,e[t]=24}if(typeof r.Name=="string"){let n=oS.encode(r.Name);t-=n.length,e.set(n,t),t=nu(e,t,n.length)-1,e[t]=18}return r.Hash&&(t-=r.Hash.length,e.set(r.Hash,t),t=nu(e,t,r.Hash.length)-1,e[t]=10),e.length-t}function iS(r){let e=QN(r),t=new Uint8Array(e),n=e;if(r.Data&&(n-=r.Data.length,t.set(r.Data,n),n=nu(t,n,r.Data.length)-1,t[n]=10),r.Links)for(let o=r.Links.length-1;o>=0;o--){let i=ZN(r.Links[o],t.subarray(0,n));n-=i,n=nu(t,n,i)-1,t[n]=18}return t}function JN(r){let e=0;if(r.Hash){let t=r.Hash.length;e+=1+t+Zs(t)}if(typeof r.Name=="string"){let t=oS.encode(r.Name).length;e+=1+t+Zs(t)}return typeof r.Tsize=="number"&&(e+=1+Zs(r.Tsize)),e}function QN(r){let e=0;if(r.Data){let t=r.Data.length;e+=1+t+Zs(t)}if(r.Links)for(let t of r.Links){let n=JN(t);e+=1+n+Zs(n)}return e}function nu(r,e,t){e-=Zs(t);let n=e;for(;t>=XN;)r[e++]=t&127|128,t/=128;for(;t>=128;)r[e++]=t&127|128,t>>>=7;return r[e]=t,n}function Zs(r){return r%2===0&&r++,Math.floor((e3(r)+6)/7)}function e3(r){let e=0;return r>=nS&&(r=Math.floor(r/nS),e=32),r>=65536&&(r>>>=16,e+=16),r>=256&&(r>>>=8,e+=8),e+t3[r]}var t3=[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 r3=["Data","Links"],n3=["Hash","Name","Tsize"],Y0=new TextEncoder;function aS(r,e){if(r===e)return 0;let t=r.Name?Y0.encode(r.Name):[],n=e.Name?Y0.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 sS(r,e){return!Object.keys(r).some(t=>!e.includes(t))}function cS(r){if(typeof r.asCID=="object"){let t=Q.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=Q.asCID(r.Hash);try{t||(typeof r.Hash=="string"?t=Q.parse(r.Hash):r.Hash instanceof Uint8Array&&(t=Q.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 X0(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=Y0.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(cS),e.Links.sort(aS);else throw new TypeError("Invalid DAG-PB form");else e.Links=[];return e}function Z0(r){if(!r||typeof r!="object"||Array.isArray(r)||r instanceof Uint8Array||r["/"]&&r["/"]===r.bytes)throw new TypeError("Invalid DAG-PB form");if(!sS(r,r3))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(!sS(t,n3))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&&aS(t,r.Links[e-1])===-1)throw new TypeError("Invalid DAG-PB form (links must be sorted by Name bytes)")}}function uS(r,e=[]){return X0({Data:r,Links:e})}function lS(r,e,t){return cS({Hash:t,Name:r,Tsize:e})}function fS(r){return r instanceof ArrayBuffer?new Uint8Array(r,0,r.byteLength):r}var o3="dag-pb",J0=112;function i3(r){Z0(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),iS(e)}function s3(r){let e=fS(r),t=rS(e),n={};return t.Data&&(n.Data=t.Data),t.Links&&(n.Links=t.Links.map(o=>{let i={};try{i.Hash=Q.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 Js(r){return r?.then!=null}function dS(r=[],e){let t={[J0]:Q0,[Vo]:ji,[C0]:B0,[j0]:G0,[Cm]:nl};return r.forEach(n=>{t[n.code]=n}),async n=>{let o=t[n];if(o==null&&e!=null){let i=e(n);Js(i)?o=await i:o=i,t[o.code]=o}if(o!=null)return o;throw new Mc(`Could not load codec for ${n}`)}}function hS(r=[],e){let t={[Ir.code]:Ir,[ol.code]:ol,[Ve.code]:Ve};return r.forEach(n=>{t[n.code]=n}),async n=>{let o=t[n];if(o==null&&e!=null){let i=e(n);Js(i)?o=await i:o=i,t[o.code]=o}if(o!=null)return o;throw new Oc(`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 wr=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 Un=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 Md=0,Qs=class extends Error{static name="IdentityHashDigestTooLongError";name="IdentityHashDigestTooLongError"},Fd=class extends Un{child;maxDigestLength;constructor(e,t){super(),this.child=e,this.maxDigestLength=t?.maxDigestLength}put(e,t,n){if(e.multihash.code===Md){if(this.maxDigestLength!=null&&e.multihash.digest.byteLength>this.maxDigestLength)throw new Qs(`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===Md){if(this.maxDigestLength!=null&&e.multihash.digest.byteLength>this.maxDigestLength)throw new Qs(`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 wr;yield*this.child.get(e,t)}has(e,t){if(e.multihash.code===Md){if(this.maxDigestLength!=null&&e.multihash.digest.byteLength>this.maxDigestLength)throw new Qs(`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===Md){if(this.maxDigestLength!=null&&e.multihash.digest.byteLength>this.maxDigestLength)throw new Qs(`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 a3(r){return r[Symbol.asyncIterator]!=null}function c3(r,e){let t=0;if(a3(r))return(async function*(){for await(let c of r)await e(c,t++)&&(yield c)})();let n=Ns(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 Yr=c3;function u3(r){return r[Symbol.asyncIterator]!=null}function pS(r){return r?.then!=null}function l3(r,e){let t=0;if(u3(r))return(async function*(){for await(let c of r){let u=e(c,t++);pS(u)&&await u,yield c}})();let n=Ns(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 u=e(c,t++);pS(u)&&await u,yield c}})();let a=e;return(function*(){yield o;for(let c of n)a(c,t++),yield c})()}var ew=l3;var f3=128,ea=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 Fd(e.blockstore,{maxDigestLength:t.maxIdentityHashDigestLength??f3}),this.getHasher=e.getHasher}async put(e,t,n={}){return await this.child.has(e,n)?(n.onProgress?.(new $("blocks:put:duplicate",e)),e):(n.onProgress?.(new $("blocks:put:providers:notify",e)),await Promise.all(this.blockBrokers.map(async o=>o.announce?.(e,n))),n.onProgress?.(new $("blocks:put:blockstore:put",e)),this.child.put(e,t,n))}async*putMany(e,t={}){let n=Yr(e,async({cid:i})=>{let s=await this.child.has(i,t);return s&&t.onProgress?.(new $("blocks:put-many:duplicate",i)),!s}),o=ew(n,async({cid:i})=>{t.onProgress?.(new $("blocks:put-many:providers:notify",i)),await Promise.all(this.blockBrokers.map(async s=>s.announce?.(i,t)))});t.onProgress?.(new $("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 Rc("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 $("blocks:get:providers:get",e));let s=await mS(e,this.blockBrokers,i,{...t,log:this.log});t.onProgress?.(new $("blocks:get:blockstore:put",e)),await this.child.put(e,s,t),t.onProgress?.(new $("blocks:get:providers:notify",e)),await Promise.all(this.blockBrokers.map(async a=>a.announce?.(e,t))),yield s;return}t.onProgress?.(new $("blocks:get:blockstore:get",e)),yield*this.child.get(e,t)}async*getMany(e,t={}){t.onProgress?.(new $("blocks:get-many:blockstore:get-many")),yield*this.child.getMany(ew(e,async n=>{let o=await this.child.has(n,t),i=t.offline===!0;if(!o){if(i)throw new Rc("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 $("blocks:get-many:providers:get",n));let a=await mS(n,this.blockBrokers,s,{...t,log:this.log});t.onProgress?.(new $("blocks:get-many:blockstore:put",n)),await this.child.put(n,a,t),t.onProgress?.(new $("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 $("blocks:delete:blockstore:delete",e)),await this.child.delete(e,t)}async*deleteMany(e,t={}){t.onProgress?.(new $("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 $("blocks:get-all:blockstore:get-many")),yield*this.child.getAll(e)}};async function mS(r,e,t,n){let o=h3(r,t),i=new AbortController,s=Ie([i.signal,n.signal]);i.signal;let a=[];for(let c of e)d3(c)&&a.push(c);if(a.length===0)throw new xi(`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 u=!1,l=await c.retrieve(r,{...n,signal:s,validateFn:async f=>{await o(f),n.signal?.throwIfAborted(),u=!0}});return u||(await o(l),n.signal?.throwIfAborted()),l}catch(u){throw n.log.error("could not retrieve verified block for %c from %s - %e",r,c.name,u),u}}))}catch(c){throw new Kf(c.errors,`Failed to load block for ${r}`)}finally{i.abort(),s.clear()}}function d3(r){return typeof r.retrieve=="function"}var h3=(r,e)=>{if(e==null)throw new T(`No hasher configured for multihash code 0x${r.multihash.code.toString(16)}, please configure one. You can look up which hash this is at https://github.com/multiformats/multicodec/blob/master/table.csv`);return async t=>{let n,o=e.digest(t,{truncate:r.multihash.digest.byteLength});if(Js(o)?n=await o:n=o,!ce(n.digest,r.multihash.digest))throw new Wn("Hash of downloaded block did not match multihash from passed CID")}};var $d=class extends ea{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=Ie([this.closeController.signal,n.signal]);try{return await super.put(e,t,{...n,signal:o})}finally{o.clear()}}async*putMany(e,t={}){let n=Ie([this.closeController.signal,t.signal]);try{yield*super.putMany(e,{...t,signal:n})}finally{n.clear()}}async*get(e,t={}){let n=Ie([this.closeController.signal,t.signal]);try{yield*super.get(e,{...t,signal:n})}finally{n.clear()}}async*getMany(e,t={}){let n=Ie([this.closeController.signal,t.signal]);try{yield*super.getMany(e,{...t,signal:n})}finally{n.clear()}}async delete(e,t={}){let n=Ie([this.closeController.signal,t.signal]);try{await super.delete(e,{...t,signal:n})}finally{n.clear()}}async*deleteMany(e,t={}){let n=Ie([this.closeController.signal,t.signal]);try{yield*super.deleteMany(e,{...t,signal:n})}finally{n.clear()}}async has(e,t={}){let n=Ie([this.closeController.signal,t.signal]);try{return await super.has(e,{...t,signal:n})}finally{n.clear()}}async*getAll(e={}){let t=Ie([this.closeController.signal,e.signal]);try{yield*super.getAll({...e,signal:t})}finally{t.clear()}}};var Vd=class extends ea{started;constructor(e,t={}){super(e,t),this.started=!1}isStarted(){return this.started}async start(){await rn(this.child,...this.blockBrokers),this.started=!0}async stop(){await nn(this.child,...this.blockBrokers),this.started=!1}unwrap(){return this.child}createSession(e,t){if(this.blockBrokers.length===0)throw new xi("No block brokers configured");let n=this.blockBrokers.map(o=>o.createSession?.(t)).filter(o=>o!=null);if(n.length===0)throw new xi(`No configured block brokers support sessions - tried ${this.blockBrokers.map(o=>o.name).join(", ")}`);return new $d({blockstore:this.child,blockBrokers:n,getHasher:this.getHasher,logger:this.logger},{root:e})}};var iu=class extends ze{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=uo(this.maxProviders),this.initialProviders=[...t.providers??[]]}async retrieve(e,t={}){let n=yt.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=ge(),s={promise:i.promise,observers:1,queryFilter:uo(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,u=new $r({concurrency:this.maxProviders});u.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)}),u.addEventListener("success",d=>{c=!0,i.resolve(d.detail.result)}),u.addEventListener("idle",()=>{if(c){this.log.trace("session idle, found block");return}if(t.signal?.aborted===!0){this.log.trace("session idle, signal aborted");return}Promise.resolve().then(async()=>{this.log("no session peers had block for for %c, finding new providers",e);for(let d=0;d<this.minProviders&&this.providers.length!==0;d++){let h=this.providers[Math.floor(Math.random()*this.providers.length)];this.evict(h)}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(d=>{this.log.error("could not find new providers for %c - %e",e,d),i.reject(d)})});let l=d=>{let h=this.toFilterKey(d.detail);s.queryFilter.has(h)||(s.queryFilter.add(h),this.emitFoundProviderProgressEvent(e,d.detail,t),u.add(async()=>this.queryProvider(e,d.detail,t),{provider:d.detail}).catch(m=>{t.signal?.aborted!==!0&&this.log.error("error retrieving session block for %c - %e",e,m)}))};if(this.addEventListener("provider",l),a)try{await kt(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&&i.reject(d),d}Promise.all([...this.providers].filter(d=>{let h=this.toFilterKey(d),m=s.queryFilter.has(h);return m||s.queryFilter.add(this.toFilterKey(d)),!m}).map(async d=>u.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=()=>{i.reject(new Rt(t.signal?.reason??"Session aborted")),u.abort()};t.signal?.addEventListener("abort",f);try{return await i.promise}finally{this.removeEventListener("provider",l),t.signal?.removeEventListener("abort",f),u.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=ge(),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 u=s.initialProviders.pop();if(u==null)continue;let l=await s.convertToProvider(u,"manual",n);l!=null&&(yield l)}},c=async function*(){yield*a(),yield*s.findNewProviders(e,n)};for await(let u of c()){if(this.providers.length===this.maxProviders||n.signal?.aborted===!0)break;if(!this.hasProvider(u)&&(this.log("found %d providers, %d in session",i,this.providers.length),this.providers.push(u),this.safeDispatchEvent("provider",{detail:u}),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 Uc(`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}};var Kd=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=hS(e.hashers,e.loadHasher),this.getCodec=dS(e.codecs,e.loadCodec),this.dns=e.dns??vf(),this.metrics=e.metrics,this.libp2p=e.libp2p,this.events=new ze;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 zf(t,{routers:(e.routers??[]).flatMap(o=>{typeof o=="function"&&(o=o(t));let i=[o],s=p3(o);s!=null&&i.push(s);let a=m3(o);return a!=null&&i.push(a),i}),providerLookupConcurrency:e.providerLookupConcurrency}),t.blockBrokers=e.blockBrokers.map(o=>o(t));let n=new Vd(t,e);this.pins=new Hf(e.datastore,n,this.getCodec),this.blockstore=new cd(n,this.pins,this.routing,{holdGcLock:e.holdGcLock??!0}),this.datastore=e.datastore}async start(){await $v(this.datastore),await rn(this.blockstore,this.datastore,this.routing,this.libp2p),this.events.dispatchEvent(new CustomEvent("start",{detail:this}))}async stop(){await nn(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 yc(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 $("helia:gc:deleted",i))}catch(s){n.log.error("error during gc - %e",s),e.onProgress?.(new $("helia:gc:error",s))}})()))}finally{t()}this.log("gc finished")}};function p3(r){return r?.[Uo]}function m3(r){return r?.[Mo]}var g3=[6,53,56,54,55];function gS(r){return bS("sni",r)?.value}function yS(r){let e=bS("tcp",r)?.value;return e==null?"":`:${e}`}function bS(r,e){return e.find(t=>t.name===r)}function wS(r){return r.some(({code:e})=>e===448)}function Xr(r,e){let t=xS[r.name];if(t==null)throw new Error(`Can't interpret protocol ${r.name}`);let n=t(r,e);return r.code===41?`[${n}]`:n}var xS={ip4:(r,e)=>r.value,ip6:(r,e)=>e.length===0?r.value:`[${r.value}]`,tcp:(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");return`tcp://${Xr(t,e)}:${r.value}`},udp:(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");return`udp://${Xr(t,e)}:${r.value}`},dnsaddr:(r,e)=>r.value,dns4:(r,e)=>r.value,dns6:(r,e)=>r.value,dns:(r,e)=>r.value,ipfs:(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");return`${Xr(t,e)}`},p2p:(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");return`${Xr(t,e)}`},http:(r,e)=>{let t=wS(e),n=gS(e),o=yS(e);if(t&&n!=null)return`https://${n}${o}`;let i=t?"https://":"http://",s=e.pop();if(s==null)throw new Error("Unexpected end of multiaddr");let a=Xr(s,e);return a=a?.replace("tcp://",""),`${i}${a}`},"http-path":(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");let n=Xr(t,e),o=decodeURIComponent(r.value??"");return`${n}${o}`},tls:(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");return Xr(t,e)},sni:(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");return Xr(t,e)},https:(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");let n=Xr(t,e);return n=n?.replace("tcp://",""),`https://${n}`},ws:(r,e)=>{let t=wS(e),n=gS(e),o=yS(e);if(t&&n!=null)return`wss://${n}${o}`;let i=t?"wss://":"ws://",s=e.pop();if(s==null)throw new Error("Unexpected end of multiaddr");let a=Xr(s,e);return a=a?.replace("tcp://",""),`${i}${a}`},wss:(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");let n=Xr(t,e);return n=n?.replace("tcp://",""),`wss://${n}`}};function qd(r,e){let n=fe(r).getComponents(),o=n.pop();if(o==null)throw new Error("Unexpected end of multiaddr");let i=xS[o.name];if(i==null)throw new Error(`No interpreter found for ${o.name}`);let s=i(o,n)??"";return e?.assumeHttp!==!1&&g3.includes(o.code)&&(s=s.replace(/^.*:\/\//,""),o.value==="443"?s=`https://${s}`:s=`http://${s}`),(s.startsWith("http://")||s.startsWith("https://")||s.startsWith("ws://")||s.startsWith("wss://"))&&(s=new URL(s).toString(),s.endsWith("/")&&(s=s.substring(0,s.length-1))),s}var ES="[a-fA-F\\d:]",_o=r=>r&&r.includeBoundaries?`(?:(?<=\\s|^)(?=${ES})|(?<=${ES})(?=\\s|$))`:"",Zr="(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)(?:\\.(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)){3}",Ke="[a-fA-F\\d]{1,4}",Hd=`
|
|
14
14
|
(?:
|
|
15
15
|
(?:${Ke}:){7}(?:${Ke}|:)| // 1:2:3:4:5:6:7:: 1:2:3:4:5:6:7:8
|
|
16
16
|
(?:${Ke}:){6}(?:${Zr}|:${Ke}|:)| // 1:2:3:4:5:6:: 1:2:3:4:5:6::8 1:2:3:4:5:6::8 1:2:3:4:5:6::1.2.3.4
|