@helia/block-brokers 4.2.1 → 4.2.2-1e9745c0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.min.js CHANGED
@@ -1,4 +1,4 @@
1
1
  (function (root, factory) {(typeof module === 'object' && module.exports) ? module.exports = factory() : root.HeliaBlockBrokers = factory()}(typeof self !== 'undefined' ? self : this, function () {
2
- "use strict";var HeliaBlockBrokers=(()=>{var vi=Object.create;var fe=Object.defineProperty;var Ei=Object.getOwnPropertyDescriptor;var _i=Object.getOwnPropertyNames;var Si=Object.getPrototypeOf,ki=Object.prototype.hasOwnProperty;var Hn=(r,t)=>()=>(t||r((t={exports:{}}).exports,t),t.exports),O=(r,t)=>{for(var e in t)fe(r,e,{get:t[e],enumerable:!0})},Vn=(r,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of _i(t))!ki.call(r,s)&&s!==e&&fe(r,s,{get:()=>t[s],enumerable:!(n=Ei(t,s))||n.enumerable});return r};var Wn=(r,t,e)=>(e=r!=null?vi(Si(r)):{},Vn(t||!r||!r.__esModule?fe(e,"default",{value:r,enumerable:!0}):e,r)),Ii=r=>Vn(fe({},"__esModule",{value:!0}),r);var Bs=Hn((Bf,Rs)=>{Rs.exports=function(r){if(!r)throw Error("hashlru must have a max value, of type number, greater than 0");var t=0,e=Object.create(null),n=Object.create(null);function s(i,o){e[i]=o,t++,t>=r&&(t=0,n=e,e=Object.create(null))}return{has:function(i){return e[i]!==void 0||n[i]!==void 0},remove:function(i){e[i]!==void 0&&(e[i]=void 0),n[i]!==void 0&&(n[i]=void 0)},get:function(i){var o=e[i];if(o!==void 0)return o;if((o=n[i])!==void 0)return s(i,o),o},set:function(i,o){e[i]!==void 0?e[i]=o:s(i,o)},clear:function(){e=Object.create(null),n=Object.create(null)}}}});var ai=Hn(ce=>{(function(){var r,t,e,n,s,i,o,a;a=function(c){var l,u,h,f;return l=(c&255<<24)>>>24,u=(c&255<<16)>>>16,h=(c&65280)>>>8,f=c&255,[l,u,h,f].join(".")},o=function(c){var l,u,h,f,m,d;for(l=[],h=f=0;f<=3&&c.length!==0;h=++f){if(h>0){if(c[0]!==".")throw new Error("Invalid IP");c=c.substring(1)}d=t(c),m=d[0],u=d[1],c=c.substring(u),l.push(m)}if(c.length!==0)throw new Error("Invalid IP");switch(l.length){case 1:if(l[0]>4294967295)throw new Error("Invalid IP");return l[0]>>>0;case 2:if(l[0]>255||l[1]>16777215)throw new Error("Invalid IP");return(l[0]<<24|l[1])>>>0;case 3:if(l[0]>255||l[1]>255||l[2]>65535)throw new Error("Invalid IP");return(l[0]<<24|l[1]<<16|l[2])>>>0;case 4:if(l[0]>255||l[1]>255||l[2]>255||l[3]>255)throw new Error("Invalid IP");return(l[0]<<24|l[1]<<16|l[2]<<8|l[3])>>>0;default:throw new Error("Invalid IP")}},e=function(c){return c.charCodeAt(0)},n=e("0"),i=e("a"),s=e("A"),t=function(c){var l,u,h,f,m;for(f=0,l=10,u="9",h=0,c.length>1&&c[h]==="0"&&(c[h+1]==="x"||c[h+1]==="X"?(h+=2,l=16):"0"<=c[h+1]&&c[h+1]<="9"&&(h++,l=8,u="7")),m=h;h<c.length;){if("0"<=c[h]&&c[h]<=u)f=f*l+(e(c[h])-n)>>>0;else if(l===16)if("a"<=c[h]&&c[h]<="f")f=f*l+(10+e(c[h])-i)>>>0;else if("A"<=c[h]&&c[h]<="F")f=f*l+(10+e(c[h])-s)>>>0;else break;else break;if(f>4294967295)throw new Error("too large");h++}if(h===m)throw new Error("empty octet");return[f,h]},r=function(){function c(l,u){var h,f,m,d;if(typeof l!="string")throw new Error("Missing `net' parameter");if(u||(d=l.split("/",2),l=d[0],u=d[1]),u||(u=32),typeof u=="string"&&u.indexOf(".")>-1){try{this.maskLong=o(u)}catch(E){throw h=E,new Error("Invalid mask: "+u)}for(f=m=32;m>=0;f=--m)if(this.maskLong===4294967295<<32-f>>>0){this.bitmask=f;break}}else if(u||u===0)this.bitmask=parseInt(u,10),this.maskLong=0,this.bitmask>0&&(this.maskLong=4294967295<<32-this.bitmask>>>0);else throw new Error("Invalid mask: empty");try{this.netLong=(o(l)&this.maskLong)>>>0}catch(E){throw h=E,new Error("Invalid net address: "+l)}if(!(this.bitmask<=32))throw new Error("Invalid mask for ip4: "+u);this.size=Math.pow(2,32-this.bitmask),this.base=a(this.netLong),this.mask=a(this.maskLong),this.hostmask=a(~this.maskLong),this.first=this.bitmask<=30?a(this.netLong+1):this.base,this.last=this.bitmask<=30?a(this.netLong+this.size-2):a(this.netLong+this.size-1),this.broadcast=this.bitmask<=30?a(this.netLong+this.size-1):void 0}return c.prototype.contains=function(l){return typeof l=="string"&&(l.indexOf("/")>0||l.split(".").length!==4)&&(l=new c(l)),l instanceof c?this.contains(l.base)&&this.contains(l.broadcast||l.last):(o(l)&this.maskLong)>>>0===(this.netLong&this.maskLong)>>>0},c.prototype.next=function(l){return l==null&&(l=1),new c(a(this.netLong+this.size*l),this.mask)},c.prototype.forEach=function(l){var u,h,f;for(f=o(this.first),h=o(this.last),u=0;f<=h;)l(a(f),f,u),u++,f++},c.prototype.toString=function(){return this.base+"/"+this.bitmask},c}(),ce.ip2long=o,ce.long2ip=a,ce.Netmask=r}).call(ce)});var bc={};O(bc,{bitswap:()=>Hs,trustlessGateway:()=>xi});var Ai=Symbol.for("@libp2p/peer-id");function de(r){return!!r?.[Ai]}var X=class extends Error{static name="AbortError";constructor(t="The operation was aborted"){super(t),this.name="AbortError"}};var pe=class extends Error{static name="InvalidParametersError";constructor(t="Invalid parameters"){super(t),this.name="InvalidParametersError"}};var me=class extends Error{static name="UnsupportedProtocolError";constructor(t="Unsupported protocol error"){super(t),this.name="UnsupportedProtocolError"}};var ge=class extends Error{static name="TimeoutError";constructor(t="Timed out"){super(t),this.name="TimeoutError"}},we=class extends Error{static name="NotStartedError";constructor(t="Not started"){super(t),this.name="NotStartedError"}};var tt=class extends EventTarget{#t=new Map;constructor(){super()}listenerCount(t){let e=this.#t.get(t);return e==null?0:e.length}addEventListener(t,e,n){super.addEventListener(t,e,n);let s=this.#t.get(t);s==null&&(s=[],this.#t.set(t,s)),s.push({callback:e,once:(n!==!0&&n!==!1&&n?.once)??!1})}removeEventListener(t,e,n){super.removeEventListener(t.toString(),e??null,n);let s=this.#t.get(t);s!=null&&(s=s.filter(({callback:i})=>i!==e),this.#t.set(t,s))}dispatchEvent(t){let e=super.dispatchEvent(t),n=this.#t.get(t.type);return n==null||(n=n.filter(({once:s})=>!s),this.#t.set(t.type,n)),e}safeDispatchEvent(t,e={}){return this.dispatchEvent(new CustomEvent(t,e))}};function Gn(r){let t=new globalThis.AbortController;function e(){t.abort();for(let i of r)i?.removeEventListener!=null&&i.removeEventListener("abort",e)}for(let i of r){if(i?.aborted===!0){e();break}i?.addEventListener!=null&&i.addEventListener("abort",e)}function n(){for(let i of r)i?.removeEventListener!=null&&i.removeEventListener("abort",e)}let s=t.signal;return s.clear=n,s}function D(){let r={};return r.promise=new Promise((t,e)=>{r.resolve=t,r.reject=e}),r}var be=class{buffer;mask;top;btm;next;constructor(t){if(!(t>0)||(t-1&t)!==0)throw new Error("Max size for a FixedFIFO should be a power of two");this.buffer=new Array(t),this.mask=t-1,this.top=0,this.btm=0,this.next=null}push(t){return this.buffer[this.top]!==void 0?!1:(this.buffer[this.top]=t,this.top=this.top+1&this.mask,!0)}shift(){let t=this.buffer[this.btm];if(t!==void 0)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,t}isEmpty(){return this.buffer[this.btm]===void 0}},kt=class{size;hwm;head;tail;constructor(t={}){this.hwm=t.splitLimit??16,this.head=new be(this.hwm),this.tail=this.head,this.size=0}calculateSize(t){return t?.byteLength!=null?t.byteLength:1}push(t){if(t?.value!=null&&(this.size+=this.calculateSize(t.value)),!this.head.push(t)){let e=this.head;this.head=e.next=new be(2*this.head.buffer.length),this.head.push(t)}}shift(){let t=this.tail.shift();if(t===void 0&&this.tail.next!=null){let e=this.tail.next;this.tail.next=null,this.tail=e,t=this.tail.shift()}return t?.value!=null&&(this.size-=this.calculateSize(t.value)),t}isEmpty(){return this.head.isEmpty()}};var mr=class extends Error{type;code;constructor(t,e){super(t??"The operation was aborted"),this.type="aborted",this.code=e??"ABORT_ERR"}};function ye(r={}){return Li(e=>{let n=e.shift();if(n==null)return{done:!0};if(n.error!=null)throw n.error;return{done:n.done===!0,value:n.value}},r)}function Li(r,t){t=t??{};let e=t.onEnd,n=new kt,s,i,o,a=D(),c=async()=>{try{return n.isEmpty()?o?{done:!0}:await new Promise((b,L)=>{i=B=>{i=null,n.push(B);try{b(r(n))}catch(T){L(T)}return s}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=D()})}},l=b=>i!=null?i(b):(n.push(b),s),u=b=>(n=new kt,i!=null?i({error:b}):(n.push({error:b}),s)),h=b=>{if(o)return s;if(t?.objectMode!==!0&&b?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return l({done:!1,value:b})},f=b=>o?s:(o=!0,b!=null?u(b):l({done:!0})),m=()=>(n=new kt,f(),{done:!0}),d=b=>(f(b),{done:!0});if(s={[Symbol.asyncIterator](){return this},next:c,return:m,throw:d,push:h,end:f,get readableLength(){return n.size},onEmpty:async b=>{let L=b?.signal;if(L?.throwIfAborted(),n.isEmpty())return;let B,T;L!=null&&(B=new Promise((z,H)=>{T=()=>{H(new mr)},L.addEventListener("abort",T)}));try{await Promise.race([a.promise,B])}finally{T!=null&&L!=null&&L?.removeEventListener("abort",T)}}},e==null)return s;let E=s;return s={[Symbol.asyncIterator](){return this},next(){return E.next()},throw(b){return E.throw(b),e!=null&&(e(b),e=void 0),{done:!0}},return(){return E.return(),e!=null&&(e(),e=void 0),{done:!0}},push:h,end(b){return E.end(b),e!=null&&(e(b),e=void 0),s},get readableLength(){return E.readableLength},onEmpty:b=>E.onEmpty(b)},s}var gr=class extends Error{type;code;constructor(t,e){super(t??"The operation was aborted"),this.type="aborted",this.name="AbortError",this.code=e??"ABORT_ERR"}};async function Q(r,t,e,n){let s=new gr(n?.errorMessage,n?.errorCode);return e?.aborted===!0?Promise.reject(s):new Promise((i,o)=>{function a(){e?.removeEventListener("abort",u),r.removeEventListener(t,c),n?.errorEvent!=null&&r.removeEventListener(n.errorEvent,l)}let c=h=>{try{if(n?.filter?.(h)===!1)return}catch(f){a(),o(f);return}a(),i(h)},l=h=>{a(),o(h.detail)},u=()=>{a(),o(s)};e?.addEventListener("abort",u),r.addEventListener(t,c),n?.errorEvent!=null&&r.addEventListener(n.errorEvent,l)})}var xe=class extends Error{static name="QueueFullError";constructor(t="The queue was full"){super(t),this.name="QueueFullError"}};var ve=class extends Error{type;code;constructor(t,e,n){super(t??"The operation was aborted"),this.type="aborted",this.name=n??"AbortError",this.code=e??"ABORT_ERR"}};async function Ee(r,t,e){if(t==null)return r;if(t.aborted)return r.catch(()=>{}),Promise.reject(new ve(e?.errorMessage,e?.errorCode,e?.errorName));let n,s=new ve(e?.errorMessage,e?.errorCode,e?.errorName);try{return await Promise.race([r,new Promise((i,o)=>{n=()=>{o(s)},t.addEventListener("abort",n)})])}finally{n!=null&&t.removeEventListener("abort",n)}}var _e=class{deferred;signal;constructor(t){this.signal=t,this.deferred=D(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new X)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function Ti(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var Se=class{id;fn;options;recipients;status;timeline;controller;constructor(t,e){this.id=Ti(),this.status="queued",this.fn=t,this.options=e,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,this.controller.signal,this.onAbort=this.onAbort.bind(this)}abort(t){this.controller.abort(t)}onAbort(){this.recipients.reduce((e,n)=>e&&n.signal?.aborted===!0,!0)&&(this.controller.abort(new X),this.cleanup())}async join(t={}){let e=new _e(t.signal);return this.recipients.push(e),t.signal?.addEventListener("abort",this.onAbort),e.deferred.promise}async run(){this.status="running",this.timeline.started=Date.now();try{this.controller.signal.throwIfAborted();let t=await Ee(this.fn({...this.options??{},signal:this.controller.signal}),this.controller.signal);this.recipients.forEach(e=>{e.deferred.resolve(t)}),this.status="complete"}catch(t){this.recipients.forEach(e=>{e.deferred.reject(t)}),this.status="errored"}finally{this.timeline.finished=Date.now(),this.cleanup()}}cleanup(){this.recipients.forEach(t=>{t.cleanup(),t.signal?.removeEventListener("abort",this.onAbort)})}};var It=class extends tt{concurrency;maxSize;queue;pending;sort;constructor(t={}){super(),this.concurrency=t.concurrency??Number.POSITIVE_INFINITY,this.maxSize=t.maxSize??Number.POSITIVE_INFINITY,this.pending=0,t.metricName!=null&&t.metrics?.registerMetricGroup(t.metricName,{calculate:()=>({size:this.queue.length,running:this.pending,queued:this.queue.length-this.pending})}),this.sort=t.sort,this.queue=[]}tryToStartAnother(){if(this.size===0)return queueMicrotask(()=>{this.safeDispatchEvent("empty")}),this.running===0&&queueMicrotask(()=>{this.safeDispatchEvent("idle")}),!1;if(this.pending<this.concurrency){let t;for(let e of this.queue)if(e.status==="queued"){t=e;break}return t==null?!1:(this.safeDispatchEvent("active"),this.pending++,t.run().finally(()=>{for(let e=0;e<this.queue.length;e++)if(this.queue[e]===t){this.queue.splice(e,1);break}this.pending--,this.tryToStartAnother(),this.safeDispatchEvent("next")}),!0)}return!1}enqueue(t){this.queue.push(t),this.sort!=null&&this.queue.sort(this.sort)}async add(t,e){if(e?.signal?.throwIfAborted(),this.size===this.maxSize)throw new xe;let n=new Se(t,e);return this.enqueue(n),this.safeDispatchEvent("add"),this.tryToStartAnother(),n.join(e).then(s=>(this.safeDispatchEvent("completed",{detail:s}),this.safeDispatchEvent("success",{detail:{job:n,result:s}}),s)).catch(s=>{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("error",{detail:s}),this.safeDispatchEvent("failure",{detail:{job:n,error:s}}),s})}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(t=>{t.abort(new X)}),this.clear()}async onEmpty(t){this.size!==0&&await Q(this,"empty",t?.signal)}async onSizeLessThan(t,e){this.size<t||await Q(this,"next",e?.signal,{filter:()=>this.size<t})}async onIdle(t){this.pending===0&&this.size===0||await Q(this,"idle",t?.signal)}get size(){return this.queue.length}get queued(){return this.queue.length-this.pending}get running(){return this.pending}async*toGenerator(t){t?.signal?.throwIfAborted();let e=ye({objectMode:!0}),n=c=>{c!=null?this.abort():this.clear(),e.end(c)},s=c=>{c.detail!=null&&e.push(c.detail)},i=c=>{n(c.detail)},o=()=>{n()},a=()=>{n(new X("Queue aborted"))};this.addEventListener("completed",s),this.addEventListener("error",i),this.addEventListener("idle",o),t?.signal?.addEventListener("abort",a);try{yield*e}finally{this.removeEventListener("completed",s),this.removeEventListener("error",i),this.removeEventListener("idle",o),t?.signal?.removeEventListener("abort",a),n()}}};var ke=class extends It{has(t){return this.find(t)!=null}find(t){return this.queue.find(e=>t.equals(e.options.peerId))}};function Pi(r){return r[Symbol.asyncIterator]!=null}function Di(r){if(Pi(r))return(async()=>{for await(let t of r);})();for(let t of r);}var br=Di;function N(r=0){return new Uint8Array(r)}function C(r=0){return new Uint8Array(r)}var Ni=Math.pow(2,7),Ci=Math.pow(2,14),Fi=Math.pow(2,21),yr=Math.pow(2,28),xr=Math.pow(2,35),vr=Math.pow(2,42),Er=Math.pow(2,49),x=128,F=127;function _(r){if(r<Ni)return 1;if(r<Ci)return 2;if(r<Fi)return 3;if(r<yr)return 4;if(r<xr)return 5;if(r<vr)return 6;if(r<Er)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function _r(r,t,e=0){switch(_(r)){case 8:t[e++]=r&255|x,r/=128;case 7:t[e++]=r&255|x,r/=128;case 6:t[e++]=r&255|x,r/=128;case 5:t[e++]=r&255|x,r/=128;case 4:t[e++]=r&255|x,r>>>=7;case 3:t[e++]=r&255|x,r>>>=7;case 2:t[e++]=r&255|x,r>>>=7;case 1:{t[e++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return t}function Mi(r,t,e=0){switch(_(r)){case 8:t.set(e++,r&255|x),r/=128;case 7:t.set(e++,r&255|x),r/=128;case 6:t.set(e++,r&255|x),r/=128;case 5:t.set(e++,r&255|x),r/=128;case 4:t.set(e++,r&255|x),r>>>=7;case 3:t.set(e++,r&255|x),r>>>=7;case 2:t.set(e++,r&255|x),r>>>=7;case 1:{t.set(e++,r&255),r>>>=7;break}default:throw new Error("unreachable")}return t}function Sr(r,t){let e=r[t],n=0;if(n+=e&F,e<x||(e=r[t+1],n+=(e&F)<<7,e<x)||(e=r[t+2],n+=(e&F)<<14,e<x)||(e=r[t+3],n+=(e&F)<<21,e<x)||(e=r[t+4],n+=(e&F)*yr,e<x)||(e=r[t+5],n+=(e&F)*xr,e<x)||(e=r[t+6],n+=(e&F)*vr,e<x)||(e=r[t+7],n+=(e&F)*Er,e<x))return n;throw new RangeError("Could not decode varint")}function Ui(r,t){let e=r.get(t),n=0;if(n+=e&F,e<x||(e=r.get(t+1),n+=(e&F)<<7,e<x)||(e=r.get(t+2),n+=(e&F)<<14,e<x)||(e=r.get(t+3),n+=(e&F)<<21,e<x)||(e=r.get(t+4),n+=(e&F)*yr,e<x)||(e=r.get(t+5),n+=(e&F)*xr,e<x)||(e=r.get(t+6),n+=(e&F)*vr,e<x)||(e=r.get(t+7),n+=(e&F)*Er,e<x))return n;throw new RangeError("Could not decode varint")}function et(r,t,e=0){return t==null&&(t=C(_(r))),t instanceof Uint8Array?_r(r,t,e):Mi(r,t,e)}function j(r,t=0){return r instanceof Uint8Array?Sr(r,t):Ui(r,t)}function V(r,t){t==null&&(t=r.reduce((s,i)=>s+i.length,0));let e=C(t),n=0;for(let s of r)e.set(s,n),n+=s.length;return e}function K(r,t){if(r===t)return!0;if(r.byteLength!==t.byteLength)return!1;for(let e=0;e<r.byteLength;e++)if(r[e]!==t[e])return!1;return!0}var Qn=Symbol.for("@achingbrain/uint8arraylist");function Xn(r,t){if(t==null||t<0)throw new RangeError("index is out of bounds");let e=0;for(let n of r){let s=e+n.byteLength;if(t<s)return{buf:n,index:t-e};e=s}throw new RangeError("index is out of bounds")}function Ae(r){return!!r?.[Qn]}var At=class r{bufs;length;[Qn]=!0;constructor(...t){this.bufs=[],this.length=0,t.length>0&&this.appendAll(t)}*[Symbol.iterator](){yield*this.bufs}get byteLength(){return this.length}append(...t){this.appendAll(t)}appendAll(t){let e=0;for(let n of t)if(n instanceof Uint8Array)e+=n.byteLength,this.bufs.push(n);else if(Ae(n))e+=n.byteLength,this.bufs.push(...n.bufs);else throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");this.length+=e}prepend(...t){this.prependAll(t)}prependAll(t){let e=0;for(let n of t.reverse())if(n instanceof Uint8Array)e+=n.byteLength,this.bufs.unshift(n);else if(Ae(n))e+=n.byteLength,this.bufs.unshift(...n.bufs);else throw new Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");this.length+=e}get(t){let e=Xn(this.bufs,t);return e.buf[e.index]}set(t,e){let n=Xn(this.bufs,t);n.buf[n.index]=e}write(t,e=0){if(t instanceof Uint8Array)for(let n=0;n<t.length;n++)this.set(e+n,t[n]);else if(Ae(t))for(let n=0;n<t.length;n++)this.set(e+n,t.get(n));else throw new Error("Could not write value, must be an Uint8Array or a Uint8ArrayList")}consume(t){if(t=Math.trunc(t),!(Number.isNaN(t)||t<=0)){if(t===this.byteLength){this.bufs=[],this.length=0;return}for(;this.bufs.length>0;)if(t>=this.bufs[0].byteLength)t-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift();else{this.bufs[0]=this.bufs[0].subarray(t),this.length-=t;break}}}slice(t,e){let{bufs:n,length:s}=this._subList(t,e);return V(n,s)}subarray(t,e){let{bufs:n,length:s}=this._subList(t,e);return n.length===1?n[0]:V(n,s)}sublist(t,e){let{bufs:n,length:s}=this._subList(t,e),i=new r;return i.length=s,i.bufs=[...n],i}_subList(t,e){if(t=t??0,e=e??this.length,t<0&&(t=this.length+t),e<0&&(e=this.length+e),t<0||e>this.length)throw new RangeError("index is out of bounds");if(t===e)return{bufs:[],length:0};if(t===0&&e===this.length)return{bufs:this.bufs,length:this.length};let n=[],s=0;for(let i=0;i<this.bufs.length;i++){let o=this.bufs[i],a=s,c=a+o.byteLength;if(s=c,t>=c)continue;let l=t>=a&&t<c,u=e>a&&e<=c;if(l&&u){if(t===a&&e===c){n.push(o);break}let h=t-a;n.push(o.subarray(h,h+(e-t)));break}if(l){if(t===0){n.push(o);continue}n.push(o.subarray(t-a));continue}if(u){if(e===c){n.push(o);break}n.push(o.subarray(0,e-a));break}n.push(o)}return{bufs:n,length:e-t}}indexOf(t,e=0){if(!Ae(t)&&!(t instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');let n=t instanceof Uint8Array?t:t.subarray();if(e=Number(e??0),isNaN(e)&&(e=0),e<0&&(e=this.length+e),e<0&&(e=0),t.length===0)return e>this.length?this.length:e;let s=n.byteLength;if(s===0)throw new TypeError("search must be at least 1 byte long");let i=256,o=new Int32Array(i);for(let h=0;h<i;h++)o[h]=-1;for(let h=0;h<s;h++)o[n[h]]=h;let a=o,c=this.byteLength-n.byteLength,l=n.byteLength-1,u;for(let h=e;h<=c;h+=u){u=0;for(let f=l;f>=0;f--){let m=this.get(h+f);if(n[f]!==m){u=Math.max(1,f-a[m]);break}}if(u===0)return h}return-1}getInt8(t){let e=this.subarray(t,t+1);return new DataView(e.buffer,e.byteOffset,e.byteLength).getInt8(0)}setInt8(t,e){let n=C(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt8(0,e),this.write(n,t)}getInt16(t,e){let n=this.subarray(t,t+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt16(0,e)}setInt16(t,e,n){let s=N(2);new DataView(s.buffer,s.byteOffset,s.byteLength).setInt16(0,e,n),this.write(s,t)}getInt32(t,e){let n=this.subarray(t,t+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt32(0,e)}setInt32(t,e,n){let s=N(4);new DataView(s.buffer,s.byteOffset,s.byteLength).setInt32(0,e,n),this.write(s,t)}getBigInt64(t,e){let n=this.subarray(t,t+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigInt64(0,e)}setBigInt64(t,e,n){let s=N(8);new DataView(s.buffer,s.byteOffset,s.byteLength).setBigInt64(0,e,n),this.write(s,t)}getUint8(t){let e=this.subarray(t,t+1);return new DataView(e.buffer,e.byteOffset,e.byteLength).getUint8(0)}setUint8(t,e){let n=C(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint8(0,e),this.write(n,t)}getUint16(t,e){let n=this.subarray(t,t+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint16(0,e)}setUint16(t,e,n){let s=N(2);new DataView(s.buffer,s.byteOffset,s.byteLength).setUint16(0,e,n),this.write(s,t)}getUint32(t,e){let n=this.subarray(t,t+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint32(0,e)}setUint32(t,e,n){let s=N(4);new DataView(s.buffer,s.byteOffset,s.byteLength).setUint32(0,e,n),this.write(s,t)}getBigUint64(t,e){let n=this.subarray(t,t+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigUint64(0,e)}setBigUint64(t,e,n){let s=N(8);new DataView(s.buffer,s.byteOffset,s.byteLength).setBigUint64(0,e,n),this.write(s,t)}getFloat32(t,e){let n=this.subarray(t,t+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat32(0,e)}setFloat32(t,e,n){let s=N(4);new DataView(s.buffer,s.byteOffset,s.byteLength).setFloat32(0,e,n),this.write(s,t)}getFloat64(t,e){let n=this.subarray(t,t+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat64(0,e)}setFloat64(t,e,n){let s=N(8);new DataView(s.buffer,s.byteOffset,s.byteLength).setFloat64(0,e,n),this.write(s,t)}equals(t){if(t==null||!(t instanceof r)||t.bufs.length!==this.bufs.length)return!1;for(let e=0;e<this.bufs.length;e++)if(!K(this.bufs[e],t.bufs[e]))return!1;return!0}static fromUint8Arrays(t,e){let n=new r;return n.bufs=t,e==null&&(e=t.reduce((s,i)=>s+i.byteLength,0)),n.length=e,n}};var Le=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},Lt=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},Te=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"},Gt=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};function Pe(r){return r[Symbol.asyncIterator]!=null}function jn(r,t){if(r.byteLength>t)throw new Lt("Message length too long")}var Ne=r=>{let t=_(r),e=C(t);return et(r,e),Ne.bytes=t,e};Ne.bytes=0;function Ce(r,t){t=t??{};let e=t.lengthEncoder??Ne,n=t?.maxDataLength??4194304;function*s(i){jn(i,n);let o=e(i.byteLength);o instanceof Uint8Array?yield o:yield*o,i instanceof Uint8Array?yield i:yield*i}return Pe(r)?async function*(){for await(let i of r)yield*s(i)}():function*(){for(let i of r)yield*s(i)}()}Ce.single=(r,t)=>{t=t??{};let e=t.lengthEncoder??Ne,n=t?.maxDataLength??4194304;return jn(r,n),new At(e(r.byteLength),r)};var ft;(function(r){r[r.LENGTH=0]="LENGTH",r[r.DATA=1]="DATA"})(ft||(ft={}));var kr=r=>{let t=j(r);return kr.bytes=_(t),t};kr.bytes=0;function Xt(r,t){let e=new At,n=ft.LENGTH,s=-1,i=t?.lengthDecoder??kr,o=t?.maxLengthLength??8,a=t?.maxDataLength??4194304;function*c(){for(;e.byteLength>0;){if(n===ft.LENGTH)try{if(s=i(e),s<0)throw new Le("Invalid message length");if(s>a)throw new Lt("Message length too long");let l=i.bytes;e.consume(l),t?.onLength!=null&&t.onLength(s),n=ft.DATA}catch(l){if(l instanceof RangeError){if(e.byteLength>o)throw new Te("Message length length too long");break}throw l}if(n===ft.DATA){if(e.byteLength<s)break;let l=e.sublist(0,s);e.consume(s),t?.onData!=null&&t.onData(l),yield l,n=ft.LENGTH}}}return Pe(r)?async function*(){for await(let l of r)e.append(l),yield*c();if(e.byteLength>0)throw new Gt("Unexpected end of input")}():function*(){for(let l of r)e.append(l),yield*c();if(e.byteLength>0)throw new Gt("Unexpected end of input")}()}Xt.fromReader=(r,t)=>{let e=1,n=async function*(){for(;;)try{let{done:i,value:o}=await r.next(e);if(i===!0)return;o!=null&&(yield o)}catch(i){if(i.code==="ERR_UNDER_READ")return{done:!0,value:null};throw i}finally{e=1}}();return Xt(n,{...t??{},onLength:i=>{e=i}})};function zi(r){let[t,e]=r[Symbol.asyncIterator]!=null?[r[Symbol.asyncIterator](),Symbol.asyncIterator]:[r[Symbol.iterator](),Symbol.iterator],n=[];return{peek:()=>t.next(),push:s=>{n.push(s)},next:()=>n.length>0?{done:!1,value:n.shift()}:t.next(),[e](){return this}}}var Kn=zi;function Oi(r){return r[Symbol.asyncIterator]!=null}function $i(r,t){let e=0;if(Oi(r))return async function*(){for await(let c of r)yield t(c,e++)}();let n=Kn(r),{value:s,done:i}=n.next();if(i===!0)return function*(){}();let o=t(s,e++);if(typeof o.then=="function")return async function*(){yield await o;for await(let c of n)yield t(c,e++)}();let a=t;return function*(){yield o;for(let c of n)yield a(c,e++)}()}var Jn=$i;var Ir=class{readNext;haveNext;ended;nextResult;error;constructor(){this.ended=!1,this.readNext=D(),this.haveNext=D()}[Symbol.asyncIterator](){return this}async next(){if(this.nextResult==null&&await this.haveNext.promise,this.nextResult==null)throw new Error("HaveNext promise resolved but nextResult was undefined");let t=this.nextResult;return this.nextResult=void 0,this.readNext.resolve(),this.readNext=D(),t}async throw(t){return this.ended=!0,this.error=t,t!=null&&(this.haveNext.promise.catch(()=>{}),this.haveNext.reject(t)),{done:!0,value:void 0}}async return(){let t={done:!0,value:void 0};return this.ended=!0,this.nextResult=t,this.haveNext.resolve(),t}async push(t,e){await this._push(t,e)}async end(t,e){t!=null?await this.throw(t):await this._push(void 0,e)}async _push(t,e){if(t!=null&&this.ended)throw this.error??new Error("Cannot push value onto an ended pushable");for(;this.nextResult!=null;)await this.readNext.promise;t!=null?this.nextResult={done:!1,value:t}:(this.ended=!0,this.nextResult={done:!0,value:void 0}),this.haveNext.resolve(),this.haveNext=D(),await Ee(this.readNext.promise,e?.signal,e)}};function Zn(){return new Ir}function qi(r){return r[Symbol.asyncIterator]!=null}async function Hi(r,t,e){try{await Promise.all(r.map(async n=>{for await(let s of n)await t.push(s,{signal:e}),e.throwIfAborted()})),await t.end(void 0,{signal:e})}catch(n){await t.end(n,{signal:e}).catch(()=>{})}}async function*Vi(r){let t=new AbortController,e=Zn();Hi(r,e,t.signal).catch(()=>{});try{yield*e}finally{t.abort()}}function*Wi(r){for(let t of r)yield*t}function Gi(...r){let t=[];for(let e of r)qi(e)||t.push(e);return t.length===r.length?Wi(t):Vi(r)}var Yn=Gi;function Lr(r,...t){if(r==null)throw new Error("Empty pipeline");if(Ar(r)){let n=r;r=()=>n.source}else if(es(r)||ts(r)){let n=r;r=()=>n}let e=[r,...t];if(e.length>1&&Ar(e[e.length-1])&&(e[e.length-1]=e[e.length-1].sink),e.length>2)for(let n=1;n<e.length-1;n++)Ar(e[n])&&(e[n]=Qi(e[n]));return Xi(...e)}var Xi=(...r)=>{let t;for(;r.length>0;)t=r.shift()(t);return t},ts=r=>r?.[Symbol.asyncIterator]!=null,es=r=>r?.[Symbol.iterator]!=null,Ar=r=>r==null?!1:r.sink!=null&&r.source!=null,Qi=r=>t=>{let e=r.sink(t);if(e?.then!=null){let n=ye({objectMode:!0});e.then(()=>{n.end()},o=>{n.end(o)});let s,i=r.source;if(ts(i))s=async function*(){yield*i,n.end()};else if(es(i))s=function*(){yield*i,n.end()};else throw new Error("Unknown duplex source type - must be Iterable or AsyncIterable");return Yn(n,s())}return r.source};function ji(r){return r[Symbol.asyncIterator]!=null}function Ki(r,t){return ji(r)?async function*(){let e=0;if(!(t<1)){for await(let n of r)if(yield n,e++,e===t)return}}():function*(){let e=0;if(!(t<1)){for(let n of r)if(yield n,e++,e===t)return}}()}var rs=Ki;var rt=class extends Event{type;detail;constructor(t,e){super(t),this.type=t,this.detail=e}};var Qt="/ipfs/bitswap/1.2.0";var Tr=new Float32Array([-0]),ut=new Uint8Array(Tr.buffer);function ns(r,t,e){Tr[0]=r,t[e]=ut[0],t[e+1]=ut[1],t[e+2]=ut[2],t[e+3]=ut[3]}function ss(r,t){return ut[0]=r[t],ut[1]=r[t+1],ut[2]=r[t+2],ut[3]=r[t+3],Tr[0]}var Pr=new Float64Array([-0]),M=new Uint8Array(Pr.buffer);function is(r,t,e){Pr[0]=r,t[e]=M[0],t[e+1]=M[1],t[e+2]=M[2],t[e+3]=M[3],t[e+4]=M[4],t[e+5]=M[5],t[e+6]=M[6],t[e+7]=M[7]}function os(r,t){return M[0]=r[t],M[1]=r[t+1],M[2]=r[t+2],M[3]=r[t+3],M[4]=r[t+4],M[5]=r[t+5],M[6]=r[t+6],M[7]=r[t+7],Pr[0]}var Ji=BigInt(Number.MAX_SAFE_INTEGER),Zi=BigInt(Number.MIN_SAFE_INTEGER),$=class r{lo;hi;constructor(t,e){this.lo=t|0,this.hi=e|0}toNumber(t=!1){if(!t&&this.hi>>>31>0){let e=~this.lo+1>>>0,n=~this.hi>>>0;return e===0&&(n=n+1>>>0),-(e+n*4294967296)}return this.lo+this.hi*4294967296}toBigInt(t=!1){if(t)return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n);if(this.hi>>>31){let e=~this.lo+1>>>0,n=~this.hi>>>0;return e===0&&(n=n+1>>>0),-(BigInt(e)+(BigInt(n)<<32n))}return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n)}toString(t=!1){return this.toBigInt(t).toString()}zzEncode(){let t=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^t)>>>0,this.lo=(this.lo<<1^t)>>>0,this}zzDecode(){let t=-(this.lo&1);return this.lo=((this.lo>>>1|this.hi<<31)^t)>>>0,this.hi=(this.hi>>>1^t)>>>0,this}length(){let t=this.lo,e=(this.lo>>>28|this.hi<<4)>>>0,n=this.hi>>>24;return n===0?e===0?t<16384?t<128?1:2:t<2097152?3:4:e<16384?e<128?5:6:e<2097152?7:8:n<128?9:10}static fromBigInt(t){if(t===0n)return dt;if(t<Ji&&t>Zi)return this.fromNumber(Number(t));let e=t<0n;e&&(t=-t);let n=t>>32n,s=t-(n<<32n);return e&&(n=~n|0n,s=~s|0n,++s>as&&(s=0n,++n>as&&(n=0n))),new r(Number(s),Number(n))}static fromNumber(t){if(t===0)return dt;let e=t<0;e&&(t=-t);let n=t>>>0,s=(t-n)/4294967296>>>0;return e&&(s=~s>>>0,n=~n>>>0,++n>4294967295&&(n=0,++s>4294967295&&(s=0))),new r(n,s)}static from(t){return typeof t=="number"?r.fromNumber(t):typeof t=="bigint"?r.fromBigInt(t):typeof t=="string"?r.fromBigInt(BigInt(t)):t.low!=null||t.high!=null?new r(t.low>>>0,t.high>>>0):dt}},dt=new $(0,0);dt.toBigInt=function(){return 0n};dt.zzEncode=dt.zzDecode=function(){return this};dt.length=function(){return 1};var as=4294967296n;function cs(r){let t=0,e=0;for(let n=0;n<r.length;++n)e=r.charCodeAt(n),e<128?t+=1:e<2048?t+=2:(e&64512)===55296&&(r.charCodeAt(n+1)&64512)===56320?(++n,t+=4):t+=3;return t}function ls(r,t,e){if(e-t<1)return"";let s,i=[],o=0,a;for(;t<e;)a=r[t++],a<128?i[o++]=a:a>191&&a<224?i[o++]=(a&31)<<6|r[t++]&63:a>239&&a<365?(a=((a&7)<<18|(r[t++]&63)<<12|(r[t++]&63)<<6|r[t++]&63)-65536,i[o++]=55296+(a>>10),i[o++]=56320+(a&1023)):i[o++]=(a&15)<<12|(r[t++]&63)<<6|r[t++]&63,o>8191&&((s??(s=[])).push(String.fromCharCode.apply(String,i)),o=0);return s!=null?(o>0&&s.push(String.fromCharCode.apply(String,i.slice(0,o))),s.join("")):String.fromCharCode.apply(String,i.slice(0,o))}function Dr(r,t,e){let n=e,s,i;for(let o=0;o<r.length;++o)s=r.charCodeAt(o),s<128?t[e++]=s:s<2048?(t[e++]=s>>6|192,t[e++]=s&63|128):(s&64512)===55296&&((i=r.charCodeAt(o+1))&64512)===56320?(s=65536+((s&1023)<<10)+(i&1023),++o,t[e++]=s>>18|240,t[e++]=s>>12&63|128,t[e++]=s>>6&63|128,t[e++]=s&63|128):(t[e++]=s>>12|224,t[e++]=s>>6&63|128,t[e++]=s&63|128);return e-n}function J(r,t){return RangeError(`index out of range: ${r.pos} + ${t??1} > ${r.len}`)}function Fe(r,t){return(r[t-4]|r[t-3]<<8|r[t-2]<<16|r[t-1]<<24)>>>0}var Nr=class{buf;pos;len;_slice=Uint8Array.prototype.subarray;constructor(t){this.buf=t,this.pos=0,this.len=t.length}uint32(){let t=4294967295;if(t=(this.buf[this.pos]&127)>>>0,this.buf[this.pos++]<128||(t=(t|(this.buf[this.pos]&127)<<7)>>>0,this.buf[this.pos++]<128)||(t=(t|(this.buf[this.pos]&127)<<14)>>>0,this.buf[this.pos++]<128)||(t=(t|(this.buf[this.pos]&127)<<21)>>>0,this.buf[this.pos++]<128)||(t=(t|(this.buf[this.pos]&15)<<28)>>>0,this.buf[this.pos++]<128))return t;if((this.pos+=5)>this.len)throw this.pos=this.len,J(this,10);return t}int32(){return this.uint32()|0}sint32(){let t=this.uint32();return t>>>1^-(t&1)|0}bool(){return this.uint32()!==0}fixed32(){if(this.pos+4>this.len)throw J(this,4);return Fe(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw J(this,4);return Fe(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw J(this,4);let t=ss(this.buf,this.pos);return this.pos+=4,t}double(){if(this.pos+8>this.len)throw J(this,4);let t=os(this.buf,this.pos);return this.pos+=8,t}bytes(){let t=this.uint32(),e=this.pos,n=this.pos+t;if(n>this.len)throw J(this,t);return this.pos+=t,e===n?new Uint8Array(0):this.buf.subarray(e,n)}string(){let t=this.bytes();return ls(t,0,t.length)}skip(t){if(typeof t=="number"){if(this.pos+t>this.len)throw J(this,t);this.pos+=t}else do if(this.pos>=this.len)throw J(this);while((this.buf[this.pos++]&128)!==0);return this}skipType(t){switch(t){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;(t=this.uint32()&7)!==4;)this.skipType(t);break;case 5:this.skip(4);break;default:throw Error(`invalid wire type ${t} at offset ${this.pos}`)}return this}readLongVarint(){let t=new $(0,0),e=0;if(this.len-this.pos>4){for(;e<4;++e)if(t.lo=(t.lo|(this.buf[this.pos]&127)<<e*7)>>>0,this.buf[this.pos++]<128)return t;if(t.lo=(t.lo|(this.buf[this.pos]&127)<<28)>>>0,t.hi=(t.hi|(this.buf[this.pos]&127)>>4)>>>0,this.buf[this.pos++]<128)return t;e=0}else{for(;e<3;++e){if(this.pos>=this.len)throw J(this);if(t.lo=(t.lo|(this.buf[this.pos]&127)<<e*7)>>>0,this.buf[this.pos++]<128)return t}return t.lo=(t.lo|(this.buf[this.pos++]&127)<<e*7)>>>0,t}if(this.len-this.pos>4){for(;e<5;++e)if(t.hi=(t.hi|(this.buf[this.pos]&127)<<e*7+3)>>>0,this.buf[this.pos++]<128)return t}else for(;e<5;++e){if(this.pos>=this.len)throw J(this);if(t.hi=(t.hi|(this.buf[this.pos]&127)<<e*7+3)>>>0,this.buf[this.pos++]<128)return t}throw Error("invalid varint encoding")}readFixed64(){if(this.pos+8>this.len)throw J(this,8);let t=Fe(this.buf,this.pos+=4),e=Fe(this.buf,this.pos+=4);return new $(t,e)}int64(){return this.readLongVarint().toBigInt()}int64Number(){return this.readLongVarint().toNumber()}int64String(){return this.readLongVarint().toString()}uint64(){return this.readLongVarint().toBigInt(!0)}uint64Number(){let t=Sr(this.buf,this.pos);return this.pos+=_(t),t}uint64String(){return this.readLongVarint().toString(!0)}sint64(){return this.readLongVarint().zzDecode().toBigInt()}sint64Number(){return this.readLongVarint().zzDecode().toNumber()}sint64String(){return this.readLongVarint().zzDecode().toString()}fixed64(){return this.readFixed64().toBigInt()}fixed64Number(){return this.readFixed64().toNumber()}fixed64String(){return this.readFixed64().toString()}sfixed64(){return this.readFixed64().toBigInt()}sfixed64Number(){return this.readFixed64().toNumber()}sfixed64String(){return this.readFixed64().toString()}};function Cr(r){return new Nr(r instanceof Uint8Array?r:r.subarray())}function pt(r,t,e){let n=Cr(r);return t.decode(n,void 0,e)}var Br={};O(Br,{base10:()=>so});var Vl=new Uint8Array(0);function hs(r,t){if(r===t)return!0;if(r.byteLength!==t.byteLength)return!1;for(let e=0;e<r.byteLength;e++)if(r[e]!==t[e])return!1;return!0}function st(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength);throw new Error("Unknown type, must be binary type")}function fs(r){return new TextEncoder().encode(r)}function ds(r){return new TextDecoder().decode(r)}function Yi(r,t){if(r.length>=255)throw new TypeError("Alphabet too long");for(var e=new Uint8Array(256),n=0;n<e.length;n++)e[n]=255;for(var s=0;s<r.length;s++){var i=r.charAt(s),o=i.charCodeAt(0);if(e[o]!==255)throw new TypeError(i+" is ambiguous");e[o]=s}var a=r.length,c=r.charAt(0),l=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function h(d){if(d instanceof Uint8Array||(ArrayBuffer.isView(d)?d=new Uint8Array(d.buffer,d.byteOffset,d.byteLength):Array.isArray(d)&&(d=Uint8Array.from(d))),!(d instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(d.length===0)return"";for(var E=0,b=0,L=0,B=d.length;L!==B&&d[L]===0;)L++,E++;for(var T=(B-L)*u+1>>>0,z=new Uint8Array(T);L!==B;){for(var H=d[L],lt=0,G=T-1;(H!==0||lt<b)&&G!==-1;G--,lt++)H+=256*z[G]>>>0,z[G]=H%a>>>0,H=H/a>>>0;if(H!==0)throw new Error("Non-zero carry");b=lt,L++}for(var nt=T-b;nt!==T&&z[nt]===0;)nt++;for(var he=c.repeat(E);nt<T;++nt)he+=r.charAt(z[nt]);return he}function f(d){if(typeof d!="string")throw new TypeError("Expected String");if(d.length===0)return new Uint8Array;var E=0;if(d[E]!==" "){for(var b=0,L=0;d[E]===c;)b++,E++;for(var B=(d.length-E)*l+1>>>0,T=new Uint8Array(B);d[E];){var z=e[d.charCodeAt(E)];if(z===255)return;for(var H=0,lt=B-1;(z!==0||H<L)&&lt!==-1;lt--,H++)z+=a*T[lt]>>>0,T[lt]=z%256>>>0,z=z/256>>>0;if(z!==0)throw new Error("Non-zero carry");L=H,E++}if(d[E]!==" "){for(var G=B-L;G!==B&&T[G]===0;)G++;for(var nt=new Uint8Array(b+(B-G)),he=b;G!==B;)nt[he++]=T[G++];return nt}}}function m(d){var E=f(d);if(E)return E;throw new Error(`Non-${t} character`)}return{encode:h,decodeUnsafe:f,decode:m}}var to=Yi,eo=to,ms=eo;var Fr=class{name;prefix;baseEncode;constructor(t,e,n){this.name=t,this.prefix=e,this.baseEncode=n}encode(t){if(t instanceof Uint8Array)return`${this.prefix}${this.baseEncode(t)}`;throw Error("Unknown type, must be binary type")}},Mr=class{name;prefix;baseDecode;prefixCodePoint;constructor(t,e,n){this.name=t,this.prefix=e;let s=e.codePointAt(0);if(s===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=s,this.baseDecode=n}decode(t){if(typeof t=="string"){if(t.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(t)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(t.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(t){return gs(this,t)}},Ur=class{decoders;constructor(t){this.decoders=t}or(t){return gs(this,t)}decode(t){let e=t[0],n=this.decoders[e];if(n!=null)return n.decode(t);throw RangeError(`Unable to decode multibase string ${JSON.stringify(t)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function gs(r,t){return new Ur({...r.decoders??{[r.prefix]:r},...t.decoders??{[t.prefix]:t}})}var Rr=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(t,e,n,s){this.name=t,this.prefix=e,this.baseEncode=n,this.baseDecode=s,this.encoder=new Fr(t,e,n),this.decoder=new Mr(t,e,s)}encode(t){return this.encoder.encode(t)}decode(t){return this.decoder.decode(t)}};function Tt({name:r,prefix:t,encode:e,decode:n}){return new Rr(r,t,e,n)}function ht({name:r,prefix:t,alphabet:e}){let{encode:n,decode:s}=ms(e,r);return Tt({prefix:t,name:r,encode:n,decode:i=>st(s(i))})}function ro(r,t,e,n){let s={};for(let u=0;u<t.length;++u)s[t[u]]=u;let i=r.length;for(;r[i-1]==="=";)--i;let o=new Uint8Array(i*e/8|0),a=0,c=0,l=0;for(let u=0;u<i;++u){let h=s[r[u]];if(h===void 0)throw new SyntaxError(`Non-${n} character`);c=c<<e|h,a+=e,a>=8&&(a-=8,o[l++]=255&c>>a)}if(a>=e||(255&c<<8-a)!==0)throw new SyntaxError("Unexpected end of data");return o}function no(r,t,e){let n=t[t.length-1]==="=",s=(1<<e)-1,i="",o=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],o+=8;o>e;)o-=e,i+=t[s&a>>o];if(o!==0&&(i+=t[s&a<<e-o]),n)for(;(i.length*e&7)!==0;)i+="=";return i}function I({name:r,prefix:t,bitsPerChar:e,alphabet:n}){return Tt({prefix:t,name:r,encode(s){return no(s,n,e)},decode(s){return ro(s,n,e,r)}})}var so=ht({prefix:"9",name:"base10",alphabet:"0123456789"});var zr={};O(zr,{base16:()=>io,base16upper:()=>oo});var io=I({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),oo=I({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var Or={};O(Or,{base2:()=>ao});var ao=I({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var $r={};O($r,{base256emoji:()=>fo});var ws=Array.from("\u{1F680}\u{1FA90}\u2604\u{1F6F0}\u{1F30C}\u{1F311}\u{1F312}\u{1F313}\u{1F314}\u{1F315}\u{1F316}\u{1F317}\u{1F318}\u{1F30D}\u{1F30F}\u{1F30E}\u{1F409}\u2600\u{1F4BB}\u{1F5A5}\u{1F4BE}\u{1F4BF}\u{1F602}\u2764\u{1F60D}\u{1F923}\u{1F60A}\u{1F64F}\u{1F495}\u{1F62D}\u{1F618}\u{1F44D}\u{1F605}\u{1F44F}\u{1F601}\u{1F525}\u{1F970}\u{1F494}\u{1F496}\u{1F499}\u{1F622}\u{1F914}\u{1F606}\u{1F644}\u{1F4AA}\u{1F609}\u263A\u{1F44C}\u{1F917}\u{1F49C}\u{1F614}\u{1F60E}\u{1F607}\u{1F339}\u{1F926}\u{1F389}\u{1F49E}\u270C\u2728\u{1F937}\u{1F631}\u{1F60C}\u{1F338}\u{1F64C}\u{1F60B}\u{1F497}\u{1F49A}\u{1F60F}\u{1F49B}\u{1F642}\u{1F493}\u{1F929}\u{1F604}\u{1F600}\u{1F5A4}\u{1F603}\u{1F4AF}\u{1F648}\u{1F447}\u{1F3B6}\u{1F612}\u{1F92D}\u2763\u{1F61C}\u{1F48B}\u{1F440}\u{1F62A}\u{1F611}\u{1F4A5}\u{1F64B}\u{1F61E}\u{1F629}\u{1F621}\u{1F92A}\u{1F44A}\u{1F973}\u{1F625}\u{1F924}\u{1F449}\u{1F483}\u{1F633}\u270B\u{1F61A}\u{1F61D}\u{1F634}\u{1F31F}\u{1F62C}\u{1F643}\u{1F340}\u{1F337}\u{1F63B}\u{1F613}\u2B50\u2705\u{1F97A}\u{1F308}\u{1F608}\u{1F918}\u{1F4A6}\u2714\u{1F623}\u{1F3C3}\u{1F490}\u2639\u{1F38A}\u{1F498}\u{1F620}\u261D\u{1F615}\u{1F33A}\u{1F382}\u{1F33B}\u{1F610}\u{1F595}\u{1F49D}\u{1F64A}\u{1F639}\u{1F5E3}\u{1F4AB}\u{1F480}\u{1F451}\u{1F3B5}\u{1F91E}\u{1F61B}\u{1F534}\u{1F624}\u{1F33C}\u{1F62B}\u26BD\u{1F919}\u2615\u{1F3C6}\u{1F92B}\u{1F448}\u{1F62E}\u{1F646}\u{1F37B}\u{1F343}\u{1F436}\u{1F481}\u{1F632}\u{1F33F}\u{1F9E1}\u{1F381}\u26A1\u{1F31E}\u{1F388}\u274C\u270A\u{1F44B}\u{1F630}\u{1F928}\u{1F636}\u{1F91D}\u{1F6B6}\u{1F4B0}\u{1F353}\u{1F4A2}\u{1F91F}\u{1F641}\u{1F6A8}\u{1F4A8}\u{1F92C}\u2708\u{1F380}\u{1F37A}\u{1F913}\u{1F619}\u{1F49F}\u{1F331}\u{1F616}\u{1F476}\u{1F974}\u25B6\u27A1\u2753\u{1F48E}\u{1F4B8}\u2B07\u{1F628}\u{1F31A}\u{1F98B}\u{1F637}\u{1F57A}\u26A0\u{1F645}\u{1F61F}\u{1F635}\u{1F44E}\u{1F932}\u{1F920}\u{1F927}\u{1F4CC}\u{1F535}\u{1F485}\u{1F9D0}\u{1F43E}\u{1F352}\u{1F617}\u{1F911}\u{1F30A}\u{1F92F}\u{1F437}\u260E\u{1F4A7}\u{1F62F}\u{1F486}\u{1F446}\u{1F3A4}\u{1F647}\u{1F351}\u2744\u{1F334}\u{1F4A3}\u{1F438}\u{1F48C}\u{1F4CD}\u{1F940}\u{1F922}\u{1F445}\u{1F4A1}\u{1F4A9}\u{1F450}\u{1F4F8}\u{1F47B}\u{1F910}\u{1F92E}\u{1F3BC}\u{1F975}\u{1F6A9}\u{1F34E}\u{1F34A}\u{1F47C}\u{1F48D}\u{1F4E3}\u{1F942}"),co=ws.reduce((r,t,e)=>(r[e]=t,r),[]),lo=ws.reduce((r,t,e)=>{let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);return r[n]=e,r},[]);function uo(r){return r.reduce((t,e)=>(t+=co[e],t),"")}function ho(r){let t=[];for(let e of r){let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);let s=lo[n];if(s==null)throw new Error(`Non-base256emoji character: ${e}`);t.push(s)}return new Uint8Array(t)}var fo=Tt({prefix:"\u{1F680}",name:"base256emoji",encode:uo,decode:ho});var qr={};O(qr,{base32:()=>it,base32hex:()=>wo,base32hexpad:()=>yo,base32hexpadupper:()=>xo,base32hexupper:()=>bo,base32pad:()=>mo,base32padupper:()=>go,base32upper:()=>po,base32z:()=>vo});var it=I({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),po=I({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),mo=I({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),go=I({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),wo=I({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),bo=I({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),yo=I({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),xo=I({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),vo=I({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Hr={};O(Hr,{base36:()=>jt,base36upper:()=>Eo});var jt=ht({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Eo=ht({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var Vr={};O(Vr,{base58btc:()=>P,base58flickr:()=>_o});var P=ht({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),_o=ht({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var Gr={};O(Gr,{base64:()=>ot,base64pad:()=>So,base64url:()=>Wr,base64urlpad:()=>ko});var ot=I({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),So=I({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Wr=I({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),ko=I({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var Xr={};O(Xr,{base8:()=>Io});var Io=I({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var Qr={};O(Qr,{identity:()=>Ao});var Ao=Tt({prefix:"\0",name:"identity",encode:r=>ds(r),decode:r=>fs(r)});var ou=new TextEncoder,au=new TextDecoder;var Kr={};O(Kr,{identity:()=>Ko});var Po=xs,bs=128,Do=127,No=~Do,Co=Math.pow(2,31);function xs(r,t,e){t=t||[],e=e||0;for(var n=e;r>=Co;)t[e++]=r&255|bs,r/=128;for(;r&No;)t[e++]=r&255|bs,r>>>=7;return t[e]=r|0,xs.bytes=e-n+1,t}var Fo=jr,Mo=128,ys=127;function jr(r,n){var e=0,n=n||0,s=0,i=n,o,a=r.length;do{if(i>=a)throw jr.bytes=0,new RangeError("Could not decode varint");o=r[i++],e+=s<28?(o&ys)<<s:(o&ys)*Math.pow(2,s),s+=7}while(o>=Mo);return jr.bytes=i-n,e}var Uo=Math.pow(2,7),Ro=Math.pow(2,14),Bo=Math.pow(2,21),zo=Math.pow(2,28),Oo=Math.pow(2,35),$o=Math.pow(2,42),qo=Math.pow(2,49),Ho=Math.pow(2,56),Vo=Math.pow(2,63),Wo=function(r){return r<Uo?1:r<Ro?2:r<Bo?3:r<zo?4:r<Oo?5:r<$o?6:r<qo?7:r<Ho?8:r<Vo?9:10},Go={encode:Po,decode:Fo,encodingLength:Wo},Xo=Go,Kt=Xo;function Jt(r,t=0){return[Kt.decode(r,t),Kt.decode.bytes]}function Pt(r,t,e=0){return Kt.encode(r,t,e),t}function Dt(r){return Kt.encodingLength(r)}function mt(r,t){let e=t.byteLength,n=Dt(r),s=n+Dt(e),i=new Uint8Array(s+e);return Pt(r,i,0),Pt(e,i,n),i.set(t,s),new Nt(r,e,t,i)}function Zt(r){let t=st(r),[e,n]=Jt(t),[s,i]=Jt(t.subarray(n)),o=t.subarray(n+i);if(o.byteLength!==s)throw new Error("Incorrect length");return new Nt(e,s,o,t)}function vs(r,t){if(r===t)return!0;{let e=t;return r.code===e.code&&r.size===e.size&&e.bytes instanceof Uint8Array&&hs(r.bytes,e.bytes)}}var Nt=class{code;size;digest;bytes;constructor(t,e,n,s){this.code=t,this.size=e,this.digest=n,this.bytes=s}};var Es=0,Qo="identity",_s=st;function jo(r){return mt(Es,_s(r))}var Ko={code:Es,name:Qo,encode:_s,digest:jo};var Yr={};O(Yr,{sha256:()=>Ue,sha512:()=>Jo});function Zr({name:r,code:t,encode:e}){return new Jr(r,t,e)}var Jr=class{name;code;encode;constructor(t,e,n){this.name=t,this.code=e,this.encode=n}digest(t){if(t instanceof Uint8Array){let e=this.encode(t);return e instanceof Uint8Array?mt(this.code,e):e.then(n=>mt(this.code,n))}else throw Error("Unknown type, must be binary type")}};function ks(r){return async t=>new Uint8Array(await crypto.subtle.digest(r,t))}var Ue=Zr({name:"sha2-256",code:18,encode:ks("SHA-256")}),Jo=Zr({name:"sha2-512",code:19,encode:ks("SHA-512")});function Is(r,t){let{bytes:e,version:n}=r;switch(n){case 0:return Yo(e,tn(r),t??P.encoder);default:return ta(e,tn(r),t??it.encoder)}}var As=new WeakMap;function tn(r){let t=As.get(r);if(t==null){let e=new Map;return As.set(r,e),e}return t}var q=class r{code;version;multihash;bytes;"/";constructor(t,e,n,s){this.code=e,this.version=t,this.multihash=n,this.bytes=s,this["/"]=s}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:t,multihash:e}=this;if(t!==Yt)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(e.code!==ea)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return r.createV0(e)}default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}toV1(){switch(this.version){case 0:{let{code:t,digest:e}=this.multihash,n=mt(t,e);return r.createV1(this.code,n)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(t){return r.equals(this,t)}static equals(t,e){let n=e;return n!=null&&t.code===n.code&&t.version===n.version&&vs(t.multihash,n.multihash)}toString(t){return Is(this,t)}toJSON(){return{"/":Is(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(t){if(t==null)return null;let e=t;if(e instanceof r)return e;if(e["/"]!=null&&e["/"]===e.bytes||e.asCID===e){let{version:n,code:s,multihash:i,bytes:o}=e;return new r(n,s,i,o??Ls(n,s,i.bytes))}else if(e[ra]===!0){let{version:n,multihash:s,code:i}=e,o=Zt(s);return r.create(n,i,o)}else return null}static create(t,e,n){if(typeof e!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(t){case 0:{if(e!==Yt)throw new Error(`Version 0 CID must use dag-pb (code: ${Yt}) block encoding`);return new r(t,e,n,n.bytes)}case 1:{let s=Ls(t,e,n.bytes);return new r(t,e,n,s)}default:throw new Error("Invalid version")}}static createV0(t){return r.create(0,Yt,t)}static createV1(t,e){return r.create(1,t,e)}static decode(t){let[e,n]=r.decodeFirst(t);if(n.length!==0)throw new Error("Incorrect length");return e}static decodeFirst(t){let e=r.inspectBytes(t),n=e.size-e.multihashSize,s=st(t.subarray(n,n+e.multihashSize));if(s.byteLength!==e.multihashSize)throw new Error("Incorrect length");let i=s.subarray(e.multihashSize-e.digestSize),o=new Nt(e.multihashCode,e.digestSize,i,s);return[e.version===0?r.createV0(o):r.createV1(e.codec,o),t.subarray(e.size)]}static inspectBytes(t){let e=0,n=()=>{let[h,f]=Jt(t.subarray(e));return e+=f,h},s=n(),i=Yt;if(s===18?(s=0,e=0):i=n(),s!==0&&s!==1)throw new RangeError(`Invalid CID version ${s}`);let o=e,a=n(),c=n(),l=e+c,u=l-o;return{version:s,codec:i,multihashCode:a,digestSize:c,multihashSize:u,size:l}}static parse(t,e){let[n,s]=Zo(t,e),i=r.decode(s);if(i.version===0&&t[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return tn(i).set(n,t),i}};function Zo(r,t){switch(r[0]){case"Q":{let e=t??P;return[P.prefix,e.decode(`${P.prefix}${r}`)]}case P.prefix:{let e=t??P;return[P.prefix,e.decode(r)]}case it.prefix:{let e=t??it;return[it.prefix,e.decode(r)]}case jt.prefix:{let e=t??jt;return[jt.prefix,e.decode(r)]}default:{if(t==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[r[0],t.decode(r)]}}}function Yo(r,t,e){let{prefix:n}=e;if(n!==P.prefix)throw Error(`Cannot string encode V0 in ${e.name} encoding`);let s=t.get(n);if(s==null){let i=e.encode(r).slice(1);return t.set(n,i),i}else return s}function ta(r,t,e){let{prefix:n}=e,s=t.get(n);if(s==null){let i=e.encode(r);return t.set(n,i),i}else return s}var Yt=112,ea=18;function Ls(r,t,e){let n=Dt(r),s=n+Dt(t),i=new Uint8Array(s+e.byteLength);return Pt(r,i,0),Pt(t,i,n),i.set(e,s),i}var ra=Symbol.for("@ipld/js-cid/CID");var te={...Qr,...Or,...Xr,...Br,...zr,...qr,...Hr,...Vr,...Gr,...$r},Tu={...Yr,...Kr};function Ps(r,t,e,n){return{name:r,prefix:t,encoder:{name:r,prefix:t,encode:e},decoder:{decode:n}}}var Ts=Ps("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),en=Ps("ascii","a",r=>{let t="a";for(let e=0;e<r.length;e++)t+=String.fromCharCode(r[e]);return t},r=>{r=r.substring(1);let t=C(r.length);for(let e=0;e<r.length;e++)t[e]=r.charCodeAt(e);return t}),na={utf8:Ts,"utf-8":Ts,hex:te.base16,latin1:en,ascii:en,binary:en,...te},Re=na;function U(r,t="utf8"){let e=Re[t];if(e==null)throw new Error(`Unsupported encoding "${t}"`);return e.decoder.decode(`${e.prefix}${r}`)}function rn(r){let t=r??8192,e=t>>>1,n,s=t;return function(o){if(o<1||o>e)return C(o);s+o>t&&(n=C(t),s=0);let a=n.subarray(s,s+=o);return(s&7)!==0&&(s=(s|7)+1),a}}var wt=class{fn;len;next;val;constructor(t,e,n){this.fn=t,this.len=e,this.next=void 0,this.val=n}};function nn(){}var on=class{head;tail;len;next;constructor(t){this.head=t.head,this.tail=t.tail,this.len=t.len,this.next=t.states}},sa=rn();function ia(r){return globalThis.Buffer!=null?C(r):sa(r)}var re=class{len;head;tail;states;constructor(){this.len=0,this.head=new wt(nn,0,0),this.tail=this.head,this.states=null}_push(t,e,n){return this.tail=this.tail.next=new wt(t,e,n),this.len+=e,this}uint32(t){return this.len+=(this.tail=this.tail.next=new an((t=t>>>0)<128?1:t<16384?2:t<2097152?3:t<268435456?4:5,t)).len,this}int32(t){return t<0?this._push(Be,10,$.fromNumber(t)):this.uint32(t)}sint32(t){return this.uint32((t<<1^t>>31)>>>0)}uint64(t){let e=$.fromBigInt(t);return this._push(Be,e.length(),e)}uint64Number(t){return this._push(_r,_(t),t)}uint64String(t){return this.uint64(BigInt(t))}int64(t){return this.uint64(t)}int64Number(t){return this.uint64Number(t)}int64String(t){return this.uint64String(t)}sint64(t){let e=$.fromBigInt(t).zzEncode();return this._push(Be,e.length(),e)}sint64Number(t){let e=$.fromNumber(t).zzEncode();return this._push(Be,e.length(),e)}sint64String(t){return this.sint64(BigInt(t))}bool(t){return this._push(sn,1,t?1:0)}fixed32(t){return this._push(ee,4,t>>>0)}sfixed32(t){return this.fixed32(t)}fixed64(t){let e=$.fromBigInt(t);return this._push(ee,4,e.lo)._push(ee,4,e.hi)}fixed64Number(t){let e=$.fromNumber(t);return this._push(ee,4,e.lo)._push(ee,4,e.hi)}fixed64String(t){return this.fixed64(BigInt(t))}sfixed64(t){return this.fixed64(t)}sfixed64Number(t){return this.fixed64Number(t)}sfixed64String(t){return this.fixed64String(t)}float(t){return this._push(ns,4,t)}double(t){return this._push(is,8,t)}bytes(t){let e=t.length>>>0;return e===0?this._push(sn,1,0):this.uint32(e)._push(aa,e,t)}string(t){let e=cs(t);return e!==0?this.uint32(e)._push(Dr,e,t):this._push(sn,1,0)}fork(){return this.states=new on(this),this.head=this.tail=new wt(nn,0,0),this.len=0,this}reset(){return this.states!=null?(this.head=this.states.head,this.tail=this.states.tail,this.len=this.states.len,this.states=this.states.next):(this.head=this.tail=new wt(nn,0,0),this.len=0),this}ldelim(){let t=this.head,e=this.tail,n=this.len;return this.reset().uint32(n),n!==0&&(this.tail.next=t.next,this.tail=e,this.len+=n),this}finish(){let t=this.head.next,e=ia(this.len),n=0;for(;t!=null;)t.fn(t.val,e,n),n+=t.len,t=t.next;return e}};function sn(r,t,e){t[e]=r&255}function oa(r,t,e){for(;r>127;)t[e++]=r&127|128,r>>>=7;t[e]=r}var an=class extends wt{next;constructor(t,e){super(oa,t,e),this.next=void 0}};function Be(r,t,e){for(;r.hi!==0;)t[e++]=r.lo&127|128,r.lo=(r.lo>>>7|r.hi<<25)>>>0,r.hi>>>=7;for(;r.lo>127;)t[e++]=r.lo&127|128,r.lo=r.lo>>>7;t[e++]=r.lo}function ee(r,t,e){t[e]=r&255,t[e+1]=r>>>8&255,t[e+2]=r>>>16&255,t[e+3]=r>>>24}function aa(r,t,e){t.set(r,e)}globalThis.Buffer!=null&&(re.prototype.bytes=function(r){let t=r.length>>>0;return this.uint32(t),t>0&&this._push(ca,t,r),this},re.prototype.string=function(r){let t=globalThis.Buffer.byteLength(r);return this.uint32(t),t>0&&this._push(la,t,r),this});function ca(r,t,e){t.set(r,e)}function la(r,t,e){r.length<40?Dr(r,t,e):t.utf8Write!=null?t.utf8Write(r,e):t.set(U(r),e)}function cn(){return new re}function bt(r,t){let e=cn();return t.encode(r,e,{lengthDelimited:!1}),e.finish()}var Ct;(function(r){r[r.VARINT=0]="VARINT",r[r.BIT64=1]="BIT64",r[r.LENGTH_DELIMITED=2]="LENGTH_DELIMITED",r[r.START_GROUP=3]="START_GROUP",r[r.END_GROUP=4]="END_GROUP",r[r.BIT32=5]="BIT32"})(Ct||(Ct={}));function ze(r,t,e,n){return{name:r,type:t,encode:e,decode:n}}function Oe(r){function t(s){if(r[s.toString()]==null)throw new Error("Invalid enum value");return r[s]}let e=function(i,o){let a=t(i);o.int32(a)},n=function(i){let o=i.int32();return t(o)};return ze("enum",Ct.VARINT,e,n)}function yt(r,t){return ze("message",Ct.LENGTH_DELIMITED,r,t)}var Ft=class extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"};var A;(function(r){r.WantBlock="WantBlock",r.WantHave="WantHave"})(A||(A={}));var ln;(function(r){r[r.WantBlock=0]="WantBlock",r[r.WantHave=1]="WantHave"})(ln||(ln={}));(function(r){r.codec=()=>Oe(ln)})(A||(A={}));var Mt;(function(r){let t;r.codec=()=>(t==null&&(t=yt((e,n,s={})=>{s.lengthDelimited!==!1&&n.fork(),e.cid!=null&&e.cid.byteLength>0&&(n.uint32(10),n.bytes(e.cid)),e.priority!=null&&e.priority!==0&&(n.uint32(16),n.int32(e.priority)),e.cancel!=null&&(n.uint32(24),n.bool(e.cancel)),e.wantType!=null&&(n.uint32(32),A.codec().encode(e.wantType,n)),e.sendDontHave!=null&&(n.uint32(40),n.bool(e.sendDontHave)),s.lengthDelimited!==!1&&n.ldelim()},(e,n,s={})=>{let i={cid:N(0),priority:0},o=n==null?e.len:e.pos+n;for(;e.pos<o;){let a=e.uint32();switch(a>>>3){case 1:{i.cid=e.bytes();break}case 2:{i.priority=e.int32();break}case 3:{i.cancel=e.bool();break}case 4:{i.wantType=A.codec().decode(e);break}case 5:{i.sendDontHave=e.bool();break}default:{e.skipType(a&7);break}}}return i})),t),r.encode=e=>bt(e,r.codec()),r.decode=(e,n)=>pt(e,r.codec(),n)})(Mt||(Mt={}));var $e;(function(r){let t;r.codec=()=>(t==null&&(t=yt((e,n,s={})=>{if(s.lengthDelimited!==!1&&n.fork(),e.entries!=null)for(let i of e.entries)n.uint32(10),Mt.codec().encode(i,n);e.full!=null&&(n.uint32(16),n.bool(e.full)),s.lengthDelimited!==!1&&n.ldelim()},(e,n,s={})=>{let i={entries:[]},o=n==null?e.len:e.pos+n;for(;e.pos<o;){let a=e.uint32();switch(a>>>3){case 1:{if(s.limits?.entries!=null&&i.entries.length===s.limits.entries)throw new Ft('Decode error - map field "entries" had too many elements');i.entries.push(Mt.codec().decode(e,e.uint32(),{limits:s.limits?.entries$}));break}case 2:{i.full=e.bool();break}default:{e.skipType(a&7);break}}}return i})),t),r.encode=e=>bt(e,r.codec()),r.decode=(e,n)=>pt(e,r.codec(),n)})($e||($e={}));var Ut;(function(r){let t;r.codec=()=>(t==null&&(t=yt((e,n,s={})=>{s.lengthDelimited!==!1&&n.fork(),e.prefix!=null&&e.prefix.byteLength>0&&(n.uint32(10),n.bytes(e.prefix)),e.data!=null&&e.data.byteLength>0&&(n.uint32(18),n.bytes(e.data)),s.lengthDelimited!==!1&&n.ldelim()},(e,n,s={})=>{let i={prefix:N(0),data:N(0)},o=n==null?e.len:e.pos+n;for(;e.pos<o;){let a=e.uint32();switch(a>>>3){case 1:{i.prefix=e.bytes();break}case 2:{i.data=e.bytes();break}default:{e.skipType(a&7);break}}}return i})),t),r.encode=e=>bt(e,r.codec()),r.decode=(e,n)=>pt(e,r.codec(),n)})(Ut||(Ut={}));var W;(function(r){r.HaveBlock="HaveBlock",r.DoNotHaveBlock="DoNotHaveBlock"})(W||(W={}));var qe;(function(r){r[r.HaveBlock=0]="HaveBlock",r[r.DoNotHaveBlock=1]="DoNotHaveBlock"})(qe||(qe={}));(function(r){r.codec=()=>Oe(qe)})(W||(W={}));var Rt;(function(r){let t;r.codec=()=>(t==null&&(t=yt((e,n,s={})=>{s.lengthDelimited!==!1&&n.fork(),e.cid!=null&&e.cid.byteLength>0&&(n.uint32(10),n.bytes(e.cid)),e.type!=null&&qe[e.type]!==0&&(n.uint32(16),W.codec().encode(e.type,n)),s.lengthDelimited!==!1&&n.ldelim()},(e,n,s={})=>{let i={cid:N(0),type:W.HaveBlock},o=n==null?e.len:e.pos+n;for(;e.pos<o;){let a=e.uint32();switch(a>>>3){case 1:{i.cid=e.bytes();break}case 2:{i.type=W.codec().decode(e);break}default:{e.skipType(a&7);break}}}return i})),t),r.encode=e=>bt(e,r.codec()),r.decode=(e,n)=>pt(e,r.codec(),n)})(Rt||(Rt={}));var xt;(function(r){let t;r.codec=()=>(t==null&&(t=yt((e,n,s={})=>{if(s.lengthDelimited!==!1&&n.fork(),e.wantlist!=null&&(n.uint32(10),$e.codec().encode(e.wantlist,n)),e.blocks!=null)for(let i of e.blocks)n.uint32(26),Ut.codec().encode(i,n);if(e.blockPresences!=null)for(let i of e.blockPresences)n.uint32(34),Rt.codec().encode(i,n);e.pendingBytes!=null&&e.pendingBytes!==0&&(n.uint32(40),n.int32(e.pendingBytes)),s.lengthDelimited!==!1&&n.ldelim()},(e,n,s={})=>{let i={blocks:[],blockPresences:[],pendingBytes:0},o=n==null?e.len:e.pos+n;for(;e.pos<o;){let a=e.uint32();switch(a>>>3){case 1:{i.wantlist=$e.codec().decode(e,e.uint32(),{limits:s.limits?.wantlist});break}case 3:{if(s.limits?.blocks!=null&&i.blocks.length===s.limits.blocks)throw new Ft('Decode error - map field "blocks" had too many elements');i.blocks.push(Ut.codec().decode(e,e.uint32(),{limits:s.limits?.blocks$}));break}case 4:{if(s.limits?.blockPresences!=null&&i.blockPresences.length===s.limits.blockPresences)throw new Ft('Decode error - map field "blockPresences" had too many elements');i.blockPresences.push(Rt.codec().decode(e,e.uint32(),{limits:s.limits?.blockPresences$}));break}case 5:{i.pendingBytes=e.int32();break}default:{e.skipType(a&7);break}}}return i})),t),r.encode=e=>bt(e,r.codec()),r.decode=(e,n)=>pt(e,r.codec(),n)})(xt||(xt={}));function Ds(r,t){for(let[e,n]of t.wantlist.entries()){let s=r.wantlist.get(e);s!=null&&(s.priority>n.priority&&(n.priority=s.priority),n.cancel=n.cancel??s.cancel,n.wantType=n.wantType??s.wantType,n.sendDontHave=n.sendDontHave??s.sendDontHave),r.wantlist.set(e,n)}for(let[e,n]of t.blockPresences.entries())r.blockPresences.set(e,n);for(let[e,n]of t.blocks.entries())r.blocks.set(e,n);return t.full&&!r.full&&(r.full=!0),r}var He=class extends Error{static name="BlockTooLargeError";constructor(t="Block too large"){super(t),this.name="BlockTooLargeError"}};var ua=4193648,ha=ua+16;function*Ns(r,t){let e=[...r.wantlist.values()],n=[...r.blockPresences.values()],s=[...r.blocks.values()],i=0,o=0,a=0,c=!1;for(;;){let l={wantlist:{full:r.full??!1,entries:[]},blockPresences:[],blocks:[],pendingBytes:0},u=xt.encode(l).byteLength,{added:h,hasMore:f,newSize:m}=un(s,l.blocks,a,t,u,fa);a+=h,u=m;let d=f;({added:h,hasMore:f,newSize:m}=un(n,l.blockPresences,o,t,u,da)),o+=h,u=m;let E=f;if({added:h,hasMore:f,newSize:m}=un(e,l.wantlist.entries,i,t,u,pa),i+=h,u=m,c=!d&&!E&&!f,c||(l.wantlist.full=!1),yield xt.encode(l),c)break}}function un(r,t,e,n,s,i){let o=0,a=!1;for(let c=e;c<r.length;c++){let l=r[c],u=i(l);if(u>ha)throw new He("Cannot send block as after encoding it is over the max message size");let h=s+u;if(h>n){a=!0;break}t.push(l),o++,s=h}return{hasMore:a,added:o,newSize:s}}function fa(r){return hn(3,Ut.encode(r))}function da(r){return hn(4,Rt.encode(r))}function pa(r){return hn(1,Mt.encode(r))}function hn(r,t){let e=_(r),n=_(t.byteLength);return e+n+t.byteLength}var Ve=class extends tt{log;libp2p;routing;protocols;running;maxInboundStreams;maxOutboundStreams;messageReceiveTimeout;registrarIds;metrics;sendQueue;runOnLimitedConnections;maxOutgoingMessageSize;maxIncomingMessageSize;constructor(t,e={}){super(),this.log=t.logger.forComponent("helia:bitswap:network"),this.libp2p=t.libp2p,this.routing=t.routing,this.protocols=e.protocols??[Qt],this.registrarIds=[],this.running=!1,this._onStream=this._onStream.bind(this),this.maxInboundStreams=e.maxInboundStreams??1024,this.maxOutboundStreams=e.maxOutboundStreams??1024,this.messageReceiveTimeout=e.messageReceiveTimeout??5e3,this.runOnLimitedConnections=e.runOnLimitedConnections??!1,this.maxIncomingMessageSize=e.maxIncomingMessageSize??4194304,this.maxOutgoingMessageSize=e.maxOutgoingMessageSize??e.maxIncomingMessageSize??4194304,this.metrics={blocksSent:t.metrics?.registerCounter("helia_bitswap_sent_blocks_total"),dataSent:t.metrics?.registerCounter("helia_bitswap_sent_data_bytes_total")},this.sendQueue=new ke({concurrency:e.messageSendConcurrency??50,metrics:t.metrics,metricName:"helia_bitswap_message_send_queue"}),this.sendQueue.addEventListener("error",n=>{this.log.error("error sending wantlist to peer",n.detail)})}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 t={onConnect:e=>{this.safeDispatchEvent("peer:connected",{detail:e})},onDisconnect:e=>{this.safeDispatchEvent("peer:disconnected",{detail:e})}};this.registrarIds=[];for(let e of this.protocols)this.registrarIds.push(await this.libp2p.register(e,t));this.libp2p.getConnections().forEach(e=>{this.safeDispatchEvent("peer:connected",{detail:e.remotePeer})})}async stop(){if(this.running=!1,await this.libp2p.unhandle(this.protocols),this.registrarIds!=null){for(let t of this.registrarIds)this.libp2p.unregister(t);this.registrarIds=[]}}_onStream(t){if(!this.running)return;let{stream:e,connection:n}=t;Promise.resolve().then(async()=>{this.log("incoming new bitswap %s stream from %p",e.protocol,n.remotePeer);let s=()=>{e.status==="open"?e.abort(new ge(`Incoming Bitswap stream timed out after ${this.messageReceiveTimeout}ms`)):this.log("stream aborted with status %s",e.status)},i=AbortSignal.timeout(this.messageReceiveTimeout);i.addEventListener("abort",s),await e.closeWrite(),await Lr(e,o=>Xt(o,{maxDataLength:this.maxIncomingMessageSize}),async o=>{for await(let a of o)try{let c=xt.decode(a);this.log("incoming new bitswap %s message from %p on stream",e.protocol,n.remotePeer,e.id),this.safeDispatchEvent("bitswap:message",{detail:{peer:n.remotePeer,message:c}}),i.removeEventListener("abort",s),i=AbortSignal.timeout(this.messageReceiveTimeout),i.addEventListener("abort",s)}catch(c){this.log.error("error reading incoming bitswap message from %p on stream",n.remotePeer,e.id,c),e.abort(c);break}})}).catch(s=>{this.log.error("error handling incoming stream from %p",n.remotePeer,s),e.abort(s)})}async*findProviders(t,e){e?.onProgress?.(new rt("bitswap:network:find-providers",t));for await(let n of this.routing.findProviders(t,e))await this.libp2p.isDialable(n.multiaddrs,{runOnLimitedConnection:this.runOnLimitedConnections})&&(yield n)}async findAndConnect(t,e){e?.providers!=null&&await Promise.all(e.providers.map(async n=>this.connectTo(n).catch(s=>{this.log.error("could not connect to supplied provider - %e",s)}))),await br(Jn(rs(this.findProviders(t,e),e?.maxProviders??3),async n=>this.connectTo(n.id,e))).catch(n=>{this.log.error(n)})}async sendMessage(t,e,n){if(!this.running)throw new Error("network isn't running");let s=this.sendQueue.queue.find(i=>t.equals(i.options.peerId)&&i.status==="queued");if(s!=null){s.options.message=Ds(s.options.message,e),await s.join({signal:n?.signal});return}await this.sendQueue.add(async i=>{let o=i?.message;if(o==null)throw new pe("No message to send");this.log("sendMessage to %p",t),i?.onProgress?.(new rt("bitswap:network:send-wantlist",t));let a=await this.libp2p.dialProtocol(t,Qt,i);await a.closeRead();try{await Lr(Ns(o,this.maxOutgoingMessageSize),c=>Ce(c),a),await a.close(i)}catch(c){i?.onProgress?.(new rt("bitswap:network:send-wantlist:error",{peer:t,error:c})),this.log.error("error sending message to %p",t,c),a.abort(c)}this._updateSentStats(o.blocks)},{peerId:t,signal:n?.signal,message:e})}async connectTo(t,e){if(!this.running)throw new we("Network isn't running");e?.onProgress?.(new rt("bitswap:network:dial",t));let[n]=await Promise.all([this.libp2p.dial(t,e),Q(this.libp2p,"peer:identify",e?.signal,{filter:s=>{if(!s.detail.peerId.equals(t))return!1;if(s.detail.protocols.includes(Qt))return!0;throw new me(`${t} did not support ${Qt}`)}})]);return n}_updateSentStats(t){let e=0;for(let n of t.values())e+=n.data.byteLength;this.metrics.dataSent?.increment(e),this.metrics.blocksSent?.increment(t.size)}};function S(r,t="utf8"){let e=Re[t];if(e==null)throw new Error(`Unsupported encoding "${t}"`);return e.encoder.encode(r).substring(1)}function We(r,t){let e={[Symbol.iterator]:()=>e,next:()=>{let n=r.next(),s=n.value;return n.done===!0||s==null?{done:!0,value:void 0}:{done:!1,value:t(s)}}};return e}var ne=class{map;constructor(t){if(this.map=new Map,t!=null)for(let[e,n]of t.entries())this.map.set(e.toString(),{key:e,value:n})}[Symbol.iterator](){return this.entries()}clear(){this.map.clear()}delete(t){return this.map.delete(t.toString())}entries(){return We(this.map.entries(),t=>[t[1].key,t[1].value])}forEach(t){this.map.forEach((e,n)=>{t(e.value,e.key,this)})}get(t){return this.map.get(t.toString())?.value}has(t){return this.map.has(t.toString())}set(t,e){this.map.set(t.toString(),{key:t,value:e})}keys(){return We(this.map.values(),t=>t.key)}values(){return We(this.map.values(),t=>t.value)}get size(){return this.map.size}};var fn={32:16777619n,64:1099511628211n,128:309485009821345068724781371n,256:374144419156711147060143317175368453031918731002211n,512:35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759n,1024:5016456510113118655434598811035278955030765345404790744303017523831112055108147451509157692220295382716162651878526895249385292291816524375083746691371804094271873160484737966720260389217684476157468082573n},Cs={32:2166136261n,64:14695981039346656037n,128:144066263297769815596495629667062367629n,256:100029257958052580907070968620625704837092796014241193945225284501741471925557n,512:9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785n,1024:14197795064947621068722070641403218320880622795441933960878474914617582723252296732303717722150864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915n},Fs=new globalThis.TextEncoder;function _a(r,t){let e=fn[t],n=Cs[t];for(let s=0;s<r.length;s++)n^=BigInt(r[s]),n=BigInt.asUintN(t,n*e);return n}function Sa(r,t,e){if(e.length===0)throw new Error("The `utf8Buffer` option must have a length greater than zero");let n=fn[t],s=Cs[t],i=r;for(;i.length>0;){let o=Fs.encodeInto(i,e);i=i.slice(o.read);for(let a=0;a<o.written;a++)s^=BigInt(e[a]),s=BigInt.asUintN(t,s*n)}return s}function dn(r,{size:t=32,utf8Buffer:e}={}){if(!fn[t])throw new Error("The `size` option must be one of 32, 64, 128, 256, 512, or 1024");if(typeof r=="string"){if(e)return Sa(r,t,e);r=Fs.encode(r)}return _a(r,t)}var se={hash:r=>Number(dn(r,{size:32})),hashV:(r,t)=>ka(se.hash(r,t))};function ka(r){let t=r.toString(16);return t.length%2===1&&(t=`0${t}`),U(t,"base16")}var pn=64,Z=class{fp;h;seed;constructor(t,e,n,s=2){if(s>pn)throw new TypeError("Invalid Fingerprint Size");let i=e.hashV(t,n),o=N(s);for(let a=0;a<o.length;a++)o[a]=i[a];o.length===0&&(o[0]=7),this.fp=o,this.h=e,this.seed=n}hash(){return this.h.hash(this.fp,this.seed)}equals(t){return t?.fp instanceof Uint8Array?K(this.fp,t.fp):!1}};function vt(r,t){return Math.floor(Math.random()*(t-r))+r}var Et=class{contents;constructor(t){this.contents=new Array(t).fill(null)}has(t){if(!(t instanceof Z))throw new TypeError("Invalid Fingerprint");return this.contents.some(e=>t.equals(e))}add(t){if(!(t instanceof Z))throw new TypeError("Invalid Fingerprint");for(let e=0;e<this.contents.length;e++)if(this.contents[e]==null)return this.contents[e]=t,!0;return!0}swap(t){if(!(t instanceof Z))throw new TypeError("Invalid Fingerprint");let e=vt(0,this.contents.length-1),n=this.contents[e];return this.contents[e]=t,n}remove(t){if(!(t instanceof Z))throw new TypeError("Invalid Fingerprint");let e=this.contents.findIndex(n=>t.equals(n));return e>-1?(this.contents[e]=null,!0):!1}};var Ia=500,ie=class{bucketSize;filterSize;fingerprintSize;buckets;count;hash;seed;constructor(t){this.filterSize=t.filterSize,this.bucketSize=t.bucketSize??4,this.fingerprintSize=t.fingerprintSize??2,this.count=0,this.buckets=[],this.hash=t.hash??se,this.seed=t.seed??vt(0,Math.pow(2,10))}add(t){typeof t=="string"&&(t=U(t));let e=new Z(t,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(t,this.seed)%this.filterSize,s=(n^e.hash())%this.filterSize;if(this.buckets[n]==null&&(this.buckets[n]=new Et(this.bucketSize)),this.buckets[s]==null&&(this.buckets[s]=new Et(this.bucketSize)),this.buckets[n].add(e)||this.buckets[s].add(e))return this.count++,!0;let i=[n,s],o=i[vt(0,i.length-1)];this.buckets[o]==null&&(this.buckets[o]=new Et(this.bucketSize));for(let a=0;a<Ia;a++){let c=this.buckets[o].swap(e);if(c!=null&&(o=(o^c.hash())%this.filterSize,this.buckets[o]==null&&(this.buckets[o]=new Et(this.bucketSize)),this.buckets[o].add(c)))return this.count++,!0}return!1}has(t){typeof t=="string"&&(t=U(t));let e=new Z(t,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(t,this.seed)%this.filterSize,s=this.buckets[n]?.has(e)??!1;if(s)return s;let i=(n^e.hash())%this.filterSize;return this.buckets[i]?.has(e)??!1}remove(t){typeof t=="string"&&(t=U(t));let e=new Z(t,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(t,this.seed)%this.filterSize,s=this.buckets[n]?.remove(e)??!1;if(s)return this.count--,s;let i=(n^e.hash())%this.filterSize,o=this.buckets[i]?.remove(e)??!1;return o&&this.count--,o}get reliable(){return Math.floor(100*(this.count/this.filterSize))<=90}},Aa={1:.5,2:.84,4:.95,8:.98};function La(r=.001){return r>.002?2:r>1e-5?4:8}function Ms(r,t=.001){let e=La(t),n=Aa[e],s=Math.round(r/n),i=Math.min(Math.ceil(Math.log2(1/t)+Math.log2(2*e)),pn);return{filterSize:s,bucketSize:e,fingerprintSize:i}}var Ge=class{filterSize;bucketSize;fingerprintSize;scale;filterSeries;hash;seed;constructor(t){this.bucketSize=t.bucketSize??4,this.filterSize=t.filterSize??(1<<18)/this.bucketSize,this.fingerprintSize=t.fingerprintSize??2,this.scale=t.scale??2,this.hash=t.hash??se,this.seed=t.seed??vt(0,Math.pow(2,10)),this.filterSeries=[new ie({filterSize:this.filterSize,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed})]}add(t){if(typeof t=="string"&&(t=U(t)),this.has(t))return!0;let e=this.filterSeries.find(n=>n.reliable);if(e==null){let n=this.filterSize*Math.pow(this.scale,this.filterSeries.length);e=new ie({filterSize:n,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed}),this.filterSeries.push(e)}return e.add(t)}has(t){typeof t=="string"&&(t=U(t));for(let e=0;e<this.filterSeries.length;e++)if(this.filterSeries[e].has(t))return!0;return!1}remove(t){typeof t=="string"&&(t=U(t));for(let e=0;e<this.filterSeries.length;e++)if(this.filterSeries[e].remove(t))return!0;return!1}get count(){return this.filterSeries.reduce((t,e)=>t+e.count,0)}};function mn(r,t=.001,e){return new Ge({...Ms(r,t),...e??{}})}var gn=class extends ne{metric;constructor(t){super();let{name:e,metrics:n}=t;this.metric=n.registerMetric(e),this.updateComponentMetric()}set(t,e){return super.set(t,e),this.updateComponentMetric(),this}delete(t){let e=super.delete(t);return this.updateComponentMetric(),e}clear(){super.clear(),this.updateComponentMetric()}updateComponentMetric(){this.metric.update(this.size)}};function oe(r){let{name:t,metrics:e}=r,n;return e!=null?n=new gn({name:t,metrics:e}):n=new ne,n}var at=class{full;pendingBytes;wantlist;blocks;blockPresences;constructor(t=!1,e=0){this.full=t,this.wantlist=new Map,this.blocks=new Map,this.blockPresences=new Map,this.pendingBytes=0}addWantlistEntry(t,e){let n=ot.encode(t.multihash.bytes);this.wantlist.set(n,e)}addBlockPresence(t,e){let n=ot.encode(t.multihash.bytes);this.blockPresences.set(n,e)}addBlock(t,e){let n=ot.encode(t.multihash.bytes);this.blocks.set(n,e)}};function Ta(r){let t=new Uint8Array(r.reduce((n,s)=>n+_(s),0)),e=0;for(let n of r)t=et(n,t,e),e+=_(n);return t}var Us=Ta;function wn(r){return Us([r.version,r.code,r.multihash.code,r.multihash.digest.byteLength])}var Xe=class{peerId;blockstore;network;wants;exchangeCount;bytesSent;bytesReceived;lastExchange;maxSizeReplaceHasWithBlock;log;constructor(t,e){this.peerId=t.peerId,this.blockstore=t.blockstore,this.network=t.network,this.wants=new Map,this.log=t.logger.forComponent(`helia:bitswap:ledger:${t.peerId}`),this.exchangeCount=0,this.bytesSent=0,this.bytesReceived=0,this.maxSizeReplaceHasWithBlock=e.maxSizeReplaceHasWithBlock??1024}sentBytes(t){this.exchangeCount++,this.lastExchange=new Date().getTime(),this.bytesSent+=t}receivedBytes(t){this.exchangeCount++,this.lastExchange=new Date().getTime(),this.bytesReceived+=t}debtRatio(){return this.bytesSent/(this.bytesReceived+1)}async sendBlocksToPeer(t){let e=new at,n=new Set;for(let[s,i]of this.wants.entries())try{let o=await this.blockstore.get(i.cid,t);i.wantType===A.WantHave?o.byteLength<this.maxSizeReplaceHasWithBlock?(this.log("sending have and block for %c",i.cid),n.add(s),e.addBlock(i.cid,{data:o,prefix:wn(i.cid)})):(this.log("sending have for %c",i.cid),e.addBlockPresence(i.cid,{cid:i.cid.bytes,type:W.HaveBlock})):(this.log("sending block for %c",i.cid),n.add(s),e.addBlock(i.cid,{data:o,prefix:wn(i.cid)}))}catch(o){if(o.name!=="NotFoundError")throw o;if(this.log("do not have block for %c",i.cid),!i.sendDontHave||i.sentDoNotHave===!0)continue;i.sentDoNotHave=!0,e.addBlockPresence(i.cid,{cid:i.cid.bytes,type:W.DoNotHaveBlock})}if(e.blocks.size>0||e.blockPresences.size>0){this.log("sending message"),await this.network.sendMessage(this.peerId,e,t),this.log("sent message"),this.sentBytes([...e.blocks.values()].reduce((s,i)=>s+i.data.byteLength,0));for(let s of n)this.wants.delete(s)}}};var Qe=class{blockstore;network;ledgerMap;maxSizeReplaceHasWithBlock;log;logger;constructor(t,e={}){this.blockstore=t.blockstore,this.network=t.network,this.maxSizeReplaceHasWithBlock=e.maxSizeReplaceHasWithBlock,this.log=t.logger.forComponent("helia:bitswap:peer-want-lists"),this.logger=t.logger,this.ledgerMap=oe({name:"helia_bitswap_ledger_map",metrics:t.metrics}),this.network.addEventListener("bitswap:message",n=>{this.receiveMessage(n.detail.peer,n.detail.message).catch(s=>{this.log.error("error receiving bitswap message from %p",n.detail.peer,s)})}),this.network.addEventListener("peer:disconnected",n=>{this.peerDisconnected(n.detail)})}ledgerForPeer(t){let e=this.ledgerMap.get(t);if(e!=null)return{peer:e.peerId,value:e.debtRatio(),sent:e.bytesSent,received:e.bytesReceived,exchanged:e.exchangeCount}}wantListForPeer(t){let e=this.ledgerMap.get(t);if(e!=null)return[...e.wants.values()]}peers(){return Array.from(this.ledgerMap.values()).map(t=>t.peerId)}async receiveMessage(t,e){let n=this.ledgerMap.get(t);if(n==null&&(n=new Xe({peerId:t,blockstore:this.blockstore,network:this.network,logger:this.logger},{maxSizeReplaceHasWithBlock:this.maxSizeReplaceHasWithBlock}),this.ledgerMap.set(t,n)),n.receivedBytes(e.blocks?.reduce((s,i)=>s+i.data.byteLength,0)??0),e.wantlist!=null){e.wantlist.full===!0&&n.wants.clear();for(let s of e.wantlist.entries){let i=q.decode(s.cid),o=S(i.multihash.bytes,"base64");s.cancel===!0?(this.log("peer %p cancelled want of block for %c",t,i),n.wants.delete(o)):(s.wantType===A.WantHave?this.log("peer %p wanted block presence for %c",t,i):this.log("peer %p wanted block for %c",t,i),n.wants.set(o,{cid:i,priority:s.priority,wantType:s.wantType??A.WantBlock,sendDontHave:s.sendDontHave??!1}))}}this.log("send blocks to peer"),await n.sendBlocksToPeer()}async receivedBlock(t,e){let n=S(t.multihash.bytes,"base64"),s=[];for(let i of this.ledgerMap.values())i.wants.has(n)&&s.push(i);await Promise.all(s.map(async i=>i.sendBlocksToPeer(e)))}peerDisconnected(t){this.ledgerMap.delete(t)}};var Na=Wn(Bs(),1);var Bt;(function(r){r[r.A=1]="A",r[r.CNAME=5]="CNAME",r[r.TXT=16]="TXT",r[r.AAAA=28]="AAAA"})(Bt||(Bt={}));var je=class extends Error{static name="InsufficientProvidersError";constructor(t="Insufficient providers found"){super(t),this.name="InsufficientProvidersError"}};var _t=class extends tt{initialPeerSearchComplete;requests;name;log;logger;minProviders;maxProviders;providers;evictionFilter;initialProviders;constructor(t,e){super(),this.name=e.name,this.logger=t.logger,this.log=t.logger.forComponent(this.name),this.requests=new Map,this.minProviders=e.minProviders??1,this.maxProviders=e.maxProviders??5,this.providers=[],this.evictionFilter=mn(this.maxProviders),this.initialProviders=e.providers??[]}async retrieve(t,e={}){let n=ot.encode(t.multihash.bytes),s=this.requests.get(n);if(s!=null)return this.log("join existing request for %c",t),s;let i=D();if(this.requests.set(n,i.promise),this.providers.length===0){let u=!1;this.initialPeerSearchComplete==null&&(u=!0,this.log=this.logger.forComponent(`${this.name}:${t}`),this.initialPeerSearchComplete=this.findProviders(t,this.minProviders,e)),await this.initialPeerSearchComplete,u&&this.log("found initial session peers for %c",t)}let o=!1,a=new It({concurrency:this.maxProviders});a.addEventListener("error",()=>{}),a.addEventListener("failure",u=>{this.log.error("error querying provider %o, evicting from session",u.detail.job.options.provider,u.detail.error),this.evict(u.detail.job.options.provider)}),a.addEventListener("success",u=>{o=!0,i.resolve(u.detail.result)}),a.addEventListener("idle",()=>{if(o||e.signal?.aborted===!0){this.log.trace("session idle, found block");return}Promise.resolve().then(async()=>{this.log("no session peers had block for for %c, finding new providers",t);for(let u=0;u<this.minProviders&&this.providers.length!==0;u++){let h=this.providers[Math.floor(Math.random()*this.providers.length)];this.evict(h)}await this.findProviders(t,this.minProviders,e),this.log("found new providers re-retrieving %c",t),this.requests.delete(n),i.resolve(await this.retrieve(t,e))}).catch(u=>{this.log.error("could not find new providers for %c",t,u),i.reject(u)})});let c=u=>{a.add(async()=>this.queryProvider(t,u.detail,e),{provider:u.detail}).catch(h=>{e.signal?.aborted!==!0&&this.log.error("error retrieving session block for %c",t,h)})};this.addEventListener("provider",c),Promise.all([...this.providers].map(async u=>a.add(async()=>this.queryProvider(t,u,e),{provider:u}))).catch(u=>{e.signal?.aborted!==!0&&this.log.error("error retrieving session block for %c",t,u)});let l=()=>{i.reject(new X(e.signal?.reason??"Session aborted")),a.abort()};e.signal?.addEventListener("abort",l);try{return await i.promise}finally{this.removeEventListener("provider",c),e.signal?.removeEventListener("abort",l),a.clear(),this.requests.delete(n)}}evict(t){this.evictionFilter.add(this.toEvictionKey(t));let e=this.providers.findIndex(n=>this.equals(n,t));e!==-1&&this.providers.splice(e,1)}isEvicted(t){return this.evictionFilter.has(this.toEvictionKey(t))}hasProvider(t){return!!(this.providers.find(e=>this.equals(e,t))!=null||this.isEvicted(t))}async findProviders(t,e,n){let s=D(),i=0;return Promise.resolve().then(async()=>{if(this.log("finding %d-%d new provider(s) for %c",e,this.maxProviders,t),this.initialProviders.length>0)for(;i<e&&this.initialProviders.length>0;){let o=this.initialProviders.pop();if(o==null)break;let a=await this.convertToProvider(o,n);if(n.signal?.aborted===!0)break;if(a!=null&&!this.hasProvider(a)&&(this.log("found %d/%d new providers",i,this.maxProviders),this.providers.push(a),this.safeDispatchEvent("provider",{detail:a}),i++,i===e&&(this.log("session is ready"),s.resolve()),this.providers.length===this.maxProviders)){this.log("found max session peers",i);break}}if(i<this.maxProviders)for await(let o of this.findNewProviders(t,n)){if(i===this.maxProviders||n.signal?.aborted===!0)break;if(!this.hasProvider(o)&&(this.log("found %d/%d new providers",i,this.maxProviders),this.providers.push(o),this.safeDispatchEvent("provider",{detail:o}),i++,i===e&&(this.log("session is ready"),s.resolve()),this.providers.length===this.maxProviders)){this.log("found max session peers",i);break}}if(this.log("found %d/%d new session peers",i,this.maxProviders),i<e)throw new je(`Found ${i} of ${e} ${this.name} providers for ${t}`)}).catch(o=>{this.log.error("error searching routing for potential session peers for %c",t,o.errors??o),s.reject(o)}),s.promise}};var bn=class extends _t{wantList;network;libp2p;constructor(t,e){super(t,{...e,name:"helia:bitswap:session"}),this.wantList=t.wantList,this.network=t.network,this.libp2p=t.libp2p}async queryProvider(t,e,n){this.log("sending WANT-BLOCK for %c to %p",t,e);let s=await this.wantList.wantSessionBlock(t,e,n);if(this.log("%p %s %c",e,s.has?"has":"does not have",t),s.has&&s.block!=null)return s.block;throw new Error("Provider did not have block")}async*findNewProviders(t,e={}){for await(let n of this.network.findProviders(t,e))yield n.id}toEvictionKey(t){return t.toMultihash().bytes}equals(t,e){return t.equals(e)}async convertToProvider(t,e){return de(t)?t:(await this.libp2p.dial(t,e)).remotePeer}};function zs(r,t){return new bn(r,t)}var Ke=class{blocksReceived;duplicateBlocksReceived;dataReceived;duplicateDataReceived;constructor(t){this.blocksReceived=t.metrics?.registerMetricGroup("helia_bitswap_received_blocks"),this.duplicateBlocksReceived=t.metrics?.registerMetricGroup("helia_bitswap_duplicate_received_blocks"),this.dataReceived=t.metrics?.registerMetricGroup("helia_bitswap_data_received_bytes"),this.duplicateDataReceived=t.metrics?.registerMetricGroup("helia_bitswap_duplicate_data_received_bytes")}updateBlocksReceived(t=1,e){let n={global:t};e!=null&&(n[e.toString()]=t),this.blocksReceived?.increment(n)}updateDuplicateBlocksReceived(t=1,e){let n={global:t};e!=null&&(n[e.toString()]=t),this.duplicateBlocksReceived?.increment(n)}updateDataReceived(t,e){let n={global:t};e!=null&&(n[e.toString()]=t),this.dataReceived?.increment(n)}updateDuplicateDataReceived(t,e){let n={global:t};e!=null&&(n[e.toString()]=t),this.duplicateDataReceived?.increment(n)}};var yn=class extends Map{metric;constructor(t){super();let{name:e,metrics:n}=t;this.metric=n.registerMetric(e),this.updateComponentMetric()}set(t,e){return super.set(t,e),this.updateComponentMetric(),this}delete(t){let e=super.delete(t);return this.updateComponentMetric(),e}clear(){super.clear(),this.updateComponentMetric()}updateComponentMetric(){this.metric.update(this.size)}};function Os(r){let{name:t,metrics:e}=r,n;return e!=null?n=new yn({name:t,metrics:e}):n=new Map,n}function Ma(r){if(!(r instanceof Uint8Array))throw new Error("arg needs to be a Uint8Array");let t=[];for(;r.length>0;){let e=j(r);t.push(e),r=r.slice(_(e))}return t}var $s=Ma;var Je=class extends tt{peers;wants;network;log;sendMessagesDelay;sendMessagesTimeout;hashLoader;sendingMessages;constructor(t,e={}){super(),this.peers=oe({name:"helia_bitswap_peers",metrics:t.metrics}),this.wants=Os({name:"helia_bitswap_wantlist",metrics:t.metrics}),this.network=t.network,this.sendMessagesDelay=e.sendMessagesDelay??10,this.log=t.logger.forComponent("helia:bitswap:wantlist"),this.hashLoader=e.hashLoader,this.network.addEventListener("bitswap:message",n=>{this.receiveMessage(n.detail.peer,n.detail.message).catch(s=>{this.log.error("error receiving bitswap message from %p",n.detail.peer,s)})}),this.network.addEventListener("peer:connected",n=>{this.peerConnected(n.detail).catch(s=>{this.log.error("error processing newly connected bitswap peer %p",n.detail,s)})}),this.network.addEventListener("peer:disconnected",n=>{this.peerDisconnected(n.detail)})}async addEntry(t,e){let n=S(t.multihash.bytes,"base64"),s=this.wants.get(n);s==null&&(s={cid:t,priority:e.priority??1,wantType:e.wantType??A.WantBlock,cancel:!1,sendDontHave:!0},this.wants.set(n,s)),s.wantType===A.WantHave&&e.wantType===A.WantBlock&&(s.wantType=A.WantBlock),await this.sendMessagesDebounced();try{return e.wantType===A.WantBlock?(await Q(this,"block",e?.signal,{filter:a=>K(t.multihash.digest,a.detail.cid.multihash.digest),errorMessage:"Want was aborted"})).detail:(await Q(this,"presence",e?.signal,{filter:o=>K(t.multihash.digest,o.detail.cid.multihash.digest),errorMessage:"Want was aborted"})).detail}finally{e.signal?.aborted===!0&&(this.log("want for %c was aborted, cancelling want",t),s.cancel=!0,await this.sendMessagesDebounced())}}async sendMessagesDebounced(){await this.sendingMessages?.promise,clearTimeout(this.sendMessagesTimeout),this.sendMessagesTimeout=setTimeout(()=>{this.sendMessages().catch(t=>{this.log("error sending messages to peers",t)})},this.sendMessagesDelay)}async sendMessages(){this.sendingMessages=D(),await Promise.all([...this.peers.entries()].map(async([t,e])=>{let n=new Set,s=new at;for(let[i,o]of this.wants.entries())e.has(i)||o.cancel||(n.add(i),s.addWantlistEntry(o.cid,{cid:o.cid.bytes,priority:o.priority,wantType:o.wantType,cancel:o.cancel,sendDontHave:o.sendDontHave}));if(s.wantlist.size!==0)try{await this.network.sendMessage(t,s);for(let i of n)e.add(i)}catch(i){this.log.error("error sending full wantlist to new peer",i)}})).catch(t=>{this.log.error("error sending messages",t)});for(let[t,e]of this.wants)if(e.cancel){this.wants.delete(t);for(let n of this.peers.values())n.delete(t)}this.sendingMessages.resolve()}has(t){let e=S(t.multihash.bytes,"base64");return this.wants.has(e)}async wantSessionPresence(t,e,n={}){let s=new at;return s.addWantlistEntry(t,{cid:t.bytes,sendDontHave:!0,wantType:A.WantHave,priority:1}),await this.network.sendMessage(e,s),(await Q(this,"presence",n.signal,{filter:o=>e.equals(o.detail.sender)&&K(t.multihash.digest,o.detail.cid.multihash.digest)})).detail}async wantBlock(t,e={}){return this.addEntry(t,{...e,wantType:A.WantBlock})}async wantSessionBlock(t,e,n={}){let s=new at;return s.addWantlistEntry(t,{cid:t.bytes,sendDontHave:!0,wantType:A.WantBlock,priority:1}),await this.network.sendMessage(e,s),(await Q(this,"presence",n.signal,{filter:o=>e.equals(o.detail.sender)&&K(t.multihash.digest,o.detail.cid.multihash.digest)})).detail}async receivedBlock(t,e){let n=S(t.multihash.bytes,"base64"),s=this.wants.get(n);s!=null&&(s.cancel=!0,await this.sendMessagesDebounced())}async receiveMessage(t,e){this.log("received message from %p with %d blocks",t,e.blocks.length);let n=!1;for(let s of e.blocks){if(s.prefix==null||s.data==null)continue;let i=$s(s.prefix),o=i[0],a=i[1],c=i[2],l=c===Ue.code?Ue:await this.hashLoader?.getHasher(c);if(l==null){this.log.error("unknown hash algorithm",c);continue}let u=l.digest(s.data);u.then!=null&&(u=await u);let h=q.create(o===0?0:1,a,u);this.log("received block from %p for %c",t,h),this.safeDispatchEvent("block",{detail:{sender:t,cid:h,block:s.data}}),this.safeDispatchEvent("presence",{detail:{sender:t,cid:h,has:!0,block:s.data}});let f=S(h.multihash.bytes,"base64"),m=this.wants.get(f);m!=null&&(m.cancel=!0,n=!0)}for(let{cid:s,type:i}of e.blockPresences){let o=q.decode(s);this.log("received %s from %p for %c",i,t,o),this.safeDispatchEvent("presence",{detail:{sender:t,cid:o,has:i===W.HaveBlock}})}n&&await this.sendMessagesDebounced()}async peerConnected(t){let e=new Set,n=new at(!0);for(let[s,i]of this.wants.entries())i.cancel||(e.add(s),n.addWantlistEntry(i.cid,{cid:i.cid.bytes,priority:1,wantType:A.WantBlock,cancel:!1,sendDontHave:!1}));if(n.wantlist.size===0){this.peers.set(t,e);return}try{await this.network.sendMessage(t,n),this.peers.set(t,e)}catch(s){this.log.error("error sending full wantlist to new peer %p",t,s)}}peerDisconnected(t){this.peers.delete(t)}start(){}stop(){this.peers.clear(),clearTimeout(this.sendMessagesTimeout)}};var Ze=class{log;logger;stats;network;blockstore;peerWantLists;wantList;libp2p;constructor(t,e={}){this.logger=t.logger,this.log=t.logger.forComponent("helia:bitswap"),this.blockstore=t.blockstore,this.libp2p=t.libp2p,this.stats=new Ke(t),this.network=new Ve(t,e),this.peerWantLists=new Qe({...t,network:this.network},e),this.wantList=new Je({...t,network:this.network},e)}createSession(t={}){return zs({wantList:this.wantList,network:this.network,logger:this.logger,libp2p:this.libp2p},t)}async want(t,e={}){let n=new AbortController,s=Gn([n.signal,e.signal]);n.signal,this.network.findAndConnect(t,{...e,signal:s}).catch(i=>{n.signal.aborted||this.log.error("error during finding and connect for cid %c",t,i)});try{return(await this.wantList.wantBlock(t,{...e,signal:s})).block}finally{n.abort(),s.clear()}}async notify(t,e,n={}){await Promise.all([this.peerWantLists.receivedBlock(t,n),this.wantList.receivedBlock(t,n)])}getWantlist(){return[...this.wantList.wants.values()].filter(t=>!t.cancel).map(t=>({cid:t.cid,priority:t.priority,wantType:t.wantType}))}getPeerWantlist(t){return this.peerWantLists.wantListForPeer(t)}async start(){this.wantList.start(),await this.network.start()}async stop(){this.wantList.stop(),await this.network.stop()}};var qs=(r,t={})=>new Ze(r,t);var xn=class{bitswap;started;constructor(t,e={}){let{getHasher:n}=t;this.bitswap=qs(t,{hashLoader:{getHasher:async s=>n(s)},...e}),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(t,e,n){await this.bitswap.notify(t,e,n)}async retrieve(t,e={}){return this.bitswap.want(t,e)}createSession(t){let e=this.bitswap.createSession(t);return{announce:async(n,s,i)=>{await this.bitswap.notify(n,s,i)},retrieve:async(n,s)=>e.retrieve(n,s)}}};function Hs(r={}){return t=>new xn(t,r)}var Ye=class{index=0;input="";new(t){return this.index=0,this.input=t,this}readAtomically(t){let e=this.index,n=t();return n===void 0&&(this.index=e),n}parseWith(t){let e=t();if(this.index===this.input.length)return e}peekChar(){if(!(this.index>=this.input.length))return this.input[this.index]}readChar(){if(!(this.index>=this.input.length))return this.input[this.index++]}readGivenChar(t){return this.readAtomically(()=>{let e=this.readChar();if(e===t)return e})}readSeparator(t,e,n){return this.readAtomically(()=>{if(!(e>0&&this.readGivenChar(t)===void 0))return n()})}readNumber(t,e,n,s){return this.readAtomically(()=>{let i=0,o=0,a=this.peekChar();if(a===void 0)return;let c=a==="0",l=2**(8*s)-1;for(;;){let u=this.readAtomically(()=>{let h=this.readChar();if(h===void 0)return;let f=Number.parseInt(h,t);if(!Number.isNaN(f))return f});if(u===void 0)break;if(i*=t,i+=u,i>l||(o+=1,e!==void 0&&o>e))return}if(o!==0)return!n&&c&&o>1?void 0:i})}readIPv4Addr(){return this.readAtomically(()=>{let t=new Uint8Array(4);for(let e=0;e<t.length;e++){let n=this.readSeparator(".",e,()=>this.readNumber(10,3,!1,1));if(n===void 0)return;t[e]=n}return t})}readIPv6Addr(){let t=e=>{for(let n=0;n<e.length/2;n++){let s=n*2;if(n<e.length-3){let o=this.readSeparator(":",n,()=>this.readIPv4Addr());if(o!==void 0)return e[s]=o[0],e[s+1]=o[1],e[s+2]=o[2],e[s+3]=o[3],[s+4,!0]}let i=this.readSeparator(":",n,()=>this.readNumber(16,4,!0,2));if(i===void 0)return[s,!1];e[s]=i>>8,e[s+1]=i&255}return[e.length,!1]};return this.readAtomically(()=>{let e=new Uint8Array(16),[n,s]=t(e);if(n===16)return e;if(s||this.readGivenChar(":")===void 0||this.readGivenChar(":")===void 0)return;let i=new Uint8Array(14),o=16-(n+2),[a]=t(i.subarray(0,o));return e.set(i.subarray(0,a),16-a),e})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};var Vs=45,Ua=15,zt=new Ye;function vn(r){if(!(r.length>Ua))return zt.new(r).parseWith(()=>zt.readIPv4Addr())}function En(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>Vs))return zt.new(r).parseWith(()=>zt.readIPv6Addr())}function tr(r,t=!1){if(r.includes("%")&&(r=r.split("%")[0]),r.length>Vs)return;let e=zt.new(r).parseWith(()=>zt.readIPAddr());if(e)return t&&e.length===4?Uint8Array.from([0,0,0,0,0,0,0,0,0,0,255,255,e[0],e[1],e[2],e[3]]):e}var tp=parseInt("0xFFFF",16),ep=new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);function Ot(r){return!!vn(r)}function $t(r){return!!En(r)}function er(r){return!!tr(r)}var Xs=Ot,$a=$t,_n=function(r){let t=0;if(r=r.toString().trim(),Xs(r)){let e=new Uint8Array(t+4);return r.split(/\./g).forEach(n=>{e[t++]=parseInt(n,10)&255}),e}if($a(r)){let e=r.split(":",8),n;for(n=0;n<e.length;n++){let i=Xs(e[n]),o;i&&(o=_n(e[n]),e[n]=S(o.slice(0,2),"base16")),o!=null&&++n<8&&e.splice(n,0,S(o.slice(2,4),"base16"))}if(e[0]==="")for(;e.length<8;)e.unshift("0");else if(e[e.length-1]==="")for(;e.length<8;)e.push("0");else if(e.length<8){for(n=0;n<e.length&&e[n]!=="";n++);let i=[n,1];for(n=9-e.length;n>0;n--)i.push("0");e.splice.apply(e,i)}let s=new Uint8Array(t+16);for(n=0;n<e.length;n++){let i=parseInt(e[n],16);s[t++]=i>>8&255,s[t++]=i&255}return s}throw new Error("invalid ip address")},Qs=function(r,t=0,e){t=~~t,e=e??r.length-t;let n=new DataView(r.buffer);if(e===4){let s=[];for(let i=0;i<e;i++)s.push(r[t+i]);return s.join(".")}if(e===16){let s=[];for(let i=0;i<e;i+=2)s.push(n.getUint16(t+i).toString(16));return s.join(":").replace(/(^|:)0(:0)*:0(:|$)/,"$1::$3").replace(/:{3,4}/,"::")}return""};var qt={},Sn={},Ha=[[4,32,"ip4"],[6,16,"tcp"],[33,16,"dccp"],[41,128,"ip6"],[42,-1,"ip6zone"],[43,8,"ipcidr"],[53,-1,"dns",!0],[54,-1,"dns4",!0],[55,-1,"dns6",!0],[56,-1,"dnsaddr",!0],[132,16,"sctp"],[273,16,"udp"],[275,0,"p2p-webrtc-star"],[276,0,"p2p-webrtc-direct"],[277,0,"p2p-stardust"],[280,0,"webrtc-direct"],[281,0,"webrtc"],[290,0,"p2p-circuit"],[301,0,"udt"],[302,0,"utp"],[400,-1,"unix",!1,!0],[421,-1,"ipfs"],[421,-1,"p2p"],[443,0,"https"],[444,96,"onion"],[445,296,"onion3"],[446,-1,"garlic64"],[448,0,"tls"],[449,-1,"sni"],[460,0,"quic"],[461,0,"quic-v1"],[465,0,"webtransport"],[466,-1,"certhash"],[477,0,"ws"],[478,0,"wss"],[479,0,"p2p-websocket-star"],[480,0,"http"],[481,-1,"http-path"],[777,-1,"memory"]];Ha.forEach(r=>{let t=Va(...r);Sn[t.code]=t,qt[t.name]=t});function Va(r,t,e,n,s){return{code:r,size:t,name:e,resolvable:!!n,path:!!s}}function p(r){if(typeof r=="number"){if(Sn[r]!=null)return Sn[r];throw new Error(`no protocol with code: ${r}`)}else if(typeof r=="string"){if(qt[r]!=null)return qt[r];throw new Error(`no protocol with name: ${r}`)}throw new Error(`invalid protocol id type: ${typeof r}`)}var Bp=p("ip4"),zp=p("ip6"),Op=p("ipcidr");function Ln(r,t){switch(p(r).code){case 4:case 41:return Ga(t);case 42:return An(t);case 43:return S(t,"base10");case 6:case 273:case 33:case 132:return Js(t).toString();case 53:case 54:case 55:case 56:case 400:case 449:case 777:return An(t);case 421:return Ka(t);case 444:return Ks(t);case 445:return Ks(t);case 466:return ja(t);case 481:return globalThis.encodeURIComponent(An(t));default:return S(t,"base16")}}function Tn(r,t){switch(p(r).code){case 4:return js(t);case 41:return js(t);case 42:return In(t);case 43:return U(t,"base10");case 6:case 273:case 33:case 132:return Pn(parseInt(t,10));case 53:case 54:case 55:case 56:case 400:case 449:case 777:return In(t);case 421:return Xa(t);case 444:return Ja(t);case 445:return Za(t);case 466:return Qa(t);case 481:return In(globalThis.decodeURIComponent(t));default:return U(t,"base16")}}var kn=Object.values(te).map(r=>r.decoder),Wa=function(){let r=kn[0].or(kn[1]);return kn.slice(2).forEach(t=>r=r.or(t)),r}();function js(r){if(!er(r))throw new Error("invalid ip address");return _n(r)}function Ga(r){let t=Qs(r,0,r.length);if(t==null)throw new Error("ipBuff is required");if(!er(t))throw new Error("invalid ip address");return t}function Pn(r){let t=new ArrayBuffer(2);return new DataView(t).setUint16(0,r),new Uint8Array(t)}function Js(r){return new DataView(r.buffer).getUint16(r.byteOffset)}function In(r){let t=U(r),e=Uint8Array.from(et(t.length));return V([e,t],e.length+t.length)}function An(r){let t=j(r);if(r=r.slice(_(t)),r.length!==t)throw new Error("inconsistent lengths");return S(r)}function Xa(r){let t;r[0]==="Q"||r[0]==="1"?t=Zt(P.decode(`z${r}`)).bytes:t=q.parse(r).multihash.bytes;let e=Uint8Array.from(et(t.length));return V([e,t],e.length+t.length)}function Qa(r){let t=Wa.decode(r),e=Uint8Array.from(et(t.length));return V([e,t],e.length+t.length)}function ja(r){let t=j(r),e=r.slice(_(t));if(e.length!==t)throw new Error("inconsistent lengths");return"u"+S(e,"base64url")}function Ka(r){let t=j(r),e=r.slice(_(t));if(e.length!==t)throw new Error("inconsistent lengths");return S(e,"base58btc")}function Ja(r){let t=r.split(":");if(t.length!==2)throw new Error(`failed to parse onion addr: ["'${t.join('", "')}'"]' does not contain a port number`);if(t[0].length!==16)throw new Error(`failed to parse onion addr: ${t[0]} not a Tor onion address.`);let e=it.decode("b"+t[0]),n=parseInt(t[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let s=Pn(n);return V([e,s],e.length+s.length)}function Za(r){let t=r.split(":");if(t.length!==2)throw new Error(`failed to parse onion addr: ["'${t.join('", "')}'"]' does not contain a port number`);if(t[0].length!==56)throw new Error(`failed to parse onion addr: ${t[0]} not a Tor onion3 address.`);let e=it.decode(`b${t[0]}`),n=parseInt(t[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let s=Pn(n);return V([e,s],e.length+s.length)}function Ks(r){let t=r.slice(0,r.length-2),e=r.slice(r.length-2),n=S(t,"base32"),s=Js(e);return`${n}:${s}`}function Zs(r){r=Dn(r);let t=[],e=[],n=null,s=r.split("/").slice(1);if(s.length===1&&s[0]==="")return{bytes:new Uint8Array,string:"/",tuples:[],stringTuples:[],path:null};for(let i=0;i<s.length;i++){let o=s[i],a=p(o);if(a.size===0){t.push([a.code]),e.push([a.code]);continue}if(i++,i>=s.length)throw new rr("invalid address: "+r);if(a.path===!0){n=Dn(s.slice(i).join("/")),t.push([a.code,Tn(a.code,n)]),e.push([a.code,n]);break}let c=Tn(a.code,s[i]);t.push([a.code,c]),e.push([a.code,Ln(a.code,c)])}return{string:Ys(e),bytes:nr(t),tuples:t,stringTuples:e,path:n}}function Nn(r){let t=[],e=[],n=null,s=0;for(;s<r.length;){let i=j(r,s),o=_(i),a=p(i),c=Ya(a,r.slice(s+o));if(c===0){t.push([i]),e.push([i]),s+=o;continue}let l=r.slice(s+o,s+o+c);if(s+=c+o,s>r.length)throw new rr("Invalid address Uint8Array: "+S(r,"base16"));t.push([i,l]);let u=Ln(i,l);if(e.push([i,u]),a.path===!0){n=u;break}}return{bytes:Uint8Array.from(r),string:Ys(e),tuples:t,stringTuples:e,path:n}}function Ys(r){let t=[];return r.map(e=>{let n=p(e[0]);return t.push(n.name),e.length>1&&e[1]!=null&&t.push(e[1]),null}),Dn(t.join("/"))}function nr(r){return V(r.map(t=>{let e=p(t[0]),n=Uint8Array.from(et(e.code));return t.length>1&&t[1]!=null&&(n=V([n,t[1]])),n}))}function Ya(r,t){if(r.size>0)return r.size/8;if(r.size===0)return 0;{let e=j(t instanceof Uint8Array?t:Uint8Array.from(t));return e+_(e)}}function Dn(r){return"/"+r.trim().split("/").filter(t=>t).join("/")}var rr=class extends Error{static name="ParseError";name="ParseError";constructor(t){super(`Error parsing address: ${t}`)}};var tc=Symbol.for("nodejs.util.inspect.custom"),Fn=Symbol.for("@multiformats/js-multiaddr/multiaddr"),ec=[p("dns").code,p("dns4").code,p("dns6").code,p("dnsaddr").code],Cn=class extends Error{constructor(t="No available resolver"){super(t),this.name="NoAvailableResolverError"}},sr=class r{bytes;#t;#e;#r;#n;[Fn]=!0;constructor(t){t==null&&(t="");let e;if(t instanceof Uint8Array)e=Nn(t);else if(typeof t=="string"){if(t.length>0&&t.charAt(0)!=="/")throw new Error(`multiaddr "${t}" must start with a "/"`);e=Zs(t)}else if(ei(t))e=Nn(t.bytes);else throw new Error("addr must be a string, Buffer, or another Multiaddr");this.bytes=e.bytes,this.#t=e.string,this.#e=e.tuples,this.#r=e.stringTuples,this.#n=e.path}toString(){return this.#t}toJSON(){return this.toString()}toOptions(){let t,e,n,s,i="",o=p("tcp"),a=p("udp"),c=p("ip4"),l=p("ip6"),u=p("dns6"),h=p("ip6zone");for(let[m,d]of this.stringTuples())m===h.code&&(i=`%${d??""}`),ec.includes(m)&&(e=o.name==="tcp"?"tcp":"udp",s=443,n=`${d??""}${i}`,t=m===u.code?6:4),(m===o.code||m===a.code)&&(e=p(m).name==="tcp"?"tcp":"udp",s=parseInt(d??"")),(m===c.code||m===l.code)&&(e=p(m).name==="tcp"?"tcp":"udp",n=`${d??""}${i}`,t=m===l.code?6:4);if(t==null||e==null||n==null||s==null)throw new Error('multiaddr must have a valid format: "/{ip4, ip6, dns4, dns6, dnsaddr}/{address}/{tcp, udp}/{port}".');return{family:t,host:n,transport:e,port:s}}protos(){return this.#e.map(([t])=>Object.assign({},p(t)))}protoCodes(){return this.#e.map(([t])=>t)}protoNames(){return this.#e.map(([t])=>p(t).name)}tuples(){return this.#e.map(([t,e])=>e==null?[t]:[t,e])}stringTuples(){return this.#r.map(([t,e])=>e==null?[t]:[t,e])}encapsulate(t){return t=new r(t),new r(this.toString()+t.toString())}decapsulate(t){let e=t.toString(),n=this.toString(),s=n.lastIndexOf(e);if(s<0)throw new Error(`Address ${this.toString()} does not contain subaddress: ${t.toString()}`);return new r(n.slice(0,s))}decapsulateCode(t){let e=this.tuples();for(let n=e.length-1;n>=0;n--)if(e[n][0]===t)return new r(nr(e.slice(0,n)));return this}getPeerId(){try{let t=[];this.stringTuples().forEach(([n,s])=>{n===qt.p2p.code&&t.push([n,s]),n===qt["p2p-circuit"].code&&(t=[])});let e=t.pop();if(e?.[1]!=null){let n=e[1];return n[0]==="Q"||n[0]==="1"?S(P.decode(`z${n}`),"base58btc"):S(q.parse(n).multihash.bytes,"base58btc")}return null}catch{return null}}getPath(){return this.#n}equals(t){return K(this.bytes,t.bytes)}async resolve(t){let e=this.protos().find(i=>i.resolvable);if(e==null)return[this];let n=ti.get(e.name);if(n==null)throw new Cn(`no available resolver for ${e.name}`);return(await n(this,t)).map(i=>ae(i))}nodeAddress(){let t=this.toOptions();if(t.transport!=="tcp"&&t.transport!=="udp")throw new Error(`multiaddr must have a valid format - no protocol with name: "${t.transport}". Must have a valid transport protocol: "{tcp, udp}"`);return{family:t.family,address:t.host,port:t.port}}isThinWaistAddress(t){let e=(t??this).protos();return!(e.length!==2||e[0].code!==4&&e[0].code!==41||e[1].code!==6&&e[1].code!==273)}[tc](){return`Multiaddr(${this.#t})`}};var ti=new Map;function ei(r){return!!r?.[Fn]}function ae(r){return new sr(r)}var rc=[p("tcp").code,p("dns").code,p("dnsaddr").code,p("dns4").code,p("dns6").code];function ri(r){return ii("sni",r)?.[1]}function ni(r){let t=ii("tcp",r)?.[1];return t==null?"":`:${t}`}function ii(r,t){let e;try{e=p(r).code}catch{return}for(let[n,s]of t)if(n===e&&s!=null)return[n,s]}function si(r){return r.some(([t,e])=>t===p("tls").code)}function Y(r,t,e){let n=oi[p(r).name];if(n==null)throw new Error(`Can't interpret protocol ${p(r).name}`);let s=n(t,e);return r===p("ip6").code?`[${s}]`:s}var oi={ip4:(r,t)=>r,ip6:(r,t)=>t.length===0?r:`[${r}]`,tcp:(r,t)=>{let e=t.pop();if(e==null)throw new Error("Unexpected end of multiaddr");return`tcp://${Y(e[0],e[1]??"",t)}:${r}`},udp:(r,t)=>{let e=t.pop();if(e==null)throw new Error("Unexpected end of multiaddr");return`udp://${Y(e[0],e[1]??"",t)}:${r}`},dnsaddr:(r,t)=>r,dns4:(r,t)=>r,dns6:(r,t)=>r,dns:(r,t)=>r,ipfs:(r,t)=>{let e=t.pop();if(e==null)throw new Error("Unexpected end of multiaddr");return`${Y(e[0],e[1]??"",t)}`},p2p:(r,t)=>{let e=t.pop();if(e==null)throw new Error("Unexpected end of multiaddr");return`${Y(e[0],e[1]??"",t)}`},http:(r,t)=>{let e=si(t),n=ri(t),s=ni(t);if(e&&n!=null)return`https://${n}${s}`;let i=e?"https://":"http://",o=t.pop();if(o==null)throw new Error("Unexpected end of multiaddr");let a=Y(o[0],o[1]??"",t);return a=a.replace("tcp://",""),`${i}${a}`},"http-path":(r,t)=>{let e=t.pop();if(e==null)throw new Error("Unexpected end of multiaddr");let n=Y(e[0],e[1]??"",t),s=decodeURIComponent(r);return`${n}/${s}`},tls:(r,t)=>{let e=t.pop();if(e==null)throw new Error("Unexpected end of multiaddr");return Y(e[0],e[1]??"",t)},sni:(r,t)=>{let e=t.pop();if(e==null)throw new Error("Unexpected end of multiaddr");return Y(e[0],e[1]??"",t)},https:(r,t)=>{let e=t.pop();if(e==null)throw new Error("Unexpected end of multiaddr");let n=Y(e[0],e[1]??"",t);return n=n.replace("tcp://",""),`https://${n}`},ws:(r,t)=>{let e=si(t),n=ri(t),s=ni(t);if(e&&n!=null)return`wss://${n}${s}`;let i=e?"wss://":"ws://",o=t.pop();if(o==null)throw new Error("Unexpected end of multiaddr");let a=Y(o[0],o[1]??"",t);return a=a.replace("tcp://",""),`${i}${a}`},wss:(r,t)=>{let e=t.pop();if(e==null)throw new Error("Unexpected end of multiaddr");let n=Y(e[0],e[1]??"",t);return n=n.replace("tcp://",""),`wss://${n}`}};function ir(r,t){let n=ae(r).stringTuples(),s=n.pop();if(s==null)throw new Error("Unexpected end of multiaddr");let i=p(s[0]),o=oi[i.name];if(o==null)throw new Error(`No interpreter found for ${i.name}`);let a=o(s[1]??"",n);return t?.assumeHttp!==!1&&rc.includes(s[0])&&(a=a.replace(/^.*:\/\//,""),s[1]==="443"?a=`https://${a}`:a=`http://${a}`),(a.startsWith("http://")||a.startsWith("https://")||a.startsWith("ws://")||a.startsWith("wss://"))&&(a=new URL(a).toString(),a.endsWith("/")&&(a=a.substring(0,a.length-1))),a}var Ht=class{url;#t=0;#e=0;#r=0;#n=0;#s=new Map;log;transformRequestInit;constructor(t,{logger:e,transformRequestInit:n}){this.url=t instanceof URL?t:new URL(t),this.transformRequestInit=n,this.log=e.forComponent(`helia:trustless-gateway-block-broker:${this.url.hostname}`)}#i(t){let e=t.multihash.bytes;return ot.encode(e)}async getRawBlock(t,e){let n=new URL(this.url.toString());if(n.pathname=`/ipfs/${t.toString()}`,n.search="?format=raw",e?.aborted===!0)throw new Error(`Signal to fetch raw block for CID ${t} from gateway ${this.url} was aborted prior to fetch`);let s=this.#i(t),i=new AbortController,o=()=>{i.abort()};e?.addEventListener("abort",o);try{let a=this.#s.get(s);if(a==null){this.#t++;let c={signal:i.signal,headers:{Accept:"application/vnd.ipld.raw"},cache:"force-cache"},l=this.transformRequestInit!=null?await this.transformRequestInit(c):c;a=fetch(n.toString(),l).then(async u=>{if(this.log("GET %s %d",n,u.status),!u.ok)throw this.#e++,new Error(`unable to fetch raw block for CID ${t} from gateway ${this.url}`);return this.#n++,new Uint8Array(await u.arrayBuffer())}),this.#s.set(s,a)}return await a}catch{throw e?.aborted===!0?new Error(`fetching raw block for CID ${t} from gateway ${this.url} was aborted`):(this.#e++,new Error(`unable to fetch raw block for CID ${t}`))}finally{e?.removeEventListener("abort",o),this.#s.delete(s)}}reliability(){return this.#t===0?1:this.#r>0?-1/0:this.#n/(this.#t+this.#e*3)}incrementInvalidBlocks(){this.#r++}getStats(){return{attempts:this.#t,errors:this.#e,invalidBlocks:this.#r,successes:this.#n,pendingResponses:this.#s.size}}};var ci=Wn(ai(),1),nc=["0.0.0.0/8","10.0.0.0/8","100.64.0.0/10","127.0.0.0/8","169.254.0.0/16","172.16.0.0/12","192.0.0.0/24","192.0.0.0/29","192.0.0.8/32","192.0.0.9/32","192.0.0.10/32","192.0.0.170/32","192.0.0.171/32","192.0.2.0/24","192.31.196.0/24","192.52.193.0/24","192.88.99.0/24","192.168.0.0/16","192.175.48.0/24","198.18.0.0/15","198.51.100.0/24","203.0.113.0/24","240.0.0.0/4","255.255.255.255/32"],sc=nc.map(r=>new ci.Netmask(r));function Mn(r){for(let t of sc)if(t.contains(r))return!0;return!1}function ic(r){return/^::ffff:([0-9a-fA-F]{1,4}):([0-9a-fA-F]{1,4})$/.test(r)}function oc(r){let t=r.split(":");if(t.length<2)return!1;let e=t[t.length-1].padStart(4,"0"),n=t[t.length-2].padStart(4,"0"),s=`${parseInt(n.substring(0,2),16)}.${parseInt(n.substring(2),16)}.${parseInt(e.substring(0,2),16)}.${parseInt(e.substring(2),16)}`;return Mn(s)}function ac(r){return/^::ffff:([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)}function cc(r){let t=r.split(":"),e=t[t.length-1];return Mn(e)}function lc(r){return/^::$/.test(r)||/^::1$/.test(r)||/^64:ff9b::([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)||/^100::([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^2001::([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^2001:2[0-9a-fA-F]:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^2001:db8:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^2002:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^f[c-d]([0-9a-fA-F]{2,2}):/i.test(r)||/^fe[8-9a-bA-B][0-9a-fA-F]:/i.test(r)||/^ff([0-9a-fA-F]{2,2}):/i.test(r)}function li(r){return Ot(r)?Mn(r):ic(r)?oc(r):ac(r)?cc(r):$t(r)?lc(r):void 0}var uc=r=>r.toString().split("/").slice(1),Vt=r=>({match:t=>t.length<1?!1:r(t[0])?t.slice(1):!1,pattern:"fn"}),g=r=>({match:t=>Vt(e=>e===r).match(t),pattern:r}),St=()=>({match:r=>Vt(t=>typeof t=="string").match(r),pattern:"{string}"}),Wt=()=>({match:r=>Vt(t=>!isNaN(parseInt(t))).match(r),pattern:"{number}"}),v=()=>({match:r=>{if(r.length<2||r[0]!=="p2p"&&r[0]!=="ipfs")return!1;if(r[1].startsWith("Q")||r[1].startsWith("1"))try{P.decode(`z${r[1]}`)}catch{return!1}else return!1;return r.slice(2)},pattern:"/p2p/{peerid}"}),le=()=>({match:r=>{if(r.length<2||r[0]!=="certhash")return!1;try{Wr.decode(r[1])}catch{return!1}return r.slice(2)},pattern:"/certhash/{certhash}"}),y=r=>({match:t=>{let e=r.match(t);return e===!1?t:e},pattern:`optional(${r.pattern})`}),R=(...r)=>({match:t=>{let e;for(let n of r){let s=n.match(t);s!==!1&&(e==null||s.length<e.length)&&(e=s)}return e??!1},pattern:`or(${r.map(t=>t.pattern).join(", ")})`}),w=(...r)=>({match:t=>{for(let e of r){let n=e.match(t);if(n===!1)return!1;t=n}return t},pattern:`and(${r.map(t=>t.pattern).join(", ")})`});function k(...r){function t(s){let i=uc(s);for(let o of r){let a=o.match(i);if(a===!1)return!1;i=a}return i}function e(s){return t(s)!==!1}function n(s){let i=t(s);return i===!1?!1:i.length===0}return{matchers:r,matches:e,exactMatch:n}}var hc=v(),Sm=k(hc),ar=w(g("dns4"),St()),cr=w(g("dns6"),St()),lr=w(g("dnsaddr"),St()),Rn=w(g("dns"),St()),km=k(ar,y(v())),Im=k(cr,y(v())),Am=k(lr,y(v())),ui=k(R(Rn,lr,ar,cr),y(v())),hi=w(g("ip4"),Vt(Ot)),fi=w(g("ip6"),Vt($t)),Bn=R(hi,fi),ct=R(Bn,Rn,ar,cr,lr),Lm=k(R(Bn,w(R(Rn,lr,ar,cr),y(v())))),Tm=k(hi),Pm=k(fi),Dm=k(Bn),zn=w(ct,g("tcp"),Wt()),ue=w(ct,g("udp"),Wt()),Nm=k(w(zn,y(v()))),Cm=k(ue),On=w(ue,g("quic"),y(v())),ur=w(ue,g("quic-v1"),y(v())),fc=R(On,ur),Fm=k(On),Mm=k(ur),Un=R(ct,zn,ue,On,ur),di=R(w(Un,g("ws"),y(v()))),Um=k(di),pi=R(w(Un,g("wss"),y(v())),w(Un,g("tls"),y(w(g("sni"),St())),g("ws"),y(v()))),Rm=k(pi),mi=w(ue,g("webrtc-direct"),y(le()),y(le()),y(v())),Bm=k(mi),gi=w(ur,g("webtransport"),y(le()),y(le()),y(v())),zm=k(gi),or=R(di,pi,w(zn,y(v())),w(fc,y(v())),w(ct,y(v())),mi,gi,v()),Om=k(or),dc=w(or,g("p2p-circuit"),v()),$m=k(dc),pc=R(w(or,g("p2p-circuit"),g("webrtc"),y(v())),w(or,g("webrtc"),y(v())),w(g("webrtc"),y(v()))),qm=k(pc),mc=R(w(ct,g("tcp"),Wt(),g("http"),y(v())),w(ct,g("http"),y(v()))),wi=k(mc),gc=R(w(ct,g("tcp"),R(w(g("443"),g("http")),w(Wt(),g("https")),w(Wt(),g("tls"),g("http"))),y(v())),w(ct,g("tls"),g("http"),y(v())),w(ct,g("https"),y(v()))),bi=k(gc),wc=R(w(g("memory"),St(),y(v()))),Hm=k(wc);function $n(r,t,e){return r.filter(n=>{if(bi.matches(n)||t&&wi.matches(n))return e||ui.matches(n)?!0:li(n.toOptions().host)===!1;if(!t&&e){let{host:s}=n.toOptions();if(s==="127.0.0.1"||s==="localhost"||s.endsWith(".localhost"))return!0}return!1})}async function*hr(r,t,e,n,s,i={}){for await(let o of t.findProviders(r,i)){let a=$n(o.multiaddrs,n,s);if(a.length===0)continue;let c=ir(a[0]);yield new Ht(c,{logger:e,transformRequestInit:i.transformRequestInit})}}var qn=class extends _t{routing;allowInsecure;allowLocal;transformRequestInit;constructor(t,e){super(t,{...e,name:"helia:trustless-gateway:session"}),this.routing=t.routing,this.allowInsecure=e.allowInsecure??fr,this.allowLocal=e.allowLocal??dr,this.transformRequestInit=e.transformRequestInit}async queryProvider(t,e,n){this.log("fetching BLOCK for %c from %s",t,e.url);let s=await e.getRawBlock(t,n.signal);return this.log.trace("got block for %c from %s",t,e.url),await n.validateFn?.(s),s}async*findNewProviders(t,e={}){yield*hr(t,this.routing,this.logger,this.allowInsecure,this.allowLocal,{...e,transformRequestInit:this.transformRequestInit})}toEvictionKey(t){return t.url.toString()}equals(t,e){return t.url.toString()===e.url.toString()}async convertToProvider(t,e){if(de(t))return;let n=$n(Array.isArray(t)?t:[t],this.allowInsecure,this.allowLocal);if(n.length===0)return;let s=ir(n[0]);return new Ht(s,{logger:this.logger,transformRequestInit:this.transformRequestInit})}};function yi(r,t){return new qn(r,t)}var pr=class{allowInsecure;allowLocal;transformRequestInit;routing;log;logger;constructor(t,e={}){this.log=t.logger.forComponent("helia:trustless-gateway-block-broker"),this.logger=t.logger,this.routing=t.routing,this.allowInsecure=e.allowInsecure??fr,this.allowLocal=e.allowLocal??dr,this.transformRequestInit=e.transformRequestInit}async retrieve(t,e={}){let n=[];for await(let s of hr(t,this.routing,this.logger,this.allowInsecure,this.allowLocal,{...e,transformRequestInit:this.transformRequestInit})){this.log("getting block for %c from %s",t,s.url);try{let i=await s.getRawBlock(t,e.signal);this.log.trace("got block for %c from %s",t,s.url);try{await e.validateFn?.(i)}catch(o){this.log.error("failed to validate block for %c from %s",t,s.url,o);continue}return i}catch(i){if(this.log.error("failed to get block for %c from %s",t,s.url,i),i instanceof Error?n.push(i):n.push(new Error(`Unable to fetch raw block for CID ${t} from gateway ${s.url}`)),e.signal?.aborted===!0){this.log.trace("request aborted while fetching raw block for CID %c from gateway %s",t,s.url);break}}}throw n.length>0?new AggregateError(n,`Unable to fetch raw block for CID ${t} from any gateway`):new Error(`Unable to fetch raw block for CID ${t} from any gateway`)}createSession(t={}){return yi({logger:this.logger,routing:this.routing},{...t,allowLocal:this.allowLocal,allowInsecure:this.allowInsecure,transformRequestInit:this.transformRequestInit})}};var fr=!1,dr=!1;function xi(r={}){return t=>new pr(t,r)}return Ii(bc);})();
2
+ "use strict";var HeliaBlockBrokers=(()=>{var $o=Object.create;var ye=Object.defineProperty;var qo=Object.getOwnPropertyDescriptor;var Vo=Object.getOwnPropertyNames;var Ho=Object.getPrototypeOf,Wo=Object.prototype.hasOwnProperty;var ts=(r,t)=>()=>(t||r((t={exports:{}}).exports,t),t.exports),q=(r,t)=>{for(var e in t)ye(r,e,{get:t[e],enumerable:!0})},es=(r,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of Vo(t))!Wo.call(r,s)&&s!==e&&ye(r,s,{get:()=>t[s],enumerable:!(n=qo(t,s))||n.enumerable});return r};var rs=(r,t,e)=>(e=r!=null?$o(Ho(r)):{},es(t||!r||!r.__esModule?ye(e,"default",{value:r,enumerable:!0}):e,r)),Go=r=>es(ye({},"__esModule",{value:!0}),r);var Ks=ts((Nd,Zs)=>{Zs.exports=function(r){if(!r)throw Error("hashlru must have a max value, of type number, greater than 0");var t=0,e=Object.create(null),n=Object.create(null);function s(o,i){e[o]=i,t++,t>=r&&(t=0,n=e,e=Object.create(null))}return{has:function(o){return e[o]!==void 0||n[o]!==void 0},remove:function(o){e[o]!==void 0&&(e[o]=void 0),n[o]!==void 0&&(n[o]=void 0)},get:function(o){var i=e[o];if(i!==void 0)return i;if((i=n[o])!==void 0)return s(o,i),i},set:function(o,i){e[o]!==void 0?e[o]=i:s(o,i)},clear:function(){e=Object.create(null),n=Object.create(null)}}}});var Io=ts(me=>{(function(){var r,t,e,n,s,o,i,a;a=function(c){var l,u,h,f;return l=(c&255<<24)>>>24,u=(c&255<<16)>>>16,h=(c&65280)>>>8,f=c&255,[l,u,h,f].join(".")},i=function(c){var l,u,h,f,E,d;for(l=[],h=f=0;f<=3&&c.length!==0;h=++f){if(h>0){if(c[0]!==".")throw new Error("Invalid IP");c=c.substring(1)}d=t(c),E=d[0],u=d[1],c=c.substring(u),l.push(E)}if(c.length!==0)throw new Error("Invalid IP");switch(l.length){case 1:if(l[0]>4294967295)throw new Error("Invalid IP");return l[0]>>>0;case 2:if(l[0]>255||l[1]>16777215)throw new Error("Invalid IP");return(l[0]<<24|l[1])>>>0;case 3:if(l[0]>255||l[1]>255||l[2]>65535)throw new Error("Invalid IP");return(l[0]<<24|l[1]<<16|l[2])>>>0;case 4:if(l[0]>255||l[1]>255||l[2]>255||l[3]>255)throw new Error("Invalid IP");return(l[0]<<24|l[1]<<16|l[2]<<8|l[3])>>>0;default:throw new Error("Invalid IP")}},e=function(c){return c.charCodeAt(0)},n=e("0"),o=e("a"),s=e("A"),t=function(c){var l,u,h,f,E;for(f=0,l=10,u="9",h=0,c.length>1&&c[h]==="0"&&(c[h+1]==="x"||c[h+1]==="X"?(h+=2,l=16):"0"<=c[h+1]&&c[h+1]<="9"&&(h++,l=8,u="7")),E=h;h<c.length;){if("0"<=c[h]&&c[h]<=u)f=f*l+(e(c[h])-n)>>>0;else if(l===16)if("a"<=c[h]&&c[h]<="f")f=f*l+(10+e(c[h])-o)>>>0;else if("A"<=c[h]&&c[h]<="F")f=f*l+(10+e(c[h])-s)>>>0;else break;else break;if(f>4294967295)throw new Error("too large");h++}if(h===E)throw new Error("empty octet");return[f,h]},r=function(){function c(l,u){var h,f,E,d;if(typeof l!="string")throw new Error("Missing `net' parameter");if(u||(d=l.split("/",2),l=d[0],u=d[1]),u||(u=32),typeof u=="string"&&u.indexOf(".")>-1){try{this.maskLong=i(u)}catch(x){throw h=x,new Error("Invalid mask: "+u)}for(f=E=32;E>=0;f=--E)if(this.maskLong===4294967295<<32-f>>>0){this.bitmask=f;break}}else if(u||u===0)this.bitmask=parseInt(u,10),this.maskLong=0,this.bitmask>0&&(this.maskLong=4294967295<<32-this.bitmask>>>0);else throw new Error("Invalid mask: empty");try{this.netLong=(i(l)&this.maskLong)>>>0}catch(x){throw h=x,new Error("Invalid net address: "+l)}if(!(this.bitmask<=32))throw new Error("Invalid mask for ip4: "+u);this.size=Math.pow(2,32-this.bitmask),this.base=a(this.netLong),this.mask=a(this.maskLong),this.hostmask=a(~this.maskLong),this.first=this.bitmask<=30?a(this.netLong+1):this.base,this.last=this.bitmask<=30?a(this.netLong+this.size-2):a(this.netLong+this.size-1),this.broadcast=this.bitmask<=30?a(this.netLong+this.size-1):void 0}return c.prototype.contains=function(l){return typeof l=="string"&&(l.indexOf("/")>0||l.split(".").length!==4)&&(l=new c(l)),l instanceof c?this.contains(l.base)&&this.contains(l.broadcast||l.last):(i(l)&this.maskLong)>>>0===(this.netLong&this.maskLong)>>>0},c.prototype.next=function(l){return l==null&&(l=1),new c(a(this.netLong+this.size*l),this.mask)},c.prototype.forEach=function(l){var u,h,f;for(f=i(this.first),h=i(this.last),u=0;f<=h;)l(a(f),f,u),u++,f++},c.prototype.toString=function(){return this.base+"/"+this.bitmask},c}(),me.ip2long=i,me.long2ip=a,me.Netmask=r}).call(me)});var ul={};q(ul,{bitswap:()=>eo,trustlessGateway:()=>zo});var Xo=Symbol.for("@libp2p/peer-id");function xe(r){return!!r?.[Xo]}var Z=class extends Error{static name="AbortError";constructor(t="The operation was aborted"){super(t),this.name="AbortError"}};var Ee=class extends Error{static name="InvalidParametersError";constructor(t="Invalid parameters"){super(t),this.name="InvalidParametersError"}};var _e=class extends Error{static name="UnsupportedProtocolError";constructor(t="Unsupported protocol error"){super(t),this.name="UnsupportedProtocolError"}};var ve=class extends Error{static name="TimeoutError";constructor(t="Timed out"){super(t),this.name="TimeoutError"}},Se=class extends Error{static name="NotStartedError";constructor(t="Not started"){super(t),this.name="NotStartedError"}};var et=class extends EventTarget{#t=new Map;constructor(){super()}listenerCount(t){let e=this.#t.get(t);return e==null?0:e.length}addEventListener(t,e,n){super.addEventListener(t,e,n);let s=this.#t.get(t);s==null&&(s=[],this.#t.set(t,s)),s.push({callback:e,once:(n!==!0&&n!==!1&&n?.once)??!1})}removeEventListener(t,e,n){super.removeEventListener(t.toString(),e??null,n);let s=this.#t.get(t);s!=null&&(s=s.filter(({callback:o})=>o!==e),this.#t.set(t,s))}dispatchEvent(t){let e=super.dispatchEvent(t),n=this.#t.get(t.type);return n==null||(n=n.filter(({once:s})=>!s),this.#t.set(t.type,n)),e}safeDispatchEvent(t,e={}){return this.dispatchEvent(new CustomEvent(t,e))}};function ns(r){let t=new globalThis.AbortController;function e(){t.abort();for(let o of r)o?.removeEventListener!=null&&o.removeEventListener("abort",e)}for(let o of r){if(o?.aborted===!0){e();break}o?.addEventListener!=null&&o.addEventListener("abort",e)}function n(){for(let o of r)o?.removeEventListener!=null&&o.removeEventListener("abort",e)}let s=t.signal;return s.clear=n,s}function P(){let r={};return r.promise=new Promise((t,e)=>{r.resolve=t,r.reject=e}),r}var Ie=class{buffer;mask;top;btm;next;constructor(t){if(!(t>0)||(t-1&t)!==0)throw new Error("Max size for a FixedFIFO should be a power of two");this.buffer=new Array(t),this.mask=t-1,this.top=0,this.btm=0,this.next=null}push(t){return this.buffer[this.top]!==void 0?!1:(this.buffer[this.top]=t,this.top=this.top+1&this.mask,!0)}shift(){let t=this.buffer[this.btm];if(t!==void 0)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,t}isEmpty(){return this.buffer[this.btm]===void 0}},Lt=class{size;hwm;head;tail;constructor(t={}){this.hwm=t.splitLimit??16,this.head=new Ie(this.hwm),this.tail=this.head,this.size=0}calculateSize(t){return t?.byteLength!=null?t.byteLength:1}push(t){if(t?.value!=null&&(this.size+=this.calculateSize(t.value)),!this.head.push(t)){let e=this.head;this.head=e.next=new Ie(2*this.head.buffer.length),this.head.push(t)}}shift(){let t=this.tail.shift();if(t===void 0&&this.tail.next!=null){let e=this.tail.next;this.tail.next=null,this.tail=e,t=this.tail.shift()}return t?.value!=null&&(this.size-=this.calculateSize(t.value)),t}isEmpty(){return this.head.isEmpty()}};var Sr=class extends Error{type;code;constructor(t,e){super(t??"The operation was aborted"),this.type="aborted",this.code=e??"ABORT_ERR"}};function ke(r={}){return Qo(e=>{let n=e.shift();if(n==null)return{done:!0};if(n.error!=null)throw n.error;return{done:n.done===!0,value:n.value}},r)}function Qo(r,t){t=t??{};let e=t.onEnd,n=new Lt,s,o,i,a=P(),c=async()=>{try{return n.isEmpty()?i?{done:!0}:await new Promise((g,T)=>{o=B=>{o=null,n.push(B);try{g(r(n))}catch(L){T(L)}return s}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=P()})}},l=g=>o!=null?o(g):(n.push(g),s),u=g=>(n=new Lt,o!=null?o({error:g}):(n.push({error:g}),s)),h=g=>{if(i)return s;if(t?.objectMode!==!0&&g?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return l({done:!1,value:g})},f=g=>i?s:(i=!0,g!=null?u(g):l({done:!0})),E=()=>(n=new Lt,f(),{done:!0}),d=g=>(f(g),{done:!0});if(s={[Symbol.asyncIterator](){return this},next:c,return:E,throw:d,push:h,end:f,get readableLength(){return n.size},onEmpty:async g=>{let T=g?.signal;if(T?.throwIfAborted(),n.isEmpty())return;let B,L;T!=null&&(B=new Promise(($,W)=>{L=()=>{W(new Sr)},T.addEventListener("abort",L)}));try{await Promise.race([a.promise,B])}finally{L!=null&&T!=null&&T?.removeEventListener("abort",L)}}},e==null)return s;let x=s;return s={[Symbol.asyncIterator](){return this},next(){return x.next()},throw(g){return x.throw(g),e!=null&&(e(g),e=void 0),{done:!0}},return(){return x.return(),e!=null&&(e(),e=void 0),{done:!0}},push:h,end(g){return x.end(g),e!=null&&(e(g),e=void 0),s},get readableLength(){return x.readableLength},onEmpty:g=>x.onEmpty(g)},s}var Ir=class extends Error{type;code;constructor(t,e){super(t??"The operation was aborted"),this.type="aborted",this.name="AbortError",this.code=e??"ABORT_ERR"}};async function K(r,t,e,n){let s=new Ir(n?.errorMessage,n?.errorCode);return e?.aborted===!0?Promise.reject(s):new Promise((o,i)=>{function a(){e?.removeEventListener("abort",u),r.removeEventListener(t,c),n?.errorEvent!=null&&r.removeEventListener(n.errorEvent,l)}let c=h=>{try{if(n?.filter?.(h)===!1)return}catch(f){a(),i(f);return}a(),o(h)},l=h=>{a(),i(h.detail)},u=()=>{a(),i(s)};e?.addEventListener("abort",u),r.addEventListener(t,c),n?.errorEvent!=null&&r.addEventListener(n.errorEvent,l)})}function kr(r,t){let e,n=function(){let s=function(){e=void 0,r()};clearTimeout(e),e=setTimeout(s,t)};return n.start=()=>{},n.stop=()=>{clearTimeout(e)},n}var Ae=class extends Error{static name="QueueFullError";constructor(t="The queue was full"){super(t),this.name="QueueFullError"}};var Te=class extends Error{type;code;constructor(t,e,n){super(t??"The operation was aborted"),this.type="aborted",this.name=n??"AbortError",this.code=e??"ABORT_ERR"}};async function De(r,t,e){if(t==null)return r;if(t.aborted)return r.catch(()=>{}),Promise.reject(new Te(e?.errorMessage,e?.errorCode,e?.errorName));let n,s=new Te(e?.errorMessage,e?.errorCode,e?.errorName);try{return await Promise.race([r,new Promise((o,i)=>{n=()=>{i(s)},t.addEventListener("abort",n)})])}finally{n!=null&&t.removeEventListener("abort",n)}}var Le=class{deferred;signal;constructor(t){this.signal=t,this.deferred=P(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new Z)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function Zo(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var Ce=class{id;fn;options;recipients;status;timeline;controller;constructor(t,e){this.id=Zo(),this.status="queued",this.fn=t,this.options=e,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,this.controller.signal,this.onAbort=this.onAbort.bind(this)}abort(t){this.controller.abort(t)}onAbort(){this.recipients.reduce((e,n)=>e&&n.signal?.aborted===!0,!0)&&(this.controller.abort(new Z),this.cleanup())}async join(t={}){let e=new Le(t.signal);return this.recipients.push(e),t.signal?.addEventListener("abort",this.onAbort),e.deferred.promise}async run(){this.status="running",this.timeline.started=Date.now();try{this.controller.signal.throwIfAborted();let t=await De(this.fn({...this.options??{},signal:this.controller.signal}),this.controller.signal);this.recipients.forEach(e=>{e.deferred.resolve(t)}),this.status="complete"}catch(t){this.recipients.forEach(e=>{e.deferred.reject(t)}),this.status="errored"}finally{this.timeline.finished=Date.now(),this.cleanup()}}cleanup(){this.recipients.forEach(t=>{t.cleanup(),t.signal?.removeEventListener("abort",this.onAbort)})}};var Ct=class extends et{concurrency;maxSize;queue;pending;sort;constructor(t={}){super(),this.concurrency=t.concurrency??Number.POSITIVE_INFINITY,this.maxSize=t.maxSize??Number.POSITIVE_INFINITY,this.pending=0,t.metricName!=null&&t.metrics?.registerMetricGroup(t.metricName,{calculate:()=>({size:this.queue.length,running:this.pending,queued:this.queue.length-this.pending})}),this.sort=t.sort,this.queue=[],this.emitEmpty=kr(this.emitEmpty.bind(this),1),this.emitIdle=kr(this.emitIdle.bind(this),1)}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 t;for(let e of this.queue)if(e.status==="queued"){t=e;break}return t==null?!1:(this.safeDispatchEvent("active"),this.pending++,t.run().finally(()=>{for(let e=0;e<this.queue.length;e++)if(this.queue[e]===t){this.queue.splice(e,1);break}this.pending--,this.tryToStartAnother(),this.safeDispatchEvent("next")}),!0)}return!1}enqueue(t){this.queue.push(t),this.sort!=null&&this.queue.sort(this.sort)}async add(t,e){if(e?.signal?.throwIfAborted(),this.size===this.maxSize)throw new Ae;let n=new Ce(t,e);return this.enqueue(n),this.safeDispatchEvent("add"),this.tryToStartAnother(),n.join(e).then(s=>(this.safeDispatchEvent("completed",{detail:s}),this.safeDispatchEvent("success",{detail:{job:n,result:s}}),s)).catch(s=>{if(n.status==="queued"){for(let o=0;o<this.queue.length;o++)if(this.queue[o]===n){this.queue.splice(o,1);break}}throw this.safeDispatchEvent("error",{detail:s}),this.safeDispatchEvent("failure",{detail:{job:n,error:s}}),s})}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(t=>{t.abort(new Z)}),this.clear()}async onEmpty(t){this.size!==0&&await K(this,"empty",t?.signal)}async onSizeLessThan(t,e){this.size<t||await K(this,"next",e?.signal,{filter:()=>this.size<t})}async onIdle(t){this.pending===0&&this.size===0||await K(this,"idle",t?.signal)}get size(){return this.queue.length}get queued(){return this.queue.length-this.pending}get running(){return this.pending}async*toGenerator(t){t?.signal?.throwIfAborted();let e=ke({objectMode:!0}),n=c=>{c!=null?this.abort():this.clear(),e.end(c)},s=c=>{c.detail!=null&&e.push(c.detail)},o=c=>{n(c.detail)},i=()=>{n()},a=()=>{n(new Z("Queue aborted"))};this.addEventListener("completed",s),this.addEventListener("error",o),this.addEventListener("idle",i),t?.signal?.addEventListener("abort",a);try{yield*e}finally{this.removeEventListener("completed",s),this.removeEventListener("error",o),this.removeEventListener("idle",i),t?.signal?.removeEventListener("abort",a),n()}}};var Pe=class extends Ct{has(t){return this.find(t)!=null}find(t){return this.queue.find(e=>t.equals(e.options.peerId))}};function Ko(r){return r[Symbol.asyncIterator]!=null}function Jo(r){if(Ko(r))return(async()=>{for await(let t of r);})();for(let t of r);}var Ar=Jo;function N(r=0){return new Uint8Array(r)}function R(r=0){return new Uint8Array(r)}var jo=Math.pow(2,7),Yo=Math.pow(2,14),ti=Math.pow(2,21),Tr=Math.pow(2,28),Dr=Math.pow(2,35),Lr=Math.pow(2,42),Cr=Math.pow(2,49),b=128,U=127;function _(r){if(r<jo)return 1;if(r<Yo)return 2;if(r<ti)return 3;if(r<Tr)return 4;if(r<Dr)return 5;if(r<Lr)return 6;if(r<Cr)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function Pt(r,t,e=0){switch(_(r)){case 8:t[e++]=r&255|b,r/=128;case 7:t[e++]=r&255|b,r/=128;case 6:t[e++]=r&255|b,r/=128;case 5:t[e++]=r&255|b,r/=128;case 4:t[e++]=r&255|b,r>>>=7;case 3:t[e++]=r&255|b,r>>>=7;case 2:t[e++]=r&255|b,r>>>=7;case 1:{t[e++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return t}function ei(r,t,e=0){switch(_(r)){case 8:t.set(e++,r&255|b),r/=128;case 7:t.set(e++,r&255|b),r/=128;case 6:t.set(e++,r&255|b),r/=128;case 5:t.set(e++,r&255|b),r/=128;case 4:t.set(e++,r&255|b),r>>>=7;case 3:t.set(e++,r&255|b),r>>>=7;case 2:t.set(e++,r&255|b),r>>>=7;case 1:{t.set(e++,r&255),r>>>=7;break}default:throw new Error("unreachable")}return t}function Pr(r,t){let e=r[t],n=0;if(n+=e&U,e<b||(e=r[t+1],n+=(e&U)<<7,e<b)||(e=r[t+2],n+=(e&U)<<14,e<b)||(e=r[t+3],n+=(e&U)<<21,e<b)||(e=r[t+4],n+=(e&U)*Tr,e<b)||(e=r[t+5],n+=(e&U)*Dr,e<b)||(e=r[t+6],n+=(e&U)*Lr,e<b)||(e=r[t+7],n+=(e&U)*Cr,e<b))return n;throw new RangeError("Could not decode varint")}function ri(r,t){let e=r.get(t),n=0;if(n+=e&U,e<b||(e=r.get(t+1),n+=(e&U)<<7,e<b)||(e=r.get(t+2),n+=(e&U)<<14,e<b)||(e=r.get(t+3),n+=(e&U)<<21,e<b)||(e=r.get(t+4),n+=(e&U)*Tr,e<b)||(e=r.get(t+5),n+=(e&U)*Dr,e<b)||(e=r.get(t+6),n+=(e&U)*Lr,e<b)||(e=r.get(t+7),n+=(e&U)*Cr,e<b))return n;throw new RangeError("Could not decode varint")}function Ne(r,t,e=0){return t==null&&(t=R(_(r))),t instanceof Uint8Array?Pt(r,t,e):ei(r,t,e)}function gt(r,t=0){return r instanceof Uint8Array?Pr(r,t):ri(r,t)}function ut(r,t){t==null&&(t=r.reduce((s,o)=>s+o.length,0));let e=R(t),n=0;for(let s of r)e.set(s,n),n+=s.length;return e}function J(r,t){if(r===t)return!0;if(r.byteLength!==t.byteLength)return!1;for(let e=0;e<r.byteLength;e++)if(r[e]!==t[e])return!1;return!0}var os=Symbol.for("@achingbrain/uint8arraylist");function ss(r,t){if(t==null||t<0)throw new RangeError("index is out of bounds");let e=0;for(let n of r){let s=e+n.byteLength;if(t<s)return{buf:n,index:t-e};e=s}throw new RangeError("index is out of bounds")}function Re(r){return!!r?.[os]}var ht=class r{bufs;length;[os]=!0;constructor(...t){this.bufs=[],this.length=0,t.length>0&&this.appendAll(t)}*[Symbol.iterator](){yield*this.bufs}get byteLength(){return this.length}append(...t){this.appendAll(t)}appendAll(t){let e=0;for(let n of t)if(n instanceof Uint8Array)e+=n.byteLength,this.bufs.push(n);else if(Re(n))e+=n.byteLength,this.bufs.push(...n.bufs);else throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");this.length+=e}prepend(...t){this.prependAll(t)}prependAll(t){let e=0;for(let n of t.reverse())if(n instanceof Uint8Array)e+=n.byteLength,this.bufs.unshift(n);else if(Re(n))e+=n.byteLength,this.bufs.unshift(...n.bufs);else throw new Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");this.length+=e}get(t){let e=ss(this.bufs,t);return e.buf[e.index]}set(t,e){let n=ss(this.bufs,t);n.buf[n.index]=e}write(t,e=0){if(t instanceof Uint8Array)for(let n=0;n<t.length;n++)this.set(e+n,t[n]);else if(Re(t))for(let n=0;n<t.length;n++)this.set(e+n,t.get(n));else throw new Error("Could not write value, must be an Uint8Array or a Uint8ArrayList")}consume(t){if(t=Math.trunc(t),!(Number.isNaN(t)||t<=0)){if(t===this.byteLength){this.bufs=[],this.length=0;return}for(;this.bufs.length>0;)if(t>=this.bufs[0].byteLength)t-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift();else{this.bufs[0]=this.bufs[0].subarray(t),this.length-=t;break}}}slice(t,e){let{bufs:n,length:s}=this._subList(t,e);return ut(n,s)}subarray(t,e){let{bufs:n,length:s}=this._subList(t,e);return n.length===1?n[0]:ut(n,s)}sublist(t,e){let{bufs:n,length:s}=this._subList(t,e),o=new r;return o.length=s,o.bufs=[...n],o}_subList(t,e){if(t=t??0,e=e??this.length,t<0&&(t=this.length+t),e<0&&(e=this.length+e),t<0||e>this.length)throw new RangeError("index is out of bounds");if(t===e)return{bufs:[],length:0};if(t===0&&e===this.length)return{bufs:this.bufs,length:this.length};let n=[],s=0;for(let o=0;o<this.bufs.length;o++){let i=this.bufs[o],a=s,c=a+i.byteLength;if(s=c,t>=c)continue;let l=t>=a&&t<c,u=e>a&&e<=c;if(l&&u){if(t===a&&e===c){n.push(i);break}let h=t-a;n.push(i.subarray(h,h+(e-t)));break}if(l){if(t===0){n.push(i);continue}n.push(i.subarray(t-a));continue}if(u){if(e===c){n.push(i);break}n.push(i.subarray(0,e-a));break}n.push(i)}return{bufs:n,length:e-t}}indexOf(t,e=0){if(!Re(t)&&!(t instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');let n=t instanceof Uint8Array?t:t.subarray();if(e=Number(e??0),isNaN(e)&&(e=0),e<0&&(e=this.length+e),e<0&&(e=0),t.length===0)return e>this.length?this.length:e;let s=n.byteLength;if(s===0)throw new TypeError("search must be at least 1 byte long");let o=256,i=new Int32Array(o);for(let h=0;h<o;h++)i[h]=-1;for(let h=0;h<s;h++)i[n[h]]=h;let a=i,c=this.byteLength-n.byteLength,l=n.byteLength-1,u;for(let h=e;h<=c;h+=u){u=0;for(let f=l;f>=0;f--){let E=this.get(h+f);if(n[f]!==E){u=Math.max(1,f-a[E]);break}}if(u===0)return h}return-1}getInt8(t){let e=this.subarray(t,t+1);return new DataView(e.buffer,e.byteOffset,e.byteLength).getInt8(0)}setInt8(t,e){let n=R(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt8(0,e),this.write(n,t)}getInt16(t,e){let n=this.subarray(t,t+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt16(0,e)}setInt16(t,e,n){let s=N(2);new DataView(s.buffer,s.byteOffset,s.byteLength).setInt16(0,e,n),this.write(s,t)}getInt32(t,e){let n=this.subarray(t,t+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt32(0,e)}setInt32(t,e,n){let s=N(4);new DataView(s.buffer,s.byteOffset,s.byteLength).setInt32(0,e,n),this.write(s,t)}getBigInt64(t,e){let n=this.subarray(t,t+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigInt64(0,e)}setBigInt64(t,e,n){let s=N(8);new DataView(s.buffer,s.byteOffset,s.byteLength).setBigInt64(0,e,n),this.write(s,t)}getUint8(t){let e=this.subarray(t,t+1);return new DataView(e.buffer,e.byteOffset,e.byteLength).getUint8(0)}setUint8(t,e){let n=R(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint8(0,e),this.write(n,t)}getUint16(t,e){let n=this.subarray(t,t+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint16(0,e)}setUint16(t,e,n){let s=N(2);new DataView(s.buffer,s.byteOffset,s.byteLength).setUint16(0,e,n),this.write(s,t)}getUint32(t,e){let n=this.subarray(t,t+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint32(0,e)}setUint32(t,e,n){let s=N(4);new DataView(s.buffer,s.byteOffset,s.byteLength).setUint32(0,e,n),this.write(s,t)}getBigUint64(t,e){let n=this.subarray(t,t+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigUint64(0,e)}setBigUint64(t,e,n){let s=N(8);new DataView(s.buffer,s.byteOffset,s.byteLength).setBigUint64(0,e,n),this.write(s,t)}getFloat32(t,e){let n=this.subarray(t,t+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat32(0,e)}setFloat32(t,e,n){let s=N(4);new DataView(s.buffer,s.byteOffset,s.byteLength).setFloat32(0,e,n),this.write(s,t)}getFloat64(t,e){let n=this.subarray(t,t+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat64(0,e)}setFloat64(t,e,n){let s=N(8);new DataView(s.buffer,s.byteOffset,s.byteLength).setFloat64(0,e,n),this.write(s,t)}equals(t){if(t==null||!(t instanceof r)||t.bufs.length!==this.bufs.length)return!1;for(let e=0;e<this.bufs.length;e++)if(!J(this.bufs[e],t.bufs[e]))return!1;return!0}static fromUint8Arrays(t,e){let n=new r;return n.bufs=t,e==null&&(e=t.reduce((s,o)=>s+o.byteLength,0)),n.length=e,n}};var Ue=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},Nt=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},Me=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"},Kt=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};function Fe(r){return r[Symbol.asyncIterator]!=null}function is(r,t){if(r.byteLength>t)throw new Nt("Message length too long")}var Oe=r=>{let t=_(r),e=R(t);return Ne(r,e),Oe.bytes=t,e};Oe.bytes=0;function ze(r,t){t=t??{};let e=t.lengthEncoder??Oe,n=t?.maxDataLength??4194304;function*s(o){is(o,n);let i=e(o.byteLength);i instanceof Uint8Array?yield i:yield*i,o instanceof Uint8Array?yield o:yield*o}return Fe(r)?async function*(){for await(let o of r)yield*s(o)}():function*(){for(let o of r)yield*s(o)}()}ze.single=(r,t)=>{t=t??{};let e=t.lengthEncoder??Oe,n=t?.maxDataLength??4194304;return is(r,n),new ht(e(r.byteLength),r)};var wt;(function(r){r[r.LENGTH=0]="LENGTH",r[r.DATA=1]="DATA"})(wt||(wt={}));var Rr=r=>{let t=gt(r);return Rr.bytes=_(t),t};Rr.bytes=0;function Jt(r,t){let e=new ht,n=wt.LENGTH,s=-1,o=t?.lengthDecoder??Rr,i=t?.maxLengthLength??8,a=t?.maxDataLength??4194304;function*c(){for(;e.byteLength>0;){if(n===wt.LENGTH)try{if(s=o(e),s<0)throw new Ue("Invalid message length");if(s>a)throw new Nt("Message length too long");let l=o.bytes;e.consume(l),t?.onLength!=null&&t.onLength(s),n=wt.DATA}catch(l){if(l instanceof RangeError){if(e.byteLength>i)throw new Me("Message length length too long");break}throw l}if(n===wt.DATA){if(e.byteLength<s)break;let l=e.sublist(0,s);e.consume(s),t?.onData!=null&&t.onData(l),yield l,n=wt.LENGTH}}}return Fe(r)?async function*(){for await(let l of r)e.append(l),yield*c();if(e.byteLength>0)throw new Kt("Unexpected end of input")}():function*(){for(let l of r)e.append(l),yield*c();if(e.byteLength>0)throw new Kt("Unexpected end of input")}()}Jt.fromReader=(r,t)=>{let e=1,n=async function*(){for(;;)try{let{done:o,value:i}=await r.next(e);if(o===!0)return;i!=null&&(yield i)}catch(o){if(o.code==="ERR_UNDER_READ")return{done:!0,value:null};throw o}finally{e=1}}();return Jt(n,{...t??{},onLength:o=>{e=o}})};function oi(r){let[t,e]=r[Symbol.asyncIterator]!=null?[r[Symbol.asyncIterator](),Symbol.asyncIterator]:[r[Symbol.iterator](),Symbol.iterator],n=[];return{peek:()=>t.next(),push:s=>{n.push(s)},next:()=>n.length>0?{done:!1,value:n.shift()}:t.next(),[e](){return this}}}var as=oi;function ii(r){return r[Symbol.asyncIterator]!=null}function ai(r,t){let e=0;if(ii(r))return async function*(){for await(let c of r)yield t(c,e++)}();let n=as(r),{value:s,done:o}=n.next();if(o===!0)return function*(){}();let i=t(s,e++);if(typeof i.then=="function")return async function*(){yield await i;for(let c of n)yield t(c,e++)}();let a=t;return function*(){yield i;for(let c of n)yield a(c,e++)}()}var cs=ai;var Ur=class{readNext;haveNext;ended;nextResult;error;constructor(){this.ended=!1,this.readNext=P(),this.haveNext=P()}[Symbol.asyncIterator](){return this}async next(){if(this.nextResult==null&&await this.haveNext.promise,this.nextResult==null)throw new Error("HaveNext promise resolved but nextResult was undefined");let t=this.nextResult;return this.nextResult=void 0,this.readNext.resolve(),this.readNext=P(),t}async throw(t){return this.ended=!0,this.error=t,t!=null&&(this.haveNext.promise.catch(()=>{}),this.haveNext.reject(t)),{done:!0,value:void 0}}async return(){let t={done:!0,value:void 0};return this.ended=!0,this.nextResult=t,this.haveNext.resolve(),t}async push(t,e){await this._push(t,e)}async end(t,e){t!=null?await this.throw(t):await this._push(void 0,e)}async _push(t,e){if(t!=null&&this.ended)throw this.error??new Error("Cannot push value onto an ended pushable");for(;this.nextResult!=null;)await this.readNext.promise;t!=null?this.nextResult={done:!1,value:t}:(this.ended=!0,this.nextResult={done:!0,value:void 0}),this.haveNext.resolve(),this.haveNext=P(),await De(this.readNext.promise,e?.signal,e)}};function ls(){return new Ur}function ci(r){return r[Symbol.asyncIterator]!=null}async function li(r,t,e){try{await Promise.all(r.map(async n=>{for await(let s of n)await t.push(s,{signal:e}),e.throwIfAborted()})),await t.end(void 0,{signal:e})}catch(n){await t.end(n,{signal:e}).catch(()=>{})}}async function*ui(r){let t=new AbortController,e=ls();li(r,e,t.signal).catch(()=>{});try{yield*e}finally{t.abort()}}function*hi(r){for(let t of r)yield*t}function fi(...r){let t=[];for(let e of r)ci(e)||t.push(e);return t.length===r.length?hi(t):ui(r)}var us=fi;function Fr(r,...t){if(r==null)throw new Error("Empty pipeline");if(Mr(r)){let n=r;r=()=>n.source}else if(fs(r)||hs(r)){let n=r;r=()=>n}let e=[r,...t];if(e.length>1&&Mr(e[e.length-1])&&(e[e.length-1]=e[e.length-1].sink),e.length>2)for(let n=1;n<e.length-1;n++)Mr(e[n])&&(e[n]=pi(e[n]));return di(...e)}var di=(...r)=>{let t;for(;r.length>0;)t=r.shift()(t);return t},hs=r=>r?.[Symbol.asyncIterator]!=null,fs=r=>r?.[Symbol.iterator]!=null,Mr=r=>r==null?!1:r.sink!=null&&r.source!=null,pi=r=>t=>{let e=r.sink(t);if(e?.then!=null){let n=ke({objectMode:!0});e.then(()=>{n.end()},i=>{n.end(i)});let s,o=r.source;if(hs(o))s=async function*(){yield*o,n.end()};else if(fs(o))s=function*(){yield*o,n.end()};else throw new Error("Unknown duplex source type - must be Iterable or AsyncIterable");return us(n,s())}return r.source};function mi(r){return r[Symbol.asyncIterator]!=null}function gi(r,t){return mi(r)?async function*(){let e=0;if(!(t<1)){for await(let n of r)if(yield n,e++,e===t)return}}():function*(){let e=0;if(!(t<1)){for(let n of r)if(yield n,e++,e===t)return}}()}var ds=gi;var rt=class extends Event{type;detail;constructor(t,e){super(t),this.type=t,this.detail=e}};var jt="/ipfs/bitswap/1.2.0";var Br=new Float32Array([-0]),ft=new Uint8Array(Br.buffer);function ps(r,t,e){Br[0]=r,t[e]=ft[0],t[e+1]=ft[1],t[e+2]=ft[2],t[e+3]=ft[3]}function ms(r,t){return ft[0]=r[t],ft[1]=r[t+1],ft[2]=r[t+2],ft[3]=r[t+3],Br[0]}var Or=new Float64Array([-0]),M=new Uint8Array(Or.buffer);function gs(r,t,e){Or[0]=r,t[e]=M[0],t[e+1]=M[1],t[e+2]=M[2],t[e+3]=M[3],t[e+4]=M[4],t[e+5]=M[5],t[e+6]=M[6],t[e+7]=M[7]}function ws(r,t){return M[0]=r[t],M[1]=r[t+1],M[2]=r[t+2],M[3]=r[t+3],M[4]=r[t+4],M[5]=r[t+5],M[6]=r[t+6],M[7]=r[t+7],Or[0]}var wi=BigInt(Number.MAX_SAFE_INTEGER),bi=BigInt(Number.MIN_SAFE_INTEGER),V=class r{lo;hi;constructor(t,e){this.lo=t|0,this.hi=e|0}toNumber(t=!1){if(!t&&this.hi>>>31>0){let e=~this.lo+1>>>0,n=~this.hi>>>0;return e===0&&(n=n+1>>>0),-(e+n*4294967296)}return this.lo+this.hi*4294967296}toBigInt(t=!1){if(t)return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n);if(this.hi>>>31){let e=~this.lo+1>>>0,n=~this.hi>>>0;return e===0&&(n=n+1>>>0),-(BigInt(e)+(BigInt(n)<<32n))}return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n)}toString(t=!1){return this.toBigInt(t).toString()}zzEncode(){let t=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^t)>>>0,this.lo=(this.lo<<1^t)>>>0,this}zzDecode(){let t=-(this.lo&1);return this.lo=((this.lo>>>1|this.hi<<31)^t)>>>0,this.hi=(this.hi>>>1^t)>>>0,this}length(){let t=this.lo,e=(this.lo>>>28|this.hi<<4)>>>0,n=this.hi>>>24;return n===0?e===0?t<16384?t<128?1:2:t<2097152?3:4:e<16384?e<128?5:6:e<2097152?7:8:n<128?9:10}static fromBigInt(t){if(t===0n)return bt;if(t<wi&&t>bi)return this.fromNumber(Number(t));let e=t<0n;e&&(t=-t);let n=t>>32n,s=t-(n<<32n);return e&&(n=~n|0n,s=~s|0n,++s>bs&&(s=0n,++n>bs&&(n=0n))),new r(Number(s),Number(n))}static fromNumber(t){if(t===0)return bt;let e=t<0;e&&(t=-t);let n=t>>>0,s=(t-n)/4294967296>>>0;return e&&(s=~s>>>0,n=~n>>>0,++n>4294967295&&(n=0,++s>4294967295&&(s=0))),new r(n,s)}static from(t){return typeof t=="number"?r.fromNumber(t):typeof t=="bigint"?r.fromBigInt(t):typeof t=="string"?r.fromBigInt(BigInt(t)):t.low!=null||t.high!=null?new r(t.low>>>0,t.high>>>0):bt}},bt=new V(0,0);bt.toBigInt=function(){return 0n};bt.zzEncode=bt.zzDecode=function(){return this};bt.length=function(){return 1};var bs=4294967296n;function ys(r){let t=0,e=0;for(let n=0;n<r.length;++n)e=r.charCodeAt(n),e<128?t+=1:e<2048?t+=2:(e&64512)===55296&&(r.charCodeAt(n+1)&64512)===56320?(++n,t+=4):t+=3;return t}function xs(r,t,e){if(e-t<1)return"";let s,o=[],i=0,a;for(;t<e;)a=r[t++],a<128?o[i++]=a:a>191&&a<224?o[i++]=(a&31)<<6|r[t++]&63:a>239&&a<365?(a=((a&7)<<18|(r[t++]&63)<<12|(r[t++]&63)<<6|r[t++]&63)-65536,o[i++]=55296+(a>>10),o[i++]=56320+(a&1023)):o[i++]=(a&15)<<12|(r[t++]&63)<<6|r[t++]&63,i>8191&&((s??(s=[])).push(String.fromCharCode.apply(String,o)),i=0);return s!=null?(i>0&&s.push(String.fromCharCode.apply(String,o.slice(0,i))),s.join("")):String.fromCharCode.apply(String,o.slice(0,i))}function zr(r,t,e){let n=e,s,o;for(let i=0;i<r.length;++i)s=r.charCodeAt(i),s<128?t[e++]=s:s<2048?(t[e++]=s>>6|192,t[e++]=s&63|128):(s&64512)===55296&&((o=r.charCodeAt(i+1))&64512)===56320?(s=65536+((s&1023)<<10)+(o&1023),++i,t[e++]=s>>18|240,t[e++]=s>>12&63|128,t[e++]=s>>6&63|128,t[e++]=s&63|128):(t[e++]=s>>12|224,t[e++]=s>>6&63|128,t[e++]=s&63|128);return e-n}function j(r,t){return RangeError(`index out of range: ${r.pos} + ${t??1} > ${r.len}`)}function $e(r,t){return(r[t-4]|r[t-3]<<8|r[t-2]<<16|r[t-1]<<24)>>>0}var $r=class{buf;pos;len;_slice=Uint8Array.prototype.subarray;constructor(t){this.buf=t,this.pos=0,this.len=t.length}uint32(){let t=4294967295;if(t=(this.buf[this.pos]&127)>>>0,this.buf[this.pos++]<128||(t=(t|(this.buf[this.pos]&127)<<7)>>>0,this.buf[this.pos++]<128)||(t=(t|(this.buf[this.pos]&127)<<14)>>>0,this.buf[this.pos++]<128)||(t=(t|(this.buf[this.pos]&127)<<21)>>>0,this.buf[this.pos++]<128)||(t=(t|(this.buf[this.pos]&15)<<28)>>>0,this.buf[this.pos++]<128))return t;if((this.pos+=5)>this.len)throw this.pos=this.len,j(this,10);return t}int32(){return this.uint32()|0}sint32(){let t=this.uint32();return t>>>1^-(t&1)|0}bool(){return this.uint32()!==0}fixed32(){if(this.pos+4>this.len)throw j(this,4);return $e(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw j(this,4);return $e(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw j(this,4);let t=ms(this.buf,this.pos);return this.pos+=4,t}double(){if(this.pos+8>this.len)throw j(this,4);let t=ws(this.buf,this.pos);return this.pos+=8,t}bytes(){let t=this.uint32(),e=this.pos,n=this.pos+t;if(n>this.len)throw j(this,t);return this.pos+=t,e===n?new Uint8Array(0):this.buf.subarray(e,n)}string(){let t=this.bytes();return xs(t,0,t.length)}skip(t){if(typeof t=="number"){if(this.pos+t>this.len)throw j(this,t);this.pos+=t}else do if(this.pos>=this.len)throw j(this);while((this.buf[this.pos++]&128)!==0);return this}skipType(t){switch(t){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;(t=this.uint32()&7)!==4;)this.skipType(t);break;case 5:this.skip(4);break;default:throw Error(`invalid wire type ${t} at offset ${this.pos}`)}return this}readLongVarint(){let t=new V(0,0),e=0;if(this.len-this.pos>4){for(;e<4;++e)if(t.lo=(t.lo|(this.buf[this.pos]&127)<<e*7)>>>0,this.buf[this.pos++]<128)return t;if(t.lo=(t.lo|(this.buf[this.pos]&127)<<28)>>>0,t.hi=(t.hi|(this.buf[this.pos]&127)>>4)>>>0,this.buf[this.pos++]<128)return t;e=0}else{for(;e<3;++e){if(this.pos>=this.len)throw j(this);if(t.lo=(t.lo|(this.buf[this.pos]&127)<<e*7)>>>0,this.buf[this.pos++]<128)return t}return t.lo=(t.lo|(this.buf[this.pos++]&127)<<e*7)>>>0,t}if(this.len-this.pos>4){for(;e<5;++e)if(t.hi=(t.hi|(this.buf[this.pos]&127)<<e*7+3)>>>0,this.buf[this.pos++]<128)return t}else for(;e<5;++e){if(this.pos>=this.len)throw j(this);if(t.hi=(t.hi|(this.buf[this.pos]&127)<<e*7+3)>>>0,this.buf[this.pos++]<128)return t}throw Error("invalid varint encoding")}readFixed64(){if(this.pos+8>this.len)throw j(this,8);let t=$e(this.buf,this.pos+=4),e=$e(this.buf,this.pos+=4);return new V(t,e)}int64(){return this.readLongVarint().toBigInt()}int64Number(){return this.readLongVarint().toNumber()}int64String(){return this.readLongVarint().toString()}uint64(){return this.readLongVarint().toBigInt(!0)}uint64Number(){let t=Pr(this.buf,this.pos);return this.pos+=_(t),t}uint64String(){return this.readLongVarint().toString(!0)}sint64(){return this.readLongVarint().zzDecode().toBigInt()}sint64Number(){return this.readLongVarint().zzDecode().toNumber()}sint64String(){return this.readLongVarint().zzDecode().toString()}fixed64(){return this.readFixed64().toBigInt()}fixed64Number(){return this.readFixed64().toNumber()}fixed64String(){return this.readFixed64().toString()}sfixed64(){return this.readFixed64().toBigInt()}sfixed64Number(){return this.readFixed64().toNumber()}sfixed64String(){return this.readFixed64().toString()}};function qr(r){return new $r(r instanceof Uint8Array?r:r.subarray())}function yt(r,t,e){let n=qr(r);return t.decode(n,void 0,e)}var Xr={};q(Xr,{base10:()=>Ii});var Ou=new Uint8Array(0);function _s(r,t){if(r===t)return!0;if(r.byteLength!==t.byteLength)return!1;for(let e=0;e<r.byteLength;e++)if(r[e]!==t[e])return!1;return!0}function st(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength);throw new Error("Unknown type, must be binary type")}function vs(r){return new TextEncoder().encode(r)}function Ss(r){return new TextDecoder().decode(r)}function yi(r,t){if(r.length>=255)throw new TypeError("Alphabet too long");for(var e=new Uint8Array(256),n=0;n<e.length;n++)e[n]=255;for(var s=0;s<r.length;s++){var o=r.charAt(s),i=o.charCodeAt(0);if(e[i]!==255)throw new TypeError(o+" is ambiguous");e[i]=s}var a=r.length,c=r.charAt(0),l=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function h(d){if(d instanceof Uint8Array||(ArrayBuffer.isView(d)?d=new Uint8Array(d.buffer,d.byteOffset,d.byteLength):Array.isArray(d)&&(d=Uint8Array.from(d))),!(d instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(d.length===0)return"";for(var x=0,g=0,T=0,B=d.length;T!==B&&d[T]===0;)T++,x++;for(var L=(B-T)*u+1>>>0,$=new Uint8Array(L);T!==B;){for(var W=d[T],lt=0,Q=L-1;(W!==0||lt<g)&&Q!==-1;Q--,lt++)W+=256*$[Q]>>>0,$[Q]=W%a>>>0,W=W/a>>>0;if(W!==0)throw new Error("Non-zero carry");g=lt,T++}for(var nt=L-g;nt!==L&&$[nt]===0;)nt++;for(var be=c.repeat(x);nt<L;++nt)be+=r.charAt($[nt]);return be}function f(d){if(typeof d!="string")throw new TypeError("Expected String");if(d.length===0)return new Uint8Array;var x=0;if(d[x]!==" "){for(var g=0,T=0;d[x]===c;)g++,x++;for(var B=(d.length-x)*l+1>>>0,L=new Uint8Array(B);d[x];){var $=e[d.charCodeAt(x)];if($===255)return;for(var W=0,lt=B-1;($!==0||W<T)&&lt!==-1;lt--,W++)$+=a*L[lt]>>>0,L[lt]=$%256>>>0,$=$/256>>>0;if($!==0)throw new Error("Non-zero carry");T=W,x++}if(d[x]!==" "){for(var Q=B-T;Q!==B&&L[Q]===0;)Q++;for(var nt=new Uint8Array(g+(B-Q)),be=g;Q!==B;)nt[be++]=L[Q++];return nt}}}function E(d){var x=f(d);if(x)return x;throw new Error(`Non-${t} character`)}return{encode:h,decodeUnsafe:f,decode:E}}var xi=yi,Ei=xi,ks=Ei;var Vr=class{name;prefix;baseEncode;constructor(t,e,n){this.name=t,this.prefix=e,this.baseEncode=n}encode(t){if(t instanceof Uint8Array)return`${this.prefix}${this.baseEncode(t)}`;throw Error("Unknown type, must be binary type")}},Hr=class{name;prefix;baseDecode;prefixCodePoint;constructor(t,e,n){this.name=t,this.prefix=e;let s=e.codePointAt(0);if(s===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=s,this.baseDecode=n}decode(t){if(typeof t=="string"){if(t.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(t)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(t.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(t){return As(this,t)}},Wr=class{decoders;constructor(t){this.decoders=t}or(t){return As(this,t)}decode(t){let e=t[0],n=this.decoders[e];if(n!=null)return n.decode(t);throw RangeError(`Unable to decode multibase string ${JSON.stringify(t)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function As(r,t){return new Wr({...r.decoders??{[r.prefix]:r},...t.decoders??{[t.prefix]:t}})}var Gr=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(t,e,n,s){this.name=t,this.prefix=e,this.baseEncode=n,this.baseDecode=s,this.encoder=new Vr(t,e,n),this.decoder=new Hr(t,e,s)}encode(t){return this.encoder.encode(t)}decode(t){return this.decoder.decode(t)}};function Rt({name:r,prefix:t,encode:e,decode:n}){return new Gr(r,t,e,n)}function dt({name:r,prefix:t,alphabet:e}){let{encode:n,decode:s}=ks(e,r);return Rt({prefix:t,name:r,encode:n,decode:o=>st(s(o))})}function _i(r,t,e,n){let s=r.length;for(;r[s-1]==="=";)--s;let o=new Uint8Array(s*e/8|0),i=0,a=0,c=0;for(let l=0;l<s;++l){let u=t[r[l]];if(u===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<e|u,i+=e,i>=8&&(i-=8,o[c++]=255&a>>i)}if(i>=e||(255&a<<8-i)!==0)throw new SyntaxError("Unexpected end of data");return o}function vi(r,t,e){let n=t[t.length-1]==="=",s=(1<<e)-1,o="",i=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],i+=8;i>e;)i-=e,o+=t[s&a>>i];if(i!==0&&(o+=t[s&a<<e-i]),n)for(;(o.length*e&7)!==0;)o+="=";return o}function Si(r){let t={};for(let e=0;e<r.length;++e)t[r[e]]=e;return t}function S({name:r,prefix:t,bitsPerChar:e,alphabet:n}){let s=Si(n);return Rt({prefix:t,name:r,encode(o){return vi(o,n,e)},decode(o){return _i(o,s,e,r)}})}var Ii=dt({prefix:"9",name:"base10",alphabet:"0123456789"});var Qr={};q(Qr,{base16:()=>ki,base16upper:()=>Ai});var ki=S({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),Ai=S({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var Zr={};q(Zr,{base2:()=>Ti});var Ti=S({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var Kr={};q(Kr,{base256emoji:()=>Ni});var Ts=Array.from("\u{1F680}\u{1FA90}\u2604\u{1F6F0}\u{1F30C}\u{1F311}\u{1F312}\u{1F313}\u{1F314}\u{1F315}\u{1F316}\u{1F317}\u{1F318}\u{1F30D}\u{1F30F}\u{1F30E}\u{1F409}\u2600\u{1F4BB}\u{1F5A5}\u{1F4BE}\u{1F4BF}\u{1F602}\u2764\u{1F60D}\u{1F923}\u{1F60A}\u{1F64F}\u{1F495}\u{1F62D}\u{1F618}\u{1F44D}\u{1F605}\u{1F44F}\u{1F601}\u{1F525}\u{1F970}\u{1F494}\u{1F496}\u{1F499}\u{1F622}\u{1F914}\u{1F606}\u{1F644}\u{1F4AA}\u{1F609}\u263A\u{1F44C}\u{1F917}\u{1F49C}\u{1F614}\u{1F60E}\u{1F607}\u{1F339}\u{1F926}\u{1F389}\u{1F49E}\u270C\u2728\u{1F937}\u{1F631}\u{1F60C}\u{1F338}\u{1F64C}\u{1F60B}\u{1F497}\u{1F49A}\u{1F60F}\u{1F49B}\u{1F642}\u{1F493}\u{1F929}\u{1F604}\u{1F600}\u{1F5A4}\u{1F603}\u{1F4AF}\u{1F648}\u{1F447}\u{1F3B6}\u{1F612}\u{1F92D}\u2763\u{1F61C}\u{1F48B}\u{1F440}\u{1F62A}\u{1F611}\u{1F4A5}\u{1F64B}\u{1F61E}\u{1F629}\u{1F621}\u{1F92A}\u{1F44A}\u{1F973}\u{1F625}\u{1F924}\u{1F449}\u{1F483}\u{1F633}\u270B\u{1F61A}\u{1F61D}\u{1F634}\u{1F31F}\u{1F62C}\u{1F643}\u{1F340}\u{1F337}\u{1F63B}\u{1F613}\u2B50\u2705\u{1F97A}\u{1F308}\u{1F608}\u{1F918}\u{1F4A6}\u2714\u{1F623}\u{1F3C3}\u{1F490}\u2639\u{1F38A}\u{1F498}\u{1F620}\u261D\u{1F615}\u{1F33A}\u{1F382}\u{1F33B}\u{1F610}\u{1F595}\u{1F49D}\u{1F64A}\u{1F639}\u{1F5E3}\u{1F4AB}\u{1F480}\u{1F451}\u{1F3B5}\u{1F91E}\u{1F61B}\u{1F534}\u{1F624}\u{1F33C}\u{1F62B}\u26BD\u{1F919}\u2615\u{1F3C6}\u{1F92B}\u{1F448}\u{1F62E}\u{1F646}\u{1F37B}\u{1F343}\u{1F436}\u{1F481}\u{1F632}\u{1F33F}\u{1F9E1}\u{1F381}\u26A1\u{1F31E}\u{1F388}\u274C\u270A\u{1F44B}\u{1F630}\u{1F928}\u{1F636}\u{1F91D}\u{1F6B6}\u{1F4B0}\u{1F353}\u{1F4A2}\u{1F91F}\u{1F641}\u{1F6A8}\u{1F4A8}\u{1F92C}\u2708\u{1F380}\u{1F37A}\u{1F913}\u{1F619}\u{1F49F}\u{1F331}\u{1F616}\u{1F476}\u{1F974}\u25B6\u27A1\u2753\u{1F48E}\u{1F4B8}\u2B07\u{1F628}\u{1F31A}\u{1F98B}\u{1F637}\u{1F57A}\u26A0\u{1F645}\u{1F61F}\u{1F635}\u{1F44E}\u{1F932}\u{1F920}\u{1F927}\u{1F4CC}\u{1F535}\u{1F485}\u{1F9D0}\u{1F43E}\u{1F352}\u{1F617}\u{1F911}\u{1F30A}\u{1F92F}\u{1F437}\u260E\u{1F4A7}\u{1F62F}\u{1F486}\u{1F446}\u{1F3A4}\u{1F647}\u{1F351}\u2744\u{1F334}\u{1F4A3}\u{1F438}\u{1F48C}\u{1F4CD}\u{1F940}\u{1F922}\u{1F445}\u{1F4A1}\u{1F4A9}\u{1F450}\u{1F4F8}\u{1F47B}\u{1F910}\u{1F92E}\u{1F3BC}\u{1F975}\u{1F6A9}\u{1F34E}\u{1F34A}\u{1F47C}\u{1F48D}\u{1F4E3}\u{1F942}"),Di=Ts.reduce((r,t,e)=>(r[e]=t,r),[]),Li=Ts.reduce((r,t,e)=>{let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);return r[n]=e,r},[]);function Ci(r){return r.reduce((t,e)=>(t+=Di[e],t),"")}function Pi(r){let t=[];for(let e of r){let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);let s=Li[n];if(s==null)throw new Error(`Non-base256emoji character: ${e}`);t.push(s)}return new Uint8Array(t)}var Ni=Rt({prefix:"\u{1F680}",name:"base256emoji",encode:Ci,decode:Pi});var Jr={};q(Jr,{base32:()=>pt,base32hex:()=>Fi,base32hexpad:()=>Oi,base32hexpadupper:()=>zi,base32hexupper:()=>Bi,base32pad:()=>Ui,base32padupper:()=>Mi,base32upper:()=>Ri,base32z:()=>$i});var pt=S({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Ri=S({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Ui=S({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Mi=S({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Fi=S({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Bi=S({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Oi=S({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),zi=S({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),$i=S({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var jr={};q(jr,{base36:()=>Yt,base36upper:()=>qi});var Yt=dt({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),qi=dt({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var Yr={};q(Yr,{base58btc:()=>O,base58flickr:()=>Vi});var O=dt({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Vi=dt({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var tn={};q(tn,{base64:()=>ot,base64pad:()=>Hi,base64url:()=>te,base64urlpad:()=>Wi});var ot=S({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Hi=S({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),te=S({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Wi=S({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var en={};q(en,{base8:()=>Gi});var Gi=S({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var rn={};q(rn,{identity:()=>Xi});var Xi=Rt({prefix:"\0",name:"identity",encode:r=>Ss(r),decode:r=>vs(r)});var eh=new TextEncoder,rh=new TextDecoder;var on={};q(on,{identity:()=>ga});var Ki=Cs,Ds=128,Ji=127,ji=~Ji,Yi=Math.pow(2,31);function Cs(r,t,e){t=t||[],e=e||0;for(var n=e;r>=Yi;)t[e++]=r&255|Ds,r/=128;for(;r&ji;)t[e++]=r&255|Ds,r>>>=7;return t[e]=r|0,Cs.bytes=e-n+1,t}var ta=nn,ea=128,Ls=127;function nn(r,n){var e=0,n=n||0,s=0,o=n,i,a=r.length;do{if(o>=a)throw nn.bytes=0,new RangeError("Could not decode varint");i=r[o++],e+=s<28?(i&Ls)<<s:(i&Ls)*Math.pow(2,s),s+=7}while(i>=ea);return nn.bytes=o-n,e}var ra=Math.pow(2,7),na=Math.pow(2,14),sa=Math.pow(2,21),oa=Math.pow(2,28),ia=Math.pow(2,35),aa=Math.pow(2,42),ca=Math.pow(2,49),la=Math.pow(2,56),ua=Math.pow(2,63),ha=function(r){return r<ra?1:r<na?2:r<sa?3:r<oa?4:r<ia?5:r<aa?6:r<ca?7:r<la?8:r<ua?9:10},fa={encode:Ki,decode:ta,encodingLength:ha},da=fa,ee=da;function re(r,t=0){return[ee.decode(r,t),ee.decode.bytes]}function Ut(r,t,e=0){return ee.encode(r,t,e),t}function Mt(r){return ee.encodingLength(r)}function xt(r,t){let e=t.byteLength,n=Mt(r),s=n+Mt(e),o=new Uint8Array(s+e);return Ut(r,o,0),Ut(e,o,n),o.set(t,s),new Ft(r,e,t,o)}function sn(r){let t=st(r),[e,n]=re(t),[s,o]=re(t.subarray(n)),i=t.subarray(n+o);if(i.byteLength!==s)throw new Error("Incorrect length");return new Ft(e,s,i,t)}function Ps(r,t){if(r===t)return!0;{let e=t;return r.code===e.code&&r.size===e.size&&e.bytes instanceof Uint8Array&&_s(r.bytes,e.bytes)}}var Ft=class{code;size;digest;bytes;constructor(t,e,n,s){this.code=t,this.size=e,this.digest=n,this.bytes=s}};var Ns=0,pa="identity",Rs=st;function ma(r){return xt(Ns,Rs(r))}var ga={code:Ns,name:pa,encode:Rs,digest:ma};var ln={};q(ln,{sha256:()=>Ve,sha512:()=>wa});function cn({name:r,code:t,encode:e}){return new an(r,t,e)}var an=class{name;code;encode;constructor(t,e,n){this.name=t,this.code=e,this.encode=n}digest(t){if(t instanceof Uint8Array){let e=this.encode(t);return e instanceof Uint8Array?xt(this.code,e):e.then(n=>xt(this.code,n))}else throw Error("Unknown type, must be binary type")}};function Ms(r){return async t=>new Uint8Array(await crypto.subtle.digest(r,t))}var Ve=cn({name:"sha2-256",code:18,encode:Ms("SHA-256")}),wa=cn({name:"sha2-512",code:19,encode:Ms("SHA-512")});function Fs(r,t){let{bytes:e,version:n}=r;switch(n){case 0:return ya(e,un(r),t??O.encoder);default:return xa(e,un(r),t??pt.encoder)}}var Bs=new WeakMap;function un(r){let t=Bs.get(r);if(t==null){let e=new Map;return Bs.set(r,e),e}return t}var H=class r{code;version;multihash;bytes;"/";constructor(t,e,n,s){this.code=e,this.version=t,this.multihash=n,this.bytes=s,this["/"]=s}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:t,multihash:e}=this;if(t!==ne)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(e.code!==Ea)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return r.createV0(e)}default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}toV1(){switch(this.version){case 0:{let{code:t,digest:e}=this.multihash,n=xt(t,e);return r.createV1(this.code,n)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(t){return r.equals(this,t)}static equals(t,e){let n=e;return n!=null&&t.code===n.code&&t.version===n.version&&Ps(t.multihash,n.multihash)}toString(t){return Fs(this,t)}toJSON(){return{"/":Fs(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(t){if(t==null)return null;let e=t;if(e instanceof r)return e;if(e["/"]!=null&&e["/"]===e.bytes||e.asCID===e){let{version:n,code:s,multihash:o,bytes:i}=e;return new r(n,s,o,i??Os(n,s,o.bytes))}else if(e[_a]===!0){let{version:n,multihash:s,code:o}=e,i=sn(s);return r.create(n,o,i)}else return null}static create(t,e,n){if(typeof e!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(t){case 0:{if(e!==ne)throw new Error(`Version 0 CID must use dag-pb (code: ${ne}) block encoding`);return new r(t,e,n,n.bytes)}case 1:{let s=Os(t,e,n.bytes);return new r(t,e,n,s)}default:throw new Error("Invalid version")}}static createV0(t){return r.create(0,ne,t)}static createV1(t,e){return r.create(1,t,e)}static decode(t){let[e,n]=r.decodeFirst(t);if(n.length!==0)throw new Error("Incorrect length");return e}static decodeFirst(t){let e=r.inspectBytes(t),n=e.size-e.multihashSize,s=st(t.subarray(n,n+e.multihashSize));if(s.byteLength!==e.multihashSize)throw new Error("Incorrect length");let o=s.subarray(e.multihashSize-e.digestSize),i=new Ft(e.multihashCode,e.digestSize,o,s);return[e.version===0?r.createV0(i):r.createV1(e.codec,i),t.subarray(e.size)]}static inspectBytes(t){let e=0,n=()=>{let[h,f]=re(t.subarray(e));return e+=f,h},s=n(),o=ne;if(s===18?(s=0,e=0):o=n(),s!==0&&s!==1)throw new RangeError(`Invalid CID version ${s}`);let i=e,a=n(),c=n(),l=e+c,u=l-i;return{version:s,codec:o,multihashCode:a,digestSize:c,multihashSize:u,size:l}}static parse(t,e){let[n,s]=ba(t,e),o=r.decode(s);if(o.version===0&&t[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return un(o).set(n,t),o}};function ba(r,t){switch(r[0]){case"Q":{let e=t??O;return[O.prefix,e.decode(`${O.prefix}${r}`)]}case O.prefix:{let e=t??O;return[O.prefix,e.decode(r)]}case pt.prefix:{let e=t??pt;return[pt.prefix,e.decode(r)]}case Yt.prefix:{let e=t??Yt;return[Yt.prefix,e.decode(r)]}default:{if(t==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[r[0],t.decode(r)]}}}function ya(r,t,e){let{prefix:n}=e;if(n!==O.prefix)throw Error(`Cannot string encode V0 in ${e.name} encoding`);let s=t.get(n);if(s==null){let o=e.encode(r).slice(1);return t.set(n,o),o}else return s}function xa(r,t,e){let{prefix:n}=e,s=t.get(n);if(s==null){let o=e.encode(r);return t.set(n,o),o}else return s}var ne=112,Ea=18;function Os(r,t,e){let n=Mt(r),s=n+Mt(t),o=new Uint8Array(s+e.byteLength);return Ut(r,o,0),Ut(t,o,n),o.set(e,s),o}var _a=Symbol.for("@ipld/js-cid/CID");var se={...rn,...Zr,...en,...Xr,...Qr,...Jr,...jr,...Yr,...tn,...Kr},Sh={...ln,...on};function $s(r,t,e,n){return{name:r,prefix:t,encoder:{name:r,prefix:t,encode:e},decoder:{decode:n}}}var zs=$s("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),hn=$s("ascii","a",r=>{let t="a";for(let e=0;e<r.length;e++)t+=String.fromCharCode(r[e]);return t},r=>{r=r.substring(1);let t=R(r.length);for(let e=0;e<r.length;e++)t[e]=r.charCodeAt(e);return t}),va={utf8:zs,"utf-8":zs,hex:se.base16,latin1:hn,ascii:hn,binary:hn,...se},He=va;function A(r,t="utf8"){let e=He[t];if(e==null)throw new Error(`Unsupported encoding "${t}"`);return e.decoder.decode(`${e.prefix}${r}`)}function fn(r){let t=r??8192,e=t>>>1,n,s=t;return function(i){if(i<1||i>e)return R(i);s+i>t&&(n=R(t),s=0);let a=n.subarray(s,s+=i);return(s&7)!==0&&(s=(s|7)+1),a}}var Et=class{fn;len;next;val;constructor(t,e,n){this.fn=t,this.len=e,this.next=void 0,this.val=n}};function dn(){}var mn=class{head;tail;len;next;constructor(t){this.head=t.head,this.tail=t.tail,this.len=t.len,this.next=t.states}},Sa=fn();function Ia(r){return globalThis.Buffer!=null?R(r):Sa(r)}var ie=class{len;head;tail;states;constructor(){this.len=0,this.head=new Et(dn,0,0),this.tail=this.head,this.states=null}_push(t,e,n){return this.tail=this.tail.next=new Et(t,e,n),this.len+=e,this}uint32(t){return this.len+=(this.tail=this.tail.next=new gn((t=t>>>0)<128?1:t<16384?2:t<2097152?3:t<268435456?4:5,t)).len,this}int32(t){return t<0?this._push(We,10,V.fromNumber(t)):this.uint32(t)}sint32(t){return this.uint32((t<<1^t>>31)>>>0)}uint64(t){let e=V.fromBigInt(t);return this._push(We,e.length(),e)}uint64Number(t){return this._push(Pt,_(t),t)}uint64String(t){return this.uint64(BigInt(t))}int64(t){return this.uint64(t)}int64Number(t){return this.uint64Number(t)}int64String(t){return this.uint64String(t)}sint64(t){let e=V.fromBigInt(t).zzEncode();return this._push(We,e.length(),e)}sint64Number(t){let e=V.fromNumber(t).zzEncode();return this._push(We,e.length(),e)}sint64String(t){return this.sint64(BigInt(t))}bool(t){return this._push(pn,1,t?1:0)}fixed32(t){return this._push(oe,4,t>>>0)}sfixed32(t){return this.fixed32(t)}fixed64(t){let e=V.fromBigInt(t);return this._push(oe,4,e.lo)._push(oe,4,e.hi)}fixed64Number(t){let e=V.fromNumber(t);return this._push(oe,4,e.lo)._push(oe,4,e.hi)}fixed64String(t){return this.fixed64(BigInt(t))}sfixed64(t){return this.fixed64(t)}sfixed64Number(t){return this.fixed64Number(t)}sfixed64String(t){return this.fixed64String(t)}float(t){return this._push(ps,4,t)}double(t){return this._push(gs,8,t)}bytes(t){let e=t.length>>>0;return e===0?this._push(pn,1,0):this.uint32(e)._push(Aa,e,t)}string(t){let e=ys(t);return e!==0?this.uint32(e)._push(zr,e,t):this._push(pn,1,0)}fork(){return this.states=new mn(this),this.head=this.tail=new Et(dn,0,0),this.len=0,this}reset(){return this.states!=null?(this.head=this.states.head,this.tail=this.states.tail,this.len=this.states.len,this.states=this.states.next):(this.head=this.tail=new Et(dn,0,0),this.len=0),this}ldelim(){let t=this.head,e=this.tail,n=this.len;return this.reset().uint32(n),n!==0&&(this.tail.next=t.next,this.tail=e,this.len+=n),this}finish(){let t=this.head.next,e=Ia(this.len),n=0;for(;t!=null;)t.fn(t.val,e,n),n+=t.len,t=t.next;return e}};function pn(r,t,e){t[e]=r&255}function ka(r,t,e){for(;r>127;)t[e++]=r&127|128,r>>>=7;t[e]=r}var gn=class extends Et{next;constructor(t,e){super(ka,t,e),this.next=void 0}};function We(r,t,e){for(;r.hi!==0;)t[e++]=r.lo&127|128,r.lo=(r.lo>>>7|r.hi<<25)>>>0,r.hi>>>=7;for(;r.lo>127;)t[e++]=r.lo&127|128,r.lo=r.lo>>>7;t[e++]=r.lo}function oe(r,t,e){t[e]=r&255,t[e+1]=r>>>8&255,t[e+2]=r>>>16&255,t[e+3]=r>>>24}function Aa(r,t,e){t.set(r,e)}globalThis.Buffer!=null&&(ie.prototype.bytes=function(r){let t=r.length>>>0;return this.uint32(t),t>0&&this._push(Ta,t,r),this},ie.prototype.string=function(r){let t=globalThis.Buffer.byteLength(r);return this.uint32(t),t>0&&this._push(Da,t,r),this});function Ta(r,t,e){t.set(r,e)}function Da(r,t,e){r.length<40?zr(r,t,e):t.utf8Write!=null?t.utf8Write(r,e):t.set(A(r),e)}function wn(){return new ie}function _t(r,t){let e=wn();return t.encode(r,e,{lengthDelimited:!1}),e.finish()}var Ot;(function(r){r[r.VARINT=0]="VARINT",r[r.BIT64=1]="BIT64",r[r.LENGTH_DELIMITED=2]="LENGTH_DELIMITED",r[r.START_GROUP=3]="START_GROUP",r[r.END_GROUP=4]="END_GROUP",r[r.BIT32=5]="BIT32"})(Ot||(Ot={}));function Ge(r,t,e,n){return{name:r,type:t,encode:e,decode:n}}function Xe(r){function t(s){if(r[s.toString()]==null)throw new Error("Invalid enum value");return r[s]}let e=function(o,i){let a=t(o);i.int32(a)},n=function(o){let i=o.int32();return t(i)};return Ge("enum",Ot.VARINT,e,n)}function vt(r,t){return Ge("message",Ot.LENGTH_DELIMITED,r,t)}var zt=class extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"};var I;(function(r){r.WantBlock="WantBlock",r.WantHave="WantHave"})(I||(I={}));var bn;(function(r){r[r.WantBlock=0]="WantBlock",r[r.WantHave=1]="WantHave"})(bn||(bn={}));(function(r){r.codec=()=>Xe(bn)})(I||(I={}));var $t;(function(r){let t;r.codec=()=>(t==null&&(t=vt((e,n,s={})=>{s.lengthDelimited!==!1&&n.fork(),e.cid!=null&&e.cid.byteLength>0&&(n.uint32(10),n.bytes(e.cid)),e.priority!=null&&e.priority!==0&&(n.uint32(16),n.int32(e.priority)),e.cancel!=null&&(n.uint32(24),n.bool(e.cancel)),e.wantType!=null&&(n.uint32(32),I.codec().encode(e.wantType,n)),e.sendDontHave!=null&&(n.uint32(40),n.bool(e.sendDontHave)),s.lengthDelimited!==!1&&n.ldelim()},(e,n,s={})=>{let o={cid:N(0),priority:0},i=n==null?e.len:e.pos+n;for(;e.pos<i;){let a=e.uint32();switch(a>>>3){case 1:{o.cid=e.bytes();break}case 2:{o.priority=e.int32();break}case 3:{o.cancel=e.bool();break}case 4:{o.wantType=I.codec().decode(e);break}case 5:{o.sendDontHave=e.bool();break}default:{e.skipType(a&7);break}}}return o})),t),r.encode=e=>_t(e,r.codec()),r.decode=(e,n)=>yt(e,r.codec(),n)})($t||($t={}));var Qe;(function(r){let t;r.codec=()=>(t==null&&(t=vt((e,n,s={})=>{if(s.lengthDelimited!==!1&&n.fork(),e.entries!=null)for(let o of e.entries)n.uint32(10),$t.codec().encode(o,n);e.full!=null&&(n.uint32(16),n.bool(e.full)),s.lengthDelimited!==!1&&n.ldelim()},(e,n,s={})=>{let o={entries:[]},i=n==null?e.len:e.pos+n;for(;e.pos<i;){let a=e.uint32();switch(a>>>3){case 1:{if(s.limits?.entries!=null&&o.entries.length===s.limits.entries)throw new zt('Decode error - map field "entries" had too many elements');o.entries.push($t.codec().decode(e,e.uint32(),{limits:s.limits?.entries$}));break}case 2:{o.full=e.bool();break}default:{e.skipType(a&7);break}}}return o})),t),r.encode=e=>_t(e,r.codec()),r.decode=(e,n)=>yt(e,r.codec(),n)})(Qe||(Qe={}));var qt;(function(r){let t;r.codec=()=>(t==null&&(t=vt((e,n,s={})=>{s.lengthDelimited!==!1&&n.fork(),e.prefix!=null&&e.prefix.byteLength>0&&(n.uint32(10),n.bytes(e.prefix)),e.data!=null&&e.data.byteLength>0&&(n.uint32(18),n.bytes(e.data)),s.lengthDelimited!==!1&&n.ldelim()},(e,n,s={})=>{let o={prefix:N(0),data:N(0)},i=n==null?e.len:e.pos+n;for(;e.pos<i;){let a=e.uint32();switch(a>>>3){case 1:{o.prefix=e.bytes();break}case 2:{o.data=e.bytes();break}default:{e.skipType(a&7);break}}}return o})),t),r.encode=e=>_t(e,r.codec()),r.decode=(e,n)=>yt(e,r.codec(),n)})(qt||(qt={}));var G;(function(r){r.HaveBlock="HaveBlock",r.DoNotHaveBlock="DoNotHaveBlock"})(G||(G={}));var Ze;(function(r){r[r.HaveBlock=0]="HaveBlock",r[r.DoNotHaveBlock=1]="DoNotHaveBlock"})(Ze||(Ze={}));(function(r){r.codec=()=>Xe(Ze)})(G||(G={}));var Vt;(function(r){let t;r.codec=()=>(t==null&&(t=vt((e,n,s={})=>{s.lengthDelimited!==!1&&n.fork(),e.cid!=null&&e.cid.byteLength>0&&(n.uint32(10),n.bytes(e.cid)),e.type!=null&&Ze[e.type]!==0&&(n.uint32(16),G.codec().encode(e.type,n)),s.lengthDelimited!==!1&&n.ldelim()},(e,n,s={})=>{let o={cid:N(0),type:G.HaveBlock},i=n==null?e.len:e.pos+n;for(;e.pos<i;){let a=e.uint32();switch(a>>>3){case 1:{o.cid=e.bytes();break}case 2:{o.type=G.codec().decode(e);break}default:{e.skipType(a&7);break}}}return o})),t),r.encode=e=>_t(e,r.codec()),r.decode=(e,n)=>yt(e,r.codec(),n)})(Vt||(Vt={}));var St;(function(r){let t;r.codec=()=>(t==null&&(t=vt((e,n,s={})=>{if(s.lengthDelimited!==!1&&n.fork(),e.wantlist!=null&&(n.uint32(10),Qe.codec().encode(e.wantlist,n)),e.blocks!=null)for(let o of e.blocks)n.uint32(26),qt.codec().encode(o,n);if(e.blockPresences!=null)for(let o of e.blockPresences)n.uint32(34),Vt.codec().encode(o,n);e.pendingBytes!=null&&e.pendingBytes!==0&&(n.uint32(40),n.int32(e.pendingBytes)),s.lengthDelimited!==!1&&n.ldelim()},(e,n,s={})=>{let o={blocks:[],blockPresences:[],pendingBytes:0},i=n==null?e.len:e.pos+n;for(;e.pos<i;){let a=e.uint32();switch(a>>>3){case 1:{o.wantlist=Qe.codec().decode(e,e.uint32(),{limits:s.limits?.wantlist});break}case 3:{if(s.limits?.blocks!=null&&o.blocks.length===s.limits.blocks)throw new zt('Decode error - map field "blocks" had too many elements');o.blocks.push(qt.codec().decode(e,e.uint32(),{limits:s.limits?.blocks$}));break}case 4:{if(s.limits?.blockPresences!=null&&o.blockPresences.length===s.limits.blockPresences)throw new zt('Decode error - map field "blockPresences" had too many elements');o.blockPresences.push(Vt.codec().decode(e,e.uint32(),{limits:s.limits?.blockPresences$}));break}case 5:{o.pendingBytes=e.int32();break}default:{e.skipType(a&7);break}}}return o})),t),r.encode=e=>_t(e,r.codec()),r.decode=(e,n)=>yt(e,r.codec(),n)})(St||(St={}));function qs(r,t){for(let[e,n]of t.wantlist.entries()){let s=r.wantlist.get(e);s!=null&&(s.priority>n.priority&&(n.priority=s.priority),n.cancel=n.cancel??s.cancel,n.wantType=n.wantType??s.wantType,n.sendDontHave=n.sendDontHave??s.sendDontHave),r.wantlist.set(e,n)}for(let[e,n]of t.blockPresences.entries())r.blockPresences.set(e,n);for(let[e,n]of t.blocks.entries())r.blocks.set(e,n);return t.full&&!r.full&&(r.full=!0),r}var Ke=class extends Error{static name="BlockTooLargeError";constructor(t="Block too large"){super(t),this.name="BlockTooLargeError"}};var La=4193648,Ca=La+16;function*Vs(r,t){let e=[...r.wantlist.values()],n=[...r.blockPresences.values()],s=[...r.blocks.values()],o=0,i=0,a=0,c=!1;for(;;){let l={wantlist:{full:r.full??!1,entries:[]},blockPresences:[],blocks:[],pendingBytes:0},u=St.encode(l).byteLength,{added:h,hasMore:f,newSize:E}=yn(s,l.blocks,a,t,u,Pa);a+=h,u=E;let d=f;({added:h,hasMore:f,newSize:E}=yn(n,l.blockPresences,i,t,u,Na)),i+=h,u=E;let x=f;if({added:h,hasMore:f,newSize:E}=yn(e,l.wantlist.entries,o,t,u,Ra),o+=h,u=E,c=!d&&!x&&!f,c||(l.wantlist.full=!1),yield St.encode(l),c)break}}function yn(r,t,e,n,s,o){let i=0,a=!1;for(let c=e;c<r.length;c++){let l=r[c],u=o(l);if(u>Ca)throw new Ke("Cannot send block as after encoding it is over the max message size");let h=s+u;if(h>n){a=!0;break}t.push(l),i++,s=h}return{hasMore:a,added:i,newSize:s}}function Pa(r){return xn(3,qt.encode(r))}function Na(r){return xn(4,Vt.encode(r))}function Ra(r){return xn(1,$t.encode(r))}function xn(r,t){let e=_(r),n=_(t.byteLength);return e+n+t.byteLength}var Je=class extends et{log;libp2p;routing;protocols;running;maxInboundStreams;maxOutboundStreams;messageReceiveTimeout;registrarIds;metrics;sendQueue;runOnLimitedConnections;maxOutgoingMessageSize;maxIncomingMessageSize;constructor(t,e={}){super(),this.log=t.logger.forComponent("helia:bitswap:network"),this.libp2p=t.libp2p,this.routing=t.routing,this.protocols=e.protocols??[jt],this.registrarIds=[],this.running=!1,this._onStream=this._onStream.bind(this),this.maxInboundStreams=e.maxInboundStreams??1024,this.maxOutboundStreams=e.maxOutboundStreams??1024,this.messageReceiveTimeout=e.messageReceiveTimeout??5e3,this.runOnLimitedConnections=e.runOnLimitedConnections??!1,this.maxIncomingMessageSize=e.maxIncomingMessageSize??4194304,this.maxOutgoingMessageSize=e.maxOutgoingMessageSize??e.maxIncomingMessageSize??4194304,this.metrics={blocksSent:t.metrics?.registerCounter("helia_bitswap_sent_blocks_total"),dataSent:t.metrics?.registerCounter("helia_bitswap_sent_data_bytes_total")},this.sendQueue=new Pe({concurrency:e.messageSendConcurrency??50,metrics:t.metrics,metricName:"helia_bitswap_message_send_queue"}),this.sendQueue.addEventListener("error",n=>{this.log.error("error sending wantlist to peer",n.detail)})}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 t={onConnect:e=>{this.safeDispatchEvent("peer:connected",{detail:e})},onDisconnect:e=>{this.safeDispatchEvent("peer:disconnected",{detail:e})}};this.registrarIds=[];for(let e of this.protocols)this.registrarIds.push(await this.libp2p.register(e,t));this.libp2p.getConnections().forEach(e=>{this.safeDispatchEvent("peer:connected",{detail:e.remotePeer})})}async stop(){if(this.running=!1,await this.libp2p.unhandle(this.protocols),this.registrarIds!=null){for(let t of this.registrarIds)this.libp2p.unregister(t);this.registrarIds=[]}}_onStream(t){if(!this.running)return;let{stream:e,connection:n}=t;Promise.resolve().then(async()=>{this.log("incoming new bitswap %s stream from %p",e.protocol,n.remotePeer);let s=()=>{e.status==="open"?e.abort(new ve(`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",s),await e.closeWrite(),await Fr(e,i=>Jt(i,{maxDataLength:this.maxIncomingMessageSize}),async i=>{for await(let a of i)try{let c=St.decode(a);this.log("incoming new bitswap %s message from %p on stream",e.protocol,n.remotePeer,e.id),this.safeDispatchEvent("bitswap:message",{detail:{peer:n.remotePeer,message:c}}),o.removeEventListener("abort",s),o=AbortSignal.timeout(this.messageReceiveTimeout),o.addEventListener("abort",s)}catch(c){this.log.error("error reading incoming bitswap message from %p on stream",n.remotePeer,e.id,c),e.abort(c);break}})}).catch(s=>{this.log.error("error handling incoming stream from %p",n.remotePeer,s),e.abort(s)})}async*findProviders(t,e){e?.onProgress?.(new rt("bitswap:network:find-providers",t));for await(let n of this.routing.findProviders(t,e))await this.libp2p.isDialable(n.multiaddrs,{runOnLimitedConnection:this.runOnLimitedConnections})&&(yield n)}async findAndConnect(t,e){e?.providers!=null&&await Promise.all(e.providers.map(async n=>this.connectTo(n).catch(s=>{this.log.error("could not connect to supplied provider - %e",s)}))),await Ar(cs(ds(this.findProviders(t,e),e?.maxProviders??3),async n=>this.connectTo(n.id,e))).catch(n=>{this.log.error(n)})}async sendMessage(t,e,n){if(!this.running)throw new Error("network isn't running");let s=this.sendQueue.queue.find(o=>t.equals(o.options.peerId)&&o.status==="queued");if(s!=null){s.options.message=qs(s.options.message,e),await s.join({signal:n?.signal});return}await this.sendQueue.add(async o=>{let i=o?.message;if(i==null)throw new Ee("No message to send");this.log("sendMessage to %p",t),o?.onProgress?.(new rt("bitswap:network:send-wantlist",t));let a=await this.libp2p.dialProtocol(t,jt,o);await a.closeRead();try{await Fr(Vs(i,this.maxOutgoingMessageSize),c=>ze(c),a),await a.close(o)}catch(c){o?.onProgress?.(new rt("bitswap:network:send-wantlist:error",{peer:t,error:c})),this.log.error("error sending message to %p",t,c),a.abort(c)}this._updateSentStats(i.blocks)},{peerId:t,signal:n?.signal,message:e})}async connectTo(t,e){if(!this.running)throw new Se("Network isn't running");e?.onProgress?.(new rt("bitswap:network:dial",t));let[n]=await Promise.all([this.libp2p.dial(t,e),K(this.libp2p,"peer:identify",e?.signal,{filter:s=>{if(!s.detail.peerId.equals(t))return!1;if(s.detail.protocols.includes(jt))return!0;throw new _e(`${t} did not support ${jt}`)}})]);return n}_updateSentStats(t){let e=0;for(let n of t.values())e+=n.data.byteLength;this.metrics.dataSent?.increment(e),this.metrics.blocksSent?.increment(t.size)}};function k(r,t="utf8"){let e=He[t];if(e==null)throw new Error(`Unsupported encoding "${t}"`);return e.encoder.encode(r).substring(1)}function je(r,t){let e={[Symbol.iterator]:()=>e,next:()=>{let n=r.next(),s=n.value;return n.done===!0||s==null?{done:!0,value:void 0}:{done:!1,value:t(s)}}};return e}var ae=class{map;constructor(t){if(this.map=new Map,t!=null)for(let[e,n]of t.entries())this.map.set(e.toString(),{key:e,value:n})}[Symbol.iterator](){return this.entries()}clear(){this.map.clear()}delete(t){return this.map.delete(t.toString())}entries(){return je(this.map.entries(),t=>[t[1].key,t[1].value])}forEach(t){this.map.forEach((e,n)=>{t(e.value,e.key,this)})}get(t){return this.map.get(t.toString())?.value}has(t){return this.map.has(t.toString())}set(t,e){this.map.set(t.toString(),{key:t,value:e})}keys(){return je(this.map.values(),t=>t.key)}values(){return je(this.map.values(),t=>t.value)}get size(){return this.map.size}};var En={32:16777619n,64:1099511628211n,128:309485009821345068724781371n,256:374144419156711147060143317175368453031918731002211n,512:35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759n,1024:5016456510113118655434598811035278955030765345404790744303017523831112055108147451509157692220295382716162651878526895249385292291816524375083746691371804094271873160484737966720260389217684476157468082573n},Ws={32:2166136261n,64:14695981039346656037n,128:144066263297769815596495629667062367629n,256:100029257958052580907070968620625704837092796014241193945225284501741471925557n,512:9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785n,1024:14197795064947621068722070641403218320880622795441933960878474914617582723252296732303717722150864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915n},Gs=new globalThis.TextEncoder;function Va(r,t){let e=En[t],n=Ws[t];for(let s=0;s<r.length;s++)n^=BigInt(r[s]),n=BigInt.asUintN(t,n*e);return n}function Ha(r,t,e){if(e.length===0)throw new Error("The `utf8Buffer` option must have a length greater than zero");let n=En[t],s=Ws[t],o=r;for(;o.length>0;){let i=Gs.encodeInto(o,e);o=o.slice(i.read);for(let a=0;a<i.written;a++)s^=BigInt(e[a]),s=BigInt.asUintN(t,s*n)}return s}function _n(r,{size:t=32,utf8Buffer:e}={}){if(!En[t])throw new Error("The `size` option must be one of 32, 64, 128, 256, 512, or 1024");if(typeof r=="string"){if(e)return Ha(r,t,e);r=Gs.encode(r)}return Va(r,t)}var ce={hash:r=>Number(_n(r,{size:32})),hashV:(r,t)=>Wa(ce.hash(r,t))};function Wa(r){let t=r.toString(16);return t.length%2===1&&(t=`0${t}`),A(t,"base16")}var vn=64,Y=class{fp;h;seed;constructor(t,e,n,s=2){if(s>vn)throw new TypeError("Invalid Fingerprint Size");let o=e.hashV(t,n),i=N(s);for(let a=0;a<i.length;a++)i[a]=o[a];i.length===0&&(i[0]=7),this.fp=i,this.h=e,this.seed=n}hash(){return this.h.hash(this.fp,this.seed)}equals(t){return t?.fp instanceof Uint8Array?J(this.fp,t.fp):!1}};function It(r,t){return Math.floor(Math.random()*(t-r))+r}var kt=class{contents;constructor(t){this.contents=new Array(t).fill(null)}has(t){if(!(t instanceof Y))throw new TypeError("Invalid Fingerprint");return this.contents.some(e=>t.equals(e))}add(t){if(!(t instanceof Y))throw new TypeError("Invalid Fingerprint");for(let e=0;e<this.contents.length;e++)if(this.contents[e]==null)return this.contents[e]=t,!0;return!0}swap(t){if(!(t instanceof Y))throw new TypeError("Invalid Fingerprint");let e=It(0,this.contents.length-1),n=this.contents[e];return this.contents[e]=t,n}remove(t){if(!(t instanceof Y))throw new TypeError("Invalid Fingerprint");let e=this.contents.findIndex(n=>t.equals(n));return e>-1?(this.contents[e]=null,!0):!1}};var Ga=500,le=class{bucketSize;filterSize;fingerprintSize;buckets;count;hash;seed;constructor(t){this.filterSize=t.filterSize,this.bucketSize=t.bucketSize??4,this.fingerprintSize=t.fingerprintSize??2,this.count=0,this.buckets=[],this.hash=t.hash??ce,this.seed=t.seed??It(0,Math.pow(2,10))}add(t){typeof t=="string"&&(t=A(t));let e=new Y(t,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(t,this.seed)%this.filterSize,s=(n^e.hash())%this.filterSize;if(this.buckets[n]==null&&(this.buckets[n]=new kt(this.bucketSize)),this.buckets[s]==null&&(this.buckets[s]=new kt(this.bucketSize)),this.buckets[n].add(e)||this.buckets[s].add(e))return this.count++,!0;let o=[n,s],i=o[It(0,o.length-1)];this.buckets[i]==null&&(this.buckets[i]=new kt(this.bucketSize));for(let a=0;a<Ga;a++){let c=this.buckets[i].swap(e);if(c!=null&&(i=(i^c.hash())%this.filterSize,this.buckets[i]==null&&(this.buckets[i]=new kt(this.bucketSize)),this.buckets[i].add(c)))return this.count++,!0}return!1}has(t){typeof t=="string"&&(t=A(t));let e=new Y(t,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(t,this.seed)%this.filterSize,s=this.buckets[n]?.has(e)??!1;if(s)return s;let o=(n^e.hash())%this.filterSize;return this.buckets[o]?.has(e)??!1}remove(t){typeof t=="string"&&(t=A(t));let e=new Y(t,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(t,this.seed)%this.filterSize,s=this.buckets[n]?.remove(e)??!1;if(s)return this.count--,s;let o=(n^e.hash())%this.filterSize,i=this.buckets[o]?.remove(e)??!1;return i&&this.count--,i}get reliable(){return Math.floor(100*(this.count/this.filterSize))<=90}},Xa={1:.5,2:.84,4:.95,8:.98};function Qa(r=.001){return r>.002?2:r>1e-5?4:8}function Xs(r,t=.001){let e=Qa(t),n=Xa[e],s=Math.round(r/n),o=Math.min(Math.ceil(Math.log2(1/t)+Math.log2(2*e)),vn);return{filterSize:s,bucketSize:e,fingerprintSize:o}}var Ye=class{filterSize;bucketSize;fingerprintSize;scale;filterSeries;hash;seed;constructor(t){this.bucketSize=t.bucketSize??4,this.filterSize=t.filterSize??(1<<18)/this.bucketSize,this.fingerprintSize=t.fingerprintSize??2,this.scale=t.scale??2,this.hash=t.hash??ce,this.seed=t.seed??It(0,Math.pow(2,10)),this.filterSeries=[new le({filterSize:this.filterSize,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed})]}add(t){if(typeof t=="string"&&(t=A(t)),this.has(t))return!0;let e=this.filterSeries.find(n=>n.reliable);if(e==null){let n=this.filterSize*Math.pow(this.scale,this.filterSeries.length);e=new le({filterSize:n,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed}),this.filterSeries.push(e)}return e.add(t)}has(t){typeof t=="string"&&(t=A(t));for(let e=0;e<this.filterSeries.length;e++)if(this.filterSeries[e].has(t))return!0;return!1}remove(t){typeof t=="string"&&(t=A(t));for(let e=0;e<this.filterSeries.length;e++)if(this.filterSeries[e].remove(t))return!0;return!1}get count(){return this.filterSeries.reduce((t,e)=>t+e.count,0)}};function Sn(r,t=.001,e){return new Ye({...Xs(r,t),...e??{}})}var In=class extends ae{metric;constructor(t){super();let{name:e,metrics:n}=t;this.metric=n.registerMetric(e),this.updateComponentMetric()}set(t,e){return super.set(t,e),this.updateComponentMetric(),this}delete(t){let e=super.delete(t);return this.updateComponentMetric(),e}clear(){super.clear(),this.updateComponentMetric()}updateComponentMetric(){this.metric.update(this.size)}};function ue(r){let{name:t,metrics:e}=r,n;return e!=null?n=new In({name:t,metrics:e}):n=new ae,n}var it=class{full;pendingBytes;wantlist;blocks;blockPresences;constructor(t=!1,e=0){this.full=t,this.wantlist=new Map,this.blocks=new Map,this.blockPresences=new Map,this.pendingBytes=0}addWantlistEntry(t,e){let n=ot.encode(t.multihash.bytes);this.wantlist.set(n,e)}addBlockPresence(t,e){let n=ot.encode(t.multihash.bytes);this.blockPresences.set(n,e)}addBlock(t,e){let n=ot.encode(t.multihash.bytes);this.blocks.set(n,e)}};function Za(r){let t=new Uint8Array(r.reduce((n,s)=>n+_(s),0)),e=0;for(let n of r)t=Ne(n,t,e),e+=_(n);return t}var Qs=Za;function kn(r){return Qs([r.version,r.code,r.multihash.code,r.multihash.digest.byteLength])}var tr=class{peerId;blockstore;network;wants;exchangeCount;bytesSent;bytesReceived;lastExchange;maxSizeReplaceHasWithBlock;log;constructor(t,e){this.peerId=t.peerId,this.blockstore=t.blockstore,this.network=t.network,this.wants=new Map,this.log=t.logger.forComponent(`helia:bitswap:ledger:${t.peerId}`),this.exchangeCount=0,this.bytesSent=0,this.bytesReceived=0,this.maxSizeReplaceHasWithBlock=e.maxSizeReplaceHasWithBlock??1024}sentBytes(t){this.exchangeCount++,this.lastExchange=new Date().getTime(),this.bytesSent+=t}receivedBytes(t){this.exchangeCount++,this.lastExchange=new Date().getTime(),this.bytesReceived+=t}debtRatio(){return this.bytesSent/(this.bytesReceived+1)}async sendBlocksToPeer(t){let e=new it,n=new Set;for(let[s,o]of this.wants.entries())try{let i=await this.blockstore.get(o.cid,t);o.wantType===I.WantHave?i.byteLength<this.maxSizeReplaceHasWithBlock?(this.log("sending have and block for %c",o.cid),n.add(s),e.addBlock(o.cid,{data:i,prefix:kn(o.cid)})):(this.log("sending have for %c",o.cid),e.addBlockPresence(o.cid,{cid:o.cid.bytes,type:G.HaveBlock})):(this.log("sending block for %c",o.cid),n.add(s),e.addBlock(o.cid,{data:i,prefix:kn(o.cid)}))}catch(i){if(i.name!=="NotFoundError")throw i;if(this.log("do not have block for %c",o.cid),!o.sendDontHave||o.sentDoNotHave===!0)continue;o.sentDoNotHave=!0,e.addBlockPresence(o.cid,{cid:o.cid.bytes,type:G.DoNotHaveBlock})}if(e.blocks.size>0||e.blockPresences.size>0){this.log("sending message"),await this.network.sendMessage(this.peerId,e,t),this.log("sent message"),this.sentBytes([...e.blocks.values()].reduce((s,o)=>s+o.data.byteLength,0));for(let s of n)this.wants.delete(s)}}};var er=class{blockstore;network;ledgerMap;maxSizeReplaceHasWithBlock;log;logger;constructor(t,e={}){this.blockstore=t.blockstore,this.network=t.network,this.maxSizeReplaceHasWithBlock=e.maxSizeReplaceHasWithBlock,this.log=t.logger.forComponent("helia:bitswap:peer-want-lists"),this.logger=t.logger,this.ledgerMap=ue({name:"helia_bitswap_ledger_map",metrics:t.metrics}),this.network.addEventListener("bitswap:message",n=>{this.receiveMessage(n.detail.peer,n.detail.message).catch(s=>{this.log.error("error receiving bitswap message from %p",n.detail.peer,s)})}),this.network.addEventListener("peer:disconnected",n=>{this.peerDisconnected(n.detail)})}ledgerForPeer(t){let e=this.ledgerMap.get(t);if(e!=null)return{peer:e.peerId,value:e.debtRatio(),sent:e.bytesSent,received:e.bytesReceived,exchanged:e.exchangeCount}}wantListForPeer(t){let e=this.ledgerMap.get(t);if(e!=null)return[...e.wants.values()]}peers(){return Array.from(this.ledgerMap.values()).map(t=>t.peerId)}async receiveMessage(t,e){let n=this.ledgerMap.get(t);if(n==null&&(n=new tr({peerId:t,blockstore:this.blockstore,network:this.network,logger:this.logger},{maxSizeReplaceHasWithBlock:this.maxSizeReplaceHasWithBlock}),this.ledgerMap.set(t,n)),n.receivedBytes(e.blocks?.reduce((s,o)=>s+o.data.byteLength,0)??0),e.wantlist!=null){e.wantlist.full===!0&&n.wants.clear();for(let s of e.wantlist.entries){let o=H.decode(s.cid),i=k(o.multihash.bytes,"base64");s.cancel===!0?(this.log("peer %p cancelled want of block for %c",t,o),n.wants.delete(i)):(s.wantType===I.WantHave?this.log("peer %p wanted block presence for %c",t,o):this.log("peer %p wanted block for %c",t,o),n.wants.set(i,{cid:o,priority:s.priority,wantType:s.wantType??I.WantBlock,sendDontHave:s.sendDontHave??!1}))}}this.log("send blocks to peer"),await n.sendBlocksToPeer()}async receivedBlock(t,e){let n=k(t.multihash.bytes,"base64"),s=[];for(let o of this.ledgerMap.values())o.wants.has(n)&&s.push(o);await Promise.all(s.map(async o=>o.sendBlocksToPeer(e)))}peerDisconnected(t){this.ledgerMap.delete(t)}};var ja=rs(Ks(),1);var Ht;(function(r){r[r.A=1]="A",r[r.CNAME=5]="CNAME",r[r.TXT=16]="TXT",r[r.AAAA=28]="AAAA"})(Ht||(Ht={}));var rr=class extends Error{static name="InsufficientProvidersError";constructor(t="Insufficient providers found"){super(t),this.name="InsufficientProvidersError"}};var At=class extends et{initialPeerSearchComplete;requests;name;log;logger;minProviders;maxProviders;providers;evictionFilter;initialProviders;constructor(t,e){super(),this.name=e.name,this.logger=t.logger,this.log=t.logger.forComponent(this.name),this.requests=new Map,this.minProviders=e.minProviders??1,this.maxProviders=e.maxProviders??5,this.providers=[],this.evictionFilter=Sn(this.maxProviders),this.initialProviders=e.providers??[]}async retrieve(t,e={}){let n=ot.encode(t.multihash.bytes),s=this.requests.get(n);if(s!=null)return this.log("join existing request for %c",t),s;let o=P();if(this.requests.set(n,o.promise),this.providers.length===0){let u=!1;this.initialPeerSearchComplete==null&&(u=!0,this.log=this.logger.forComponent(`${this.name}:${t}`),this.initialPeerSearchComplete=this.findProviders(t,this.minProviders,e)),await this.initialPeerSearchComplete,u&&this.log("found initial session peers for %c",t)}let i=!1,a=new Ct({concurrency:this.maxProviders});a.addEventListener("error",()=>{}),a.addEventListener("failure",u=>{this.log.error("error querying provider %o, evicting from session",u.detail.job.options.provider,u.detail.error),this.evict(u.detail.job.options.provider)}),a.addEventListener("success",u=>{i=!0,o.resolve(u.detail.result)}),a.addEventListener("idle",()=>{if(i||e.signal?.aborted===!0){this.log.trace("session idle, found block");return}Promise.resolve().then(async()=>{this.log("no session peers had block for for %c, finding new providers",t);for(let u=0;u<this.minProviders&&this.providers.length!==0;u++){let h=this.providers[Math.floor(Math.random()*this.providers.length)];this.evict(h)}await this.findProviders(t,this.minProviders,e),this.log("found new providers re-retrieving %c",t),this.requests.delete(n),o.resolve(await this.retrieve(t,e))}).catch(u=>{this.log.error("could not find new providers for %c",t,u),o.reject(u)})});let c=u=>{a.add(async()=>this.queryProvider(t,u.detail,e),{provider:u.detail}).catch(h=>{e.signal?.aborted!==!0&&this.log.error("error retrieving session block for %c",t,h)})};this.addEventListener("provider",c),Promise.all([...this.providers].map(async u=>a.add(async()=>this.queryProvider(t,u,e),{provider:u}))).catch(u=>{e.signal?.aborted!==!0&&this.log.error("error retrieving session block for %c",t,u)});let l=()=>{o.reject(new Z(e.signal?.reason??"Session aborted")),a.abort()};e.signal?.addEventListener("abort",l);try{return await o.promise}finally{this.removeEventListener("provider",c),e.signal?.removeEventListener("abort",l),a.clear(),this.requests.delete(n)}}evict(t){this.evictionFilter.add(this.toEvictionKey(t));let e=this.providers.findIndex(n=>this.equals(n,t));e!==-1&&this.providers.splice(e,1)}isEvicted(t){return this.evictionFilter.has(this.toEvictionKey(t))}hasProvider(t){return!!(this.providers.find(e=>this.equals(e,t))!=null||this.isEvicted(t))}async findProviders(t,e,n){let s=P(),o=0;return Promise.resolve().then(async()=>{if(this.log("finding %d-%d new provider(s) for %c",e,this.maxProviders,t),this.initialProviders.length>0)for(;o<e&&this.initialProviders.length>0;){let i=this.initialProviders.pop();if(i==null)break;let a=await this.convertToProvider(i,n);if(n.signal?.aborted===!0)break;if(a!=null&&!this.hasProvider(a)&&(this.log("found %d/%d new providers",o,this.maxProviders),this.providers.push(a),this.safeDispatchEvent("provider",{detail:a}),o++,o===e&&(this.log("session is ready"),s.resolve()),this.providers.length===this.maxProviders)){this.log("found max session peers",o);break}}if(o<this.maxProviders)for await(let i of this.findNewProviders(t,n)){if(o===this.maxProviders||n.signal?.aborted===!0)break;if(!this.hasProvider(i)&&(this.log("found %d/%d new providers",o,this.maxProviders),this.providers.push(i),this.safeDispatchEvent("provider",{detail:i}),o++,o===e&&(this.log("session is ready"),s.resolve()),this.providers.length===this.maxProviders)){this.log("found max session peers",o);break}}if(this.log("found %d/%d new session peers",o,this.maxProviders),o<e)throw new rr(`Found ${o} of ${e} ${this.name} providers for ${t}`)}).catch(i=>{this.log.error("error searching routing for potential session peers for %c",t,i.errors??i),s.reject(i)}),s.promise}};var An=class extends At{wantList;network;libp2p;constructor(t,e){super(t,{...e,name:"helia:bitswap:session"}),this.wantList=t.wantList,this.network=t.network,this.libp2p=t.libp2p}async queryProvider(t,e,n){this.log("sending WANT-BLOCK for %c to %p",t,e);let s=await this.wantList.wantSessionBlock(t,e,n);if(this.log("%p %s %c",e,s.has?"has":"does not have",t),s.has&&s.block!=null)return s.block;throw new Error("Provider did not have block")}async*findNewProviders(t,e={}){for await(let n of this.network.findProviders(t,e))yield n.id}toEvictionKey(t){return t.toMultihash().bytes}equals(t,e){return t.equals(e)}async convertToProvider(t,e){return xe(t)?t:(await this.libp2p.dial(t,e)).remotePeer}};function Js(r,t){return new An(r,t)}var nr=class{blocksReceived;duplicateBlocksReceived;dataReceived;duplicateDataReceived;constructor(t){this.blocksReceived=t.metrics?.registerMetricGroup("helia_bitswap_received_blocks"),this.duplicateBlocksReceived=t.metrics?.registerMetricGroup("helia_bitswap_duplicate_received_blocks"),this.dataReceived=t.metrics?.registerMetricGroup("helia_bitswap_data_received_bytes"),this.duplicateDataReceived=t.metrics?.registerMetricGroup("helia_bitswap_duplicate_data_received_bytes")}updateBlocksReceived(t=1,e){let n={global:t};e!=null&&(n[e.toString()]=t),this.blocksReceived?.increment(n)}updateDuplicateBlocksReceived(t=1,e){let n={global:t};e!=null&&(n[e.toString()]=t),this.duplicateBlocksReceived?.increment(n)}updateDataReceived(t,e){let n={global:t};e!=null&&(n[e.toString()]=t),this.dataReceived?.increment(n)}updateDuplicateDataReceived(t,e){let n={global:t};e!=null&&(n[e.toString()]=t),this.duplicateDataReceived?.increment(n)}};var Tn=class extends Map{metric;constructor(t){super();let{name:e,metrics:n}=t;this.metric=n.registerMetric(e),this.updateComponentMetric()}set(t,e){return super.set(t,e),this.updateComponentMetric(),this}delete(t){let e=super.delete(t);return this.updateComponentMetric(),e}clear(){super.clear(),this.updateComponentMetric()}updateComponentMetric(){this.metric.update(this.size)}};function js(r){let{name:t,metrics:e}=r,n;return e!=null?n=new Tn({name:t,metrics:e}):n=new Map,n}function ec(r){if(!(r instanceof Uint8Array))throw new Error("arg needs to be a Uint8Array");let t=[];for(;r.length>0;){let e=gt(r);t.push(e),r=r.slice(_(e))}return t}var Ys=ec;var sr=class extends et{peers;wants;network;log;sendMessagesDelay;sendMessagesTimeout;hashLoader;sendingMessages;constructor(t,e={}){super(),this.peers=ue({name:"helia_bitswap_peers",metrics:t.metrics}),this.wants=js({name:"helia_bitswap_wantlist",metrics:t.metrics}),this.network=t.network,this.sendMessagesDelay=e.sendMessagesDelay??10,this.log=t.logger.forComponent("helia:bitswap:wantlist"),this.hashLoader=e.hashLoader,this.network.addEventListener("bitswap:message",n=>{this.receiveMessage(n.detail.peer,n.detail.message).catch(s=>{this.log.error("error receiving bitswap message from %p",n.detail.peer,s)})}),this.network.addEventListener("peer:connected",n=>{this.peerConnected(n.detail).catch(s=>{this.log.error("error processing newly connected bitswap peer %p",n.detail,s)})}),this.network.addEventListener("peer:disconnected",n=>{this.peerDisconnected(n.detail)})}async addEntry(t,e){let n=k(t.multihash.bytes,"base64"),s=this.wants.get(n);s==null&&(s={cid:t,priority:e.priority??1,wantType:e.wantType??I.WantBlock,cancel:!1,sendDontHave:!0},this.wants.set(n,s)),s.wantType===I.WantHave&&e.wantType===I.WantBlock&&(s.wantType=I.WantBlock),await this.sendMessagesDebounced();try{return e.wantType===I.WantBlock?(await K(this,"block",e?.signal,{filter:a=>J(t.multihash.digest,a.detail.cid.multihash.digest),errorMessage:"Want was aborted"})).detail:(await K(this,"presence",e?.signal,{filter:i=>J(t.multihash.digest,i.detail.cid.multihash.digest),errorMessage:"Want was aborted"})).detail}finally{e.signal?.aborted===!0&&(this.log("want for %c was aborted, cancelling want",t),s.cancel=!0,await this.sendMessagesDebounced())}}async sendMessagesDebounced(){await this.sendingMessages?.promise,clearTimeout(this.sendMessagesTimeout),this.sendMessagesTimeout=setTimeout(()=>{this.sendMessages().catch(t=>{this.log("error sending messages to peers",t)})},this.sendMessagesDelay)}async sendMessages(){this.sendingMessages=P(),await Promise.all([...this.peers.entries()].map(async([t,e])=>{let n=new Set,s=new it;for(let[o,i]of this.wants.entries())e.has(o)||i.cancel||(n.add(o),s.addWantlistEntry(i.cid,{cid:i.cid.bytes,priority:i.priority,wantType:i.wantType,cancel:i.cancel,sendDontHave:i.sendDontHave}));if(s.wantlist.size!==0)try{await this.network.sendMessage(t,s);for(let o of n)e.add(o)}catch(o){this.log.error("error sending full wantlist to new peer",o)}})).catch(t=>{this.log.error("error sending messages",t)});for(let[t,e]of this.wants)if(e.cancel){this.wants.delete(t);for(let n of this.peers.values())n.delete(t)}this.sendingMessages.resolve()}has(t){let e=k(t.multihash.bytes,"base64");return this.wants.has(e)}async wantSessionPresence(t,e,n={}){let s=new it;return s.addWantlistEntry(t,{cid:t.bytes,sendDontHave:!0,wantType:I.WantHave,priority:1}),await this.network.sendMessage(e,s),(await K(this,"presence",n.signal,{filter:i=>e.equals(i.detail.sender)&&J(t.multihash.digest,i.detail.cid.multihash.digest)})).detail}async wantBlock(t,e={}){return this.addEntry(t,{...e,wantType:I.WantBlock})}async wantSessionBlock(t,e,n={}){let s=new it;return s.addWantlistEntry(t,{cid:t.bytes,sendDontHave:!0,wantType:I.WantBlock,priority:1}),await this.network.sendMessage(e,s),(await K(this,"presence",n.signal,{filter:i=>e.equals(i.detail.sender)&&J(t.multihash.digest,i.detail.cid.multihash.digest)})).detail}async receivedBlock(t,e){let n=k(t.multihash.bytes,"base64"),s=this.wants.get(n);s!=null&&(s.cancel=!0,await this.sendMessagesDebounced())}async receiveMessage(t,e){this.log("received message from %p with %d blocks",t,e.blocks.length);let n=!1;for(let s of e.blocks){if(s.prefix==null||s.data==null)continue;let o=Ys(s.prefix),i=o[0],a=o[1],c=o[2],l=c===Ve.code?Ve:await this.hashLoader?.getHasher(c);if(l==null){this.log.error("unknown hash algorithm",c);continue}let u=l.digest(s.data);u.then!=null&&(u=await u);let h=H.create(i===0?0:1,a,u);this.log("received block from %p for %c",t,h),this.safeDispatchEvent("block",{detail:{sender:t,cid:h,block:s.data}}),this.safeDispatchEvent("presence",{detail:{sender:t,cid:h,has:!0,block:s.data}});let f=k(h.multihash.bytes,"base64"),E=this.wants.get(f);E!=null&&(E.cancel=!0,n=!0)}for(let{cid:s,type:o}of e.blockPresences){let i=H.decode(s);this.log("received %s from %p for %c",o,t,i),this.safeDispatchEvent("presence",{detail:{sender:t,cid:i,has:o===G.HaveBlock}})}n&&await this.sendMessagesDebounced()}async peerConnected(t){let e=new Set,n=new it(!0);for(let[s,o]of this.wants.entries())o.cancel||(e.add(s),n.addWantlistEntry(o.cid,{cid:o.cid.bytes,priority:1,wantType:I.WantBlock,cancel:!1,sendDontHave:!1}));if(n.wantlist.size===0){this.peers.set(t,e);return}try{await this.network.sendMessage(t,n),this.peers.set(t,e)}catch(s){this.log.error("error sending full wantlist to new peer %p",t,s)}}peerDisconnected(t){this.peers.delete(t)}start(){}stop(){this.peers.clear(),clearTimeout(this.sendMessagesTimeout)}};var or=class{log;logger;stats;network;blockstore;peerWantLists;wantList;libp2p;constructor(t,e={}){this.logger=t.logger,this.log=t.logger.forComponent("helia:bitswap"),this.blockstore=t.blockstore,this.libp2p=t.libp2p,this.stats=new nr(t),this.network=new Je(t,e),this.peerWantLists=new er({...t,network:this.network},e),this.wantList=new sr({...t,network:this.network},e)}createSession(t={}){return Js({wantList:this.wantList,network:this.network,logger:this.logger,libp2p:this.libp2p},t)}async want(t,e={}){let n=new AbortController,s=ns([n.signal,e.signal]);n.signal,this.network.findAndConnect(t,{...e,signal:s}).catch(o=>{n.signal.aborted||this.log.error("error during finding and connect for cid %c",t,o)});try{return(await this.wantList.wantBlock(t,{...e,signal:s})).block}finally{n.abort(),s.clear()}}async notify(t,e,n={}){await Promise.all([this.peerWantLists.receivedBlock(t,n),this.wantList.receivedBlock(t,n)])}getWantlist(){return[...this.wantList.wants.values()].filter(t=>!t.cancel).map(t=>({cid:t.cid,priority:t.priority,wantType:t.wantType}))}getPeerWantlist(t){return this.peerWantLists.wantListForPeer(t)}async start(){this.wantList.start(),await this.network.start()}async stop(){this.wantList.stop(),await this.network.stop()}};var to=(r,t={})=>new or(r,t);var Dn=class{bitswap;started;constructor(t,e={}){let{getHasher:n}=t;this.bitswap=to(t,{hashLoader:{getHasher:async s=>n(s)},...e}),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(t,e,n){await this.bitswap.notify(t,e,n)}async retrieve(t,e={}){return this.bitswap.want(t,e)}createSession(t){let e=this.bitswap.createSession(t);return{announce:async(n,s,o)=>{await this.bitswap.notify(n,s,o)},retrieve:async(n,s)=>e.retrieve(n,s)}}};function eo(r={}){return t=>new Dn(t,r)}var C=class extends Error{static name="InvalidMultiaddrError";name="InvalidMultiaddrError"},at=class extends Error{static name="ValidationError";name="ValidationError"},he=class extends Error{static name="InvalidParametersError";name="InvalidParametersError"},ir=class extends Error{static name="UnknownProtocolError";name="UnknownProtocolError"};var ar=class{index=0;input="";new(t){return this.index=0,this.input=t,this}readAtomically(t){let e=this.index,n=t();return n===void 0&&(this.index=e),n}parseWith(t){let e=t();if(this.index===this.input.length)return e}peekChar(){if(!(this.index>=this.input.length))return this.input[this.index]}readChar(){if(!(this.index>=this.input.length))return this.input[this.index++]}readGivenChar(t){return this.readAtomically(()=>{let e=this.readChar();if(e===t)return e})}readSeparator(t,e,n){return this.readAtomically(()=>{if(!(e>0&&this.readGivenChar(t)===void 0))return n()})}readNumber(t,e,n,s){return this.readAtomically(()=>{let o=0,i=0,a=this.peekChar();if(a===void 0)return;let c=a==="0",l=2**(8*s)-1;for(;;){let u=this.readAtomically(()=>{let h=this.readChar();if(h===void 0)return;let f=Number.parseInt(h,t);if(!Number.isNaN(f))return f});if(u===void 0)break;if(o*=t,o+=u,o>l||(i+=1,e!==void 0&&i>e))return}if(i!==0)return!n&&c&&i>1?void 0:o})}readIPv4Addr(){return this.readAtomically(()=>{let t=new Uint8Array(4);for(let e=0;e<t.length;e++){let n=this.readSeparator(".",e,()=>this.readNumber(10,3,!1,1));if(n===void 0)return;t[e]=n}return t})}readIPv6Addr(){let t=e=>{for(let n=0;n<e.length/2;n++){let s=n*2;if(n<e.length-3){let i=this.readSeparator(":",n,()=>this.readIPv4Addr());if(i!==void 0)return e[s]=i[0],e[s+1]=i[1],e[s+2]=i[2],e[s+3]=i[3],[s+4,!0]}let o=this.readSeparator(":",n,()=>this.readNumber(16,4,!0,2));if(o===void 0)return[s,!1];e[s]=o>>8,e[s+1]=o&255}return[e.length,!1]};return this.readAtomically(()=>{let e=new Uint8Array(16),[n,s]=t(e);if(n===16)return e;if(s||this.readGivenChar(":")===void 0||this.readGivenChar(":")===void 0)return;let o=new Uint8Array(14),i=16-(n+2),[a]=t(o.subarray(0,i));return e.set(o.subarray(0,a),16-a),e})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};var rc=45,nc=15,cr=new ar;function Ln(r){if(!(r.length>nc))return cr.new(r).parseWith(()=>cr.readIPv4Addr())}function Cn(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>rc))return cr.new(r).parseWith(()=>cr.readIPv6Addr())}function mt(r){return!!Ln(r)}function Wt(r){return!!Cn(r)}function Nn(r){return t=>k(t,r)}function Rn(r){return t=>A(t,r)}function Gt(r){return new DataView(r.buffer).getUint16(r.byteOffset).toString()}function Tt(r){let t=new ArrayBuffer(2);return new DataView(t).setUint16(0,typeof r=="string"?parseInt(r):r),new Uint8Array(t)}function no(r){let t=r.split(":");if(t.length!==2)throw new Error(`failed to parse onion addr: ["'${t.join('", "')}'"]' does not contain a port number`);if(t[0].length!==16)throw new Error(`failed to parse onion addr: ${t[0]} not a Tor onion address.`);let e=A(t[0],"base32"),n=parseInt(t[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let s=Tt(n);return ut([e,s],e.length+s.length)}function so(r){let t=r.split(":");if(t.length!==2)throw new Error(`failed to parse onion addr: ["'${t.join('", "')}'"]' does not contain a port number`);if(t[0].length!==56)throw new Error(`failed to parse onion addr: ${t[0]} not a Tor onion3 address.`);let e=pt.decode(`b${t[0]}`),n=parseInt(t[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let s=Tt(n);return ut([e,s],e.length+s.length)}function Un(r){let t=r.subarray(0,r.length-2),e=r.subarray(r.length-2),n=k(t,"base32"),s=Gt(e);return`${n}:${s}`}var Mn=function(r){r=r.toString().trim();let t=new Uint8Array(4);return r.split(/\./g).forEach((e,n)=>{let s=parseInt(e,10);if(isNaN(s)||s<0||s>255)throw new C("Invalid byte value in IP address");t[n]=s}),t},oo=function(r){let t=0;r=r.toString().trim();let e=r.split(":",8),n;for(n=0;n<e.length;n++){let o=mt(e[n]),i;o&&(i=Mn(e[n]),e[n]=k(i.subarray(0,2),"base16")),i!=null&&++n<8&&e.splice(n,0,k(i.subarray(2,4),"base16"))}if(e[0]==="")for(;e.length<8;)e.unshift("0");else if(e[e.length-1]==="")for(;e.length<8;)e.push("0");else if(e.length<8){for(n=0;n<e.length&&e[n]!=="";n++);let o=[n,1];for(n=9-e.length;n>0;n--)o.push("0");e.splice.apply(e,o)}let s=new Uint8Array(t+16);for(n=0;n<e.length;n++){e[n]===""&&(e[n]="0");let o=parseInt(e[n],16);if(isNaN(o)||o<0||o>65535)throw new C("Invalid byte value in IP address");s[t++]=o>>8&255,s[t++]=o&255}return s},io=function(r){if(r.byteLength!==4)throw new C("IPv4 address was incorrect length");let t=[];for(let e=0;e<r.byteLength;e++)t.push(r[e]);return t.join(".")},ao=function(r){if(r.byteLength!==16)throw new C("IPv6 address was incorrect length");let t=[];for(let n=0;n<r.byteLength;n+=2){let s=r[n],o=r[n+1],i=`${s.toString(16).padStart(2,"0")}${o.toString(16).padStart(2,"0")}`;t.push(i)}let e=t.join(":");try{let n=new URL(`http://[${e}]`);return n.hostname.substring(1,n.hostname.length-1)}catch{throw new C(`Invalid IPv6 address "${e}"`)}};function co(r){try{let t=new URL(`http://[${r}]`);return t.hostname.substring(1,t.hostname.length-1)}catch{throw new C(`Invalid IPv6 address "${r}"`)}}var Pn=Object.values(se).map(r=>r.decoder),sc=function(){let r=Pn[0].or(Pn[1]);return Pn.slice(2).forEach(t=>r=r.or(t)),r}();function lo(r){return sc.decode(r)}function uo(r){return t=>r.encoder.encode(t)}function oc(r){if(parseInt(r).toString()!==r)throw new at("Value must be an integer")}function ic(r){if(r<0)throw new at("Value must be a positive integer, or zero")}function ac(r){return t=>{if(t>r)throw new at(`Value must be smaller than or equal to ${r}`)}}function cc(...r){return t=>{for(let e of r)e(t)}}var fe=cc(oc,ic,ac(65535));var D=-1,Fn=class{protocolsByCode=new Map;protocolsByName=new Map;getProtocol(t){let e;if(typeof t=="string"?e=this.protocolsByName.get(t):e=this.protocolsByCode.get(t),e==null)throw new ir(`Protocol ${t} was unknown`);return e}addProtocol(t){this.protocolsByCode.set(t.code,t),this.protocolsByName.set(t.name,t),t.aliases?.forEach(e=>{this.protocolsByName.set(e,t)})}removeProtocol(t){let e=this.protocolsByCode.get(t);e!=null&&(this.protocolsByCode.delete(e.code),this.protocolsByName.delete(e.name),e.aliases?.forEach(n=>{this.protocolsByName.delete(n)}))}},z=new Fn,Bc=[{code:4,name:"ip4",size:32,valueToBytes:Mn,bytesToValue:io,validate:r=>{if(!mt(r))throw new at(`Invalid IPv4 address "${r}"`)}},{code:6,name:"tcp",size:16,valueToBytes:Tt,bytesToValue:Gt,validate:fe},{code:273,name:"udp",size:16,valueToBytes:Tt,bytesToValue:Gt,validate:fe},{code:33,name:"dccp",size:16,valueToBytes:Tt,bytesToValue:Gt,validate:fe},{code:41,name:"ip6",size:128,valueToBytes:oo,bytesToValue:ao,stringToValue:co,validate:r=>{if(!Wt(r))throw new at(`Invalid IPv6 address "${r}"`)}},{code:42,name:"ip6zone",size:D},{code:43,name:"ipcidr",size:8,bytesToValue:Nn("base10"),valueToBytes:Rn("base10")},{code:53,name:"dns",size:D,resolvable:!0},{code:54,name:"dns4",size:D,resolvable:!0},{code:55,name:"dns6",size:D,resolvable:!0},{code:56,name:"dnsaddr",size:D,resolvable:!0},{code:132,name:"sctp",size:16,valueToBytes:Tt,bytesToValue:Gt,validate:fe},{code:301,name:"udt"},{code:302,name:"utp"},{code:400,name:"unix",size:D,path:!0,stringToValue:r=>decodeURIComponent(r),valueToString:r=>encodeURIComponent(r)},{code:421,name:"p2p",aliases:["ipfs"],size:D,bytesToValue:Nn("base58btc"),valueToBytes:r=>r.startsWith("Q")||r.startsWith("1")?Rn("base58btc")(r):H.parse(r).multihash.bytes},{code:444,name:"onion",size:96,bytesToValue:Un,valueToBytes:no},{code:445,name:"onion3",size:296,bytesToValue:Un,valueToBytes:so},{code:446,name:"garlic64",size:D},{code:447,name:"garlic32",size:D},{code:448,name:"tls"},{code:449,name:"sni",size:D},{code:454,name:"noise"},{code:460,name:"quic"},{code:461,name:"quic-v1"},{code:465,name:"webtransport"},{code:466,name:"certhash",size:D,bytesToValue:uo(te),valueToBytes:lo},{code:480,name:"http"},{code:481,name:"http-path",size:D,stringToValue:r=>`/${decodeURIComponent(r)}`,valueToString:r=>encodeURIComponent(r.substring(1))},{code:443,name:"https"},{code:477,name:"ws"},{code:478,name:"wss"},{code:479,name:"p2p-websocket-star"},{code:277,name:"p2p-stardust"},{code:275,name:"p2p-webrtc-star"},{code:276,name:"p2p-webrtc-direct"},{code:280,name:"webrtc-direct"},{code:281,name:"webrtc"},{code:290,name:"p2p-circuit"},{code:777,name:"memory",size:D}];Bc.forEach(r=>{z.addProtocol(r)});function ho(r){let t=[],e=0;for(;e<r.length;){let n=gt(r,e),s=z.getProtocol(n),o=_(n),i=Oc(s,r,e+o),a=0;i>0&&s.size===D&&(a=_(i));let c=o+a+i,l={code:n,name:s.name,bytes:r.subarray(e,e+c)};if(i>0){let u=e+o+a,h=r.subarray(u,u+i);l.value=s.bytesToValue?.(h)??k(h)}t.push(l),e+=c}return t}function fo(r){let t=0,e=[];for(let n of r){if(n.bytes==null){let s=z.getProtocol(n.code),o=_(n.code),i,a=0,c=0;n.value!=null&&(i=s.valueToBytes?.(n.value)??A(n.value),a=i.byteLength,s.size===D&&(c=_(a)));let l=new Uint8Array(o+c+a),u=0;Pt(n.code,l,u),u+=o,i!=null&&(s.size===D&&(Pt(a,l,u),u+=c),l.set(i,u)),n.bytes=l}e.push(n.bytes),t+=n.bytes.byteLength}return ut(e,t)}function po(r){if(r.charAt(0)!=="/")throw new C('String multiaddr must start with "/"');let t=[],e="protocol",n="",s="";for(let o=1;o<r.length;o++){let i=r.charAt(o);i!=="/"&&(e==="protocol"?s+=r.charAt(o):n+=r.charAt(o));let a=o===r.length-1;if(i==="/"||a){let c=z.getProtocol(s);if(e==="protocol"){if(c.size==null||c.size===0){t.push({code:c.code,name:c.name}),n="",s="",e="protocol";continue}else if(a)throw new C(`Component ${s} was missing value`);e="value"}else if(e==="value"){let l={code:c.code,name:c.name};if(c.size!=null&&c.size!==0){if(n==="")throw new C(`Component ${s} was missing value`);l.value=c.stringToValue?.(n)??n}t.push(l),n="",s="",e="protocol"}}}if(s!==""&&n!=="")throw new C("Incomplete multiaddr");return t}function mo(r){return`/${r.flatMap(t=>{if(t.value==null)return t.name;let e=z.getProtocol(t.code);if(e==null)throw new C(`Unknown protocol code ${t.code}`);return[t.name,e.valueToString?.(t.value)??t.value]}).join("/")}`}function Oc(r,t,e){return r.size==null||r.size===0?0:r.size>0?r.size/8:gt(t,e)}var zc=Symbol.for("nodejs.util.inspect.custom"),Wn=Symbol.for("@multiformats/multiaddr"),$c=[53,54,55,56],Hn=class extends Error{constructor(t="No available resolver"){super(t),this.name="NoAvailableResolverError"}};function qc(r){if(r==null&&(r="/"),wo(r))return r.getComponents();if(r instanceof Uint8Array)return ho(r);if(typeof r=="string")return r=r.replace(/\/(\/)+/,"/").replace(/(\/)+$/,""),r===""&&(r="/"),po(r);if(Array.isArray(r))return r;throw new C("Must be a string, Uint8Array, Component[], or another Multiaddr")}var dr=class r{[Wn]=!0;#t;#e;#r;constructor(t="/",e={}){this.#t=qc(t),e.validate!==!1&&Vc(this)}get bytes(){return this.#r==null&&(this.#r=fo(this.#t)),this.#r}toString(){return this.#e==null&&(this.#e=mo(this.#t)),this.#e}toJSON(){return this.toString()}toOptions(){let t,e,n,s,o="";for(let{code:a,name:c,value:l}of this.#t)a===42&&(o=`%${l??""}`),$c.includes(a)&&(e="tcp",s=443,n=`${l??""}${o}`,t=a===55?6:4),(a===6||a===273)&&(e=c==="tcp"?"tcp":"udp",s=parseInt(l??"")),(a===4||a===41)&&(e="tcp",n=`${l??""}${o}`,t=a===41?6:4);if(t==null||e==null||n==null||s==null)throw new Error('multiaddr must have a valid format: "/{ip4, ip6, dns4, dns6, dnsaddr}/{address}/{tcp, udp}/{port}".');return{family:t,host:n,transport:e,port:s}}getComponents(){return[...this.#t]}protos(){return this.#t.map(({code:t,value:e})=>{let n=z.getProtocol(t);return{code:t,size:n.size??0,name:n.name,resolvable:!!n.resolvable,path:!!n.path}})}protoCodes(){return this.#t.map(({code:t})=>t)}protoNames(){return this.#t.map(({name:t})=>t)}tuples(){return this.#t.map(({code:t,value:e})=>{if(e==null)return[t];let n=z.getProtocol(t),s=[t];return e!=null&&s.push(n.valueToBytes?.(e)??A(e)),s})}stringTuples(){return this.#t.map(({code:t,value:e})=>e==null?[t]:[t,e])}encapsulate(t){let e=new r(t);return new r([...this.#t,...e.getComponents()],{validate:!1})}decapsulate(t){let e=t.toString(),n=this.toString(),s=n.lastIndexOf(e);if(s<0)throw new he(`Address ${this.toString()} does not contain subaddress: ${t.toString()}`);return new r(n.slice(0,s),{validate:!1})}decapsulateCode(t){let e;for(let n=this.#t.length-1;n>-1;n--)if(this.#t[n].code===t){e=n;break}return new r(this.#t.slice(0,e),{validate:!1})}getPeerId(){try{let t=[];this.#t.forEach(({code:n,value:s})=>{n===421&&t.push([n,s]),n===290&&(t=[])});let e=t.pop();if(e?.[1]!=null){let n=e[1];return n[0]==="Q"||n[0]==="1"?k(O.decode(`z${n}`),"base58btc"):k(H.parse(n).multihash.bytes,"base58btc")}return null}catch{return null}}getPath(){for(let t of this.#t)if(z.getProtocol(t.code).path)return t.value??null;return null}equals(t){return J(this.bytes,t.bytes)}async resolve(t){let e=this.protos().find(o=>o.resolvable);if(e==null)return[this];let n=go.get(e.name);if(n==null)throw new Hn(`no available resolver for ${e.name}`);return(await n(this,t)).map(o=>pe(o))}nodeAddress(){let t=this.toOptions();if(t.transport!=="tcp"&&t.transport!=="udp")throw new Error(`multiaddr must have a valid format - no protocol with name: "${t.transport}". Must have a valid transport protocol: "{tcp, udp}"`);return{family:t.family,address:t.host,port:t.port}}isThinWaistAddress(){return!(this.#t.length!==2||this.#t[0].code!==4&&this.#t[0].code!==41||this.#t[1].code!==6&&this.#t[1].code!==273)}[zc](){return`Multiaddr(${this.toString()})`}};function Vc(r){r.getComponents().forEach(t=>{let e=z.getProtocol(t.code);t.value!=null&&e.validate?.(t.value)})}var Rm=parseInt("0xFFFF",16),Um=new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);var go=new Map;function wo(r){return!!r?.[Wn]}function pe(r){return new dr(r)}function X(r){let t=z.getProtocol(r);return{code:t.code,size:t.size??0,name:t.name,resolvable:!!t.resolvable,path:!!t.path}}var Qc=[X("tcp").code,X("dns").code,X("dnsaddr").code,X("dns4").code,X("dns6").code];function xo(r){return vo("sni",r)?.[1]}function Eo(r){let t=vo("tcp",r)?.[1];return t==null?"":`:${t}`}function vo(r,t){let e;try{e=X(r).code}catch{return}for(let[n,s]of t)if(n===e&&s!=null)return[n,s]}function _o(r){return r.some(([t,e])=>t===X("tls").code)}function tt(r,t,e){let n=So[X(r).name];if(n==null)throw new Error(`Can't interpret protocol ${X(r).name}`);let s=n(t,e);return r===X("ip6").code?`[${s}]`:s}var So={ip4:(r,t)=>r,ip6:(r,t)=>t.length===0?r:`[${r}]`,tcp:(r,t)=>{let e=t.pop();if(e==null)throw new Error("Unexpected end of multiaddr");return`tcp://${tt(e[0],e[1]??"",t)}:${r}`},udp:(r,t)=>{let e=t.pop();if(e==null)throw new Error("Unexpected end of multiaddr");return`udp://${tt(e[0],e[1]??"",t)}:${r}`},dnsaddr:(r,t)=>r,dns4:(r,t)=>r,dns6:(r,t)=>r,dns:(r,t)=>r,ipfs:(r,t)=>{let e=t.pop();if(e==null)throw new Error("Unexpected end of multiaddr");return`${tt(e[0],e[1]??"",t)}`},p2p:(r,t)=>{let e=t.pop();if(e==null)throw new Error("Unexpected end of multiaddr");return`${tt(e[0],e[1]??"",t)}`},http:(r,t)=>{let e=_o(t),n=xo(t),s=Eo(t);if(e&&n!=null)return`https://${n}${s}`;let o=e?"https://":"http://",i=t.pop();if(i==null)throw new Error("Unexpected end of multiaddr");let a=tt(i[0],i[1]??"",t);return a=a.replace("tcp://",""),`${o}${a}`},"http-path":(r,t)=>{let e=t.pop();if(e==null)throw new Error("Unexpected end of multiaddr");let n=tt(e[0],e[1]??"",t),s=decodeURIComponent(r);return`${n}/${s}`},tls:(r,t)=>{let e=t.pop();if(e==null)throw new Error("Unexpected end of multiaddr");return tt(e[0],e[1]??"",t)},sni:(r,t)=>{let e=t.pop();if(e==null)throw new Error("Unexpected end of multiaddr");return tt(e[0],e[1]??"",t)},https:(r,t)=>{let e=t.pop();if(e==null)throw new Error("Unexpected end of multiaddr");let n=tt(e[0],e[1]??"",t);return n=n.replace("tcp://",""),`https://${n}`},ws:(r,t)=>{let e=_o(t),n=xo(t),s=Eo(t);if(e&&n!=null)return`wss://${n}${s}`;let o=e?"wss://":"ws://",i=t.pop();if(i==null)throw new Error("Unexpected end of multiaddr");let a=tt(i[0],i[1]??"",t);return a=a.replace("tcp://",""),`${o}${a}`},wss:(r,t)=>{let e=t.pop();if(e==null)throw new Error("Unexpected end of multiaddr");let n=tt(e[0],e[1]??"",t);return n=n.replace("tcp://",""),`wss://${n}`}};function pr(r,t){let n=pe(r).stringTuples(),s=n.pop();if(s==null)throw new Error("Unexpected end of multiaddr");let o=X(s[0]),i=So[o.name];if(i==null)throw new Error(`No interpreter found for ${o.name}`);let a=i(s[1]??"",n);return t?.assumeHttp!==!1&&Qc.includes(s[0])&&(a=a.replace(/^.*:\/\//,""),s[1]==="443"?a=`https://${a}`:a=`http://${a}`),(a.startsWith("http://")||a.startsWith("https://")||a.startsWith("ws://")||a.startsWith("wss://"))&&(a=new URL(a).toString(),a.endsWith("/")&&(a=a.substring(0,a.length-1))),a}var ko=rs(Io(),1),Zc=["0.0.0.0/8","10.0.0.0/8","100.64.0.0/10","127.0.0.0/8","169.254.0.0/16","172.16.0.0/12","192.0.0.0/24","192.0.0.0/29","192.0.0.8/32","192.0.0.9/32","192.0.0.10/32","192.0.0.170/32","192.0.0.171/32","192.0.2.0/24","192.31.196.0/24","192.52.193.0/24","192.88.99.0/24","192.168.0.0/16","192.175.48.0/24","198.18.0.0/15","198.51.100.0/24","203.0.113.0/24","240.0.0.0/4","255.255.255.255/32"],Kc=Zc.map(r=>new ko.Netmask(r));function Gn(r){for(let t of Kc)if(t.contains(r))return!0;return!1}function Jc(r){return/^::ffff:([0-9a-fA-F]{1,4}):([0-9a-fA-F]{1,4})$/.test(r)}function jc(r){let t=r.split(":");if(t.length<2)return!1;let e=t[t.length-1].padStart(4,"0"),n=t[t.length-2].padStart(4,"0"),s=`${parseInt(n.substring(0,2),16)}.${parseInt(n.substring(2),16)}.${parseInt(e.substring(0,2),16)}.${parseInt(e.substring(2),16)}`;return Gn(s)}function Yc(r){return/^::ffff:([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)}function tl(r){let t=r.split(":"),e=t[t.length-1];return Gn(e)}function el(r){return/^::$/.test(r)||/^::1$/.test(r)||/^64:ff9b::([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)||/^100::([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^2001::([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^2001:2[0-9a-fA-F]:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^2001:db8:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^2002:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^f[c-d]([0-9a-fA-F]{2,2}):/i.test(r)||/^fe[8-9a-bA-B][0-9a-fA-F]:/i.test(r)||/^ff([0-9a-fA-F]{2,2}):/i.test(r)}function Ao(r){if(mt(r))return Gn(r);if(Jc(r))return jc(r);if(Yc(r))return tl(r);if(Wt(r))return el(r)}var rl=r=>r.toString().split("/").slice(1),Xt=r=>({match:t=>t.length<1?!1:r(t[0])?t.slice(1):!1,pattern:"fn"}),p=r=>({match:t=>Xt(e=>e===r).match(t),pattern:r}),Dt=()=>({match:r=>Xt(t=>typeof t=="string").match(r),pattern:"{string}"}),Qt=()=>({match:r=>Xt(t=>!isNaN(parseInt(t))).match(r),pattern:"{number}"}),y=()=>({match:r=>{if(r.length<2||r[0]!=="p2p"&&r[0]!=="ipfs")return!1;if(r[1].startsWith("Q")||r[1].startsWith("1"))try{O.decode(`z${r[1]}`)}catch{return!1}else return!1;return r.slice(2)},pattern:"/p2p/{peerid}"}),ge=()=>({match:r=>{if(r.length<2||r[0]!=="certhash")return!1;try{te.decode(r[1])}catch{return!1}return r.slice(2)},pattern:"/certhash/{certhash}"}),w=r=>({match:t=>{let e=r.match(t);return e===!1?t:e},pattern:`optional(${r.pattern})`}),F=(...r)=>({match:t=>{let e;for(let n of r){let s=n.match(t);s!==!1&&(e==null||s.length<e.length)&&(e=s)}return e??!1},pattern:`or(${r.map(t=>t.pattern).join(", ")})`}),m=(...r)=>({match:t=>{for(let e of r){let n=e.match(t);if(n===!1)return!1;t=n}return t},pattern:`and(${r.map(t=>t.pattern).join(", ")})`});function v(...r){function t(s){let o=rl(s);for(let i of r){let a=i.match(o);if(a===!1)return!1;o=a}return o}function e(s){return t(s)!==!1}function n(s){let o=t(s);return o===!1?!1:o.length===0}return{matchers:r,matches:e,exactMatch:n}}var nl=y(),Lg=v(nl),gr=m(p("dns4"),Dt()),wr=m(p("dns6"),Dt()),br=m(p("dnsaddr"),Dt()),Qn=m(p("dns"),Dt()),Cg=v(gr,w(y())),Pg=v(wr,w(y())),Ng=v(br,w(y())),To=v(F(Qn,br,gr,wr),w(y())),Do=m(p("ip4"),Xt(mt)),Lo=m(p("ip6"),Xt(Wt)),Zn=F(Do,Lo),ct=F(Zn,Qn,gr,wr,br),Rg=v(F(Zn,m(F(Qn,br,gr,wr),w(y())))),Ug=v(Do),Mg=v(Lo),Fg=v(Zn),Kn=m(ct,p("tcp"),Qt()),we=m(ct,p("udp"),Qt()),Bg=v(m(Kn,w(y()))),Og=v(we),Jn=m(we,p("quic"),w(y())),yr=m(we,p("quic-v1"),w(y())),sl=F(Jn,yr),zg=v(Jn),$g=v(yr),Xn=F(ct,Kn,we,Jn,yr),Co=F(m(Xn,p("ws"),w(y()))),qg=v(Co),Po=F(m(Xn,p("wss"),w(y())),m(Xn,p("tls"),w(m(p("sni"),Dt())),p("ws"),w(y()))),Vg=v(Po),No=m(we,p("webrtc-direct"),w(ge()),w(ge()),w(y())),Hg=v(No),Ro=m(yr,p("webtransport"),w(ge()),w(ge()),w(y())),Wg=v(Ro),mr=F(Co,Po,m(Kn,w(y())),m(sl,w(y())),m(ct,w(y())),No,Ro,y()),Gg=v(mr),ol=m(mr,p("p2p-circuit"),y()),Xg=v(ol),il=F(m(mr,p("p2p-circuit"),p("webrtc"),w(y())),m(mr,p("webrtc"),w(y())),m(p("webrtc"),w(y()))),Qg=v(il),al=F(m(ct,p("tcp"),Qt(),p("http"),w(y())),m(ct,p("http"),w(y()))),Uo=v(al),cl=F(m(ct,p("tcp"),F(m(p("443"),p("http")),m(Qt(),p("https")),m(Qt(),p("tls"),p("http"))),w(y())),m(ct,p("tls"),p("http"),w(y())),m(ct,p("https"),w(y()))),Mo=v(cl),ll=F(m(p("memory"),Dt(),w(y()))),Zg=v(ll);function jn(r,t,e){return r.filter(n=>{if(Mo.matches(n)||t&&Uo.matches(n))return e||To.matches(n)?!0:Ao(n.toOptions().host)===!1;if(!t&&e){let{host:s}=n.toOptions();if(s==="127.0.0.1"||s==="localhost"||s.endsWith(".localhost"))return!0}return!1})}async function*xr(r,t,e,n,s,o={}){for await(let i of t.findProviders(r,o)){let a=jn(i.multiaddrs,n,s);if(a.length===0)continue;let c=pr(a[0]);yield new Zt(c,{logger:e,transformRequestInit:o.transformRequestInit})}}async function Fo(r,t,e){let{signal:n,log:s}=e??{},o=r.headers.get("content-length");if(o!=null){let c=parseInt(o,10);if(c>t)throw s?.error("content-length header (%d) is greater than the limit (%d)",c,t),r.body!=null&&await r.body.cancel().catch(l=>{s?.error("error cancelling response body after content-length check - %e",l)}),new Error(`Content-Length header (${c}) is greater than the limit (${t}).`)}let i=r.body?.getReader();if(i==null)throw new Error("Response body is not readable");let a=new ht;try{for(;;){if(n?.aborted===!0)throw new Error("Response body read was aborted.");let{done:c,value:l}=await i.read();if(c)break;if(a.append(l),a.byteLength>t)throw new Error(`Response body is greater than the limit (${t}), received ${a.byteLength} bytes.`)}}finally{i.cancel().catch(c=>{s?.error("error cancelling reader - %e",c)}).finally(()=>{i.releaseLock()})}return a.subarray()}var Zt=class{url;#t=0;#e=0;#r=0;#s=0;#n=new Map;log;transformRequestInit;constructor(t,{logger:e,transformRequestInit:n}){this.url=t instanceof URL?t:new URL(t),this.transformRequestInit=n,this.log=e.forComponent(`helia:trustless-gateway-block-broker:${this.url.hostname}`)}#o(t){let e=t.multihash.bytes;return ot.encode(e)}async getRawBlock(t,{signal:e,maxSize:n=Bo}={}){let s=new URL(this.url.toString());if(s.pathname=`/ipfs/${t.toString()}`,s.search="?format=raw",e?.aborted===!0)throw new Error(`Signal to fetch raw block for CID ${t} from gateway ${this.url} was aborted prior to fetch`);let o=this.#o(t),i=new AbortController,a=()=>{i.abort()};e?.addEventListener("abort",a);try{let c=this.#n.get(o);if(c==null){this.#t++;let l={signal:i.signal,headers:{Accept:"application/vnd.ipld.raw"},cache:"force-cache"},u=this.transformRequestInit!=null?await this.transformRequestInit(l):l;c=fetch(s.toString(),u).then(async h=>{if(this.log("GET %s %d",s,h.status),!h.ok)throw this.#e++,new Error(`unable to fetch raw block for CID ${t} from gateway ${this.url}`);let f=await Fo(h,n,{signal:i.signal,log:this.log});return this.#s++,f}),this.#n.set(o,c)}return await c}catch{throw e?.aborted===!0?new Error(`fetching raw block for CID ${t} from gateway ${this.url} was aborted`):(this.#e++,new Error(`unable to fetch raw block for CID ${t}`))}finally{e?.removeEventListener("abort",a),this.#n.delete(o)}}reliability(){return this.#t===0?1:this.#r>0?-1/0:this.#s/(this.#t+this.#e*3)}incrementInvalidBlocks(){this.#r++}getStats(){return{attempts:this.#t,errors:this.#e,invalidBlocks:this.#r,successes:this.#s,pendingResponses:this.#n.size}}};var Yn=class extends At{routing;allowInsecure;allowLocal;transformRequestInit;constructor(t,e){super(t,{...e,name:"helia:trustless-gateway:session"}),this.routing=t.routing,this.allowInsecure=e.allowInsecure??Er,this.allowLocal=e.allowLocal??_r,this.transformRequestInit=e.transformRequestInit}async queryProvider(t,e,n){this.log("fetching BLOCK for %c from %s",t,e.url);let s=await e.getRawBlock(t,n);return this.log.trace("got block for %c from %s",t,e.url),await n.validateFn?.(s),s}async*findNewProviders(t,e={}){yield*xr(t,this.routing,this.logger,this.allowInsecure,this.allowLocal,{...e,transformRequestInit:this.transformRequestInit})}toEvictionKey(t){return t.url.toString()}equals(t,e){return t.url.toString()===e.url.toString()}async convertToProvider(t,e){if(xe(t))return;let n=jn(Array.isArray(t)?t:[t],this.allowInsecure,this.allowLocal);if(n.length===0)return;let s=pr(n[0]);return new Zt(s,{logger:this.logger,transformRequestInit:this.transformRequestInit})}};function Oo(r,t){return new Yn(r,t)}var vr=class{allowInsecure;allowLocal;transformRequestInit;routing;log;logger;constructor(t,e={}){this.log=t.logger.forComponent("helia:trustless-gateway-block-broker"),this.logger=t.logger,this.routing=t.routing,this.allowInsecure=e.allowInsecure??Er,this.allowLocal=e.allowLocal??_r,this.transformRequestInit=e.transformRequestInit}async retrieve(t,e={}){let n=[];for await(let s of xr(t,this.routing,this.logger,this.allowInsecure,this.allowLocal,{...e,transformRequestInit:this.transformRequestInit})){this.log("getting block for %c from %s",t,s.url);try{let o=await s.getRawBlock(t,e);this.log.trace("got block for %c from %s",t,s.url);try{await e.validateFn?.(o)}catch(i){this.log.error("failed to validate block for %c from %s",t,s.url,i);continue}return o}catch(o){if(this.log.error("failed to get block for %c from %s",t,s.url,o),o instanceof Error?n.push(o):n.push(new Error(`Unable to fetch raw block for CID ${t} from gateway ${s.url}`)),e.signal?.aborted===!0){this.log.trace("request aborted while fetching raw block for CID %c from gateway %s",t,s.url);break}}}throw n.length>0?new AggregateError(n,`Unable to fetch raw block for CID ${t} from any gateway`):new Error(`Unable to fetch raw block for CID ${t} from any gateway`)}createSession(t={}){return Oo({logger:this.logger,routing:this.routing},{...t,allowLocal:this.allowLocal,allowInsecure:this.allowInsecure,transformRequestInit:this.transformRequestInit})}};var Er=!1,_r=!1,Bo=2097152;function zo(r={}){return t=>new vr(t,r)}return Go(ul);})();
3
3
  return HeliaBlockBrokers}));
4
4
  //# sourceMappingURL=index.min.js.map