helia 6.1.2-eb1908b3 → 6.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 CHANGED
@@ -10,7 +10,7 @@ ${e}`)}`:n!=null?`${n.split(`
10
10
  ${e}`)}`:t!=null?`${t}`:`${r.toString()}`}function TO(r){return r instanceof AggregateError||r?.name==="AggregateError"&&Array.isArray(r.errors)}function ox(r,e=""){if(TO(r)){let t=rx(r,e);return r.errors.length>0?(e=`${e} `,t+=`
11
11
  ${e}${r.errors.map(n=>`${ox(n,`${e}`)}`).join(`
12
12
  ${e}`)}`):t+=`
13
- ${e}[Error list was empty]`,t.trim()}return rx(r,e)}Tr.formatters.e=r=>r==null?"undefined":ox(r);function _O(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 Fc(r){return{forComponent(e){return mn(e,r)}}}function mn(r,e){let t=_O(`${r}:trace`);return Tr.enabled(`${r}:trace`)&&Tr.names.map(n=>n.toString()).find(n=>n.includes(":trace"))!=null&&(t=Tr(`${r}:trace`,e)),Object.assign(Tr(r,e),{error:Tr(`${r}:error`,e),trace:t,newScope:n=>mn(`${r}:${n}`,e)})}function nx(r){if(r!=null&&(r=r.trim(),r.length!==0))return r}var ix=Symbol.for("sindresorhus/unlimited-timeout#brand");function sx(r,e,...t){if(typeof r!="function")throw new TypeError("Expected callback to be a function");e??=0,e=Number(e);let n=!1,o={[ix]:!0,id:void 0,cleared:!1,ref(){return n=!1,o.id?.ref?.(),o},unref(){return n=!0,o.id?.unref?.(),o}};if(e===Number.POSITIVE_INFINITY||e>Number.MAX_SAFE_INTEGER)return o;(!Number.isFinite(e)||e<0)&&(e=0);let i=performance.now()+e,s=a=>{o.cleared||(a<=2147483647?(o.id=globalThis.setTimeout(()=>{o.cleared||r(...t)},a),n&&o.id?.unref?.()):(o.id=globalThis.setTimeout(()=>{let c=performance.now(),l=Math.max(0,i-c);s(l)},2147483647),n&&o.id?.unref?.()))};return s(e),o}function ax(r){!r||typeof r!="object"||!r[ix]||(r.cleared=!0,r.id!==void 0&&(globalThis.clearTimeout(r.id),r.id=void 0))}var IO=new WeakMap;function kO({clearTimeout:r,setTimeout:e}={}){return(t,{value:n,signal:o}={})=>{if(o?.aborted)return Promise.reject(o.reason);let i,s,a,c=r??clearTimeout,l=()=>{c(i),a(o.reason)},u=()=>{o&&o.removeEventListener("abort",l)},d=new Promise((f,h)=>{s=()=>{u(),f(n)},a=h,i=(e??setTimeout)(s,t)});return o&&o.addEventListener("abort",l,{once:!0}),IO.set(d,()=>{c(i),i=null,s()}),d}}var CO=kO({setTimeout:sx,clearTimeout:ax}),cx=CO;var Qt=class extends Yt{has(e){return this.find(e)!=null}find(e){return this.queue.find(t=>e.equals(t.options.peerId))}};var L1=class extends Yt{constructor(e={}){super({...e,sort:(t,n)=>t.options.priority>n.options.priority?-1:t.options.priority<n.options.priority?1:0})}};var $c=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 H6}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 c1("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)}},H6=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}};function Vc(r,e,t){let n,o,i=!1;function s(){let l={signal:o.signal},u;t?.timeout!=null&&(u=Ee([o.signal,AbortSignal.timeout(t.timeout)]),l.signal=u),i=!0,Promise.resolve().then(async()=>{await r(l)}).catch(()=>{}).finally(()=>{u!=null&&(u.aborted?u.clear():u.addEventListener("abort",()=>{u.clear()},{once:!0})),i=!1,!o.signal.aborted&&(n=setTimeout(s,e))})}let a=Qo(s,t?.debounce??100),c=!1;return{setInterval:l=>{e!==l&&(e=l,n!=null&&(clearTimeout(n),n=setTimeout(s,e)))},setTimeout:l=>{t??={},t.timeout=l},run:()=>{i||(clearTimeout(n),a())},start:()=>{c||(c=!0,o=new AbortController,o.signal,t?.runImmediately===!0?queueMicrotask(()=>{s()}):n=setTimeout(s,e))},stop:()=>{clearTimeout(n),o?.abort(),c=!1}}}var q6=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 St(r){let{name:e,metrics:t}=r,n;return t!=null?n=new q6({name:e,metrics:t}):n=new Map,n}var RO=["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 z6(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=PO(r);return t||"Object"}function PO(r){let e=Object.prototype.toString.call(r).slice(8,-1);if(RO.includes(e))return e}var I=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}};I.uint=new I(0,"uint",!0);I.negint=new I(1,"negint",!0);I.bytes=new I(2,"bytes",!0);I.string=new I(3,"string",!0);I.array=new I(4,"array",!1);I.map=new I(5,"map",!1);I.tag=new I(6,"tag",!1);I.float=new I(7,"float",!0);I.false=new I(7,"false",!0);I.true=new I(7,"true",!0);I.null=new I(7,"null",!0);I.undefined=new I(7,"undefined",!0);I.break=new I(7,"break",!0);var te=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 Xu=globalThis.process&&!globalThis.process.browser&&globalThis.Buffer&&typeof globalThis.Buffer.isBuffer=="function",LO=new TextEncoder;function N1(r){return Xu&&globalThis.Buffer.isBuffer(r)}function Qu(r){return r instanceof Uint8Array?N1(r)?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):r:Uint8Array.from(r)}var NO=24,DO=200,D1=Xu?r=>r.length>=NO?globalThis.Buffer.from(r):lx(r):r=>r.length>=DO?LO.encode(r):lx(r),xo=r=>Uint8Array.from(r),ux=Xu?(r,e,t)=>N1(r)?new Uint8Array(r.subarray(e,t)):r.slice(e,t):(r,e,t)=>r.slice(e,t),dx=Xu?(r,e)=>(r=r.map(t=>t instanceof Uint8Array?t:globalThis.Buffer.from(t)),Qu(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},fx=Xu?r=>globalThis.Buffer.allocUnsafe(r):r=>new Uint8Array(r);function O1(r,e){if(N1(r)&&N1(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 lx(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 OO=256,Zu=class{constructor(e=OO){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=fx(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=ux(n,0,this.cursor)}else t=dx(this.chunks,this.cursor);return e&&this.reset(),t}},B1=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 le="CBOR decode error:",M1="CBOR encode error:",Ju=[];Ju[23]=1;Ju[24]=2;Ju[25]=3;Ju[26]=5;Ju[27]=9;function ri(r,e,t){if(r.length-e<t)throw new Error(`${le} not enough data for type`)}var Bt=[24,256,65536,4294967296,BigInt("18446744073709551616")];function $r(r,e,t){ri(r,e,1);let n=r[e];if(t.strict===!0&&n<Bt[0])throw new Error(`${le} integer encoded in more bytes than necessary (strict decode)`);return n}function Vr(r,e,t){ri(r,e,2);let n=r[e]<<8|r[e+1];if(t.strict===!0&&n<Bt[1])throw new Error(`${le} integer encoded in more bytes than necessary (strict decode)`);return n}function Kr(r,e,t){ri(r,e,4);let n=r[e]*16777216+(r[e+1]<<16)+(r[e+2]<<8)+r[e+3];if(t.strict===!0&&n<Bt[2])throw new Error(`${le} integer encoded in more bytes than necessary (strict decode)`);return n}function Hr(r,e,t){ri(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<Bt[3])throw new Error(`${le} 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(`${le} integers outside of the safe integer range are not supported`)}function hx(r,e,t,n){return new te(I.uint,$r(r,e+1,n),2)}function px(r,e,t,n){return new te(I.uint,Vr(r,e+1,n),3)}function mx(r,e,t,n){return new te(I.uint,Kr(r,e+1,n),5)}function gx(r,e,t,n){return new te(I.uint,Hr(r,e+1,n),9)}function gn(r,e){return ot(r,0,e.value)}function ot(r,e,t){if(t<Bt[0]){let n=Number(t);r.push([e|n])}else if(t<Bt[1]){let n=Number(t);r.push([e|24,n])}else if(t<Bt[2]){let n=Number(t);r.push([e|25,n>>>8,n&255])}else if(t<Bt[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<Bt[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(`${le} encountered BigInt larger than allowable range`)}}gn.encodedSize=function(e){return ot.encodedSize(e.value)};ot.encodedSize=function(e){return e<Bt[0]?1:e<Bt[1]?2:e<Bt[2]?3:e<Bt[3]?5:9};gn.compareTokens=function(e,t){return e.value<t.value?-1:e.value>t.value?1:0};function yx(r,e,t,n){return new te(I.negint,-1-$r(r,e+1,n),2)}function wx(r,e,t,n){return new te(I.negint,-1-Vr(r,e+1,n),3)}function bx(r,e,t,n){return new te(I.negint,-1-Kr(r,e+1,n),5)}var W6=BigInt(-1),xx=BigInt(1);function Ex(r,e,t,n){let o=Hr(r,e+1,n);if(typeof o!="bigint"){let i=-1-o;if(i>=Number.MIN_SAFE_INTEGER)return new te(I.negint,i,9)}if(n.allowBigInt!==!0)throw new Error(`${le} integers outside of the safe integer range are not supported`);return new te(I.negint,W6-BigInt(o),9)}function U1(r,e){let t=e.value,n=typeof t=="bigint"?t*W6-xx:t*-1-1;ot(r,e.type.majorEncoded,n)}U1.encodedSize=function(e){let t=e.value,n=typeof t=="bigint"?t*W6-xx:t*-1-1;return n<Bt[0]?1:n<Bt[1]?2:n<Bt[2]?3:n<Bt[3]?5:9};U1.compareTokens=function(e,t){return e.value<t.value?1:e.value>t.value?-1:0};function ed(r,e,t,n){ri(r,e,t+n);let o=r.slice(e+t,e+t+n);return new te(I.bytes,o,t+n)}function vx(r,e,t,n){return ed(r,e,1,t)}function Sx(r,e,t,n){return ed(r,e,2,$r(r,e+1,n))}function Ax(r,e,t,n){return ed(r,e,3,Vr(r,e+1,n))}function Tx(r,e,t,n){return ed(r,e,5,Kr(r,e+1,n))}function _x(r,e,t,n){let o=Hr(r,e+1,n);if(typeof o=="bigint")throw new Error(`${le} 64-bit integer bytes lengths not supported`);return ed(r,e,9,o)}function F1(r){return r.encodedBytes===void 0&&(r.encodedBytes=I.equals(r.type,I.string)?D1(r.value):r.value),r.encodedBytes}function Kc(r,e){let t=F1(e);ot(r,e.type.majorEncoded,t.length),r.push(t)}Kc.encodedSize=function(e){let t=F1(e);return ot.encodedSize(t.length)+t.length};Kc.compareTokens=function(e,t){return MO(F1(e),F1(t))};function MO(r,e){return r.length<e.length?-1:r.length>e.length?1:O1(r,e)}var Ix=new TextDecoder,FO=32;function $O(r,e,t){if(t-e<FO){let o="";for(let i=e;i<t;i++){let s=r[i];if(s&128)return Ix.decode(r.subarray(e,t));o+=String.fromCharCode(s)}return o}return Ix.decode(r.subarray(e,t))}function td(r,e,t,n,o){let i=t+n;ri(r,e,i);let s=new te(I.string,$O(r,e+t,e+i),i);return o.retainStringBytes===!0&&(s.byteValue=r.slice(e+t,e+i)),s}function kx(r,e,t,n){return td(r,e,1,t,n)}function Cx(r,e,t,n){return td(r,e,2,$r(r,e+1,n),n)}function Rx(r,e,t,n){return td(r,e,3,Vr(r,e+1,n),n)}function Px(r,e,t,n){return td(r,e,5,Kr(r,e+1,n),n)}function Lx(r,e,t,n){let o=Hr(r,e+1,n);if(typeof o=="bigint")throw new Error(`${le} 64-bit integer string lengths not supported`);return td(r,e,9,o,n)}var Nx=Kc;function Hc(r,e,t,n){return new te(I.array,n,t)}function Dx(r,e,t,n){return Hc(r,e,1,t)}function Ox(r,e,t,n){return Hc(r,e,2,$r(r,e+1,n))}function Bx(r,e,t,n){return Hc(r,e,3,Vr(r,e+1,n))}function Mx(r,e,t,n){return Hc(r,e,5,Kr(r,e+1,n))}function Ux(r,e,t,n){let o=Hr(r,e+1,n);if(typeof o=="bigint")throw new Error(`${le} 64-bit integer array lengths not supported`);return Hc(r,e,9,o)}function Fx(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${le} indefinite length items not allowed`);return Hc(r,e,1,1/0)}function $1(r,e){ot(r,I.array.majorEncoded,e.value)}$1.compareTokens=gn.compareTokens;$1.encodedSize=function(e){return ot.encodedSize(e.value)};function qc(r,e,t,n){return new te(I.map,n,t)}function $x(r,e,t,n){return qc(r,e,1,t)}function Vx(r,e,t,n){return qc(r,e,2,$r(r,e+1,n))}function Kx(r,e,t,n){return qc(r,e,3,Vr(r,e+1,n))}function Hx(r,e,t,n){return qc(r,e,5,Kr(r,e+1,n))}function qx(r,e,t,n){let o=Hr(r,e+1,n);if(typeof o=="bigint")throw new Error(`${le} 64-bit integer map lengths not supported`);return qc(r,e,9,o)}function zx(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${le} indefinite length items not allowed`);return qc(r,e,1,1/0)}function V1(r,e){ot(r,I.map.majorEncoded,e.value)}V1.compareTokens=gn.compareTokens;V1.encodedSize=function(e){return ot.encodedSize(e.value)};function Wx(r,e,t,n){return new te(I.tag,t,1)}function Gx(r,e,t,n){return new te(I.tag,$r(r,e+1,n),2)}function jx(r,e,t,n){return new te(I.tag,Vr(r,e+1,n),3)}function Yx(r,e,t,n){return new te(I.tag,Kr(r,e+1,n),5)}function Xx(r,e,t,n){return new te(I.tag,Hr(r,e+1,n),9)}function K1(r,e){ot(r,I.tag.majorEncoded,e.value)}K1.compareTokens=gn.compareTokens;K1.encodedSize=function(e){return ot.encodedSize(e.value)};var G6=20,j6=21,Y6=22,X6=23;function Qx(r,e,t,n){if(n.allowUndefined===!1)throw new Error(`${le} undefined values are not supported`);return n.coerceUndefinedToNull===!0?new te(I.null,null,1):new te(I.undefined,void 0,1)}function Zx(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${le} indefinite length items not allowed`);return new te(I.break,void 0,1)}function Q6(r,e,t){if(t){if(t.allowNaN===!1&&Number.isNaN(r))throw new Error(`${le} NaN values are not supported`);if(t.allowInfinity===!1&&(r===1/0||r===-1/0))throw new Error(`${le} Infinity values are not supported`)}return new te(I.float,r,e)}function Jx(r,e,t,n){return Q6(Z6(r,e+1),3,n)}function eE(r,e,t,n){return Q6(J6(r,e+1),5,n)}function tE(r,e,t,n){return Q6(iE(r,e+1),9,n)}function rd(r,e,t){let n=e.value;if(n===!1)r.push([I.float.majorEncoded|G6]);else if(n===!0)r.push([I.float.majorEncoded|j6]);else if(n===null)r.push([I.float.majorEncoded|Y6]);else if(n===void 0)r.push([I.float.majorEncoded|X6]);else{let o,i=!1;(!t||t.float64!==!0)&&(nE(n),o=Z6(zn,1),n===o||Number.isNaN(n)?(zn[0]=249,r.push(zn.slice(0,3)),i=!0):(oE(n),o=J6(zn,1),n===o&&(zn[0]=250,r.push(zn.slice(0,5)),i=!0))),i||(zO(n),o=iE(zn,1),zn[0]=251,r.push(zn.slice(0,9)))}}rd.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){nE(n);let o=Z6(zn,1);if(n===o||Number.isNaN(n))return 3;if(oE(n),o=J6(zn,1),n===o)return 5}return 9};var rE=new ArrayBuffer(9),yn=new DataView(rE,1),zn=new Uint8Array(rE,0);function nE(r){if(r===1/0)yn.setUint16(0,31744,!1);else if(r===-1/0)yn.setUint16(0,64512,!1);else if(Number.isNaN(r))yn.setUint16(0,32256,!1);else{yn.setFloat32(0,r);let e=yn.getUint32(0),t=(e&2139095040)>>23,n=e&8388607;if(t===255)yn.setUint16(0,31744,!1);else if(t===0)yn.setUint16(0,(e&2147483648)>>16|n>>13,!1);else{let o=t-127;o<-24?yn.setUint16(0,0):o<-14?yn.setUint16(0,(e&2147483648)>>16|1<<24+o,!1):yn.setUint16(0,(e&2147483648)>>16|o+15<<10|n>>13,!1)}}}function Z6(r,e){if(r.length-e<2)throw new Error(`${le} 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 oE(r){yn.setFloat32(0,r,!1)}function J6(r,e){if(r.length-e<4)throw new Error(`${le} not enough data for float32`);let t=(r.byteOffset||0)+e;return new DataView(r.buffer,t,4).getFloat32(0,!1)}function zO(r){yn.setFloat64(0,r,!1)}function iE(r,e){if(r.length-e<8)throw new Error(`${le} not enough data for float64`);let t=(r.byteOffset||0)+e;return new DataView(r.buffer,t,8).getFloat64(0,!1)}rd.compareTokens=gn.compareTokens;function De(r,e,t){throw new Error(`${le} encountered invalid minor (${t}) for major ${r[e]>>>5}`)}function H1(r){return()=>{throw new Error(`${le} ${r}`)}}var G=[];for(let r=0;r<=23;r++)G[r]=De;G[24]=hx;G[25]=px;G[26]=mx;G[27]=gx;G[28]=De;G[29]=De;G[30]=De;G[31]=De;for(let r=32;r<=55;r++)G[r]=De;G[56]=yx;G[57]=wx;G[58]=bx;G[59]=Ex;G[60]=De;G[61]=De;G[62]=De;G[63]=De;for(let r=64;r<=87;r++)G[r]=vx;G[88]=Sx;G[89]=Ax;G[90]=Tx;G[91]=_x;G[92]=De;G[93]=De;G[94]=De;G[95]=H1("indefinite length bytes/strings are not supported");for(let r=96;r<=119;r++)G[r]=kx;G[120]=Cx;G[121]=Rx;G[122]=Px;G[123]=Lx;G[124]=De;G[125]=De;G[126]=De;G[127]=H1("indefinite length bytes/strings are not supported");for(let r=128;r<=151;r++)G[r]=Dx;G[152]=Ox;G[153]=Bx;G[154]=Mx;G[155]=Ux;G[156]=De;G[157]=De;G[158]=De;G[159]=Fx;for(let r=160;r<=183;r++)G[r]=$x;G[184]=Vx;G[185]=Kx;G[186]=Hx;G[187]=qx;G[188]=De;G[189]=De;G[190]=De;G[191]=zx;for(let r=192;r<=215;r++)G[r]=Wx;G[216]=Gx;G[217]=jx;G[218]=Yx;G[219]=Xx;G[220]=De;G[221]=De;G[222]=De;G[223]=De;for(let r=224;r<=243;r++)G[r]=H1("simple values are not supported");G[244]=De;G[245]=De;G[246]=De;G[247]=Qx;G[248]=H1("simple values are not supported");G[249]=Jx;G[250]=eE;G[251]=tE;G[252]=De;G[253]=De;G[254]=De;G[255]=Zx;var Wn=[];for(let r=0;r<24;r++)Wn[r]=new te(I.uint,r,1);for(let r=-1;r>=-24;r--)Wn[31-r]=new te(I.negint,r,1);Wn[64]=new te(I.bytes,new Uint8Array(0),1);Wn[96]=new te(I.string,"",1);Wn[128]=new te(I.array,0,1);Wn[160]=new te(I.map,0,1);Wn[244]=new te(I.false,!1,1);Wn[245]=new te(I.true,!0,1);Wn[246]=new te(I.null,null,1);function ey(r){switch(r.type){case I.false:return xo([244]);case I.true:return xo([245]);case I.null:return xo([246]);case I.bytes:return r.value.length?void 0:xo([64]);case I.string:return r.value===""?xo([96]):void 0;case I.array:return r.value===0?xo([128]):void 0;case I.map:return r.value===0?xo([160]):void 0;case I.uint:return r.value<24?xo([Number(r.value)]):void 0;case I.negint:if(r.value>=-24)return xo([31-Number(r.value)])}}var GO={float64:!1,mapSorter:XO,quickEncodeToken:ey},uE=Object.freeze({float64:!0,mapSorter:QO,quickEncodeToken:ey});function jO(){let r=[];return r[I.uint.major]=gn,r[I.negint.major]=U1,r[I.bytes.major]=Kc,r[I.string.major]=Nx,r[I.array.major]=$1,r[I.map.major]=V1,r[I.tag.major]=K1,r[I.float.major]=rd,r}var Wc=jO(),q1=new Zu,od=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(`${M1} object contains circular references`);return new r(t,e)}},Xi={null:new te(I.null,null),undefined:new te(I.undefined,void 0),true:new te(I.true,!0),false:new te(I.false,!1),emptyArray:new te(I.array,0),emptyMap:new te(I.map,0)},Eo={number(r,e,t,n){return!Number.isInteger(r)||!Number.isSafeInteger(r)?new te(I.float,r):r>=0?new te(I.uint,r):new te(I.negint,r)},bigint(r,e,t,n){return r>=BigInt(0)?new te(I.uint,r):new te(I.negint,r)},Uint8Array(r,e,t,n){return new te(I.bytes,r)},string(r,e,t,n){return new te(I.string,r)},boolean(r,e,t,n){return r?Xi.true:Xi.false},null(r,e,t,n){return Xi.null},undefined(r,e,t,n){return Xi.undefined},ArrayBuffer(r,e,t,n){return new te(I.bytes,new Uint8Array(r))},DataView(r,e,t,n){return new te(I.bytes,new Uint8Array(r.buffer,r.byteOffset,r.byteLength))},Array(r,e,t,n){if(!r.length)return t.addBreakTokens===!0?[Xi.emptyArray,new te(I.break)]:Xi.emptyArray;n=od.createCheck(n,r);let o=[],i=0;for(let s of r)o[i++]=zc(s,t,n);return t.addBreakTokens?[new te(I.array,r.length),o,new te(I.break)]:[new te(I.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=od.createCheck(n,r);let c=!o&&t.ignoreUndefinedProperties,l=0;for(let u of i){let d=o?r.get(u):r[u];c&&d===void 0||(a[l++]=[zc(u,t,n),zc(d,t,n)])}l<s&&(a.length=l)}return a?.length?(YO(a,t),t.addBreakTokens?[new te(I.map,a.length),a,new te(I.break)]:[new te(I.map,a.length),a]):t.addBreakTokens===!0?[Xi.emptyMap,new te(I.break)]:Xi.emptyMap},Tagged(r,e,t,n){return[new te(I.tag,r.tag),zc(r.value,t,n)]}};Eo.Map=Eo.Object;Eo.Buffer=Eo.Uint8Array;for(let r of"Uint8Clamped Uint16 Uint32 Int8 Int16 Int32 BigUint64 BigInt64 Float32 Float64".split(" "))Eo[`${r}Array`]=Eo.DataView;function zc(r,e={},t){let n=z6(r),o=e&&e.typeEncoders&&e.typeEncoders[n]||Eo[n];if(typeof o=="function"){let s=o(r,n,e,t);if(s!=null)return s}let i=Eo[n];if(!i)throw new Error(`${M1} unsupported type: ${n}`);return i(r,n,e,t)}function YO(r,e){e.mapSorter&&r.sort(e.mapSorter)}function XO(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=Wc[o].compareTokens(t,n);return i===0&&console.warn("WARNING: complex key types used, CBOR key sorting guarantees are gone"),i}function QO(r,e){if(r[0]instanceof te&&e[0]instanceof te){let t=r[0],n=e[0];return t._keyBytes||(t._keyBytes=sE(t.value)),n._keyBytes||(n._keyBytes=sE(n.value)),O1(t._keyBytes,n._keyBytes)}throw new Error("rfc8949MapSorter: complex key types are not supported yet")}function sE(r){return fE(r,Wc,uE)}function nd(r,e,t,n){if(Array.isArray(e))for(let o of e)nd(r,o,t,n);else t[e.type.major](r,e,n)}var aE=I.uint.majorEncoded,cE=I.negint.majorEncoded,ZO=I.bytes.majorEncoded,JO=I.string.majorEncoded,lE=I.array.majorEncoded,eB=I.float.majorEncoded|G6,tB=I.float.majorEncoded|j6,rB=I.float.majorEncoded|Y6,nB=I.float.majorEncoded|X6,oB=BigInt(-1),iB=BigInt(1);function sB(r){return r.addBreakTokens!==!0}function dE(r,e,t,n){let o=z6(e),i=t.typeEncoders&&t.typeEncoders[o];if(i){let s=i(e,o,t,n);if(s!=null){nd(r,s,Wc,t);return}}switch(o){case"null":r.push([rB]);return;case"undefined":r.push([nB]);return;case"boolean":r.push([e?tB:eB]);return;case"number":!Number.isInteger(e)||!Number.isSafeInteger(e)?rd(r,new te(I.float,e),t):e>=0?ot(r,aE,e):ot(r,cE,e*-1-1);return;case"bigint":e>=BigInt(0)?ot(r,aE,e):ot(r,cE,e*oB-iB);return;case"string":{let s=D1(e);ot(r,JO,s.length),r.push(s);return}case"Uint8Array":ot(r,ZO,e.length),r.push(e);return;case"Array":if(!e.length){r.push([lE]);return}n=od.createCheck(n,e),ot(r,lE,e.length);for(let s of e)dE(r,s,t,n);return;case"Object":case"Map":{let s=Eo.Object(e,o,t,n);nd(r,s,Wc,t)}return;default:{let s=Eo[o];if(!s)throw new Error(`${M1} unsupported type: ${o}`);let a=s(e,o,t,n);nd(r,a,Wc,t)}}}function fE(r,e,t,n){let o=n instanceof Uint8Array,i=o?new B1(n):q1,s=zc(r,t);if(!Array.isArray(s)&&t.quickEncodeToken){let a=t.quickEncodeToken(s);if(a)return o?(i.push(a),i.toBytes()):a;let c=e[s.type.major];if(c.encodedSize){let l=c.encodedSize(s,t);if(o||(i=new Zu(l)),c(i,s,t),i.chunks.length!==1)throw new Error(`Unexpected error: pre-calculated length for ${s} was wrong`);return o?i.toBytes():Qu(i.chunks[0])}}return i.reset(),nd(i,s,e,t),i.toBytes(!0)}function id(r,e){return e=Object.assign({},GO,e),sB(e)?(q1.reset(),dE(q1,r,e,void 0),q1.toBytes(!0)):fE(r,Wc,e)}var aB={strict:!1,allowIndefinite:!0,allowUndefined:!0,allowBigInt:!0},z1=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=Wn[e];if(t===void 0){let n=G[e];if(!n)throw new Error(`${le} 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}},Qi=Symbol.for("DONE"),Gc=Symbol.for("BREAK");function cB(r,e,t){let n=[];for(let o=0;o<r.value;o++){let i=Zi(e,t);if(i===Gc){if(r.value===1/0)break;throw new Error(`${le} got unexpected break to lengthed array`)}if(i===Qi)throw new Error(`${le} found array but not enough entries (got ${o}, expected ${r.value})`);n[o]=i}return n}function lB(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=Zi(e,t);if(c===Gc){if(r.value===1/0)break;throw new Error(`${le} got unexpected break to lengthed map`)}if(c===Qi)throw new Error(`${le} found map but not enough entries (got ${a} [no key], expected ${r.value})`);if(!n&&typeof c!="string")throw new Error(`${le} non-string keys not supported (got ${typeof c})`);if(o&&(n&&s.has(c)||!n&&Object.hasOwn(i,c)))throw new Error(`${le} found repeat map key "${c}"`);let l=Zi(e,t);if(l===Qi)throw new Error(`${le} found map but not enough entries (got ${a} [no value], expected ${r.value})`);n?s.set(c,l):i[c]=l}return n?s:i}function*uB(r,e,t){for(let n=0;n<r.value;n++){let o=Zi(e,t);if(o===Gc){if(r.value===1/0)break;throw new Error(`${le} got unexpected break to lengthed map`)}if(o===Qi)throw new Error(`${le} found map but not enough entries (got ${n} [no key], expected ${r.value})`);let i=Zi(e,t);if(i===Qi)throw new Error(`${le} found map but not enough entries (got ${n} [no value], expected ${r.value})`);yield[o,i]}}function dB(r,e){let t=!1,n=function(){if(t)throw new Error(`${le} tag decode() may only be called once`);t=!0;let o=Zi(r,e);if(o===Qi)throw new Error(`${le} tag content missing`);if(o===Gc)throw new Error(`${le} got unexpected break in tag content`);return o};return n.entries=function(){if(t)throw new Error(`${le} tag decode() may only be called once`);t=!0;let o=r.next();if(!I.equals(o.type,I.map))throw new Error(`${le} entries() requires map content, got ${o.type.name}`);let i=[];for(let s of uB(o,r,e))i.push(s);return i},Object.defineProperty(n,"_called",{get(){return t},enumerable:!1}),n}function Zi(r,e){if(r.done())return Qi;let t=r.next();if(I.equals(t.type,I.break))return Gc;if(t.type.terminal)return t.value;if(I.equals(t.type,I.array))return cB(t,r,e);if(I.equals(t.type,I.map))return lB(t,r,e);if(I.equals(t.type,I.tag)){if(e.tags&&typeof e.tags[t.value]=="function"){let n=dB(r,e),o=e.tags[t.value](n);if(!n._called)throw new Error(`${le} tag decoder must call decode() or entries()`);return o}throw new Error(`${le} tag not supported (${t.value})`)}throw new Error("unsupported")}function hE(r,e){if(!(r instanceof Uint8Array))throw new Error(`${le} data to decode must be a Uint8Array`);e=Object.assign({},aB,e);let t=Qu(r),n=e.tokenizer||new z1(t,e),o=Zi(n,e);if(o===Qi)throw new Error(`${le} did not find any content to decode`);if(o===Gc)throw new Error(`${le} got unexpected break`);return[o,r.subarray(n.pos())]}function ba(r,e){let[t,n]=hE(r,e);if(n.length>0)throw new Error(`${le} too many terminals, data makes no sense`);return t}var W1=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(W1.prototype,Symbol.toStringTag,{value:"Tagged"});var ni="/",pE=new TextEncoder().encode(ni),G1=pE[0],rt=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]!==G1)throw new Error("Invalid key")}toString(e="utf8"){return D(this._buf,e)}uint8Array(){return this._buf}get[Symbol.toStringTag](){return`Key(${this.toString()})`}static withNamespaces(e){return new r(e.join(ni))}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=pE),this._buf[0]!==G1){let e=new Uint8Array(this._buf.byteLength+1);e.fill(G1,0,1),e.set(this._buf,1),this._buf=e}for(;this._buf.byteLength>1&&this._buf[this._buf.byteLength-1]===G1;)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(ni).slice(1)}type(){return hB(this.baseNamespace())}name(){return pB(this.baseNamespace())}instance(e){return new r(this.toString()+":"+e)}path(){let e=this.parent().toString();return e.endsWith(ni)||(e+=ni),e+=this.type(),new r(e)}parent(){let e=this.list();return e.length===1?new r(ni):new r(e.slice(0,-1).join(ni))}child(e){return this.toString()===ni?e:e.toString()===ni?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(),...mB(e.map(t=>t.namespaces()))])}};function hB(r){let e=r.split(":");return e.length<2?"":e.slice(0,-1).join(":")}function pB(r){let e=r.split(":");return e[e.length-1]}function mB(r){return[].concat(...r)}function gB(r){return r[Symbol.asyncIterator]!=null}function yB(r){if(gB(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 j1=yB;function Y1({enumerable:r=!0,configurable:e=!1}={}){return{enumerable:r,configurable:e,writable:!1}}function*wB(r,e){if(e!=null&&typeof e=="object")if(Array.isArray(e))for(let[t,n]of e.entries()){let o=[...r,t],i=J.asCID(n);i!=null?yield[o.join("/"),i]:typeof n=="object"&&(yield*ty(n,o))}else{let t=J.asCID(e);t!=null?yield[r.join("/"),t]:yield*ty(e,r)}}function*ty(r,e){if(r==null||r instanceof Uint8Array)return;let t=J.asCID(r);t!=null&&(yield[e.join("/"),t]);for(let[n,o]of Object.entries(r)){let i=[...e,n];yield*wB(i,o)}}function*bB(r,e){if(Array.isArray(e))for(let[t,n]of e.entries()){let o=[...r,t];yield o.join("/"),typeof n=="object"&&J.asCID(n)==null&&(yield*ry(n,o))}else yield*ry(e,r)}function*ry(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"&&J.asCID(n)==null&&(yield*bB(o,n))}}function xB(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=J.asCID(t);if(i!=null)return{value:i,remaining:e.slice(n+1).join("/")}}return{value:t}}var ny=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:Y1(),bytes:Y1(),value:Y1(),asBlock:Y1()})}links(){return ty(this.value,[])}tree(){return ry(this.value,[])}get(e="/"){return xB(this.value,e.split("/").filter(Boolean))}};function mE({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 ny({cid:e,bytes:r,value:o})}var X1=class extends Error{static name="AlreadyPinnedError";name="AlreadyPinnedError"},sd=class extends Error{static name="BlockPinnedError";name="BlockPinnedError"},Q1=class extends Error{static name="InvalidDatastoreVersionError";name="InvalidDatastoreVersionError"},xa=class extends Error{static name="InvalidConfigurationError";name="InvalidConfigurationError"},Z1=class extends AggregateError{static name="GetFailedError";name="GetFailedError"},J1=class extends AggregateError{static name="LoadBlockFailedError";name="LoadBlockFailedError"},ad=class extends Error{static name="BlockNotFoundWhileOfflineError";name="BlockNotFoundWhileOfflineError"};var wE="/pin/",gE="/pinned-block/",oy=dn,yE=1;function ep(r){return r.version===0&&(r=r.toV1()),new rt(`${wE}${r.toString(oy)}`)}var tp=class{datastore;blockstore;getCodec;constructor(e,t,n){this.datastore=e,this.blockstore=t,this.getCodec=n}async*add(e,t={}){let n=ep(e);if(await this.datastore.has(n))throw new X1("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 Yt({concurrency:yE});for await(let a of this.#e(e,i,{...t,depth:o}))await this.#t(a,c=>c.pinnedBy.find(l=>ce(l,e.bytes))!=null?!1:(c.pinCount++,c.pinnedBy.push(e.bytes),!0),t),yield a;let s={depth:o,metadata:t.metadata??{}};await this.datastore.put(n,id(s),t)}async*#e(e,t,n){if(n.depth===-1)return;let o=await this.getCodec(e.code),i=await j1(this.blockstore.get(e,n)),s=mE({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 rt(`${gE}${oy.encode(e.multihash.bytes)}`),i={pinCount:0,pinnedBy:[]};try{i=ba(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,id(i),n),n.onProgress?.(new U("helia:pin:add",e))}}async*rm(e,t={}){let n=ep(e),o=await this.datastore.get(n,t),i=ba(o);await this.datastore.delete(n,t);let s=new Yt({concurrency:yE});for await(let a of this.#e(e,s,{...t,depth:i.depth}))await this.#t(a,c=>(c.pinCount--,c.pinnedBy=c.pinnedBy.filter(l=>ce(l,e.bytes)),!0),{...t,depth:i.depth}),yield a}async*ls(e={}){for await(let{key:t,value:n}of this.datastore.query({prefix:wE+(e.cid!=null?`${e.cid.toString(dn)}`:"")},e)){let o=J.parse(t.toString().substring(5),dn),i=ba(n);yield{cid:o,...i}}}async isPinned(e,t={}){let n=new rt(`${gE}${oy.encode(e.multihash.bytes)}`);return this.datastore.has(n,t)}async get(e,t){let n=ep(e),o=await this.datastore.get(n,t);return ba(o)}async setMetadata(e,t,n){let o=ep(e),i=await this.datastore.get(o,n),s=ba(i);s.metadata=t??{},await this.datastore.put(o,id(s),n)}};var iy=1,sy=5,ay=100;var cd=class extends Error{static name="InsufficientProvidersError";constructor(e="Insufficient providers found"){super(e),this.name="InsufficientProvidersError"}},Ji=class extends Error{static name="NoRoutersAvailableError";constructor(e="No routers available"){super(e),this.name="NoRoutersAvailableError"}},ld=class extends Error{static name="UnknownHashAlgorithmError";constructor(e="Unknown hash algorithm"){super(e),this.name="UnknownHashAlgorithmError"}},ud=class extends Error{static name="UnknownCodecError";constructor(e="Unknown codec"){super(e),this.name="UnknownCodecError"}},cy=class extends Error{static name="InvalidCodecError";constructor(e="Invalid codec"){super(e),this.name="InvalidCodecError"}};var EB=5,rp=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??EB,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 Tt(...this.routers)}async stop(){await Pt(...this.routers)}async*findProviders(e,t={}){if(this.routers.length===0)throw new Ji("No content routers available");let n=new Qt({concurrency:this.providerLookupConcurrency}),o=0,i=[],s=this,a=0;this.log("findProviders for %c start using routers %s",e,this.routers.map(l=>l.toString()).join(", "));let c=Ea(this.routers,"findProviders").map(async function*(l){let u=0;t?.onProgress?.(new U("helia:routing:find-providers:start",{routing:l.name,cid:e}));try{for await(let d of l.findProviders(e,t))u++,t?.onProgress?.(new U("helia:routing:find-providers:provider",{routing:l.name,cid:e,provider:d})),yield d}catch(d){i.push(d)}finally{s.log("router %s found %d providers for %c",l,u,e),t?.onProgress?.(new U("helia:routing:find-providers:end",{routing:l.name,cid:e,found:u})),a++,a===c.length&&n.size===0&&n.emitIdle()}});for await(let l of wr(n.toGenerator(),...c))if(l!=null){if(l.multiaddrs.length===0){if(n.find(l.id)!=null)continue;n.add(async()=>{try{let u=await this.findPeer(l.id,t);return u.multiaddrs.length===0?null:{...u,protocols:l.protocols,routing:l.routing}}catch(u){return this.log.error("could not load multiaddrs for peer %p - %e",l.id,u),null}},{peerId:l.id,signal:t.signal}).catch(u=>{this.log.error("could not load multiaddrs for peer %p - %e",l.id,u)});continue}o++,yield l}this.log("findProviders finished, found %d providers for %c",o,e)}async provide(e,t={}){if(this.routers.length===0)throw new Ji("No content routers available");await Promise.all(Ea(this.routers,"provide").map(async n=>{t?.onProgress?.(new U("helia:routing:provide:start",{routing:n.name,cid:e})),await n.provide(e,t),t?.onProgress?.(new U("helia:routing:provide:end",{routing:n.name,cid:e}))}))}async cancelReprovide(e,t={}){await Promise.all(Ea(this.routers,"cancelReprovide").map(async n=>{t?.onProgress?.(new U("helia:routing:cancel-reprovide:start",{routing:n.name,cid:e})),await n.cancelReprovide(e,t),t?.onProgress?.(new U("helia:routing:cancel-reprovide:end",{routing:n.name,cid:e}))}))}async put(e,t,n){await Promise.all(Ea(this.routers,"put").map(async o=>{n?.onProgress?.(new U("helia:routing:put:start",{routing:o.name,key:e,value:t})),await o.put(e,t,n),n?.onProgress?.(new U("helia:routing:put:end",{routing:o.name,key:e,value:t}))}))}async get(e,t){let n=[],o;try{o=await Promise.any(Ea(this.routers,"get").map(async i=>{t?.onProgress?.(new U("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 U("helia:routing:get:end",{routing:i.name,key:e}))}}))}catch{}if(o==null)throw new Z1(n,`Failed to get value key ${D(e,"base58btc")}`);return o}async findPeer(e,t){if(this.routers.length===0)throw new Ji("No peer routers available");let n=this,o=wr(...Ea(this.routers,"findPeer").map(i=>(async function*(){t?.onProgress?.(new U("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 U("helia:routing:find-peer:end",{routing:i.name,peerId:e}))}})()));for await(let i of o)if(i!=null)return i;throw new je("Could not find peer in routing")}async*getClosestPeers(e,t={}){if(this.routers.length===0)throw new Ji("No peer routers available");for await(let n of wr(...Ea(this.routers,"getClosestPeers").map(async function*(o){t?.onProgress?.(new U("helia:routing:get-closest-peers:start",{routing:o.name,key:e}));try{yield*o.getClosestPeers(e,t)}finally{t?.onProgress?.(new U("helia:routing:get-closest-peers:end",{routing:o.name,key:e}))}})))n!=null&&(yield n)}};function Ea(r,e){return r.filter(t=>t[e]!=null)}var qr=class extends Error{static name="AbortError";name="AbortError";constructor(e="The operation was aborted",...t){super(e,...t)}};async function br(r,e,t,n){let o=new qr(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(){uy(t,"abort",d),uy(r,e,l),uy(r,i,u)}let l=f=>{try{if(n?.filter?.(f)===!1)return}catch(h){c(),a(h);return}c(),s(f)},u=f=>{if(c(),f instanceof Error){a(f);return}a(f.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.`))},d=()=>{c(),a(o)};ly(t,"abort",d),ly(r,e,l),ly(r,i,u)})}function ly(r,e,t){r!=null&&(bE(r)?r.addEventListener(e,t):r.addListener(e,t))}function uy(r,e,t){r!=null&&(bE(r)?r.removeEventListener(e,t):r.removeListener(e,t))}function bE(r){return typeof r.addEventListener=="function"&&typeof r.removeEventListener=="function"}var np=class extends Error{static name="QueueFullError";constructor(e="The queue was full"){super(e),this.name="QueueFullError"}};var op=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 qr)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function vB(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var ip=class{id;fn;options;recipients;status;timeline;controller;constructor(e,t){this.id=vB(),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 qr),this.cleanup())}async join(e={}){let t=new op(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 Ze(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 dy(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 dd=class extends we{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=dy(this.emitEmpty.bind(this),1),this.emitIdle=dy(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 np;let n=new ip(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 qr)}),this.clear()}async onEmpty(e){this.size!==0&&await br(this,"empty",e?.signal)}async onSizeLessThan(e,t){this.size<e||await br(this,"next",t?.signal,{filter:()=>this.size<e})}async onIdle(e){this.pending===0&&this.size===0||await br(this,"idle",e?.signal)}get size(){return this.queue.length}get queued(){return this.queue.length-this.pending}get running(){return this.pending}async*toGenerator(e){e?.signal?.throwIfAborted();let t=jt({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 qr("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 sp="lock:worker:request-read",ap="lock:worker:abort-read-request",cp="lock:worker:release-read",lp="lock:master:grant-read",up="lock:master:error-read",dp="lock:worker:request-write",fp="lock:worker:abort-write-request",hp="lock:worker:release-write",pp="lock:master:grant-write",mp="lock:master:error-write",gp="lock:worker:finalize",yp="mortice",xE={singleProcess:!1};var fy=(r,e,t,n,o,i,s,a,c)=>l=>{if(l.data==null)return;let u={type:l.data.type,name:l.data.name,identifier:l.data.identifier};u.type===o&&r.safeDispatchEvent(t,{detail:{name:u.name,identifier:u.identifier,handler:async()=>{e.postMessage({type:c,name:u.name,identifier:u.identifier}),await new Promise(d=>{let f=h=>{if(h?.data==null)return;let p={type:h.data.type,name:h.data.name,identifier:h.data.identifier};p.type===a&&p.identifier===u.identifier&&(e.removeEventListener("message",f),d())};e.addEventListener("message",f)})},onError:d=>{e.postMessage({type:s,name:u.name,identifier:u.identifier,error:{message:d.message,name:d.name,stack:d.stack}})}}}),u.type===i&&r.safeDispatchEvent(n,{detail:{name:u.name,identifier:u.identifier}}),u.type===gp&&r.safeDispatchEvent("finalizeRequest",{detail:{name:u.name}})};var EE=(r=10)=>Math.random().toString().substring(2,r+2);var wp=class{name;channel;constructor(e){this.name=e,this.channel=new BroadcastChannel(yp)}readLock(e){return this.sendRequest(sp,ap,lp,up,cp,e)}writeLock(e){return this.sendRequest(dp,fp,pp,mp,hp,e)}finalize(){this.channel.postMessage({type:gp,name:this.name}),this.channel.close()}async sendRequest(e,t,n,o,i,s){s?.signal?.throwIfAborted();let a=EE();return this.channel.postMessage({type:e,identifier:a,name:this.name}),new Promise((c,l)=>{let u=()=>{this.channel.postMessage({type:t,identifier:a,name:this.name})};s?.signal?.addEventListener("abort",u,{once:!0});let d=f=>{if(f.data?.identifier===a&&(f.data?.type===n&&(this.channel.removeEventListener("message",d),s?.signal?.removeEventListener("abort",u),c(()=>{this.channel.postMessage({type:i,identifier:a,name:this.name})})),f.data.type===o)){this.channel.removeEventListener("message",d),s?.signal?.removeEventListener("abort",u);let h=new Error;f.data.error!=null&&(h.message=f.data.error.message,h.name=f.data.error.name,h.stack=f.data.error.stack),l(h)}};this.channel.addEventListener("message",d)})}};var vE=r=>{if(r=Object.assign({},xE,r),!!globalThis.document||r.singleProcess){let t=new BroadcastChannel(yp),n=new we;return t.addEventListener("message",fy(n,t,"requestReadLock","abortReadLockRequest",sp,ap,up,cp,lp)),t.addEventListener("message",fy(n,t,"requestWriteLock","abortWriteLockRequest",dp,fp,mp,hp,pp)),n}return new wp(r.name)};var va=new Map,fd;function SE(r){return typeof r?.readLock=="function"&&typeof r?.writeLock=="function"}function SB(r){if(fd==null&&(fd=vE(r),!SE(fd))){let e=fd;e.addEventListener("requestReadLock",t=>{let n=t.detail.name,o=t.detail.identifier,i=va.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=va.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=va.get(n);o?.finalize()})}return fd}async function hy(r,e){let t,n,o=new Promise((s,a)=>{t=s,n=a}),i=()=>{n(new qr)};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 AE=(r,e)=>{let t=va.get(r);if(t!=null)return t;let n=SB(e);if(SE(n))return t=n,va.set(r,t),t;let o=new dd({concurrency:1}),i;return t={async readLock(s){if(i!=null)return hy(i,s);i=new dd({concurrency:e.concurrency,autoStart:!1});let a=i,c=hy(i,s);return o.add(async()=>{a.start(),await a.onIdle().then(()=>{i===a&&(i=null)})}),c},async writeLock(s){return i=null,hy(o,s)},finalize:()=>{va.delete(r)},queue:o},va.set(r,t),e.autoFinalize===!0&&o.addEventListener("idle",()=>{t.finalize()},{once:!0}),t};var AB={name:"lock",concurrency:1/0,singleProcess:!1,autoFinalize:!1};function hd(r){let e=Object.assign({},AB,r);return AE(e.name,e)}var bp=class{lock;child;pins;started;constructor(e,t,n={}){this.child=e,this.pins=t,this.lock=hd({singleProcess:n.holdGcLock}),this.started=!1}isStarted(){return this.started}async start(){await Tt(this.child),this.started=!0}async stop(){await Pt(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 sd("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 sd("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 py=new rt("/version"),TE=1;async function _E(r){if(!await r.has(py)){await r.put(py,L(`${TE}`));return}let e=await r.get(py),t=D(e);if(parseInt(t,10)!==TE)throw new Q1("Invalid datastore version, a datastore migration may be required")}var Ry={};wt(Ry,{code:()=>Cy,decode:()=>yM,decodeOptions:()=>pM,encode:()=>gM,encodeOptions:()=>fM,name:()=>mM,toByteView:()=>Nv});var TB=["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 my(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=_B(r);return t||"Object"}function _B(r){let e=Object.prototype.toString.call(r).slice(8,-1);if(TB.includes(e))return e}var _=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}};_.uint=new _(0,"uint",!0);_.negint=new _(1,"negint",!0);_.bytes=new _(2,"bytes",!0);_.string=new _(3,"string",!0);_.array=new _(4,"array",!1);_.map=new _(5,"map",!1);_.tag=new _(6,"tag",!1);_.float=new _(7,"float",!0);_.false=new _(7,"false",!0);_.true=new _(7,"true",!0);_.null=new _(7,"null",!0);_.undefined=new _(7,"undefined",!0);_.break=new _(7,"break",!0);var Q=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 pd=globalThis.process&&!globalThis.process.browser&&globalThis.Buffer&&typeof globalThis.Buffer.isBuffer=="function",IB=new TextEncoder;function xp(r){return pd&&globalThis.Buffer.isBuffer(r)}function md(r){return r instanceof Uint8Array?xp(r)?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):r:Uint8Array.from(r)}var kB=24,CB=200,Ep=pd?r=>r.length>=kB?globalThis.Buffer.from(r):IE(r):r=>r.length>=CB?IB.encode(r):IE(r),vo=r=>Uint8Array.from(r),kE=pd?(r,e,t)=>xp(r)?new Uint8Array(r.subarray(e,t)):r.slice(e,t):(r,e,t)=>r.slice(e,t),CE=pd?(r,e)=>(r=r.map(t=>t instanceof Uint8Array?t:globalThis.Buffer.from(t)),md(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},RE=pd?r=>globalThis.Buffer.allocUnsafe(r):r=>new Uint8Array(r);function vp(r,e){if(xp(r)&&xp(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 IE(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 RB=256,gd=class{constructor(e=RB){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=RE(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=kE(n,0,this.cursor)}else t=CE(this.chunks,this.cursor);return e&&this.reset(),t}},Sp=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 ue="CBOR decode error:",Ap="CBOR encode error:",yd=[];yd[23]=1;yd[24]=2;yd[25]=3;yd[26]=5;yd[27]=9;function oi(r,e,t){if(r.length-e<t)throw new Error(`${ue} not enough data for type`)}var Mt=[24,256,65536,4294967296,BigInt("18446744073709551616")];function zr(r,e,t){oi(r,e,1);let n=r[e];if(t.strict===!0&&n<Mt[0])throw new Error(`${ue} integer encoded in more bytes than necessary (strict decode)`);return n}function Wr(r,e,t){oi(r,e,2);let n=r[e]<<8|r[e+1];if(t.strict===!0&&n<Mt[1])throw new Error(`${ue} integer encoded in more bytes than necessary (strict decode)`);return n}function Gr(r,e,t){oi(r,e,4);let n=r[e]*16777216+(r[e+1]<<16)+(r[e+2]<<8)+r[e+3];if(t.strict===!0&&n<Mt[2])throw new Error(`${ue} integer encoded in more bytes than necessary (strict decode)`);return n}function jr(r,e,t){oi(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<Mt[3])throw new Error(`${ue} 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(`${ue} integers outside of the safe integer range are not supported`)}function PE(r,e,t,n){return new Q(_.uint,zr(r,e+1,n),2)}function LE(r,e,t,n){return new Q(_.uint,Wr(r,e+1,n),3)}function NE(r,e,t,n){return new Q(_.uint,Gr(r,e+1,n),5)}function DE(r,e,t,n){return new Q(_.uint,jr(r,e+1,n),9)}function wn(r,e){return it(r,0,e.value)}function it(r,e,t){if(t<Mt[0]){let n=Number(t);r.push([e|n])}else if(t<Mt[1]){let n=Number(t);r.push([e|24,n])}else if(t<Mt[2]){let n=Number(t);r.push([e|25,n>>>8,n&255])}else if(t<Mt[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<Mt[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(`${ue} encountered BigInt larger than allowable range`)}}wn.encodedSize=function(e){return it.encodedSize(e.value)};it.encodedSize=function(e){return e<Mt[0]?1:e<Mt[1]?2:e<Mt[2]?3:e<Mt[3]?5:9};wn.compareTokens=function(e,t){return e.value<t.value?-1:e.value>t.value?1:0};function OE(r,e,t,n){return new Q(_.negint,-1-zr(r,e+1,n),2)}function BE(r,e,t,n){return new Q(_.negint,-1-Wr(r,e+1,n),3)}function ME(r,e,t,n){return new Q(_.negint,-1-Gr(r,e+1,n),5)}var gy=BigInt(-1),UE=BigInt(1);function FE(r,e,t,n){let o=jr(r,e+1,n);if(typeof o!="bigint"){let i=-1-o;if(i>=Number.MIN_SAFE_INTEGER)return new Q(_.negint,i,9)}if(n.allowBigInt!==!0)throw new Error(`${ue} integers outside of the safe integer range are not supported`);return new Q(_.negint,gy-BigInt(o),9)}function Tp(r,e){let t=e.value,n=typeof t=="bigint"?t*gy-UE:t*-1-1;it(r,e.type.majorEncoded,n)}Tp.encodedSize=function(e){let t=e.value,n=typeof t=="bigint"?t*gy-UE:t*-1-1;return n<Mt[0]?1:n<Mt[1]?2:n<Mt[2]?3:n<Mt[3]?5:9};Tp.compareTokens=function(e,t){return e.value<t.value?1:e.value>t.value?-1:0};function wd(r,e,t,n){oi(r,e,t+n);let o=r.slice(e+t,e+t+n);return new Q(_.bytes,o,t+n)}function $E(r,e,t,n){return wd(r,e,1,t)}function VE(r,e,t,n){return wd(r,e,2,zr(r,e+1,n))}function KE(r,e,t,n){return wd(r,e,3,Wr(r,e+1,n))}function HE(r,e,t,n){return wd(r,e,5,Gr(r,e+1,n))}function qE(r,e,t,n){let o=jr(r,e+1,n);if(typeof o=="bigint")throw new Error(`${ue} 64-bit integer bytes lengths not supported`);return wd(r,e,9,o)}function _p(r){return r.encodedBytes===void 0&&(r.encodedBytes=_.equals(r.type,_.string)?Ep(r.value):r.value),r.encodedBytes}function jc(r,e){let t=_p(e);it(r,e.type.majorEncoded,t.length),r.push(t)}jc.encodedSize=function(e){let t=_p(e);return it.encodedSize(t.length)+t.length};jc.compareTokens=function(e,t){return LB(_p(e),_p(t))};function LB(r,e){return r.length<e.length?-1:r.length>e.length?1:vp(r,e)}var zE=new TextDecoder,DB=32;function OB(r,e,t){if(t-e<DB){let o="";for(let i=e;i<t;i++){let s=r[i];if(s&128)return zE.decode(r.subarray(e,t));o+=String.fromCharCode(s)}return o}return zE.decode(r.subarray(e,t))}function bd(r,e,t,n,o){let i=t+n;oi(r,e,i);let s=new Q(_.string,OB(r,e+t,e+i),i);return o.retainStringBytes===!0&&(s.byteValue=r.slice(e+t,e+i)),s}function WE(r,e,t,n){return bd(r,e,1,t,n)}function GE(r,e,t,n){return bd(r,e,2,zr(r,e+1,n),n)}function jE(r,e,t,n){return bd(r,e,3,Wr(r,e+1,n),n)}function YE(r,e,t,n){return bd(r,e,5,Gr(r,e+1,n),n)}function XE(r,e,t,n){let o=jr(r,e+1,n);if(typeof o=="bigint")throw new Error(`${ue} 64-bit integer string lengths not supported`);return bd(r,e,9,o,n)}var QE=jc;function Yc(r,e,t,n){return new Q(_.array,n,t)}function ZE(r,e,t,n){return Yc(r,e,1,t)}function JE(r,e,t,n){return Yc(r,e,2,zr(r,e+1,n))}function ev(r,e,t,n){return Yc(r,e,3,Wr(r,e+1,n))}function tv(r,e,t,n){return Yc(r,e,5,Gr(r,e+1,n))}function rv(r,e,t,n){let o=jr(r,e+1,n);if(typeof o=="bigint")throw new Error(`${ue} 64-bit integer array lengths not supported`);return Yc(r,e,9,o)}function nv(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${ue} indefinite length items not allowed`);return Yc(r,e,1,1/0)}function Ip(r,e){it(r,_.array.majorEncoded,e.value)}Ip.compareTokens=wn.compareTokens;Ip.encodedSize=function(e){return it.encodedSize(e.value)};function Xc(r,e,t,n){return new Q(_.map,n,t)}function ov(r,e,t,n){return Xc(r,e,1,t)}function iv(r,e,t,n){return Xc(r,e,2,zr(r,e+1,n))}function sv(r,e,t,n){return Xc(r,e,3,Wr(r,e+1,n))}function av(r,e,t,n){return Xc(r,e,5,Gr(r,e+1,n))}function cv(r,e,t,n){let o=jr(r,e+1,n);if(typeof o=="bigint")throw new Error(`${ue} 64-bit integer map lengths not supported`);return Xc(r,e,9,o)}function lv(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${ue} indefinite length items not allowed`);return Xc(r,e,1,1/0)}function kp(r,e){it(r,_.map.majorEncoded,e.value)}kp.compareTokens=wn.compareTokens;kp.encodedSize=function(e){return it.encodedSize(e.value)};function uv(r,e,t,n){return new Q(_.tag,t,1)}function dv(r,e,t,n){return new Q(_.tag,zr(r,e+1,n),2)}function fv(r,e,t,n){return new Q(_.tag,Wr(r,e+1,n),3)}function hv(r,e,t,n){return new Q(_.tag,Gr(r,e+1,n),5)}function pv(r,e,t,n){return new Q(_.tag,jr(r,e+1,n),9)}function Cp(r,e){it(r,_.tag.majorEncoded,e.value)}Cp.compareTokens=wn.compareTokens;Cp.encodedSize=function(e){return it.encodedSize(e.value)};var yy=20,wy=21,by=22,xy=23;function mv(r,e,t,n){if(n.allowUndefined===!1)throw new Error(`${ue} undefined values are not supported`);return n.coerceUndefinedToNull===!0?new Q(_.null,null,1):new Q(_.undefined,void 0,1)}function gv(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${ue} indefinite length items not allowed`);return new Q(_.break,void 0,1)}function Ey(r,e,t){if(t){if(t.allowNaN===!1&&Number.isNaN(r))throw new Error(`${ue} NaN values are not supported`);if(t.allowInfinity===!1&&(r===1/0||r===-1/0))throw new Error(`${ue} Infinity values are not supported`)}return new Q(_.float,r,e)}function yv(r,e,t,n){return Ey(vy(r,e+1),3,n)}function wv(r,e,t,n){return Ey(Sy(r,e+1),5,n)}function bv(r,e,t,n){return Ey(Sv(r,e+1),9,n)}function xd(r,e,t){let n=e.value;if(n===!1)r.push([_.float.majorEncoded|yy]);else if(n===!0)r.push([_.float.majorEncoded|wy]);else if(n===null)r.push([_.float.majorEncoded|by]);else if(n===void 0)r.push([_.float.majorEncoded|xy]);else{let o,i=!1;(!t||t.float64!==!0)&&(Ev(n),o=vy(Gn,1),n===o||Number.isNaN(n)?(Gn[0]=249,r.push(Gn.slice(0,3)),i=!0):(vv(n),o=Sy(Gn,1),n===o&&(Gn[0]=250,r.push(Gn.slice(0,5)),i=!0))),i||($B(n),o=Sv(Gn,1),Gn[0]=251,r.push(Gn.slice(0,9)))}}xd.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){Ev(n);let o=vy(Gn,1);if(n===o||Number.isNaN(n))return 3;if(vv(n),o=Sy(Gn,1),n===o)return 5}return 9};var xv=new ArrayBuffer(9),bn=new DataView(xv,1),Gn=new Uint8Array(xv,0);function Ev(r){if(r===1/0)bn.setUint16(0,31744,!1);else if(r===-1/0)bn.setUint16(0,64512,!1);else if(Number.isNaN(r))bn.setUint16(0,32256,!1);else{bn.setFloat32(0,r);let e=bn.getUint32(0),t=(e&2139095040)>>23,n=e&8388607;if(t===255)bn.setUint16(0,31744,!1);else if(t===0)bn.setUint16(0,(e&2147483648)>>16|n>>13,!1);else{let o=t-127;o<-24?bn.setUint16(0,0):o<-14?bn.setUint16(0,(e&2147483648)>>16|1<<24+o,!1):bn.setUint16(0,(e&2147483648)>>16|o+15<<10|n>>13,!1)}}}function vy(r,e){if(r.length-e<2)throw new Error(`${ue} 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 vv(r){bn.setFloat32(0,r,!1)}function Sy(r,e){if(r.length-e<4)throw new Error(`${ue} not enough data for float32`);let t=(r.byteOffset||0)+e;return new DataView(r.buffer,t,4).getFloat32(0,!1)}function $B(r){bn.setFloat64(0,r,!1)}function Sv(r,e){if(r.length-e<8)throw new Error(`${ue} not enough data for float64`);let t=(r.byteOffset||0)+e;return new DataView(r.buffer,t,8).getFloat64(0,!1)}xd.compareTokens=wn.compareTokens;function Oe(r,e,t){throw new Error(`${ue} encountered invalid minor (${t}) for major ${r[e]>>>5}`)}function Rp(r){return()=>{throw new Error(`${ue} ${r}`)}}var j=[];for(let r=0;r<=23;r++)j[r]=Oe;j[24]=PE;j[25]=LE;j[26]=NE;j[27]=DE;j[28]=Oe;j[29]=Oe;j[30]=Oe;j[31]=Oe;for(let r=32;r<=55;r++)j[r]=Oe;j[56]=OE;j[57]=BE;j[58]=ME;j[59]=FE;j[60]=Oe;j[61]=Oe;j[62]=Oe;j[63]=Oe;for(let r=64;r<=87;r++)j[r]=$E;j[88]=VE;j[89]=KE;j[90]=HE;j[91]=qE;j[92]=Oe;j[93]=Oe;j[94]=Oe;j[95]=Rp("indefinite length bytes/strings are not supported");for(let r=96;r<=119;r++)j[r]=WE;j[120]=GE;j[121]=jE;j[122]=YE;j[123]=XE;j[124]=Oe;j[125]=Oe;j[126]=Oe;j[127]=Rp("indefinite length bytes/strings are not supported");for(let r=128;r<=151;r++)j[r]=ZE;j[152]=JE;j[153]=ev;j[154]=tv;j[155]=rv;j[156]=Oe;j[157]=Oe;j[158]=Oe;j[159]=nv;for(let r=160;r<=183;r++)j[r]=ov;j[184]=iv;j[185]=sv;j[186]=av;j[187]=cv;j[188]=Oe;j[189]=Oe;j[190]=Oe;j[191]=lv;for(let r=192;r<=215;r++)j[r]=uv;j[216]=dv;j[217]=fv;j[218]=hv;j[219]=pv;j[220]=Oe;j[221]=Oe;j[222]=Oe;j[223]=Oe;for(let r=224;r<=243;r++)j[r]=Rp("simple values are not supported");j[244]=Oe;j[245]=Oe;j[246]=Oe;j[247]=mv;j[248]=Rp("simple values are not supported");j[249]=yv;j[250]=wv;j[251]=bv;j[252]=Oe;j[253]=Oe;j[254]=Oe;j[255]=gv;var jn=[];for(let r=0;r<24;r++)jn[r]=new Q(_.uint,r,1);for(let r=-1;r>=-24;r--)jn[31-r]=new Q(_.negint,r,1);jn[64]=new Q(_.bytes,new Uint8Array(0),1);jn[96]=new Q(_.string,"",1);jn[128]=new Q(_.array,0,1);jn[160]=new Q(_.map,0,1);jn[244]=new Q(_.false,!1,1);jn[245]=new Q(_.true,!0,1);jn[246]=new Q(_.null,null,1);function Ay(r){switch(r.type){case _.false:return vo([244]);case _.true:return vo([245]);case _.null:return vo([246]);case _.bytes:return r.value.length?void 0:vo([64]);case _.string:return r.value===""?vo([96]):void 0;case _.array:return r.value===0?vo([128]):void 0;case _.map:return r.value===0?vo([160]):void 0;case _.uint:return r.value<24?vo([Number(r.value)]):void 0;case _.negint:if(r.value>=-24)return vo([31-Number(r.value)])}}var KB={float64:!1,mapSorter:zB,quickEncodeToken:Ay},kv=Object.freeze({float64:!0,mapSorter:WB,quickEncodeToken:Ay});function HB(){let r=[];return r[_.uint.major]=wn,r[_.negint.major]=Tp,r[_.bytes.major]=jc,r[_.string.major]=QE,r[_.array.major]=Ip,r[_.map.major]=kp,r[_.tag.major]=Cp,r[_.float.major]=xd,r}var Zc=HB(),Pp=new gd,vd=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(`${Ap} object contains circular references`);return new r(t,e)}},es={null:new Q(_.null,null),undefined:new Q(_.undefined,void 0),true:new Q(_.true,!0),false:new Q(_.false,!1),emptyArray:new Q(_.array,0),emptyMap:new Q(_.map,0)},So={number(r,e,t,n){return!Number.isInteger(r)||!Number.isSafeInteger(r)?new Q(_.float,r):r>=0?new Q(_.uint,r):new Q(_.negint,r)},bigint(r,e,t,n){return r>=BigInt(0)?new Q(_.uint,r):new Q(_.negint,r)},Uint8Array(r,e,t,n){return new Q(_.bytes,r)},string(r,e,t,n){return new Q(_.string,r)},boolean(r,e,t,n){return r?es.true:es.false},null(r,e,t,n){return es.null},undefined(r,e,t,n){return es.undefined},ArrayBuffer(r,e,t,n){return new Q(_.bytes,new Uint8Array(r))},DataView(r,e,t,n){return new Q(_.bytes,new Uint8Array(r.buffer,r.byteOffset,r.byteLength))},Array(r,e,t,n){if(!r.length)return t.addBreakTokens===!0?[es.emptyArray,new Q(_.break)]:es.emptyArray;n=vd.createCheck(n,r);let o=[],i=0;for(let s of r)o[i++]=Qc(s,t,n);return t.addBreakTokens?[new Q(_.array,r.length),o,new Q(_.break)]:[new Q(_.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=vd.createCheck(n,r);let c=!o&&t.ignoreUndefinedProperties,l=0;for(let u of i){let d=o?r.get(u):r[u];c&&d===void 0||(a[l++]=[Qc(u,t,n),Qc(d,t,n)])}l<s&&(a.length=l)}return a?.length?(qB(a,t),t.addBreakTokens?[new Q(_.map,a.length),a,new Q(_.break)]:[new Q(_.map,a.length),a]):t.addBreakTokens===!0?[es.emptyMap,new Q(_.break)]:es.emptyMap},Tagged(r,e,t,n){return[new Q(_.tag,r.tag),Qc(r.value,t,n)]}};So.Map=So.Object;So.Buffer=So.Uint8Array;for(let r of"Uint8Clamped Uint16 Uint32 Int8 Int16 Int32 BigUint64 BigInt64 Float32 Float64".split(" "))So[`${r}Array`]=So.DataView;function Qc(r,e={},t){let n=my(r),o=e&&e.typeEncoders&&e.typeEncoders[n]||So[n];if(typeof o=="function"){let s=o(r,n,e,t);if(s!=null)return s}let i=So[n];if(!i)throw new Error(`${Ap} unsupported type: ${n}`);return i(r,n,e,t)}function qB(r,e){e.mapSorter&&r.sort(e.mapSorter)}function zB(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=Zc[o].compareTokens(t,n);return i===0&&console.warn("WARNING: complex key types used, CBOR key sorting guarantees are gone"),i}function WB(r,e){if(r[0]instanceof Q&&e[0]instanceof Q){let t=r[0],n=e[0];return t._keyBytes||(t._keyBytes=Av(t.value)),n._keyBytes||(n._keyBytes=Av(n.value)),vp(t._keyBytes,n._keyBytes)}throw new Error("rfc8949MapSorter: complex key types are not supported yet")}function Av(r){return Rv(r,Zc,kv)}function Ed(r,e,t,n){if(Array.isArray(e))for(let o of e)Ed(r,o,t,n);else t[e.type.major](r,e,n)}var Tv=_.uint.majorEncoded,_v=_.negint.majorEncoded,GB=_.bytes.majorEncoded,jB=_.string.majorEncoded,Iv=_.array.majorEncoded,YB=_.float.majorEncoded|yy,XB=_.float.majorEncoded|wy,QB=_.float.majorEncoded|by,ZB=_.float.majorEncoded|xy,JB=BigInt(-1),eM=BigInt(1);function tM(r){return r.addBreakTokens!==!0}function Cv(r,e,t,n){let o=my(e),i=t.typeEncoders&&t.typeEncoders[o];if(i){let s=i(e,o,t,n);if(s!=null){Ed(r,s,Zc,t);return}}switch(o){case"null":r.push([QB]);return;case"undefined":r.push([ZB]);return;case"boolean":r.push([e?XB:YB]);return;case"number":!Number.isInteger(e)||!Number.isSafeInteger(e)?xd(r,new Q(_.float,e),t):e>=0?it(r,Tv,e):it(r,_v,e*-1-1);return;case"bigint":e>=BigInt(0)?it(r,Tv,e):it(r,_v,e*JB-eM);return;case"string":{let s=Ep(e);it(r,jB,s.length),r.push(s);return}case"Uint8Array":it(r,GB,e.length),r.push(e);return;case"Array":if(!e.length){r.push([Iv]);return}n=vd.createCheck(n,e),it(r,Iv,e.length);for(let s of e)Cv(r,s,t,n);return;case"Object":case"Map":{let s=So.Object(e,o,t,n);Ed(r,s,Zc,t)}return;default:{let s=So[o];if(!s)throw new Error(`${Ap} unsupported type: ${o}`);let a=s(e,o,t,n);Ed(r,a,Zc,t)}}}function Rv(r,e,t,n){let o=n instanceof Uint8Array,i=o?new Sp(n):Pp,s=Qc(r,t);if(!Array.isArray(s)&&t.quickEncodeToken){let a=t.quickEncodeToken(s);if(a)return o?(i.push(a),i.toBytes()):a;let c=e[s.type.major];if(c.encodedSize){let l=c.encodedSize(s,t);if(o||(i=new gd(l)),c(i,s,t),i.chunks.length!==1)throw new Error(`Unexpected error: pre-calculated length for ${s} was wrong`);return o?i.toBytes():md(i.chunks[0])}}return i.reset(),Ed(i,s,e,t),i.toBytes(!0)}function Ty(r,e){return e=Object.assign({},KB,e),tM(e)?(Pp.reset(),Cv(Pp,r,e,void 0),Pp.toBytes(!0)):Rv(r,Zc,e)}var rM={strict:!1,allowIndefinite:!0,allowUndefined:!0,allowBigInt:!0},Lp=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=jn[e];if(t===void 0){let n=j[e];if(!n)throw new Error(`${ue} 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}},ts=Symbol.for("DONE"),Jc=Symbol.for("BREAK");function nM(r,e,t){let n=[];for(let o=0;o<r.value;o++){let i=rs(e,t);if(i===Jc){if(r.value===1/0)break;throw new Error(`${ue} got unexpected break to lengthed array`)}if(i===ts)throw new Error(`${ue} found array but not enough entries (got ${o}, expected ${r.value})`);n[o]=i}return n}function oM(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=rs(e,t);if(c===Jc){if(r.value===1/0)break;throw new Error(`${ue} got unexpected break to lengthed map`)}if(c===ts)throw new Error(`${ue} found map but not enough entries (got ${a} [no key], expected ${r.value})`);if(!n&&typeof c!="string")throw new Error(`${ue} non-string keys not supported (got ${typeof c})`);if(o&&(n&&s.has(c)||!n&&Object.hasOwn(i,c)))throw new Error(`${ue} found repeat map key "${c}"`);let l=rs(e,t);if(l===ts)throw new Error(`${ue} found map but not enough entries (got ${a} [no value], expected ${r.value})`);n?s.set(c,l):i[c]=l}return n?s:i}function*iM(r,e,t){for(let n=0;n<r.value;n++){let o=rs(e,t);if(o===Jc){if(r.value===1/0)break;throw new Error(`${ue} got unexpected break to lengthed map`)}if(o===ts)throw new Error(`${ue} found map but not enough entries (got ${n} [no key], expected ${r.value})`);let i=rs(e,t);if(i===ts)throw new Error(`${ue} found map but not enough entries (got ${n} [no value], expected ${r.value})`);yield[o,i]}}function sM(r,e){let t=!1,n=function(){if(t)throw new Error(`${ue} tag decode() may only be called once`);t=!0;let o=rs(r,e);if(o===ts)throw new Error(`${ue} tag content missing`);if(o===Jc)throw new Error(`${ue} got unexpected break in tag content`);return o};return n.entries=function(){if(t)throw new Error(`${ue} tag decode() may only be called once`);t=!0;let o=r.next();if(!_.equals(o.type,_.map))throw new Error(`${ue} entries() requires map content, got ${o.type.name}`);let i=[];for(let s of iM(o,r,e))i.push(s);return i},Object.defineProperty(n,"_called",{get(){return t},enumerable:!1}),n}function rs(r,e){if(r.done())return ts;let t=r.next();if(_.equals(t.type,_.break))return Jc;if(t.type.terminal)return t.value;if(_.equals(t.type,_.array))return nM(t,r,e);if(_.equals(t.type,_.map))return oM(t,r,e);if(_.equals(t.type,_.tag)){if(e.tags&&typeof e.tags[t.value]=="function"){let n=sM(r,e),o=e.tags[t.value](n);if(!n._called)throw new Error(`${ue} tag decoder must call decode() or entries()`);return o}throw new Error(`${ue} tag not supported (${t.value})`)}throw new Error("unsupported")}function Pv(r,e){if(!(r instanceof Uint8Array))throw new Error(`${ue} data to decode must be a Uint8Array`);e=Object.assign({},rM,e);let t=md(r),n=e.tokenizer||new Lp(t,e),o=rs(n,e);if(o===ts)throw new Error(`${ue} did not find any content to decode`);if(o===Jc)throw new Error(`${ue} got unexpected break`);return[o,r.subarray(n.pos())]}function _y(r,e){let[t,n]=Pv(r,e);if(n.length>0)throw new Error(`${ue} too many terminals, data makes no sense`);return t}var Np=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(Np.prototype,Symbol.toStringTag,{value:"Tagged"});var Lv=42;function Nv(r){return r instanceof ArrayBuffer?new Uint8Array(r,0,r.byteLength):r}function cM(r){if(r.asCID!==r&&r["/"]!==r.bytes)return null;let e=J.asCID(r);if(!e)return null;let t=new Uint8Array(e.bytes.byteLength+1);return t.set(e.bytes,1),[new Q(_.tag,Lv),new Q(_.bytes,t)]}function lM(){throw new Error("`undefined` is not supported by the IPLD Data Model and cannot be encoded")}function uM(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 dM(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 Iy={float64:!0,typeEncoders:{Map:dM,Object:cM,undefined:lM,number:uM}},fM={...Iy,typeEncoders:{...Iy.typeEncoders}};function hM(r){let e=r();if(e[0]!==0)throw new Error("Invalid CID for CBOR tag 42; expected leading 0x00");return J.decode(e.subarray(1))}var ky={allowIndefinite:!1,coerceUndefinedToNull:!0,allowNaN:!1,allowInfinity:!1,allowBigInt:!0,strict:!0,useMaps:!1,rejectDuplicateMapKeys:!0,tags:{[Lv]:hM}},pM={...ky,tags:{...ky.tags}},mM="dag-cbor",Cy=113,gM=r=>Ty(r,Iy),yM=r=>_y(Nv(r),ky);var Gy={};wt(Gy,{code:()=>Wy,decode:()=>$S,encode:()=>FS,format:()=>tU,name:()=>eU,parse:()=>nU,stringify:()=>tU});var wM=["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 Dv(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=bM(r);return t||"Object"}function bM(r){let e=Object.prototype.toString.call(r).slice(8,-1);if(wM.includes(e))return e}var w=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}};w.uint=new w(0,"uint",!0);w.negint=new w(1,"negint",!0);w.bytes=new w(2,"bytes",!0);w.string=new w(3,"string",!0);w.array=new w(4,"array",!1);w.map=new w(5,"map",!1);w.tag=new w(6,"tag",!1);w.float=new w(7,"float",!0);w.false=new w(7,"false",!0);w.true=new w(7,"true",!0);w.null=new w(7,"null",!0);w.undefined=new w(7,"undefined",!0);w.break=new w(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 Sd=globalThis.process&&!globalThis.process.browser&&globalThis.Buffer&&typeof globalThis.Buffer.isBuffer=="function",xM=new TextEncoder;function Dp(r){return Sd&&globalThis.Buffer.isBuffer(r)}function Aa(r){return r instanceof Uint8Array?Dp(r)?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):r:Uint8Array.from(r)}var EM=24,vM=200,Ad=Sd?r=>r.length>=EM?globalThis.Buffer.from(r):Ov(r):r=>r.length>=vM?xM.encode(r):Ov(r),Ao=r=>Uint8Array.from(r),Mv=Sd?(r,e,t)=>Dp(r)?new Uint8Array(r.subarray(e,t)):r.slice(e,t):(r,e,t)=>r.slice(e,t),Uv=Sd?(r,e)=>(r=r.map(t=>t instanceof Uint8Array?t:globalThis.Buffer.from(t)),Aa(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},Fv=Sd?r=>globalThis.Buffer.allocUnsafe(r):r=>new Uint8Array(r);function Op(r,e){if(Dp(r)&&Dp(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 Ov(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 Bv=4096;function $v(r){let e=r.length;if(e<=Bv)return String.fromCharCode.apply(String,r);let t="",n=0;for(;n<e;)t+=String.fromCharCode.apply(String,r.slice(n,n+=Bv));return t}var SM=256,Td=class{constructor(e=SM){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=Fv(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=Mv(n,0,this.cursor)}else t=Uv(this.chunks,this.cursor);return e&&this.reset(),t}},Bp=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 ee="CBOR decode error:",ii="CBOR encode error:",_d=[];_d[23]=1;_d[24]=2;_d[25]=3;_d[26]=5;_d[27]=9;function si(r,e,t){if(r.length-e<t)throw new Error(`${ee} not enough data for type`)}var Ut=[24,256,65536,4294967296,BigInt("18446744073709551616")];function Yr(r,e,t){si(r,e,1);let n=r[e];if(t.strict===!0&&n<Ut[0])throw new Error(`${ee} integer encoded in more bytes than necessary (strict decode)`);return n}function Xr(r,e,t){si(r,e,2);let n=r[e]<<8|r[e+1];if(t.strict===!0&&n<Ut[1])throw new Error(`${ee} integer encoded in more bytes than necessary (strict decode)`);return n}function Qr(r,e,t){si(r,e,4);let n=r[e]*16777216+(r[e+1]<<16)+(r[e+2]<<8)+r[e+3];if(t.strict===!0&&n<Ut[2])throw new Error(`${ee} integer encoded in more bytes than necessary (strict decode)`);return n}function Zr(r,e,t){si(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<Ut[3])throw new Error(`${ee} 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(`${ee} integers outside of the safe integer range are not supported`)}function Vv(r,e,t,n){return new K(w.uint,Yr(r,e+1,n),2)}function Kv(r,e,t,n){return new K(w.uint,Xr(r,e+1,n),3)}function Hv(r,e,t,n){return new K(w.uint,Qr(r,e+1,n),5)}function qv(r,e,t,n){return new K(w.uint,Zr(r,e+1,n),9)}function xn(r,e){return Ft(r,0,e.value)}function Ft(r,e,t){if(t<Ut[0]){let n=Number(t);r.push([e|n])}else if(t<Ut[1]){let n=Number(t);r.push([e|24,n])}else if(t<Ut[2]){let n=Number(t);r.push([e|25,n>>>8,n&255])}else if(t<Ut[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<Ut[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(`${ee} encountered BigInt larger than allowable range`)}}xn.encodedSize=function(e){return Ft.encodedSize(e.value)};Ft.encodedSize=function(e){return e<Ut[0]?1:e<Ut[1]?2:e<Ut[2]?3:e<Ut[3]?5:9};xn.compareTokens=function(e,t){return e.value<t.value?-1:e.value>t.value?1:0};function zv(r,e,t,n){return new K(w.negint,-1-Yr(r,e+1,n),2)}function Wv(r,e,t,n){return new K(w.negint,-1-Xr(r,e+1,n),3)}function Gv(r,e,t,n){return new K(w.negint,-1-Qr(r,e+1,n),5)}var Py=BigInt(-1),jv=BigInt(1);function Yv(r,e,t,n){let o=Zr(r,e+1,n);if(typeof o!="bigint"){let i=-1-o;if(i>=Number.MIN_SAFE_INTEGER)return new K(w.negint,i,9)}if(n.allowBigInt!==!0)throw new Error(`${ee} integers outside of the safe integer range are not supported`);return new K(w.negint,Py-BigInt(o),9)}function Mp(r,e){let t=e.value,n=typeof t=="bigint"?t*Py-jv:t*-1-1;Ft(r,e.type.majorEncoded,n)}Mp.encodedSize=function(e){let t=e.value,n=typeof t=="bigint"?t*Py-jv:t*-1-1;return n<Ut[0]?1:n<Ut[1]?2:n<Ut[2]?3:n<Ut[3]?5:9};Mp.compareTokens=function(e,t){return e.value<t.value?1:e.value>t.value?-1:0};function Id(r,e,t,n){si(r,e,t+n);let o=r.slice(e+t,e+t+n);return new K(w.bytes,o,t+n)}function Xv(r,e,t,n){return Id(r,e,1,t)}function Qv(r,e,t,n){return Id(r,e,2,Yr(r,e+1,n))}function Zv(r,e,t,n){return Id(r,e,3,Xr(r,e+1,n))}function Jv(r,e,t,n){return Id(r,e,5,Qr(r,e+1,n))}function eS(r,e,t,n){let o=Zr(r,e+1,n);if(typeof o=="bigint")throw new Error(`${ee} 64-bit integer bytes lengths not supported`);return Id(r,e,9,o)}function Up(r){return r.encodedBytes===void 0&&(r.encodedBytes=w.equals(r.type,w.string)?Ad(r.value):r.value),r.encodedBytes}function el(r,e){let t=Up(e);Ft(r,e.type.majorEncoded,t.length),r.push(t)}el.encodedSize=function(e){let t=Up(e);return Ft.encodedSize(t.length)+t.length};el.compareTokens=function(e,t){return TM(Up(e),Up(t))};function TM(r,e){return r.length<e.length?-1:r.length>e.length?1:Op(r,e)}var tS=new TextDecoder,IM=32;function kM(r,e,t){if(t-e<IM){let o="";for(let i=e;i<t;i++){let s=r[i];if(s&128)return tS.decode(r.subarray(e,t));o+=String.fromCharCode(s)}return o}return tS.decode(r.subarray(e,t))}function kd(r,e,t,n,o){let i=t+n;si(r,e,i);let s=new K(w.string,kM(r,e+t,e+i),i);return o.retainStringBytes===!0&&(s.byteValue=r.slice(e+t,e+i)),s}function rS(r,e,t,n){return kd(r,e,1,t,n)}function nS(r,e,t,n){return kd(r,e,2,Yr(r,e+1,n),n)}function oS(r,e,t,n){return kd(r,e,3,Xr(r,e+1,n),n)}function iS(r,e,t,n){return kd(r,e,5,Qr(r,e+1,n),n)}function sS(r,e,t,n){let o=Zr(r,e+1,n);if(typeof o=="bigint")throw new Error(`${ee} 64-bit integer string lengths not supported`);return kd(r,e,9,o,n)}var aS=el;function tl(r,e,t,n){return new K(w.array,n,t)}function cS(r,e,t,n){return tl(r,e,1,t)}function lS(r,e,t,n){return tl(r,e,2,Yr(r,e+1,n))}function uS(r,e,t,n){return tl(r,e,3,Xr(r,e+1,n))}function dS(r,e,t,n){return tl(r,e,5,Qr(r,e+1,n))}function fS(r,e,t,n){let o=Zr(r,e+1,n);if(typeof o=="bigint")throw new Error(`${ee} 64-bit integer array lengths not supported`);return tl(r,e,9,o)}function hS(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${ee} indefinite length items not allowed`);return tl(r,e,1,1/0)}function Fp(r,e){Ft(r,w.array.majorEncoded,e.value)}Fp.compareTokens=xn.compareTokens;Fp.encodedSize=function(e){return Ft.encodedSize(e.value)};function rl(r,e,t,n){return new K(w.map,n,t)}function pS(r,e,t,n){return rl(r,e,1,t)}function mS(r,e,t,n){return rl(r,e,2,Yr(r,e+1,n))}function gS(r,e,t,n){return rl(r,e,3,Xr(r,e+1,n))}function yS(r,e,t,n){return rl(r,e,5,Qr(r,e+1,n))}function wS(r,e,t,n){let o=Zr(r,e+1,n);if(typeof o=="bigint")throw new Error(`${ee} 64-bit integer map lengths not supported`);return rl(r,e,9,o)}function bS(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${ee} indefinite length items not allowed`);return rl(r,e,1,1/0)}function $p(r,e){Ft(r,w.map.majorEncoded,e.value)}$p.compareTokens=xn.compareTokens;$p.encodedSize=function(e){return Ft.encodedSize(e.value)};function xS(r,e,t,n){return new K(w.tag,t,1)}function ES(r,e,t,n){return new K(w.tag,Yr(r,e+1,n),2)}function vS(r,e,t,n){return new K(w.tag,Xr(r,e+1,n),3)}function SS(r,e,t,n){return new K(w.tag,Qr(r,e+1,n),5)}function AS(r,e,t,n){return new K(w.tag,Zr(r,e+1,n),9)}function Vp(r,e){Ft(r,w.tag.majorEncoded,e.value)}Vp.compareTokens=xn.compareTokens;Vp.encodedSize=function(e){return Ft.encodedSize(e.value)};var Ly=20,Ny=21,Dy=22,Oy=23;function TS(r,e,t,n){if(n.allowUndefined===!1)throw new Error(`${ee} undefined values are not supported`);return n.coerceUndefinedToNull===!0?new K(w.null,null,1):new K(w.undefined,void 0,1)}function _S(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${ee} indefinite length items not allowed`);return new K(w.break,void 0,1)}function By(r,e,t){if(t){if(t.allowNaN===!1&&Number.isNaN(r))throw new Error(`${ee} NaN values are not supported`);if(t.allowInfinity===!1&&(r===1/0||r===-1/0))throw new Error(`${ee} Infinity values are not supported`)}return new K(w.float,r,e)}function IS(r,e,t,n){return By(My(r,e+1),3,n)}function kS(r,e,t,n){return By(Uy(r,e+1),5,n)}function CS(r,e,t,n){return By(NS(r,e+1),9,n)}function Kp(r,e,t){let n=e.value;if(n===!1)r.push([w.float.majorEncoded|Ly]);else if(n===!0)r.push([w.float.majorEncoded|Ny]);else if(n===null)r.push([w.float.majorEncoded|Dy]);else if(n===void 0)r.push([w.float.majorEncoded|Oy]);else{let o,i=!1;(!t||t.float64!==!0)&&(PS(n),o=My(Yn,1),n===o||Number.isNaN(n)?(Yn[0]=249,r.push(Yn.slice(0,3)),i=!0):(LS(n),o=Uy(Yn,1),n===o&&(Yn[0]=250,r.push(Yn.slice(0,5)),i=!0))),i||(NM(n),o=NS(Yn,1),Yn[0]=251,r.push(Yn.slice(0,9)))}}Kp.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){PS(n);let o=My(Yn,1);if(n===o||Number.isNaN(n))return 3;if(LS(n),o=Uy(Yn,1),n===o)return 5}return 9};var RS=new ArrayBuffer(9),En=new DataView(RS,1),Yn=new Uint8Array(RS,0);function PS(r){if(r===1/0)En.setUint16(0,31744,!1);else if(r===-1/0)En.setUint16(0,64512,!1);else if(Number.isNaN(r))En.setUint16(0,32256,!1);else{En.setFloat32(0,r);let e=En.getUint32(0),t=(e&2139095040)>>23,n=e&8388607;if(t===255)En.setUint16(0,31744,!1);else if(t===0)En.setUint16(0,(e&2147483648)>>16|n>>13,!1);else{let o=t-127;o<-24?En.setUint16(0,0):o<-14?En.setUint16(0,(e&2147483648)>>16|1<<24+o,!1):En.setUint16(0,(e&2147483648)>>16|o+15<<10|n>>13,!1)}}}function My(r,e){if(r.length-e<2)throw new Error(`${ee} 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 LS(r){En.setFloat32(0,r,!1)}function Uy(r,e){if(r.length-e<4)throw new Error(`${ee} not enough data for float32`);let t=(r.byteOffset||0)+e;return new DataView(r.buffer,t,4).getFloat32(0,!1)}function NM(r){En.setFloat64(0,r,!1)}function NS(r,e){if(r.length-e<8)throw new Error(`${ee} not enough data for float64`);let t=(r.byteOffset||0)+e;return new DataView(r.buffer,t,8).getFloat64(0,!1)}Kp.compareTokens=xn.compareTokens;function Be(r,e,t){throw new Error(`${ee} encountered invalid minor (${t}) for major ${r[e]>>>5}`)}function Hp(r){return()=>{throw new Error(`${ee} ${r}`)}}var Y=[];for(let r=0;r<=23;r++)Y[r]=Be;Y[24]=Vv;Y[25]=Kv;Y[26]=Hv;Y[27]=qv;Y[28]=Be;Y[29]=Be;Y[30]=Be;Y[31]=Be;for(let r=32;r<=55;r++)Y[r]=Be;Y[56]=zv;Y[57]=Wv;Y[58]=Gv;Y[59]=Yv;Y[60]=Be;Y[61]=Be;Y[62]=Be;Y[63]=Be;for(let r=64;r<=87;r++)Y[r]=Xv;Y[88]=Qv;Y[89]=Zv;Y[90]=Jv;Y[91]=eS;Y[92]=Be;Y[93]=Be;Y[94]=Be;Y[95]=Hp("indefinite length bytes/strings are not supported");for(let r=96;r<=119;r++)Y[r]=rS;Y[120]=nS;Y[121]=oS;Y[122]=iS;Y[123]=sS;Y[124]=Be;Y[125]=Be;Y[126]=Be;Y[127]=Hp("indefinite length bytes/strings are not supported");for(let r=128;r<=151;r++)Y[r]=cS;Y[152]=lS;Y[153]=uS;Y[154]=dS;Y[155]=fS;Y[156]=Be;Y[157]=Be;Y[158]=Be;Y[159]=hS;for(let r=160;r<=183;r++)Y[r]=pS;Y[184]=mS;Y[185]=gS;Y[186]=yS;Y[187]=wS;Y[188]=Be;Y[189]=Be;Y[190]=Be;Y[191]=bS;for(let r=192;r<=215;r++)Y[r]=xS;Y[216]=ES;Y[217]=vS;Y[218]=SS;Y[219]=AS;Y[220]=Be;Y[221]=Be;Y[222]=Be;Y[223]=Be;for(let r=224;r<=243;r++)Y[r]=Hp("simple values are not supported");Y[244]=Be;Y[245]=Be;Y[246]=Be;Y[247]=TS;Y[248]=Hp("simple values are not supported");Y[249]=IS;Y[250]=kS;Y[251]=CS;Y[252]=Be;Y[253]=Be;Y[254]=Be;Y[255]=_S;var Xn=[];for(let r=0;r<24;r++)Xn[r]=new K(w.uint,r,1);for(let r=-1;r>=-24;r--)Xn[31-r]=new K(w.negint,r,1);Xn[64]=new K(w.bytes,new Uint8Array(0),1);Xn[96]=new K(w.string,"",1);Xn[128]=new K(w.array,0,1);Xn[160]=new K(w.map,0,1);Xn[244]=new K(w.false,!1,1);Xn[245]=new K(w.true,!0,1);Xn[246]=new K(w.null,null,1);function DS(r){switch(r.type){case w.false:return Ao([244]);case w.true:return Ao([245]);case w.null:return Ao([246]);case w.bytes:return r.value.length?void 0:Ao([64]);case w.string:return r.value===""?Ao([96]):void 0;case w.array:return r.value===0?Ao([128]):void 0;case w.map:return r.value===0?Ao([160]):void 0;case w.uint:return r.value<24?Ao([Number(r.value)]):void 0;case w.negint:if(r.value>=-24)return Ao([31-Number(r.value)])}}var BS=Object.freeze({float64:!0,mapSorter:FM,quickEncodeToken:DS});function OM(){let r=[];return r[w.uint.major]=xn,r[w.negint.major]=Mp,r[w.bytes.major]=el,r[w.string.major]=aS,r[w.array.major]=Fp,r[w.map.major]=$p,r[w.tag.major]=Vp,r[w.float.major]=Kp,r}var BM=OM(),MM=new Td,qp=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(`${ii} object contains circular references`);return new r(t,e)}},ns={null:new K(w.null,null),undefined:new K(w.undefined,void 0),true:new K(w.true,!0),false:new K(w.false,!1),emptyArray:new K(w.array,0),emptyMap:new K(w.map,0)},os={number(r,e,t,n){return!Number.isInteger(r)||!Number.isSafeInteger(r)?new K(w.float,r):r>=0?new K(w.uint,r):new K(w.negint,r)},bigint(r,e,t,n){return r>=BigInt(0)?new K(w.uint,r):new K(w.negint,r)},Uint8Array(r,e,t,n){return new K(w.bytes,r)},string(r,e,t,n){return new K(w.string,r)},boolean(r,e,t,n){return r?ns.true:ns.false},null(r,e,t,n){return ns.null},undefined(r,e,t,n){return ns.undefined},ArrayBuffer(r,e,t,n){return new K(w.bytes,new Uint8Array(r))},DataView(r,e,t,n){return new K(w.bytes,new Uint8Array(r.buffer,r.byteOffset,r.byteLength))},Array(r,e,t,n){if(!r.length)return t.addBreakTokens===!0?[ns.emptyArray,new K(w.break)]:ns.emptyArray;n=qp.createCheck(n,r);let o=[],i=0;for(let s of r)o[i++]=nl(s,t,n);return t.addBreakTokens?[new K(w.array,r.length),o,new K(w.break)]:[new K(w.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=qp.createCheck(n,r);let c=!o&&t.ignoreUndefinedProperties,l=0;for(let u of i){let d=o?r.get(u):r[u];c&&d===void 0||(a[l++]=[nl(u,t,n),nl(d,t,n)])}l<s&&(a.length=l)}return a?.length?(UM(a,t),t.addBreakTokens?[new K(w.map,a.length),a,new K(w.break)]:[new K(w.map,a.length),a]):t.addBreakTokens===!0?[ns.emptyMap,new K(w.break)]:ns.emptyMap},Tagged(r,e,t,n){return[new K(w.tag,r.tag),nl(r.value,t,n)]}};os.Map=os.Object;os.Buffer=os.Uint8Array;for(let r of"Uint8Clamped Uint16 Uint32 Int8 Int16 Int32 BigUint64 BigInt64 Float32 Float64".split(" "))os[`${r}Array`]=os.DataView;function nl(r,e={},t){let n=Dv(r),o=e&&e.typeEncoders&&e.typeEncoders[n]||os[n];if(typeof o=="function"){let s=o(r,n,e,t);if(s!=null)return s}let i=os[n];if(!i)throw new Error(`${ii} unsupported type: ${n}`);return i(r,n,e,t)}function UM(r,e){e.mapSorter&&r.sort(e.mapSorter)}function FM(r,e){if(r[0]instanceof K&&e[0]instanceof K){let t=r[0],n=e[0];return t._keyBytes||(t._keyBytes=OS(t.value)),n._keyBytes||(n._keyBytes=OS(n.value)),Op(t._keyBytes,n._keyBytes)}throw new Error("rfc8949MapSorter: complex key types are not supported yet")}function OS(r){return Fy(r,BM,BS)}function MS(r,e,t,n){if(Array.isArray(e))for(let o of e)MS(r,o,t,n);else t[e.type.major](r,e,n)}var Noe=w.uint.majorEncoded,Doe=w.negint.majorEncoded,Ooe=w.bytes.majorEncoded,Boe=w.string.majorEncoded,Moe=w.array.majorEncoded,Uoe=w.float.majorEncoded|Ly,Foe=w.float.majorEncoded|Ny,$oe=w.float.majorEncoded|Dy,Voe=w.float.majorEncoded|Oy,Koe=BigInt(-1),Hoe=BigInt(1);function Fy(r,e,t,n){let o=n instanceof Uint8Array,i=o?new Bp(n):MM,s=nl(r,t);if(!Array.isArray(s)&&t.quickEncodeToken){let a=t.quickEncodeToken(s);if(a)return o?(i.push(a),i.toBytes()):a;let c=e[s.type.major];if(c.encodedSize){let l=c.encodedSize(s,t);if(o||(i=new Td(l)),c(i,s,t),i.chunks.length!==1)throw new Error(`Unexpected error: pre-calculated length for ${s} was wrong`);return o?i.toBytes():Aa(i.chunks[0])}}return i.reset(),MS(i,s,e,t),i.toBytes(!0)}var $M={strict:!1,allowIndefinite:!0,allowUndefined:!0,allowBigInt:!0},zp=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=Xn[e];if(t===void 0){let n=Y[e];if(!n)throw new Error(`${ee} 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}},is=Symbol.for("DONE"),ol=Symbol.for("BREAK");function VM(r,e,t){let n=[];for(let o=0;o<r.value;o++){let i=ss(e,t);if(i===ol){if(r.value===1/0)break;throw new Error(`${ee} got unexpected break to lengthed array`)}if(i===is)throw new Error(`${ee} found array but not enough entries (got ${o}, expected ${r.value})`);n[o]=i}return n}function KM(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=ss(e,t);if(c===ol){if(r.value===1/0)break;throw new Error(`${ee} got unexpected break to lengthed map`)}if(c===is)throw new Error(`${ee} found map but not enough entries (got ${a} [no key], expected ${r.value})`);if(!n&&typeof c!="string")throw new Error(`${ee} non-string keys not supported (got ${typeof c})`);if(o&&(n&&s.has(c)||!n&&Object.hasOwn(i,c)))throw new Error(`${ee} found repeat map key "${c}"`);let l=ss(e,t);if(l===is)throw new Error(`${ee} found map but not enough entries (got ${a} [no value], expected ${r.value})`);n?s.set(c,l):i[c]=l}return n?s:i}function*HM(r,e,t){for(let n=0;n<r.value;n++){let o=ss(e,t);if(o===ol){if(r.value===1/0)break;throw new Error(`${ee} got unexpected break to lengthed map`)}if(o===is)throw new Error(`${ee} found map but not enough entries (got ${n} [no key], expected ${r.value})`);let i=ss(e,t);if(i===is)throw new Error(`${ee} found map but not enough entries (got ${n} [no value], expected ${r.value})`);yield[o,i]}}function qM(r,e){let t=!1,n=function(){if(t)throw new Error(`${ee} tag decode() may only be called once`);t=!0;let o=ss(r,e);if(o===is)throw new Error(`${ee} tag content missing`);if(o===ol)throw new Error(`${ee} got unexpected break in tag content`);return o};return n.entries=function(){if(t)throw new Error(`${ee} tag decode() may only be called once`);t=!0;let o=r.next();if(!w.equals(o.type,w.map))throw new Error(`${ee} entries() requires map content, got ${o.type.name}`);let i=[];for(let s of HM(o,r,e))i.push(s);return i},Object.defineProperty(n,"_called",{get(){return t},enumerable:!1}),n}function ss(r,e){if(r.done())return is;let t=r.next();if(w.equals(t.type,w.break))return ol;if(t.type.terminal)return t.value;if(w.equals(t.type,w.array))return VM(t,r,e);if(w.equals(t.type,w.map))return KM(t,r,e);if(w.equals(t.type,w.tag)){if(e.tags&&typeof e.tags[t.value]=="function"){let n=qM(r,e),o=e.tags[t.value](n);if(!n._called)throw new Error(`${ee} tag decoder must call decode() or entries()`);return o}throw new Error(`${ee} tag not supported (${t.value})`)}throw new Error("unsupported")}function $y(r,e){if(!(r instanceof Uint8Array))throw new Error(`${ee} data to decode must be a Uint8Array`);e=Object.assign({},$M,e);let t=Aa(r),n=e.tokenizer||new zp(t,e),o=ss(n,e);if(o===is)throw new Error(`${ee} did not find any content to decode`);if(o===ol)throw new Error(`${ee} got unexpected break`);return[o,r.subarray(n.pos())]}function Vy(r,e){let[t,n]=$y(r,e);if(n.length>0)throw new Error(`${ee} too many terminals, data makes no sense`);return t}var Wp=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(Wp.prototype,Symbol.toStringTag,{value:"Tagged"});var Ky=class extends Array{constructor(){super(),this.inRecursive=[]}prefix(e){let t=this.inRecursive[this.inRecursive.length-1];t&&(w.equals(t.type,w.array)&&(t.elements++,t.elements!==1&&e.push([44])),w.equals(t.type,w.map)&&(t.elements++,t.elements!==1&&(t.elements%2===1?e.push([44]):e.push([58]))))}[w.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)}[w.negint.major](e,t){this[w.uint.major](e,t)}[w.bytes.major](e,t){throw new Error(`${ii} unsupported type: Uint8Array`)}[w.string.major](e,t){this.prefix(e);let n=Ad(JSON.stringify(t.value));e.push(n.length>32?Aa(n):n)}[w.array.major](e,t){this.prefix(e),this.inRecursive.push({type:w.array,elements:0}),e.push([91])}[w.map.major](e,t){this.prefix(e),this.inRecursive.push({type:w.map,elements:0}),e.push([123])}[w.tag.major](e,t){}[w.float.major](e,t){if(t.type.name==="break"){let s=this.inRecursive.pop();if(s){if(w.equals(s.type,w.array))e.push([93]);else if(w.equals(s.type,w.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(`${ii} 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 zM(r,e){if(Array.isArray(r[0])||Array.isArray(e[0]))throw new Error(`${ii} complex map keys are not supported`);let t=r[0],n=e[0];if(t.type!==w.string||n.type!==w.string)throw new Error(`${ii} non-string map keys are not supported`);if(t<n)return-1;if(t>n)return 1;throw new Error(`${ii} unexpected duplicate map keys, this is not supported`)}var WM={addBreakTokens:!0,mapSorter:zM};function Hy(r,e){return e=Object.assign({},WM,e),Fy(r,new Ky,e)}var il=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(`${ee} 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(`${ee} 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 K(w.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(`${ee} unexpected token at position ${this._pos}`);if(!this.done()&&this.ch()===46){if(n)throw new Error(`${ee} 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 K(w.float,s,this._pos-e):this.options.allowBigInt!==!0||Number.isSafeInteger(s)?new K(s>=0?w.uint:w.negint,s,this._pos-e):new K(s>=0?w.uint:w.negint,BigInt(i),this._pos-e)}parseString(){if(this.ch()!==34)throw new Error(`${ee} 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 K(w.string,c,s)}}let e=this._pos,t=[],n=()=>{if(this._pos+4>=this.data.length)throw new Error(`${ee} 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(`${ee} 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(`${ee} unexpected unicode sequence at position ${this._pos}`);let c,l,u,d;switch(a){case 1:i<128&&(s=i);break;case 2:c=this.data[this._pos+1],(c&192)===128&&(d=(i&31)<<6|c&63,d>127&&(s=d));break;case 3:c=this.data[this._pos+1],l=this.data[this._pos+2],(c&192)===128&&(l&192)===128&&(d=(i&15)<<12|(c&63)<<6|l&63,d>2047&&(d<55296||d>57343)&&(s=d));break;case 4:c=this.data[this._pos+1],l=this.data[this._pos+2],u=this.data[this._pos+3],(c&192)===128&&(l&192)===128&&(u&192)===128&&(d=(i&15)<<18|(c&63)<<12|(l&63)<<6|u&63,d>65535&&d<1114112&&(s=d))}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(`${ee} 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(`${ee} unexpected string escape character at position ${this._pos}`)}break;case 34:return this._pos++,new K(w.string,$v(t),this._pos-e);default:if(i<32)throw new Error(`${ee} invalid control character at position ${this._pos}`);i<128?(t.push(i),this._pos++):o()}}throw new Error(`${ee} unexpected end of string at position ${this._pos}`)}parseValue(){switch(this.ch()){case 123:return this.modeStack.push("obj-start"),this._pos++,new K(w.map,1/0,1);case 91:return this.modeStack.push("array-start"),this._pos++,new K(w.array,1/0,1);case 34:return this.parseString();case 110:return this.expect([110,117,108,108]),new K(w.null,null,4);case 102:return this.expect([102,97,108,115,101]),new K(w.false,!1,5);case 116:return this.expect([116,114,117,101]),new K(w.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(`${ee} 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 K(w.break,void 0,1);if(this.ch()!==44)throw new Error(`${ee} 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 K(w.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 K(w.break,void 0,1);if(this.ch()!==44)throw new Error(`${ee} 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 K(w.break,void 0,1);let e=this.parseString();if(this.skipWhitespace(),this.ch()!==58)throw new Error(`${ee} 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(`${ee} unexpected parse state at position ${this._pos}; this shouldn't happen`)}}};function qy(r,e){return e=Object.assign({tokenizer:new il(r,e)},e),Vy(r,e)}function jM(r){return r instanceof ArrayBuffer?new Uint8Array(r,0,r.byteLength):r}function YM(r){if(r.asCID!==r&&r["/"]!==r.bytes)return null;let e=J.asCID(r);if(!e)return null;let t=e.toString();return[new K(w.map,1/0,1),new K(w.string,"/",1),new K(w.string,t,t.length),new K(w.break,void 0,1)]}function Gp(r){let e=xt.encode(r).slice(1);return[new K(w.map,1/0,1),new K(w.string,"/",1),new K(w.map,1/0,1),new K(w.string,"bytes",5),new K(w.string,e,e.length),new K(w.break,void 0,1),new K(w.break,void 0,1)]}function Qn(r){return Gp(new Uint8Array(r.buffer,r.byteOffset,r.byteLength))}function XM(r){return Gp(new Uint8Array(r))}function QM(){throw new Error("`undefined` is not supported by the IPLD Data Model and cannot be encoded")}function ZM(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 JM={typeEncoders:{Object:YM,Buffer:Gp,Uint8Array:Gp,Int8Array:Qn,Uint16Array:Qn,Int16Array:Qn,Uint32Array:Qn,Int32Array:Qn,Float32Array:Qn,Float64Array:Qn,Uint8ClampedArray:Qn,BigInt64Array:Qn,BigUint64Array:Qn,DataView:Qn,ArrayBuffer:XM,undefined:QM,number:ZM}},zy=class extends il{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(w.equals(e.type,w.map)){let t=this._next();if(w.equals(t.type,w.string)&&t.value==="/"){let n=this._next();if(w.equals(n.type,w.string)){let o=this._next();if(!w.equals(o.type,w.break))throw new Error("Invalid encoded CID form");return this.tokenBuffer.push(n),new K(w.tag,42,0)}if(w.equals(n.type,w.map)){let o=this._next();if(w.equals(o.type,w.string)&&o.value==="bytes"){let i=this._next();if(w.equals(i.type,w.string)){for(let a=0;a<2;a++){let c=this._next();if(!w.equals(c.type,w.break))throw new Error("Invalid encoded Bytes form")}let s=xt.decode(`m${i.value}`);return new K(w.bytes,s,i.value.length)}this.tokenBuffer.push(i)}this.tokenBuffer.push(o)}this.tokenBuffer.push(n)}this.tokenBuffer.push(t)}return e}},US={allowIndefinite:!1,allowUndefined:!1,allowNaN:!1,allowInfinity:!1,allowBigInt:!0,strict:!0,useMaps:!1,rejectDuplicateMapKeys:!0,tags:{42:r=>J.parse(r())}},eU="dag-json",Wy=297,FS=r=>Hy(r,JM),$S=r=>{let e=jM(r),t=Object.assign(US,{tokenizer:new zy(e,US)});return qy(e,t)},tU=r=>rU.decode(FS(r));var rU=new TextDecoder,nU=r=>$S(oU.encode(r)),oU=new TextEncoder;var Jy={};wt(Jy,{code:()=>Zy,createLink:()=>XS,createNode:()=>YS,decode:()=>yU,encode:()=>gU,name:()=>mU,prepare:()=>Xy,validate:()=>Qy});var iU=new TextDecoder;function jy(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 jp(r,e){let t;[t,e]=jy(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 VS(r,e){let t;return[t,e]=jy(r,e),[t&7,t>>3,e]}function sU(r){let e={},t=r.length,n=0;for(;n<t;){let o,i;if([o,i,n]=VS(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]=jp(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]=jp(r,n),e.Name=iU.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]=jy(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 KS(r){let e=r.length,t=0,n,o=!1,i;for(;t<e;){let a,c;if([a,c,t]=VS(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]=jp(r,t),n&&(o=!0)}else if(c===2){if(o)throw new Error("protobuf: (PBNode) duplicate Links section");n||(n=[]);let l;[l,t]=jp(r,t),n.push(sU(l))}else throw new Error(`protobuf: (PBNode) invalid fieldNumber, expected 1 or 2, got ${c}`)}if(t>e)throw new Error("protobuf: (PBNode) unexpected end of data");let s={};return i&&(s.Data=i),s.Links=n||[],s}var qS=new TextEncoder,HS=2**32,aU=2**31;function cU(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=Cd(e,t,r.Tsize)-1,e[t]=24}if(typeof r.Name=="string"){let n=qS.encode(r.Name);t-=n.length,e.set(n,t),t=Cd(e,t,n.length)-1,e[t]=18}return r.Hash&&(t-=r.Hash.length,e.set(r.Hash,t),t=Cd(e,t,r.Hash.length)-1,e[t]=10),e.length-t}function zS(r){let e=uU(r),t=new Uint8Array(e),n=e;if(r.Data&&(n-=r.Data.length,t.set(r.Data,n),n=Cd(t,n,r.Data.length)-1,t[n]=10),r.Links)for(let o=r.Links.length-1;o>=0;o--){let i=cU(r.Links[o],t.subarray(0,n));n-=i,n=Cd(t,n,i)-1,t[n]=18}return t}function lU(r){let e=0;if(r.Hash){let t=r.Hash.length;e+=1+t+sl(t)}if(typeof r.Name=="string"){let t=qS.encode(r.Name).length;e+=1+t+sl(t)}return typeof r.Tsize=="number"&&(e+=1+sl(r.Tsize)),e}function uU(r){let e=0;if(r.Data){let t=r.Data.length;e+=1+t+sl(t)}if(r.Links)for(let t of r.Links){let n=lU(t);e+=1+n+sl(n)}return e}function Cd(r,e,t){e-=sl(t);let n=e;for(;t>=aU;)r[e++]=t&127|128,t/=128;for(;t>=128;)r[e++]=t&127|128,t>>>=7;return r[e]=t,n}function sl(r){return r%2===0&&r++,Math.floor((dU(r)+6)/7)}function dU(r){let e=0;return r>=HS&&(r=Math.floor(r/HS),e=32),r>=65536&&(r>>>=16,e+=16),r>=256&&(r>>>=8,e+=8),e+fU[r]}var fU=[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 hU=["Data","Links"],pU=["Hash","Name","Tsize"],Yy=new TextEncoder;function GS(r,e){if(r===e)return 0;let t=r.Name?Yy.encode(r.Name):[],n=e.Name?Yy.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 WS(r,e){return!Object.keys(r).some(t=>!e.includes(t))}function jS(r){if(typeof r.asCID=="object"){let t=J.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=J.asCID(r.Hash);try{t||(typeof r.Hash=="string"?t=J.parse(r.Hash):r.Hash instanceof Uint8Array&&(t=J.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 Xy(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=Yy.encode(r.Data);else if(r.Data instanceof Uint8Array)e.Data=r.Data;else throw new TypeError("Invalid DAG-PB form");if(r.Links!==void 0)if(Array.isArray(r.Links))e.Links=r.Links.map(jS),e.Links.sort(GS);else throw new TypeError("Invalid DAG-PB form");else e.Links=[];return e}function Qy(r){if(!r||typeof r!="object"||Array.isArray(r)||r instanceof Uint8Array||r["/"]&&r["/"]===r.bytes)throw new TypeError("Invalid DAG-PB form");if(!WS(r,hU))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(!WS(t,pU))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&&GS(t,r.Links[e-1])===-1)throw new TypeError("Invalid DAG-PB form (links must be sorted by Name bytes)")}}function YS(r,e=[]){return Xy({Data:r,Links:e})}function XS(r,e,t){return jS({Hash:t,Name:r,Tsize:e})}function QS(r){return r instanceof ArrayBuffer?new Uint8Array(r,0,r.byteLength):r}var mU="dag-pb",Zy=112;function gU(r){Qy(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),zS(e)}function yU(r){let e=QS(r),t=KS(e),n={};return t.Data&&(n.Data=t.Data),t.Links&&(n.Links=t.Links.map(o=>{let i={};try{i.Hash=J.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 al(r){return r?.then!=null}function ZS(r=[],e){let t={[Zy]:Jy,[Ho]:Fs,[Cy]:Ry,[Wy]:Gy,[U3]:bh};return r.forEach(n=>{t[n.code]=n}),async n=>{let o=t[n];if(o==null&&e!=null){let i=e(n);al(i)?o=await i:o=i,t[o.code]=o}if(o!=null)return o;throw new ud(`Could not load codec for ${n}`)}}function JS(r=[],e){let t={[ft.code]:ft,[Eh.code]:Eh,[Et.code]:Et};return r.forEach(n=>{t[n.code]=n}),async n=>{let o=t[n];if(o==null&&e!=null){let i=e(n);al(i)?o=await i:o=i,t[o.code]=o}if(o!=null)return o;throw new ld(`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 vn=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 ai=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 Yp=0,cl=class extends Error{static name="IdentityHashDigestTooLongError";name="IdentityHashDigestTooLongError"},Xp=class extends ai{child;maxDigestLength;constructor(e,t){super(),this.child=e,this.maxDigestLength=t?.maxDigestLength}put(e,t,n){if(e.multihash.code===Yp){if(this.maxDigestLength!=null&&e.multihash.digest.byteLength>this.maxDigestLength)throw new cl(`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===Yp){if(this.maxDigestLength!=null&&e.multihash.digest.byteLength>this.maxDigestLength)throw new cl(`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 vn;yield*this.child.get(e,t)}has(e,t){if(e.multihash.code===Yp){if(this.maxDigestLength!=null&&e.multihash.digest.byteLength>this.maxDigestLength)throw new cl(`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===Yp){if(this.maxDigestLength!=null&&e.multihash.digest.byteLength>this.maxDigestLength)throw new cl(`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 wU(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 ll=wU;function bU(r){return r[Symbol.asyncIterator]!=null}function xU(r,e){let t=0;if(bU(r))return(async function*(){for await(let c of r)await e(c,t++)&&(yield c)})();let n=ll(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 Zn=xU;function EU(r){return r[Symbol.asyncIterator]!=null}function eA(r){return r?.then!=null}function vU(r,e){let t=0;if(EU(r))return(async function*(){for await(let c of r){let l=e(c,t++);eA(l)&&await l,yield c}})();let n=ll(r),{value:o,done:i}=n.next();if(i===!0)return(function*(){})();let s=e(o,t++);if(typeof s?.then=="function")return(async function*(){await s,yield o;for(let c of n){let l=e(c,t++);eA(l)&&await l,yield c}})();let a=e;return(function*(){yield o;for(let c of n)a(c,t++),yield c})()}var e8=vU;var SU=128,ul=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 Xp(e.blockstore,{maxDigestLength:t.maxIdentityHashDigestLength??SU}),this.getHasher=e.getHasher}async put(e,t,n={}){return await this.child.has(e,n)?(n.onProgress?.(new U("blocks:put:duplicate",e)),e):(n.onProgress?.(new U("blocks:put:providers:notify",e)),await Promise.all(this.blockBrokers.map(async o=>o.announce?.(e,n))),n.onProgress?.(new U("blocks:put:blockstore:put",e)),this.child.put(e,t,n))}async*putMany(e,t={}){let n=Zn(e,async({cid:i})=>{let s=await this.child.has(i,t);return s&&t.onProgress?.(new U("blocks:put-many:duplicate",i)),!s}),o=e8(n,async({cid:i})=>{t.onProgress?.(new U("blocks:put-many:providers:notify",i)),await Promise.all(this.blockBrokers.map(async s=>s.announce?.(i,t)))});t.onProgress?.(new U("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 ad("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 U("blocks:get:providers:get",e));let s=await tA(e,this.blockBrokers,i,{...t,log:this.log});t.onProgress?.(new U("blocks:get:blockstore:put",e)),await this.child.put(e,s,t),t.onProgress?.(new U("blocks:get:providers:notify",e)),await Promise.all(this.blockBrokers.map(async a=>a.announce?.(e,t))),yield s;return}t.onProgress?.(new U("blocks:get:blockstore:get",e)),yield*this.child.get(e,t)}async*getMany(e,t={}){t.onProgress?.(new U("blocks:get-many:blockstore:get-many")),yield*this.child.getMany(e8(e,async n=>{let o=await this.child.has(n,t),i=t.offline===!0;if(!o){if(i)throw new ad("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 U("blocks:get-many:providers:get",n));let a=await tA(n,this.blockBrokers,s,{...t,log:this.log});t.onProgress?.(new U("blocks:get-many:blockstore:put",n)),await this.child.put(n,a,t),t.onProgress?.(new U("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 U("blocks:delete:blockstore:delete",e)),await this.child.delete(e,t)}async*deleteMany(e,t={}){t.onProgress?.(new U("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 U("blocks:get-all:blockstore:get-many")),yield*this.child.getAll(e)}};async function tA(r,e,t,n){let o=TU(r,t),i=new AbortController,s=Ee([i.signal,n.signal]);i.signal;let a=[];for(let c of e)AU(c)&&a.push(c);if(a.length===0)throw new xa(`No block brokers capable of retrieving blocks are configured, the CID ${r} cannot be fetched from the network`);try{return await Promise.any(a.map(async c=>{try{let l=!1,u=await c.retrieve(r,{...n,signal:s,validateFn:async d=>{await o(d),n.signal?.throwIfAborted(),l=!0}});return l||(await o(u),n.signal?.throwIfAborted()),u}catch(l){throw n.log.error("could not retrieve verified block for %c from %s - %e",r,c.name,l),l}}))}catch(c){throw new J1(c.errors,`Failed to load block for ${r}`)}finally{i.abort(),s.clear()}}function AU(r){return typeof r.retrieve=="function"}var TU=(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(al(o)?n=await o:n=o,!ce(n.digest,r.multihash.digest))throw new _i("Hash of downloaded block did not match multihash from passed CID")}};var Qp=class extends ul{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=Ee([this.closeController.signal,n.signal]);try{return await super.put(e,t,{...n,signal:o})}finally{o.clear()}}async*putMany(e,t={}){let n=Ee([this.closeController.signal,t.signal]);try{yield*super.putMany(e,{...t,signal:n})}finally{n.clear()}}async*get(e,t={}){let n=Ee([this.closeController.signal,t.signal]);try{yield*super.get(e,{...t,signal:n})}finally{n.clear()}}async*getMany(e,t={}){let n=Ee([this.closeController.signal,t.signal]);try{yield*super.getMany(e,{...t,signal:n})}finally{n.clear()}}async delete(e,t={}){let n=Ee([this.closeController.signal,t.signal]);try{await super.delete(e,{...t,signal:n})}finally{n.clear()}}async*deleteMany(e,t={}){let n=Ee([this.closeController.signal,t.signal]);try{yield*super.deleteMany(e,{...t,signal:n})}finally{n.clear()}}async has(e,t={}){let n=Ee([this.closeController.signal,t.signal]);try{return await super.has(e,{...t,signal:n})}finally{n.clear()}}async*getAll(e={}){let t=Ee([this.closeController.signal,e.signal]);try{yield*super.getAll({...e,signal:t})}finally{t.clear()}}};var Zp=class extends ul{started;constructor(e,t={}){super(e,t),this.started=!1}isStarted(){return this.started}async start(){await Tt(this.child,...this.blockBrokers),this.started=!0}async stop(){await Pt(this.child,...this.blockBrokers),this.started=!1}unwrap(){return this.child}createSession(e,t){if(this.blockBrokers.length===0)throw new xa("No block brokers configured");let n=this.blockBrokers.map(o=>o.createSession?.(t)).filter(o=>o!=null);if(n.length===0)throw new xa(`No configured block brokers support sessions - tried ${this.blockBrokers.map(o=>o.name).join(", ")}`);return new Qp({blockstore:this.child,blockBrokers:n,getHasher:this.getHasher,logger:this.logger},{root:e})}};var _a=class extends we{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=Wt(this.maxProviders),this.initialProviders=[...t.providers??[]]}async retrieve(e,t={}){let n=xt.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=Ie(),s={promise:i.promise,observers:1,queryFilter:Wt(this.cidPeerFilterSize)};this.requests.set(n,s);let a=!1;this.initialPeerSearchComplete==null&&(a=!0,this.log=this.logger.forComponent(`${this.logName}:${e}`),this.initialPeerSearchComplete=this.findProviders(e,this.minProviders,t));let c=!1,l=new Yt({concurrency:this.maxProviders});l.addEventListener("failure",f=>{this.log.error("error querying provider %s, evicting from session - %e",f.detail.job.options.provider,f.detail.error),this.evict(f.detail.job.options.provider)}),l.addEventListener("success",f=>{c=!0,i.resolve(f.detail.result)}),l.addEventListener("idle",()=>{if(c){this.log.trace("session idle, found block");return}if(t.signal?.aborted===!0){this.log.trace("session idle, signal aborted");return}Promise.resolve().then(async()=>{this.log("no session peers had block for for %c, finding new providers",e);for(let f=0;f<this.minProviders&&this.providers.length!==0;f++){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(f=>{this.log.error("could not find new providers for %c - %e",e,f),i.reject(f)})});let u=f=>{let h=this.toFilterKey(f.detail);s.queryFilter.has(h)||(s.queryFilter.add(h),this.emitFoundProviderProgressEvent(e,f.detail,t),l.add(async()=>this.queryProvider(e,f.detail,t),{provider:f.detail}).catch(p=>{t.signal?.aborted!==!0&&this.log.error("error retrieving session block for %c - %e",e,p)}))};if(this.addEventListener("provider",u),a)try{await Ze(this.initialPeerSearchComplete,t.signal),a&&this.log("found initial session peers for %c",e)}catch(f){throw a&&this.log("failed to find initial session peers for %c - %e",e,f),this.requests.delete(n),s.observers>1&&i.reject(f),f}Promise.all([...this.providers].filter(f=>{let h=this.toFilterKey(f),p=s.queryFilter.has(h);return p||s.queryFilter.add(this.toFilterKey(f)),!p}).map(async f=>l.add(async()=>this.queryProvider(e,f,t),{provider:f}))).catch(f=>{t.signal?.aborted!==!0&&this.log.error("error retrieving session block for %c - %e",e,f)});let d=()=>{i.reject(new fr(t.signal?.reason??"Session aborted")),l.abort()};t.signal?.addEventListener("abort",d);try{return await i.promise}finally{this.removeEventListener("provider",u),t.signal?.removeEventListener("abort",d),l.clear(),this.requests.delete(n)}}evict(e){this.evictionFilter.add(this.toFilterKey(e));let t=this.providers.findIndex(n=>this.equals(n,e));t!==-1&&this.providers.splice(t,1)}isEvicted(e){return this.evictionFilter.has(this.toFilterKey(e))}hasProvider(e){return!!(this.providers.find(t=>this.equals(t,e))!=null||this.isEvicted(e))}async addPeer(e,t){let n=await this.convertToProvider(e,"manually-added",t);n==null||this.hasProvider(n)||(this.providers.push(n),this.safeDispatchEvent("provider",{detail:n}))}async findProviders(e,t,n){let o=Ie(),i=0;return Promise.resolve().then(async()=>{this.log("finding %d-%d new provider(s) for %c - %d initial providers",t,this.maxProviders,e,this.initialProviders.length);let s=this,a=async function*(){for(;s.initialProviders.length>0;){let l=s.initialProviders.pop();if(l==null)continue;let u=await s.convertToProvider(l,"manual",n);u!=null&&(yield u)}},c=async function*(){yield*a(),yield*s.findNewProviders(e,n)};for await(let l of c()){if(this.providers.length===this.maxProviders||n.signal?.aborted===!0)break;if(!this.hasProvider(l)&&(this.log("found %d providers, %d in session",i,this.providers.length),this.providers.push(l),this.safeDispatchEvent("provider",{detail:l}),i++,this.providers.length===t&&(this.log("session is ready with %d peer(s), new peers present",this.providers.length),o.resolve()),this.providers.length===this.maxProviders)){this.log("found max session peers %d",this.providers.length);break}}if(this.log("found %d new session peers while trying to find %d, %d in session",i,t,this.providers.length),this.providers.length<t)throw new cd(`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 Jp=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=JS(e.hashers,e.loadHasher),this.getCodec=ZS(e.codecs,e.loadCodec),this.dns=e.dns??Th(),this.metrics=e.metrics,this.libp2p=e.libp2p,this.events=new we;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 rp(t,{routers:(e.routers??[]).flatMap(o=>{typeof o=="function"&&(o=o(t));let i=[o],s=_U(o);s!=null&&i.push(s);let a=IU(o);return a!=null&&i.push(a),i}),providerLookupConcurrency:e.providerLookupConcurrency}),t.blockBrokers=e.blockBrokers.map(o=>o(t));let n=new Zp(t,e);this.pins=new tp(e.datastore,n,this.getCodec),this.blockstore=new bp(n,this.pins,{holdGcLock:e.holdGcLock??!0}),this.datastore=e.datastore}async start(){await _E(this.datastore),await Tt(this.blockstore,this.datastore,this.routing,this.libp2p),this.events.dispatchEvent(new CustomEvent("start",{detail:this}))}async stop(){await Pt(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 Sr(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 U("helia:gc:deleted",i))}catch(s){n.log.error("error during gc - %e",s),e.onProgress?.(new U("helia:gc:error",s))}})()))}finally{t()}this.log("gc finished")}};function _U(r){return r?.[$o]}function IU(r){return r?.[Ko]}function kU(r){return r[Symbol.asyncIterator]!=null}function CU(r,e){let t=0;if(kU(r))return(async function*(){for await(let c of r)yield e(c,t++)})();let n=ll(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 Sn=CU;function RU(r){return r[Symbol.asyncIterator]!=null}function PU(r,e){return RU(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 as=PU;var Rd="/ipfs/bitswap/1.2.0";var dt;(function(r){r.WantBlock="WantBlock",r.WantHave="WantHave"})(dt||(dt={}));var t8;(function(r){r[r.WantBlock=0]="WantBlock",r[r.WantHave=1]="WantHave"})(t8||(t8={}));(function(r){r.codec=()=>ut(t8)})(dt||(dt={}));var Ia;(function(r){let e;r.codec=()=>(e==null&&(e=ye((i,s,a={})=>{a.lengthDelimited!==!1&&s.fork(),i.cid!=null&&i.cid.byteLength>0&&(s.uint32(10),s.bytes(i.cid)),i.priority!=null&&i.priority!==0&&(s.uint32(16),s.int32(i.priority)),i.cancel!=null&&(s.uint32(24),s.bool(i.cancel)),i.wantType!=null&&(s.uint32(32),dt.codec().encode(i.wantType,s)),i.sendDontHave!=null&&(s.uint32(40),s.bool(i.sendDontHave)),a.lengthDelimited!==!1&&s.ldelim()},(i,s,a={})=>{let c={cid:be(0),priority:0},l=s==null?i.len:i.pos+s;for(;i.pos<l;){let u=i.uint32();switch(u>>>3){case 1:{c.cid=i.bytes();break}case 2:{c.priority=i.int32();break}case 3:{c.cancel=i.bool();break}case 4:{c.wantType=dt.codec().decode(i);break}case 5:{c.sendDontHave=i.bool();break}default:{i.skipType(u&7);break}}}return c},function*(i,s,a,c={}){let l=s==null?i.len:i.pos+s;for(;i.pos<l;){let u=i.uint32();switch(u>>>3){case 1:{yield{field:`${a}.cid`,value:i.bytes()};break}case 2:{yield{field:`${a}.priority`,value:i.int32()};break}case 3:{yield{field:`${a}.cancel`,value:i.bool()};break}case 4:{yield{field:`${a}.wantType`,value:dt.codec().decode(i)};break}case 5:{yield{field:`${a}.sendDontHave`,value:i.bool()};break}default:{i.skipType(u&7);break}}}})),e);function t(i){return me(i,r.codec())}r.encode=t;function n(i,s){return pe(i,r.codec(),s)}r.decode=n;function o(i,s){return ge(i,r.codec(),s)}r.stream=o})(Ia||(Ia={}));var Pd;(function(r){let e;r.codec=()=>(e==null&&(e=ye((i,s,a={})=>{if(a.lengthDelimited!==!1&&s.fork(),i.entries!=null&&i.entries.length>0)for(let c of i.entries)s.uint32(10),Ia.codec().encode(c,s);i.full!=null&&(s.uint32(16),s.bool(i.full)),a.lengthDelimited!==!1&&s.ldelim()},(i,s,a={})=>{let c={entries:[]},l=s==null?i.len:i.pos+s;for(;i.pos<l;){let u=i.uint32();switch(u>>>3){case 1:{if(a.limits?.entries!=null&&c.entries.length===a.limits.entries)throw new Se('Decode error - repeated field "entries" had too many elements');c.entries.push(Ia.codec().decode(i,i.uint32(),{limits:a.limits?.entries$}));break}case 2:{c.full=i.bool();break}default:{i.skipType(u&7);break}}}return c},function*(i,s,a,c={}){let l={entries:0},u=s==null?i.len:i.pos+s;for(;i.pos<u;){let d=i.uint32();switch(d>>>3){case 1:{if(c.limits?.entries!=null&&l.entries===c.limits.entries)throw new Se('Streaming decode error - repeated field "entries" had too many elements');for(let f of Ia.codec().stream(i,i.uint32(),`${a}.entries[]`,{limits:c.limits?.entries$}))yield{...f,index:l.entries};l.entries++;break}case 2:{yield{field:`${a}.full`,value:i.bool()};break}default:{i.skipType(d&7);break}}}})),e);function t(i){return me(i,r.codec())}r.encode=t;function n(i,s){return pe(i,r.codec(),s)}r.decode=n;function o(i,s){return ge(i,r.codec(),s)}r.stream=o})(Pd||(Pd={}));var ka;(function(r){let e;r.codec=()=>(e==null&&(e=ye((i,s,a={})=>{a.lengthDelimited!==!1&&s.fork(),i.prefix!=null&&i.prefix.byteLength>0&&(s.uint32(10),s.bytes(i.prefix)),i.data!=null&&i.data.byteLength>0&&(s.uint32(18),s.bytes(i.data)),a.lengthDelimited!==!1&&s.ldelim()},(i,s,a={})=>{let c={prefix:be(0),data:be(0)},l=s==null?i.len:i.pos+s;for(;i.pos<l;){let u=i.uint32();switch(u>>>3){case 1:{c.prefix=i.bytes();break}case 2:{c.data=i.bytes();break}default:{i.skipType(u&7);break}}}return c},function*(i,s,a,c={}){let l=s==null?i.len:i.pos+s;for(;i.pos<l;){let u=i.uint32();switch(u>>>3){case 1:{yield{field:`${a}.prefix`,value:i.bytes()};break}case 2:{yield{field:`${a}.data`,value:i.bytes()};break}default:{i.skipType(u&7);break}}}})),e);function t(i){return me(i,r.codec())}r.encode=t;function n(i,s){return pe(i,r.codec(),s)}r.decode=n;function o(i,s){return ge(i,r.codec(),s)}r.stream=o})(ka||(ka={}));var Jr;(function(r){r.HaveBlock="HaveBlock",r.DoNotHaveBlock="DoNotHaveBlock"})(Jr||(Jr={}));var e0;(function(r){r[r.HaveBlock=0]="HaveBlock",r[r.DoNotHaveBlock=1]="DoNotHaveBlock"})(e0||(e0={}));(function(r){r.codec=()=>ut(e0)})(Jr||(Jr={}));var Ca;(function(r){let e;r.codec=()=>(e==null&&(e=ye((i,s,a={})=>{a.lengthDelimited!==!1&&s.fork(),i.cid!=null&&i.cid.byteLength>0&&(s.uint32(10),s.bytes(i.cid)),i.type!=null&&e0[i.type]!==0&&(s.uint32(16),Jr.codec().encode(i.type,s)),a.lengthDelimited!==!1&&s.ldelim()},(i,s,a={})=>{let c={cid:be(0),type:Jr.HaveBlock},l=s==null?i.len:i.pos+s;for(;i.pos<l;){let u=i.uint32();switch(u>>>3){case 1:{c.cid=i.bytes();break}case 2:{c.type=Jr.codec().decode(i);break}default:{i.skipType(u&7);break}}}return c},function*(i,s,a,c={}){let l=s==null?i.len:i.pos+s;for(;i.pos<l;){let u=i.uint32();switch(u>>>3){case 1:{yield{field:`${a}.cid`,value:i.bytes()};break}case 2:{yield{field:`${a}.type`,value:Jr.codec().decode(i)};break}default:{i.skipType(u&7);break}}}})),e);function t(i){return me(i,r.codec())}r.encode=t;function n(i,s){return pe(i,r.codec(),s)}r.decode=n;function o(i,s){return ge(i,r.codec(),s)}r.stream=o})(Ca||(Ca={}));var Ra;(function(r){let e;r.codec=()=>(e==null&&(e=ye((i,s,a={})=>{if(a.lengthDelimited!==!1&&s.fork(),i.wantlist!=null&&(s.uint32(10),Pd.codec().encode(i.wantlist,s)),i.blocks!=null&&i.blocks.length>0)for(let c of i.blocks)s.uint32(26),ka.codec().encode(c,s);if(i.blockPresences!=null&&i.blockPresences.length>0)for(let c of i.blockPresences)s.uint32(34),Ca.codec().encode(c,s);i.pendingBytes!=null&&i.pendingBytes!==0&&(s.uint32(40),s.int32(i.pendingBytes)),a.lengthDelimited!==!1&&s.ldelim()},(i,s,a={})=>{let c={blocks:[],blockPresences:[],pendingBytes:0},l=s==null?i.len:i.pos+s;for(;i.pos<l;){let u=i.uint32();switch(u>>>3){case 1:{c.wantlist=Pd.codec().decode(i,i.uint32(),{limits:a.limits?.wantlist});break}case 3:{if(a.limits?.blocks!=null&&c.blocks.length===a.limits.blocks)throw new Se('Decode error - repeated field "blocks" had too many elements');c.blocks.push(ka.codec().decode(i,i.uint32(),{limits:a.limits?.blocks$}));break}case 4:{if(a.limits?.blockPresences!=null&&c.blockPresences.length===a.limits.blockPresences)throw new Se('Decode error - repeated field "blockPresences" had too many elements');c.blockPresences.push(Ca.codec().decode(i,i.uint32(),{limits:a.limits?.blockPresences$}));break}case 5:{c.pendingBytes=i.int32();break}default:{i.skipType(u&7);break}}}return c},function*(i,s,a,c={}){let l={blocks:0,blockPresences:0},u=s==null?i.len:i.pos+s;for(;i.pos<u;){let d=i.uint32();switch(d>>>3){case 1:{yield*Pd.codec().stream(i,i.uint32(),`${a}.wantlist`,{limits:c.limits?.wantlist});break}case 3:{if(c.limits?.blocks!=null&&l.blocks===c.limits.blocks)throw new Se('Streaming decode error - repeated field "blocks" had too many elements');for(let f of ka.codec().stream(i,i.uint32(),`${a}.blocks[]`,{limits:c.limits?.blocks$}))yield{...f,index:l.blocks};l.blocks++;break}case 4:{if(c.limits?.blockPresences!=null&&l.blockPresences===c.limits.blockPresences)throw new Se('Streaming decode error - repeated field "blockPresences" had too many elements');for(let f of Ca.codec().stream(i,i.uint32(),`${a}.blockPresences[]`,{limits:c.limits?.blockPresences$}))yield{...f,index:l.blockPresences};l.blockPresences++;break}case 5:{yield{field:`${a}.pendingBytes`,value:i.int32()};break}default:{i.skipType(d&7);break}}}})),e);function t(i){return me(i,r.codec())}r.encode=t;function n(i,s){return pe(i,r.codec(),s)}r.decode=n;function o(i,s){return ge(i,r.codec(),s)}r.stream=o})(Ra||(Ra={}));function rA(r,e){for(let[t,n]of e.wantlist.entries()){let o=r.wantlist.get(t);o!=null&&(o.priority>n.priority&&(n.priority=o.priority),n.cancel=n.cancel??o.cancel,n.wantType=n.wantType??o.wantType,n.sendDontHave=n.sendDontHave??o.sendDontHave),r.wantlist.set(t,n)}for(let[t,n]of e.blockPresences.entries())r.blockPresences.set(t,n);for(let[t,n]of e.blocks.entries())r.blocks.set(t,n);return e.full&&!r.full&&(r.full=!0),r}var t0=class extends Error{static name="BlockTooLargeError";constructor(e="Block too large"){super(e),this.name="BlockTooLargeError"}};var LU=4193648,NU=LU+16;function*nA(r,e){let t=[...r.wantlist.values()],n=[...r.blockPresences.values()],o=[...r.blocks.values()],i=0,s=0,a=0,c=!1;for(;;){let l={wantlist:{full:r.full??!1,entries:[]},blockPresences:[],blocks:[],pendingBytes:0},u=Ra.encode(l).byteLength,{added:d,hasMore:f,newSize:h}=r8(o,l.blocks,a,e,u,DU);a+=d,u=h;let p=f;({added:d,hasMore:f,newSize:h}=r8(n,l.blockPresences,s,e,u,OU)),s+=d,u=h;let y=f;if({added:d,hasMore:f,newSize:h}=r8(t,l.wantlist.entries,i,e,u,BU),i+=d,u=h,c=!p&&!y&&!f,c||(l.wantlist.full=!1),yield Ra.encode(l),c)break}}function r8(r,e,t,n,o,i){let s=0,a=!1;for(let c=t;c<r.length;c++){let l=r[c],u=i(l);if(u>NU)throw new t0("Cannot send block as after encoding it is over the max message size");let d=o+u;if(d>n){a=!0;break}e.push(l),s++,o=d}return{hasMore:a,added:s,newSize:o}}function DU(r){return n8(3,ka.encode(r))}function OU(r){return n8(4,Ca.encode(r))}function BU(r){return n8(1,Ia.encode(r))}function n8(r,e){let t=Ae(r),n=Ae(e.byteLength);return t+n+e.byteLength}var r0=class extends we{log;libp2p;routing;protocols;running;maxInboundStreams;maxOutboundStreams;messageReceiveTimeout;messageSendTimeout;registrarIds;metrics;sendQueue;runOnLimitedConnections;maxOutgoingMessageSize;maxIncomingMessageSize;constructor(e,t={}){super(),this.log=e.logger.forComponent("helia:bitswap:network"),this.libp2p=e.libp2p,this.routing=e.routing,this.protocols=t.protocols??[Rd],this.registrarIds=[],this.running=!1,this._onStream=this._onStream.bind(this),this.maxInboundStreams=t.maxInboundStreams??1024,this.maxOutboundStreams=t.maxOutboundStreams??1024,this.messageReceiveTimeout=t.messageReceiveTimeout??1e4,this.messageSendTimeout=t.messageSendTimeout??1e4,this.runOnLimitedConnections=t.runOnLimitedConnections??!1,this.maxIncomingMessageSize=t.maxIncomingMessageSize??4194304,this.maxOutgoingMessageSize=t.maxOutgoingMessageSize??t.maxIncomingMessageSize??4194304,this.metrics={blocksSent:e.metrics?.registerCounter("helia_bitswap_sent_blocks_total"),dataSent:e.metrics?.registerCounter("helia_bitswap_sent_data_bytes_total")},this.sendQueue=new Qt({concurrency:t.messageSendConcurrency??50,metrics:e.metrics,metricName:"helia_bitswap_message_send_queue"})}async start(){if(this.running)return;this.running=!0,await this.libp2p.handle(this.protocols,this._onStream,{maxInboundStreams:this.maxInboundStreams,maxOutboundStreams:this.maxOutboundStreams,runOnLimitedConnection:this.runOnLimitedConnections});let e={onConnect:t=>{this.safeDispatchEvent("peer:connected",{detail:t})},onDisconnect:t=>{this.safeDispatchEvent("peer:disconnected",{detail:t})}};this.registrarIds=[];for(let t of this.protocols)this.registrarIds.push(await this.libp2p.register(t,e));this.libp2p.getConnections().forEach(t=>{this.safeDispatchEvent("peer:connected",{detail:t.remotePeer})})}async stop(){if(this.running=!1,await this.libp2p.unhandle(this.protocols),this.registrarIds!=null){for(let e of this.registrarIds)this.libp2p.unregister(e);this.registrarIds=[]}}_onStream(e,t){this.running&&Promise.resolve().then(async()=>{this.log("incoming new bitswap %s stream from %p",e.protocol,t.remotePeer);let n=()=>{e.status==="open"?e.abort(new fo(`Incoming Bitswap stream timed out after ${this.messageReceiveTimeout}ms`)):this.log("stream aborted with status %s",e.status)},o=AbortSignal.timeout(this.messageReceiveTimeout);o.addEventListener("abort",n),await e.close({signal:o});let i=jt();e.addEventListener("message",s=>{i.push(s.data)}),e.addEventListener("remoteCloseWrite",()=>{i.end()}),e.addEventListener("close",s=>{s.error!=null&&i.end(s.error)});for await(let s of ga(i,{maxDataLength:this.maxIncomingMessageSize}))try{let a=Ra.decode(s);this.log("incoming new bitswap %s message from %p on stream",e.protocol,t.remotePeer,e.id),this.safeDispatchEvent("bitswap:message",{detail:{peer:t.remotePeer,message:a,connection:t}}),o.removeEventListener("abort",n),o=AbortSignal.timeout(this.messageReceiveTimeout),o.addEventListener("abort",n)}catch(a){this.log.error("error reading incoming bitswap message from %p on stream - %e",t.remotePeer,e.id,a),e.abort(a);break}}).catch(n=>{this.log.error("error handling incoming stream from %p - %e",t.remotePeer,n),e.abort(n)})}async*findProviders(e,t){t?.onProgress?.(new U("bitswap:find-providers",e));for await(let n of this.routing.findProviders(e,t)){if(!await this.libp2p.isDialable(n.multiaddrs,{runOnLimitedConnection:this.runOnLimitedConnections})){this.log("skipping peer %p as they are not dialable - %a",n.id,n.multiaddrs);continue}t?.onProgress?.(new U("bitswap:found-provider",{type:"bitswap",cid:e,provider:n,routing:n.routing})),yield n}}async findAndConnect(e,t){t?.providers!=null&&await Promise.all(t.providers.map(async n=>this.connectTo(n).catch(o=>{this.log.error("could not connect to supplied provider - %e",o)}))),await Sr(Sn(as(this.findProviders(e,t),t?.maxProviders??3),async n=>this.connectTo(n.id,t))).catch(n=>{this.log.error(n)})}async sendMessage(e,t,n){if(!this.running)throw new Error("network isn't running");let o=this.sendQueue.queue.find(i=>e.equals(i.options.peerId)&&i.status==="queued");if(o!=null){o.options.message=rA(o.options.message,t),await o.join(n);return}await this.sendQueue.add(async i=>{let s=i.message;if(s==null)throw new T("No message to send");this.log("sendMessage to %p",e),i.onProgress?.(new U("bitswap:send-wantlist",e));let a=await this.libp2p.dialProtocol(e,Rd,i);await a.closeRead(i);try{for(let c of nA(s,this.maxOutgoingMessageSize))a.send(ti.single(c))||await a.onDrain(i);await a.close(i)}catch(c){this.log.error("error sending message to %p - %e",e,c),i?.onProgress?.(new U("bitswap:send-wantlist:error",{peer:e,error:c})),a.abort(c)}this._updateSentStats(s.blocks)},{onProgress:n?.onProgress,peerId:e,signal:n?.signal??AbortSignal.timeout(this.messageSendTimeout),message:t})}async connectTo(e,t){if(!this.running)throw new Rn("Network isn't running");t?.onProgress?.(new U("bitswap:dial",e));let[n]=await Promise.all([this.libp2p.dial(e,t),br(this.libp2p,"peer:identify",t?.signal,{filter:o=>{if(!o.detail.peerId.equals(e))return!1;if(o.detail.protocols.includes(Rd))return!0;throw new tc(`${e} did not support ${Rd}`)}})]);return n}_updateSentStats(e){let t=0;for(let n of e.values())t+=n.data.byteLength;this.metrics.dataSent?.increment(t),this.metrics.blocksSent?.increment(e.size)}};var oA=Symbol.for("nodejs.util.inspect.custom"),WU=114,Ld=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()})`}[ph]=!0;toString(){return this.string==null&&(this.string=Ye.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return J.createV1(WU,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")}[oA](){return`PeerId(${this.toString()})`}},Nd=class extends Ld{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}},Dd=class extends Ld{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.publicKey}},Od=class extends Ld{type="secp256k1";publicKey;constructor(e){super({...e,type:"secp256k1"}),this.publicKey=e.publicKey}},GU=2336,Bd=class{type="url";multihash;publicKey;url;constructor(e){this.url=e.toString(),this.multihash=Et.digest(L(this.url))}[oA](){return`PeerId(${this.url})`}[ph]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return J.createV1(GU,this.toMultihash())}toJSON(){return this.toString()}equals(e){return e==null?!1:(e instanceof Uint8Array&&(e=D(e)),e.toString()===this.toString())}};var jU=114,iA=2336;function et(r,e){let t;if(r.charAt(0)==="1"||r.charAt(0)==="Q")t=Ge(Ye.decode(`z${r}`));else{if(r.startsWith("k51qzi5uqu5")||r.startsWith("kzwfwjn5ji4")||r.startsWith("k2k4r8")||r.startsWith("bafz"))return en(J.parse(r));if(e==null)throw new T('Please pass a multibase decoder for strings that do not start with "1" or "Q"');t=Ge(e.decode(r))}return yt(t)}function To(r){if(r.type==="Ed25519")return new Dd({multihash:r.toCID().multihash,publicKey:r});if(r.type==="secp256k1")return new Od({multihash:r.toCID().multihash,publicKey:r});if(r.type==="RSA")return new Nd({multihash:r.toCID().multihash,publicKey:r});throw new Pn}function sA(r){return To(r.publicKey)}function yt(r){if(XU(r))return new Nd({multihash:r});if(YU(r))try{let e=Zh(r);if(e.type==="Ed25519")return new Dd({multihash:r,publicKey:e});if(e.type==="secp256k1")return new Od({multihash:r,publicKey:e})}catch{let t=D(r.digest);return new Bd(new URL(t))}throw new _i("Supplied PeerID Multihash is invalid")}function en(r){if(r?.multihash==null||r.version==null||r.version===1&&r.code!==jU&&r.code!==iA)throw new lh("Supplied PeerID CID is invalid");if(r.code===iA){let e=D(r.multihash.digest);return new Bd(new URL(e))}return yt(r.multihash)}function YU(r){return r.code===Et.code}function XU(r){return r.code===ft.code}function Pa(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 n0(r){let e=Ge(Ye.decode(`z${r}`));return yt(e)}var ar=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 Pa(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 Pa(this.map.values(),e=>e.key)}values(){return Pa(this.map.values(),e=>e.value)}get size(){return this.map.size}};var tn=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 Pa(this.set.entries(),e=>{let t=n0(e[0]);return[t,t]})}forEach(e){this.set.forEach(t=>{let n=n0(t);e(n,n,this)})}has(e){return this.set.has(e.toString())}values(){return Pa(this.set.values(),e=>n0(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}};function o8(){return new tn}var o0=class{filter;constructor(e,t){this.filter=Wt(e,t)}has(e){return this.filter.has(e.toMultihash().bytes)}add(e){this.filter.add(e.toMultihash().bytes)}remove(e){this.filter.remove?.(e.toMultihash().bytes)}};function i8(r,e=.001){return new o0(r,e)}var s8=class extends ar{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 ci(r){let{name:e,metrics:t}=r,n;return t!=null?n=new s8({name:e,metrics:t}):n=new ar,n}var li=class{full;pendingBytes;wantlist;blocks;blockPresences;constructor(e=!1,t=0){this.full=e,this.wantlist=new Map,this.blocks=new Map,this.blockPresences=new Map,this.pendingBytes=0}addWantlistEntry(e,t){let n=xt.encode(e.multihash.bytes);this.wantlist.set(n,t)}addBlockPresence(e,t){let n=xt.encode(e.multihash.bytes);this.blockPresences.set(n,t)}addBlock(e,t){let n=xt.encode(e.multihash.bytes);this.blocks.set(n,t)}};function QU(r){let e=new Uint8Array(r.reduce((n,o)=>n+Ae(o),0)),t=0;for(let n of r)e=ir(n,e,t),t+=Ae(n);return e}var aA=QU;function a8(r){return aA([r.version,r.code,r.multihash.code,r.multihash.digest.byteLength])}var i0=class{peerId;blockstore;network;wants;exchangeCount;bytesSent;bytesReceived;lastExchange;maxSizeReplaceHasWithBlock;log;doNotResendBlockWindow;maxWantListSize;constructor(e,t){this.peerId=e.peerId,this.blockstore=e.blockstore,this.network=e.network,this.wants=new Map,this.log=e.logger.forComponent(`helia:bitswap:ledger:${e.peerId}`),this.exchangeCount=0,this.bytesSent=0,this.bytesReceived=0,this.maxSizeReplaceHasWithBlock=t.maxSizeReplaceHasWithBlock??1024,this.doNotResendBlockWindow=t.doNotResendBlockWindow??5e3,this.maxWantListSize=t.maxWantListSize??1024}sentBytes(e){this.exchangeCount++,this.lastExchange=new Date().getTime(),this.bytesSent+=e}receivedBytes(e){this.exchangeCount++,this.lastExchange=new Date().getTime(),this.bytesReceived+=e}debtRatio(){return this.bytesSent/(this.bytesReceived+1)}removeExpiredWants(){this.wants.forEach((e,t)=>{e.expires!=null&&e.expires<Date.now()&&this.wants.delete(t)})}addWants(e){if(e==null)return;e.full===!0&&this.wants.forEach((n,o)=>{n.status==="want"&&this.wants.delete(o)});for(let n of e.entries){let o=J.decode(n.cid),i=D(o.multihash.bytes,"base64");if(n.cancel===!0)this.log("peer %p cancelled want of block for %c",this.peerId,o),this.wants.delete(i);else{n.wantType===dt.WantHave?this.log("peer %p wanted block presence for %c",this.peerId,o):this.log("peer %p wanted block for %c",this.peerId,o);let s=this.wants.get(i);if(s!=null){let a=s.status==="sent"||s.status==="sending",c=s.wantType===dt.WantHave&&(n.wantType==null||n.wantType===dt.WantBlock);a&&c&&(s.status="want"),s.priority=n.priority,s.wantType=n.wantType??dt.WantBlock,s.sendDontHave=n.sendDontHave??!1;continue}this.wants.set(i,{cid:o,priority:n.priority,wantType:n.wantType??dt.WantBlock,sendDontHave:n.sendDontHave??!1,status:"want",created:Date.now()})}}let t=[...this.wants.entries()].filter(([n,o])=>o.status==="want");t.length>this.maxWantListSize&&this.truncateWants(t)}truncateWants(e){e=e.sort((n,o)=>n[1].created<o[1].created?-1:o[1].created<n[1].created?1:0).sort((n,o)=>n[1].haveBlock===!1?-1:o[1].haveBlock===!1?1:0).sort((n,o)=>n[1].priority<o[1].priority?-1:o[1].priority<n[1].priority?1:0);let t=e.length-this.maxWantListSize;for(let n=0;n<t;n++)this.wants.delete(e[n][0])}getWants(){return[...this.wants.values()]}hasWant(e){let t=D(e.multihash.bytes,"base64");return this.wants.has(t)}async sendBlocksToPeer(e){let t=new li,n=new Set;this.removeExpiredWants();let o=[...this.wants.entries()].filter(([i,s])=>s.status==="want");o.forEach(([i,s])=>{s.status="sending"});for(let[i,s]of o)try{let a=await j1(this.blockstore.get(s.cid,e));if(s.status!=="sending")continue;s.wantType===dt.WantHave?a.byteLength<this.maxSizeReplaceHasWithBlock?(this.log("sending have and block for %c",s.cid),n.add(i),t.addBlock(s.cid,{data:a,prefix:a8(s.cid)})):(this.log("sending have for %c",s.cid),t.addBlockPresence(s.cid,{cid:s.cid.bytes,type:Jr.HaveBlock})):(this.log("sending block for %c",s.cid),n.add(i),t.addBlock(s.cid,{data:a,prefix:a8(s.cid)})),s.status="sent",s.expires=Date.now()+this.doNotResendBlockWindow}catch(a){if(a.name!=="NotFoundError")throw a;if(s.status="want",s.haveBlock=!1,this.log("do not have block for %c",s.cid),!s.sendDontHave||s.sentDoNotHave===!0)continue;s.sentDoNotHave=!0,t.addBlockPresence(s.cid,{cid:s.cid.bytes,type:Jr.DoNotHaveBlock})}(t.blocks.size>0||t.blockPresences.size>0)&&(this.log("sending message"),await this.network.sendMessage(this.peerId,t,e),this.log("sent message"),this.sentBytes([...t.blocks.values()].reduce((i,s)=>i+s.data.byteLength,0)))}};var s0=class{blockstore;network;ledgerMap;maxSizeReplaceHasWithBlock;doNotResendBlockWindow;maxWantListSize;log;logger;constructor(e,t={}){this.blockstore=e.blockstore,this.network=e.network,this.maxSizeReplaceHasWithBlock=t.maxSizeReplaceHasWithBlock,this.doNotResendBlockWindow=t.doNotResendBlockWindow,this.maxWantListSize=t.maxWantListSize,this.log=e.logger.forComponent("helia:bitswap:peer-want-lists"),this.logger=e.logger,this.ledgerMap=ci({name:"helia_bitswap_ledger_map",metrics:e.metrics}),this.network.addEventListener("bitswap:message",n=>{this.receiveMessage(n.detail.connection.remotePeer,n.detail.message).catch(o=>{this.log.error("error receiving bitswap message from %p - %e",n.detail.connection.remotePeer,o)})}),this.network.addEventListener("peer:disconnected",n=>{this.peerDisconnected(n.detail)})}ledgerForPeer(e){let t=this.ledgerMap.get(e);if(t!=null)return{peer:t.peerId,value:t.debtRatio(),sent:t.bytesSent,received:t.bytesReceived,exchanged:t.exchangeCount}}wantListForPeer(e){let t=this.ledgerMap.get(e);if(t!=null)return t.removeExpiredWants(),t.getWants()}peers(){return Array.from(this.ledgerMap.values()).map(e=>e.peerId)}async receiveMessage(e,t){let n=this.ledgerMap.get(e);n==null&&(n=new i0({peerId:e,blockstore:this.blockstore,network:this.network,logger:this.logger},{maxSizeReplaceHasWithBlock:this.maxSizeReplaceHasWithBlock,doNotResendBlockWindow:this.doNotResendBlockWindow,maxWantListSize:this.maxWantListSize}),this.ledgerMap.set(e,n)),n.receivedBytes(t.blocks?.reduce((o,i)=>o+i.data.byteLength,0)??0),n.removeExpiredWants(),n.addWants(t.wantlist),this.log("send blocks to peer"),await n.sendBlocksToPeer()}async receivedBlock(e,t){let n=[];for(let o of this.ledgerMap.values())o.hasWant(e)&&n.push(o);await Promise.all(n.map(async o=>o.sendBlocksToPeer(t)))}peerDisconnected(e){this.ledgerMap.delete(e)}};var c8=class extends _a{name="bitswap-session";wantList;network;libp2p;constructor(e,t){super(e,{...t,name:"helia:bitswap:session"}),this.wantList=e.wantList,this.network=e.network,this.libp2p=e.libp2p}async queryProvider(e,t,n){this.log("sending WANT-BLOCK for %c to %p",e,t);let o=await this.wantList.wantSessionBlock(e,t.peerId,n);if(this.log("%p %s %c",t,o.has?"has":"does not have",e),o.has){if(o.block!=null)return o.block;throw new Error("Provider has block but did not send it to us")}throw new Error("Provider did not have block")}async*findNewProviders(e,t={}){for await(let n of this.network.findProviders(e,t))yield{peerId:n.id,routing:n.routing,toString:()=>`Bitswap(${n.id})`}}toFilterKey(e){return e.peerId.toMultihash().bytes}equals(e,t){return e.peerId.equals(t.peerId)}async convertToProvider(e,t,n){if(Rt(e))return{peerId:e,routing:t,toString:()=>`Bitswap(${e})`};if(await this.libp2p.isDialable(e)!==!1)try{let o=await this.libp2p.dial(e,n);return{peerId:o.remotePeer,routing:t,toString:()=>`Bitswap(${o.remotePeer})`}}catch{}}emitFoundProviderProgressEvent(e,t,n){n?.onProgress?.(new U("bitswap:found-provider",{type:"bitswap",cid:e,provider:{id:t.peerId,multiaddrs:[],routing:t.routing},routing:t.routing}))}};function cA(r,e){return new c8(r,e)}var a0=class{blocksReceived;duplicateBlocksReceived;dataReceived;duplicateDataReceived;constructor(e){this.blocksReceived=e.metrics?.registerMetricGroup("helia_bitswap_received_blocks"),this.duplicateBlocksReceived=e.metrics?.registerMetricGroup("helia_bitswap_duplicate_received_blocks"),this.dataReceived=e.metrics?.registerMetricGroup("helia_bitswap_data_received_bytes"),this.duplicateDataReceived=e.metrics?.registerMetricGroup("helia_bitswap_duplicate_data_received_bytes")}updateBlocksReceived(e=1,t){let n={global:e};t!=null&&(n[t.toString()]=e),this.blocksReceived?.increment(n)}updateDuplicateBlocksReceived(e=1,t){let n={global:e};t!=null&&(n[t.toString()]=e),this.duplicateBlocksReceived?.increment(n)}updateDataReceived(e,t){let n={global:e};t!=null&&(n[t.toString()]=e),this.dataReceived?.increment(n)}updateDuplicateDataReceived(e,t){let n={global:e};t!=null&&(n[t.toString()]=e),this.duplicateDataReceived?.increment(n)}};function ZU(r){if(!(r instanceof Uint8Array))throw new Error("arg needs to be a Uint8Array");let e=[];for(;r.length>0;){let t=Ur(r);e.push(t),r=r.slice(Ae(t))}return e}var lA=ZU;var c0=class extends we{peers;wants;network;log;sendWantlistDebounce;sendMessagesTimeout;getHasher;sendingMessages;constructor(e,t={}){super(),this.peers=ci({name:"helia_bitswap_peers",metrics:e.metrics}),this.wants=St({name:"helia_bitswap_wantlist",metrics:e.metrics}),this.network=e.network,this.sendWantlistDebounce=t.sendWantlistDebounce??10,this.log=e.logger.forComponent("helia:bitswap:wantlist"),this.getHasher=e.getHasher,this.network.addEventListener("bitswap:message",n=>{this.receiveMessage(n.detail.connection,n.detail.message).catch(o=>{this.log.error("error receiving bitswap message from %p - %e",n.detail.connection.remotePeer,o)})}),this.network.addEventListener("peer:connected",n=>{this.peerConnected(n.detail).catch(o=>{this.log.error("error processing newly connected bitswap peer %p - %e",n.detail,o)})}),this.network.addEventListener("peer:disconnected",n=>{this.peerDisconnected(n.detail)})}async addEntry(e,t){let n=D(e.multihash.bytes,"base64"),o=this.wants.get(n);o==null&&(o={cid:e,priority:t.priority??1,wantType:t.wantType??dt.WantBlock,cancel:!1,sendDontHave:!0,onProgress:[]},this.wants.set(n,o)),t.onProgress!=null&&o.onProgress.push({onProgress:t.onProgress,signal:t.signal}),o.wantType===dt.WantHave&&t.wantType===dt.WantBlock&&(o.wantType=dt.WantBlock),await this.sendMessagesDebounced();try{return t.wantType===dt.WantBlock?(await br(this,"block",t?.signal,{filter:a=>ce(e.multihash.digest,a.detail.cid.multihash.digest),errorMessage:"Want was aborted"})).detail:(await br(this,"presence",t?.signal,{filter:s=>ce(e.multihash.digest,s.detail.cid.multihash.digest),errorMessage:"Want was aborted"})).detail}finally{t.signal?.aborted===!0&&(this.log("want for %c was aborted, cancelling want",e),o.cancel=!0,await this.sendMessagesDebounced())}}async sendMessagesDebounced(){await this.sendingMessages?.promise,clearTimeout(this.sendMessagesTimeout),this.sendMessagesTimeout=setTimeout(()=>{this.sendMessages().catch(e=>{this.log("error sending messages to peers - %e",e)})},this.sendWantlistDebounce)}async sendMessages(){this.sendingMessages=Ie(),await Promise.all([...this.peers.entries()].map(async([e,t])=>{let n=new Set,o=new li;for(let[i,s]of this.wants.entries())t.has(i)||s.cancel||(n.add(i),o.addWantlistEntry(s.cid,{cid:s.cid.bytes,priority:s.priority,wantType:s.wantType,cancel:s.cancel,sendDontHave:s.sendDontHave}));if(o.wantlist.size!==0)try{await this.network.sendMessage(e,o,{onProgress:i=>{this.wants.forEach(({onProgress:s})=>{s.forEach(({onProgress:a})=>{a(i)})})}});for(let i of n)t.add(i)}catch(i){this.log.error("error sending full wantlist to new peer - %e",i)}})).catch(e=>{this.log.error("error sending messages - %e",e)});for(let[e,t]of this.wants)if(t.cancel){this.wants.delete(e);for(let n of this.peers.values())n.delete(e)}this.sendingMessages.resolve()}has(e){let t=D(e.multihash.bytes,"base64");return this.wants.has(t)}async wantSessionPresence(e,t,n={}){let o=new li;return o.addWantlistEntry(e,{cid:e.bytes,sendDontHave:!0,wantType:dt.WantHave,priority:1}),await this.network.sendMessage(t,o,n),(await br(this,"presence",n.signal,{filter:s=>t.equals(s.detail.sender)&&ce(e.multihash.digest,s.detail.cid.multihash.digest)})).detail}async wantBlock(e,t={}){return this.addEntry(e,{...t,wantType:dt.WantBlock})}async wantSessionBlock(e,t,n={}){let o=new li;return o.addWantlistEntry(e,{cid:e.bytes,sendDontHave:!0,wantType:dt.WantBlock,priority:1}),await this.network.sendMessage(t,o,n),(await br(this,"presence",n.signal,{filter:s=>t.equals(s.detail.sender)&&ce(e.multihash.digest,s.detail.cid.multihash.digest)})).detail}async receivedBlock(e,t){let n=D(e.multihash.bytes,"base64"),o=this.wants.get(n);o!=null&&(o.cancel=!0,await this.sendMessagesDebounced())}async receiveMessage(e,t){this.log("received message from %p with %d blocks",e.remotePeer,t.blocks.length);let n=!1;for(let o of t.blocks){if(o.prefix==null||o.data==null)continue;let i=lA(o.prefix),s=i[0],a=i[1],c=i[2],l=i[3],u=c===ft.code?ft:await this.getHasher(c);if(u==null){this.log.error("unknown hash algorithm",c);continue}let d=u.digest(o.data,{truncate:l});d.then!=null&&(d=await d);let f=J.create(s===0?0:1,a,d);this.log("received block from %p for %c",e.remotePeer,f),this.safeDispatchEvent("block",{detail:{sender:e.remotePeer,cid:f,block:o.data,connection:e}}),this.safeDispatchEvent("presence",{detail:{sender:e.remotePeer,cid:f,has:!0,block:o.data}});let h=D(f.multihash.bytes,"base64"),p=this.wants.get(h);p!=null&&(p.cancel=!0,n=!0)}for(let{cid:o,type:i}of t.blockPresences){let s=J.decode(o);this.log("received %s from %p for %c",i,e.remotePeer,s),this.safeDispatchEvent("presence",{detail:{sender:e.remotePeer,cid:s,has:i===Jr.HaveBlock}})}n&&await this.sendMessagesDebounced()}async peerConnected(e){let t=new Set,n=new li(!0);for(let[o,i]of this.wants.entries())i.cancel||(t.add(o),n.addWantlistEntry(i.cid,{cid:i.cid.bytes,priority:1,wantType:dt.WantBlock,cancel:!1,sendDontHave:!1}));if(n.wantlist.size===0){this.peers.set(e,t);return}try{await this.network.sendMessage(e,n,{onProgress:o=>{this.wants.forEach(({onProgress:i})=>{i.forEach(({onProgress:s})=>{s(o)})})}}),this.peers.set(e,t)}catch(o){this.log.error("error sending full wantlist to new peer %p - %e",e,o)}}peerDisconnected(e){this.peers.delete(e)}start(){}stop(){this.peers.clear(),clearTimeout(this.sendMessagesTimeout)}};var l0=class{log;logger;stats;network;blockstore;peerWantLists;wantList;libp2p;constructor(e,t={}){this.logger=e.logger,this.log=e.logger.forComponent("helia:bitswap"),this.blockstore=e.blockstore,this.libp2p=e.libp2p,this.stats=new a0(e),this.network=new r0(e,t),this.peerWantLists=new s0({...e,network:this.network},t),this.wantList=new c0({...e,network:this.network},t)}createSession(e={}){return cA({wantList:this.wantList,network:this.network,logger:this.logger,libp2p:this.libp2p},e)}async want(e,t={}){let n=new AbortController,o=Ee([n.signal,t.signal]);n.signal,this.network.findAndConnect(e,{...t,signal:o}).catch(i=>{n.signal.aborted||this.log.error("error during finding and connect for cid %c - %e",e,i)});try{let i=await this.wantList.wantBlock(e,{...t,signal:o});return t.onProgress?.(new U("bitswap:block",{cid:e,sender:i.connection.remotePeer})),i.block}finally{n.abort(),o.clear()}}async notify(e,t={}){await Promise.all([this.peerWantLists.receivedBlock(e,t),this.wantList.receivedBlock(e,t)])}getWantlist(){return[...this.wantList.wants.values()].filter(e=>!e.cancel).map(e=>({cid:e.cid,priority:e.priority,wantType:e.wantType}))}getPeerWantlist(e){return this.peerWantLists.wantListForPeer(e)}async start(){this.wantList.start(),await this.network.start()}async stop(){this.wantList.stop(),await this.network.stop()}};var uA=(r,e={})=>new l0(r,e);var l8=class{name="bitswap";bitswap;started;constructor(e,t={}){this.bitswap=uA(e,t),this.started=!1}isStarted(){return this.started}async start(){await this.bitswap.start(),this.started=!0}async stop(){await this.bitswap.stop(),this.started=!1}async announce(e,t){await this.bitswap.notify(e,t)}async retrieve(e,t={}){return this.bitswap.want(e,{...t,onProgress:function(o){if(t?.onProgress!=null)if(t.onProgress(o),o.type==="connection:open"){if(!Rt(o.detail))return;t.onProgress(new U("helia:block-broker:connect",{broker:"bitswap",type:"connect",provider:o.detail,cid:e}))}else o.type==="connection:opened"?t.onProgress(new U("helia:block-broker:connected",{broker:"bitswap",type:"connected",provider:o.detail.remotePeer,address:o.detail.remoteAddr,cid:e})):o.type==="bitswap:send-wantlist"?t.onProgress(new U("helia:block-broker:request-block",{broker:"bitswap",type:"request-block",provider:o.detail,cid:e})):o.type==="bitswap:block"&&t.onProgress(new U("helia:block-broker:receive-block",{broker:"bitswap",type:"receive-block",provider:o.detail.sender,cid:e}))}})}createSession(e){let t=this.bitswap.createSession(e);return{name:"bitswap-session",addPeer:async(n,o)=>{await t.addPeer(n,o)},announce:async(n,o)=>{await this.bitswap.notify(n,o)},retrieve:async(n,o)=>t.retrieve(n,o)}}};function u8(r={}){return e=>new l8(e,r)}var JU=[6,53,56,54,55];function dA(r){return pA("sni",r)?.value}function fA(r){let e=pA("tcp",r)?.value;return e==null?"":`:${e}`}function pA(r,e){return e.find(t=>t.name===r)}function hA(r){return r.some(({code:e})=>e===448)}function Jn(r,e){let t=mA[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 mA={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://${Jn(t,e)}:${r.value}`},udp:(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");return`udp://${Jn(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`${Jn(t,e)}`},p2p:(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");return`${Jn(t,e)}`},http:(r,e)=>{let t=hA(e),n=dA(e),o=fA(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=Jn(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=Jn(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 Jn(t,e)},sni:(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");return Jn(t,e)},https:(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");let n=Jn(t,e);return n=n?.replace("tcp://",""),`https://${n}`},ws:(r,e)=>{let t=hA(e),n=dA(e),o=fA(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=Jn(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=Jn(t,e);return n=n?.replace("tcp://",""),`wss://${n}`}};function cs(r,e){let n=Z(r).getComponents(),o=n.pop();if(o==null)throw new Error("Unexpected end of multiaddr");let i=mA[o.name];if(i==null)throw new Error(`No interpreter found for ${o.name}`);let s=i(o,n)??"";return e?.assumeHttp!==!1&&JU.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 gA="[a-fA-F\\d:]",ls=r=>r&&r.includeBoundaries?`(?:(?<=\\s|^)(?=${gA})|(?<=${gA})(?=\\s|$))`:"",eo="(?: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}",At="[a-fA-F\\d]{1,4}",u0=`
13
+ ${e}[Error list was empty]`,t.trim()}return rx(r,e)}Tr.formatters.e=r=>r==null?"undefined":ox(r);function _O(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 Fc(r){return{forComponent(e){return mn(e,r)}}}function mn(r,e){let t=_O(`${r}:trace`);return Tr.enabled(`${r}:trace`)&&Tr.names.map(n=>n.toString()).find(n=>n.includes(":trace"))!=null&&(t=Tr(`${r}:trace`,e)),Object.assign(Tr(r,e),{error:Tr(`${r}:error`,e),trace:t,newScope:n=>mn(`${r}:${n}`,e)})}function nx(r){if(r!=null&&(r=r.trim(),r.length!==0))return r}var ix=Symbol.for("sindresorhus/unlimited-timeout#brand");function sx(r,e,...t){if(typeof r!="function")throw new TypeError("Expected callback to be a function");e??=0,e=Number(e);let n=!1,o={[ix]:!0,id:void 0,cleared:!1,ref(){return n=!1,o.id?.ref?.(),o},unref(){return n=!0,o.id?.unref?.(),o}};if(e===Number.POSITIVE_INFINITY||e>Number.MAX_SAFE_INTEGER)return o;(!Number.isFinite(e)||e<0)&&(e=0);let i=performance.now()+e,s=a=>{o.cleared||(a<=2147483647?(o.id=globalThis.setTimeout(()=>{o.cleared||r(...t)},a),n&&o.id?.unref?.()):(o.id=globalThis.setTimeout(()=>{let c=performance.now(),l=Math.max(0,i-c);s(l)},2147483647),n&&o.id?.unref?.()))};return s(e),o}function ax(r){!r||typeof r!="object"||!r[ix]||(r.cleared=!0,r.id!==void 0&&(globalThis.clearTimeout(r.id),r.id=void 0))}var IO=new WeakMap;function kO({clearTimeout:r,setTimeout:e}={}){return(t,{value:n,signal:o}={})=>{if(o?.aborted)return Promise.reject(o.reason);let i,s,a,c=r??clearTimeout,l=()=>{c(i),a(o.reason)},u=()=>{o&&o.removeEventListener("abort",l)},d=new Promise((f,h)=>{s=()=>{u(),f(n)},a=h,i=(e??setTimeout)(s,t)});return o&&o.addEventListener("abort",l,{once:!0}),IO.set(d,()=>{c(i),i=null,s()}),d}}var CO=kO({setTimeout:sx,clearTimeout:ax}),cx=CO;var Qt=class extends Yt{has(e){return this.find(e)!=null}find(e){return this.queue.find(t=>e.equals(t.options.peerId))}};var L1=class extends Yt{constructor(e={}){super({...e,sort:(t,n)=>t.options.priority>n.options.priority?-1:t.options.priority<n.options.priority?1:0})}};var $c=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 H6}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 c1("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)}},H6=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}};function Vc(r,e,t){let n,o,i=!1;function s(){let l={signal:o.signal},u;t?.timeout!=null&&(u=Ee([o.signal,AbortSignal.timeout(t.timeout)]),l.signal=u),i=!0,Promise.resolve().then(async()=>{await r(l)}).catch(()=>{}).finally(()=>{u!=null&&(u.aborted?u.clear():u.addEventListener("abort",()=>{u.clear()},{once:!0})),i=!1,!o.signal.aborted&&(n=setTimeout(s,e))})}let a=Qo(s,t?.debounce??100),c=!1;return{setInterval:l=>{e!==l&&(e=l,n!=null&&(clearTimeout(n),n=setTimeout(s,e)))},setTimeout:l=>{t??={},t.timeout=l},run:()=>{i||(clearTimeout(n),a())},start:()=>{c||(c=!0,o=new AbortController,o.signal,t?.runImmediately===!0?queueMicrotask(()=>{s()}):n=setTimeout(s,e))},stop:()=>{clearTimeout(n),o?.abort(),c=!1}}}var q6=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 St(r){let{name:e,metrics:t}=r,n;return t!=null?n=new q6({name:e,metrics:t}):n=new Map,n}var RO=["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 z6(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=PO(r);return t||"Object"}function PO(r){let e=Object.prototype.toString.call(r).slice(8,-1);if(RO.includes(e))return e}var I=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}};I.uint=new I(0,"uint",!0);I.negint=new I(1,"negint",!0);I.bytes=new I(2,"bytes",!0);I.string=new I(3,"string",!0);I.array=new I(4,"array",!1);I.map=new I(5,"map",!1);I.tag=new I(6,"tag",!1);I.float=new I(7,"float",!0);I.false=new I(7,"false",!0);I.true=new I(7,"true",!0);I.null=new I(7,"null",!0);I.undefined=new I(7,"undefined",!0);I.break=new I(7,"break",!0);var te=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 Xu=globalThis.process&&!globalThis.process.browser&&globalThis.Buffer&&typeof globalThis.Buffer.isBuffer=="function",LO=new TextEncoder;function N1(r){return Xu&&globalThis.Buffer.isBuffer(r)}function Qu(r){return r instanceof Uint8Array?N1(r)?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):r:Uint8Array.from(r)}var NO=24,DO=200,D1=Xu?r=>r.length>=NO?globalThis.Buffer.from(r):lx(r):r=>r.length>=DO?LO.encode(r):lx(r),xo=r=>Uint8Array.from(r),ux=Xu?(r,e,t)=>N1(r)?new Uint8Array(r.subarray(e,t)):r.slice(e,t):(r,e,t)=>r.slice(e,t),dx=Xu?(r,e)=>(r=r.map(t=>t instanceof Uint8Array?t:globalThis.Buffer.from(t)),Qu(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},fx=Xu?r=>globalThis.Buffer.allocUnsafe(r):r=>new Uint8Array(r);function O1(r,e){if(N1(r)&&N1(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 lx(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 OO=256,Zu=class{constructor(e=OO){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=fx(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=ux(n,0,this.cursor)}else t=dx(this.chunks,this.cursor);return e&&this.reset(),t}},B1=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 le="CBOR decode error:",M1="CBOR encode error:",Ju=[];Ju[23]=1;Ju[24]=2;Ju[25]=3;Ju[26]=5;Ju[27]=9;function ri(r,e,t){if(r.length-e<t)throw new Error(`${le} not enough data for type`)}var Bt=[24,256,65536,4294967296,BigInt("18446744073709551616")];function $r(r,e,t){ri(r,e,1);let n=r[e];if(t.strict===!0&&n<Bt[0])throw new Error(`${le} integer encoded in more bytes than necessary (strict decode)`);return n}function Vr(r,e,t){ri(r,e,2);let n=r[e]<<8|r[e+1];if(t.strict===!0&&n<Bt[1])throw new Error(`${le} integer encoded in more bytes than necessary (strict decode)`);return n}function Kr(r,e,t){ri(r,e,4);let n=r[e]*16777216+(r[e+1]<<16)+(r[e+2]<<8)+r[e+3];if(t.strict===!0&&n<Bt[2])throw new Error(`${le} integer encoded in more bytes than necessary (strict decode)`);return n}function Hr(r,e,t){ri(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<Bt[3])throw new Error(`${le} 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(`${le} integers outside of the safe integer range are not supported`)}function hx(r,e,t,n){return new te(I.uint,$r(r,e+1,n),2)}function px(r,e,t,n){return new te(I.uint,Vr(r,e+1,n),3)}function mx(r,e,t,n){return new te(I.uint,Kr(r,e+1,n),5)}function gx(r,e,t,n){return new te(I.uint,Hr(r,e+1,n),9)}function gn(r,e){return ot(r,0,e.value)}function ot(r,e,t){if(t<Bt[0]){let n=Number(t);r.push([e|n])}else if(t<Bt[1]){let n=Number(t);r.push([e|24,n])}else if(t<Bt[2]){let n=Number(t);r.push([e|25,n>>>8,n&255])}else if(t<Bt[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<Bt[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(`${le} encountered BigInt larger than allowable range`)}}gn.encodedSize=function(e){return ot.encodedSize(e.value)};ot.encodedSize=function(e){return e<Bt[0]?1:e<Bt[1]?2:e<Bt[2]?3:e<Bt[3]?5:9};gn.compareTokens=function(e,t){return e.value<t.value?-1:e.value>t.value?1:0};function yx(r,e,t,n){return new te(I.negint,-1-$r(r,e+1,n),2)}function wx(r,e,t,n){return new te(I.negint,-1-Vr(r,e+1,n),3)}function bx(r,e,t,n){return new te(I.negint,-1-Kr(r,e+1,n),5)}var W6=BigInt(-1),xx=BigInt(1);function Ex(r,e,t,n){let o=Hr(r,e+1,n);if(typeof o!="bigint"){let i=-1-o;if(i>=Number.MIN_SAFE_INTEGER)return new te(I.negint,i,9)}if(n.allowBigInt!==!0)throw new Error(`${le} integers outside of the safe integer range are not supported`);return new te(I.negint,W6-BigInt(o),9)}function U1(r,e){let t=e.value,n=typeof t=="bigint"?t*W6-xx:t*-1-1;ot(r,e.type.majorEncoded,n)}U1.encodedSize=function(e){let t=e.value,n=typeof t=="bigint"?t*W6-xx:t*-1-1;return n<Bt[0]?1:n<Bt[1]?2:n<Bt[2]?3:n<Bt[3]?5:9};U1.compareTokens=function(e,t){return e.value<t.value?1:e.value>t.value?-1:0};function ed(r,e,t,n){ri(r,e,t+n);let o=r.slice(e+t,e+t+n);return new te(I.bytes,o,t+n)}function vx(r,e,t,n){return ed(r,e,1,t)}function Sx(r,e,t,n){return ed(r,e,2,$r(r,e+1,n))}function Ax(r,e,t,n){return ed(r,e,3,Vr(r,e+1,n))}function Tx(r,e,t,n){return ed(r,e,5,Kr(r,e+1,n))}function _x(r,e,t,n){let o=Hr(r,e+1,n);if(typeof o=="bigint")throw new Error(`${le} 64-bit integer bytes lengths not supported`);return ed(r,e,9,o)}function F1(r){return r.encodedBytes===void 0&&(r.encodedBytes=I.equals(r.type,I.string)?D1(r.value):r.value),r.encodedBytes}function Kc(r,e){let t=F1(e);ot(r,e.type.majorEncoded,t.length),r.push(t)}Kc.encodedSize=function(e){let t=F1(e);return ot.encodedSize(t.length)+t.length};Kc.compareTokens=function(e,t){return MO(F1(e),F1(t))};function MO(r,e){return r.length<e.length?-1:r.length>e.length?1:O1(r,e)}var Ix=new TextDecoder,FO=32;function $O(r,e,t){if(t-e<FO){let o="";for(let i=e;i<t;i++){let s=r[i];if(s&128)return Ix.decode(r.subarray(e,t));o+=String.fromCharCode(s)}return o}return Ix.decode(r.subarray(e,t))}function td(r,e,t,n,o){let i=t+n;ri(r,e,i);let s=new te(I.string,$O(r,e+t,e+i),i);return o.retainStringBytes===!0&&(s.byteValue=r.slice(e+t,e+i)),s}function kx(r,e,t,n){return td(r,e,1,t,n)}function Cx(r,e,t,n){return td(r,e,2,$r(r,e+1,n),n)}function Rx(r,e,t,n){return td(r,e,3,Vr(r,e+1,n),n)}function Px(r,e,t,n){return td(r,e,5,Kr(r,e+1,n),n)}function Lx(r,e,t,n){let o=Hr(r,e+1,n);if(typeof o=="bigint")throw new Error(`${le} 64-bit integer string lengths not supported`);return td(r,e,9,o,n)}var Nx=Kc;function Hc(r,e,t,n){return new te(I.array,n,t)}function Dx(r,e,t,n){return Hc(r,e,1,t)}function Ox(r,e,t,n){return Hc(r,e,2,$r(r,e+1,n))}function Bx(r,e,t,n){return Hc(r,e,3,Vr(r,e+1,n))}function Mx(r,e,t,n){return Hc(r,e,5,Kr(r,e+1,n))}function Ux(r,e,t,n){let o=Hr(r,e+1,n);if(typeof o=="bigint")throw new Error(`${le} 64-bit integer array lengths not supported`);return Hc(r,e,9,o)}function Fx(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${le} indefinite length items not allowed`);return Hc(r,e,1,1/0)}function $1(r,e){ot(r,I.array.majorEncoded,e.value)}$1.compareTokens=gn.compareTokens;$1.encodedSize=function(e){return ot.encodedSize(e.value)};function qc(r,e,t,n){return new te(I.map,n,t)}function $x(r,e,t,n){return qc(r,e,1,t)}function Vx(r,e,t,n){return qc(r,e,2,$r(r,e+1,n))}function Kx(r,e,t,n){return qc(r,e,3,Vr(r,e+1,n))}function Hx(r,e,t,n){return qc(r,e,5,Kr(r,e+1,n))}function qx(r,e,t,n){let o=Hr(r,e+1,n);if(typeof o=="bigint")throw new Error(`${le} 64-bit integer map lengths not supported`);return qc(r,e,9,o)}function zx(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${le} indefinite length items not allowed`);return qc(r,e,1,1/0)}function V1(r,e){ot(r,I.map.majorEncoded,e.value)}V1.compareTokens=gn.compareTokens;V1.encodedSize=function(e){return ot.encodedSize(e.value)};function Wx(r,e,t,n){return new te(I.tag,t,1)}function Gx(r,e,t,n){return new te(I.tag,$r(r,e+1,n),2)}function jx(r,e,t,n){return new te(I.tag,Vr(r,e+1,n),3)}function Yx(r,e,t,n){return new te(I.tag,Kr(r,e+1,n),5)}function Xx(r,e,t,n){return new te(I.tag,Hr(r,e+1,n),9)}function K1(r,e){ot(r,I.tag.majorEncoded,e.value)}K1.compareTokens=gn.compareTokens;K1.encodedSize=function(e){return ot.encodedSize(e.value)};var G6=20,j6=21,Y6=22,X6=23;function Qx(r,e,t,n){if(n.allowUndefined===!1)throw new Error(`${le} undefined values are not supported`);return n.coerceUndefinedToNull===!0?new te(I.null,null,1):new te(I.undefined,void 0,1)}function Zx(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${le} indefinite length items not allowed`);return new te(I.break,void 0,1)}function Q6(r,e,t){if(t){if(t.allowNaN===!1&&Number.isNaN(r))throw new Error(`${le} NaN values are not supported`);if(t.allowInfinity===!1&&(r===1/0||r===-1/0))throw new Error(`${le} Infinity values are not supported`)}return new te(I.float,r,e)}function Jx(r,e,t,n){return Q6(Z6(r,e+1),3,n)}function eE(r,e,t,n){return Q6(J6(r,e+1),5,n)}function tE(r,e,t,n){return Q6(iE(r,e+1),9,n)}function rd(r,e,t){let n=e.value;if(n===!1)r.push([I.float.majorEncoded|G6]);else if(n===!0)r.push([I.float.majorEncoded|j6]);else if(n===null)r.push([I.float.majorEncoded|Y6]);else if(n===void 0)r.push([I.float.majorEncoded|X6]);else{let o,i=!1;(!t||t.float64!==!0)&&(nE(n),o=Z6(zn,1),n===o||Number.isNaN(n)?(zn[0]=249,r.push(zn.slice(0,3)),i=!0):(oE(n),o=J6(zn,1),n===o&&(zn[0]=250,r.push(zn.slice(0,5)),i=!0))),i||(zO(n),o=iE(zn,1),zn[0]=251,r.push(zn.slice(0,9)))}}rd.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){nE(n);let o=Z6(zn,1);if(n===o||Number.isNaN(n))return 3;if(oE(n),o=J6(zn,1),n===o)return 5}return 9};var rE=new ArrayBuffer(9),yn=new DataView(rE,1),zn=new Uint8Array(rE,0);function nE(r){if(r===1/0)yn.setUint16(0,31744,!1);else if(r===-1/0)yn.setUint16(0,64512,!1);else if(Number.isNaN(r))yn.setUint16(0,32256,!1);else{yn.setFloat32(0,r);let e=yn.getUint32(0),t=(e&2139095040)>>23,n=e&8388607;if(t===255)yn.setUint16(0,31744,!1);else if(t===0)yn.setUint16(0,(e&2147483648)>>16|n>>13,!1);else{let o=t-127;o<-24?yn.setUint16(0,0):o<-14?yn.setUint16(0,(e&2147483648)>>16|1<<24+o,!1):yn.setUint16(0,(e&2147483648)>>16|o+15<<10|n>>13,!1)}}}function Z6(r,e){if(r.length-e<2)throw new Error(`${le} 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 oE(r){yn.setFloat32(0,r,!1)}function J6(r,e){if(r.length-e<4)throw new Error(`${le} not enough data for float32`);let t=(r.byteOffset||0)+e;return new DataView(r.buffer,t,4).getFloat32(0,!1)}function zO(r){yn.setFloat64(0,r,!1)}function iE(r,e){if(r.length-e<8)throw new Error(`${le} not enough data for float64`);let t=(r.byteOffset||0)+e;return new DataView(r.buffer,t,8).getFloat64(0,!1)}rd.compareTokens=gn.compareTokens;function De(r,e,t){throw new Error(`${le} encountered invalid minor (${t}) for major ${r[e]>>>5}`)}function H1(r){return()=>{throw new Error(`${le} ${r}`)}}var G=[];for(let r=0;r<=23;r++)G[r]=De;G[24]=hx;G[25]=px;G[26]=mx;G[27]=gx;G[28]=De;G[29]=De;G[30]=De;G[31]=De;for(let r=32;r<=55;r++)G[r]=De;G[56]=yx;G[57]=wx;G[58]=bx;G[59]=Ex;G[60]=De;G[61]=De;G[62]=De;G[63]=De;for(let r=64;r<=87;r++)G[r]=vx;G[88]=Sx;G[89]=Ax;G[90]=Tx;G[91]=_x;G[92]=De;G[93]=De;G[94]=De;G[95]=H1("indefinite length bytes/strings are not supported");for(let r=96;r<=119;r++)G[r]=kx;G[120]=Cx;G[121]=Rx;G[122]=Px;G[123]=Lx;G[124]=De;G[125]=De;G[126]=De;G[127]=H1("indefinite length bytes/strings are not supported");for(let r=128;r<=151;r++)G[r]=Dx;G[152]=Ox;G[153]=Bx;G[154]=Mx;G[155]=Ux;G[156]=De;G[157]=De;G[158]=De;G[159]=Fx;for(let r=160;r<=183;r++)G[r]=$x;G[184]=Vx;G[185]=Kx;G[186]=Hx;G[187]=qx;G[188]=De;G[189]=De;G[190]=De;G[191]=zx;for(let r=192;r<=215;r++)G[r]=Wx;G[216]=Gx;G[217]=jx;G[218]=Yx;G[219]=Xx;G[220]=De;G[221]=De;G[222]=De;G[223]=De;for(let r=224;r<=243;r++)G[r]=H1("simple values are not supported");G[244]=De;G[245]=De;G[246]=De;G[247]=Qx;G[248]=H1("simple values are not supported");G[249]=Jx;G[250]=eE;G[251]=tE;G[252]=De;G[253]=De;G[254]=De;G[255]=Zx;var Wn=[];for(let r=0;r<24;r++)Wn[r]=new te(I.uint,r,1);for(let r=-1;r>=-24;r--)Wn[31-r]=new te(I.negint,r,1);Wn[64]=new te(I.bytes,new Uint8Array(0),1);Wn[96]=new te(I.string,"",1);Wn[128]=new te(I.array,0,1);Wn[160]=new te(I.map,0,1);Wn[244]=new te(I.false,!1,1);Wn[245]=new te(I.true,!0,1);Wn[246]=new te(I.null,null,1);function ey(r){switch(r.type){case I.false:return xo([244]);case I.true:return xo([245]);case I.null:return xo([246]);case I.bytes:return r.value.length?void 0:xo([64]);case I.string:return r.value===""?xo([96]):void 0;case I.array:return r.value===0?xo([128]):void 0;case I.map:return r.value===0?xo([160]):void 0;case I.uint:return r.value<24?xo([Number(r.value)]):void 0;case I.negint:if(r.value>=-24)return xo([31-Number(r.value)])}}var GO={float64:!1,mapSorter:XO,quickEncodeToken:ey},uE=Object.freeze({float64:!0,mapSorter:QO,quickEncodeToken:ey});function jO(){let r=[];return r[I.uint.major]=gn,r[I.negint.major]=U1,r[I.bytes.major]=Kc,r[I.string.major]=Nx,r[I.array.major]=$1,r[I.map.major]=V1,r[I.tag.major]=K1,r[I.float.major]=rd,r}var Wc=jO(),q1=new Zu,od=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(`${M1} object contains circular references`);return new r(t,e)}},Xi={null:new te(I.null,null),undefined:new te(I.undefined,void 0),true:new te(I.true,!0),false:new te(I.false,!1),emptyArray:new te(I.array,0),emptyMap:new te(I.map,0)},Eo={number(r,e,t,n){return!Number.isInteger(r)||!Number.isSafeInteger(r)?new te(I.float,r):r>=0?new te(I.uint,r):new te(I.negint,r)},bigint(r,e,t,n){return r>=BigInt(0)?new te(I.uint,r):new te(I.negint,r)},Uint8Array(r,e,t,n){return new te(I.bytes,r)},string(r,e,t,n){return new te(I.string,r)},boolean(r,e,t,n){return r?Xi.true:Xi.false},null(r,e,t,n){return Xi.null},undefined(r,e,t,n){return Xi.undefined},ArrayBuffer(r,e,t,n){return new te(I.bytes,new Uint8Array(r))},DataView(r,e,t,n){return new te(I.bytes,new Uint8Array(r.buffer,r.byteOffset,r.byteLength))},Array(r,e,t,n){if(!r.length)return t.addBreakTokens===!0?[Xi.emptyArray,new te(I.break)]:Xi.emptyArray;n=od.createCheck(n,r);let o=[],i=0;for(let s of r)o[i++]=zc(s,t,n);return t.addBreakTokens?[new te(I.array,r.length),o,new te(I.break)]:[new te(I.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=od.createCheck(n,r);let c=!o&&t.ignoreUndefinedProperties,l=0;for(let u of i){let d=o?r.get(u):r[u];c&&d===void 0||(a[l++]=[zc(u,t,n),zc(d,t,n)])}l<s&&(a.length=l)}return a?.length?(YO(a,t),t.addBreakTokens?[new te(I.map,a.length),a,new te(I.break)]:[new te(I.map,a.length),a]):t.addBreakTokens===!0?[Xi.emptyMap,new te(I.break)]:Xi.emptyMap},Tagged(r,e,t,n){return[new te(I.tag,r.tag),zc(r.value,t,n)]}};Eo.Map=Eo.Object;Eo.Buffer=Eo.Uint8Array;for(let r of"Uint8Clamped Uint16 Uint32 Int8 Int16 Int32 BigUint64 BigInt64 Float32 Float64".split(" "))Eo[`${r}Array`]=Eo.DataView;function zc(r,e={},t){let n=z6(r),o=e&&e.typeEncoders&&e.typeEncoders[n]||Eo[n];if(typeof o=="function"){let s=o(r,n,e,t);if(s!=null)return s}let i=Eo[n];if(!i)throw new Error(`${M1} unsupported type: ${n}`);return i(r,n,e,t)}function YO(r,e){e.mapSorter&&r.sort(e.mapSorter)}function XO(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=Wc[o].compareTokens(t,n);return i===0&&console.warn("WARNING: complex key types used, CBOR key sorting guarantees are gone"),i}function QO(r,e){if(r[0]instanceof te&&e[0]instanceof te){let t=r[0],n=e[0];return t._keyBytes||(t._keyBytes=sE(t.value)),n._keyBytes||(n._keyBytes=sE(n.value)),O1(t._keyBytes,n._keyBytes)}throw new Error("rfc8949MapSorter: complex key types are not supported yet")}function sE(r){return fE(r,Wc,uE)}function nd(r,e,t,n){if(Array.isArray(e))for(let o of e)nd(r,o,t,n);else t[e.type.major](r,e,n)}var aE=I.uint.majorEncoded,cE=I.negint.majorEncoded,ZO=I.bytes.majorEncoded,JO=I.string.majorEncoded,lE=I.array.majorEncoded,eB=I.float.majorEncoded|G6,tB=I.float.majorEncoded|j6,rB=I.float.majorEncoded|Y6,nB=I.float.majorEncoded|X6,oB=BigInt(-1),iB=BigInt(1);function sB(r){return r.addBreakTokens!==!0}function dE(r,e,t,n){let o=z6(e),i=t.typeEncoders&&t.typeEncoders[o];if(i){let s=i(e,o,t,n);if(s!=null){nd(r,s,Wc,t);return}}switch(o){case"null":r.push([rB]);return;case"undefined":r.push([nB]);return;case"boolean":r.push([e?tB:eB]);return;case"number":!Number.isInteger(e)||!Number.isSafeInteger(e)?rd(r,new te(I.float,e),t):e>=0?ot(r,aE,e):ot(r,cE,e*-1-1);return;case"bigint":e>=BigInt(0)?ot(r,aE,e):ot(r,cE,e*oB-iB);return;case"string":{let s=D1(e);ot(r,JO,s.length),r.push(s);return}case"Uint8Array":ot(r,ZO,e.length),r.push(e);return;case"Array":if(!e.length){r.push([lE]);return}n=od.createCheck(n,e),ot(r,lE,e.length);for(let s of e)dE(r,s,t,n);return;case"Object":case"Map":{let s=Eo.Object(e,o,t,n);nd(r,s,Wc,t)}return;default:{let s=Eo[o];if(!s)throw new Error(`${M1} unsupported type: ${o}`);let a=s(e,o,t,n);nd(r,a,Wc,t)}}}function fE(r,e,t,n){let o=n instanceof Uint8Array,i=o?new B1(n):q1,s=zc(r,t);if(!Array.isArray(s)&&t.quickEncodeToken){let a=t.quickEncodeToken(s);if(a)return o?(i.push(a),i.toBytes()):a;let c=e[s.type.major];if(c.encodedSize){let l=c.encodedSize(s,t);if(o||(i=new Zu(l)),c(i,s,t),i.chunks.length!==1)throw new Error(`Unexpected error: pre-calculated length for ${s} was wrong`);return o?i.toBytes():Qu(i.chunks[0])}}return i.reset(),nd(i,s,e,t),i.toBytes(!0)}function id(r,e){return e=Object.assign({},GO,e),sB(e)?(q1.reset(),dE(q1,r,e,void 0),q1.toBytes(!0)):fE(r,Wc,e)}var aB={strict:!1,allowIndefinite:!0,allowUndefined:!0,allowBigInt:!0},z1=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=Wn[e];if(t===void 0){let n=G[e];if(!n)throw new Error(`${le} 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}},Qi=Symbol.for("DONE"),Gc=Symbol.for("BREAK");function cB(r,e,t){let n=[];for(let o=0;o<r.value;o++){let i=Zi(e,t);if(i===Gc){if(r.value===1/0)break;throw new Error(`${le} got unexpected break to lengthed array`)}if(i===Qi)throw new Error(`${le} found array but not enough entries (got ${o}, expected ${r.value})`);n[o]=i}return n}function lB(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=Zi(e,t);if(c===Gc){if(r.value===1/0)break;throw new Error(`${le} got unexpected break to lengthed map`)}if(c===Qi)throw new Error(`${le} found map but not enough entries (got ${a} [no key], expected ${r.value})`);if(!n&&typeof c!="string")throw new Error(`${le} non-string keys not supported (got ${typeof c})`);if(o&&(n&&s.has(c)||!n&&Object.hasOwn(i,c)))throw new Error(`${le} found repeat map key "${c}"`);let l=Zi(e,t);if(l===Qi)throw new Error(`${le} found map but not enough entries (got ${a} [no value], expected ${r.value})`);n?s.set(c,l):i[c]=l}return n?s:i}function*uB(r,e,t){for(let n=0;n<r.value;n++){let o=Zi(e,t);if(o===Gc){if(r.value===1/0)break;throw new Error(`${le} got unexpected break to lengthed map`)}if(o===Qi)throw new Error(`${le} found map but not enough entries (got ${n} [no key], expected ${r.value})`);let i=Zi(e,t);if(i===Qi)throw new Error(`${le} found map but not enough entries (got ${n} [no value], expected ${r.value})`);yield[o,i]}}function dB(r,e){let t=!1,n=function(){if(t)throw new Error(`${le} tag decode() may only be called once`);t=!0;let o=Zi(r,e);if(o===Qi)throw new Error(`${le} tag content missing`);if(o===Gc)throw new Error(`${le} got unexpected break in tag content`);return o};return n.entries=function(){if(t)throw new Error(`${le} tag decode() may only be called once`);t=!0;let o=r.next();if(!I.equals(o.type,I.map))throw new Error(`${le} entries() requires map content, got ${o.type.name}`);let i=[];for(let s of uB(o,r,e))i.push(s);return i},Object.defineProperty(n,"_called",{get(){return t},enumerable:!1}),n}function Zi(r,e){if(r.done())return Qi;let t=r.next();if(I.equals(t.type,I.break))return Gc;if(t.type.terminal)return t.value;if(I.equals(t.type,I.array))return cB(t,r,e);if(I.equals(t.type,I.map))return lB(t,r,e);if(I.equals(t.type,I.tag)){if(e.tags&&typeof e.tags[t.value]=="function"){let n=dB(r,e),o=e.tags[t.value](n);if(!n._called)throw new Error(`${le} tag decoder must call decode() or entries()`);return o}throw new Error(`${le} tag not supported (${t.value})`)}throw new Error("unsupported")}function hE(r,e){if(!(r instanceof Uint8Array))throw new Error(`${le} data to decode must be a Uint8Array`);e=Object.assign({},aB,e);let t=Qu(r),n=e.tokenizer||new z1(t,e),o=Zi(n,e);if(o===Qi)throw new Error(`${le} did not find any content to decode`);if(o===Gc)throw new Error(`${le} got unexpected break`);return[o,r.subarray(n.pos())]}function ba(r,e){let[t,n]=hE(r,e);if(n.length>0)throw new Error(`${le} too many terminals, data makes no sense`);return t}var W1=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(W1.prototype,Symbol.toStringTag,{value:"Tagged"});var ni="/",pE=new TextEncoder().encode(ni),G1=pE[0],rt=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]!==G1)throw new Error("Invalid key")}toString(e="utf8"){return D(this._buf,e)}uint8Array(){return this._buf}get[Symbol.toStringTag](){return`Key(${this.toString()})`}static withNamespaces(e){return new r(e.join(ni))}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=pE),this._buf[0]!==G1){let e=new Uint8Array(this._buf.byteLength+1);e.fill(G1,0,1),e.set(this._buf,1),this._buf=e}for(;this._buf.byteLength>1&&this._buf[this._buf.byteLength-1]===G1;)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(ni).slice(1)}type(){return hB(this.baseNamespace())}name(){return pB(this.baseNamespace())}instance(e){return new r(this.toString()+":"+e)}path(){let e=this.parent().toString();return e.endsWith(ni)||(e+=ni),e+=this.type(),new r(e)}parent(){let e=this.list();return e.length===1?new r(ni):new r(e.slice(0,-1).join(ni))}child(e){return this.toString()===ni?e:e.toString()===ni?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(),...mB(e.map(t=>t.namespaces()))])}};function hB(r){let e=r.split(":");return e.length<2?"":e.slice(0,-1).join(":")}function pB(r){let e=r.split(":");return e[e.length-1]}function mB(r){return[].concat(...r)}function gB(r){return r[Symbol.asyncIterator]!=null}function yB(r){if(gB(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 j1=yB;function Y1({enumerable:r=!0,configurable:e=!1}={}){return{enumerable:r,configurable:e,writable:!1}}function*wB(r,e){if(e!=null&&typeof e=="object")if(Array.isArray(e))for(let[t,n]of e.entries()){let o=[...r,t],i=J.asCID(n);i!=null?yield[o.join("/"),i]:typeof n=="object"&&(yield*ty(n,o))}else{let t=J.asCID(e);t!=null?yield[r.join("/"),t]:yield*ty(e,r)}}function*ty(r,e){if(r==null||r instanceof Uint8Array)return;let t=J.asCID(r);t!=null&&(yield[e.join("/"),t]);for(let[n,o]of Object.entries(r)){let i=[...e,n];yield*wB(i,o)}}function*bB(r,e){if(Array.isArray(e))for(let[t,n]of e.entries()){let o=[...r,t];yield o.join("/"),typeof n=="object"&&J.asCID(n)==null&&(yield*ry(n,o))}else yield*ry(e,r)}function*ry(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"&&J.asCID(n)==null&&(yield*bB(o,n))}}function xB(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=J.asCID(t);if(i!=null)return{value:i,remaining:e.slice(n+1).join("/")}}return{value:t}}var ny=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:Y1(),bytes:Y1(),value:Y1(),asBlock:Y1()})}links(){return ty(this.value,[])}tree(){return ry(this.value,[])}get(e="/"){return xB(this.value,e.split("/").filter(Boolean))}};function mE({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 ny({cid:e,bytes:r,value:o})}var X1=class extends Error{static name="AlreadyPinnedError";name="AlreadyPinnedError"},sd=class extends Error{static name="BlockPinnedError";name="BlockPinnedError"},Q1=class extends Error{static name="InvalidDatastoreVersionError";name="InvalidDatastoreVersionError"},xa=class extends Error{static name="InvalidConfigurationError";name="InvalidConfigurationError"},Z1=class extends AggregateError{static name="GetFailedError";name="GetFailedError"},J1=class extends AggregateError{static name="LoadBlockFailedError";name="LoadBlockFailedError"},ad=class extends Error{static name="BlockNotFoundWhileOfflineError";name="BlockNotFoundWhileOfflineError"};var wE="/pin/",gE="/pinned-block/",oy=dn,yE=1;function ep(r){return r.version===0&&(r=r.toV1()),new rt(`${wE}${r.toString(oy)}`)}var tp=class{datastore;blockstore;getCodec;constructor(e,t,n){this.datastore=e,this.blockstore=t,this.getCodec=n}async*add(e,t={}){let n=ep(e);if(await this.datastore.has(n))throw new X1("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 Yt({concurrency:yE});for await(let a of this.#e(e,i,{...t,depth:o}))await this.#t(a,c=>c.pinnedBy.find(l=>ce(l,e.bytes))!=null?!1:(c.pinCount++,c.pinnedBy.push(e.bytes),!0),t),yield a;let s={depth:o,metadata:t.metadata??{}};await this.datastore.put(n,id(s),t)}async*#e(e,t,n){if(n.depth===-1)return;let o=await this.getCodec(e.code),i=await j1(this.blockstore.get(e,n)),s=mE({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 rt(`${gE}${oy.encode(e.multihash.bytes)}`),i={pinCount:0,pinnedBy:[]};try{i=ba(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,id(i),n),n.onProgress?.(new U("helia:pin:add",e))}}async*rm(e,t={}){let n=ep(e),o=await this.datastore.get(n,t),i=ba(o);await this.datastore.delete(n,t);let s=new Yt({concurrency:yE});for await(let a of this.#e(e,s,{...t,depth:i.depth}))await this.#t(a,c=>(c.pinCount--,c.pinnedBy=c.pinnedBy.filter(l=>ce(l,e.bytes)),!0),{...t,depth:i.depth}),yield a}async*ls(e={}){for await(let{key:t,value:n}of this.datastore.query({prefix:wE+(e.cid!=null?`${e.cid.toString(dn)}`:"")},e)){let o=J.parse(t.toString().substring(5),dn),i=ba(n);yield{cid:o,...i}}}async isPinned(e,t={}){let n=new rt(`${gE}${oy.encode(e.multihash.bytes)}`);return this.datastore.has(n,t)}async get(e,t){let n=ep(e),o=await this.datastore.get(n,t);return ba(o)}async setMetadata(e,t,n){let o=ep(e),i=await this.datastore.get(o,n),s=ba(i);s.metadata=t??{},await this.datastore.put(o,id(s),n)}};var iy=1,sy=5,ay=100;var cd=class extends Error{static name="InsufficientProvidersError";constructor(e="Insufficient providers found"){super(e),this.name="InsufficientProvidersError"}},Ji=class extends Error{static name="NoRoutersAvailableError";constructor(e="No routers available"){super(e),this.name="NoRoutersAvailableError"}},ld=class extends Error{static name="UnknownHashAlgorithmError";constructor(e="Unknown hash algorithm"){super(e),this.name="UnknownHashAlgorithmError"}},ud=class extends Error{static name="UnknownCodecError";constructor(e="Unknown codec"){super(e),this.name="UnknownCodecError"}},cy=class extends Error{static name="InvalidCodecError";constructor(e="Invalid codec"){super(e),this.name="InvalidCodecError"}};var EB=5,rp=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??EB,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 Tt(...this.routers)}async stop(){await Pt(...this.routers)}async*findProviders(e,t={}){if(this.routers.length===0)throw new Ji("No content routers available");let n=new Qt({concurrency:this.providerLookupConcurrency}),o=0,i=[],s=this,a=0;this.log("findProviders for %c start using routers %s",e,this.routers.map(l=>l.toString()).join(", "));let c=Ea(this.routers,"findProviders").map(async function*(l){let u=0;t?.onProgress?.(new U("helia:routing:find-providers:start",{routing:l.name,cid:e}));try{for await(let d of l.findProviders(e,t))u++,t?.onProgress?.(new U("helia:routing:find-providers:provider",{routing:l.name,cid:e,provider:d})),yield d}catch(d){i.push(d)}finally{s.log("router %s found %d providers for %c",l,u,e),t?.onProgress?.(new U("helia:routing:find-providers:end",{routing:l.name,cid:e,found:u})),a++,a===c.length&&n.size===0&&n.emitIdle()}});for await(let l of wr(n.toGenerator(),...c))if(l!=null){if(l.multiaddrs.length===0){if(n.find(l.id)!=null)continue;n.add(async()=>{try{let u=await this.findPeer(l.id,t);return u.multiaddrs.length===0?null:{...u,protocols:l.protocols,routing:l.routing}}catch(u){return this.log.error("could not load multiaddrs for peer %p - %e",l.id,u),null}},{peerId:l.id,signal:t.signal}).catch(u=>{this.log.error("could not load multiaddrs for peer %p - %e",l.id,u)});continue}o++,yield l}this.log("findProviders finished, found %d providers for %c",o,e)}async provide(e,t={}){if(this.routers.length===0)throw new Ji("No content routers available");await Promise.all(Ea(this.routers,"provide").map(async n=>{t?.onProgress?.(new U("helia:routing:provide:start",{routing:n.name,cid:e})),await n.provide(e,t),t?.onProgress?.(new U("helia:routing:provide:end",{routing:n.name,cid:e}))}))}async cancelReprovide(e,t={}){await Promise.all(Ea(this.routers,"cancelReprovide").map(async n=>{t?.onProgress?.(new U("helia:routing:cancel-reprovide:start",{routing:n.name,cid:e})),await n.cancelReprovide(e,t),t?.onProgress?.(new U("helia:routing:cancel-reprovide:end",{routing:n.name,cid:e}))}))}async put(e,t,n){await Promise.all(Ea(this.routers,"put").map(async o=>{n?.onProgress?.(new U("helia:routing:put:start",{routing:o.name,key:e,value:t})),await o.put(e,t,n),n?.onProgress?.(new U("helia:routing:put:end",{routing:o.name,key:e,value:t}))}))}async get(e,t){let n=[],o;try{o=await Promise.any(Ea(this.routers,"get").map(async i=>{t?.onProgress?.(new U("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 U("helia:routing:get:end",{routing:i.name,key:e}))}}))}catch{}if(o==null)throw new Z1(n,`Failed to get value key ${D(e,"base58btc")}`);return o}async findPeer(e,t){if(this.routers.length===0)throw new Ji("No peer routers available");let n=this,o=wr(...Ea(this.routers,"findPeer").map(i=>(async function*(){t?.onProgress?.(new U("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 U("helia:routing:find-peer:end",{routing:i.name,peerId:e}))}})()));for await(let i of o)if(i!=null)return i;throw new je("Could not find peer in routing")}async*getClosestPeers(e,t={}){if(this.routers.length===0)throw new Ji("No peer routers available");for await(let n of wr(...Ea(this.routers,"getClosestPeers").map(async function*(o){t?.onProgress?.(new U("helia:routing:get-closest-peers:start",{routing:o.name,key:e}));try{yield*o.getClosestPeers(e,t)}finally{t?.onProgress?.(new U("helia:routing:get-closest-peers:end",{routing:o.name,key:e}))}})))n!=null&&(yield n)}};function Ea(r,e){return r.filter(t=>t[e]!=null)}var qr=class extends Error{static name="AbortError";name="AbortError";constructor(e="The operation was aborted",...t){super(e,...t)}};async function br(r,e,t,n){let o=new qr(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(){uy(t,"abort",d),uy(r,e,l),uy(r,i,u)}let l=f=>{try{if(n?.filter?.(f)===!1)return}catch(h){c(),a(h);return}c(),s(f)},u=f=>{if(c(),f instanceof Error){a(f);return}a(f.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.`))},d=()=>{c(),a(o)};ly(t,"abort",d),ly(r,e,l),ly(r,i,u)})}function ly(r,e,t){r!=null&&(bE(r)?r.addEventListener(e,t):r.addListener(e,t))}function uy(r,e,t){r!=null&&(bE(r)?r.removeEventListener(e,t):r.removeListener(e,t))}function bE(r){return typeof r.addEventListener=="function"&&typeof r.removeEventListener=="function"}var np=class extends Error{static name="QueueFullError";constructor(e="The queue was full"){super(e),this.name="QueueFullError"}};var op=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 qr)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function vB(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var ip=class{id;fn;options;recipients;status;timeline;controller;constructor(e,t){this.id=vB(),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 qr),this.cleanup())}async join(e={}){let t=new op(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 Ze(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 dy(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 dd=class extends we{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=dy(this.emitEmpty.bind(this),1),this.emitIdle=dy(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 np;let n=new ip(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 qr)}),this.clear()}async onEmpty(e){this.size!==0&&await br(this,"empty",e?.signal)}async onSizeLessThan(e,t){this.size<e||await br(this,"next",t?.signal,{filter:()=>this.size<e})}async onIdle(e){this.pending===0&&this.size===0||await br(this,"idle",e?.signal)}get size(){return this.queue.length}get queued(){return this.queue.length-this.pending}get running(){return this.pending}async*toGenerator(e){e?.signal?.throwIfAborted();let t=jt({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 qr("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 sp="lock:worker:request-read",ap="lock:worker:abort-read-request",cp="lock:worker:release-read",lp="lock:master:grant-read",up="lock:master:error-read",dp="lock:worker:request-write",fp="lock:worker:abort-write-request",hp="lock:worker:release-write",pp="lock:master:grant-write",mp="lock:master:error-write",gp="lock:worker:finalize",yp="mortice",xE={singleProcess:!1};var fy=(r,e,t,n,o,i,s,a,c)=>l=>{if(l.data==null)return;let u={type:l.data.type,name:l.data.name,identifier:l.data.identifier};u.type===o&&r.safeDispatchEvent(t,{detail:{name:u.name,identifier:u.identifier,handler:async()=>{e.postMessage({type:c,name:u.name,identifier:u.identifier}),await new Promise(d=>{let f=h=>{if(h?.data==null)return;let p={type:h.data.type,name:h.data.name,identifier:h.data.identifier};p.type===a&&p.identifier===u.identifier&&(e.removeEventListener("message",f),d())};e.addEventListener("message",f)})},onError:d=>{e.postMessage({type:s,name:u.name,identifier:u.identifier,error:{message:d.message,name:d.name,stack:d.stack}})}}}),u.type===i&&r.safeDispatchEvent(n,{detail:{name:u.name,identifier:u.identifier}}),u.type===gp&&r.safeDispatchEvent("finalizeRequest",{detail:{name:u.name}})};var EE=(r=10)=>Math.random().toString().substring(2,r+2);var wp=class{name;channel;constructor(e){this.name=e,this.channel=new BroadcastChannel(yp)}readLock(e){return this.sendRequest(sp,ap,lp,up,cp,e)}writeLock(e){return this.sendRequest(dp,fp,pp,mp,hp,e)}finalize(){this.channel.postMessage({type:gp,name:this.name}),this.channel.close()}async sendRequest(e,t,n,o,i,s){s?.signal?.throwIfAborted();let a=EE();return this.channel.postMessage({type:e,identifier:a,name:this.name}),new Promise((c,l)=>{let u=()=>{this.channel.postMessage({type:t,identifier:a,name:this.name})};s?.signal?.addEventListener("abort",u,{once:!0});let d=f=>{if(f.data?.identifier===a&&(f.data?.type===n&&(this.channel.removeEventListener("message",d),s?.signal?.removeEventListener("abort",u),c(()=>{this.channel.postMessage({type:i,identifier:a,name:this.name})})),f.data.type===o)){this.channel.removeEventListener("message",d),s?.signal?.removeEventListener("abort",u);let h=new Error;f.data.error!=null&&(h.message=f.data.error.message,h.name=f.data.error.name,h.stack=f.data.error.stack),l(h)}};this.channel.addEventListener("message",d)})}};var vE=r=>{if(r=Object.assign({},xE,r),!!globalThis.document||r.singleProcess){let t=new BroadcastChannel(yp),n=new we;return t.addEventListener("message",fy(n,t,"requestReadLock","abortReadLockRequest",sp,ap,up,cp,lp)),t.addEventListener("message",fy(n,t,"requestWriteLock","abortWriteLockRequest",dp,fp,mp,hp,pp)),n}return new wp(r.name)};var va=new Map,fd;function SE(r){return typeof r?.readLock=="function"&&typeof r?.writeLock=="function"}function SB(r){if(fd==null&&(fd=vE(r),!SE(fd))){let e=fd;e.addEventListener("requestReadLock",t=>{let n=t.detail.name,o=t.detail.identifier,i=va.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=va.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=va.get(n);o?.finalize()})}return fd}async function hy(r,e){let t,n,o=new Promise((s,a)=>{t=s,n=a}),i=()=>{n(new qr)};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 AE=(r,e)=>{let t=va.get(r);if(t!=null)return t;let n=SB(e);if(SE(n))return t=n,va.set(r,t),t;let o=new dd({concurrency:1}),i;return t={async readLock(s){if(i!=null)return hy(i,s);i=new dd({concurrency:e.concurrency,autoStart:!1});let a=i,c=hy(i,s);return o.add(async()=>{a.start(),await a.onIdle().then(()=>{i===a&&(i=null)})}),c},async writeLock(s){return i=null,hy(o,s)},finalize:()=>{va.delete(r)},queue:o},va.set(r,t),e.autoFinalize===!0&&o.addEventListener("idle",()=>{t.finalize()},{once:!0}),t};var AB={name:"lock",concurrency:1/0,singleProcess:!1,autoFinalize:!1};function hd(r){let e=Object.assign({},AB,r);return AE(e.name,e)}var bp=class{lock;child;pins;routing;started;constructor(e,t,n,o={}){this.child=e,this.pins=t,this.routing=n,this.lock=hd({singleProcess:o.holdGcLock}),this.started=!1}isStarted(){return this.started}async start(){await Tt(this.child),this.started=!0}async stop(){await Pt(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 sd("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 sd("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 py=new rt("/version"),TE=1;async function _E(r){if(!await r.has(py)){await r.put(py,L(`${TE}`));return}let e=await r.get(py),t=D(e);if(parseInt(t,10)!==TE)throw new Q1("Invalid datastore version, a datastore migration may be required")}var Ry={};wt(Ry,{code:()=>Cy,decode:()=>yM,decodeOptions:()=>pM,encode:()=>gM,encodeOptions:()=>fM,name:()=>mM,toByteView:()=>Nv});var TB=["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 my(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=_B(r);return t||"Object"}function _B(r){let e=Object.prototype.toString.call(r).slice(8,-1);if(TB.includes(e))return e}var _=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}};_.uint=new _(0,"uint",!0);_.negint=new _(1,"negint",!0);_.bytes=new _(2,"bytes",!0);_.string=new _(3,"string",!0);_.array=new _(4,"array",!1);_.map=new _(5,"map",!1);_.tag=new _(6,"tag",!1);_.float=new _(7,"float",!0);_.false=new _(7,"false",!0);_.true=new _(7,"true",!0);_.null=new _(7,"null",!0);_.undefined=new _(7,"undefined",!0);_.break=new _(7,"break",!0);var Q=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 pd=globalThis.process&&!globalThis.process.browser&&globalThis.Buffer&&typeof globalThis.Buffer.isBuffer=="function",IB=new TextEncoder;function xp(r){return pd&&globalThis.Buffer.isBuffer(r)}function md(r){return r instanceof Uint8Array?xp(r)?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):r:Uint8Array.from(r)}var kB=24,CB=200,Ep=pd?r=>r.length>=kB?globalThis.Buffer.from(r):IE(r):r=>r.length>=CB?IB.encode(r):IE(r),vo=r=>Uint8Array.from(r),kE=pd?(r,e,t)=>xp(r)?new Uint8Array(r.subarray(e,t)):r.slice(e,t):(r,e,t)=>r.slice(e,t),CE=pd?(r,e)=>(r=r.map(t=>t instanceof Uint8Array?t:globalThis.Buffer.from(t)),md(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},RE=pd?r=>globalThis.Buffer.allocUnsafe(r):r=>new Uint8Array(r);function vp(r,e){if(xp(r)&&xp(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 IE(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 RB=256,gd=class{constructor(e=RB){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=RE(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=kE(n,0,this.cursor)}else t=CE(this.chunks,this.cursor);return e&&this.reset(),t}},Sp=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 ue="CBOR decode error:",Ap="CBOR encode error:",yd=[];yd[23]=1;yd[24]=2;yd[25]=3;yd[26]=5;yd[27]=9;function oi(r,e,t){if(r.length-e<t)throw new Error(`${ue} not enough data for type`)}var Mt=[24,256,65536,4294967296,BigInt("18446744073709551616")];function zr(r,e,t){oi(r,e,1);let n=r[e];if(t.strict===!0&&n<Mt[0])throw new Error(`${ue} integer encoded in more bytes than necessary (strict decode)`);return n}function Wr(r,e,t){oi(r,e,2);let n=r[e]<<8|r[e+1];if(t.strict===!0&&n<Mt[1])throw new Error(`${ue} integer encoded in more bytes than necessary (strict decode)`);return n}function Gr(r,e,t){oi(r,e,4);let n=r[e]*16777216+(r[e+1]<<16)+(r[e+2]<<8)+r[e+3];if(t.strict===!0&&n<Mt[2])throw new Error(`${ue} integer encoded in more bytes than necessary (strict decode)`);return n}function jr(r,e,t){oi(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<Mt[3])throw new Error(`${ue} 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(`${ue} integers outside of the safe integer range are not supported`)}function PE(r,e,t,n){return new Q(_.uint,zr(r,e+1,n),2)}function LE(r,e,t,n){return new Q(_.uint,Wr(r,e+1,n),3)}function NE(r,e,t,n){return new Q(_.uint,Gr(r,e+1,n),5)}function DE(r,e,t,n){return new Q(_.uint,jr(r,e+1,n),9)}function wn(r,e){return it(r,0,e.value)}function it(r,e,t){if(t<Mt[0]){let n=Number(t);r.push([e|n])}else if(t<Mt[1]){let n=Number(t);r.push([e|24,n])}else if(t<Mt[2]){let n=Number(t);r.push([e|25,n>>>8,n&255])}else if(t<Mt[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<Mt[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(`${ue} encountered BigInt larger than allowable range`)}}wn.encodedSize=function(e){return it.encodedSize(e.value)};it.encodedSize=function(e){return e<Mt[0]?1:e<Mt[1]?2:e<Mt[2]?3:e<Mt[3]?5:9};wn.compareTokens=function(e,t){return e.value<t.value?-1:e.value>t.value?1:0};function OE(r,e,t,n){return new Q(_.negint,-1-zr(r,e+1,n),2)}function BE(r,e,t,n){return new Q(_.negint,-1-Wr(r,e+1,n),3)}function ME(r,e,t,n){return new Q(_.negint,-1-Gr(r,e+1,n),5)}var gy=BigInt(-1),UE=BigInt(1);function FE(r,e,t,n){let o=jr(r,e+1,n);if(typeof o!="bigint"){let i=-1-o;if(i>=Number.MIN_SAFE_INTEGER)return new Q(_.negint,i,9)}if(n.allowBigInt!==!0)throw new Error(`${ue} integers outside of the safe integer range are not supported`);return new Q(_.negint,gy-BigInt(o),9)}function Tp(r,e){let t=e.value,n=typeof t=="bigint"?t*gy-UE:t*-1-1;it(r,e.type.majorEncoded,n)}Tp.encodedSize=function(e){let t=e.value,n=typeof t=="bigint"?t*gy-UE:t*-1-1;return n<Mt[0]?1:n<Mt[1]?2:n<Mt[2]?3:n<Mt[3]?5:9};Tp.compareTokens=function(e,t){return e.value<t.value?1:e.value>t.value?-1:0};function wd(r,e,t,n){oi(r,e,t+n);let o=r.slice(e+t,e+t+n);return new Q(_.bytes,o,t+n)}function $E(r,e,t,n){return wd(r,e,1,t)}function VE(r,e,t,n){return wd(r,e,2,zr(r,e+1,n))}function KE(r,e,t,n){return wd(r,e,3,Wr(r,e+1,n))}function HE(r,e,t,n){return wd(r,e,5,Gr(r,e+1,n))}function qE(r,e,t,n){let o=jr(r,e+1,n);if(typeof o=="bigint")throw new Error(`${ue} 64-bit integer bytes lengths not supported`);return wd(r,e,9,o)}function _p(r){return r.encodedBytes===void 0&&(r.encodedBytes=_.equals(r.type,_.string)?Ep(r.value):r.value),r.encodedBytes}function jc(r,e){let t=_p(e);it(r,e.type.majorEncoded,t.length),r.push(t)}jc.encodedSize=function(e){let t=_p(e);return it.encodedSize(t.length)+t.length};jc.compareTokens=function(e,t){return LB(_p(e),_p(t))};function LB(r,e){return r.length<e.length?-1:r.length>e.length?1:vp(r,e)}var zE=new TextDecoder,DB=32;function OB(r,e,t){if(t-e<DB){let o="";for(let i=e;i<t;i++){let s=r[i];if(s&128)return zE.decode(r.subarray(e,t));o+=String.fromCharCode(s)}return o}return zE.decode(r.subarray(e,t))}function bd(r,e,t,n,o){let i=t+n;oi(r,e,i);let s=new Q(_.string,OB(r,e+t,e+i),i);return o.retainStringBytes===!0&&(s.byteValue=r.slice(e+t,e+i)),s}function WE(r,e,t,n){return bd(r,e,1,t,n)}function GE(r,e,t,n){return bd(r,e,2,zr(r,e+1,n),n)}function jE(r,e,t,n){return bd(r,e,3,Wr(r,e+1,n),n)}function YE(r,e,t,n){return bd(r,e,5,Gr(r,e+1,n),n)}function XE(r,e,t,n){let o=jr(r,e+1,n);if(typeof o=="bigint")throw new Error(`${ue} 64-bit integer string lengths not supported`);return bd(r,e,9,o,n)}var QE=jc;function Yc(r,e,t,n){return new Q(_.array,n,t)}function ZE(r,e,t,n){return Yc(r,e,1,t)}function JE(r,e,t,n){return Yc(r,e,2,zr(r,e+1,n))}function ev(r,e,t,n){return Yc(r,e,3,Wr(r,e+1,n))}function tv(r,e,t,n){return Yc(r,e,5,Gr(r,e+1,n))}function rv(r,e,t,n){let o=jr(r,e+1,n);if(typeof o=="bigint")throw new Error(`${ue} 64-bit integer array lengths not supported`);return Yc(r,e,9,o)}function nv(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${ue} indefinite length items not allowed`);return Yc(r,e,1,1/0)}function Ip(r,e){it(r,_.array.majorEncoded,e.value)}Ip.compareTokens=wn.compareTokens;Ip.encodedSize=function(e){return it.encodedSize(e.value)};function Xc(r,e,t,n){return new Q(_.map,n,t)}function ov(r,e,t,n){return Xc(r,e,1,t)}function iv(r,e,t,n){return Xc(r,e,2,zr(r,e+1,n))}function sv(r,e,t,n){return Xc(r,e,3,Wr(r,e+1,n))}function av(r,e,t,n){return Xc(r,e,5,Gr(r,e+1,n))}function cv(r,e,t,n){let o=jr(r,e+1,n);if(typeof o=="bigint")throw new Error(`${ue} 64-bit integer map lengths not supported`);return Xc(r,e,9,o)}function lv(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${ue} indefinite length items not allowed`);return Xc(r,e,1,1/0)}function kp(r,e){it(r,_.map.majorEncoded,e.value)}kp.compareTokens=wn.compareTokens;kp.encodedSize=function(e){return it.encodedSize(e.value)};function uv(r,e,t,n){return new Q(_.tag,t,1)}function dv(r,e,t,n){return new Q(_.tag,zr(r,e+1,n),2)}function fv(r,e,t,n){return new Q(_.tag,Wr(r,e+1,n),3)}function hv(r,e,t,n){return new Q(_.tag,Gr(r,e+1,n),5)}function pv(r,e,t,n){return new Q(_.tag,jr(r,e+1,n),9)}function Cp(r,e){it(r,_.tag.majorEncoded,e.value)}Cp.compareTokens=wn.compareTokens;Cp.encodedSize=function(e){return it.encodedSize(e.value)};var yy=20,wy=21,by=22,xy=23;function mv(r,e,t,n){if(n.allowUndefined===!1)throw new Error(`${ue} undefined values are not supported`);return n.coerceUndefinedToNull===!0?new Q(_.null,null,1):new Q(_.undefined,void 0,1)}function gv(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${ue} indefinite length items not allowed`);return new Q(_.break,void 0,1)}function Ey(r,e,t){if(t){if(t.allowNaN===!1&&Number.isNaN(r))throw new Error(`${ue} NaN values are not supported`);if(t.allowInfinity===!1&&(r===1/0||r===-1/0))throw new Error(`${ue} Infinity values are not supported`)}return new Q(_.float,r,e)}function yv(r,e,t,n){return Ey(vy(r,e+1),3,n)}function wv(r,e,t,n){return Ey(Sy(r,e+1),5,n)}function bv(r,e,t,n){return Ey(Sv(r,e+1),9,n)}function xd(r,e,t){let n=e.value;if(n===!1)r.push([_.float.majorEncoded|yy]);else if(n===!0)r.push([_.float.majorEncoded|wy]);else if(n===null)r.push([_.float.majorEncoded|by]);else if(n===void 0)r.push([_.float.majorEncoded|xy]);else{let o,i=!1;(!t||t.float64!==!0)&&(Ev(n),o=vy(Gn,1),n===o||Number.isNaN(n)?(Gn[0]=249,r.push(Gn.slice(0,3)),i=!0):(vv(n),o=Sy(Gn,1),n===o&&(Gn[0]=250,r.push(Gn.slice(0,5)),i=!0))),i||($B(n),o=Sv(Gn,1),Gn[0]=251,r.push(Gn.slice(0,9)))}}xd.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){Ev(n);let o=vy(Gn,1);if(n===o||Number.isNaN(n))return 3;if(vv(n),o=Sy(Gn,1),n===o)return 5}return 9};var xv=new ArrayBuffer(9),bn=new DataView(xv,1),Gn=new Uint8Array(xv,0);function Ev(r){if(r===1/0)bn.setUint16(0,31744,!1);else if(r===-1/0)bn.setUint16(0,64512,!1);else if(Number.isNaN(r))bn.setUint16(0,32256,!1);else{bn.setFloat32(0,r);let e=bn.getUint32(0),t=(e&2139095040)>>23,n=e&8388607;if(t===255)bn.setUint16(0,31744,!1);else if(t===0)bn.setUint16(0,(e&2147483648)>>16|n>>13,!1);else{let o=t-127;o<-24?bn.setUint16(0,0):o<-14?bn.setUint16(0,(e&2147483648)>>16|1<<24+o,!1):bn.setUint16(0,(e&2147483648)>>16|o+15<<10|n>>13,!1)}}}function vy(r,e){if(r.length-e<2)throw new Error(`${ue} 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 vv(r){bn.setFloat32(0,r,!1)}function Sy(r,e){if(r.length-e<4)throw new Error(`${ue} not enough data for float32`);let t=(r.byteOffset||0)+e;return new DataView(r.buffer,t,4).getFloat32(0,!1)}function $B(r){bn.setFloat64(0,r,!1)}function Sv(r,e){if(r.length-e<8)throw new Error(`${ue} not enough data for float64`);let t=(r.byteOffset||0)+e;return new DataView(r.buffer,t,8).getFloat64(0,!1)}xd.compareTokens=wn.compareTokens;function Oe(r,e,t){throw new Error(`${ue} encountered invalid minor (${t}) for major ${r[e]>>>5}`)}function Rp(r){return()=>{throw new Error(`${ue} ${r}`)}}var j=[];for(let r=0;r<=23;r++)j[r]=Oe;j[24]=PE;j[25]=LE;j[26]=NE;j[27]=DE;j[28]=Oe;j[29]=Oe;j[30]=Oe;j[31]=Oe;for(let r=32;r<=55;r++)j[r]=Oe;j[56]=OE;j[57]=BE;j[58]=ME;j[59]=FE;j[60]=Oe;j[61]=Oe;j[62]=Oe;j[63]=Oe;for(let r=64;r<=87;r++)j[r]=$E;j[88]=VE;j[89]=KE;j[90]=HE;j[91]=qE;j[92]=Oe;j[93]=Oe;j[94]=Oe;j[95]=Rp("indefinite length bytes/strings are not supported");for(let r=96;r<=119;r++)j[r]=WE;j[120]=GE;j[121]=jE;j[122]=YE;j[123]=XE;j[124]=Oe;j[125]=Oe;j[126]=Oe;j[127]=Rp("indefinite length bytes/strings are not supported");for(let r=128;r<=151;r++)j[r]=ZE;j[152]=JE;j[153]=ev;j[154]=tv;j[155]=rv;j[156]=Oe;j[157]=Oe;j[158]=Oe;j[159]=nv;for(let r=160;r<=183;r++)j[r]=ov;j[184]=iv;j[185]=sv;j[186]=av;j[187]=cv;j[188]=Oe;j[189]=Oe;j[190]=Oe;j[191]=lv;for(let r=192;r<=215;r++)j[r]=uv;j[216]=dv;j[217]=fv;j[218]=hv;j[219]=pv;j[220]=Oe;j[221]=Oe;j[222]=Oe;j[223]=Oe;for(let r=224;r<=243;r++)j[r]=Rp("simple values are not supported");j[244]=Oe;j[245]=Oe;j[246]=Oe;j[247]=mv;j[248]=Rp("simple values are not supported");j[249]=yv;j[250]=wv;j[251]=bv;j[252]=Oe;j[253]=Oe;j[254]=Oe;j[255]=gv;var jn=[];for(let r=0;r<24;r++)jn[r]=new Q(_.uint,r,1);for(let r=-1;r>=-24;r--)jn[31-r]=new Q(_.negint,r,1);jn[64]=new Q(_.bytes,new Uint8Array(0),1);jn[96]=new Q(_.string,"",1);jn[128]=new Q(_.array,0,1);jn[160]=new Q(_.map,0,1);jn[244]=new Q(_.false,!1,1);jn[245]=new Q(_.true,!0,1);jn[246]=new Q(_.null,null,1);function Ay(r){switch(r.type){case _.false:return vo([244]);case _.true:return vo([245]);case _.null:return vo([246]);case _.bytes:return r.value.length?void 0:vo([64]);case _.string:return r.value===""?vo([96]):void 0;case _.array:return r.value===0?vo([128]):void 0;case _.map:return r.value===0?vo([160]):void 0;case _.uint:return r.value<24?vo([Number(r.value)]):void 0;case _.negint:if(r.value>=-24)return vo([31-Number(r.value)])}}var KB={float64:!1,mapSorter:zB,quickEncodeToken:Ay},kv=Object.freeze({float64:!0,mapSorter:WB,quickEncodeToken:Ay});function HB(){let r=[];return r[_.uint.major]=wn,r[_.negint.major]=Tp,r[_.bytes.major]=jc,r[_.string.major]=QE,r[_.array.major]=Ip,r[_.map.major]=kp,r[_.tag.major]=Cp,r[_.float.major]=xd,r}var Zc=HB(),Pp=new gd,vd=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(`${Ap} object contains circular references`);return new r(t,e)}},es={null:new Q(_.null,null),undefined:new Q(_.undefined,void 0),true:new Q(_.true,!0),false:new Q(_.false,!1),emptyArray:new Q(_.array,0),emptyMap:new Q(_.map,0)},So={number(r,e,t,n){return!Number.isInteger(r)||!Number.isSafeInteger(r)?new Q(_.float,r):r>=0?new Q(_.uint,r):new Q(_.negint,r)},bigint(r,e,t,n){return r>=BigInt(0)?new Q(_.uint,r):new Q(_.negint,r)},Uint8Array(r,e,t,n){return new Q(_.bytes,r)},string(r,e,t,n){return new Q(_.string,r)},boolean(r,e,t,n){return r?es.true:es.false},null(r,e,t,n){return es.null},undefined(r,e,t,n){return es.undefined},ArrayBuffer(r,e,t,n){return new Q(_.bytes,new Uint8Array(r))},DataView(r,e,t,n){return new Q(_.bytes,new Uint8Array(r.buffer,r.byteOffset,r.byteLength))},Array(r,e,t,n){if(!r.length)return t.addBreakTokens===!0?[es.emptyArray,new Q(_.break)]:es.emptyArray;n=vd.createCheck(n,r);let o=[],i=0;for(let s of r)o[i++]=Qc(s,t,n);return t.addBreakTokens?[new Q(_.array,r.length),o,new Q(_.break)]:[new Q(_.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=vd.createCheck(n,r);let c=!o&&t.ignoreUndefinedProperties,l=0;for(let u of i){let d=o?r.get(u):r[u];c&&d===void 0||(a[l++]=[Qc(u,t,n),Qc(d,t,n)])}l<s&&(a.length=l)}return a?.length?(qB(a,t),t.addBreakTokens?[new Q(_.map,a.length),a,new Q(_.break)]:[new Q(_.map,a.length),a]):t.addBreakTokens===!0?[es.emptyMap,new Q(_.break)]:es.emptyMap},Tagged(r,e,t,n){return[new Q(_.tag,r.tag),Qc(r.value,t,n)]}};So.Map=So.Object;So.Buffer=So.Uint8Array;for(let r of"Uint8Clamped Uint16 Uint32 Int8 Int16 Int32 BigUint64 BigInt64 Float32 Float64".split(" "))So[`${r}Array`]=So.DataView;function Qc(r,e={},t){let n=my(r),o=e&&e.typeEncoders&&e.typeEncoders[n]||So[n];if(typeof o=="function"){let s=o(r,n,e,t);if(s!=null)return s}let i=So[n];if(!i)throw new Error(`${Ap} unsupported type: ${n}`);return i(r,n,e,t)}function qB(r,e){e.mapSorter&&r.sort(e.mapSorter)}function zB(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=Zc[o].compareTokens(t,n);return i===0&&console.warn("WARNING: complex key types used, CBOR key sorting guarantees are gone"),i}function WB(r,e){if(r[0]instanceof Q&&e[0]instanceof Q){let t=r[0],n=e[0];return t._keyBytes||(t._keyBytes=Av(t.value)),n._keyBytes||(n._keyBytes=Av(n.value)),vp(t._keyBytes,n._keyBytes)}throw new Error("rfc8949MapSorter: complex key types are not supported yet")}function Av(r){return Rv(r,Zc,kv)}function Ed(r,e,t,n){if(Array.isArray(e))for(let o of e)Ed(r,o,t,n);else t[e.type.major](r,e,n)}var Tv=_.uint.majorEncoded,_v=_.negint.majorEncoded,GB=_.bytes.majorEncoded,jB=_.string.majorEncoded,Iv=_.array.majorEncoded,YB=_.float.majorEncoded|yy,XB=_.float.majorEncoded|wy,QB=_.float.majorEncoded|by,ZB=_.float.majorEncoded|xy,JB=BigInt(-1),eM=BigInt(1);function tM(r){return r.addBreakTokens!==!0}function Cv(r,e,t,n){let o=my(e),i=t.typeEncoders&&t.typeEncoders[o];if(i){let s=i(e,o,t,n);if(s!=null){Ed(r,s,Zc,t);return}}switch(o){case"null":r.push([QB]);return;case"undefined":r.push([ZB]);return;case"boolean":r.push([e?XB:YB]);return;case"number":!Number.isInteger(e)||!Number.isSafeInteger(e)?xd(r,new Q(_.float,e),t):e>=0?it(r,Tv,e):it(r,_v,e*-1-1);return;case"bigint":e>=BigInt(0)?it(r,Tv,e):it(r,_v,e*JB-eM);return;case"string":{let s=Ep(e);it(r,jB,s.length),r.push(s);return}case"Uint8Array":it(r,GB,e.length),r.push(e);return;case"Array":if(!e.length){r.push([Iv]);return}n=vd.createCheck(n,e),it(r,Iv,e.length);for(let s of e)Cv(r,s,t,n);return;case"Object":case"Map":{let s=So.Object(e,o,t,n);Ed(r,s,Zc,t)}return;default:{let s=So[o];if(!s)throw new Error(`${Ap} unsupported type: ${o}`);let a=s(e,o,t,n);Ed(r,a,Zc,t)}}}function Rv(r,e,t,n){let o=n instanceof Uint8Array,i=o?new Sp(n):Pp,s=Qc(r,t);if(!Array.isArray(s)&&t.quickEncodeToken){let a=t.quickEncodeToken(s);if(a)return o?(i.push(a),i.toBytes()):a;let c=e[s.type.major];if(c.encodedSize){let l=c.encodedSize(s,t);if(o||(i=new gd(l)),c(i,s,t),i.chunks.length!==1)throw new Error(`Unexpected error: pre-calculated length for ${s} was wrong`);return o?i.toBytes():md(i.chunks[0])}}return i.reset(),Ed(i,s,e,t),i.toBytes(!0)}function Ty(r,e){return e=Object.assign({},KB,e),tM(e)?(Pp.reset(),Cv(Pp,r,e,void 0),Pp.toBytes(!0)):Rv(r,Zc,e)}var rM={strict:!1,allowIndefinite:!0,allowUndefined:!0,allowBigInt:!0},Lp=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=jn[e];if(t===void 0){let n=j[e];if(!n)throw new Error(`${ue} 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}},ts=Symbol.for("DONE"),Jc=Symbol.for("BREAK");function nM(r,e,t){let n=[];for(let o=0;o<r.value;o++){let i=rs(e,t);if(i===Jc){if(r.value===1/0)break;throw new Error(`${ue} got unexpected break to lengthed array`)}if(i===ts)throw new Error(`${ue} found array but not enough entries (got ${o}, expected ${r.value})`);n[o]=i}return n}function oM(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=rs(e,t);if(c===Jc){if(r.value===1/0)break;throw new Error(`${ue} got unexpected break to lengthed map`)}if(c===ts)throw new Error(`${ue} found map but not enough entries (got ${a} [no key], expected ${r.value})`);if(!n&&typeof c!="string")throw new Error(`${ue} non-string keys not supported (got ${typeof c})`);if(o&&(n&&s.has(c)||!n&&Object.hasOwn(i,c)))throw new Error(`${ue} found repeat map key "${c}"`);let l=rs(e,t);if(l===ts)throw new Error(`${ue} found map but not enough entries (got ${a} [no value], expected ${r.value})`);n?s.set(c,l):i[c]=l}return n?s:i}function*iM(r,e,t){for(let n=0;n<r.value;n++){let o=rs(e,t);if(o===Jc){if(r.value===1/0)break;throw new Error(`${ue} got unexpected break to lengthed map`)}if(o===ts)throw new Error(`${ue} found map but not enough entries (got ${n} [no key], expected ${r.value})`);let i=rs(e,t);if(i===ts)throw new Error(`${ue} found map but not enough entries (got ${n} [no value], expected ${r.value})`);yield[o,i]}}function sM(r,e){let t=!1,n=function(){if(t)throw new Error(`${ue} tag decode() may only be called once`);t=!0;let o=rs(r,e);if(o===ts)throw new Error(`${ue} tag content missing`);if(o===Jc)throw new Error(`${ue} got unexpected break in tag content`);return o};return n.entries=function(){if(t)throw new Error(`${ue} tag decode() may only be called once`);t=!0;let o=r.next();if(!_.equals(o.type,_.map))throw new Error(`${ue} entries() requires map content, got ${o.type.name}`);let i=[];for(let s of iM(o,r,e))i.push(s);return i},Object.defineProperty(n,"_called",{get(){return t},enumerable:!1}),n}function rs(r,e){if(r.done())return ts;let t=r.next();if(_.equals(t.type,_.break))return Jc;if(t.type.terminal)return t.value;if(_.equals(t.type,_.array))return nM(t,r,e);if(_.equals(t.type,_.map))return oM(t,r,e);if(_.equals(t.type,_.tag)){if(e.tags&&typeof e.tags[t.value]=="function"){let n=sM(r,e),o=e.tags[t.value](n);if(!n._called)throw new Error(`${ue} tag decoder must call decode() or entries()`);return o}throw new Error(`${ue} tag not supported (${t.value})`)}throw new Error("unsupported")}function Pv(r,e){if(!(r instanceof Uint8Array))throw new Error(`${ue} data to decode must be a Uint8Array`);e=Object.assign({},rM,e);let t=md(r),n=e.tokenizer||new Lp(t,e),o=rs(n,e);if(o===ts)throw new Error(`${ue} did not find any content to decode`);if(o===Jc)throw new Error(`${ue} got unexpected break`);return[o,r.subarray(n.pos())]}function _y(r,e){let[t,n]=Pv(r,e);if(n.length>0)throw new Error(`${ue} too many terminals, data makes no sense`);return t}var Np=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(Np.prototype,Symbol.toStringTag,{value:"Tagged"});var Lv=42;function Nv(r){return r instanceof ArrayBuffer?new Uint8Array(r,0,r.byteLength):r}function cM(r){if(r.asCID!==r&&r["/"]!==r.bytes)return null;let e=J.asCID(r);if(!e)return null;let t=new Uint8Array(e.bytes.byteLength+1);return t.set(e.bytes,1),[new Q(_.tag,Lv),new Q(_.bytes,t)]}function lM(){throw new Error("`undefined` is not supported by the IPLD Data Model and cannot be encoded")}function uM(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 dM(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 Iy={float64:!0,typeEncoders:{Map:dM,Object:cM,undefined:lM,number:uM}},fM={...Iy,typeEncoders:{...Iy.typeEncoders}};function hM(r){let e=r();if(e[0]!==0)throw new Error("Invalid CID for CBOR tag 42; expected leading 0x00");return J.decode(e.subarray(1))}var ky={allowIndefinite:!1,coerceUndefinedToNull:!0,allowNaN:!1,allowInfinity:!1,allowBigInt:!0,strict:!0,useMaps:!1,rejectDuplicateMapKeys:!0,tags:{[Lv]:hM}},pM={...ky,tags:{...ky.tags}},mM="dag-cbor",Cy=113,gM=r=>Ty(r,Iy),yM=r=>_y(Nv(r),ky);var Gy={};wt(Gy,{code:()=>Wy,decode:()=>$S,encode:()=>FS,format:()=>tU,name:()=>eU,parse:()=>nU,stringify:()=>tU});var wM=["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 Dv(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=bM(r);return t||"Object"}function bM(r){let e=Object.prototype.toString.call(r).slice(8,-1);if(wM.includes(e))return e}var w=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}};w.uint=new w(0,"uint",!0);w.negint=new w(1,"negint",!0);w.bytes=new w(2,"bytes",!0);w.string=new w(3,"string",!0);w.array=new w(4,"array",!1);w.map=new w(5,"map",!1);w.tag=new w(6,"tag",!1);w.float=new w(7,"float",!0);w.false=new w(7,"false",!0);w.true=new w(7,"true",!0);w.null=new w(7,"null",!0);w.undefined=new w(7,"undefined",!0);w.break=new w(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 Sd=globalThis.process&&!globalThis.process.browser&&globalThis.Buffer&&typeof globalThis.Buffer.isBuffer=="function",xM=new TextEncoder;function Dp(r){return Sd&&globalThis.Buffer.isBuffer(r)}function Aa(r){return r instanceof Uint8Array?Dp(r)?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):r:Uint8Array.from(r)}var EM=24,vM=200,Ad=Sd?r=>r.length>=EM?globalThis.Buffer.from(r):Ov(r):r=>r.length>=vM?xM.encode(r):Ov(r),Ao=r=>Uint8Array.from(r),Mv=Sd?(r,e,t)=>Dp(r)?new Uint8Array(r.subarray(e,t)):r.slice(e,t):(r,e,t)=>r.slice(e,t),Uv=Sd?(r,e)=>(r=r.map(t=>t instanceof Uint8Array?t:globalThis.Buffer.from(t)),Aa(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},Fv=Sd?r=>globalThis.Buffer.allocUnsafe(r):r=>new Uint8Array(r);function Op(r,e){if(Dp(r)&&Dp(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 Ov(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 Bv=4096;function $v(r){let e=r.length;if(e<=Bv)return String.fromCharCode.apply(String,r);let t="",n=0;for(;n<e;)t+=String.fromCharCode.apply(String,r.slice(n,n+=Bv));return t}var SM=256,Td=class{constructor(e=SM){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=Fv(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=Mv(n,0,this.cursor)}else t=Uv(this.chunks,this.cursor);return e&&this.reset(),t}},Bp=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 ee="CBOR decode error:",ii="CBOR encode error:",_d=[];_d[23]=1;_d[24]=2;_d[25]=3;_d[26]=5;_d[27]=9;function si(r,e,t){if(r.length-e<t)throw new Error(`${ee} not enough data for type`)}var Ut=[24,256,65536,4294967296,BigInt("18446744073709551616")];function Yr(r,e,t){si(r,e,1);let n=r[e];if(t.strict===!0&&n<Ut[0])throw new Error(`${ee} integer encoded in more bytes than necessary (strict decode)`);return n}function Xr(r,e,t){si(r,e,2);let n=r[e]<<8|r[e+1];if(t.strict===!0&&n<Ut[1])throw new Error(`${ee} integer encoded in more bytes than necessary (strict decode)`);return n}function Qr(r,e,t){si(r,e,4);let n=r[e]*16777216+(r[e+1]<<16)+(r[e+2]<<8)+r[e+3];if(t.strict===!0&&n<Ut[2])throw new Error(`${ee} integer encoded in more bytes than necessary (strict decode)`);return n}function Zr(r,e,t){si(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<Ut[3])throw new Error(`${ee} 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(`${ee} integers outside of the safe integer range are not supported`)}function Vv(r,e,t,n){return new K(w.uint,Yr(r,e+1,n),2)}function Kv(r,e,t,n){return new K(w.uint,Xr(r,e+1,n),3)}function Hv(r,e,t,n){return new K(w.uint,Qr(r,e+1,n),5)}function qv(r,e,t,n){return new K(w.uint,Zr(r,e+1,n),9)}function xn(r,e){return Ft(r,0,e.value)}function Ft(r,e,t){if(t<Ut[0]){let n=Number(t);r.push([e|n])}else if(t<Ut[1]){let n=Number(t);r.push([e|24,n])}else if(t<Ut[2]){let n=Number(t);r.push([e|25,n>>>8,n&255])}else if(t<Ut[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<Ut[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(`${ee} encountered BigInt larger than allowable range`)}}xn.encodedSize=function(e){return Ft.encodedSize(e.value)};Ft.encodedSize=function(e){return e<Ut[0]?1:e<Ut[1]?2:e<Ut[2]?3:e<Ut[3]?5:9};xn.compareTokens=function(e,t){return e.value<t.value?-1:e.value>t.value?1:0};function zv(r,e,t,n){return new K(w.negint,-1-Yr(r,e+1,n),2)}function Wv(r,e,t,n){return new K(w.negint,-1-Xr(r,e+1,n),3)}function Gv(r,e,t,n){return new K(w.negint,-1-Qr(r,e+1,n),5)}var Py=BigInt(-1),jv=BigInt(1);function Yv(r,e,t,n){let o=Zr(r,e+1,n);if(typeof o!="bigint"){let i=-1-o;if(i>=Number.MIN_SAFE_INTEGER)return new K(w.negint,i,9)}if(n.allowBigInt!==!0)throw new Error(`${ee} integers outside of the safe integer range are not supported`);return new K(w.negint,Py-BigInt(o),9)}function Mp(r,e){let t=e.value,n=typeof t=="bigint"?t*Py-jv:t*-1-1;Ft(r,e.type.majorEncoded,n)}Mp.encodedSize=function(e){let t=e.value,n=typeof t=="bigint"?t*Py-jv:t*-1-1;return n<Ut[0]?1:n<Ut[1]?2:n<Ut[2]?3:n<Ut[3]?5:9};Mp.compareTokens=function(e,t){return e.value<t.value?1:e.value>t.value?-1:0};function Id(r,e,t,n){si(r,e,t+n);let o=r.slice(e+t,e+t+n);return new K(w.bytes,o,t+n)}function Xv(r,e,t,n){return Id(r,e,1,t)}function Qv(r,e,t,n){return Id(r,e,2,Yr(r,e+1,n))}function Zv(r,e,t,n){return Id(r,e,3,Xr(r,e+1,n))}function Jv(r,e,t,n){return Id(r,e,5,Qr(r,e+1,n))}function eS(r,e,t,n){let o=Zr(r,e+1,n);if(typeof o=="bigint")throw new Error(`${ee} 64-bit integer bytes lengths not supported`);return Id(r,e,9,o)}function Up(r){return r.encodedBytes===void 0&&(r.encodedBytes=w.equals(r.type,w.string)?Ad(r.value):r.value),r.encodedBytes}function el(r,e){let t=Up(e);Ft(r,e.type.majorEncoded,t.length),r.push(t)}el.encodedSize=function(e){let t=Up(e);return Ft.encodedSize(t.length)+t.length};el.compareTokens=function(e,t){return TM(Up(e),Up(t))};function TM(r,e){return r.length<e.length?-1:r.length>e.length?1:Op(r,e)}var tS=new TextDecoder,IM=32;function kM(r,e,t){if(t-e<IM){let o="";for(let i=e;i<t;i++){let s=r[i];if(s&128)return tS.decode(r.subarray(e,t));o+=String.fromCharCode(s)}return o}return tS.decode(r.subarray(e,t))}function kd(r,e,t,n,o){let i=t+n;si(r,e,i);let s=new K(w.string,kM(r,e+t,e+i),i);return o.retainStringBytes===!0&&(s.byteValue=r.slice(e+t,e+i)),s}function rS(r,e,t,n){return kd(r,e,1,t,n)}function nS(r,e,t,n){return kd(r,e,2,Yr(r,e+1,n),n)}function oS(r,e,t,n){return kd(r,e,3,Xr(r,e+1,n),n)}function iS(r,e,t,n){return kd(r,e,5,Qr(r,e+1,n),n)}function sS(r,e,t,n){let o=Zr(r,e+1,n);if(typeof o=="bigint")throw new Error(`${ee} 64-bit integer string lengths not supported`);return kd(r,e,9,o,n)}var aS=el;function tl(r,e,t,n){return new K(w.array,n,t)}function cS(r,e,t,n){return tl(r,e,1,t)}function lS(r,e,t,n){return tl(r,e,2,Yr(r,e+1,n))}function uS(r,e,t,n){return tl(r,e,3,Xr(r,e+1,n))}function dS(r,e,t,n){return tl(r,e,5,Qr(r,e+1,n))}function fS(r,e,t,n){let o=Zr(r,e+1,n);if(typeof o=="bigint")throw new Error(`${ee} 64-bit integer array lengths not supported`);return tl(r,e,9,o)}function hS(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${ee} indefinite length items not allowed`);return tl(r,e,1,1/0)}function Fp(r,e){Ft(r,w.array.majorEncoded,e.value)}Fp.compareTokens=xn.compareTokens;Fp.encodedSize=function(e){return Ft.encodedSize(e.value)};function rl(r,e,t,n){return new K(w.map,n,t)}function pS(r,e,t,n){return rl(r,e,1,t)}function mS(r,e,t,n){return rl(r,e,2,Yr(r,e+1,n))}function gS(r,e,t,n){return rl(r,e,3,Xr(r,e+1,n))}function yS(r,e,t,n){return rl(r,e,5,Qr(r,e+1,n))}function wS(r,e,t,n){let o=Zr(r,e+1,n);if(typeof o=="bigint")throw new Error(`${ee} 64-bit integer map lengths not supported`);return rl(r,e,9,o)}function bS(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${ee} indefinite length items not allowed`);return rl(r,e,1,1/0)}function $p(r,e){Ft(r,w.map.majorEncoded,e.value)}$p.compareTokens=xn.compareTokens;$p.encodedSize=function(e){return Ft.encodedSize(e.value)};function xS(r,e,t,n){return new K(w.tag,t,1)}function ES(r,e,t,n){return new K(w.tag,Yr(r,e+1,n),2)}function vS(r,e,t,n){return new K(w.tag,Xr(r,e+1,n),3)}function SS(r,e,t,n){return new K(w.tag,Qr(r,e+1,n),5)}function AS(r,e,t,n){return new K(w.tag,Zr(r,e+1,n),9)}function Vp(r,e){Ft(r,w.tag.majorEncoded,e.value)}Vp.compareTokens=xn.compareTokens;Vp.encodedSize=function(e){return Ft.encodedSize(e.value)};var Ly=20,Ny=21,Dy=22,Oy=23;function TS(r,e,t,n){if(n.allowUndefined===!1)throw new Error(`${ee} undefined values are not supported`);return n.coerceUndefinedToNull===!0?new K(w.null,null,1):new K(w.undefined,void 0,1)}function _S(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${ee} indefinite length items not allowed`);return new K(w.break,void 0,1)}function By(r,e,t){if(t){if(t.allowNaN===!1&&Number.isNaN(r))throw new Error(`${ee} NaN values are not supported`);if(t.allowInfinity===!1&&(r===1/0||r===-1/0))throw new Error(`${ee} Infinity values are not supported`)}return new K(w.float,r,e)}function IS(r,e,t,n){return By(My(r,e+1),3,n)}function kS(r,e,t,n){return By(Uy(r,e+1),5,n)}function CS(r,e,t,n){return By(NS(r,e+1),9,n)}function Kp(r,e,t){let n=e.value;if(n===!1)r.push([w.float.majorEncoded|Ly]);else if(n===!0)r.push([w.float.majorEncoded|Ny]);else if(n===null)r.push([w.float.majorEncoded|Dy]);else if(n===void 0)r.push([w.float.majorEncoded|Oy]);else{let o,i=!1;(!t||t.float64!==!0)&&(PS(n),o=My(Yn,1),n===o||Number.isNaN(n)?(Yn[0]=249,r.push(Yn.slice(0,3)),i=!0):(LS(n),o=Uy(Yn,1),n===o&&(Yn[0]=250,r.push(Yn.slice(0,5)),i=!0))),i||(NM(n),o=NS(Yn,1),Yn[0]=251,r.push(Yn.slice(0,9)))}}Kp.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){PS(n);let o=My(Yn,1);if(n===o||Number.isNaN(n))return 3;if(LS(n),o=Uy(Yn,1),n===o)return 5}return 9};var RS=new ArrayBuffer(9),En=new DataView(RS,1),Yn=new Uint8Array(RS,0);function PS(r){if(r===1/0)En.setUint16(0,31744,!1);else if(r===-1/0)En.setUint16(0,64512,!1);else if(Number.isNaN(r))En.setUint16(0,32256,!1);else{En.setFloat32(0,r);let e=En.getUint32(0),t=(e&2139095040)>>23,n=e&8388607;if(t===255)En.setUint16(0,31744,!1);else if(t===0)En.setUint16(0,(e&2147483648)>>16|n>>13,!1);else{let o=t-127;o<-24?En.setUint16(0,0):o<-14?En.setUint16(0,(e&2147483648)>>16|1<<24+o,!1):En.setUint16(0,(e&2147483648)>>16|o+15<<10|n>>13,!1)}}}function My(r,e){if(r.length-e<2)throw new Error(`${ee} 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 LS(r){En.setFloat32(0,r,!1)}function Uy(r,e){if(r.length-e<4)throw new Error(`${ee} not enough data for float32`);let t=(r.byteOffset||0)+e;return new DataView(r.buffer,t,4).getFloat32(0,!1)}function NM(r){En.setFloat64(0,r,!1)}function NS(r,e){if(r.length-e<8)throw new Error(`${ee} not enough data for float64`);let t=(r.byteOffset||0)+e;return new DataView(r.buffer,t,8).getFloat64(0,!1)}Kp.compareTokens=xn.compareTokens;function Be(r,e,t){throw new Error(`${ee} encountered invalid minor (${t}) for major ${r[e]>>>5}`)}function Hp(r){return()=>{throw new Error(`${ee} ${r}`)}}var Y=[];for(let r=0;r<=23;r++)Y[r]=Be;Y[24]=Vv;Y[25]=Kv;Y[26]=Hv;Y[27]=qv;Y[28]=Be;Y[29]=Be;Y[30]=Be;Y[31]=Be;for(let r=32;r<=55;r++)Y[r]=Be;Y[56]=zv;Y[57]=Wv;Y[58]=Gv;Y[59]=Yv;Y[60]=Be;Y[61]=Be;Y[62]=Be;Y[63]=Be;for(let r=64;r<=87;r++)Y[r]=Xv;Y[88]=Qv;Y[89]=Zv;Y[90]=Jv;Y[91]=eS;Y[92]=Be;Y[93]=Be;Y[94]=Be;Y[95]=Hp("indefinite length bytes/strings are not supported");for(let r=96;r<=119;r++)Y[r]=rS;Y[120]=nS;Y[121]=oS;Y[122]=iS;Y[123]=sS;Y[124]=Be;Y[125]=Be;Y[126]=Be;Y[127]=Hp("indefinite length bytes/strings are not supported");for(let r=128;r<=151;r++)Y[r]=cS;Y[152]=lS;Y[153]=uS;Y[154]=dS;Y[155]=fS;Y[156]=Be;Y[157]=Be;Y[158]=Be;Y[159]=hS;for(let r=160;r<=183;r++)Y[r]=pS;Y[184]=mS;Y[185]=gS;Y[186]=yS;Y[187]=wS;Y[188]=Be;Y[189]=Be;Y[190]=Be;Y[191]=bS;for(let r=192;r<=215;r++)Y[r]=xS;Y[216]=ES;Y[217]=vS;Y[218]=SS;Y[219]=AS;Y[220]=Be;Y[221]=Be;Y[222]=Be;Y[223]=Be;for(let r=224;r<=243;r++)Y[r]=Hp("simple values are not supported");Y[244]=Be;Y[245]=Be;Y[246]=Be;Y[247]=TS;Y[248]=Hp("simple values are not supported");Y[249]=IS;Y[250]=kS;Y[251]=CS;Y[252]=Be;Y[253]=Be;Y[254]=Be;Y[255]=_S;var Xn=[];for(let r=0;r<24;r++)Xn[r]=new K(w.uint,r,1);for(let r=-1;r>=-24;r--)Xn[31-r]=new K(w.negint,r,1);Xn[64]=new K(w.bytes,new Uint8Array(0),1);Xn[96]=new K(w.string,"",1);Xn[128]=new K(w.array,0,1);Xn[160]=new K(w.map,0,1);Xn[244]=new K(w.false,!1,1);Xn[245]=new K(w.true,!0,1);Xn[246]=new K(w.null,null,1);function DS(r){switch(r.type){case w.false:return Ao([244]);case w.true:return Ao([245]);case w.null:return Ao([246]);case w.bytes:return r.value.length?void 0:Ao([64]);case w.string:return r.value===""?Ao([96]):void 0;case w.array:return r.value===0?Ao([128]):void 0;case w.map:return r.value===0?Ao([160]):void 0;case w.uint:return r.value<24?Ao([Number(r.value)]):void 0;case w.negint:if(r.value>=-24)return Ao([31-Number(r.value)])}}var BS=Object.freeze({float64:!0,mapSorter:FM,quickEncodeToken:DS});function OM(){let r=[];return r[w.uint.major]=xn,r[w.negint.major]=Mp,r[w.bytes.major]=el,r[w.string.major]=aS,r[w.array.major]=Fp,r[w.map.major]=$p,r[w.tag.major]=Vp,r[w.float.major]=Kp,r}var BM=OM(),MM=new Td,qp=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(`${ii} object contains circular references`);return new r(t,e)}},ns={null:new K(w.null,null),undefined:new K(w.undefined,void 0),true:new K(w.true,!0),false:new K(w.false,!1),emptyArray:new K(w.array,0),emptyMap:new K(w.map,0)},os={number(r,e,t,n){return!Number.isInteger(r)||!Number.isSafeInteger(r)?new K(w.float,r):r>=0?new K(w.uint,r):new K(w.negint,r)},bigint(r,e,t,n){return r>=BigInt(0)?new K(w.uint,r):new K(w.negint,r)},Uint8Array(r,e,t,n){return new K(w.bytes,r)},string(r,e,t,n){return new K(w.string,r)},boolean(r,e,t,n){return r?ns.true:ns.false},null(r,e,t,n){return ns.null},undefined(r,e,t,n){return ns.undefined},ArrayBuffer(r,e,t,n){return new K(w.bytes,new Uint8Array(r))},DataView(r,e,t,n){return new K(w.bytes,new Uint8Array(r.buffer,r.byteOffset,r.byteLength))},Array(r,e,t,n){if(!r.length)return t.addBreakTokens===!0?[ns.emptyArray,new K(w.break)]:ns.emptyArray;n=qp.createCheck(n,r);let o=[],i=0;for(let s of r)o[i++]=nl(s,t,n);return t.addBreakTokens?[new K(w.array,r.length),o,new K(w.break)]:[new K(w.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=qp.createCheck(n,r);let c=!o&&t.ignoreUndefinedProperties,l=0;for(let u of i){let d=o?r.get(u):r[u];c&&d===void 0||(a[l++]=[nl(u,t,n),nl(d,t,n)])}l<s&&(a.length=l)}return a?.length?(UM(a,t),t.addBreakTokens?[new K(w.map,a.length),a,new K(w.break)]:[new K(w.map,a.length),a]):t.addBreakTokens===!0?[ns.emptyMap,new K(w.break)]:ns.emptyMap},Tagged(r,e,t,n){return[new K(w.tag,r.tag),nl(r.value,t,n)]}};os.Map=os.Object;os.Buffer=os.Uint8Array;for(let r of"Uint8Clamped Uint16 Uint32 Int8 Int16 Int32 BigUint64 BigInt64 Float32 Float64".split(" "))os[`${r}Array`]=os.DataView;function nl(r,e={},t){let n=Dv(r),o=e&&e.typeEncoders&&e.typeEncoders[n]||os[n];if(typeof o=="function"){let s=o(r,n,e,t);if(s!=null)return s}let i=os[n];if(!i)throw new Error(`${ii} unsupported type: ${n}`);return i(r,n,e,t)}function UM(r,e){e.mapSorter&&r.sort(e.mapSorter)}function FM(r,e){if(r[0]instanceof K&&e[0]instanceof K){let t=r[0],n=e[0];return t._keyBytes||(t._keyBytes=OS(t.value)),n._keyBytes||(n._keyBytes=OS(n.value)),Op(t._keyBytes,n._keyBytes)}throw new Error("rfc8949MapSorter: complex key types are not supported yet")}function OS(r){return Fy(r,BM,BS)}function MS(r,e,t,n){if(Array.isArray(e))for(let o of e)MS(r,o,t,n);else t[e.type.major](r,e,n)}var Noe=w.uint.majorEncoded,Doe=w.negint.majorEncoded,Ooe=w.bytes.majorEncoded,Boe=w.string.majorEncoded,Moe=w.array.majorEncoded,Uoe=w.float.majorEncoded|Ly,Foe=w.float.majorEncoded|Ny,$oe=w.float.majorEncoded|Dy,Voe=w.float.majorEncoded|Oy,Koe=BigInt(-1),Hoe=BigInt(1);function Fy(r,e,t,n){let o=n instanceof Uint8Array,i=o?new Bp(n):MM,s=nl(r,t);if(!Array.isArray(s)&&t.quickEncodeToken){let a=t.quickEncodeToken(s);if(a)return o?(i.push(a),i.toBytes()):a;let c=e[s.type.major];if(c.encodedSize){let l=c.encodedSize(s,t);if(o||(i=new Td(l)),c(i,s,t),i.chunks.length!==1)throw new Error(`Unexpected error: pre-calculated length for ${s} was wrong`);return o?i.toBytes():Aa(i.chunks[0])}}return i.reset(),MS(i,s,e,t),i.toBytes(!0)}var $M={strict:!1,allowIndefinite:!0,allowUndefined:!0,allowBigInt:!0},zp=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=Xn[e];if(t===void 0){let n=Y[e];if(!n)throw new Error(`${ee} 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}},is=Symbol.for("DONE"),ol=Symbol.for("BREAK");function VM(r,e,t){let n=[];for(let o=0;o<r.value;o++){let i=ss(e,t);if(i===ol){if(r.value===1/0)break;throw new Error(`${ee} got unexpected break to lengthed array`)}if(i===is)throw new Error(`${ee} found array but not enough entries (got ${o}, expected ${r.value})`);n[o]=i}return n}function KM(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=ss(e,t);if(c===ol){if(r.value===1/0)break;throw new Error(`${ee} got unexpected break to lengthed map`)}if(c===is)throw new Error(`${ee} found map but not enough entries (got ${a} [no key], expected ${r.value})`);if(!n&&typeof c!="string")throw new Error(`${ee} non-string keys not supported (got ${typeof c})`);if(o&&(n&&s.has(c)||!n&&Object.hasOwn(i,c)))throw new Error(`${ee} found repeat map key "${c}"`);let l=ss(e,t);if(l===is)throw new Error(`${ee} found map but not enough entries (got ${a} [no value], expected ${r.value})`);n?s.set(c,l):i[c]=l}return n?s:i}function*HM(r,e,t){for(let n=0;n<r.value;n++){let o=ss(e,t);if(o===ol){if(r.value===1/0)break;throw new Error(`${ee} got unexpected break to lengthed map`)}if(o===is)throw new Error(`${ee} found map but not enough entries (got ${n} [no key], expected ${r.value})`);let i=ss(e,t);if(i===is)throw new Error(`${ee} found map but not enough entries (got ${n} [no value], expected ${r.value})`);yield[o,i]}}function qM(r,e){let t=!1,n=function(){if(t)throw new Error(`${ee} tag decode() may only be called once`);t=!0;let o=ss(r,e);if(o===is)throw new Error(`${ee} tag content missing`);if(o===ol)throw new Error(`${ee} got unexpected break in tag content`);return o};return n.entries=function(){if(t)throw new Error(`${ee} tag decode() may only be called once`);t=!0;let o=r.next();if(!w.equals(o.type,w.map))throw new Error(`${ee} entries() requires map content, got ${o.type.name}`);let i=[];for(let s of HM(o,r,e))i.push(s);return i},Object.defineProperty(n,"_called",{get(){return t},enumerable:!1}),n}function ss(r,e){if(r.done())return is;let t=r.next();if(w.equals(t.type,w.break))return ol;if(t.type.terminal)return t.value;if(w.equals(t.type,w.array))return VM(t,r,e);if(w.equals(t.type,w.map))return KM(t,r,e);if(w.equals(t.type,w.tag)){if(e.tags&&typeof e.tags[t.value]=="function"){let n=qM(r,e),o=e.tags[t.value](n);if(!n._called)throw new Error(`${ee} tag decoder must call decode() or entries()`);return o}throw new Error(`${ee} tag not supported (${t.value})`)}throw new Error("unsupported")}function $y(r,e){if(!(r instanceof Uint8Array))throw new Error(`${ee} data to decode must be a Uint8Array`);e=Object.assign({},$M,e);let t=Aa(r),n=e.tokenizer||new zp(t,e),o=ss(n,e);if(o===is)throw new Error(`${ee} did not find any content to decode`);if(o===ol)throw new Error(`${ee} got unexpected break`);return[o,r.subarray(n.pos())]}function Vy(r,e){let[t,n]=$y(r,e);if(n.length>0)throw new Error(`${ee} too many terminals, data makes no sense`);return t}var Wp=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(Wp.prototype,Symbol.toStringTag,{value:"Tagged"});var Ky=class extends Array{constructor(){super(),this.inRecursive=[]}prefix(e){let t=this.inRecursive[this.inRecursive.length-1];t&&(w.equals(t.type,w.array)&&(t.elements++,t.elements!==1&&e.push([44])),w.equals(t.type,w.map)&&(t.elements++,t.elements!==1&&(t.elements%2===1?e.push([44]):e.push([58]))))}[w.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)}[w.negint.major](e,t){this[w.uint.major](e,t)}[w.bytes.major](e,t){throw new Error(`${ii} unsupported type: Uint8Array`)}[w.string.major](e,t){this.prefix(e);let n=Ad(JSON.stringify(t.value));e.push(n.length>32?Aa(n):n)}[w.array.major](e,t){this.prefix(e),this.inRecursive.push({type:w.array,elements:0}),e.push([91])}[w.map.major](e,t){this.prefix(e),this.inRecursive.push({type:w.map,elements:0}),e.push([123])}[w.tag.major](e,t){}[w.float.major](e,t){if(t.type.name==="break"){let s=this.inRecursive.pop();if(s){if(w.equals(s.type,w.array))e.push([93]);else if(w.equals(s.type,w.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(`${ii} 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 zM(r,e){if(Array.isArray(r[0])||Array.isArray(e[0]))throw new Error(`${ii} complex map keys are not supported`);let t=r[0],n=e[0];if(t.type!==w.string||n.type!==w.string)throw new Error(`${ii} non-string map keys are not supported`);if(t<n)return-1;if(t>n)return 1;throw new Error(`${ii} unexpected duplicate map keys, this is not supported`)}var WM={addBreakTokens:!0,mapSorter:zM};function Hy(r,e){return e=Object.assign({},WM,e),Fy(r,new Ky,e)}var il=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(`${ee} 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(`${ee} 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 K(w.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(`${ee} unexpected token at position ${this._pos}`);if(!this.done()&&this.ch()===46){if(n)throw new Error(`${ee} 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 K(w.float,s,this._pos-e):this.options.allowBigInt!==!0||Number.isSafeInteger(s)?new K(s>=0?w.uint:w.negint,s,this._pos-e):new K(s>=0?w.uint:w.negint,BigInt(i),this._pos-e)}parseString(){if(this.ch()!==34)throw new Error(`${ee} 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 K(w.string,c,s)}}let e=this._pos,t=[],n=()=>{if(this._pos+4>=this.data.length)throw new Error(`${ee} 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(`${ee} 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(`${ee} unexpected unicode sequence at position ${this._pos}`);let c,l,u,d;switch(a){case 1:i<128&&(s=i);break;case 2:c=this.data[this._pos+1],(c&192)===128&&(d=(i&31)<<6|c&63,d>127&&(s=d));break;case 3:c=this.data[this._pos+1],l=this.data[this._pos+2],(c&192)===128&&(l&192)===128&&(d=(i&15)<<12|(c&63)<<6|l&63,d>2047&&(d<55296||d>57343)&&(s=d));break;case 4:c=this.data[this._pos+1],l=this.data[this._pos+2],u=this.data[this._pos+3],(c&192)===128&&(l&192)===128&&(u&192)===128&&(d=(i&15)<<18|(c&63)<<12|(l&63)<<6|u&63,d>65535&&d<1114112&&(s=d))}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(`${ee} 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(`${ee} unexpected string escape character at position ${this._pos}`)}break;case 34:return this._pos++,new K(w.string,$v(t),this._pos-e);default:if(i<32)throw new Error(`${ee} invalid control character at position ${this._pos}`);i<128?(t.push(i),this._pos++):o()}}throw new Error(`${ee} unexpected end of string at position ${this._pos}`)}parseValue(){switch(this.ch()){case 123:return this.modeStack.push("obj-start"),this._pos++,new K(w.map,1/0,1);case 91:return this.modeStack.push("array-start"),this._pos++,new K(w.array,1/0,1);case 34:return this.parseString();case 110:return this.expect([110,117,108,108]),new K(w.null,null,4);case 102:return this.expect([102,97,108,115,101]),new K(w.false,!1,5);case 116:return this.expect([116,114,117,101]),new K(w.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(`${ee} 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 K(w.break,void 0,1);if(this.ch()!==44)throw new Error(`${ee} 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 K(w.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 K(w.break,void 0,1);if(this.ch()!==44)throw new Error(`${ee} 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 K(w.break,void 0,1);let e=this.parseString();if(this.skipWhitespace(),this.ch()!==58)throw new Error(`${ee} 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(`${ee} unexpected parse state at position ${this._pos}; this shouldn't happen`)}}};function qy(r,e){return e=Object.assign({tokenizer:new il(r,e)},e),Vy(r,e)}function jM(r){return r instanceof ArrayBuffer?new Uint8Array(r,0,r.byteLength):r}function YM(r){if(r.asCID!==r&&r["/"]!==r.bytes)return null;let e=J.asCID(r);if(!e)return null;let t=e.toString();return[new K(w.map,1/0,1),new K(w.string,"/",1),new K(w.string,t,t.length),new K(w.break,void 0,1)]}function Gp(r){let e=xt.encode(r).slice(1);return[new K(w.map,1/0,1),new K(w.string,"/",1),new K(w.map,1/0,1),new K(w.string,"bytes",5),new K(w.string,e,e.length),new K(w.break,void 0,1),new K(w.break,void 0,1)]}function Qn(r){return Gp(new Uint8Array(r.buffer,r.byteOffset,r.byteLength))}function XM(r){return Gp(new Uint8Array(r))}function QM(){throw new Error("`undefined` is not supported by the IPLD Data Model and cannot be encoded")}function ZM(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 JM={typeEncoders:{Object:YM,Buffer:Gp,Uint8Array:Gp,Int8Array:Qn,Uint16Array:Qn,Int16Array:Qn,Uint32Array:Qn,Int32Array:Qn,Float32Array:Qn,Float64Array:Qn,Uint8ClampedArray:Qn,BigInt64Array:Qn,BigUint64Array:Qn,DataView:Qn,ArrayBuffer:XM,undefined:QM,number:ZM}},zy=class extends il{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(w.equals(e.type,w.map)){let t=this._next();if(w.equals(t.type,w.string)&&t.value==="/"){let n=this._next();if(w.equals(n.type,w.string)){let o=this._next();if(!w.equals(o.type,w.break))throw new Error("Invalid encoded CID form");return this.tokenBuffer.push(n),new K(w.tag,42,0)}if(w.equals(n.type,w.map)){let o=this._next();if(w.equals(o.type,w.string)&&o.value==="bytes"){let i=this._next();if(w.equals(i.type,w.string)){for(let a=0;a<2;a++){let c=this._next();if(!w.equals(c.type,w.break))throw new Error("Invalid encoded Bytes form")}let s=xt.decode(`m${i.value}`);return new K(w.bytes,s,i.value.length)}this.tokenBuffer.push(i)}this.tokenBuffer.push(o)}this.tokenBuffer.push(n)}this.tokenBuffer.push(t)}return e}},US={allowIndefinite:!1,allowUndefined:!1,allowNaN:!1,allowInfinity:!1,allowBigInt:!0,strict:!0,useMaps:!1,rejectDuplicateMapKeys:!0,tags:{42:r=>J.parse(r())}},eU="dag-json",Wy=297,FS=r=>Hy(r,JM),$S=r=>{let e=jM(r),t=Object.assign(US,{tokenizer:new zy(e,US)});return qy(e,t)},tU=r=>rU.decode(FS(r));var rU=new TextDecoder,nU=r=>$S(oU.encode(r)),oU=new TextEncoder;var Jy={};wt(Jy,{code:()=>Zy,createLink:()=>XS,createNode:()=>YS,decode:()=>yU,encode:()=>gU,name:()=>mU,prepare:()=>Xy,validate:()=>Qy});var iU=new TextDecoder;function jy(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 jp(r,e){let t;[t,e]=jy(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 VS(r,e){let t;return[t,e]=jy(r,e),[t&7,t>>3,e]}function sU(r){let e={},t=r.length,n=0;for(;n<t;){let o,i;if([o,i,n]=VS(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]=jp(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]=jp(r,n),e.Name=iU.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]=jy(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 KS(r){let e=r.length,t=0,n,o=!1,i;for(;t<e;){let a,c;if([a,c,t]=VS(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]=jp(r,t),n&&(o=!0)}else if(c===2){if(o)throw new Error("protobuf: (PBNode) duplicate Links section");n||(n=[]);let l;[l,t]=jp(r,t),n.push(sU(l))}else throw new Error(`protobuf: (PBNode) invalid fieldNumber, expected 1 or 2, got ${c}`)}if(t>e)throw new Error("protobuf: (PBNode) unexpected end of data");let s={};return i&&(s.Data=i),s.Links=n||[],s}var qS=new TextEncoder,HS=2**32,aU=2**31;function cU(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=Cd(e,t,r.Tsize)-1,e[t]=24}if(typeof r.Name=="string"){let n=qS.encode(r.Name);t-=n.length,e.set(n,t),t=Cd(e,t,n.length)-1,e[t]=18}return r.Hash&&(t-=r.Hash.length,e.set(r.Hash,t),t=Cd(e,t,r.Hash.length)-1,e[t]=10),e.length-t}function zS(r){let e=uU(r),t=new Uint8Array(e),n=e;if(r.Data&&(n-=r.Data.length,t.set(r.Data,n),n=Cd(t,n,r.Data.length)-1,t[n]=10),r.Links)for(let o=r.Links.length-1;o>=0;o--){let i=cU(r.Links[o],t.subarray(0,n));n-=i,n=Cd(t,n,i)-1,t[n]=18}return t}function lU(r){let e=0;if(r.Hash){let t=r.Hash.length;e+=1+t+sl(t)}if(typeof r.Name=="string"){let t=qS.encode(r.Name).length;e+=1+t+sl(t)}return typeof r.Tsize=="number"&&(e+=1+sl(r.Tsize)),e}function uU(r){let e=0;if(r.Data){let t=r.Data.length;e+=1+t+sl(t)}if(r.Links)for(let t of r.Links){let n=lU(t);e+=1+n+sl(n)}return e}function Cd(r,e,t){e-=sl(t);let n=e;for(;t>=aU;)r[e++]=t&127|128,t/=128;for(;t>=128;)r[e++]=t&127|128,t>>>=7;return r[e]=t,n}function sl(r){return r%2===0&&r++,Math.floor((dU(r)+6)/7)}function dU(r){let e=0;return r>=HS&&(r=Math.floor(r/HS),e=32),r>=65536&&(r>>>=16,e+=16),r>=256&&(r>>>=8,e+=8),e+fU[r]}var fU=[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 hU=["Data","Links"],pU=["Hash","Name","Tsize"],Yy=new TextEncoder;function GS(r,e){if(r===e)return 0;let t=r.Name?Yy.encode(r.Name):[],n=e.Name?Yy.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 WS(r,e){return!Object.keys(r).some(t=>!e.includes(t))}function jS(r){if(typeof r.asCID=="object"){let t=J.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=J.asCID(r.Hash);try{t||(typeof r.Hash=="string"?t=J.parse(r.Hash):r.Hash instanceof Uint8Array&&(t=J.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 Xy(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=Yy.encode(r.Data);else if(r.Data instanceof Uint8Array)e.Data=r.Data;else throw new TypeError("Invalid DAG-PB form");if(r.Links!==void 0)if(Array.isArray(r.Links))e.Links=r.Links.map(jS),e.Links.sort(GS);else throw new TypeError("Invalid DAG-PB form");else e.Links=[];return e}function Qy(r){if(!r||typeof r!="object"||Array.isArray(r)||r instanceof Uint8Array||r["/"]&&r["/"]===r.bytes)throw new TypeError("Invalid DAG-PB form");if(!WS(r,hU))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(!WS(t,pU))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&&GS(t,r.Links[e-1])===-1)throw new TypeError("Invalid DAG-PB form (links must be sorted by Name bytes)")}}function YS(r,e=[]){return Xy({Data:r,Links:e})}function XS(r,e,t){return jS({Hash:t,Name:r,Tsize:e})}function QS(r){return r instanceof ArrayBuffer?new Uint8Array(r,0,r.byteLength):r}var mU="dag-pb",Zy=112;function gU(r){Qy(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),zS(e)}function yU(r){let e=QS(r),t=KS(e),n={};return t.Data&&(n.Data=t.Data),t.Links&&(n.Links=t.Links.map(o=>{let i={};try{i.Hash=J.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 al(r){return r?.then!=null}function ZS(r=[],e){let t={[Zy]:Jy,[Ho]:Fs,[Cy]:Ry,[Wy]:Gy,[U3]:bh};return r.forEach(n=>{t[n.code]=n}),async n=>{let o=t[n];if(o==null&&e!=null){let i=e(n);al(i)?o=await i:o=i,t[o.code]=o}if(o!=null)return o;throw new ud(`Could not load codec for ${n}`)}}function JS(r=[],e){let t={[ft.code]:ft,[Eh.code]:Eh,[Et.code]:Et};return r.forEach(n=>{t[n.code]=n}),async n=>{let o=t[n];if(o==null&&e!=null){let i=e(n);al(i)?o=await i:o=i,t[o.code]=o}if(o!=null)return o;throw new ld(`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 vn=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 ai=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 Yp=0,cl=class extends Error{static name="IdentityHashDigestTooLongError";name="IdentityHashDigestTooLongError"},Xp=class extends ai{child;maxDigestLength;constructor(e,t){super(),this.child=e,this.maxDigestLength=t?.maxDigestLength}put(e,t,n){if(e.multihash.code===Yp){if(this.maxDigestLength!=null&&e.multihash.digest.byteLength>this.maxDigestLength)throw new cl(`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===Yp){if(this.maxDigestLength!=null&&e.multihash.digest.byteLength>this.maxDigestLength)throw new cl(`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 vn;yield*this.child.get(e,t)}has(e,t){if(e.multihash.code===Yp){if(this.maxDigestLength!=null&&e.multihash.digest.byteLength>this.maxDigestLength)throw new cl(`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===Yp){if(this.maxDigestLength!=null&&e.multihash.digest.byteLength>this.maxDigestLength)throw new cl(`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 wU(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 ll=wU;function bU(r){return r[Symbol.asyncIterator]!=null}function xU(r,e){let t=0;if(bU(r))return(async function*(){for await(let c of r)await e(c,t++)&&(yield c)})();let n=ll(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 Zn=xU;function EU(r){return r[Symbol.asyncIterator]!=null}function eA(r){return r?.then!=null}function vU(r,e){let t=0;if(EU(r))return(async function*(){for await(let c of r){let l=e(c,t++);eA(l)&&await l,yield c}})();let n=ll(r),{value:o,done:i}=n.next();if(i===!0)return(function*(){})();let s=e(o,t++);if(typeof s?.then=="function")return(async function*(){await s,yield o;for(let c of n){let l=e(c,t++);eA(l)&&await l,yield c}})();let a=e;return(function*(){yield o;for(let c of n)a(c,t++),yield c})()}var e8=vU;var SU=128,ul=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 Xp(e.blockstore,{maxDigestLength:t.maxIdentityHashDigestLength??SU}),this.getHasher=e.getHasher}async put(e,t,n={}){return await this.child.has(e,n)?(n.onProgress?.(new U("blocks:put:duplicate",e)),e):(n.onProgress?.(new U("blocks:put:providers:notify",e)),await Promise.all(this.blockBrokers.map(async o=>o.announce?.(e,n))),n.onProgress?.(new U("blocks:put:blockstore:put",e)),this.child.put(e,t,n))}async*putMany(e,t={}){let n=Zn(e,async({cid:i})=>{let s=await this.child.has(i,t);return s&&t.onProgress?.(new U("blocks:put-many:duplicate",i)),!s}),o=e8(n,async({cid:i})=>{t.onProgress?.(new U("blocks:put-many:providers:notify",i)),await Promise.all(this.blockBrokers.map(async s=>s.announce?.(i,t)))});t.onProgress?.(new U("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 ad("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 U("blocks:get:providers:get",e));let s=await tA(e,this.blockBrokers,i,{...t,log:this.log});t.onProgress?.(new U("blocks:get:blockstore:put",e)),await this.child.put(e,s,t),t.onProgress?.(new U("blocks:get:providers:notify",e)),await Promise.all(this.blockBrokers.map(async a=>a.announce?.(e,t))),yield s;return}t.onProgress?.(new U("blocks:get:blockstore:get",e)),yield*this.child.get(e,t)}async*getMany(e,t={}){t.onProgress?.(new U("blocks:get-many:blockstore:get-many")),yield*this.child.getMany(e8(e,async n=>{let o=await this.child.has(n,t),i=t.offline===!0;if(!o){if(i)throw new ad("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 U("blocks:get-many:providers:get",n));let a=await tA(n,this.blockBrokers,s,{...t,log:this.log});t.onProgress?.(new U("blocks:get-many:blockstore:put",n)),await this.child.put(n,a,t),t.onProgress?.(new U("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 U("blocks:delete:blockstore:delete",e)),await this.child.delete(e,t)}async*deleteMany(e,t={}){t.onProgress?.(new U("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 U("blocks:get-all:blockstore:get-many")),yield*this.child.getAll(e)}};async function tA(r,e,t,n){let o=TU(r,t),i=new AbortController,s=Ee([i.signal,n.signal]);i.signal;let a=[];for(let c of e)AU(c)&&a.push(c);if(a.length===0)throw new xa(`No block brokers capable of retrieving blocks are configured, the CID ${r} cannot be fetched from the network`);try{return await Promise.any(a.map(async c=>{try{let l=!1,u=await c.retrieve(r,{...n,signal:s,validateFn:async d=>{await o(d),n.signal?.throwIfAborted(),l=!0}});return l||(await o(u),n.signal?.throwIfAborted()),u}catch(l){throw n.log.error("could not retrieve verified block for %c from %s - %e",r,c.name,l),l}}))}catch(c){throw new J1(c.errors,`Failed to load block for ${r}`)}finally{i.abort(),s.clear()}}function AU(r){return typeof r.retrieve=="function"}var TU=(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(al(o)?n=await o:n=o,!ce(n.digest,r.multihash.digest))throw new _i("Hash of downloaded block did not match multihash from passed CID")}};var Qp=class extends ul{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=Ee([this.closeController.signal,n.signal]);try{return await super.put(e,t,{...n,signal:o})}finally{o.clear()}}async*putMany(e,t={}){let n=Ee([this.closeController.signal,t.signal]);try{yield*super.putMany(e,{...t,signal:n})}finally{n.clear()}}async*get(e,t={}){let n=Ee([this.closeController.signal,t.signal]);try{yield*super.get(e,{...t,signal:n})}finally{n.clear()}}async*getMany(e,t={}){let n=Ee([this.closeController.signal,t.signal]);try{yield*super.getMany(e,{...t,signal:n})}finally{n.clear()}}async delete(e,t={}){let n=Ee([this.closeController.signal,t.signal]);try{await super.delete(e,{...t,signal:n})}finally{n.clear()}}async*deleteMany(e,t={}){let n=Ee([this.closeController.signal,t.signal]);try{yield*super.deleteMany(e,{...t,signal:n})}finally{n.clear()}}async has(e,t={}){let n=Ee([this.closeController.signal,t.signal]);try{return await super.has(e,{...t,signal:n})}finally{n.clear()}}async*getAll(e={}){let t=Ee([this.closeController.signal,e.signal]);try{yield*super.getAll({...e,signal:t})}finally{t.clear()}}};var Zp=class extends ul{started;constructor(e,t={}){super(e,t),this.started=!1}isStarted(){return this.started}async start(){await Tt(this.child,...this.blockBrokers),this.started=!0}async stop(){await Pt(this.child,...this.blockBrokers),this.started=!1}unwrap(){return this.child}createSession(e,t){if(this.blockBrokers.length===0)throw new xa("No block brokers configured");let n=this.blockBrokers.map(o=>o.createSession?.(t)).filter(o=>o!=null);if(n.length===0)throw new xa(`No configured block brokers support sessions - tried ${this.blockBrokers.map(o=>o.name).join(", ")}`);return new Qp({blockstore:this.child,blockBrokers:n,getHasher:this.getHasher,logger:this.logger},{root:e})}};var _a=class extends we{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=Wt(this.maxProviders),this.initialProviders=[...t.providers??[]]}async retrieve(e,t={}){let n=xt.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=Ie(),s={promise:i.promise,observers:1,queryFilter:Wt(this.cidPeerFilterSize)};this.requests.set(n,s);let a=!1;this.initialPeerSearchComplete==null&&(a=!0,this.log=this.logger.forComponent(`${this.logName}:${e}`),this.initialPeerSearchComplete=this.findProviders(e,this.minProviders,t));let c=!1,l=new Yt({concurrency:this.maxProviders});l.addEventListener("failure",f=>{this.log.error("error querying provider %s, evicting from session - %e",f.detail.job.options.provider,f.detail.error),this.evict(f.detail.job.options.provider)}),l.addEventListener("success",f=>{c=!0,i.resolve(f.detail.result)}),l.addEventListener("idle",()=>{if(c){this.log.trace("session idle, found block");return}if(t.signal?.aborted===!0){this.log.trace("session idle, signal aborted");return}Promise.resolve().then(async()=>{this.log("no session peers had block for for %c, finding new providers",e);for(let f=0;f<this.minProviders&&this.providers.length!==0;f++){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(f=>{this.log.error("could not find new providers for %c - %e",e,f),i.reject(f)})});let u=f=>{let h=this.toFilterKey(f.detail);s.queryFilter.has(h)||(s.queryFilter.add(h),this.emitFoundProviderProgressEvent(e,f.detail,t),l.add(async()=>this.queryProvider(e,f.detail,t),{provider:f.detail}).catch(p=>{t.signal?.aborted!==!0&&this.log.error("error retrieving session block for %c - %e",e,p)}))};if(this.addEventListener("provider",u),a)try{await Ze(this.initialPeerSearchComplete,t.signal),a&&this.log("found initial session peers for %c",e)}catch(f){throw a&&this.log("failed to find initial session peers for %c - %e",e,f),this.requests.delete(n),s.observers>1&&i.reject(f),f}Promise.all([...this.providers].filter(f=>{let h=this.toFilterKey(f),p=s.queryFilter.has(h);return p||s.queryFilter.add(this.toFilterKey(f)),!p}).map(async f=>l.add(async()=>this.queryProvider(e,f,t),{provider:f}))).catch(f=>{t.signal?.aborted!==!0&&this.log.error("error retrieving session block for %c - %e",e,f)});let d=()=>{i.reject(new fr(t.signal?.reason??"Session aborted")),l.abort()};t.signal?.addEventListener("abort",d);try{return await i.promise}finally{this.removeEventListener("provider",u),t.signal?.removeEventListener("abort",d),l.clear(),this.requests.delete(n)}}evict(e){this.evictionFilter.add(this.toFilterKey(e));let t=this.providers.findIndex(n=>this.equals(n,e));t!==-1&&this.providers.splice(t,1)}isEvicted(e){return this.evictionFilter.has(this.toFilterKey(e))}hasProvider(e){return!!(this.providers.find(t=>this.equals(t,e))!=null||this.isEvicted(e))}async addPeer(e,t){let n=await this.convertToProvider(e,"manually-added",t);n==null||this.hasProvider(n)||(this.providers.push(n),this.safeDispatchEvent("provider",{detail:n}))}async findProviders(e,t,n){let o=Ie(),i=0;return Promise.resolve().then(async()=>{this.log("finding %d-%d new provider(s) for %c - %d initial providers",t,this.maxProviders,e,this.initialProviders.length);let s=this,a=async function*(){for(;s.initialProviders.length>0;){let l=s.initialProviders.pop();if(l==null)continue;let u=await s.convertToProvider(l,"manual",n);u!=null&&(yield u)}},c=async function*(){yield*a(),yield*s.findNewProviders(e,n)};for await(let l of c()){if(this.providers.length===this.maxProviders||n.signal?.aborted===!0)break;if(!this.hasProvider(l)&&(this.log("found %d providers, %d in session",i,this.providers.length),this.providers.push(l),this.safeDispatchEvent("provider",{detail:l}),i++,this.providers.length===t&&(this.log("session is ready with %d peer(s), new peers present",this.providers.length),o.resolve()),this.providers.length===this.maxProviders)){this.log("found max session peers %d",this.providers.length);break}}if(this.log("found %d new session peers while trying to find %d, %d in session",i,t,this.providers.length),this.providers.length<t)throw new cd(`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 Jp=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=JS(e.hashers,e.loadHasher),this.getCodec=ZS(e.codecs,e.loadCodec),this.dns=e.dns??Th(),this.metrics=e.metrics,this.libp2p=e.libp2p,this.events=new we;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 rp(t,{routers:(e.routers??[]).flatMap(o=>{typeof o=="function"&&(o=o(t));let i=[o],s=_U(o);s!=null&&i.push(s);let a=IU(o);return a!=null&&i.push(a),i}),providerLookupConcurrency:e.providerLookupConcurrency}),t.blockBrokers=e.blockBrokers.map(o=>o(t));let n=new Zp(t,e);this.pins=new tp(e.datastore,n,this.getCodec),this.blockstore=new bp(n,this.pins,this.routing,{holdGcLock:e.holdGcLock??!0}),this.datastore=e.datastore}async start(){await _E(this.datastore),await Tt(this.blockstore,this.datastore,this.routing,this.libp2p),this.events.dispatchEvent(new CustomEvent("start",{detail:this}))}async stop(){await Pt(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 Sr(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 U("helia:gc:deleted",i))}catch(s){n.log.error("error during gc - %e",s),e.onProgress?.(new U("helia:gc:error",s))}})()))}finally{t()}this.log("gc finished")}};function _U(r){return r?.[$o]}function IU(r){return r?.[Ko]}function kU(r){return r[Symbol.asyncIterator]!=null}function CU(r,e){let t=0;if(kU(r))return(async function*(){for await(let c of r)yield e(c,t++)})();let n=ll(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 Sn=CU;function RU(r){return r[Symbol.asyncIterator]!=null}function PU(r,e){return RU(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 as=PU;var Rd="/ipfs/bitswap/1.2.0";var dt;(function(r){r.WantBlock="WantBlock",r.WantHave="WantHave"})(dt||(dt={}));var t8;(function(r){r[r.WantBlock=0]="WantBlock",r[r.WantHave=1]="WantHave"})(t8||(t8={}));(function(r){r.codec=()=>ut(t8)})(dt||(dt={}));var Ia;(function(r){let e;r.codec=()=>(e==null&&(e=ye((i,s,a={})=>{a.lengthDelimited!==!1&&s.fork(),i.cid!=null&&i.cid.byteLength>0&&(s.uint32(10),s.bytes(i.cid)),i.priority!=null&&i.priority!==0&&(s.uint32(16),s.int32(i.priority)),i.cancel!=null&&(s.uint32(24),s.bool(i.cancel)),i.wantType!=null&&(s.uint32(32),dt.codec().encode(i.wantType,s)),i.sendDontHave!=null&&(s.uint32(40),s.bool(i.sendDontHave)),a.lengthDelimited!==!1&&s.ldelim()},(i,s,a={})=>{let c={cid:be(0),priority:0},l=s==null?i.len:i.pos+s;for(;i.pos<l;){let u=i.uint32();switch(u>>>3){case 1:{c.cid=i.bytes();break}case 2:{c.priority=i.int32();break}case 3:{c.cancel=i.bool();break}case 4:{c.wantType=dt.codec().decode(i);break}case 5:{c.sendDontHave=i.bool();break}default:{i.skipType(u&7);break}}}return c},function*(i,s,a,c={}){let l=s==null?i.len:i.pos+s;for(;i.pos<l;){let u=i.uint32();switch(u>>>3){case 1:{yield{field:`${a}.cid`,value:i.bytes()};break}case 2:{yield{field:`${a}.priority`,value:i.int32()};break}case 3:{yield{field:`${a}.cancel`,value:i.bool()};break}case 4:{yield{field:`${a}.wantType`,value:dt.codec().decode(i)};break}case 5:{yield{field:`${a}.sendDontHave`,value:i.bool()};break}default:{i.skipType(u&7);break}}}})),e);function t(i){return me(i,r.codec())}r.encode=t;function n(i,s){return pe(i,r.codec(),s)}r.decode=n;function o(i,s){return ge(i,r.codec(),s)}r.stream=o})(Ia||(Ia={}));var Pd;(function(r){let e;r.codec=()=>(e==null&&(e=ye((i,s,a={})=>{if(a.lengthDelimited!==!1&&s.fork(),i.entries!=null&&i.entries.length>0)for(let c of i.entries)s.uint32(10),Ia.codec().encode(c,s);i.full!=null&&(s.uint32(16),s.bool(i.full)),a.lengthDelimited!==!1&&s.ldelim()},(i,s,a={})=>{let c={entries:[]},l=s==null?i.len:i.pos+s;for(;i.pos<l;){let u=i.uint32();switch(u>>>3){case 1:{if(a.limits?.entries!=null&&c.entries.length===a.limits.entries)throw new Se('Decode error - repeated field "entries" had too many elements');c.entries.push(Ia.codec().decode(i,i.uint32(),{limits:a.limits?.entries$}));break}case 2:{c.full=i.bool();break}default:{i.skipType(u&7);break}}}return c},function*(i,s,a,c={}){let l={entries:0},u=s==null?i.len:i.pos+s;for(;i.pos<u;){let d=i.uint32();switch(d>>>3){case 1:{if(c.limits?.entries!=null&&l.entries===c.limits.entries)throw new Se('Streaming decode error - repeated field "entries" had too many elements');for(let f of Ia.codec().stream(i,i.uint32(),`${a}.entries[]`,{limits:c.limits?.entries$}))yield{...f,index:l.entries};l.entries++;break}case 2:{yield{field:`${a}.full`,value:i.bool()};break}default:{i.skipType(d&7);break}}}})),e);function t(i){return me(i,r.codec())}r.encode=t;function n(i,s){return pe(i,r.codec(),s)}r.decode=n;function o(i,s){return ge(i,r.codec(),s)}r.stream=o})(Pd||(Pd={}));var ka;(function(r){let e;r.codec=()=>(e==null&&(e=ye((i,s,a={})=>{a.lengthDelimited!==!1&&s.fork(),i.prefix!=null&&i.prefix.byteLength>0&&(s.uint32(10),s.bytes(i.prefix)),i.data!=null&&i.data.byteLength>0&&(s.uint32(18),s.bytes(i.data)),a.lengthDelimited!==!1&&s.ldelim()},(i,s,a={})=>{let c={prefix:be(0),data:be(0)},l=s==null?i.len:i.pos+s;for(;i.pos<l;){let u=i.uint32();switch(u>>>3){case 1:{c.prefix=i.bytes();break}case 2:{c.data=i.bytes();break}default:{i.skipType(u&7);break}}}return c},function*(i,s,a,c={}){let l=s==null?i.len:i.pos+s;for(;i.pos<l;){let u=i.uint32();switch(u>>>3){case 1:{yield{field:`${a}.prefix`,value:i.bytes()};break}case 2:{yield{field:`${a}.data`,value:i.bytes()};break}default:{i.skipType(u&7);break}}}})),e);function t(i){return me(i,r.codec())}r.encode=t;function n(i,s){return pe(i,r.codec(),s)}r.decode=n;function o(i,s){return ge(i,r.codec(),s)}r.stream=o})(ka||(ka={}));var Jr;(function(r){r.HaveBlock="HaveBlock",r.DoNotHaveBlock="DoNotHaveBlock"})(Jr||(Jr={}));var e0;(function(r){r[r.HaveBlock=0]="HaveBlock",r[r.DoNotHaveBlock=1]="DoNotHaveBlock"})(e0||(e0={}));(function(r){r.codec=()=>ut(e0)})(Jr||(Jr={}));var Ca;(function(r){let e;r.codec=()=>(e==null&&(e=ye((i,s,a={})=>{a.lengthDelimited!==!1&&s.fork(),i.cid!=null&&i.cid.byteLength>0&&(s.uint32(10),s.bytes(i.cid)),i.type!=null&&e0[i.type]!==0&&(s.uint32(16),Jr.codec().encode(i.type,s)),a.lengthDelimited!==!1&&s.ldelim()},(i,s,a={})=>{let c={cid:be(0),type:Jr.HaveBlock},l=s==null?i.len:i.pos+s;for(;i.pos<l;){let u=i.uint32();switch(u>>>3){case 1:{c.cid=i.bytes();break}case 2:{c.type=Jr.codec().decode(i);break}default:{i.skipType(u&7);break}}}return c},function*(i,s,a,c={}){let l=s==null?i.len:i.pos+s;for(;i.pos<l;){let u=i.uint32();switch(u>>>3){case 1:{yield{field:`${a}.cid`,value:i.bytes()};break}case 2:{yield{field:`${a}.type`,value:Jr.codec().decode(i)};break}default:{i.skipType(u&7);break}}}})),e);function t(i){return me(i,r.codec())}r.encode=t;function n(i,s){return pe(i,r.codec(),s)}r.decode=n;function o(i,s){return ge(i,r.codec(),s)}r.stream=o})(Ca||(Ca={}));var Ra;(function(r){let e;r.codec=()=>(e==null&&(e=ye((i,s,a={})=>{if(a.lengthDelimited!==!1&&s.fork(),i.wantlist!=null&&(s.uint32(10),Pd.codec().encode(i.wantlist,s)),i.blocks!=null&&i.blocks.length>0)for(let c of i.blocks)s.uint32(26),ka.codec().encode(c,s);if(i.blockPresences!=null&&i.blockPresences.length>0)for(let c of i.blockPresences)s.uint32(34),Ca.codec().encode(c,s);i.pendingBytes!=null&&i.pendingBytes!==0&&(s.uint32(40),s.int32(i.pendingBytes)),a.lengthDelimited!==!1&&s.ldelim()},(i,s,a={})=>{let c={blocks:[],blockPresences:[],pendingBytes:0},l=s==null?i.len:i.pos+s;for(;i.pos<l;){let u=i.uint32();switch(u>>>3){case 1:{c.wantlist=Pd.codec().decode(i,i.uint32(),{limits:a.limits?.wantlist});break}case 3:{if(a.limits?.blocks!=null&&c.blocks.length===a.limits.blocks)throw new Se('Decode error - repeated field "blocks" had too many elements');c.blocks.push(ka.codec().decode(i,i.uint32(),{limits:a.limits?.blocks$}));break}case 4:{if(a.limits?.blockPresences!=null&&c.blockPresences.length===a.limits.blockPresences)throw new Se('Decode error - repeated field "blockPresences" had too many elements');c.blockPresences.push(Ca.codec().decode(i,i.uint32(),{limits:a.limits?.blockPresences$}));break}case 5:{c.pendingBytes=i.int32();break}default:{i.skipType(u&7);break}}}return c},function*(i,s,a,c={}){let l={blocks:0,blockPresences:0},u=s==null?i.len:i.pos+s;for(;i.pos<u;){let d=i.uint32();switch(d>>>3){case 1:{yield*Pd.codec().stream(i,i.uint32(),`${a}.wantlist`,{limits:c.limits?.wantlist});break}case 3:{if(c.limits?.blocks!=null&&l.blocks===c.limits.blocks)throw new Se('Streaming decode error - repeated field "blocks" had too many elements');for(let f of ka.codec().stream(i,i.uint32(),`${a}.blocks[]`,{limits:c.limits?.blocks$}))yield{...f,index:l.blocks};l.blocks++;break}case 4:{if(c.limits?.blockPresences!=null&&l.blockPresences===c.limits.blockPresences)throw new Se('Streaming decode error - repeated field "blockPresences" had too many elements');for(let f of Ca.codec().stream(i,i.uint32(),`${a}.blockPresences[]`,{limits:c.limits?.blockPresences$}))yield{...f,index:l.blockPresences};l.blockPresences++;break}case 5:{yield{field:`${a}.pendingBytes`,value:i.int32()};break}default:{i.skipType(d&7);break}}}})),e);function t(i){return me(i,r.codec())}r.encode=t;function n(i,s){return pe(i,r.codec(),s)}r.decode=n;function o(i,s){return ge(i,r.codec(),s)}r.stream=o})(Ra||(Ra={}));function rA(r,e){for(let[t,n]of e.wantlist.entries()){let o=r.wantlist.get(t);o!=null&&(o.priority>n.priority&&(n.priority=o.priority),n.cancel=n.cancel??o.cancel,n.wantType=n.wantType??o.wantType,n.sendDontHave=n.sendDontHave??o.sendDontHave),r.wantlist.set(t,n)}for(let[t,n]of e.blockPresences.entries())r.blockPresences.set(t,n);for(let[t,n]of e.blocks.entries())r.blocks.set(t,n);return e.full&&!r.full&&(r.full=!0),r}var t0=class extends Error{static name="BlockTooLargeError";constructor(e="Block too large"){super(e),this.name="BlockTooLargeError"}};var LU=4193648,NU=LU+16;function*nA(r,e){let t=[...r.wantlist.values()],n=[...r.blockPresences.values()],o=[...r.blocks.values()],i=0,s=0,a=0,c=!1;for(;;){let l={wantlist:{full:r.full??!1,entries:[]},blockPresences:[],blocks:[],pendingBytes:0},u=Ra.encode(l).byteLength,{added:d,hasMore:f,newSize:h}=r8(o,l.blocks,a,e,u,DU);a+=d,u=h;let p=f;({added:d,hasMore:f,newSize:h}=r8(n,l.blockPresences,s,e,u,OU)),s+=d,u=h;let y=f;if({added:d,hasMore:f,newSize:h}=r8(t,l.wantlist.entries,i,e,u,BU),i+=d,u=h,c=!p&&!y&&!f,c||(l.wantlist.full=!1),yield Ra.encode(l),c)break}}function r8(r,e,t,n,o,i){let s=0,a=!1;for(let c=t;c<r.length;c++){let l=r[c],u=i(l);if(u>NU)throw new t0("Cannot send block as after encoding it is over the max message size");let d=o+u;if(d>n){a=!0;break}e.push(l),s++,o=d}return{hasMore:a,added:s,newSize:o}}function DU(r){return n8(3,ka.encode(r))}function OU(r){return n8(4,Ca.encode(r))}function BU(r){return n8(1,Ia.encode(r))}function n8(r,e){let t=Ae(r),n=Ae(e.byteLength);return t+n+e.byteLength}var r0=class extends we{log;libp2p;routing;protocols;running;maxInboundStreams;maxOutboundStreams;messageReceiveTimeout;messageSendTimeout;registrarIds;metrics;sendQueue;runOnLimitedConnections;maxOutgoingMessageSize;maxIncomingMessageSize;constructor(e,t={}){super(),this.log=e.logger.forComponent("helia:bitswap:network"),this.libp2p=e.libp2p,this.routing=e.routing,this.protocols=t.protocols??[Rd],this.registrarIds=[],this.running=!1,this._onStream=this._onStream.bind(this),this.maxInboundStreams=t.maxInboundStreams??1024,this.maxOutboundStreams=t.maxOutboundStreams??1024,this.messageReceiveTimeout=t.messageReceiveTimeout??1e4,this.messageSendTimeout=t.messageSendTimeout??1e4,this.runOnLimitedConnections=t.runOnLimitedConnections??!1,this.maxIncomingMessageSize=t.maxIncomingMessageSize??4194304,this.maxOutgoingMessageSize=t.maxOutgoingMessageSize??t.maxIncomingMessageSize??4194304,this.metrics={blocksSent:e.metrics?.registerCounter("helia_bitswap_sent_blocks_total"),dataSent:e.metrics?.registerCounter("helia_bitswap_sent_data_bytes_total")},this.sendQueue=new Qt({concurrency:t.messageSendConcurrency??50,metrics:e.metrics,metricName:"helia_bitswap_message_send_queue"})}async start(){if(this.running)return;this.running=!0,await this.libp2p.handle(this.protocols,this._onStream,{maxInboundStreams:this.maxInboundStreams,maxOutboundStreams:this.maxOutboundStreams,runOnLimitedConnection:this.runOnLimitedConnections});let e={onConnect:t=>{this.safeDispatchEvent("peer:connected",{detail:t})},onDisconnect:t=>{this.safeDispatchEvent("peer:disconnected",{detail:t})}};this.registrarIds=[];for(let t of this.protocols)this.registrarIds.push(await this.libp2p.register(t,e));this.libp2p.getConnections().forEach(t=>{this.safeDispatchEvent("peer:connected",{detail:t.remotePeer})})}async stop(){if(this.running=!1,await this.libp2p.unhandle(this.protocols),this.registrarIds!=null){for(let e of this.registrarIds)this.libp2p.unregister(e);this.registrarIds=[]}}_onStream(e,t){this.running&&Promise.resolve().then(async()=>{this.log("incoming new bitswap %s stream from %p",e.protocol,t.remotePeer);let n=()=>{e.status==="open"?e.abort(new fo(`Incoming Bitswap stream timed out after ${this.messageReceiveTimeout}ms`)):this.log("stream aborted with status %s",e.status)},o=AbortSignal.timeout(this.messageReceiveTimeout);o.addEventListener("abort",n),await e.close({signal:o});let i=jt();e.addEventListener("message",s=>{i.push(s.data)}),e.addEventListener("remoteCloseWrite",()=>{i.end()}),e.addEventListener("close",s=>{s.error!=null&&i.end(s.error)});for await(let s of ga(i,{maxDataLength:this.maxIncomingMessageSize}))try{let a=Ra.decode(s);this.log("incoming new bitswap %s message from %p on stream",e.protocol,t.remotePeer,e.id),this.safeDispatchEvent("bitswap:message",{detail:{peer:t.remotePeer,message:a,connection:t}}),o.removeEventListener("abort",n),o=AbortSignal.timeout(this.messageReceiveTimeout),o.addEventListener("abort",n)}catch(a){this.log.error("error reading incoming bitswap message from %p on stream - %e",t.remotePeer,e.id,a),e.abort(a);break}}).catch(n=>{this.log.error("error handling incoming stream from %p - %e",t.remotePeer,n),e.abort(n)})}async*findProviders(e,t){t?.onProgress?.(new U("bitswap:find-providers",e));for await(let n of this.routing.findProviders(e,t)){if(!await this.libp2p.isDialable(n.multiaddrs,{runOnLimitedConnection:this.runOnLimitedConnections})){this.log("skipping peer %p as they are not dialable - %a",n.id,n.multiaddrs);continue}t?.onProgress?.(new U("bitswap:found-provider",{type:"bitswap",cid:e,provider:n,routing:n.routing})),yield n}}async findAndConnect(e,t){t?.providers!=null&&await Promise.all(t.providers.map(async n=>this.connectTo(n).catch(o=>{this.log.error("could not connect to supplied provider - %e",o)}))),await Sr(Sn(as(this.findProviders(e,t),t?.maxProviders??3),async n=>this.connectTo(n.id,t))).catch(n=>{this.log.error(n)})}async sendMessage(e,t,n){if(!this.running)throw new Error("network isn't running");let o=this.sendQueue.queue.find(i=>e.equals(i.options.peerId)&&i.status==="queued");if(o!=null){o.options.message=rA(o.options.message,t),await o.join(n);return}await this.sendQueue.add(async i=>{let s=i.message;if(s==null)throw new T("No message to send");this.log("sendMessage to %p",e),i.onProgress?.(new U("bitswap:send-wantlist",e));let a=await this.libp2p.dialProtocol(e,Rd,i);await a.closeRead(i);try{for(let c of nA(s,this.maxOutgoingMessageSize))a.send(ti.single(c))||await a.onDrain(i);await a.close(i)}catch(c){this.log.error("error sending message to %p - %e",e,c),i?.onProgress?.(new U("bitswap:send-wantlist:error",{peer:e,error:c})),a.abort(c)}this._updateSentStats(s.blocks)},{onProgress:n?.onProgress,peerId:e,signal:n?.signal??AbortSignal.timeout(this.messageSendTimeout),message:t})}async connectTo(e,t){if(!this.running)throw new Rn("Network isn't running");t?.onProgress?.(new U("bitswap:dial",e));let[n]=await Promise.all([this.libp2p.dial(e,t),br(this.libp2p,"peer:identify",t?.signal,{filter:o=>{if(!o.detail.peerId.equals(e))return!1;if(o.detail.protocols.includes(Rd))return!0;throw new tc(`${e} did not support ${Rd}`)}})]);return n}_updateSentStats(e){let t=0;for(let n of e.values())t+=n.data.byteLength;this.metrics.dataSent?.increment(t),this.metrics.blocksSent?.increment(e.size)}};var oA=Symbol.for("nodejs.util.inspect.custom"),WU=114,Ld=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()})`}[ph]=!0;toString(){return this.string==null&&(this.string=Ye.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return J.createV1(WU,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")}[oA](){return`PeerId(${this.toString()})`}},Nd=class extends Ld{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}},Dd=class extends Ld{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.publicKey}},Od=class extends Ld{type="secp256k1";publicKey;constructor(e){super({...e,type:"secp256k1"}),this.publicKey=e.publicKey}},GU=2336,Bd=class{type="url";multihash;publicKey;url;constructor(e){this.url=e.toString(),this.multihash=Et.digest(L(this.url))}[oA](){return`PeerId(${this.url})`}[ph]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return J.createV1(GU,this.toMultihash())}toJSON(){return this.toString()}equals(e){return e==null?!1:(e instanceof Uint8Array&&(e=D(e)),e.toString()===this.toString())}};var jU=114,iA=2336;function et(r,e){let t;if(r.charAt(0)==="1"||r.charAt(0)==="Q")t=Ge(Ye.decode(`z${r}`));else{if(r.startsWith("k51qzi5uqu5")||r.startsWith("kzwfwjn5ji4")||r.startsWith("k2k4r8")||r.startsWith("bafz"))return en(J.parse(r));if(e==null)throw new T('Please pass a multibase decoder for strings that do not start with "1" or "Q"');t=Ge(e.decode(r))}return yt(t)}function To(r){if(r.type==="Ed25519")return new Dd({multihash:r.toCID().multihash,publicKey:r});if(r.type==="secp256k1")return new Od({multihash:r.toCID().multihash,publicKey:r});if(r.type==="RSA")return new Nd({multihash:r.toCID().multihash,publicKey:r});throw new Pn}function sA(r){return To(r.publicKey)}function yt(r){if(XU(r))return new Nd({multihash:r});if(YU(r))try{let e=Zh(r);if(e.type==="Ed25519")return new Dd({multihash:r,publicKey:e});if(e.type==="secp256k1")return new Od({multihash:r,publicKey:e})}catch{let t=D(r.digest);return new Bd(new URL(t))}throw new _i("Supplied PeerID Multihash is invalid")}function en(r){if(r?.multihash==null||r.version==null||r.version===1&&r.code!==jU&&r.code!==iA)throw new lh("Supplied PeerID CID is invalid");if(r.code===iA){let e=D(r.multihash.digest);return new Bd(new URL(e))}return yt(r.multihash)}function YU(r){return r.code===Et.code}function XU(r){return r.code===ft.code}function Pa(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 n0(r){let e=Ge(Ye.decode(`z${r}`));return yt(e)}var ar=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 Pa(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 Pa(this.map.values(),e=>e.key)}values(){return Pa(this.map.values(),e=>e.value)}get size(){return this.map.size}};var tn=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 Pa(this.set.entries(),e=>{let t=n0(e[0]);return[t,t]})}forEach(e){this.set.forEach(t=>{let n=n0(t);e(n,n,this)})}has(e){return this.set.has(e.toString())}values(){return Pa(this.set.values(),e=>n0(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}};function o8(){return new tn}var o0=class{filter;constructor(e,t){this.filter=Wt(e,t)}has(e){return this.filter.has(e.toMultihash().bytes)}add(e){this.filter.add(e.toMultihash().bytes)}remove(e){this.filter.remove?.(e.toMultihash().bytes)}};function i8(r,e=.001){return new o0(r,e)}var s8=class extends ar{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 ci(r){let{name:e,metrics:t}=r,n;return t!=null?n=new s8({name:e,metrics:t}):n=new ar,n}var li=class{full;pendingBytes;wantlist;blocks;blockPresences;constructor(e=!1,t=0){this.full=e,this.wantlist=new Map,this.blocks=new Map,this.blockPresences=new Map,this.pendingBytes=0}addWantlistEntry(e,t){let n=xt.encode(e.multihash.bytes);this.wantlist.set(n,t)}addBlockPresence(e,t){let n=xt.encode(e.multihash.bytes);this.blockPresences.set(n,t)}addBlock(e,t){let n=xt.encode(e.multihash.bytes);this.blocks.set(n,t)}};function QU(r){let e=new Uint8Array(r.reduce((n,o)=>n+Ae(o),0)),t=0;for(let n of r)e=ir(n,e,t),t+=Ae(n);return e}var aA=QU;function a8(r){return aA([r.version,r.code,r.multihash.code,r.multihash.digest.byteLength])}var i0=class{peerId;blockstore;network;wants;exchangeCount;bytesSent;bytesReceived;lastExchange;maxSizeReplaceHasWithBlock;log;doNotResendBlockWindow;maxWantListSize;constructor(e,t){this.peerId=e.peerId,this.blockstore=e.blockstore,this.network=e.network,this.wants=new Map,this.log=e.logger.forComponent(`helia:bitswap:ledger:${e.peerId}`),this.exchangeCount=0,this.bytesSent=0,this.bytesReceived=0,this.maxSizeReplaceHasWithBlock=t.maxSizeReplaceHasWithBlock??1024,this.doNotResendBlockWindow=t.doNotResendBlockWindow??5e3,this.maxWantListSize=t.maxWantListSize??1024}sentBytes(e){this.exchangeCount++,this.lastExchange=new Date().getTime(),this.bytesSent+=e}receivedBytes(e){this.exchangeCount++,this.lastExchange=new Date().getTime(),this.bytesReceived+=e}debtRatio(){return this.bytesSent/(this.bytesReceived+1)}removeExpiredWants(){this.wants.forEach((e,t)=>{e.expires!=null&&e.expires<Date.now()&&this.wants.delete(t)})}addWants(e){if(e==null)return;e.full===!0&&this.wants.forEach((n,o)=>{n.status==="want"&&this.wants.delete(o)});for(let n of e.entries){let o=J.decode(n.cid),i=D(o.multihash.bytes,"base64");if(n.cancel===!0)this.log("peer %p cancelled want of block for %c",this.peerId,o),this.wants.delete(i);else{n.wantType===dt.WantHave?this.log("peer %p wanted block presence for %c",this.peerId,o):this.log("peer %p wanted block for %c",this.peerId,o);let s=this.wants.get(i);if(s!=null){let a=s.status==="sent"||s.status==="sending",c=s.wantType===dt.WantHave&&(n.wantType==null||n.wantType===dt.WantBlock);a&&c&&(s.status="want"),s.priority=n.priority,s.wantType=n.wantType??dt.WantBlock,s.sendDontHave=n.sendDontHave??!1;continue}this.wants.set(i,{cid:o,priority:n.priority,wantType:n.wantType??dt.WantBlock,sendDontHave:n.sendDontHave??!1,status:"want",created:Date.now()})}}let t=[...this.wants.entries()].filter(([n,o])=>o.status==="want");t.length>this.maxWantListSize&&this.truncateWants(t)}truncateWants(e){e=e.sort((n,o)=>n[1].created<o[1].created?-1:o[1].created<n[1].created?1:0).sort((n,o)=>n[1].haveBlock===!1?-1:o[1].haveBlock===!1?1:0).sort((n,o)=>n[1].priority<o[1].priority?-1:o[1].priority<n[1].priority?1:0);let t=e.length-this.maxWantListSize;for(let n=0;n<t;n++)this.wants.delete(e[n][0])}getWants(){return[...this.wants.values()]}hasWant(e){let t=D(e.multihash.bytes,"base64");return this.wants.has(t)}async sendBlocksToPeer(e){let t=new li,n=new Set;this.removeExpiredWants();let o=[...this.wants.entries()].filter(([i,s])=>s.status==="want");o.forEach(([i,s])=>{s.status="sending"});for(let[i,s]of o)try{let a=await j1(this.blockstore.get(s.cid,e));if(s.status!=="sending")continue;s.wantType===dt.WantHave?a.byteLength<this.maxSizeReplaceHasWithBlock?(this.log("sending have and block for %c",s.cid),n.add(i),t.addBlock(s.cid,{data:a,prefix:a8(s.cid)})):(this.log("sending have for %c",s.cid),t.addBlockPresence(s.cid,{cid:s.cid.bytes,type:Jr.HaveBlock})):(this.log("sending block for %c",s.cid),n.add(i),t.addBlock(s.cid,{data:a,prefix:a8(s.cid)})),s.status="sent",s.expires=Date.now()+this.doNotResendBlockWindow}catch(a){if(a.name!=="NotFoundError")throw a;if(s.status="want",s.haveBlock=!1,this.log("do not have block for %c",s.cid),!s.sendDontHave||s.sentDoNotHave===!0)continue;s.sentDoNotHave=!0,t.addBlockPresence(s.cid,{cid:s.cid.bytes,type:Jr.DoNotHaveBlock})}(t.blocks.size>0||t.blockPresences.size>0)&&(this.log("sending message"),await this.network.sendMessage(this.peerId,t,e),this.log("sent message"),this.sentBytes([...t.blocks.values()].reduce((i,s)=>i+s.data.byteLength,0)))}};var s0=class{blockstore;network;ledgerMap;maxSizeReplaceHasWithBlock;doNotResendBlockWindow;maxWantListSize;log;logger;constructor(e,t={}){this.blockstore=e.blockstore,this.network=e.network,this.maxSizeReplaceHasWithBlock=t.maxSizeReplaceHasWithBlock,this.doNotResendBlockWindow=t.doNotResendBlockWindow,this.maxWantListSize=t.maxWantListSize,this.log=e.logger.forComponent("helia:bitswap:peer-want-lists"),this.logger=e.logger,this.ledgerMap=ci({name:"helia_bitswap_ledger_map",metrics:e.metrics}),this.network.addEventListener("bitswap:message",n=>{this.receiveMessage(n.detail.connection.remotePeer,n.detail.message).catch(o=>{this.log.error("error receiving bitswap message from %p - %e",n.detail.connection.remotePeer,o)})}),this.network.addEventListener("peer:disconnected",n=>{this.peerDisconnected(n.detail)})}ledgerForPeer(e){let t=this.ledgerMap.get(e);if(t!=null)return{peer:t.peerId,value:t.debtRatio(),sent:t.bytesSent,received:t.bytesReceived,exchanged:t.exchangeCount}}wantListForPeer(e){let t=this.ledgerMap.get(e);if(t!=null)return t.removeExpiredWants(),t.getWants()}peers(){return Array.from(this.ledgerMap.values()).map(e=>e.peerId)}async receiveMessage(e,t){let n=this.ledgerMap.get(e);n==null&&(n=new i0({peerId:e,blockstore:this.blockstore,network:this.network,logger:this.logger},{maxSizeReplaceHasWithBlock:this.maxSizeReplaceHasWithBlock,doNotResendBlockWindow:this.doNotResendBlockWindow,maxWantListSize:this.maxWantListSize}),this.ledgerMap.set(e,n)),n.receivedBytes(t.blocks?.reduce((o,i)=>o+i.data.byteLength,0)??0),n.removeExpiredWants(),n.addWants(t.wantlist),this.log("send blocks to peer"),await n.sendBlocksToPeer()}async receivedBlock(e,t){let n=[];for(let o of this.ledgerMap.values())o.hasWant(e)&&n.push(o);await Promise.all(n.map(async o=>o.sendBlocksToPeer(t)))}peerDisconnected(e){this.ledgerMap.delete(e)}};var c8=class extends _a{name="bitswap-session";wantList;network;libp2p;constructor(e,t){super(e,{...t,name:"helia:bitswap:session"}),this.wantList=e.wantList,this.network=e.network,this.libp2p=e.libp2p}async queryProvider(e,t,n){this.log("sending WANT-BLOCK for %c to %p",e,t);let o=await this.wantList.wantSessionBlock(e,t.peerId,n);if(this.log("%p %s %c",t,o.has?"has":"does not have",e),o.has){if(o.block!=null)return o.block;throw new Error("Provider has block but did not send it to us")}throw new Error("Provider did not have block")}async*findNewProviders(e,t={}){for await(let n of this.network.findProviders(e,t))yield{peerId:n.id,routing:n.routing,toString:()=>`Bitswap(${n.id})`}}toFilterKey(e){return e.peerId.toMultihash().bytes}equals(e,t){return e.peerId.equals(t.peerId)}async convertToProvider(e,t,n){if(Rt(e))return{peerId:e,routing:t,toString:()=>`Bitswap(${e})`};if(await this.libp2p.isDialable(e)!==!1)try{let o=await this.libp2p.dial(e,n);return{peerId:o.remotePeer,routing:t,toString:()=>`Bitswap(${o.remotePeer})`}}catch{}}emitFoundProviderProgressEvent(e,t,n){n?.onProgress?.(new U("bitswap:found-provider",{type:"bitswap",cid:e,provider:{id:t.peerId,multiaddrs:[],routing:t.routing},routing:t.routing}))}};function cA(r,e){return new c8(r,e)}var a0=class{blocksReceived;duplicateBlocksReceived;dataReceived;duplicateDataReceived;constructor(e){this.blocksReceived=e.metrics?.registerMetricGroup("helia_bitswap_received_blocks"),this.duplicateBlocksReceived=e.metrics?.registerMetricGroup("helia_bitswap_duplicate_received_blocks"),this.dataReceived=e.metrics?.registerMetricGroup("helia_bitswap_data_received_bytes"),this.duplicateDataReceived=e.metrics?.registerMetricGroup("helia_bitswap_duplicate_data_received_bytes")}updateBlocksReceived(e=1,t){let n={global:e};t!=null&&(n[t.toString()]=e),this.blocksReceived?.increment(n)}updateDuplicateBlocksReceived(e=1,t){let n={global:e};t!=null&&(n[t.toString()]=e),this.duplicateBlocksReceived?.increment(n)}updateDataReceived(e,t){let n={global:e};t!=null&&(n[t.toString()]=e),this.dataReceived?.increment(n)}updateDuplicateDataReceived(e,t){let n={global:e};t!=null&&(n[t.toString()]=e),this.duplicateDataReceived?.increment(n)}};function ZU(r){if(!(r instanceof Uint8Array))throw new Error("arg needs to be a Uint8Array");let e=[];for(;r.length>0;){let t=Ur(r);e.push(t),r=r.slice(Ae(t))}return e}var lA=ZU;var c0=class extends we{peers;wants;network;log;sendWantlistDebounce;sendMessagesTimeout;getHasher;sendingMessages;constructor(e,t={}){super(),this.peers=ci({name:"helia_bitswap_peers",metrics:e.metrics}),this.wants=St({name:"helia_bitswap_wantlist",metrics:e.metrics}),this.network=e.network,this.sendWantlistDebounce=t.sendWantlistDebounce??10,this.log=e.logger.forComponent("helia:bitswap:wantlist"),this.getHasher=e.getHasher,this.network.addEventListener("bitswap:message",n=>{this.receiveMessage(n.detail.connection,n.detail.message).catch(o=>{this.log.error("error receiving bitswap message from %p - %e",n.detail.connection.remotePeer,o)})}),this.network.addEventListener("peer:connected",n=>{this.peerConnected(n.detail).catch(o=>{this.log.error("error processing newly connected bitswap peer %p - %e",n.detail,o)})}),this.network.addEventListener("peer:disconnected",n=>{this.peerDisconnected(n.detail)})}async addEntry(e,t){let n=D(e.multihash.bytes,"base64"),o=this.wants.get(n);o==null&&(o={cid:e,priority:t.priority??1,wantType:t.wantType??dt.WantBlock,cancel:!1,sendDontHave:!0,onProgress:[]},this.wants.set(n,o)),t.onProgress!=null&&o.onProgress.push({onProgress:t.onProgress,signal:t.signal}),o.wantType===dt.WantHave&&t.wantType===dt.WantBlock&&(o.wantType=dt.WantBlock),await this.sendMessagesDebounced();try{return t.wantType===dt.WantBlock?(await br(this,"block",t?.signal,{filter:a=>ce(e.multihash.digest,a.detail.cid.multihash.digest),errorMessage:"Want was aborted"})).detail:(await br(this,"presence",t?.signal,{filter:s=>ce(e.multihash.digest,s.detail.cid.multihash.digest),errorMessage:"Want was aborted"})).detail}finally{t.signal?.aborted===!0&&(this.log("want for %c was aborted, cancelling want",e),o.cancel=!0,await this.sendMessagesDebounced())}}async sendMessagesDebounced(){await this.sendingMessages?.promise,clearTimeout(this.sendMessagesTimeout),this.sendMessagesTimeout=setTimeout(()=>{this.sendMessages().catch(e=>{this.log("error sending messages to peers - %e",e)})},this.sendWantlistDebounce)}async sendMessages(){this.sendingMessages=Ie(),await Promise.all([...this.peers.entries()].map(async([e,t])=>{let n=new Set,o=new li;for(let[i,s]of this.wants.entries())t.has(i)||s.cancel||(n.add(i),o.addWantlistEntry(s.cid,{cid:s.cid.bytes,priority:s.priority,wantType:s.wantType,cancel:s.cancel,sendDontHave:s.sendDontHave}));if(o.wantlist.size!==0)try{await this.network.sendMessage(e,o,{onProgress:i=>{this.wants.forEach(({onProgress:s})=>{s.forEach(({onProgress:a})=>{a(i)})})}});for(let i of n)t.add(i)}catch(i){this.log.error("error sending full wantlist to new peer - %e",i)}})).catch(e=>{this.log.error("error sending messages - %e",e)});for(let[e,t]of this.wants)if(t.cancel){this.wants.delete(e);for(let n of this.peers.values())n.delete(e)}this.sendingMessages.resolve()}has(e){let t=D(e.multihash.bytes,"base64");return this.wants.has(t)}async wantSessionPresence(e,t,n={}){let o=new li;return o.addWantlistEntry(e,{cid:e.bytes,sendDontHave:!0,wantType:dt.WantHave,priority:1}),await this.network.sendMessage(t,o,n),(await br(this,"presence",n.signal,{filter:s=>t.equals(s.detail.sender)&&ce(e.multihash.digest,s.detail.cid.multihash.digest)})).detail}async wantBlock(e,t={}){return this.addEntry(e,{...t,wantType:dt.WantBlock})}async wantSessionBlock(e,t,n={}){let o=new li;return o.addWantlistEntry(e,{cid:e.bytes,sendDontHave:!0,wantType:dt.WantBlock,priority:1}),await this.network.sendMessage(t,o,n),(await br(this,"presence",n.signal,{filter:s=>t.equals(s.detail.sender)&&ce(e.multihash.digest,s.detail.cid.multihash.digest)})).detail}async receivedBlock(e,t){let n=D(e.multihash.bytes,"base64"),o=this.wants.get(n);o!=null&&(o.cancel=!0,await this.sendMessagesDebounced())}async receiveMessage(e,t){this.log("received message from %p with %d blocks",e.remotePeer,t.blocks.length);let n=!1;for(let o of t.blocks){if(o.prefix==null||o.data==null)continue;let i=lA(o.prefix),s=i[0],a=i[1],c=i[2],l=i[3],u=c===ft.code?ft:await this.getHasher(c);if(u==null){this.log.error("unknown hash algorithm",c);continue}let d=u.digest(o.data,{truncate:l});d.then!=null&&(d=await d);let f=J.create(s===0?0:1,a,d);this.log("received block from %p for %c",e.remotePeer,f),this.safeDispatchEvent("block",{detail:{sender:e.remotePeer,cid:f,block:o.data,connection:e}}),this.safeDispatchEvent("presence",{detail:{sender:e.remotePeer,cid:f,has:!0,block:o.data}});let h=D(f.multihash.bytes,"base64"),p=this.wants.get(h);p!=null&&(p.cancel=!0,n=!0)}for(let{cid:o,type:i}of t.blockPresences){let s=J.decode(o);this.log("received %s from %p for %c",i,e.remotePeer,s),this.safeDispatchEvent("presence",{detail:{sender:e.remotePeer,cid:s,has:i===Jr.HaveBlock}})}n&&await this.sendMessagesDebounced()}async peerConnected(e){let t=new Set,n=new li(!0);for(let[o,i]of this.wants.entries())i.cancel||(t.add(o),n.addWantlistEntry(i.cid,{cid:i.cid.bytes,priority:1,wantType:dt.WantBlock,cancel:!1,sendDontHave:!1}));if(n.wantlist.size===0){this.peers.set(e,t);return}try{await this.network.sendMessage(e,n,{onProgress:o=>{this.wants.forEach(({onProgress:i})=>{i.forEach(({onProgress:s})=>{s(o)})})}}),this.peers.set(e,t)}catch(o){this.log.error("error sending full wantlist to new peer %p - %e",e,o)}}peerDisconnected(e){this.peers.delete(e)}start(){}stop(){this.peers.clear(),clearTimeout(this.sendMessagesTimeout)}};var l0=class{log;logger;stats;network;blockstore;peerWantLists;wantList;libp2p;constructor(e,t={}){this.logger=e.logger,this.log=e.logger.forComponent("helia:bitswap"),this.blockstore=e.blockstore,this.libp2p=e.libp2p,this.stats=new a0(e),this.network=new r0(e,t),this.peerWantLists=new s0({...e,network:this.network},t),this.wantList=new c0({...e,network:this.network},t)}createSession(e={}){return cA({wantList:this.wantList,network:this.network,logger:this.logger,libp2p:this.libp2p},e)}async want(e,t={}){let n=new AbortController,o=Ee([n.signal,t.signal]);n.signal,this.network.findAndConnect(e,{...t,signal:o}).catch(i=>{n.signal.aborted||this.log.error("error during finding and connect for cid %c - %e",e,i)});try{let i=await this.wantList.wantBlock(e,{...t,signal:o});return t.onProgress?.(new U("bitswap:block",{cid:e,sender:i.connection.remotePeer})),i.block}finally{n.abort(),o.clear()}}async notify(e,t={}){await Promise.all([this.peerWantLists.receivedBlock(e,t),this.wantList.receivedBlock(e,t)])}getWantlist(){return[...this.wantList.wants.values()].filter(e=>!e.cancel).map(e=>({cid:e.cid,priority:e.priority,wantType:e.wantType}))}getPeerWantlist(e){return this.peerWantLists.wantListForPeer(e)}async start(){this.wantList.start(),await this.network.start()}async stop(){this.wantList.stop(),await this.network.stop()}};var uA=(r,e={})=>new l0(r,e);var l8=class{name="bitswap";bitswap;started;constructor(e,t={}){this.bitswap=uA(e,t),this.started=!1}isStarted(){return this.started}async start(){await this.bitswap.start(),this.started=!0}async stop(){await this.bitswap.stop(),this.started=!1}async announce(e,t){await this.bitswap.notify(e,t)}async retrieve(e,t={}){return this.bitswap.want(e,{...t,onProgress:function(o){if(t?.onProgress!=null)if(t.onProgress(o),o.type==="connection:open"){if(!Rt(o.detail))return;t.onProgress(new U("helia:block-broker:connect",{broker:"bitswap",type:"connect",provider:o.detail,cid:e}))}else o.type==="connection:opened"?t.onProgress(new U("helia:block-broker:connected",{broker:"bitswap",type:"connected",provider:o.detail.remotePeer,address:o.detail.remoteAddr,cid:e})):o.type==="bitswap:send-wantlist"?t.onProgress(new U("helia:block-broker:request-block",{broker:"bitswap",type:"request-block",provider:o.detail,cid:e})):o.type==="bitswap:block"&&t.onProgress(new U("helia:block-broker:receive-block",{broker:"bitswap",type:"receive-block",provider:o.detail.sender,cid:e}))}})}createSession(e){let t=this.bitswap.createSession(e);return{name:"bitswap-session",addPeer:async(n,o)=>{await t.addPeer(n,o)},announce:async(n,o)=>{await this.bitswap.notify(n,o)},retrieve:async(n,o)=>t.retrieve(n,o)}}};function u8(r={}){return e=>new l8(e,r)}var JU=[6,53,56,54,55];function dA(r){return pA("sni",r)?.value}function fA(r){let e=pA("tcp",r)?.value;return e==null?"":`:${e}`}function pA(r,e){return e.find(t=>t.name===r)}function hA(r){return r.some(({code:e})=>e===448)}function Jn(r,e){let t=mA[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 mA={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://${Jn(t,e)}:${r.value}`},udp:(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");return`udp://${Jn(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`${Jn(t,e)}`},p2p:(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");return`${Jn(t,e)}`},http:(r,e)=>{let t=hA(e),n=dA(e),o=fA(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=Jn(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=Jn(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 Jn(t,e)},sni:(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");return Jn(t,e)},https:(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");let n=Jn(t,e);return n=n?.replace("tcp://",""),`https://${n}`},ws:(r,e)=>{let t=hA(e),n=dA(e),o=fA(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=Jn(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=Jn(t,e);return n=n?.replace("tcp://",""),`wss://${n}`}};function cs(r,e){let n=Z(r).getComponents(),o=n.pop();if(o==null)throw new Error("Unexpected end of multiaddr");let i=mA[o.name];if(i==null)throw new Error(`No interpreter found for ${o.name}`);let s=i(o,n)??"";return e?.assumeHttp!==!1&&JU.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 gA="[a-fA-F\\d:]",ls=r=>r&&r.includeBoundaries?`(?:(?<=\\s|^)(?=${gA})|(?<=${gA})(?=\\s|$))`:"",eo="(?: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}",At="[a-fA-F\\d]{1,4}",u0=`
14
14
  (?:
15
15
  (?:${At}:){7}(?:${At}|:)| // 1:2:3:4:5:6:7:: 1:2:3:4:5:6:7:8
16
16
  (?:${At}:){6}(?:${eo}|:${At}|:)| // 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
@@ -100,7 +100,7 @@ a=end-of-candidates
100
100
  `:`
101
101
  `;try{r.sdp=r.sdp.replace(/\na=ice-ufrag:[^\n]*\n/,`
102
102
  a=ice-ufrag:`+e+t).replace(/\na=ice-pwd:[^\n]*\n/,`
103
- a=ice-pwd:`+e+t)}catch{}return r}var H7=L("libp2p-webrtc-noise:");function HR(r,e,t){let n=r.trim().toLowerCase().replaceAll(":",""),o=L(n,"hex"),i=mr(ft.code,o),s=$7.decode(V7(e)),a=H7.byteLength+i.bytes.byteLength+s.byteLength;return t==="server"?Je([H7,s,i.bytes],a):Je([H7,i.bytes,s],a)}var uq=a3?"iceconnectionstatechange":"connectionstatechange";function dq(r,e){return r.role==="server"}async function qR(r,e,t,n){let o=r.createDataChannel("",{negotiated:!0,id:0});try{if(n.role==="client"){n.log.trace("client creating local offer");let d=await r.createOffer();n.log.trace("client created local offer %s",d.sdp);let f=K7(d,t);n.log.trace("client setting local offer %s",f.sdp),await r.setLocalDescription(f);let h=$R(n.remoteAddr,t);n.log.trace("client setting server description %s",h.sdp),await r.setRemoteDescription(h)}else{let d=VR(n.remoteAddr,t);n.log.trace("server setting client %s %s",d.type,d.sdp),await r.setRemoteDescription(d),n.log.trace("server creating local answer");let f=await r.createAnswer();n.log.trace("server created local answer");let h=K7(f,t);n.log.trace("server setting local description %s",f.sdp),await r.setLocalDescription(h)}if(o.readyState!=="open"&&(n.log.trace("%s wait for handshake channel to open, starting status %s",n.role,o.readyState),await Ti(o,"open",n)),n.log.trace("%s handshake channel opened",n.role),dq(n,r)){let d=r.remoteFingerprint()?.value??"";n.remoteAddr=n.remoteAddr.encapsulate(FR(d))}let i=UR(r.localDescription?.sdp);if(i==null)throw new Ps("Could not get fingerprint from local description sdp");n.log.trace("%s performing noise handshake",n.role);let s=HR(i,n.remoteAddr,n.role),a=M2({prologueBytes:s})(n),c=oh({channel:o,direction:"outbound",isHandshake:!0,log:n.log,...n.dataChannel??{}}),l=ih({peerConnection:r,remoteAddr:n.remoteAddr,metrics:n.events,direction:n.role==="client"?"outbound":"inbound",log:n.logger.forComponent("libp2p:webrtc-direct:connection")});if(r.addEventListener(uq,()=>{switch(r.connectionState){case"failed":case"disconnected":case"closed":l.close().catch(d=>{n.log.error("error closing connection - %e",d),l.abort(d)});break;default:break}}),n.events?.increment({peer_connection:!0}),n.role==="client"){n.log.trace("%s secure inbound",n.role);let d=await a.secureInbound(c,{remotePeer:n.remotePeer,signal:n.signal,skipStreamMuxerNegotiation:!0});return n.log.trace("%s upgrade outbound",n.role),await n.upgrader.upgradeOutbound(l,{skipProtection:!0,skipEncryption:!0,remotePeer:d.remotePeer,muxerFactory:e,signal:n.signal})}n.log.trace("%s secure outbound",n.role);let u=await a.secureOutbound(c,{remotePeer:n.remotePeer,signal:n.signal,skipStreamMuxerNegotiation:!0});l.remoteAddr=l.remoteAddr.encapsulate(`/p2p/${u.remotePeer}`),n.log.trace("%s upgrade inbound",n.role),await n.upgrader.upgradeInbound(l,{skipProtection:!0,skipEncryption:!0,remotePeer:u.remotePeer,muxerFactory:e,signal:n.signal})}catch(i){throw o.close(),r.close(),i}}async function zR(r,e,t={}){let n=t.certificate;n==null&&(n=await RTCPeerConnection.generateCertificate({name:"ECDSA",namedCurve:"P-256"}));let o=typeof t.rtcConfiguration=="function"?await t.rtcConfiguration():t.rtcConfiguration,i=new RTCPeerConnection({...o??{},certificates:[n]}),s=new Rs({peerConnection:i,metrics:t.events,dataChannelOptions:t.dataChannel});return{peerConnection:i,muxerFactory:s}}var y3=class{log;metrics;components;init;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:webrtc-direct"),this.components=e,this.init=t,e.metrics!=null&&(this.metrics={dialerEvents:e.metrics.registerCounterGroup("libp2p_webrtc-direct_dialer_events_total",{label:"event",help:"Total count of WebRTC-direct dial events by type"})})}[Ci]=!0;[Symbol.toStringTag]="@libp2p/webrtc-direct";[Ce]=["@libp2p/transport"];async dial(e,t){this.log("dial %a",e),t.signal.throwIfAborted();let n,o=e.getComponents().findLast(c=>c.code===421)?.value;o!=null&&(n=et(o));let i=LR(),{peerConnection:s,muxerFactory:a}=await zR("client",i,{rtcConfiguration:typeof this.init.rtcConfiguration=="function"?await this.init.rtcConfiguration():this.init.rtcConfiguration??{},dataChannel:this.init.dataChannel});try{return await qR(s,a,i,{role:"client",log:this.log,logger:this.components.logger,events:this.metrics?.dialerEvents,signal:t.signal,remoteAddr:e,dataChannel:this.init.dataChannel,upgrader:t.upgrader,peerId:this.components.peerId,remotePeer:n,privateKey:this.components.privateKey})}catch(c){throw s.close(),c}}createListener(e){throw new d3("WebRTCDirectTransport.createListener")}listenFilter(e){return[]}dialFilter(e){return e.filter(Ud.exactMatch)}};function WR(r){return e=>new y3(e,r)}function GR(r){return e=>new g3(e,r)}var fq=r=>{let e=r.addEventListener||r.on||r.addListener,t=r.removeEventListener||r.off||r.removeListener;if(!e||!t)throw new TypeError("Emitter is not compatible");return{addListener:e.bind(r),removeListener:t.bind(r)}};function hq(r,e,t){let n,o=new Promise((i,s)=>{if(t={rejectionEvents:["error"],multiArgs:!1,rejectionMultiArgs:!1,resolveImmediately:!1,...t},!(t.count>=0&&(t.count===Number.POSITIVE_INFINITY||Number.isInteger(t.count))))throw new TypeError("The `count` option should be at least 0 or more");t.signal?.throwIfAborted();let a=[e].flat(),c=[],{addListener:l,removeListener:u}=fq(r),d=async(...h)=>{let p=t.multiArgs?h:h[0];if(t.filter)try{if(!await t.filter(p))return}catch(y){n(),s(y);return}c.push(p),t.count===c.length&&(n(),i(c))},f=(...h)=>{n(),s(t.rejectionMultiArgs?h:h[0])};n=()=>{for(let h of a)u(h,d);for(let h of t.rejectionEvents)a.includes(h)||u(h,f)};for(let h of a)l(h,d);for(let h of t.rejectionEvents)a.includes(h)||l(h,f);t.signal&&t.signal.addEventListener("abort",()=>{f(t.signal.reason)},{once:!0}),t.resolveImmediately&&i(c)});if(o.cancel=n,typeof t.timeout=="number"){let i=pr(o,{milliseconds:t.timeout});return i.cancel=()=>{n(),i.clear()},i}return o}function jR(r,e,t){typeof t=="function"&&(t={filter:t}),t={...t,count:1,resolveImmediately:!1};let n=hq(r,e,t),o=n.then(i=>i[0]);return o.cancel=n.cancel,o}function YR(){throw new Error("WebSocket Servers can not be created in the browser!")}var pq=1024*1024*4,mq=10,q7=class extends zi{websocket;maxBufferedAmount;checkBufferedAmountTask;constructor(e){super(e),this.websocket=e.websocket,this.maxBufferedAmount=e.maxBufferedAmount??pq,this.checkBufferedAmountTask=Vc(this.checkBufferedAmount.bind(this),e.bufferedAmountPollInterval??mq),this.websocket.addEventListener("close",t=>{if(this.log('closed - code %d, reason "%s", wasClean %s',t.code,t.reason,t.wasClean),this.checkBufferedAmountTask.stop(),!t.wasClean){this.onRemoteReset();return}this.onTransportClosed()},{once:!0}),this.websocket.addEventListener("message",t=>{try{let n;if(typeof t.data=="string")n=L(t.data);else if(t.data instanceof ArrayBuffer)n=new Uint8Array(t.data,0,t.data.byteLength);else{this.abort(new Error("Incorrect binary type"));return}this.onData(n)}catch(n){this.log.error("error receiving data - %e",n)}})}sendData(e){for(let n of e)this.websocket.send(n);let t=this.websocket.bufferedAmount<this.maxBufferedAmount;return t||this.checkBufferedAmountTask.start(),{sentBytes:e.byteLength,canSendMore:t}}sendReset(){this.websocket.close(1006)}async sendClose(e){this.websocket.close(),e?.signal?.throwIfAborted()}sendPause(){}sendResume(){}checkBufferedAmount(){this.log("buffered amount now %d",this.websocket.bufferedAmount),this.websocket.bufferedAmount===0&&(this.checkBufferedAmountTask.stop(),this.safeDispatchEvent("drain"))}};function XR(r){return new q7(r)}var z7=class{log;init;logger;metrics;components;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:websockets"),this.logger=e.logger,this.components=e,this.init=t,e.metrics!=null&&(this.metrics={dialerEvents:e.metrics.registerCounterGroup("libp2p_websockets_dialer_events_total",{label:"event",help:"Total count of WebSockets dialer events by type"})})}[Ci]=!0;[Symbol.toStringTag]="@libp2p/websockets";[Ce]=["@libp2p/transport"];async dial(e,t){this.log("dialing %s",e),t=t??{};let n=XR({websocket:await this._connect(e,t),remoteAddr:e,metrics:this.metrics?.dialerEvents,direction:"outbound",log:this.components.logger.forComponent("libp2p:websockets:connection"),maxBufferedAmount:this.init.maxBufferedAmount,bufferedAmountPollInterval:this.init.bufferedAmountPollInterval});this.log("new outbound connection %s",n.remoteAddr);let o=await t.upgrader.upgradeOutbound(n,t);return this.log("outbound connection %s upgraded",n.remoteAddr),o}async _connect(e,t){t?.signal?.throwIfAborted();let n=cs(e);this.log("create websocket connection to %s",n);let o=new WebSocket(n);o.binaryType="arraybuffer";try{t.onProgress?.(new U("websockets:open-connection")),await jR(o,"open",t)}catch(i){if(t.signal?.aborted)throw this.metrics?.dialerEvents.increment({abort:!0}),new Za(`Could not connect to ${n}`);this.metrics?.dialerEvents.increment({error:!0});try{o.close()}catch{}throw i}return this.log("connected %s",e),this.metrics?.dialerEvents.increment({connect:!0}),o}createListener(e){return YR({logger:this.logger,events:this.components.events,metrics:this.components.metrics},{...this.init,...e})}listenFilter(e){return e.filter(t=>ui.exactMatch(t)||Na.exactMatch(t))}dialFilter(e){return this.listenFilter(e)}};function QR(r={}){return e=>new z7(e,r)}var W7=Fo(E0(),1);function ZR(r,e){let t=e.map((n,o)=>({record:Io(n),index:o}));return t.sort((n,o)=>{let i=n.record.sequence,s=o.record.sequence;if(i>s)return-1;if(i<s)return 1;if(n.record.validityType===Ir.ValidityType.EOL&&o.record.validityType===Ir.ValidityType.EOL){let a=W7.default.fromString(n.record.validity).toDate(),c=W7.default.fromString(o.record.validity).toDate();if(a.getTime()>c.getTime())return-1;if(a.getTime()<c.getTime())return 1}return 0}),t[0].index}var JR="6.1.2-eb1908b3",eP="helia";var tP={list:["/dnsaddr/bootstrap.libp2p.io/p2p/QmNnooDu7bfjPFoTZYxMNLWUQJyrVwtbZg5gBMjTezGAJN","/dnsaddr/bootstrap.libp2p.io/p2p/QmbLHAnMoJPWSCR5Zhtx6BHJX9KiKNN6tpvbUcqanj75Nb","/dnsaddr/bootstrap.libp2p.io/p2p/QmcZf59bWwK5XFi76CZX8cbJ4BhTzzA3gU1ZjYZcYW3dwt","/dnsaddr/va1.bootstrap.libp2p.io/p2p/12D3KooWKnDdG3iXw9eTFijk3EWSunZcFi54Zka4wmtqtt6rPxc8","/ip4/104.131.131.82/tcp/4001/p2p/QmaCpDMGvV2BGHeYERUEnRQAwe3N8SzbUtfsmvsqQLuvuJ"]};function w3(r={}){let e=`${eP}/${JR} ${Nm()}`;return{privateKey:r.privateKey,dns:r.dns,nodeInfo:{userAgent:e},addresses:{listen:["/p2p-circuit","/webrtc"]},transports:[Ok(),GR(),WR(),QR()],connectionEncrypters:[M2()],streamMuxers:[bk(),pR()],peerDiscovery:[Ak(tP)],services:{autoNAT:Sk(),dcutr:Uk(),delegatedRouting:YT(V8()),dht:lR({clientMode:!0,validators:{ipns:V0},selectors:{ipns:ZR}}),identify:CC(),identifyPush:RC(),keychain:I2(r.keychain),ping:xR(),http:SC()}}}async function rP(r){let e=r.libp2p??{};e.privateKey==null&&r.datastore!=null&&(e.privateKey=await E5(r.datastore,r.keychain));let t=w3(e);return t.datastore=t.datastore??r.datastore,await D_({...t,...e,start:!1})}async function G7(r={}){let e=r.datastore??new Ba,t=r.blockstore??new Xd,n;return O_(r.libp2p)?n=r.libp2p:n=await rP({...r,libp2p:{dns:r.dns,...r.libp2p,start:void 0},datastore:e}),{...r,libp2p:n,datastore:e,blockstore:t,blockBrokers:r.blockBrokers??[k8(),u8()],routers:r.routers??[z8(n),H8()],metrics:n.metrics}}async function gq(r={}){let e=await G7(r),t=new Jp(e);return e.start!==!1&&await t.start(),t}return cP(yq);})();
103
+ a=ice-pwd:`+e+t)}catch{}return r}var H7=L("libp2p-webrtc-noise:");function HR(r,e,t){let n=r.trim().toLowerCase().replaceAll(":",""),o=L(n,"hex"),i=mr(ft.code,o),s=$7.decode(V7(e)),a=H7.byteLength+i.bytes.byteLength+s.byteLength;return t==="server"?Je([H7,s,i.bytes],a):Je([H7,i.bytes,s],a)}var uq=a3?"iceconnectionstatechange":"connectionstatechange";function dq(r,e){return r.role==="server"}async function qR(r,e,t,n){let o=r.createDataChannel("",{negotiated:!0,id:0});try{if(n.role==="client"){n.log.trace("client creating local offer");let d=await r.createOffer();n.log.trace("client created local offer %s",d.sdp);let f=K7(d,t);n.log.trace("client setting local offer %s",f.sdp),await r.setLocalDescription(f);let h=$R(n.remoteAddr,t);n.log.trace("client setting server description %s",h.sdp),await r.setRemoteDescription(h)}else{let d=VR(n.remoteAddr,t);n.log.trace("server setting client %s %s",d.type,d.sdp),await r.setRemoteDescription(d),n.log.trace("server creating local answer");let f=await r.createAnswer();n.log.trace("server created local answer");let h=K7(f,t);n.log.trace("server setting local description %s",f.sdp),await r.setLocalDescription(h)}if(o.readyState!=="open"&&(n.log.trace("%s wait for handshake channel to open, starting status %s",n.role,o.readyState),await Ti(o,"open",n)),n.log.trace("%s handshake channel opened",n.role),dq(n,r)){let d=r.remoteFingerprint()?.value??"";n.remoteAddr=n.remoteAddr.encapsulate(FR(d))}let i=UR(r.localDescription?.sdp);if(i==null)throw new Ps("Could not get fingerprint from local description sdp");n.log.trace("%s performing noise handshake",n.role);let s=HR(i,n.remoteAddr,n.role),a=M2({prologueBytes:s})(n),c=oh({channel:o,direction:"outbound",isHandshake:!0,log:n.log,...n.dataChannel??{}}),l=ih({peerConnection:r,remoteAddr:n.remoteAddr,metrics:n.events,direction:n.role==="client"?"outbound":"inbound",log:n.logger.forComponent("libp2p:webrtc-direct:connection")});if(r.addEventListener(uq,()=>{switch(r.connectionState){case"failed":case"disconnected":case"closed":l.close().catch(d=>{n.log.error("error closing connection - %e",d),l.abort(d)});break;default:break}}),n.events?.increment({peer_connection:!0}),n.role==="client"){n.log.trace("%s secure inbound",n.role);let d=await a.secureInbound(c,{remotePeer:n.remotePeer,signal:n.signal,skipStreamMuxerNegotiation:!0});return n.log.trace("%s upgrade outbound",n.role),await n.upgrader.upgradeOutbound(l,{skipProtection:!0,skipEncryption:!0,remotePeer:d.remotePeer,muxerFactory:e,signal:n.signal})}n.log.trace("%s secure outbound",n.role);let u=await a.secureOutbound(c,{remotePeer:n.remotePeer,signal:n.signal,skipStreamMuxerNegotiation:!0});l.remoteAddr=l.remoteAddr.encapsulate(`/p2p/${u.remotePeer}`),n.log.trace("%s upgrade inbound",n.role),await n.upgrader.upgradeInbound(l,{skipProtection:!0,skipEncryption:!0,remotePeer:u.remotePeer,muxerFactory:e,signal:n.signal})}catch(i){throw o.close(),r.close(),i}}async function zR(r,e,t={}){let n=t.certificate;n==null&&(n=await RTCPeerConnection.generateCertificate({name:"ECDSA",namedCurve:"P-256"}));let o=typeof t.rtcConfiguration=="function"?await t.rtcConfiguration():t.rtcConfiguration,i=new RTCPeerConnection({...o??{},certificates:[n]}),s=new Rs({peerConnection:i,metrics:t.events,dataChannelOptions:t.dataChannel});return{peerConnection:i,muxerFactory:s}}var y3=class{log;metrics;components;init;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:webrtc-direct"),this.components=e,this.init=t,e.metrics!=null&&(this.metrics={dialerEvents:e.metrics.registerCounterGroup("libp2p_webrtc-direct_dialer_events_total",{label:"event",help:"Total count of WebRTC-direct dial events by type"})})}[Ci]=!0;[Symbol.toStringTag]="@libp2p/webrtc-direct";[Ce]=["@libp2p/transport"];async dial(e,t){this.log("dial %a",e),t.signal.throwIfAborted();let n,o=e.getComponents().findLast(c=>c.code===421)?.value;o!=null&&(n=et(o));let i=LR(),{peerConnection:s,muxerFactory:a}=await zR("client",i,{rtcConfiguration:typeof this.init.rtcConfiguration=="function"?await this.init.rtcConfiguration():this.init.rtcConfiguration??{},dataChannel:this.init.dataChannel});try{return await qR(s,a,i,{role:"client",log:this.log,logger:this.components.logger,events:this.metrics?.dialerEvents,signal:t.signal,remoteAddr:e,dataChannel:this.init.dataChannel,upgrader:t.upgrader,peerId:this.components.peerId,remotePeer:n,privateKey:this.components.privateKey})}catch(c){throw s.close(),c}}createListener(e){throw new d3("WebRTCDirectTransport.createListener")}listenFilter(e){return[]}dialFilter(e){return e.filter(Ud.exactMatch)}};function WR(r){return e=>new y3(e,r)}function GR(r){return e=>new g3(e,r)}var fq=r=>{let e=r.addEventListener||r.on||r.addListener,t=r.removeEventListener||r.off||r.removeListener;if(!e||!t)throw new TypeError("Emitter is not compatible");return{addListener:e.bind(r),removeListener:t.bind(r)}};function hq(r,e,t){let n,o=new Promise((i,s)=>{if(t={rejectionEvents:["error"],multiArgs:!1,rejectionMultiArgs:!1,resolveImmediately:!1,...t},!(t.count>=0&&(t.count===Number.POSITIVE_INFINITY||Number.isInteger(t.count))))throw new TypeError("The `count` option should be at least 0 or more");t.signal?.throwIfAborted();let a=[e].flat(),c=[],{addListener:l,removeListener:u}=fq(r),d=async(...h)=>{let p=t.multiArgs?h:h[0];if(t.filter)try{if(!await t.filter(p))return}catch(y){n(),s(y);return}c.push(p),t.count===c.length&&(n(),i(c))},f=(...h)=>{n(),s(t.rejectionMultiArgs?h:h[0])};n=()=>{for(let h of a)u(h,d);for(let h of t.rejectionEvents)a.includes(h)||u(h,f)};for(let h of a)l(h,d);for(let h of t.rejectionEvents)a.includes(h)||l(h,f);t.signal&&t.signal.addEventListener("abort",()=>{f(t.signal.reason)},{once:!0}),t.resolveImmediately&&i(c)});if(o.cancel=n,typeof t.timeout=="number"){let i=pr(o,{milliseconds:t.timeout});return i.cancel=()=>{n(),i.clear()},i}return o}function jR(r,e,t){typeof t=="function"&&(t={filter:t}),t={...t,count:1,resolveImmediately:!1};let n=hq(r,e,t),o=n.then(i=>i[0]);return o.cancel=n.cancel,o}function YR(){throw new Error("WebSocket Servers can not be created in the browser!")}var pq=1024*1024*4,mq=10,q7=class extends zi{websocket;maxBufferedAmount;checkBufferedAmountTask;constructor(e){super(e),this.websocket=e.websocket,this.maxBufferedAmount=e.maxBufferedAmount??pq,this.checkBufferedAmountTask=Vc(this.checkBufferedAmount.bind(this),e.bufferedAmountPollInterval??mq),this.websocket.addEventListener("close",t=>{if(this.log('closed - code %d, reason "%s", wasClean %s',t.code,t.reason,t.wasClean),this.checkBufferedAmountTask.stop(),!t.wasClean){this.onRemoteReset();return}this.onTransportClosed()},{once:!0}),this.websocket.addEventListener("message",t=>{try{let n;if(typeof t.data=="string")n=L(t.data);else if(t.data instanceof ArrayBuffer)n=new Uint8Array(t.data,0,t.data.byteLength);else{this.abort(new Error("Incorrect binary type"));return}this.onData(n)}catch(n){this.log.error("error receiving data - %e",n)}})}sendData(e){for(let n of e)this.websocket.send(n);let t=this.websocket.bufferedAmount<this.maxBufferedAmount;return t||this.checkBufferedAmountTask.start(),{sentBytes:e.byteLength,canSendMore:t}}sendReset(){this.websocket.close(1006)}async sendClose(e){this.websocket.close(),e?.signal?.throwIfAborted()}sendPause(){}sendResume(){}checkBufferedAmount(){this.log("buffered amount now %d",this.websocket.bufferedAmount),this.websocket.bufferedAmount===0&&(this.checkBufferedAmountTask.stop(),this.safeDispatchEvent("drain"))}};function XR(r){return new q7(r)}var z7=class{log;init;logger;metrics;components;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:websockets"),this.logger=e.logger,this.components=e,this.init=t,e.metrics!=null&&(this.metrics={dialerEvents:e.metrics.registerCounterGroup("libp2p_websockets_dialer_events_total",{label:"event",help:"Total count of WebSockets dialer events by type"})})}[Ci]=!0;[Symbol.toStringTag]="@libp2p/websockets";[Ce]=["@libp2p/transport"];async dial(e,t){this.log("dialing %s",e),t=t??{};let n=XR({websocket:await this._connect(e,t),remoteAddr:e,metrics:this.metrics?.dialerEvents,direction:"outbound",log:this.components.logger.forComponent("libp2p:websockets:connection"),maxBufferedAmount:this.init.maxBufferedAmount,bufferedAmountPollInterval:this.init.bufferedAmountPollInterval});this.log("new outbound connection %s",n.remoteAddr);let o=await t.upgrader.upgradeOutbound(n,t);return this.log("outbound connection %s upgraded",n.remoteAddr),o}async _connect(e,t){t?.signal?.throwIfAborted();let n=cs(e);this.log("create websocket connection to %s",n);let o=new WebSocket(n);o.binaryType="arraybuffer";try{t.onProgress?.(new U("websockets:open-connection")),await jR(o,"open",t)}catch(i){if(t.signal?.aborted)throw this.metrics?.dialerEvents.increment({abort:!0}),new Za(`Could not connect to ${n}`);this.metrics?.dialerEvents.increment({error:!0});try{o.close()}catch{}throw i}return this.log("connected %s",e),this.metrics?.dialerEvents.increment({connect:!0}),o}createListener(e){return YR({logger:this.logger,events:this.components.events,metrics:this.components.metrics},{...this.init,...e})}listenFilter(e){return e.filter(t=>ui.exactMatch(t)||Na.exactMatch(t))}dialFilter(e){return this.listenFilter(e)}};function QR(r={}){return e=>new z7(e,r)}var W7=Fo(E0(),1);function ZR(r,e){let t=e.map((n,o)=>({record:Io(n),index:o}));return t.sort((n,o)=>{let i=n.record.sequence,s=o.record.sequence;if(i>s)return-1;if(i<s)return 1;if(n.record.validityType===Ir.ValidityType.EOL&&o.record.validityType===Ir.ValidityType.EOL){let a=W7.default.fromString(n.record.validity).toDate(),c=W7.default.fromString(o.record.validity).toDate();if(a.getTime()>c.getTime())return-1;if(a.getTime()<c.getTime())return 1}return 0}),t[0].index}var JR="6.1.3-35b081c7",eP="helia";var tP={list:["/dnsaddr/bootstrap.libp2p.io/p2p/QmNnooDu7bfjPFoTZYxMNLWUQJyrVwtbZg5gBMjTezGAJN","/dnsaddr/bootstrap.libp2p.io/p2p/QmbLHAnMoJPWSCR5Zhtx6BHJX9KiKNN6tpvbUcqanj75Nb","/dnsaddr/bootstrap.libp2p.io/p2p/QmcZf59bWwK5XFi76CZX8cbJ4BhTzzA3gU1ZjYZcYW3dwt","/dnsaddr/va1.bootstrap.libp2p.io/p2p/12D3KooWKnDdG3iXw9eTFijk3EWSunZcFi54Zka4wmtqtt6rPxc8","/ip4/104.131.131.82/tcp/4001/p2p/QmaCpDMGvV2BGHeYERUEnRQAwe3N8SzbUtfsmvsqQLuvuJ"]};function w3(r={}){let e=`${eP}/${JR} ${Nm()}`;return{privateKey:r.privateKey,dns:r.dns,nodeInfo:{userAgent:e},addresses:{listen:["/p2p-circuit","/webrtc"]},transports:[Ok(),GR(),WR(),QR()],connectionEncrypters:[M2()],streamMuxers:[bk(),pR()],peerDiscovery:[Ak(tP)],services:{autoNAT:Sk(),dcutr:Uk(),delegatedRouting:YT(V8()),dht:lR({clientMode:!0,validators:{ipns:V0},selectors:{ipns:ZR}}),identify:CC(),identifyPush:RC(),keychain:I2(r.keychain),ping:xR(),http:SC()}}}async function rP(r){let e=r.libp2p??{};e.privateKey==null&&r.datastore!=null&&(e.privateKey=await E5(r.datastore,r.keychain));let t=w3(e);return t.datastore=t.datastore??r.datastore,await D_({...t,...e,start:!1})}async function G7(r={}){let e=r.datastore??new Ba,t=r.blockstore??new Xd,n;return O_(r.libp2p)?n=r.libp2p:n=await rP({...r,libp2p:{dns:r.dns,...r.libp2p,start:void 0},datastore:e}),{...r,libp2p:n,datastore:e,blockstore:t,blockBrokers:r.blockBrokers??[k8(),u8()],routers:r.routers??[z8(n),H8()],metrics:n.metrics}}async function gq(r={}){let e=await G7(r),t=new Jp(e);return e.start!==!1&&await t.start(),t}return cP(yq);})();
104
104
  /*! Bundled license information:
105
105
 
106
106
  pvtsutils/build/index.js: