@helia/block-brokers 3.0.2 → 3.0.3-ac4bdb8

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/README.md CHANGED
@@ -21,7 +21,7 @@ $ npm i @helia/block-brokers
21
21
 
22
22
  ## Browser `<script>` tag
23
23
 
24
- Loading this module through a script tag will make it's exports available as `HeliaBlockBrokers` in the global namespace.
24
+ Loading this module through a script tag will make its exports available as `HeliaBlockBrokers` in the global namespace.
25
25
 
26
26
  ```html
27
27
  <script src="https://unpkg.com/@helia/block-brokers/dist/index.min.js"></script>
package/dist/index.min.js CHANGED
@@ -1,5 +1,5 @@
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 bo=Object.create;var ge=Object.defineProperty;var yo=Object.getOwnPropertyDescriptor;var xo=Object.getOwnPropertyNames;var Eo=Object.getPrototypeOf,vo=Object.prototype.hasOwnProperty;var Xt=(r,t)=>()=>(t||r((t={exports:{}}).exports,t),t.exports),W=(r,t)=>{for(var e in t)ge(r,e,{get:t[e],enumerable:!0})},_n=(r,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of xo(t))!vo.call(r,s)&&s!==e&&ge(r,s,{get:()=>t[s],enumerable:!(n=yo(t,s))||n.enumerable});return r};var we=(r,t,e)=>(e=r!=null?bo(Eo(r)):{},_n(t||!r||!r.__esModule?ge(e,"default",{value:r,enumerable:!0}):e,r)),Ao=r=>_n(ge({},"__esModule",{value:!0}),r);var Fn=Xt((el,Mn)=>{"use strict";function Un(r,t){for(let e in t)Object.defineProperty(r,e,{value:t[e],enumerable:!0,configurable:!0});return r}function No(r,t,e){if(!r||typeof r=="string")throw new TypeError("Please pass an Error to err-code");e||(e={}),typeof t=="object"&&(e=t,t=""),t&&(e.code=t);try{return Un(r,e)}catch{e.message=r.message,e.stack=r.stack;let s=function(){};return s.prototype=Object.create(Object.getPrototypeOf(r)),Un(new s,e)}}Mn.exports=No});var ks=Xt((ae,$e)=>{(function(r,t){"use strict";var e={version:"3.0.0",x86:{},x64:{},inputValidation:!0};function n(a){if(!Array.isArray(a)&&!ArrayBuffer.isView(a))return!1;for(var h=0;h<a.length;h++)if(!Number.isInteger(a[h])||a[h]<0||a[h]>255)return!1;return!0}function s(a,h){return(a&65535)*h+(((a>>>16)*h&65535)<<16)}function o(a,h){return a<<h|a>>>32-h}function i(a){return a^=a>>>16,a=s(a,2246822507),a^=a>>>13,a=s(a,3266489909),a^=a>>>16,a}function c(a,h){a=[a[0]>>>16,a[0]&65535,a[1]>>>16,a[1]&65535],h=[h[0]>>>16,h[0]&65535,h[1]>>>16,h[1]&65535];var p=[0,0,0,0];return p[3]+=a[3]+h[3],p[2]+=p[3]>>>16,p[3]&=65535,p[2]+=a[2]+h[2],p[1]+=p[2]>>>16,p[2]&=65535,p[1]+=a[1]+h[1],p[0]+=p[1]>>>16,p[1]&=65535,p[0]+=a[0]+h[0],p[0]&=65535,[p[0]<<16|p[1],p[2]<<16|p[3]]}function l(a,h){a=[a[0]>>>16,a[0]&65535,a[1]>>>16,a[1]&65535],h=[h[0]>>>16,h[0]&65535,h[1]>>>16,h[1]&65535];var p=[0,0,0,0];return p[3]+=a[3]*h[3],p[2]+=p[3]>>>16,p[3]&=65535,p[2]+=a[2]*h[3],p[1]+=p[2]>>>16,p[2]&=65535,p[2]+=a[3]*h[2],p[1]+=p[2]>>>16,p[2]&=65535,p[1]+=a[1]*h[3],p[0]+=p[1]>>>16,p[1]&=65535,p[1]+=a[2]*h[2],p[0]+=p[1]>>>16,p[1]&=65535,p[1]+=a[3]*h[1],p[0]+=p[1]>>>16,p[1]&=65535,p[0]+=a[0]*h[3]+a[1]*h[2]+a[2]*h[1]+a[3]*h[0],p[0]&=65535,[p[0]<<16|p[1],p[2]<<16|p[3]]}function u(a,h){return h%=64,h===32?[a[1],a[0]]:h<32?[a[0]<<h|a[1]>>>32-h,a[1]<<h|a[0]>>>32-h]:(h-=32,[a[1]<<h|a[0]>>>32-h,a[0]<<h|a[1]>>>32-h])}function d(a,h){return h%=64,h===0?a:h<32?[a[0]<<h|a[1]>>>32-h,a[1]<<h]:[a[1]<<h-32,0]}function f(a,h){return[a[0]^h[0],a[1]^h[1]]}function x(a){return a=f(a,[0,a[0]>>>1]),a=l(a,[4283543511,3981806797]),a=f(a,[0,a[0]>>>1]),a=l(a,[3301882366,444984403]),a=f(a,[0,a[0]>>>1]),a}e.x86.hash32=function(a,h){if(e.inputValidation&&!n(a))return t;h=h||0;for(var p=a.length%4,v=a.length-p,m=h,g=0,w=3432918353,y=461845907,E=0;E<v;E=E+4)g=a[E]|a[E+1]<<8|a[E+2]<<16|a[E+3]<<24,g=s(g,w),g=o(g,15),g=s(g,y),m^=g,m=o(m,13),m=s(m,5)+3864292196;switch(g=0,p){case 3:g^=a[E+2]<<16;case 2:g^=a[E+1]<<8;case 1:g^=a[E],g=s(g,w),g=o(g,15),g=s(g,y),m^=g}return m^=a.length,m=i(m),m>>>0},e.x86.hash128=function(a,h){if(e.inputValidation&&!n(a))return t;h=h||0;for(var p=a.length%16,v=a.length-p,m=h,g=h,w=h,y=h,E=0,S=0,b=0,T=0,it=597399067,de=2869860233,pe=951274213,me=2716044179,k=0;k<v;k=k+16)E=a[k]|a[k+1]<<8|a[k+2]<<16|a[k+3]<<24,S=a[k+4]|a[k+5]<<8|a[k+6]<<16|a[k+7]<<24,b=a[k+8]|a[k+9]<<8|a[k+10]<<16|a[k+11]<<24,T=a[k+12]|a[k+13]<<8|a[k+14]<<16|a[k+15]<<24,E=s(E,it),E=o(E,15),E=s(E,de),m^=E,m=o(m,19),m+=g,m=s(m,5)+1444728091,S=s(S,de),S=o(S,16),S=s(S,pe),g^=S,g=o(g,17),g+=w,g=s(g,5)+197830471,b=s(b,pe),b=o(b,17),b=s(b,me),w^=b,w=o(w,15),w+=y,w=s(w,5)+2530024501,T=s(T,me),T=o(T,18),T=s(T,it),y^=T,y=o(y,13),y+=m,y=s(y,5)+850148119;switch(E=0,S=0,b=0,T=0,p){case 15:T^=a[k+14]<<16;case 14:T^=a[k+13]<<8;case 13:T^=a[k+12],T=s(T,me),T=o(T,18),T=s(T,it),y^=T;case 12:b^=a[k+11]<<24;case 11:b^=a[k+10]<<16;case 10:b^=a[k+9]<<8;case 9:b^=a[k+8],b=s(b,pe),b=o(b,17),b=s(b,me),w^=b;case 8:S^=a[k+7]<<24;case 7:S^=a[k+6]<<16;case 6:S^=a[k+5]<<8;case 5:S^=a[k+4],S=s(S,de),S=o(S,16),S=s(S,pe),g^=S;case 4:E^=a[k+3]<<24;case 3:E^=a[k+2]<<16;case 2:E^=a[k+1]<<8;case 1:E^=a[k],E=s(E,it),E=o(E,15),E=s(E,de),m^=E}return m^=a.length,g^=a.length,w^=a.length,y^=a.length,m+=g,m+=w,m+=y,g+=m,w+=m,y+=m,m=i(m),g=i(g),w=i(w),y=i(y),m+=g,m+=w,m+=y,g+=m,w+=m,y+=m,("00000000"+(m>>>0).toString(16)).slice(-8)+("00000000"+(g>>>0).toString(16)).slice(-8)+("00000000"+(w>>>0).toString(16)).slice(-8)+("00000000"+(y>>>0).toString(16)).slice(-8)},e.x64.hash128=function(a,h){if(e.inputValidation&&!n(a))return t;h=h||0;for(var p=a.length%16,v=a.length-p,m=[0,h],g=[0,h],w=[0,0],y=[0,0],E=[2277735313,289559509],S=[1291169091,658871167],b=0;b<v;b=b+16)w=[a[b+4]|a[b+5]<<8|a[b+6]<<16|a[b+7]<<24,a[b]|a[b+1]<<8|a[b+2]<<16|a[b+3]<<24],y=[a[b+12]|a[b+13]<<8|a[b+14]<<16|a[b+15]<<24,a[b+8]|a[b+9]<<8|a[b+10]<<16|a[b+11]<<24],w=l(w,E),w=u(w,31),w=l(w,S),m=f(m,w),m=u(m,27),m=c(m,g),m=c(l(m,[0,5]),[0,1390208809]),y=l(y,S),y=u(y,33),y=l(y,E),g=f(g,y),g=u(g,31),g=c(g,m),g=c(l(g,[0,5]),[0,944331445]);switch(w=[0,0],y=[0,0],p){case 15:y=f(y,d([0,a[b+14]],48));case 14:y=f(y,d([0,a[b+13]],40));case 13:y=f(y,d([0,a[b+12]],32));case 12:y=f(y,d([0,a[b+11]],24));case 11:y=f(y,d([0,a[b+10]],16));case 10:y=f(y,d([0,a[b+9]],8));case 9:y=f(y,[0,a[b+8]]),y=l(y,S),y=u(y,33),y=l(y,E),g=f(g,y);case 8:w=f(w,d([0,a[b+7]],56));case 7:w=f(w,d([0,a[b+6]],48));case 6:w=f(w,d([0,a[b+5]],40));case 5:w=f(w,d([0,a[b+4]],32));case 4:w=f(w,d([0,a[b+3]],24));case 3:w=f(w,d([0,a[b+2]],16));case 2:w=f(w,d([0,a[b+1]],8));case 1:w=f(w,[0,a[b]]),w=l(w,E),w=u(w,31),w=l(w,S),m=f(m,w)}return m=f(m,[0,a.length]),g=f(g,[0,a.length]),m=c(m,g),g=c(g,m),m=x(m),g=x(g),m=c(m,g),g=c(g,m),("00000000"+(m[0]>>>0).toString(16)).slice(-8)+("00000000"+(m[1]>>>0).toString(16)).slice(-8)+("00000000"+(g[0]>>>0).toString(16)).slice(-8)+("00000000"+(g[1]>>>0).toString(16)).slice(-8)},typeof ae<"u"?(typeof $e<"u"&&$e.exports&&(ae=$e.exports=e),ae.murmurHash3=e):typeof define=="function"&&define.amd?define([],function(){return e}):(e._murmurHash3=r.murmurHash3,e.noConflict=function(){return r.murmurHash3=e._murmurHash3,e._murmurHash3=t,e.noConflict=t,e},r.murmurHash3=e)})(ae)});var Is=Xt((Ph,Ls)=>{Ls.exports=ks()});var Ds=Xt((df,_s)=>{_s.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 Fs=Xt(le=>{(function(){var r,t,e,n,s,o,i,c;c=function(l){var u,d,f,x;return u=(l&255<<24)>>>24,d=(l&255<<16)>>>16,f=(l&65280)>>>8,x=l&255,[u,d,f,x].join(".")},i=function(l){var u,d,f,x,a,h;for(u=[],f=x=0;x<=3&&l.length!==0;f=++x){if(f>0){if(l[0]!==".")throw new Error("Invalid IP");l=l.substring(1)}h=t(l),a=h[0],d=h[1],l=l.substring(d),u.push(a)}if(l.length!==0)throw new Error("Invalid IP");switch(u.length){case 1:if(u[0]>4294967295)throw new Error("Invalid IP");return u[0]>>>0;case 2:if(u[0]>255||u[1]>16777215)throw new Error("Invalid IP");return(u[0]<<24|u[1])>>>0;case 3:if(u[0]>255||u[1]>255||u[2]>65535)throw new Error("Invalid IP");return(u[0]<<24|u[1]<<16|u[2])>>>0;case 4:if(u[0]>255||u[1]>255||u[2]>255||u[3]>255)throw new Error("Invalid IP");return(u[0]<<24|u[1]<<16|u[2]<<8|u[3])>>>0;default:throw new Error("Invalid IP")}},e=function(l){return l.charCodeAt(0)},n=e("0"),o=e("a"),s=e("A"),t=function(l){var u,d,f,x,a;for(x=0,u=10,d="9",f=0,l.length>1&&l[f]==="0"&&(l[f+1]==="x"||l[f+1]==="X"?(f+=2,u=16):"0"<=l[f+1]&&l[f+1]<="9"&&(f++,u=8,d="7")),a=f;f<l.length;){if("0"<=l[f]&&l[f]<=d)x=x*u+(e(l[f])-n)>>>0;else if(u===16)if("a"<=l[f]&&l[f]<="f")x=x*u+(10+e(l[f])-o)>>>0;else if("A"<=l[f]&&l[f]<="F")x=x*u+(10+e(l[f])-s)>>>0;else break;else break;if(x>4294967295)throw new Error("too large");f++}if(f===a)throw new Error("empty octet");return[x,f]},r=function(){function l(u,d){var f,x,a,h;if(typeof u!="string")throw new Error("Missing `net' parameter");if(d||(h=u.split("/",2),u=h[0],d=h[1]),d||(d=32),typeof d=="string"&&d.indexOf(".")>-1){try{this.maskLong=i(d)}catch(p){throw f=p,new Error("Invalid mask: "+d)}for(x=a=32;a>=0;x=--a)if(this.maskLong===4294967295<<32-x>>>0){this.bitmask=x;break}}else if(d||d===0)this.bitmask=parseInt(d,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(u)&this.maskLong)>>>0}catch(p){throw f=p,new Error("Invalid net address: "+u)}if(!(this.bitmask<=32))throw new Error("Invalid mask for ip4: "+d);this.size=Math.pow(2,32-this.bitmask),this.base=c(this.netLong),this.mask=c(this.maskLong),this.hostmask=c(~this.maskLong),this.first=this.bitmask<=30?c(this.netLong+1):this.base,this.last=this.bitmask<=30?c(this.netLong+this.size-2):c(this.netLong+this.size-1),this.broadcast=this.bitmask<=30?c(this.netLong+this.size-1):void 0}return l.prototype.contains=function(u){return typeof u=="string"&&(u.indexOf("/")>0||u.split(".").length!==4)&&(u=new l(u)),u instanceof l?this.contains(u.base)&&this.contains(u.broadcast||u.last):(i(u)&this.maskLong)>>>0===(this.netLong&this.maskLong)>>>0},l.prototype.next=function(u){return u==null&&(u=1),new l(c(this.netLong+this.size*u),this.mask)},l.prototype.forEach=function(u){var d,f,x;for(x=i(this.first),f=i(this.last),d=0;x<=f;)u(c(x),x,d),d++,x++},l.prototype.toString=function(){return this.base+"/"+this.bitmask},l}(),le.ip2long=i,le.long2ip=c,le.Netmask=r}).call(le)});var cc={};W(cc,{bitswap:()=>Us,trustlessGateway:()=>wo});var Dn=Symbol.for("@libp2p/peer-id");var ht=class r extends Error{code;type;constructor(t="The operation was aborted"){super(t),this.name="AbortError",this.code=r.code,this.type=r.type}static code="ABORT_ERR";static type="aborted"},M=class extends Error{code;props;constructor(t,e,n){super(t),this.code=e,this.name=n?.name??"CodeError",this.props=n??{}}};var q=(r,...t)=>{try{[...t]}catch{}};var rt=class extends EventTarget{#t=new Map;constructor(){super(),q(1/0,this)}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 So(t,e))}},cr=class extends Event{detail;constructor(t,e){super(t,e),this.detail=e?.detail}},So=globalThis.CustomEvent??cr;function Pn(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 Z(){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)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}},_t=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 lr=class extends Error{type;code;constructor(t,e){super(t??"The operation was aborted"),this.type="aborted",this.code=e??"ABORT_ERR"}};function Dt(r={}){return ko(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 ko(r,t){t=t??{};let e=t.onEnd,n=new _t,s,o,i,c=Z(),l=async()=>{try{return n.isEmpty()?i?{done:!0}:await new Promise((v,m)=>{o=g=>{o=null,n.push(g);try{v(r(n))}catch(w){m(w)}return s}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{c.resolve(),c=Z()})}},u=v=>o!=null?o(v):(n.push(v),s),d=v=>(n=new _t,o!=null?o({error:v}):(n.push({error:v}),s)),f=v=>{if(i)return s;if(t?.objectMode!==!0&&v?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return u({done:!1,value:v})},x=v=>i?s:(i=!0,v!=null?d(v):u({done:!0})),a=()=>(n=new _t,x(),{done:!0}),h=v=>(x(v),{done:!0});if(s={[Symbol.asyncIterator](){return this},next:l,return:a,throw:h,push:f,end:x,get readableLength(){return n.size},onEmpty:async v=>{let m=v?.signal;if(m?.throwIfAborted(),n.isEmpty())return;let g,w;m!=null&&(g=new Promise((y,E)=>{w=()=>{E(new lr)},m.addEventListener("abort",w)}));try{await Promise.race([c.promise,g])}finally{w!=null&&m!=null&&m?.removeEventListener("abort",w)}}},e==null)return s;let p=s;return s={[Symbol.asyncIterator](){return this},next(){return p.next()},throw(v){return p.throw(v),e!=null&&(e(v),e=void 0),{done:!0}},return(){return p.return(),e!=null&&(e(),e=void 0),{done:!0}},push:f,end(v){return p.end(v),e!=null&&(e(v),e=void 0),s},get readableLength(){return p.readableLength},onEmpty:v=>p.onEmpty(v)},s}var ur=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 Y(r,t,e,n){let s=new ur(n?.errorMessage,n?.errorCode);return e?.aborted===!0?Promise.reject(s):new Promise((o,i)=>{function c(){e?.removeEventListener("abort",d),r.removeEventListener(t,l),n?.errorEvent!=null&&r.removeEventListener(n.errorEvent,u)}let l=f=>{try{if(n?.filter?.(f)===!1)return}catch(x){c(),i(x);return}c(),o(f)},u=f=>{c(),i(f.detail)},d=()=>{c(),i(s)};e?.addEventListener("abort",d),r.addEventListener(t,l),n?.errorEvent!=null&&r.addEventListener(n.errorEvent,u)})}var ye=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 Rn(r,t,e){if(t==null)return r;if(t.aborted)return Promise.reject(new ye(e?.errorMessage,e?.errorCode));let n,s=new ye(e?.errorMessage,e?.errorCode);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 xe=class{deferred;signal;where;constructor(t,e){this.signal=e,this.deferred=Z(),this.where=t,this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new ht)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function Lo(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var Ee=class{id;fn;options;recipients;status;timeline;controller;constructor(t,e){this.id=Lo(),this.status="queued",this.fn=t,this.options=e,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,q(1/0,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 ht),this.cleanup())}async join(t={}){let e=new xe(new Error("where").stack,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 Rn(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 Pt=class extends rt{concurrency;queue;pending;sort;constructor(t={}){super(),this.concurrency=t.concurrency??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){e?.signal?.throwIfAborted();let n=new Ee(t,e),s=n.join(e).then(o=>(this.safeDispatchEvent("completed",{detail:o}),this.safeDispatchEvent("success",{detail:{job:n,result:o}}),o)).catch(o=>{if(n.status==="queued"){for(let i=0;i<this.queue.length;i++)if(this.queue[i]===n){this.queue.splice(i,1);break}}throw this.safeDispatchEvent("error",{detail:o}),this.safeDispatchEvent("failure",{detail:{job:n,error:o}}),o});return this.enqueue(n),this.safeDispatchEvent("add"),this.tryToStartAnother(),s}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(t=>{t.abort(new ht)}),this.clear()}async onEmpty(t){this.size!==0&&await Y(this,"empty",t?.signal)}async onSizeLessThan(t,e){this.size<t||await Y(this,"next",e?.signal,{filter:()=>this.size<t})}async onIdle(t){this.pending===0&&this.size===0||await Y(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=Dt({objectMode:!0}),n=l=>{l!=null?this.abort():this.clear(),e.end(l)},s=l=>{l.detail!=null&&e.push(l.detail)},o=l=>{n(l.detail)},i=()=>{n()},c=()=>{n(new M("Queue aborted","ERR_QUEUE_ABORTED"))};this.addEventListener("completed",s),this.addEventListener("error",o),this.addEventListener("idle",i),t?.signal?.addEventListener("abort",c);try{yield*e}finally{this.removeEventListener("completed",s),this.removeEventListener("error",o),this.removeEventListener("idle",i),t?.signal?.removeEventListener("abort",c),n()}}};var ve=class extends Pt{has(t){return this.find(t)!=null}find(t){return this.queue.find(e=>t.equals(e.options.peerId))}};function Io(r){return r[Symbol.asyncIterator]!=null}function To(r){if(Io(r))return(async()=>{for await(let t of r);})();for(let t of r);}var hr=To;function O(r=0){return new Uint8Array(r)}function $(r=0){return new Uint8Array(r)}var _o=Math.pow(2,7),Do=Math.pow(2,14),Po=Math.pow(2,21),fr=Math.pow(2,28),dr=Math.pow(2,35),pr=Math.pow(2,42),mr=Math.pow(2,49),I=128,z=127;function D(r){if(r<_o)return 1;if(r<Do)return 2;if(r<Po)return 3;if(r<fr)return 4;if(r<dr)return 5;if(r<pr)return 6;if(r<mr)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function gr(r,t,e=0){switch(D(r)){case 8:t[e++]=r&255|I,r/=128;case 7:t[e++]=r&255|I,r/=128;case 6:t[e++]=r&255|I,r/=128;case 5:t[e++]=r&255|I,r/=128;case 4:t[e++]=r&255|I,r>>>=7;case 3:t[e++]=r&255|I,r>>>=7;case 2:t[e++]=r&255|I,r>>>=7;case 1:{t[e++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return t}function Ro(r,t,e=0){switch(D(r)){case 8:t.set(e++,r&255|I),r/=128;case 7:t.set(e++,r&255|I),r/=128;case 6:t.set(e++,r&255|I),r/=128;case 5:t.set(e++,r&255|I),r/=128;case 4:t.set(e++,r&255|I),r>>>=7;case 3:t.set(e++,r&255|I),r>>>=7;case 2:t.set(e++,r&255|I),r>>>=7;case 1:{t.set(e++,r&255),r>>>=7;break}default:throw new Error("unreachable")}return t}function wr(r,t){let e=r[t],n=0;if(n+=e&z,e<I||(e=r[t+1],n+=(e&z)<<7,e<I)||(e=r[t+2],n+=(e&z)<<14,e<I)||(e=r[t+3],n+=(e&z)<<21,e<I)||(e=r[t+4],n+=(e&z)*fr,e<I)||(e=r[t+5],n+=(e&z)*dr,e<I)||(e=r[t+6],n+=(e&z)*pr,e<I)||(e=r[t+7],n+=(e&z)*mr,e<I))return n;throw new RangeError("Could not decode varint")}function Co(r,t){let e=r.get(t),n=0;if(n+=e&z,e<I||(e=r.get(t+1),n+=(e&z)<<7,e<I)||(e=r.get(t+2),n+=(e&z)<<14,e<I)||(e=r.get(t+3),n+=(e&z)<<21,e<I)||(e=r.get(t+4),n+=(e&z)*fr,e<I)||(e=r.get(t+5),n+=(e&z)*dr,e<I)||(e=r.get(t+6),n+=(e&z)*pr,e<I)||(e=r.get(t+7),n+=(e&z)*mr,e<I))return n;throw new RangeError("Could not decode varint")}function nt(r,t,e=0){return t==null&&(t=$(D(r))),t instanceof Uint8Array?gr(r,t,e):Ro(r,t,e)}function tt(r,t=0){return r instanceof Uint8Array?wr(r,t):Co(r,t)}function j(r,t){t==null&&(t=r.reduce((s,o)=>s+o.length,0));let e=$(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 Nn=Symbol.for("@achingbrain/uint8arraylist");function Cn(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 Se(r){return!!r?.[Nn]}var ft=class r{bufs;length;[Nn]=!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(Se(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(Se(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=Cn(this.bufs,t);return e.buf[e.index]}set(t,e){let n=Cn(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(Se(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 j(n,s)}subarray(t,e){let{bufs:n,length:s}=this._subList(t,e);return n.length===1?n[0]:j(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],c=s,l=c+i.byteLength;if(s=l,t>=l)continue;let u=t>=c&&t<l,d=e>c&&e<=l;if(u&&d){if(t===c&&e===l){n.push(i);break}let f=t-c;n.push(i.subarray(f,f+(e-t)));break}if(u){if(t===0){n.push(i);continue}n.push(i.subarray(t-c));continue}if(d){if(e===l){n.push(i);break}n.push(i.subarray(0,e-c));break}n.push(i)}return{bufs:n,length:e-t}}indexOf(t,e=0){if(!Se(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 f=0;f<o;f++)i[f]=-1;for(let f=0;f<s;f++)i[n[f]]=f;let c=i,l=this.byteLength-n.byteLength,u=n.byteLength-1,d;for(let f=e;f<=l;f+=d){d=0;for(let x=u;x>=0;x--){let a=this.get(f+x);if(n[x]!==a){d=Math.max(1,x-c[a]);break}}if(d===0)return f}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=$(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=O(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=O(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=O(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=$(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=O(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=O(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=O(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=O(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=O(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,o)=>s+o.byteLength,0)),n.length=e,n}};function ke(r){return r[Symbol.asyncIterator]!=null}var Le=r=>{let t=D(r),e=$(t);return nt(r,e),Le.bytes=t,e};Le.bytes=0;function Ie(r,t){t=t??{};let e=t.lengthEncoder??Le;function*n(s){let o=e(s.byteLength);o instanceof Uint8Array?yield o:yield*o,s instanceof Uint8Array?yield s:yield*s}return ke(r)?async function*(){for await(let s of r)yield*n(s)}():function*(){for(let s of r)yield*n(s)}()}Ie.single=(r,t)=>{t=t??{};let e=t.lengthEncoder??Le;return new ft(e(r.byteLength),r)};var Rt=we(Fn(),1);var Uo=8,Mo=1024*1024*4,bt;(function(r){r[r.LENGTH=0]="LENGTH",r[r.DATA=1]="DATA"})(bt||(bt={}));var br=r=>{let t=tt(r);return br.bytes=D(t),t};br.bytes=0;function Qt(r,t){let e=new ft,n=bt.LENGTH,s=-1,o=t?.lengthDecoder??br,i=t?.maxLengthLength??Uo,c=t?.maxDataLength??Mo;function*l(){for(;e.byteLength>0;){if(n===bt.LENGTH)try{if(s=o(e),s<0)throw(0,Rt.default)(new Error("invalid message length"),"ERR_INVALID_MSG_LENGTH");if(s>c)throw(0,Rt.default)(new Error("message length too long"),"ERR_MSG_DATA_TOO_LONG");let u=o.bytes;e.consume(u),t?.onLength!=null&&t.onLength(s),n=bt.DATA}catch(u){if(u instanceof RangeError){if(e.byteLength>i)throw(0,Rt.default)(new Error("message length length too long"),"ERR_MSG_LENGTH_TOO_LONG");break}throw u}if(n===bt.DATA){if(e.byteLength<s)break;let u=e.sublist(0,s);e.consume(s),t?.onData!=null&&t.onData(u),yield u,n=bt.LENGTH}}}return ke(r)?async function*(){for await(let u of r)e.append(u),yield*l();if(e.byteLength>0)throw(0,Rt.default)(new Error("unexpected end of input"),"ERR_UNEXPECTED_EOF")}():function*(){for(let u of r)e.append(u),yield*l();if(e.byteLength>0)throw(0,Rt.default)(new Error("unexpected end of input"),"ERR_UNEXPECTED_EOF")}()}Qt.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 Qt(n,{...t??{},onLength:o=>{e=o}})};function Bo(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 Bn=Bo;function Oo(r){return r[Symbol.asyncIterator]!=null}function $o(r,t){let e=0;if(Oo(r))return async function*(){for await(let l of r)yield t(l,e++)}();let n=Bn(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 await(let l of n)yield t(l,e++)}();let c=t;return function*(){yield i;for(let l of n)yield c(l,e++)}()}var On=$o;function zo(r){return r[Symbol.asyncIterator]!=null}function Vo(...r){let t=[];for(let e of r)zo(e)||t.push(e);return t.length===r.length?function*(){for(let e of t)yield*e}():async function*(){let e=Dt({objectMode:!0});Promise.resolve().then(async()=>{try{await Promise.all(r.map(async n=>{for await(let s of n)e.push(s)})),e.end()}catch(n){e.end(n)}}),yield*e}()}var $n=Vo;function xr(r,...t){if(r==null)throw new Error("Empty pipeline");if(yr(r)){let n=r;r=()=>n.source}else if(Vn(r)||zn(r)){let n=r;r=()=>n}let e=[r,...t];if(e.length>1&&yr(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++)yr(e[n])&&(e[n]=Wo(e[n]));return Ho(...e)}var Ho=(...r)=>{let t;for(;r.length>0;)t=r.shift()(t);return t},zn=r=>r?.[Symbol.asyncIterator]!=null,Vn=r=>r?.[Symbol.iterator]!=null,yr=r=>r==null?!1:r.sink!=null&&r.source!=null,Wo=r=>t=>{let e=r.sink(t);if(e?.then!=null){let n=Dt({objectMode:!0});e.then(()=>{n.end()},i=>{n.end(i)});let s,o=r.source;if(zn(o))s=async function*(){yield*o,n.end()};else if(Vn(o))s=function*(){yield*o,n.end()};else throw new Error("Unknown duplex source type - must be Iterable or AsyncIterable");return $n(n,s())}return r.source};function qo(r){return r[Symbol.asyncIterator]!=null}function Go(r,t){return qo(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 Hn=Go;var st=class extends Event{constructor(t,e){super(t),this.detail=e}};var jt="/ipfs/bitswap/1.2.0";var Er=new Float32Array([-0]),dt=new Uint8Array(Er.buffer);function Wn(r,t,e){Er[0]=r,t[e]=dt[0],t[e+1]=dt[1],t[e+2]=dt[2],t[e+3]=dt[3]}function qn(r,t){return dt[0]=r[t],dt[1]=r[t+1],dt[2]=r[t+2],dt[3]=r[t+3],Er[0]}var vr=new Float64Array([-0]),V=new Uint8Array(vr.buffer);function Gn(r,t,e){vr[0]=r,t[e]=V[0],t[e+1]=V[1],t[e+2]=V[2],t[e+3]=V[3],t[e+4]=V[4],t[e+5]=V[5],t[e+6]=V[6],t[e+7]=V[7]}function Xn(r,t){return V[0]=r[t],V[1]=r[t+1],V[2]=r[t+2],V[3]=r[t+3],V[4]=r[t+4],V[5]=r[t+5],V[6]=r[t+6],V[7]=r[t+7],vr[0]}var Xo=BigInt(Number.MAX_SAFE_INTEGER),Qo=BigInt(Number.MIN_SAFE_INTEGER),G=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 yt;if(t<Xo&&t>Qo)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>Qn&&(s=0n,++n>Qn&&(n=0n))),new r(Number(s),Number(n))}static fromNumber(t){if(t===0)return yt;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):yt}},yt=new G(0,0);yt.toBigInt=function(){return 0n};yt.zzEncode=yt.zzDecode=function(){return this};yt.length=function(){return 1};var Qn=4294967296n;function jn(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 Kn(r,t,e){if(e-t<1)return"";let s,o=[],i=0,c;for(;t<e;)c=r[t++],c<128?o[i++]=c:c>191&&c<224?o[i++]=(c&31)<<6|r[t++]&63:c>239&&c<365?(c=((c&7)<<18|(r[t++]&63)<<12|(r[t++]&63)<<6|r[t++]&63)-65536,o[i++]=55296+(c>>10),o[i++]=56320+(c&1023)):o[i++]=(c&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 Ar(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 et(r,t){return RangeError(`index out of range: ${r.pos} + ${t??1} > ${r.len}`)}function Te(r,t){return(r[t-4]|r[t-3]<<8|r[t-2]<<16|r[t-1]<<24)>>>0}var Sr=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,et(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 et(this,4);return Te(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw et(this,4);return Te(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw et(this,4);let t=qn(this.buf,this.pos);return this.pos+=4,t}double(){if(this.pos+8>this.len)throw et(this,4);let t=Xn(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 et(this,t);return this.pos+=t,e===n?new Uint8Array(0):this.buf.subarray(e,n)}string(){let t=this.bytes();return Kn(t,0,t.length)}skip(t){if(typeof t=="number"){if(this.pos+t>this.len)throw et(this,t);this.pos+=t}else do if(this.pos>=this.len)throw et(this);while(this.buf[this.pos++]&128);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 G(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 et(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 et(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 et(this,8);let t=Te(this.buf,this.pos+=4),e=Te(this.buf,this.pos+=4);return new G(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=wr(this.buf,this.pos);return this.pos+=D(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 kr(r){return new Sr(r instanceof Uint8Array?r:r.subarray())}function xt(r,t,e){let n=kr(r);return t.decode(n,void 0,e)}var Dr={};W(Dr,{base10:()=>ti});var Ll=new Uint8Array(0);function Zn(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 at(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 Yn(r){return new TextEncoder().encode(r)}function ts(r){return new TextDecoder().decode(r)}function jo(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 c=r.length,l=r.charAt(0),u=Math.log(c)/Math.log(256),d=Math.log(256)/Math.log(c);function f(h){if(h instanceof Uint8Array||(ArrayBuffer.isView(h)?h=new Uint8Array(h.buffer,h.byteOffset,h.byteLength):Array.isArray(h)&&(h=Uint8Array.from(h))),!(h instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(h.length===0)return"";for(var p=0,v=0,m=0,g=h.length;m!==g&&h[m]===0;)m++,p++;for(var w=(g-m)*d+1>>>0,y=new Uint8Array(w);m!==g;){for(var E=h[m],S=0,b=w-1;(E!==0||S<v)&&b!==-1;b--,S++)E+=256*y[b]>>>0,y[b]=E%c>>>0,E=E/c>>>0;if(E!==0)throw new Error("Non-zero carry");v=S,m++}for(var T=w-v;T!==w&&y[T]===0;)T++;for(var it=l.repeat(p);T<w;++T)it+=r.charAt(y[T]);return it}function x(h){if(typeof h!="string")throw new TypeError("Expected String");if(h.length===0)return new Uint8Array;var p=0;if(h[p]!==" "){for(var v=0,m=0;h[p]===l;)v++,p++;for(var g=(h.length-p)*u+1>>>0,w=new Uint8Array(g);h[p];){var y=e[h.charCodeAt(p)];if(y===255)return;for(var E=0,S=g-1;(y!==0||E<m)&&S!==-1;S--,E++)y+=c*w[S]>>>0,w[S]=y%256>>>0,y=y/256>>>0;if(y!==0)throw new Error("Non-zero carry");m=E,p++}if(h[p]!==" "){for(var b=g-m;b!==g&&w[b]===0;)b++;for(var T=new Uint8Array(v+(g-b)),it=v;b!==g;)T[it++]=w[b++];return T}}}function a(h){var p=x(h);if(p)return p;throw new Error(`Non-${t} character`)}return{encode:f,decodeUnsafe:x,decode:a}}var Ko=jo,Jo=Ko,rs=Jo;var Lr=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")}},Ir=class{name;prefix;baseDecode;prefixCodePoint;constructor(t,e,n){if(this.name=t,this.prefix=e,e.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=e.codePointAt(0),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 ns(this,t)}},Tr=class{decoders;constructor(t){this.decoders=t}or(t){return ns(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 ns(r,t){return new Tr({...r.decoders??{[r.prefix]:r},...t.decoders??{[t.prefix]:t}})}var _r=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 Lr(t,e,n),this.decoder=new Ir(t,e,s)}encode(t){return this.encoder.encode(t)}decode(t){return this.decoder.decode(t)}};function Ct({name:r,prefix:t,encode:e,decode:n}){return new _r(r,t,e,n)}function pt({name:r,prefix:t,alphabet:e}){let{encode:n,decode:s}=rs(e,r);return Ct({prefix:t,name:r,encode:n,decode:o=>at(s(o))})}function Zo(r,t,e,n){let s={};for(let d=0;d<t.length;++d)s[t[d]]=d;let o=r.length;for(;r[o-1]==="=";)--o;let i=new Uint8Array(o*e/8|0),c=0,l=0,u=0;for(let d=0;d<o;++d){let f=s[r[d]];if(f===void 0)throw new SyntaxError(`Non-${n} character`);l=l<<e|f,c+=e,c>=8&&(c-=8,i[u++]=255&l>>c)}if(c>=e||255&l<<8-c)throw new SyntaxError("Unexpected end of data");return i}function Yo(r,t,e){let n=t[t.length-1]==="=",s=(1<<e)-1,o="",i=0,c=0;for(let l=0;l<r.length;++l)for(c=c<<8|r[l],i+=8;i>e;)i-=e,o+=t[s&c>>i];if(i!==0&&(o+=t[s&c<<e-i]),n)for(;o.length*e&7;)o+="=";return o}function R({name:r,prefix:t,bitsPerChar:e,alphabet:n}){return Ct({prefix:t,name:r,encode(s){return Yo(s,n,e)},decode(s){return Zo(s,n,e,r)}})}var ti=pt({prefix:"9",name:"base10",alphabet:"0123456789"});var Pr={};W(Pr,{base16:()=>ei,base16upper:()=>ri});var ei=R({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),ri=R({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var Rr={};W(Rr,{base2:()=>ni});var ni=R({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var Cr={};W(Cr,{base256emoji:()=>ci});var ss=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}"),si=ss.reduce((r,t,e)=>(r[e]=t,r),[]),oi=ss.reduce((r,t,e)=>(r[t.codePointAt(0)]=e,r),[]);function ii(r){return r.reduce((t,e)=>(t+=si[e],t),"")}function ai(r){let t=[];for(let e of r){let n=oi[e.codePointAt(0)];if(n===void 0)throw new Error(`Non-base256emoji character: ${e}`);t.push(n)}return new Uint8Array(t)}var ci=Ct({prefix:"\u{1F680}",name:"base256emoji",encode:ii,decode:ai});var Nr={};W(Nr,{base32:()=>ct,base32hex:()=>fi,base32hexpad:()=>pi,base32hexpadupper:()=>mi,base32hexupper:()=>di,base32pad:()=>ui,base32padupper:()=>hi,base32upper:()=>li,base32z:()=>gi});var ct=R({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),li=R({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),ui=R({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),hi=R({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),fi=R({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),di=R({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),pi=R({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),mi=R({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),gi=R({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Ur={};W(Ur,{base36:()=>wi,base36upper:()=>bi});var wi=pt({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),bi=pt({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var Mr={};W(Mr,{base58btc:()=>U,base58flickr:()=>yi});var U=pt({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),yi=pt({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var Br={};W(Br,{base64:()=>lt,base64pad:()=>xi,base64url:()=>Fr,base64urlpad:()=>Ei});var lt=R({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),xi=R({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Fr=R({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Ei=R({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var Or={};W(Or,{base8:()=>vi});var vi=R({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var $r={};W($r,{identity:()=>Ai});var Ai=Ct({prefix:"\0",name:"identity",encode:r=>ts(r),decode:r=>Yn(r)});var Vl=new TextEncoder,Hl=new TextDecoder;var Vr={};W(Vr,{identity:()=>De});var Li=as,os=128,Ii=127,Ti=~Ii,_i=Math.pow(2,31);function as(r,t,e){t=t||[],e=e||0;for(var n=e;r>=_i;)t[e++]=r&255|os,r/=128;for(;r&Ti;)t[e++]=r&255|os,r>>>=7;return t[e]=r|0,as.bytes=e-n+1,t}var Di=zr,Pi=128,is=127;function zr(r,n){var e=0,n=n||0,s=0,o=n,i,c=r.length;do{if(o>=c)throw zr.bytes=0,new RangeError("Could not decode varint");i=r[o++],e+=s<28?(i&is)<<s:(i&is)*Math.pow(2,s),s+=7}while(i>=Pi);return zr.bytes=o-n,e}var Ri=Math.pow(2,7),Ci=Math.pow(2,14),Ni=Math.pow(2,21),Ui=Math.pow(2,28),Mi=Math.pow(2,35),Fi=Math.pow(2,42),Bi=Math.pow(2,49),Oi=Math.pow(2,56),$i=Math.pow(2,63),zi=function(r){return r<Ri?1:r<Ci?2:r<Ni?3:r<Ui?4:r<Mi?5:r<Fi?6:r<Bi?7:r<Oi?8:r<$i?9:10},Vi={encode:Li,decode:Di,encodingLength:zi},Hi=Vi,Kt=Hi;function Jt(r,t=0){return[Kt.decode(r,t),Kt.decode.bytes]}function Nt(r,t,e=0){return Kt.encode(r,t,e),t}function Ut(r){return Kt.encodingLength(r)}function mt(r,t){let e=t.byteLength,n=Ut(r),s=n+Ut(e),o=new Uint8Array(s+e);return Nt(r,o,0),Nt(e,o,n),o.set(t,s),new Mt(r,e,t,o)}function Et(r){let t=at(r),[e,n]=Jt(t),[s,o]=Jt(t.subarray(n)),i=t.subarray(n+o);if(i.byteLength!==s)throw new Error("Incorrect length");return new Mt(e,s,i,t)}function cs(r,t){if(r===t)return!0;{let e=t;return r.code===e.code&&r.size===e.size&&e.bytes instanceof Uint8Array&&Zn(r.bytes,e.bytes)}}var Mt=class{code;size;digest;bytes;constructor(t,e,n,s){this.code=t,this.size=e,this.digest=n,this.bytes=s}};var ls=0,Wi="identity",us=at;function qi(r){return mt(ls,us(r))}var De={code:ls,name:Wi,encode:us,digest:qi};var qr={};W(qr,{sha256:()=>At,sha512:()=>Gi});function Wr({name:r,code:t,encode:e}){return new Hr(r,t,e)}var Hr=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 fs(r){return async t=>new Uint8Array(await crypto.subtle.digest(r,t))}var At=Wr({name:"sha2-256",code:18,encode:fs("SHA-256")}),Gi=Wr({name:"sha2-512",code:19,encode:fs("SHA-512")});function ds(r,t){let{bytes:e,version:n}=r;switch(n){case 0:return Qi(e,Gr(r),t??U.encoder);default:return ji(e,Gr(r),t??ct.encoder)}}var ps=new WeakMap;function Gr(r){let t=ps.get(r);if(t==null){let e=new Map;return ps.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!==Zt)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(e.code!==Ki)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&&cs(t.multihash,n.multihash)}toString(t){return ds(this,t)}toJSON(){return{"/":ds(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??ms(n,s,o.bytes))}else if(e[Ji]===!0){let{version:n,multihash:s,code:o}=e,i=Et(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!==Zt)throw new Error(`Version 0 CID must use dag-pb (code: ${Zt}) block encoding`);return new r(t,e,n,n.bytes)}case 1:{let s=ms(t,e,n.bytes);return new r(t,e,n,s)}default:throw new Error("Invalid version")}}static createV0(t){return r.create(0,Zt,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=at(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 Mt(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[f,x]=Jt(t.subarray(e));return e+=x,f},s=n(),o=Zt;if(s===18?(s=0,e=0):o=n(),s!==0&&s!==1)throw new RangeError(`Invalid CID version ${s}`);let i=e,c=n(),l=n(),u=e+l,d=u-i;return{version:s,codec:o,multihashCode:c,digestSize:l,multihashSize:d,size:u}}static parse(t,e){let[n,s]=Xi(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 Gr(o).set(n,t),o}};function Xi(r,t){switch(r[0]){case"Q":{let e=t??U;return[U.prefix,e.decode(`${U.prefix}${r}`)]}case U.prefix:{let e=t??U;return[U.prefix,e.decode(r)]}case ct.prefix:{let e=t??ct;return[ct.prefix,e.decode(r)]}default:{if(t==null)throw Error("To parse non base32 or base58btc encoded CID multibase decoder must be provided");return[r[0],t.decode(r)]}}}function Qi(r,t,e){let{prefix:n}=e;if(n!==U.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 ji(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 Zt=112,Ki=18;function ms(r,t,e){let n=Ut(r),s=n+Ut(t),o=new Uint8Array(s+e.byteLength);return Nt(r,o,0),Nt(t,o,n),o.set(e,s),o}var Ji=Symbol.for("@ipld/js-cid/CID");var gt={...$r,...Rr,...Or,...Dr,...Pr,...Nr,...Ur,...Mr,...Br,...Cr},uu={...qr,...Vr};function ws(r,t,e,n){return{name:r,prefix:t,encoder:{name:r,prefix:t,encode:e},decoder:{decode:n}}}var gs=ws("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),Xr=ws("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.length);for(let e=0;e<r.length;e++)t[e]=r.charCodeAt(e);return t}),Zi={utf8:gs,"utf-8":gs,hex:gt.base16,latin1:Xr,ascii:Xr,binary:Xr,...gt},Pe=Zi;function wt(r,t="utf8"){let e=Pe[t];if(e==null)throw new Error(`Unsupported encoding "${t}"`);return e.decoder.decode(`${e.prefix}${r}`)}function Qr(r){let t=r??8192,e=t>>>1,n,s=t;return function(i){if(i<1||i>e)return $(i);s+i>t&&(n=$(t),s=0);let c=n.subarray(s,s+=i);return s&7&&(s=(s|7)+1),c}}var St=class{fn;len;next;val;constructor(t,e,n){this.fn=t,this.len=e,this.next=void 0,this.val=n}};function jr(){}var Jr=class{head;tail;len;next;constructor(t){this.head=t.head,this.tail=t.tail,this.len=t.len,this.next=t.states}},Yi=Qr();function ta(r){return globalThis.Buffer!=null?$(r):Yi(r)}var te=class{len;head;tail;states;constructor(){this.len=0,this.head=new St(jr,0,0),this.tail=this.head,this.states=null}_push(t,e,n){return this.tail=this.tail.next=new St(t,e,n),this.len+=e,this}uint32(t){return this.len+=(this.tail=this.tail.next=new Zr((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(Re,10,G.fromNumber(t)):this.uint32(t)}sint32(t){return this.uint32((t<<1^t>>31)>>>0)}uint64(t){let e=G.fromBigInt(t);return this._push(Re,e.length(),e)}uint64Number(t){return this._push(gr,D(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=G.fromBigInt(t).zzEncode();return this._push(Re,e.length(),e)}sint64Number(t){let e=G.fromNumber(t).zzEncode();return this._push(Re,e.length(),e)}sint64String(t){return this.sint64(BigInt(t))}bool(t){return this._push(Kr,1,t?1:0)}fixed32(t){return this._push(Yt,4,t>>>0)}sfixed32(t){return this.fixed32(t)}fixed64(t){let e=G.fromBigInt(t);return this._push(Yt,4,e.lo)._push(Yt,4,e.hi)}fixed64Number(t){let e=G.fromNumber(t);return this._push(Yt,4,e.lo)._push(Yt,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(Wn,4,t)}double(t){return this._push(Gn,8,t)}bytes(t){let e=t.length>>>0;return e===0?this._push(Kr,1,0):this.uint32(e)._push(ra,e,t)}string(t){let e=jn(t);return e!==0?this.uint32(e)._push(Ar,e,t):this._push(Kr,1,0)}fork(){return this.states=new Jr(this),this.head=this.tail=new St(jr,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 St(jr,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=ta(this.len),n=0;for(;t!=null;)t.fn(t.val,e,n),n+=t.len,t=t.next;return e}};function Kr(r,t,e){t[e]=r&255}function ea(r,t,e){for(;r>127;)t[e++]=r&127|128,r>>>=7;t[e]=r}var Zr=class extends St{next;constructor(t,e){super(ea,t,e),this.next=void 0}};function Re(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 Yt(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 ra(r,t,e){t.set(r,e)}globalThis.Buffer!=null&&(te.prototype.bytes=function(r){let t=r.length>>>0;return this.uint32(t),t>0&&this._push(na,t,r),this},te.prototype.string=function(r){let t=globalThis.Buffer.byteLength(r);return this.uint32(t),t>0&&this._push(sa,t,r),this});function na(r,t,e){t.set(r,e)}function sa(r,t,e){r.length<40?Ar(r,t,e):t.utf8Write!=null?t.utf8Write(r,e):t.set(wt(r),e)}function Yr(){return new te}function kt(r,t){let e=Yr();return t.encode(r,e,{lengthDelimited:!1}),e.finish()}var Ft;(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"})(Ft||(Ft={}));function Ce(r,t,e,n){return{name:r,type:t,encode:e,decode:n}}function Ne(r){function t(s){if(r[s.toString()]==null)throw new Error("Invalid enum value");return r[s]}let e=function(o,i){let c=t(o);i.int32(c)},n=function(o){let i=o.int32();return t(i)};return Ce("enum",Ft.VARINT,e,n)}function Lt(r,t){return Ce("message",Ft.LENGTH_DELIMITED,r,t)}var Bt=class extends Error{code;constructor(t,e,n){super(t,n),this.code=e}};var C;(function(r){r.WantBlock="WantBlock",r.WantHave="WantHave"})(C||(C={}));var tn;(function(r){r[r.WantBlock=0]="WantBlock",r[r.WantHave=1]="WantHave"})(tn||(tn={}));(function(r){r.codec=()=>Ne(tn)})(C||(C={}));var Ot;(function(r){let t;r.codec=()=>(t==null&&(t=Lt((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),C.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:O(0),priority:0},i=n==null?e.len:e.pos+n;for(;e.pos<i;){let c=e.uint32();switch(c>>>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=C.codec().decode(e);break}case 5:{o.sendDontHave=e.bool();break}default:{e.skipType(c&7);break}}}return o})),t),r.encode=e=>kt(e,r.codec()),r.decode=(e,n)=>xt(e,r.codec(),n)})(Ot||(Ot={}));var Ue;(function(r){let t;r.codec=()=>(t==null&&(t=Lt((e,n,s={})=>{if(s.lengthDelimited!==!1&&n.fork(),e.entries!=null)for(let o of e.entries)n.uint32(10),Ot.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 c=e.uint32();switch(c>>>3){case 1:{if(s.limits?.entries!=null&&o.entries.length===s.limits.entries)throw new Bt('decode error - map field "entries" had too many elements',"ERR_MAX_LENGTH");o.entries.push(Ot.codec().decode(e,e.uint32(),{limits:s.limits?.entries$}));break}case 2:{o.full=e.bool();break}default:{e.skipType(c&7);break}}}return o})),t),r.encode=e=>kt(e,r.codec()),r.decode=(e,n)=>xt(e,r.codec(),n)})(Ue||(Ue={}));var $t;(function(r){let t;r.codec=()=>(t==null&&(t=Lt((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:O(0),data:O(0)},i=n==null?e.len:e.pos+n;for(;e.pos<i;){let c=e.uint32();switch(c>>>3){case 1:{o.prefix=e.bytes();break}case 2:{o.data=e.bytes();break}default:{e.skipType(c&7);break}}}return o})),t),r.encode=e=>kt(e,r.codec()),r.decode=(e,n)=>xt(e,r.codec(),n)})($t||($t={}));var J;(function(r){r.HaveBlock="HaveBlock",r.DontHaveBlock="DontHaveBlock"})(J||(J={}));var Me;(function(r){r[r.HaveBlock=0]="HaveBlock",r[r.DontHaveBlock=1]="DontHaveBlock"})(Me||(Me={}));(function(r){r.codec=()=>Ne(Me)})(J||(J={}));var zt;(function(r){let t;r.codec=()=>(t==null&&(t=Lt((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&&Me[e.type]!==0&&(n.uint32(16),J.codec().encode(e.type,n)),s.lengthDelimited!==!1&&n.ldelim()},(e,n,s={})=>{let o={cid:O(0),type:J.HaveBlock},i=n==null?e.len:e.pos+n;for(;e.pos<i;){let c=e.uint32();switch(c>>>3){case 1:{o.cid=e.bytes();break}case 2:{o.type=J.codec().decode(e);break}default:{e.skipType(c&7);break}}}return o})),t),r.encode=e=>kt(e,r.codec()),r.decode=(e,n)=>xt(e,r.codec(),n)})(zt||(zt={}));var It;(function(r){let t;r.codec=()=>(t==null&&(t=Lt((e,n,s={})=>{if(s.lengthDelimited!==!1&&n.fork(),e.wantlist!=null&&(n.uint32(10),Ue.codec().encode(e.wantlist,n)),e.blocks!=null)for(let o of e.blocks)n.uint32(26),$t.codec().encode(o,n);if(e.blockPresences!=null)for(let o of e.blockPresences)n.uint32(34),zt.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 c=e.uint32();switch(c>>>3){case 1:{o.wantlist=Ue.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 Bt('decode error - map field "blocks" had too many elements',"ERR_MAX_LENGTH");o.blocks.push($t.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 Bt('decode error - map field "blockPresences" had too many elements',"ERR_MAX_LENGTH");o.blockPresences.push(zt.codec().decode(e,e.uint32(),{limits:s.limits?.blockPresences$}));break}case 5:{o.pendingBytes=e.int32();break}default:{e.skipType(c&7);break}}}return o})),t),r.encode=e=>kt(e,r.codec()),r.decode=(e,n)=>xt(e,r.codec(),n)})(It||(It={}));function bs(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 oa=4193648,ia=oa+16;function*ys(r,t){let e=[...r.wantlist.values()],n=[...r.blockPresences.values()],s=[...r.blocks.values()],o=0,i=0,c=0,l=!1;for(;;){let u={wantlist:{full:r.full??!1,entries:[]},blockPresences:[],blocks:[],pendingBytes:0},d=It.encode(u).byteLength,{added:f,hasMore:x,newSize:a}=en(s,u.blocks,c,t,d,aa);c+=f,d=a;let h=x;({added:f,hasMore:x,newSize:a}=en(n,u.blockPresences,i,t,d,ca)),i+=f,d=a;let p=x;if({added:f,hasMore:x,newSize:a}=en(e,u.wantlist.entries,o,t,d,la),o+=f,d=a,l=!h&&!p&&!x,l||(u.wantlist.full=!1),yield It.encode(u),l)break}}function en(r,t,e,n,s,o){let i=0,c=!1;for(let l=e;l<r.length;l++){let u=r[l],d=o(u);if(d>ia)throw new M("Cannot send block as after encoding it is over the max message size","ERR_BLOCK_TOO_LARGE");let f=s+d;if(f>n){c=!0;break}t.push(u),i++,s=f}return{hasMore:c,added:i,newSize:s}}function aa(r){return rn(3,$t.encode(r))}function ca(r){return rn(4,zt.encode(r))}function la(r){return rn(1,Ot.encode(r))}function rn(r,t){let e=D(r),n=D(t.byteLength);return e+n+t.byteLength}var Fe=class extends rt{log;libp2p;routing;protocols;running;maxInboundStreams;maxOutboundStreams;messageReceiveTimeout;registrarIds;metrics;sendQueue;runOnTransientConnections;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.runOnTransientConnections=e.runOnTransientConnections??!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 ve({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,runOnTransientConnection:this.runOnTransientConnections});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 M(`Incoming Bitswap stream timed out after ${this.messageReceiveTimeout}ms`,"ERR_TIMEOUT")):this.log("stream aborted with status %s",e.status)},o=AbortSignal.timeout(this.messageReceiveTimeout);q(1/0,o),o.addEventListener("abort",s),await e.closeWrite(),await xr(e,i=>Qt(i,{maxDataLength:this.maxIncomingMessageSize}),async i=>{for await(let c of i)try{let l=It.decode(c);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:l}}),o.removeEventListener("abort",s),o=AbortSignal.timeout(this.messageReceiveTimeout),q(1/0,o),o.addEventListener("abort",s)}catch(l){this.log.error("error reading incoming bitswap message from %p on stream",n.remotePeer,e.id,l),e.abort(l);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 st("bitswap:network:find-providers",t));for await(let n of this.routing.findProviders(t,e))await this.libp2p.isDialable(n.multiaddrs,{runOnTransientConnection:this.runOnTransientConnections})&&(yield n)}async findAndConnect(t,e){await hr(On(Hn(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=bs(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 M("No message to send","ERR_NO_MESSAGE");this.log("sendMessage to %p",t),o?.onProgress?.(new st("bitswap:network:send-wantlist",t));let c=await this.libp2p.dialProtocol(t,jt,o);await c.closeRead();try{await xr(ys(i,this.maxOutgoingMessageSize),l=>Ie(l),c),await c.close(o)}catch(l){o?.onProgress?.(new st("bitswap:network:send-wantlist:error",{peer:t,error:l})),this.log.error("error sending message to %p",t,l),c.abort(l)}this._updateSentStats(i.blocks)},{peerId:t,signal:n?.signal,message:e})}async connectTo(t,e){if(!this.running)throw new M("Network isn't running","ERR_NOT_STARTED");e?.onProgress?.(new st("bitswap:network:dial",t));let[n]=await Promise.all([this.libp2p.dial(t,e),Y(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 M(`${t} did not support ${jt}`,"ERR_BITSWAP_UNSUPPORTED_BY_PEER")}})]);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)}};var ba=Symbol.for("nodejs.util.inspect.custom"),xs=Object.values(gt).map(r=>r.decoder).reduce((r,t)=>r.or(t),gt.identity.decoder),Es=114,vs=36,As=37,ee=class{type;multihash;privateKey;publicKey;string;constructor(t){this.type=t.type,this.multihash=t.multihash,this.privateKey=t.privateKey,Object.defineProperty(this,"string",{enumerable:!1,writable:!0})}get[Symbol.toStringTag](){return`PeerId(${this.toString()})`}[Dn]=!0;toString(){return this.string==null&&(this.string=U.encode(this.multihash.bytes).slice(1)),this.string}toCID(){return H.createV1(Es,this.multihash)}toBytes(){return this.multihash.bytes}toJSON(){return this.toString()}equals(t){if(t==null)return!1;if(t instanceof Uint8Array)return K(this.multihash.bytes,t);if(typeof t=="string")return oe(t).equals(this);if(t?.multihash?.bytes!=null)return K(this.multihash.bytes,t.multihash.bytes);throw new Error("not valid Id")}[ba](){return`PeerId(${this.toString()})`}},re=class extends ee{type="RSA";publicKey;constructor(t){super({...t,type:"RSA"}),this.publicKey=t.publicKey}},ne=class extends ee{type="Ed25519";publicKey;constructor(t){super({...t,type:"Ed25519"}),this.publicKey=t.multihash.digest}},se=class extends ee{type="secp256k1";publicKey;constructor(t){super({...t,type:"secp256k1"}),this.publicKey=t.multihash.digest}};function oe(r,t){if(t=t??xs,r.charAt(0)==="1"||r.charAt(0)==="Q"){let e=Et(U.decode(`z${r}`));return r.startsWith("12D")?new ne({multihash:e}):r.startsWith("16U")?new se({multihash:e}):new re({multihash:e})}return ya(xs.decode(r))}function ya(r){try{let t=Et(r);if(t.code===De.code){if(t.digest.length===vs)return new ne({multihash:t});if(t.digest.length===As)return new se({multihash:t})}if(t.code===At.code)return new re({multihash:t})}catch{return xa(H.decode(r))}throw new Error("Supplied PeerID CID is invalid")}function xa(r){if(r==null||r.multihash==null||r.version==null||r.version===1&&r.code!==Es)throw new Error("Supplied PeerID CID is invalid");let t=r.multihash;if(t.code===At.code)return new re({multihash:r.multihash});if(t.code===De.code){if(t.digest.length===vs)return new ne({multihash:r.multihash});if(t.digest.length===As)return new se({multihash:r.multihash})}throw new Error("Supplied PeerID CID is invalid")}function nn(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 ie=class{map;constructor(t){if(this.map=new Map,t!=null)for(let[e,n]of t.entries())this.map.set(e.toString(),n)}[Symbol.iterator](){return this.entries()}clear(){this.map.clear()}delete(t){return this.map.delete(t.toString())}entries(){return nn(this.map.entries(),t=>[oe(t[0]),t[1]])}forEach(t){this.map.forEach((e,n)=>{t(e,oe(n),this)})}get(t){return this.map.get(t.toString())}has(t){return this.map.has(t.toString())}set(t,e){this.map.set(t.toString(),e)}keys(){return nn(this.map.keys(),t=>oe(t))}values(){return this.map.values()}get size(){return this.map.size}};var Be=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;var Eh=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;var vh={}.toString;function Ss(r=32){if(Be&&typeof Be.getRandomValues=="function")return Be.getRandomValues(new Uint8Array(r));throw new Error("crypto.getRandomValues must be defined")}function P(r,t="utf8"){let e=Pe[t];if(e==null)throw new Error(`Unsupported encoding "${t}"`);return e.encoder.encode(r).substring(1)}function Oe(r){if(isNaN(r)||r<=0)throw new M("random bytes length must be a Number bigger than 0","ERR_INVALID_LENGTH");return Ss(r)}var sn=class extends ie{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 ce(r){let{name:t,metrics:e}=r,n;return e!=null?n=new sn({name:t,metrics:e}):n=new ie,n}var ut=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=lt.encode(t.multihash.bytes);this.wantlist.set(n,e)}addBlockPresence(t,e){let n=lt.encode(t.multihash.bytes);this.blockPresences.set(n,e)}addBlock(t,e){let n=lt.encode(t.multihash.bytes);this.blocks.set(n,e)}};function Ea(r){let t=new Uint8Array(r.reduce((n,s)=>n+D(s),0)),e=0;for(let n of r)t=nt(n,t,e),e+=D(n);return t}var Ts=Ea;function on(r){return Ts([r.version,r.code,r.multihash.code,r.multihash.digest.byteLength])}var ze=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 ut,n=new Set;for(let[s,o]of this.wants.entries())try{let i=await this.blockstore.get(o.cid,t);o.wantType===C.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:on(o.cid)})):(this.log("sending have for %c",o.cid),e.addBlockPresence(o.cid,{cid:o.cid.bytes,type:J.HaveBlock})):(this.log("sending block for %c",o.cid),n.add(s),e.addBlock(o.cid,{data:i,prefix:on(o.cid)}))}catch(i){if(i.code!=="ERR_NOT_FOUND")throw i;if(this.log("do not have block for %c",o.cid),!o.sendDontHave||o.sentDontHave===!0)continue;o.sentDontHave=!0,e.addBlockPresence(o.cid,{cid:o.cid.bytes,type:J.DontHaveBlock})}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 Ve=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=ce({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 ze({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=P(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===C.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??C.WantBlock,sendDontHave:s.sendDontHave??!1}))}}this.log("send blocks to peer"),await n.sendBlocksToPeer()}async receivedBlock(t,e){let n=P(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 Sa=we(Ds(),1);var Vt;(function(r){r[r.A=1]="A",r[r.CNAME=5]="CNAME",r[r.TXT=16]="TXT",r[r.AAAA=28]="AAAA"})(Vt||(Vt={}));var an=we(Is(),1);var ka=Math.LN2*Math.LN2,He=class r{static create(t,e=.005){let n=La(t,e);return new r(n)}seeds;bits;buffer;constructor(t={}){t.seeds!=null?this.seeds=t.seeds:this.seeds=Ia(t.hashes??8),this.bits=t.bits??1024,this.buffer=O(Math.ceil(this.bits/8))}add(t){typeof t=="string"&&(t=wt(t));for(let e=0;e<this.seeds.length;e++){let s=an.default.x86.hash32(t,this.seeds[e])%this.bits;this.setbit(s)}}has(t){typeof t=="string"&&(t=wt(t));for(let e=0;e<this.seeds.length;e++){let s=an.default.x86.hash32(t,this.seeds[e])%this.bits;if(!this.getbit(s))return!1}return!0}clear(){this.buffer.fill(0)}setbit(t){let e=0,n=t;for(;n>7;)e++,n-=8;let s=this.buffer[e];s|=1<<n,this.buffer[e]=s}getbit(t){let e=0,n=t;for(;n>7;)e++,n-=8;return(this.buffer[e]&1<<n)!==0}};function La(r,t=.005){let e=Math.round(-1*r*Math.log(t)/ka),n=Math.round(e/r*Math.LN2);return{bits:e,hashes:n}}function Ia(r){let t,e,n=[];for(let s=0;s<r;s++)for(t=new ft(Oe(4)),n[s]=t.getUint32(0,!0),e=0;e<s;e++)if(n[s]===n[e]){s--;break}return n}var Tt=class extends rt{intialPeerSearchComplete;requests;name;log;logger;minProviders;maxProviders;providers;evictionFilter;constructor(t,e){super(),q(1/0,this),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=He.create(this.maxProviders)}async retrieve(t,e={}){let n=lt.encode(t.multihash.bytes),s=this.requests.get(n);if(s!=null)return this.log("join existing request for %c",t),s;let o=Z();if(this.requests.set(n,o.promise),this.providers.length===0){let u=!1;this.intialPeerSearchComplete==null&&(u=!0,this.log=this.logger.forComponent(`${this.name}:${t}`),this.intialPeerSearchComplete=this.findProviders(t,this.minProviders,e)),await this.intialPeerSearchComplete,u&&this.log("found initial session peers for %c",t)}let i=!1,c=new Pt({concurrency:this.maxProviders});c.addEventListener("error",()=>{}),c.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)}),c.addEventListener("success",u=>{i=!0,o.resolve(u.detail.result)}),c.addEventListener("idle",()=>{i||e.signal?.aborted===!0||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 d=this.providers[Math.floor(Math.random()*this.providers.length)];this.evict(d)}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 l=u=>{c.add(async()=>this.queryProvider(t,u.detail,e),{provider:u.detail}).catch(d=>{e.signal?.aborted!==!0&&this.log.error("error retrieving session block for %c",t,d)})};this.addEventListener("provider",l),Promise.all([...this.providers].map(async u=>c.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)});try{return await o.promise}finally{this.removeEventListener("provider",l),c.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=Z(),o=0;return Promise.resolve().then(async()=>{this.log("finding %d-%d new provider(s) for %c",e,this.maxProviders,t);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 M(`Found ${o} of ${e} ${this.name} providers for ${t}`,"ERR_INSUFFICIENT_PROVIDERS_FOUND")}).catch(i=>{this.log.error("error searching routing for potential session peers for %c",t,i.errors??i),s.reject(i)}),s.promise}};var cn=class extends Tt{wantList;network;constructor(t,e){super(t,{...e,name:"helia:bitswap:session"}),this.wantList=t.wantList,this.network=t.network}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.toBytes()}equals(t,e){return t.equals(e)}};function Ps(r,t){return new cn(r,t)}var We=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 ln=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 Rs(r){let{name:t,metrics:e}=r,n;return e!=null?n=new ln({name:t,metrics:e}):n=new Map,n}function Ta(r){if(!(r instanceof Uint8Array))throw new Error("arg needs to be a Uint8Array");let t=[];for(;r.length>0;){let e=tt(r);t.push(e),r=r.slice(D(e))}return t}var Cs=Ta;var qe=class extends rt{peers;wants;network;log;sendMessagesDelay;sendMessagesTimeout;hashLoader;sendingMessages;constructor(t,e={}){super(),q(1/0,this),this.peers=ce({name:"helia_bitswap_peers",metrics:t.metrics}),this.wants=Rs({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=P(t.multihash.bytes,"base64"),s=this.wants.get(n);s==null&&(s={cid:t,priority:e.priority??1,wantType:e.wantType??C.WantBlock,cancel:!1,sendDontHave:!0},this.wants.set(n,s)),s.wantType===C.WantHave&&e.wantType===C.WantBlock&&(s.wantType=C.WantBlock),await this.sendMessagesDebounced();try{return e.wantType===C.WantBlock?(await Y(this,"block",e?.signal,{filter:c=>K(t.multihash.digest,c.detail.cid.multihash.digest),errorMessage:"Want was aborted"})).detail:(await Y(this,"presence",e?.signal,{filter:i=>K(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=Z(),await Promise.all([...this.peers.entries()].map(async([t,e])=>{let n=new Set,s=new ut;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=P(t.multihash.bytes,"base64");return this.wants.has(e)}async wantSessionPresence(t,e,n={}){let s=new ut;return s.addWantlistEntry(t,{cid:t.bytes,sendDontHave:!0,wantType:C.WantHave,priority:1}),await this.network.sendMessage(e,s),(await Y(this,"presence",n.signal,{filter:i=>e.equals(i.detail.sender)&&K(t.multihash.digest,i.detail.cid.multihash.digest)})).detail}async wantBlock(t,e={}){return this.addEntry(t,{...e,wantType:C.WantBlock})}async wantSessionBlock(t,e,n={}){let s=new ut;return s.addWantlistEntry(t,{cid:t.bytes,sendDontHave:!0,wantType:C.WantBlock,priority:1}),await this.network.sendMessage(e,s),(await Y(this,"presence",n.signal,{filter:i=>e.equals(i.detail.sender)&&K(t.multihash.digest,i.detail.cid.multihash.digest)})).detail}async receivedBlock(t,e){let n=P(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=Cs(s.prefix),i=o[0],c=o[1],l=o[2],u=l===At.code?At:await this.hashLoader?.getHasher(l);if(u==null){this.log.error("unknown hash algorithm",l);continue}let d=u.digest(s.data);d.then!=null&&(d=await d);let f=H.create(i===0?0:1,c,d);this.log("received block from %p for %c",t,f),this.safeDispatchEvent("block",{detail:{sender:t,cid:f,block:s.data}}),this.safeDispatchEvent("presence",{detail:{sender:t,cid:f,has:!0,block:s.data}});let x=P(f.multihash.bytes,"base64"),a=this.wants.get(x);a!=null&&(a.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===J.HaveBlock}})}n&&await this.sendMessagesDebounced()}async peerConnected(t){let e=new Set,n=new ut(!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:C.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 Ge=class{log;logger;stats;network;blockstore;peerWantLists;wantList;constructor(t,e={}){this.logger=t.logger,this.log=t.logger.forComponent("helia:bitswap"),this.blockstore=t.blockstore,this.stats=new We(t),this.network=new Fe(t,e),this.peerWantLists=new Ve({...t,network:this.network},e),this.wantList=new qe({...t,network:this.network},e)}createSession(t={}){return Ps({wantList:this.wantList,network:this.network,logger:this.logger},t)}async want(t,e={}){let n=new AbortController,s=Pn([n.signal,e.signal]);q(1/0,n.signal,s),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 Ns=(r,t={})=>new Ge(r,t);var un=class{bitswap;started;constructor(t,e={}){let{hashers:n}=t;this.bitswap=Ns(t,{hashLoader:{getHasher:async s=>{let o;if(typeof s=="string"?o=Object.values(n).find(i=>i.name===s):o=n[s],o!=null)return o;throw new Error(`Could not load hasher for code/name "${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 Us(r={}){return t=>new un(t,r)}var Xe=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,c=this.peekChar();if(c===void 0)return;let l=c==="0",u=2**(8*s)-1;for(;;){let d=this.readAtomically(()=>{let f=this.readChar();if(f===void 0)return;let x=Number.parseInt(f,t);if(!Number.isNaN(x))return x});if(d===void 0)break;if(o*=t,o+=d,o>u||(i+=1,e!==void 0&&i>e))return}if(i!==0)return!n&&l&&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),[c]=t(o.subarray(0,i));return e.set(o.subarray(0,c),16-c),e})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};var Ms=45,_a=15,Ht=new Xe;function hn(r){if(!(r.length>_a))return Ht.new(r).parseWith(()=>Ht.readIPv4Addr())}function fn(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>Ms))return Ht.new(r).parseWith(()=>Ht.readIPv6Addr())}function Qe(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>Ms))return Ht.new(r).parseWith(()=>Ht.readIPAddr())}function Wt(r){return!!hn(r)}function qt(r){return!!fn(r)}function je(r){return!!Qe(r)}var Bs=we(Fs(),1),Da=["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"],Pa=Da.map(r=>new Bs.Netmask(r));function Ra(r){for(let t of Pa)if(t.contains(r))return!0;return!1}function Ca(r){return/^::$/.test(r)||/^::1$/.test(r)||/^::f{4}:([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)||/^::f{4}:0.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.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 Os(r){return Wt(r)?Ra(r):qt(r)?Ca(r):void 0}var Od=parseInt("0xFFFF",16),$d=new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);var Vs=Wt,Ba=qt,dn=function(r){let t=0;if(r=r.toString().trim(),Vs(r)){let e=new Uint8Array(t+4);return r.split(/\./g).forEach(n=>{e[t++]=parseInt(n,10)&255}),e}if(Ba(r)){let e=r.split(":",8),n;for(n=0;n<e.length;n++){let o=Vs(e[n]),i;o&&(i=dn(e[n]),e[n]=P(i.slice(0,2),"base16")),i!=null&&++n<8&&e.splice(n,0,P(i.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 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++){let o=parseInt(e[n],16);s[t++]=o>>8&255,s[t++]=o&255}return s}throw new Error("invalid ip address")},Hs=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 o=0;o<e;o++)s.push(r[t+o]);return s.join(".")}if(e===16){let s=[];for(let o=0;o<e;o+=2)s.push(n.getUint16(t+o).toString(16));return s.join(":").replace(/(^|:)0(:0)*:0(:|$)/,"$1::$3").replace(/:{3,4}/,"::")}return""};var Gt={},pn={},$a=[[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"],[777,-1,"memory"]];$a.forEach(r=>{let t=za(...r);pn[t.code]=t,Gt[t.name]=t});function za(r,t,e,n,s){return{code:r,size:t,name:e,resolvable:!!n,path:!!s}}function A(r){if(typeof r=="number"){if(pn[r]!=null)return pn[r];throw new Error(`no protocol with code: ${r}`)}else if(typeof r=="string"){if(Gt[r]!=null)return Gt[r];throw new Error(`no protocol with name: ${r}`)}throw new Error(`invalid protocol id type: ${typeof r}`)}var Ep=A("ip4"),vp=A("ip6"),Ap=A("ipcidr");function gn(r,t){switch(A(r).code){case 4:case 41:return Ha(t);case 42:return Gs(t);case 6:case 273:case 33:case 132:return Qs(t).toString();case 53:case 54:case 55:case 56:case 400:case 449:case 777:return Gs(t);case 421:return Xa(t);case 444:return Xs(t);case 445:return Xs(t);case 466:return Ga(t);default:return P(t,"base16")}}function wn(r,t){switch(A(r).code){case 4:return Ws(t);case 41:return Ws(t);case 42:return qs(t);case 6:case 273:case 33:case 132:return bn(parseInt(t,10));case 53:case 54:case 55:case 56:case 400:case 449:case 777:return qs(t);case 421:return Wa(t);case 444:return Qa(t);case 445:return ja(t);case 466:return qa(t);default:return wt(t,"base16")}}var mn=Object.values(gt).map(r=>r.decoder),Va=function(){let r=mn[0].or(mn[1]);return mn.slice(2).forEach(t=>r=r.or(t)),r}();function Ws(r){if(!je(r))throw new Error("invalid ip address");return dn(r)}function Ha(r){let t=Hs(r,0,r.length);if(t==null)throw new Error("ipBuff is required");if(!je(t))throw new Error("invalid ip address");return t}function bn(r){let t=new ArrayBuffer(2);return new DataView(t).setUint16(0,r),new Uint8Array(t)}function Qs(r){return new DataView(r.buffer).getUint16(r.byteOffset)}function qs(r){let t=wt(r),e=Uint8Array.from(nt(t.length));return j([e,t],e.length+t.length)}function Gs(r){let t=tt(r);if(r=r.slice(D(t)),r.length!==t)throw new Error("inconsistent lengths");return P(r)}function Wa(r){let t;r[0]==="Q"||r[0]==="1"?t=Et(U.decode(`z${r}`)).bytes:t=H.parse(r).multihash.bytes;let e=Uint8Array.from(nt(t.length));return j([e,t],e.length+t.length)}function qa(r){let t=Va.decode(r),e=Uint8Array.from(nt(t.length));return j([e,t],e.length+t.length)}function Ga(r){let t=tt(r),e=r.slice(D(t));if(e.length!==t)throw new Error("inconsistent lengths");return"u"+P(e,"base64url")}function Xa(r){let t=tt(r),e=r.slice(D(t));if(e.length!==t)throw new Error("inconsistent lengths");return P(e,"base58btc")}function Qa(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=ct.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=bn(n);return j([e,s],e.length+s.length)}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!==56)throw new Error(`failed to parse onion addr: ${t[0]} not a Tor onion3 address.`);let e=ct.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=bn(n);return j([e,s],e.length+s.length)}function Xs(r){let t=r.slice(0,r.length-2),e=r.slice(r.length-2),n=P(t,"base32"),s=Qs(e);return`${n}:${s}`}function js(r){r=yn(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 o=0;o<s.length;o++){let i=s[o],c=A(i);if(c.size===0){t.push([c.code]),e.push([c.code]);continue}if(o++,o>=s.length)throw Js("invalid address: "+r);if(c.path===!0){n=yn(s.slice(o).join("/")),t.push([c.code,wn(c.code,n)]),e.push([c.code,n]);break}let l=wn(c.code,s[o]);t.push([c.code,l]),e.push([c.code,gn(c.code,l)])}return{string:Ks(e),bytes:En(t),tuples:t,stringTuples:e,path:n}}function xn(r){let t=[],e=[],n=null,s=0;for(;s<r.length;){let o=tt(r,s),i=D(o),c=A(o),l=Ka(c,r.slice(s+i));if(l===0){t.push([o]),e.push([o]),s+=i;continue}let u=r.slice(s+i,s+i+l);if(s+=l+i,s>r.length)throw Js("Invalid address Uint8Array: "+P(r,"base16"));t.push([o,u]);let d=gn(o,u);if(e.push([o,d]),c.path===!0){n=d;break}}return{bytes:Uint8Array.from(r),string:Ks(e),tuples:t,stringTuples:e,path:n}}function Ks(r){let t=[];return r.map(e=>{let n=A(e[0]);return t.push(n.name),e.length>1&&e[1]!=null&&t.push(e[1]),null}),yn(t.join("/"))}function En(r){return j(r.map(t=>{let e=A(t[0]),n=Uint8Array.from(nt(e.code));return t.length>1&&t[1]!=null&&(n=j([n,t[1]])),n}))}function Ka(r,t){if(r.size>0)return r.size/8;if(r.size===0)return 0;{let e=tt(t instanceof Uint8Array?t:Uint8Array.from(t));return e+D(e)}}function yn(r){return"/"+r.trim().split("/").filter(t=>t).join("/")}function Js(r){return new Error("Error parsing address: "+r)}var Ja=Symbol.for("nodejs.util.inspect.custom"),vn=Symbol.for("@multiformats/js-multiaddr/multiaddr"),Za=[A("dns").code,A("dns4").code,A("dns6").code,A("dnsaddr").code],Ke=class r{bytes;#t;#e;#r;#n;[vn]=!0;constructor(t){t==null&&(t="");let e;if(t instanceof Uint8Array)e=xn(t);else if(typeof t=="string"){if(t.length>0&&t.charAt(0)!=="/")throw new Error(`multiaddr "${t}" must start with a "/"`);e=js(t)}else if(Ys(t))e=xn(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,o="",i=A("tcp"),c=A("udp"),l=A("ip4"),u=A("ip6"),d=A("dns6"),f=A("ip6zone");for(let[a,h]of this.stringTuples())a===f.code&&(o=`%${h??""}`),Za.includes(a)&&(e=i.name,s=443,n=`${h??""}${o}`,t=a===d.code?6:4),(a===i.code||a===c.code)&&(e=A(a).name,s=parseInt(h??"")),(a===l.code||a===u.code)&&(e=A(a).name,n=`${h??""}${o}`,t=a===u.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({},A(t)))}protoCodes(){return this.#e.map(([t])=>t)}protoNames(){return this.#e.map(([t])=>A(t).name)}tuples(){return this.#e}stringTuples(){return this.#r}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(En(e.slice(0,n)));return this}getPeerId(){try{let t=[];this.stringTuples().forEach(([n,s])=>{n===Gt.p2p.code&&t.push([n,s]),n===Gt["p2p-circuit"].code&&(t=[])});let e=t.pop();if(e?.[1]!=null){let n=e[1];return n[0]==="Q"||n[0]==="1"?P(U.decode(`z${n}`),"base58btc"):P(H.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(o=>o.resolvable);if(e==null)return[this];let n=Zs.get(e.name);if(n==null)throw new M(`no available resolver for ${e.name}`,"ERR_NO_AVAILABLE_RESOLVER");return(await n(this,t)).map(o=>ue(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(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)}[Ja](){return`Multiaddr(${this.#t})`}};var Zs=new Map;function Ys(r){return!!r?.[vn]}function ue(r){return new Ke(r)}var Ya=r=>r.toString().split("/").slice(1),he=r=>({match:t=>t.length<1?!1:r(t[0])?t.slice(1):!1,pattern:"fn"}),L=r=>({match:t=>he(e=>e===r).match(t),pattern:r}),Ye=()=>({match:r=>he(t=>typeof t=="string").match(r),pattern:"{string}"}),tr=()=>({match:r=>he(t=>!isNaN(parseInt(t))).match(r),pattern:"{number}"}),F=()=>({match:r=>{if(r.length<2||r[0]!=="p2p"&&r[0]!=="ipfs")return!1;if(r[1].startsWith("Q")||r[1].startsWith("1"))try{U.decode(`z${r[1]}`)}catch{return!1}else return!1;return r.slice(2)},pattern:"/p2p/{peerid}"}),Je=()=>({match:r=>{if(r.length<2||r[0]!=="certhash")return!1;try{Fr.decode(r[1])}catch{return!1}return r.slice(2)},pattern:"/certhash/{certhash}"}),B=r=>({match:t=>{let e=r.match(t);return e===!1?t:e},pattern:`optional(${r.pattern})`}),X=(...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(", ")})`}),_=(...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 N(...r){function t(s){let o=Ya(s);for(let i of r){let c=i.match(o);if(c===!1)return!1;o=c}return o}function e(s){return t(s)!==!1}function n(s){let o=t(s);return o===!1?!1:o.length===0}return{matches:e,exactMatch:n}}var Sn=_(L("dns4"),Ye()),kn=_(L("dns6"),Ye()),Ln=_(L("dnsaddr"),Ye()),to=_(L("dns"),Ye()),Zp=N(Sn),Yp=N(kn),tm=N(Ln),eo=N(X(to,Ln,Sn,kn)),ro=_(L("ip4"),he(Wt)),no=_(L("ip6"),he(qt)),so=X(ro,no),ot=X(so,to,Sn,kn,Ln),em=N(ot),rm=N(ro),nm=N(no),sm=N(so),er=_(ot,L("tcp"),tr()),fe=_(ot,L("udp"),tr()),tc=X(er,fe),om=N(er),im=N(fe),In=_(fe,L("quic")),rr=_(fe,L("quic-v1")),ec=X(In,rr),am=N(In),cm=N(rr),An=X(ot,er,fe,In,rr),oo=X(_(An,L("ws"),B(F()))),lm=N(oo),io=X(_(An,L("wss"),B(F())),_(An,L("tls"),L("ws"),B(F()))),um=N(io),ao=_(tc,L("webrtc-direct"),Je(),B(Je()),B(F())),hm=N(ao),co=_(rr,L("webtransport"),B(Je()),B(Je()),B(F())),fm=N(co),Ze=X(oo,io,_(er,B(F())),_(ec,B(F())),_(ot,B(F())),ao,co,F()),dm=N(Ze),rc=_(Ze,L("p2p-circuit"),F()),pm=N(rc),nc=X(_(Ze,L("p2p-circuit"),L("webrtc"),F()),_(Ze,L("webrtc"),B(F())),L("webrtc")),mm=N(nc),sc=X(_(ot,L("tcp"),tr(),L("http"),B(F())),_(ot,L("http"),B(F()))),lo=N(sc),oc=X(_(ot,L("tcp"),X(_(L("443"),L("http")),_(tr(),L("https"))),B(F())),_(ot,L("tls"),L("http"),B(F())),_(ot,L("https"),B(F()))),uo=N(oc);var ic=[A("tcp").code,A("dns").code,A("dnsaddr").code,A("dns4").code,A("dns6").code];function ho(r){let t;try{t=A("sni").code}catch{return null}for(let[e,n]of r)if(e===t&&n!==void 0)return n;return null}function fo(r){return r.some(([t,e])=>t===A("tls").code)}function Q(r,t,e){let n=po[A(r).name];if(n===void 0)throw new Error(`Can't interpret protocol ${A(r).name}`);let s=n(t,e);return r===A("ip6").code?`[${s}]`:s}var po={ip4:(r,t)=>r,ip6:(r,t)=>t.length===0?r:`[${r}]`,tcp:(r,t)=>{let e=t.pop();if(e===void 0)throw new Error("Unexpected end of multiaddr");return`tcp://${Q(e[0],e[1]??"",t)}:${r}`},udp:(r,t)=>{let e=t.pop();if(e===void 0)throw new Error("Unexpected end of multiaddr");return`udp://${Q(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===void 0)throw new Error("Unexpected end of multiaddr");return`${Q(e[0],e[1]??"",t)}/ipfs/${r}`},p2p:(r,t)=>{let e=t.pop();if(e===void 0)throw new Error("Unexpected end of multiaddr");return`${Q(e[0],e[1]??"",t)}/p2p/${r}`},http:(r,t)=>{let e=fo(t),n=ho(t);if(e&&n!==null)return`https://${n}`;let s=e?"https://":"http://",o=t.pop();if(o===void 0)throw new Error("Unexpected end of multiaddr");let i=Q(o[0],o[1]??"",t);return i=i.replace("tcp://",""),`${s}${i}`},tls:(r,t)=>{let e=t.pop();if(e===void 0)throw new Error("Unexpected end of multiaddr");return Q(e[0],e[1]??"",t)},sni:(r,t)=>{let e=t.pop();if(e===void 0)throw new Error("Unexpected end of multiaddr");return Q(e[0],e[1]??"",t)},https:(r,t)=>{let e=t.pop();if(e===void 0)throw new Error("Unexpected end of multiaddr");let n=Q(e[0],e[1]??"",t);return n=n.replace("tcp://",""),`https://${n}`},ws:(r,t)=>{let e=fo(t),n=ho(t);if(e&&n!==null)return`wss://${n}`;let s=e?"wss://":"ws://",o=t.pop();if(o===void 0)throw new Error("Unexpected end of multiaddr");let i=Q(o[0],o[1]??"",t);return i=i.replace("tcp://",""),`${s}${i}`},wss:(r,t)=>{let e=t.pop();if(e===void 0)throw new Error("Unexpected end of multiaddr");let n=Q(e[0],e[1]??"",t);return n=n.replace("tcp://",""),`wss://${n}`},"p2p-websocket-star":(r,t)=>{let e=t.pop();if(e===void 0)throw new Error("Unexpected end of multiaddr");return`${Q(e[0],e[1]??"",t)}/p2p-websocket-star`},"p2p-webrtc-star":(r,t)=>{let e=t.pop();if(e===void 0)throw new Error("Unexpected end of multiaddr");return`${Q(e[0],e[1]??"",t)}/p2p-webrtc-star`},"p2p-webrtc-direct":(r,t)=>{let e=t.pop();if(e===void 0)throw new Error("Unexpected end of multiaddr");return`${Q(e[0],e[1]??"",t)}/p2p-webrtc-direct`}};function mo(r,t){let n=ue(r).stringTuples(),s=n.pop();if(s===void 0)throw new Error("Unexpected end of multiaddr");let o=A(s[0]),i=po[o.name];if(i==null)throw new Error(`No interpreter found for ${o.name}`);let c=i(s[1]??"",n);return t?.assumeHttp!==!1&&ic.includes(s[0])&&(c=c.replace(/^.*:\/\//,""),s[1]==="443"?c=`https://${c}`:c=`http://${c}`),(c.startsWith("http://")||c.startsWith("https://"))&&(c=new URL(c).toString(),c.endsWith("/")&&(c=c.substring(0,c.length-1))),c}var nr=class{url;#t=0;#e=0;#r=0;#n=0;#s=new Map;log;constructor(t,e){this.url=t instanceof URL?t:new URL(t),this.log=e.forComponent(`helia:trustless-gateway-block-broker:${this.url.hostname}`)}#o(t){let e=t.multihash.bytes;return lt.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.#o(t),o=new AbortController,i=()=>{o.abort()};e?.addEventListener("abort",i);try{let c=this.#s.get(s);return c==null&&(this.#t++,c=fetch(n.toString(),{signal:o.signal,headers:{Accept:"application/vnd.ipld.raw"},cache:"force-cache"}).then(async l=>{if(this.log("GET %s %d",n,l.status),!l.ok)throw this.#e++,new Error(`unable to fetch raw block for CID ${t} from gateway ${this.url}`);return this.#n++,new Uint8Array(await l.arrayBuffer())}),this.#s.set(s,c)),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",i),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}}};function ac(r,t,e){return r.filter(n=>uo.matches(n)||t&&lo.matches(n)?e||eo.matches(n)?!0:Os(n.toOptions().host)===!1:!1)}async function*sr(r,t,e,n,s,o){for await(let i of t.findProviders(r,o)){let c=ac(i.multiaddrs,n,s);if(c.length===0)continue;let l=mo(c[0]);yield new nr(l,e)}}var Tn=class extends Tt{routing;allowInsecure;allowLocal;constructor(t,e){super(t,{...e,name:"helia:trustless-gateway:session"}),this.routing=t.routing,this.allowInsecure=e.allowInsecure??or,this.allowLocal=e.allowLocal??ir}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*sr(t,this.routing,this.logger,this.allowInsecure,this.allowLocal,e)}toEvictionKey(t){return t.url.toString()}equals(t,e){return t.url.toString()===e.url.toString()}};function go(r,t){return new Tn(r,t)}var ar=class{allowInsecure;allowLocal;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??or,this.allowLocal=e.allowLocal??ir}async retrieve(t,e={}){let n=[];for await(let s of sr(t,this.routing,this.logger,this.allowInsecure,this.allowLocal,e)){this.log("getting block for %c from %s",t,s.url);try{let o=await s.getRawBlock(t,e.signal);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 go({logger:this.logger,routing:this.routing},t)}};var or=!1,ir=!1;function wo(r={}){return t=>new ar(t,r)}return Ao(cc);})();
2
+ "use strict";var HeliaBlockBrokers=(()=>{var vo=Object.create;var ge=Object.defineProperty;var So=Object.getOwnPropertyDescriptor;var Ao=Object.getOwnPropertyNames;var ko=Object.getPrototypeOf,Lo=Object.prototype.hasOwnProperty;var we=(r,t)=>()=>(t||r((t={exports:{}}).exports,t),t.exports),q=(r,t)=>{for(var e in t)ge(r,e,{get:t[e],enumerable:!0})},Bn=(r,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of Ao(t))!Lo.call(r,s)&&s!==e&&ge(r,s,{get:()=>t[s],enumerable:!(n=So(t,s))||n.enumerable});return r};var lr=(r,t,e)=>(e=r!=null?vo(ko(r)):{},Bn(t||!r||!r.__esModule?ge(e,"default",{value:r,enumerable:!0}):e,r)),Io=r=>Bn(ge({},"__esModule",{value:!0}),r);var Ps=we((ae,Ve)=>{(function(r,t){"use strict";var e={version:"3.0.0",x86:{},x64:{},inputValidation:!0};function n(a){if(!Array.isArray(a)&&!ArrayBuffer.isView(a))return!1;for(var h=0;h<a.length;h++)if(!Number.isInteger(a[h])||a[h]<0||a[h]>255)return!1;return!0}function s(a,h){return(a&65535)*h+(((a>>>16)*h&65535)<<16)}function o(a,h){return a<<h|a>>>32-h}function i(a){return a^=a>>>16,a=s(a,2246822507),a^=a>>>13,a=s(a,3266489909),a^=a>>>16,a}function c(a,h){a=[a[0]>>>16,a[0]&65535,a[1]>>>16,a[1]&65535],h=[h[0]>>>16,h[0]&65535,h[1]>>>16,h[1]&65535];var p=[0,0,0,0];return p[3]+=a[3]+h[3],p[2]+=p[3]>>>16,p[3]&=65535,p[2]+=a[2]+h[2],p[1]+=p[2]>>>16,p[2]&=65535,p[1]+=a[1]+h[1],p[0]+=p[1]>>>16,p[1]&=65535,p[0]+=a[0]+h[0],p[0]&=65535,[p[0]<<16|p[1],p[2]<<16|p[3]]}function l(a,h){a=[a[0]>>>16,a[0]&65535,a[1]>>>16,a[1]&65535],h=[h[0]>>>16,h[0]&65535,h[1]>>>16,h[1]&65535];var p=[0,0,0,0];return p[3]+=a[3]*h[3],p[2]+=p[3]>>>16,p[3]&=65535,p[2]+=a[2]*h[3],p[1]+=p[2]>>>16,p[2]&=65535,p[2]+=a[3]*h[2],p[1]+=p[2]>>>16,p[2]&=65535,p[1]+=a[1]*h[3],p[0]+=p[1]>>>16,p[1]&=65535,p[1]+=a[2]*h[2],p[0]+=p[1]>>>16,p[1]&=65535,p[1]+=a[3]*h[1],p[0]+=p[1]>>>16,p[1]&=65535,p[0]+=a[0]*h[3]+a[1]*h[2]+a[2]*h[1]+a[3]*h[0],p[0]&=65535,[p[0]<<16|p[1],p[2]<<16|p[3]]}function u(a,h){return h%=64,h===32?[a[1],a[0]]:h<32?[a[0]<<h|a[1]>>>32-h,a[1]<<h|a[0]>>>32-h]:(h-=32,[a[1]<<h|a[0]>>>32-h,a[0]<<h|a[1]>>>32-h])}function d(a,h){return h%=64,h===0?a:h<32?[a[0]<<h|a[1]>>>32-h,a[1]<<h]:[a[1]<<h-32,0]}function f(a,h){return[a[0]^h[0],a[1]^h[1]]}function x(a){return a=f(a,[0,a[0]>>>1]),a=l(a,[4283543511,3981806797]),a=f(a,[0,a[0]>>>1]),a=l(a,[3301882366,444984403]),a=f(a,[0,a[0]>>>1]),a}e.x86.hash32=function(a,h){if(e.inputValidation&&!n(a))return t;h=h||0;for(var p=a.length%4,v=a.length-p,m=h,g=0,w=3432918353,y=461845907,E=0;E<v;E=E+4)g=a[E]|a[E+1]<<8|a[E+2]<<16|a[E+3]<<24,g=s(g,w),g=o(g,15),g=s(g,y),m^=g,m=o(m,13),m=s(m,5)+3864292196;switch(g=0,p){case 3:g^=a[E+2]<<16;case 2:g^=a[E+1]<<8;case 1:g^=a[E],g=s(g,w),g=o(g,15),g=s(g,y),m^=g}return m^=a.length,m=i(m),m>>>0},e.x86.hash128=function(a,h){if(e.inputValidation&&!n(a))return t;h=h||0;for(var p=a.length%16,v=a.length-p,m=h,g=h,w=h,y=h,E=0,A=0,b=0,T=0,at=597399067,de=2869860233,pe=951274213,me=2716044179,k=0;k<v;k=k+16)E=a[k]|a[k+1]<<8|a[k+2]<<16|a[k+3]<<24,A=a[k+4]|a[k+5]<<8|a[k+6]<<16|a[k+7]<<24,b=a[k+8]|a[k+9]<<8|a[k+10]<<16|a[k+11]<<24,T=a[k+12]|a[k+13]<<8|a[k+14]<<16|a[k+15]<<24,E=s(E,at),E=o(E,15),E=s(E,de),m^=E,m=o(m,19),m+=g,m=s(m,5)+1444728091,A=s(A,de),A=o(A,16),A=s(A,pe),g^=A,g=o(g,17),g+=w,g=s(g,5)+197830471,b=s(b,pe),b=o(b,17),b=s(b,me),w^=b,w=o(w,15),w+=y,w=s(w,5)+2530024501,T=s(T,me),T=o(T,18),T=s(T,at),y^=T,y=o(y,13),y+=m,y=s(y,5)+850148119;switch(E=0,A=0,b=0,T=0,p){case 15:T^=a[k+14]<<16;case 14:T^=a[k+13]<<8;case 13:T^=a[k+12],T=s(T,me),T=o(T,18),T=s(T,at),y^=T;case 12:b^=a[k+11]<<24;case 11:b^=a[k+10]<<16;case 10:b^=a[k+9]<<8;case 9:b^=a[k+8],b=s(b,pe),b=o(b,17),b=s(b,me),w^=b;case 8:A^=a[k+7]<<24;case 7:A^=a[k+6]<<16;case 6:A^=a[k+5]<<8;case 5:A^=a[k+4],A=s(A,de),A=o(A,16),A=s(A,pe),g^=A;case 4:E^=a[k+3]<<24;case 3:E^=a[k+2]<<16;case 2:E^=a[k+1]<<8;case 1:E^=a[k],E=s(E,at),E=o(E,15),E=s(E,de),m^=E}return m^=a.length,g^=a.length,w^=a.length,y^=a.length,m+=g,m+=w,m+=y,g+=m,w+=m,y+=m,m=i(m),g=i(g),w=i(w),y=i(y),m+=g,m+=w,m+=y,g+=m,w+=m,y+=m,("00000000"+(m>>>0).toString(16)).slice(-8)+("00000000"+(g>>>0).toString(16)).slice(-8)+("00000000"+(w>>>0).toString(16)).slice(-8)+("00000000"+(y>>>0).toString(16)).slice(-8)},e.x64.hash128=function(a,h){if(e.inputValidation&&!n(a))return t;h=h||0;for(var p=a.length%16,v=a.length-p,m=[0,h],g=[0,h],w=[0,0],y=[0,0],E=[2277735313,289559509],A=[1291169091,658871167],b=0;b<v;b=b+16)w=[a[b+4]|a[b+5]<<8|a[b+6]<<16|a[b+7]<<24,a[b]|a[b+1]<<8|a[b+2]<<16|a[b+3]<<24],y=[a[b+12]|a[b+13]<<8|a[b+14]<<16|a[b+15]<<24,a[b+8]|a[b+9]<<8|a[b+10]<<16|a[b+11]<<24],w=l(w,E),w=u(w,31),w=l(w,A),m=f(m,w),m=u(m,27),m=c(m,g),m=c(l(m,[0,5]),[0,1390208809]),y=l(y,A),y=u(y,33),y=l(y,E),g=f(g,y),g=u(g,31),g=c(g,m),g=c(l(g,[0,5]),[0,944331445]);switch(w=[0,0],y=[0,0],p){case 15:y=f(y,d([0,a[b+14]],48));case 14:y=f(y,d([0,a[b+13]],40));case 13:y=f(y,d([0,a[b+12]],32));case 12:y=f(y,d([0,a[b+11]],24));case 11:y=f(y,d([0,a[b+10]],16));case 10:y=f(y,d([0,a[b+9]],8));case 9:y=f(y,[0,a[b+8]]),y=l(y,A),y=u(y,33),y=l(y,E),g=f(g,y);case 8:w=f(w,d([0,a[b+7]],56));case 7:w=f(w,d([0,a[b+6]],48));case 6:w=f(w,d([0,a[b+5]],40));case 5:w=f(w,d([0,a[b+4]],32));case 4:w=f(w,d([0,a[b+3]],24));case 3:w=f(w,d([0,a[b+2]],16));case 2:w=f(w,d([0,a[b+1]],8));case 1:w=f(w,[0,a[b]]),w=l(w,E),w=u(w,31),w=l(w,A),m=f(m,w)}return m=f(m,[0,a.length]),g=f(g,[0,a.length]),m=c(m,g),g=c(g,m),m=x(m),g=x(g),m=c(m,g),g=c(g,m),("00000000"+(m[0]>>>0).toString(16)).slice(-8)+("00000000"+(m[1]>>>0).toString(16)).slice(-8)+("00000000"+(g[0]>>>0).toString(16)).slice(-8)+("00000000"+(g[1]>>>0).toString(16)).slice(-8)},typeof ae<"u"?(typeof Ve<"u"&&Ve.exports&&(ae=Ve.exports=e),ae.murmurHash3=e):typeof define=="function"&&define.amd?define([],function(){return e}):(e._murmurHash3=r.murmurHash3,e.noConflict=function(){return r.murmurHash3=e._murmurHash3,e._murmurHash3=t,e.noConflict=t,e},r.murmurHash3=e)})(ae)});var Cs=we((Bh,Rs)=>{Rs.exports=Ps()});var Ms=we((xf,Ns)=>{Ns.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 Hs=we(le=>{(function(){var r,t,e,n,s,o,i,c;c=function(l){var u,d,f,x;return u=(l&255<<24)>>>24,d=(l&255<<16)>>>16,f=(l&65280)>>>8,x=l&255,[u,d,f,x].join(".")},i=function(l){var u,d,f,x,a,h;for(u=[],f=x=0;x<=3&&l.length!==0;f=++x){if(f>0){if(l[0]!==".")throw new Error("Invalid IP");l=l.substring(1)}h=t(l),a=h[0],d=h[1],l=l.substring(d),u.push(a)}if(l.length!==0)throw new Error("Invalid IP");switch(u.length){case 1:if(u[0]>4294967295)throw new Error("Invalid IP");return u[0]>>>0;case 2:if(u[0]>255||u[1]>16777215)throw new Error("Invalid IP");return(u[0]<<24|u[1])>>>0;case 3:if(u[0]>255||u[1]>255||u[2]>65535)throw new Error("Invalid IP");return(u[0]<<24|u[1]<<16|u[2])>>>0;case 4:if(u[0]>255||u[1]>255||u[2]>255||u[3]>255)throw new Error("Invalid IP");return(u[0]<<24|u[1]<<16|u[2]<<8|u[3])>>>0;default:throw new Error("Invalid IP")}},e=function(l){return l.charCodeAt(0)},n=e("0"),o=e("a"),s=e("A"),t=function(l){var u,d,f,x,a;for(x=0,u=10,d="9",f=0,l.length>1&&l[f]==="0"&&(l[f+1]==="x"||l[f+1]==="X"?(f+=2,u=16):"0"<=l[f+1]&&l[f+1]<="9"&&(f++,u=8,d="7")),a=f;f<l.length;){if("0"<=l[f]&&l[f]<=d)x=x*u+(e(l[f])-n)>>>0;else if(u===16)if("a"<=l[f]&&l[f]<="f")x=x*u+(10+e(l[f])-o)>>>0;else if("A"<=l[f]&&l[f]<="F")x=x*u+(10+e(l[f])-s)>>>0;else break;else break;if(x>4294967295)throw new Error("too large");f++}if(f===a)throw new Error("empty octet");return[x,f]},r=function(){function l(u,d){var f,x,a,h;if(typeof u!="string")throw new Error("Missing `net' parameter");if(d||(h=u.split("/",2),u=h[0],d=h[1]),d||(d=32),typeof d=="string"&&d.indexOf(".")>-1){try{this.maskLong=i(d)}catch(p){throw f=p,new Error("Invalid mask: "+d)}for(x=a=32;a>=0;x=--a)if(this.maskLong===4294967295<<32-x>>>0){this.bitmask=x;break}}else if(d||d===0)this.bitmask=parseInt(d,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(u)&this.maskLong)>>>0}catch(p){throw f=p,new Error("Invalid net address: "+u)}if(!(this.bitmask<=32))throw new Error("Invalid mask for ip4: "+d);this.size=Math.pow(2,32-this.bitmask),this.base=c(this.netLong),this.mask=c(this.maskLong),this.hostmask=c(~this.maskLong),this.first=this.bitmask<=30?c(this.netLong+1):this.base,this.last=this.bitmask<=30?c(this.netLong+this.size-2):c(this.netLong+this.size-1),this.broadcast=this.bitmask<=30?c(this.netLong+this.size-1):void 0}return l.prototype.contains=function(u){return typeof u=="string"&&(u.indexOf("/")>0||u.split(".").length!==4)&&(u=new l(u)),u instanceof l?this.contains(u.base)&&this.contains(u.broadcast||u.last):(i(u)&this.maskLong)>>>0===(this.netLong&this.maskLong)>>>0},l.prototype.next=function(u){return u==null&&(u=1),new l(c(this.netLong+this.size*u),this.mask)},l.prototype.forEach=function(u){var d,f,x;for(x=i(this.first),f=i(this.last),d=0;x<=f;)u(c(x),x,d),d++,x++},l.prototype.toString=function(){return this.base+"/"+this.bitmask},l}(),le.ip2long=i,le.long2ip=c,le.Netmask=r}).call(le)});var fc={};q(fc,{bitswap:()=>zs,trustlessGateway:()=>Eo});var ur=Symbol.for("@libp2p/peer-id");var ft=class r extends Error{code;type;constructor(t="The operation was aborted"){super(t),this.name="AbortError",this.code=r.code,this.type=r.type}static code="ABORT_ERR";static type="aborted"},F=class extends Error{code;props;constructor(t,e,n){super(t),this.code=e,this.name=n?.name??"CodeError",this.props=n??{}}};var G=(r,...t)=>{try{[...t]}catch{}};var rt=class extends EventTarget{#t=new Map;constructor(){super(),G(1/0,this)}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 To(t,e))}},hr=class extends Event{detail;constructor(t,e){super(t,e),this.detail=e?.detail}},To=globalThis.CustomEvent??hr;function On(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 Z(){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)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}},_t=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 fr=class extends Error{type;code;constructor(t,e){super(t??"The operation was aborted"),this.type="aborted",this.code=e??"ABORT_ERR"}};function Dt(r={}){return _o(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 _o(r,t){t=t??{};let e=t.onEnd,n=new _t,s,o,i,c=Z(),l=async()=>{try{return n.isEmpty()?i?{done:!0}:await new Promise((v,m)=>{o=g=>{o=null,n.push(g);try{v(r(n))}catch(w){m(w)}return s}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{c.resolve(),c=Z()})}},u=v=>o!=null?o(v):(n.push(v),s),d=v=>(n=new _t,o!=null?o({error:v}):(n.push({error:v}),s)),f=v=>{if(i)return s;if(t?.objectMode!==!0&&v?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return u({done:!1,value:v})},x=v=>i?s:(i=!0,v!=null?d(v):u({done:!0})),a=()=>(n=new _t,x(),{done:!0}),h=v=>(x(v),{done:!0});if(s={[Symbol.asyncIterator](){return this},next:l,return:a,throw:h,push:f,end:x,get readableLength(){return n.size},onEmpty:async v=>{let m=v?.signal;if(m?.throwIfAborted(),n.isEmpty())return;let g,w;m!=null&&(g=new Promise((y,E)=>{w=()=>{E(new fr)},m.addEventListener("abort",w)}));try{await Promise.race([c.promise,g])}finally{w!=null&&m!=null&&m?.removeEventListener("abort",w)}}},e==null)return s;let p=s;return s={[Symbol.asyncIterator](){return this},next(){return p.next()},throw(v){return p.throw(v),e!=null&&(e(v),e=void 0),{done:!0}},return(){return p.return(),e!=null&&(e(),e=void 0),{done:!0}},push:f,end(v){return p.end(v),e!=null&&(e(v),e=void 0),s},get readableLength(){return p.readableLength},onEmpty:v=>p.onEmpty(v)},s}var dr=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 Y(r,t,e,n){let s=new dr(n?.errorMessage,n?.errorCode);return e?.aborted===!0?Promise.reject(s):new Promise((o,i)=>{function c(){e?.removeEventListener("abort",d),r.removeEventListener(t,l),n?.errorEvent!=null&&r.removeEventListener(n.errorEvent,u)}let l=f=>{try{if(n?.filter?.(f)===!1)return}catch(x){c(),i(x);return}c(),o(f)},u=f=>{c(),i(f.detail)},d=()=>{c(),i(s)};e?.addEventListener("abort",d),r.addEventListener(t,l),n?.errorEvent!=null&&r.addEventListener(n.errorEvent,u)})}var ye=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 $n(r,t,e){if(t==null)return r;if(t.aborted)return Promise.reject(new ye(e?.errorMessage,e?.errorCode,e?.errorName));let n,s=new ye(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 xe=class{deferred;signal;constructor(t){this.signal=t,this.deferred=Z(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new ft)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function Do(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var Ee=class{id;fn;options;recipients;status;timeline;controller;constructor(t,e){this.id=Do(),this.status="queued",this.fn=t,this.options=e,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,G(1/0,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 ft),this.cleanup())}async join(t={}){let e=new xe(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 $n(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 Pt=class extends rt{concurrency;queue;pending;sort;constructor(t={}){super(),this.concurrency=t.concurrency??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){e?.signal?.throwIfAborted();let n=new Ee(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 ft)}),this.clear()}async onEmpty(t){this.size!==0&&await Y(this,"empty",t?.signal)}async onSizeLessThan(t,e){this.size<t||await Y(this,"next",e?.signal,{filter:()=>this.size<t})}async onIdle(t){this.pending===0&&this.size===0||await Y(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=Dt({objectMode:!0}),n=l=>{l!=null?this.abort():this.clear(),e.end(l)},s=l=>{l.detail!=null&&e.push(l.detail)},o=l=>{n(l.detail)},i=()=>{n()},c=()=>{n(new F("Queue aborted","ERR_QUEUE_ABORTED"))};this.addEventListener("completed",s),this.addEventListener("error",o),this.addEventListener("idle",i),t?.signal?.addEventListener("abort",c);try{yield*e}finally{this.removeEventListener("completed",s),this.removeEventListener("error",o),this.removeEventListener("idle",i),t?.signal?.removeEventListener("abort",c),n()}}};var ve=class extends Pt{has(t){return this.find(t)!=null}find(t){return this.queue.find(e=>t.equals(e.options.peerId))}};function Po(r){return r[Symbol.asyncIterator]!=null}function Ro(r){if(Po(r))return(async()=>{for await(let t of r);})();for(let t of r);}var pr=Ro;function $(r=0){return new Uint8Array(r)}function z(r=0){return new Uint8Array(r)}var Co=Math.pow(2,7),Uo=Math.pow(2,14),No=Math.pow(2,21),mr=Math.pow(2,28),gr=Math.pow(2,35),wr=Math.pow(2,42),br=Math.pow(2,49),I=128,V=127;function D(r){if(r<Co)return 1;if(r<Uo)return 2;if(r<No)return 3;if(r<mr)return 4;if(r<gr)return 5;if(r<wr)return 6;if(r<br)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function yr(r,t,e=0){switch(D(r)){case 8:t[e++]=r&255|I,r/=128;case 7:t[e++]=r&255|I,r/=128;case 6:t[e++]=r&255|I,r/=128;case 5:t[e++]=r&255|I,r/=128;case 4:t[e++]=r&255|I,r>>>=7;case 3:t[e++]=r&255|I,r>>>=7;case 2:t[e++]=r&255|I,r>>>=7;case 1:{t[e++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return t}function Mo(r,t,e=0){switch(D(r)){case 8:t.set(e++,r&255|I),r/=128;case 7:t.set(e++,r&255|I),r/=128;case 6:t.set(e++,r&255|I),r/=128;case 5:t.set(e++,r&255|I),r/=128;case 4:t.set(e++,r&255|I),r>>>=7;case 3:t.set(e++,r&255|I),r>>>=7;case 2:t.set(e++,r&255|I),r>>>=7;case 1:{t.set(e++,r&255),r>>>=7;break}default:throw new Error("unreachable")}return t}function xr(r,t){let e=r[t],n=0;if(n+=e&V,e<I||(e=r[t+1],n+=(e&V)<<7,e<I)||(e=r[t+2],n+=(e&V)<<14,e<I)||(e=r[t+3],n+=(e&V)<<21,e<I)||(e=r[t+4],n+=(e&V)*mr,e<I)||(e=r[t+5],n+=(e&V)*gr,e<I)||(e=r[t+6],n+=(e&V)*wr,e<I)||(e=r[t+7],n+=(e&V)*br,e<I))return n;throw new RangeError("Could not decode varint")}function Fo(r,t){let e=r.get(t),n=0;if(n+=e&V,e<I||(e=r.get(t+1),n+=(e&V)<<7,e<I)||(e=r.get(t+2),n+=(e&V)<<14,e<I)||(e=r.get(t+3),n+=(e&V)<<21,e<I)||(e=r.get(t+4),n+=(e&V)*mr,e<I)||(e=r.get(t+5),n+=(e&V)*gr,e<I)||(e=r.get(t+6),n+=(e&V)*wr,e<I)||(e=r.get(t+7),n+=(e&V)*br,e<I))return n;throw new RangeError("Could not decode varint")}function nt(r,t,e=0){return t==null&&(t=z(D(r))),t instanceof Uint8Array?yr(r,t,e):Mo(r,t,e)}function tt(r,t=0){return r instanceof Uint8Array?xr(r,t):Fo(r,t)}function Q(r,t){t==null&&(t=r.reduce((s,o)=>s+o.length,0));let e=z(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 Vn=Symbol.for("@achingbrain/uint8arraylist");function zn(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?.[Vn]}var dt=class r{bufs;length;[Vn]=!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=zn(this.bufs,t);return e.buf[e.index]}set(t,e){let n=zn(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 Q(n,s)}subarray(t,e){let{bufs:n,length:s}=this._subList(t,e);return n.length===1?n[0]:Q(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],c=s,l=c+i.byteLength;if(s=l,t>=l)continue;let u=t>=c&&t<l,d=e>c&&e<=l;if(u&&d){if(t===c&&e===l){n.push(i);break}let f=t-c;n.push(i.subarray(f,f+(e-t)));break}if(u){if(t===0){n.push(i);continue}n.push(i.subarray(t-c));continue}if(d){if(e===l){n.push(i);break}n.push(i.subarray(0,e-c));break}n.push(i)}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 o=256,i=new Int32Array(o);for(let f=0;f<o;f++)i[f]=-1;for(let f=0;f<s;f++)i[n[f]]=f;let c=i,l=this.byteLength-n.byteLength,u=n.byteLength-1,d;for(let f=e;f<=l;f+=d){d=0;for(let x=u;x>=0;x--){let a=this.get(f+x);if(n[x]!==a){d=Math.max(1,x-c[a]);break}}if(d===0)return f}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=z(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=$(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=$(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=$(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=z(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=$(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=$(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=$(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=$(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=$(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}};function ke(r){return r[Symbol.asyncIterator]!=null}var Le=r=>{let t=D(r),e=z(t);return nt(r,e),Le.bytes=t,e};Le.bytes=0;function Ie(r,t){t=t??{};let e=t.lengthEncoder??Le;function*n(s){let o=e(s.byteLength);o instanceof Uint8Array?yield o:yield*o,s instanceof Uint8Array?yield s:yield*s}return ke(r)?async function*(){for await(let s of r)yield*n(s)}():function*(){for(let s of r)yield*n(s)}()}Ie.single=(r,t)=>{t=t??{};let e=t.lengthEncoder??Le;return new dt(e(r.byteLength),r)};var Te=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},_e=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},De=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"},Gt=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};var Bo=8,Oo=1024*1024*4,bt;(function(r){r[r.LENGTH=0]="LENGTH",r[r.DATA=1]="DATA"})(bt||(bt={}));var Er=r=>{let t=tt(r);return Er.bytes=D(t),t};Er.bytes=0;function Xt(r,t){let e=new dt,n=bt.LENGTH,s=-1,o=t?.lengthDecoder??Er,i=t?.maxLengthLength??Bo,c=t?.maxDataLength??Oo;function*l(){for(;e.byteLength>0;){if(n===bt.LENGTH)try{if(s=o(e),s<0)throw new Te("Invalid message length");if(s>c)throw new _e("Message length too long");let u=o.bytes;e.consume(u),t?.onLength!=null&&t.onLength(s),n=bt.DATA}catch(u){if(u instanceof RangeError){if(e.byteLength>i)throw new De("Message length length too long");break}throw u}if(n===bt.DATA){if(e.byteLength<s)break;let u=e.sublist(0,s);e.consume(s),t?.onData!=null&&t.onData(u),yield u,n=bt.LENGTH}}}return ke(r)?async function*(){for await(let u of r)e.append(u),yield*l();if(e.byteLength>0)throw new Gt("Unexpected end of input")}():function*(){for(let u of r)e.append(u),yield*l();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: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 Xt(n,{...t??{},onLength:o=>{e=o}})};function zo(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 Hn=zo;function Vo(r){return r[Symbol.asyncIterator]!=null}function Ho(r,t){let e=0;if(Vo(r))return async function*(){for await(let l of r)yield t(l,e++)}();let n=Hn(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 await(let l of n)yield t(l,e++)}();let c=t;return function*(){yield i;for(let l of n)yield c(l,e++)}()}var Wn=Ho;function Wo(r){return r[Symbol.asyncIterator]!=null}function qo(...r){let t=[];for(let e of r)Wo(e)||t.push(e);return t.length===r.length?function*(){for(let e of t)yield*e}():async function*(){let e=Dt({objectMode:!0});Promise.resolve().then(async()=>{try{await Promise.all(r.map(async n=>{for await(let s of n)e.push(s)})),e.end()}catch(n){e.end(n)}}),yield*e}()}var qn=qo;function Sr(r,...t){if(r==null)throw new Error("Empty pipeline");if(vr(r)){let n=r;r=()=>n.source}else if(Xn(r)||Gn(r)){let n=r;r=()=>n}let e=[r,...t];if(e.length>1&&vr(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++)vr(e[n])&&(e[n]=Xo(e[n]));return Go(...e)}var Go=(...r)=>{let t;for(;r.length>0;)t=r.shift()(t);return t},Gn=r=>r?.[Symbol.asyncIterator]!=null,Xn=r=>r?.[Symbol.iterator]!=null,vr=r=>r==null?!1:r.sink!=null&&r.source!=null,Xo=r=>t=>{let e=r.sink(t);if(e?.then!=null){let n=Dt({objectMode:!0});e.then(()=>{n.end()},i=>{n.end(i)});let s,o=r.source;if(Gn(o))s=async function*(){yield*o,n.end()};else if(Xn(o))s=function*(){yield*o,n.end()};else throw new Error("Unknown duplex source type - must be Iterable or AsyncIterable");return qn(n,s())}return r.source};function Qo(r){return r[Symbol.asyncIterator]!=null}function jo(r,t){return Qo(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 Qn=jo;var st=class extends Event{type;detail;constructor(t,e){super(t),this.type=t,this.detail=e}};var Qt="/ipfs/bitswap/1.2.0";var Ar=new Float32Array([-0]),pt=new Uint8Array(Ar.buffer);function jn(r,t,e){Ar[0]=r,t[e]=pt[0],t[e+1]=pt[1],t[e+2]=pt[2],t[e+3]=pt[3]}function Kn(r,t){return pt[0]=r[t],pt[1]=r[t+1],pt[2]=r[t+2],pt[3]=r[t+3],Ar[0]}var kr=new Float64Array([-0]),H=new Uint8Array(kr.buffer);function Jn(r,t,e){kr[0]=r,t[e]=H[0],t[e+1]=H[1],t[e+2]=H[2],t[e+3]=H[3],t[e+4]=H[4],t[e+5]=H[5],t[e+6]=H[6],t[e+7]=H[7]}function Zn(r,t){return H[0]=r[t],H[1]=r[t+1],H[2]=r[t+2],H[3]=r[t+3],H[4]=r[t+4],H[5]=r[t+5],H[6]=r[t+6],H[7]=r[t+7],kr[0]}var Ko=BigInt(Number.MAX_SAFE_INTEGER),Jo=BigInt(Number.MIN_SAFE_INTEGER),X=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 yt;if(t<Ko&&t>Jo)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>Yn&&(s=0n,++n>Yn&&(n=0n))),new r(Number(s),Number(n))}static fromNumber(t){if(t===0)return yt;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):yt}},yt=new X(0,0);yt.toBigInt=function(){return 0n};yt.zzEncode=yt.zzDecode=function(){return this};yt.length=function(){return 1};var Yn=4294967296n;function ts(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 es(r,t,e){if(e-t<1)return"";let s,o=[],i=0,c;for(;t<e;)c=r[t++],c<128?o[i++]=c:c>191&&c<224?o[i++]=(c&31)<<6|r[t++]&63:c>239&&c<365?(c=((c&7)<<18|(r[t++]&63)<<12|(r[t++]&63)<<6|r[t++]&63)-65536,o[i++]=55296+(c>>10),o[i++]=56320+(c&1023)):o[i++]=(c&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 Lr(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 et(r,t){return RangeError(`index out of range: ${r.pos} + ${t??1} > ${r.len}`)}function Pe(r,t){return(r[t-4]|r[t-3]<<8|r[t-2]<<16|r[t-1]<<24)>>>0}var Ir=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,et(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 et(this,4);return Pe(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw et(this,4);return Pe(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw et(this,4);let t=Kn(this.buf,this.pos);return this.pos+=4,t}double(){if(this.pos+8>this.len)throw et(this,4);let t=Zn(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 et(this,t);return this.pos+=t,e===n?new Uint8Array(0):this.buf.subarray(e,n)}string(){let t=this.bytes();return es(t,0,t.length)}skip(t){if(typeof t=="number"){if(this.pos+t>this.len)throw et(this,t);this.pos+=t}else do if(this.pos>=this.len)throw et(this);while(this.buf[this.pos++]&128);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 X(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 et(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 et(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 et(this,8);let t=Pe(this.buf,this.pos+=4),e=Pe(this.buf,this.pos+=4);return new X(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=xr(this.buf,this.pos);return this.pos+=D(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 Tr(r){return new Ir(r instanceof Uint8Array?r:r.subarray())}function xt(r,t,e){let n=Tr(r);return t.decode(n,void 0,e)}var Cr={};q(Cr,{base10:()=>ni});var Pl=new Uint8Array(0);function ns(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 ct(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 ss(r){return new TextEncoder().encode(r)}function os(r){return new TextDecoder().decode(r)}function Zo(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 c=r.length,l=r.charAt(0),u=Math.log(c)/Math.log(256),d=Math.log(256)/Math.log(c);function f(h){if(h instanceof Uint8Array||(ArrayBuffer.isView(h)?h=new Uint8Array(h.buffer,h.byteOffset,h.byteLength):Array.isArray(h)&&(h=Uint8Array.from(h))),!(h instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(h.length===0)return"";for(var p=0,v=0,m=0,g=h.length;m!==g&&h[m]===0;)m++,p++;for(var w=(g-m)*d+1>>>0,y=new Uint8Array(w);m!==g;){for(var E=h[m],A=0,b=w-1;(E!==0||A<v)&&b!==-1;b--,A++)E+=256*y[b]>>>0,y[b]=E%c>>>0,E=E/c>>>0;if(E!==0)throw new Error("Non-zero carry");v=A,m++}for(var T=w-v;T!==w&&y[T]===0;)T++;for(var at=l.repeat(p);T<w;++T)at+=r.charAt(y[T]);return at}function x(h){if(typeof h!="string")throw new TypeError("Expected String");if(h.length===0)return new Uint8Array;var p=0;if(h[p]!==" "){for(var v=0,m=0;h[p]===l;)v++,p++;for(var g=(h.length-p)*u+1>>>0,w=new Uint8Array(g);h[p];){var y=e[h.charCodeAt(p)];if(y===255)return;for(var E=0,A=g-1;(y!==0||E<m)&&A!==-1;A--,E++)y+=c*w[A]>>>0,w[A]=y%256>>>0,y=y/256>>>0;if(y!==0)throw new Error("Non-zero carry");m=E,p++}if(h[p]!==" "){for(var b=g-m;b!==g&&w[b]===0;)b++;for(var T=new Uint8Array(v+(g-b)),at=v;b!==g;)T[at++]=w[b++];return T}}}function a(h){var p=x(h);if(p)return p;throw new Error(`Non-${t} character`)}return{encode:f,decodeUnsafe:x,decode:a}}var Yo=Zo,ti=Yo,as=ti;var _r=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")}},Dr=class{name;prefix;baseDecode;prefixCodePoint;constructor(t,e,n){if(this.name=t,this.prefix=e,e.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=e.codePointAt(0),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 cs(this,t)}},Pr=class{decoders;constructor(t){this.decoders=t}or(t){return cs(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 cs(r,t){return new Pr({...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 _r(t,e,n),this.decoder=new Dr(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 Rr(r,t,e,n)}function mt({name:r,prefix:t,alphabet:e}){let{encode:n,decode:s}=as(e,r);return Rt({prefix:t,name:r,encode:n,decode:o=>ct(s(o))})}function ei(r,t,e,n){let s={};for(let d=0;d<t.length;++d)s[t[d]]=d;let o=r.length;for(;r[o-1]==="=";)--o;let i=new Uint8Array(o*e/8|0),c=0,l=0,u=0;for(let d=0;d<o;++d){let f=s[r[d]];if(f===void 0)throw new SyntaxError(`Non-${n} character`);l=l<<e|f,c+=e,c>=8&&(c-=8,i[u++]=255&l>>c)}if(c>=e||255&l<<8-c)throw new SyntaxError("Unexpected end of data");return i}function ri(r,t,e){let n=t[t.length-1]==="=",s=(1<<e)-1,o="",i=0,c=0;for(let l=0;l<r.length;++l)for(c=c<<8|r[l],i+=8;i>e;)i-=e,o+=t[s&c>>i];if(i!==0&&(o+=t[s&c<<e-i]),n)for(;o.length*e&7;)o+="=";return o}function R({name:r,prefix:t,bitsPerChar:e,alphabet:n}){return Rt({prefix:t,name:r,encode(s){return ri(s,n,e)},decode(s){return ei(s,n,e,r)}})}var ni=mt({prefix:"9",name:"base10",alphabet:"0123456789"});var Ur={};q(Ur,{base16:()=>si,base16upper:()=>oi});var si=R({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),oi=R({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var Nr={};q(Nr,{base2:()=>ii});var ii=R({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var Mr={};q(Mr,{base256emoji:()=>hi});var ls=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}"),ai=ls.reduce((r,t,e)=>(r[e]=t,r),[]),ci=ls.reduce((r,t,e)=>(r[t.codePointAt(0)]=e,r),[]);function li(r){return r.reduce((t,e)=>(t+=ai[e],t),"")}function ui(r){let t=[];for(let e of r){let n=ci[e.codePointAt(0)];if(n===void 0)throw new Error(`Non-base256emoji character: ${e}`);t.push(n)}return new Uint8Array(t)}var hi=Rt({prefix:"\u{1F680}",name:"base256emoji",encode:li,decode:ui});var Fr={};q(Fr,{base32:()=>lt,base32hex:()=>mi,base32hexpad:()=>wi,base32hexpadupper:()=>bi,base32hexupper:()=>gi,base32pad:()=>di,base32padupper:()=>pi,base32upper:()=>fi,base32z:()=>yi});var lt=R({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),fi=R({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),di=R({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),pi=R({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),mi=R({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),gi=R({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),wi=R({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),bi=R({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),yi=R({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Br={};q(Br,{base36:()=>xi,base36upper:()=>Ei});var xi=mt({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Ei=mt({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var Or={};q(Or,{base58btc:()=>N,base58flickr:()=>vi});var N=mt({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),vi=mt({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var zr={};q(zr,{base64:()=>ut,base64pad:()=>Si,base64url:()=>$r,base64urlpad:()=>Ai});var ut=R({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Si=R({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),$r=R({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Ai=R({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var Vr={};q(Vr,{base8:()=>ki});var ki=R({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var Hr={};q(Hr,{identity:()=>Li});var Li=Rt({prefix:"\0",name:"identity",encode:r=>os(r),decode:r=>ss(r)});var Xl=new TextEncoder,Ql=new TextDecoder;var qr={};q(qr,{identity:()=>Jt});var _i=fs,us=128,Di=127,Pi=~Di,Ri=Math.pow(2,31);function fs(r,t,e){t=t||[],e=e||0;for(var n=e;r>=Ri;)t[e++]=r&255|us,r/=128;for(;r&Pi;)t[e++]=r&255|us,r>>>=7;return t[e]=r|0,fs.bytes=e-n+1,t}var Ci=Wr,Ui=128,hs=127;function Wr(r,n){var e=0,n=n||0,s=0,o=n,i,c=r.length;do{if(o>=c)throw Wr.bytes=0,new RangeError("Could not decode varint");i=r[o++],e+=s<28?(i&hs)<<s:(i&hs)*Math.pow(2,s),s+=7}while(i>=Ui);return Wr.bytes=o-n,e}var Ni=Math.pow(2,7),Mi=Math.pow(2,14),Fi=Math.pow(2,21),Bi=Math.pow(2,28),Oi=Math.pow(2,35),$i=Math.pow(2,42),zi=Math.pow(2,49),Vi=Math.pow(2,56),Hi=Math.pow(2,63),Wi=function(r){return r<Ni?1:r<Mi?2:r<Fi?3:r<Bi?4:r<Oi?5:r<$i?6:r<zi?7:r<Vi?8:r<Hi?9:10},qi={encode:_i,decode:Ci,encodingLength:Wi},Gi=qi,jt=Gi;function Kt(r,t=0){return[jt.decode(r,t),jt.decode.bytes]}function Ct(r,t,e=0){return jt.encode(r,t,e),t}function Ut(r){return jt.encodingLength(r)}function gt(r,t){let e=t.byteLength,n=Ut(r),s=n+Ut(e),o=new Uint8Array(s+e);return Ct(r,o,0),Ct(e,o,n),o.set(t,s),new Nt(r,e,t,o)}function Et(r){let t=ct(r),[e,n]=Kt(t),[s,o]=Kt(t.subarray(n)),i=t.subarray(n+o);if(i.byteLength!==s)throw new Error("Incorrect length");return new Nt(e,s,i,t)}function ds(r,t){if(r===t)return!0;{let e=t;return r.code===e.code&&r.size===e.size&&e.bytes instanceof Uint8Array&&ns(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 ps=0,Xi="identity",ms=ct;function Qi(r){return gt(ps,ms(r))}var Jt={code:ps,name:Xi,encode:ms,digest:Qi};var Qr={};q(Qr,{sha256:()=>St,sha512:()=>ji});function Xr({name:r,code:t,encode:e}){return new Gr(r,t,e)}var Gr=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?gt(this.code,e):e.then(n=>gt(this.code,n))}else throw Error("Unknown type, must be binary type")}};function ws(r){return async t=>new Uint8Array(await crypto.subtle.digest(r,t))}var St=Xr({name:"sha2-256",code:18,encode:ws("SHA-256")}),ji=Xr({name:"sha2-512",code:19,encode:ws("SHA-512")});function bs(r,t){let{bytes:e,version:n}=r;switch(n){case 0:return Ji(e,jr(r),t??N.encoder);default:return Zi(e,jr(r),t??lt.encoder)}}var ys=new WeakMap;function jr(r){let t=ys.get(r);if(t==null){let e=new Map;return ys.set(r,e),e}return t}var B=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!==Zt)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(e.code!==Yi)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=gt(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&&ds(t.multihash,n.multihash)}toString(t){return bs(this,t)}toJSON(){return{"/":bs(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??xs(n,s,o.bytes))}else if(e[ta]===!0){let{version:n,multihash:s,code:o}=e,i=Et(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!==Zt)throw new Error(`Version 0 CID must use dag-pb (code: ${Zt}) block encoding`);return new r(t,e,n,n.bytes)}case 1:{let s=xs(t,e,n.bytes);return new r(t,e,n,s)}default:throw new Error("Invalid version")}}static createV0(t){return r.create(0,Zt,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=ct(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 Nt(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[f,x]=Kt(t.subarray(e));return e+=x,f},s=n(),o=Zt;if(s===18?(s=0,e=0):o=n(),s!==0&&s!==1)throw new RangeError(`Invalid CID version ${s}`);let i=e,c=n(),l=n(),u=e+l,d=u-i;return{version:s,codec:o,multihashCode:c,digestSize:l,multihashSize:d,size:u}}static parse(t,e){let[n,s]=Ki(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 jr(o).set(n,t),o}};function Ki(r,t){switch(r[0]){case"Q":{let e=t??N;return[N.prefix,e.decode(`${N.prefix}${r}`)]}case N.prefix:{let e=t??N;return[N.prefix,e.decode(r)]}case lt.prefix:{let e=t??lt;return[lt.prefix,e.decode(r)]}default:{if(t==null)throw Error("To parse non base32 or base58btc encoded CID multibase decoder must be provided");return[r[0],t.decode(r)]}}}function Ji(r,t,e){let{prefix:n}=e;if(n!==N.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 Zi(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 Zt=112,Yi=18;function xs(r,t,e){let n=Ut(r),s=n+Ut(t),o=new Uint8Array(s+e.byteLength);return Ct(r,o,0),Ct(t,o,n),o.set(e,s),o}var ta=Symbol.for("@ipld/js-cid/CID");var wt={...Hr,...Nr,...Vr,...Cr,...Ur,...Fr,...Br,...Or,...zr,...Mr},mu={...Qr,...qr};function vs(r,t,e,n){return{name:r,prefix:t,encoder:{name:r,prefix:t,encode:e},decoder:{decode:n}}}var Es=vs("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),Kr=vs("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=z(r.length);for(let e=0;e<r.length;e++)t[e]=r.charCodeAt(e);return t}),ea={utf8:Es,"utf-8":Es,hex:wt.base16,latin1:Kr,ascii:Kr,binary:Kr,...wt},Ce=ea;function ot(r,t="utf8"){let e=Ce[t];if(e==null)throw new Error(`Unsupported encoding "${t}"`);return e.decoder.decode(`${e.prefix}${r}`)}function Jr(r){let t=r??8192,e=t>>>1,n,s=t;return function(i){if(i<1||i>e)return z(i);s+i>t&&(n=z(t),s=0);let c=n.subarray(s,s+=i);return s&7&&(s=(s|7)+1),c}}var At=class{fn;len;next;val;constructor(t,e,n){this.fn=t,this.len=e,this.next=void 0,this.val=n}};function Zr(){}var tn=class{head;tail;len;next;constructor(t){this.head=t.head,this.tail=t.tail,this.len=t.len,this.next=t.states}},ra=Jr();function na(r){return globalThis.Buffer!=null?z(r):ra(r)}var te=class{len;head;tail;states;constructor(){this.len=0,this.head=new At(Zr,0,0),this.tail=this.head,this.states=null}_push(t,e,n){return this.tail=this.tail.next=new At(t,e,n),this.len+=e,this}uint32(t){return this.len+=(this.tail=this.tail.next=new en((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(Ue,10,X.fromNumber(t)):this.uint32(t)}sint32(t){return this.uint32((t<<1^t>>31)>>>0)}uint64(t){let e=X.fromBigInt(t);return this._push(Ue,e.length(),e)}uint64Number(t){return this._push(yr,D(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=X.fromBigInt(t).zzEncode();return this._push(Ue,e.length(),e)}sint64Number(t){let e=X.fromNumber(t).zzEncode();return this._push(Ue,e.length(),e)}sint64String(t){return this.sint64(BigInt(t))}bool(t){return this._push(Yr,1,t?1:0)}fixed32(t){return this._push(Yt,4,t>>>0)}sfixed32(t){return this.fixed32(t)}fixed64(t){let e=X.fromBigInt(t);return this._push(Yt,4,e.lo)._push(Yt,4,e.hi)}fixed64Number(t){let e=X.fromNumber(t);return this._push(Yt,4,e.lo)._push(Yt,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(jn,4,t)}double(t){return this._push(Jn,8,t)}bytes(t){let e=t.length>>>0;return e===0?this._push(Yr,1,0):this.uint32(e)._push(oa,e,t)}string(t){let e=ts(t);return e!==0?this.uint32(e)._push(Lr,e,t):this._push(Yr,1,0)}fork(){return this.states=new tn(this),this.head=this.tail=new At(Zr,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 At(Zr,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=na(this.len),n=0;for(;t!=null;)t.fn(t.val,e,n),n+=t.len,t=t.next;return e}};function Yr(r,t,e){t[e]=r&255}function sa(r,t,e){for(;r>127;)t[e++]=r&127|128,r>>>=7;t[e]=r}var en=class extends At{next;constructor(t,e){super(sa,t,e),this.next=void 0}};function Ue(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 Yt(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 oa(r,t,e){t.set(r,e)}globalThis.Buffer!=null&&(te.prototype.bytes=function(r){let t=r.length>>>0;return this.uint32(t),t>0&&this._push(ia,t,r),this},te.prototype.string=function(r){let t=globalThis.Buffer.byteLength(r);return this.uint32(t),t>0&&this._push(aa,t,r),this});function ia(r,t,e){t.set(r,e)}function aa(r,t,e){r.length<40?Lr(r,t,e):t.utf8Write!=null?t.utf8Write(r,e):t.set(ot(r),e)}function rn(){return new te}function kt(r,t){let e=rn();return t.encode(r,e,{lengthDelimited:!1}),e.finish()}var Mt;(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"})(Mt||(Mt={}));function Ne(r,t,e,n){return{name:r,type:t,encode:e,decode:n}}function Me(r){function t(s){if(r[s.toString()]==null)throw new Error("Invalid enum value");return r[s]}let e=function(o,i){let c=t(o);i.int32(c)},n=function(o){let i=o.int32();return t(i)};return Ne("enum",Mt.VARINT,e,n)}function Lt(r,t){return Ne("message",Mt.LENGTH_DELIMITED,r,t)}var Ft=class extends Error{code;constructor(t,e){super(t),this.code=e}};var C;(function(r){r.WantBlock="WantBlock",r.WantHave="WantHave"})(C||(C={}));var nn;(function(r){r[r.WantBlock=0]="WantBlock",r[r.WantHave=1]="WantHave"})(nn||(nn={}));(function(r){r.codec=()=>Me(nn)})(C||(C={}));var Bt;(function(r){let t;r.codec=()=>(t==null&&(t=Lt((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),C.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:$(0),priority:0},i=n==null?e.len:e.pos+n;for(;e.pos<i;){let c=e.uint32();switch(c>>>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=C.codec().decode(e);break}case 5:{o.sendDontHave=e.bool();break}default:{e.skipType(c&7);break}}}return o})),t),r.encode=e=>kt(e,r.codec()),r.decode=(e,n)=>xt(e,r.codec(),n)})(Bt||(Bt={}));var Fe;(function(r){let t;r.codec=()=>(t==null&&(t=Lt((e,n,s={})=>{if(s.lengthDelimited!==!1&&n.fork(),e.entries!=null)for(let o of e.entries)n.uint32(10),Bt.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 c=e.uint32();switch(c>>>3){case 1:{if(s.limits?.entries!=null&&o.entries.length===s.limits.entries)throw new Ft('decode error - map field "entries" had too many elements',"ERR_MAX_LENGTH");o.entries.push(Bt.codec().decode(e,e.uint32(),{limits:s.limits?.entries$}));break}case 2:{o.full=e.bool();break}default:{e.skipType(c&7);break}}}return o})),t),r.encode=e=>kt(e,r.codec()),r.decode=(e,n)=>xt(e,r.codec(),n)})(Fe||(Fe={}));var Ot;(function(r){let t;r.codec=()=>(t==null&&(t=Lt((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:$(0),data:$(0)},i=n==null?e.len:e.pos+n;for(;e.pos<i;){let c=e.uint32();switch(c>>>3){case 1:{o.prefix=e.bytes();break}case 2:{o.data=e.bytes();break}default:{e.skipType(c&7);break}}}return o})),t),r.encode=e=>kt(e,r.codec()),r.decode=(e,n)=>xt(e,r.codec(),n)})(Ot||(Ot={}));var K;(function(r){r.HaveBlock="HaveBlock",r.DontHaveBlock="DontHaveBlock"})(K||(K={}));var Be;(function(r){r[r.HaveBlock=0]="HaveBlock",r[r.DontHaveBlock=1]="DontHaveBlock"})(Be||(Be={}));(function(r){r.codec=()=>Me(Be)})(K||(K={}));var $t;(function(r){let t;r.codec=()=>(t==null&&(t=Lt((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&&Be[e.type]!==0&&(n.uint32(16),K.codec().encode(e.type,n)),s.lengthDelimited!==!1&&n.ldelim()},(e,n,s={})=>{let o={cid:$(0),type:K.HaveBlock},i=n==null?e.len:e.pos+n;for(;e.pos<i;){let c=e.uint32();switch(c>>>3){case 1:{o.cid=e.bytes();break}case 2:{o.type=K.codec().decode(e);break}default:{e.skipType(c&7);break}}}return o})),t),r.encode=e=>kt(e,r.codec()),r.decode=(e,n)=>xt(e,r.codec(),n)})($t||($t={}));var It;(function(r){let t;r.codec=()=>(t==null&&(t=Lt((e,n,s={})=>{if(s.lengthDelimited!==!1&&n.fork(),e.wantlist!=null&&(n.uint32(10),Fe.codec().encode(e.wantlist,n)),e.blocks!=null)for(let o of e.blocks)n.uint32(26),Ot.codec().encode(o,n);if(e.blockPresences!=null)for(let o of e.blockPresences)n.uint32(34),$t.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 c=e.uint32();switch(c>>>3){case 1:{o.wantlist=Fe.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 Ft('decode error - map field "blocks" had too many elements',"ERR_MAX_LENGTH");o.blocks.push(Ot.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 Ft('decode error - map field "blockPresences" had too many elements',"ERR_MAX_LENGTH");o.blockPresences.push($t.codec().decode(e,e.uint32(),{limits:s.limits?.blockPresences$}));break}case 5:{o.pendingBytes=e.int32();break}default:{e.skipType(c&7);break}}}return o})),t),r.encode=e=>kt(e,r.codec()),r.decode=(e,n)=>xt(e,r.codec(),n)})(It||(It={}));function Ss(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 ca=4193648,la=ca+16;function*As(r,t){let e=[...r.wantlist.values()],n=[...r.blockPresences.values()],s=[...r.blocks.values()],o=0,i=0,c=0,l=!1;for(;;){let u={wantlist:{full:r.full??!1,entries:[]},blockPresences:[],blocks:[],pendingBytes:0},d=It.encode(u).byteLength,{added:f,hasMore:x,newSize:a}=sn(s,u.blocks,c,t,d,ua);c+=f,d=a;let h=x;({added:f,hasMore:x,newSize:a}=sn(n,u.blockPresences,i,t,d,ha)),i+=f,d=a;let p=x;if({added:f,hasMore:x,newSize:a}=sn(e,u.wantlist.entries,o,t,d,fa),o+=f,d=a,l=!h&&!p&&!x,l||(u.wantlist.full=!1),yield It.encode(u),l)break}}function sn(r,t,e,n,s,o){let i=0,c=!1;for(let l=e;l<r.length;l++){let u=r[l],d=o(u);if(d>la)throw new F("Cannot send block as after encoding it is over the max message size","ERR_BLOCK_TOO_LARGE");let f=s+d;if(f>n){c=!0;break}t.push(u),i++,s=f}return{hasMore:c,added:i,newSize:s}}function ua(r){return on(3,Ot.encode(r))}function ha(r){return on(4,$t.encode(r))}function fa(r){return on(1,Bt.encode(r))}function on(r,t){let e=D(r),n=D(t.byteLength);return e+n+t.byteLength}var Oe=class extends rt{log;libp2p;routing;protocols;running;maxInboundStreams;maxOutboundStreams;messageReceiveTimeout;registrarIds;metrics;sendQueue;runOnTransientConnections;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.runOnTransientConnections=e.runOnTransientConnections??!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 ve({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,runOnTransientConnection:this.runOnTransientConnections});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 F(`Incoming Bitswap stream timed out after ${this.messageReceiveTimeout}ms`,"ERR_TIMEOUT")):this.log("stream aborted with status %s",e.status)},o=AbortSignal.timeout(this.messageReceiveTimeout);G(1/0,o),o.addEventListener("abort",s),await e.closeWrite(),await Sr(e,i=>Xt(i,{maxDataLength:this.maxIncomingMessageSize}),async i=>{for await(let c of i)try{let l=It.decode(c);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:l}}),o.removeEventListener("abort",s),o=AbortSignal.timeout(this.messageReceiveTimeout),G(1/0,o),o.addEventListener("abort",s)}catch(l){this.log.error("error reading incoming bitswap message from %p on stream",n.remotePeer,e.id,l),e.abort(l);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 st("bitswap:network:find-providers",t));for await(let n of this.routing.findProviders(t,e))await this.libp2p.isDialable(n.multiaddrs,{runOnTransientConnection:this.runOnTransientConnections})&&(yield n)}async findAndConnect(t,e){await pr(Wn(Qn(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=Ss(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 F("No message to send","ERR_NO_MESSAGE");this.log("sendMessage to %p",t),o?.onProgress?.(new st("bitswap:network:send-wantlist",t));let c=await this.libp2p.dialProtocol(t,Qt,o);await c.closeRead();try{await Sr(As(i,this.maxOutgoingMessageSize),l=>Ie(l),c),await c.close(o)}catch(l){o?.onProgress?.(new st("bitswap:network:send-wantlist:error",{peer:t,error:l})),this.log.error("error sending message to %p",t,l),c.abort(l)}this._updateSentStats(i.blocks)},{peerId:t,signal:n?.signal,message:e})}async connectTo(t,e){if(!this.running)throw new F("Network isn't running","ERR_NOT_STARTED");e?.onProgress?.(new st("bitswap:network:dial",t));let[n]=await Promise.all([this.libp2p.dial(t,e),Y(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 F(`${t} did not support ${Qt}`,"ERR_BITSWAP_UNSUPPORTED_BY_PEER")}})]);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 P(r,t="utf8"){let e=Ce[t];if(e==null)throw new Error(`Unsupported encoding "${t}"`);return e.encoder.encode(r).substring(1)}var Ls=Symbol.for("nodejs.util.inspect.custom"),ks=Object.values(wt).map(r=>r.decoder).reduce((r,t)=>r.or(t),wt.identity.decoder),Is=114,Ts=36,_s=37,ee=class{type;multihash;privateKey;publicKey;string;constructor(t){this.type=t.type,this.multihash=t.multihash,this.privateKey=t.privateKey,Object.defineProperty(this,"string",{enumerable:!1,writable:!0})}get[Symbol.toStringTag](){return`PeerId(${this.toString()})`}[ur]=!0;toString(){return this.string==null&&(this.string=N.encode(this.multihash.bytes).slice(1)),this.string}toCID(){return B.createV1(Is,this.multihash)}toBytes(){return this.multihash.bytes}toJSON(){return this.toString()}equals(t){if(t==null)return!1;if(t instanceof Uint8Array)return j(this.multihash.bytes,t);if(typeof t=="string")return oe(t).equals(this);if(t?.multihash?.bytes!=null)return j(this.multihash.bytes,t.multihash.bytes);throw new Error("not valid Id")}[Ls](){return`PeerId(${this.toString()})`}},re=class extends ee{type="RSA";publicKey;constructor(t){super({...t,type:"RSA"}),this.publicKey=t.publicKey}},ne=class extends ee{type="Ed25519";publicKey;constructor(t){super({...t,type:"Ed25519"}),this.publicKey=t.multihash.digest}},se=class extends ee{type="secp256k1";publicKey;constructor(t){super({...t,type:"secp256k1"}),this.publicKey=t.multihash.digest}},an=2336,cn=class{type="url";multihash;privateKey;publicKey;url;constructor(t){this.url=t.toString(),this.multihash=Jt.digest(ot(this.url))}[Ls](){return`PeerId(${this.url})`}[ur]=!0;toString(){return this.toCID().toString()}toCID(){return B.createV1(an,this.multihash)}toBytes(){return this.toCID().bytes}equals(t){return t==null?!1:(t instanceof Uint8Array&&(t=P(t)),t.toString()===this.toString())}};function oe(r,t){if(t=t??ks,r.charAt(0)==="1"||r.charAt(0)==="Q"){let e=Et(N.decode(`z${r}`));return r.startsWith("12D")?new ne({multihash:e}):r.startsWith("16U")?new se({multihash:e}):new re({multihash:e})}return Ea(ks.decode(r))}function Ea(r){try{let t=Et(r);if(t.code===Jt.code){if(t.digest.length===Ts)return new ne({multihash:t});if(t.digest.length===_s)return new se({multihash:t})}if(t.code===St.code)return new re({multihash:t})}catch{return va(B.decode(r))}throw new Error("Supplied PeerID CID is invalid")}function va(r){if(r?.multihash==null||r.version==null||r.version===1&&r.code!==Is&&r.code!==an)throw new Error("Supplied PeerID CID is invalid");if(r.code===an){let e=P(r.multihash.digest);return new cn(new URL(e))}let t=r.multihash;if(t.code===St.code)return new re({multihash:r.multihash});if(t.code===Jt.code){if(t.digest.length===Ts)return new ne({multihash:r.multihash});if(t.digest.length===_s)return new se({multihash:r.multihash})}throw new Error("Supplied PeerID CID is invalid")}function ln(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 ie=class{map;constructor(t){if(this.map=new Map,t!=null)for(let[e,n]of t.entries())this.map.set(e.toString(),n)}[Symbol.iterator](){return this.entries()}clear(){this.map.clear()}delete(t){return this.map.delete(t.toString())}entries(){return ln(this.map.entries(),t=>[oe(t[0]),t[1]])}forEach(t){this.map.forEach((e,n)=>{t(e,oe(n),this)})}get(t){return this.map.get(t.toString())}has(t){return this.map.has(t.toString())}set(t,e){this.map.set(t.toString(),e)}keys(){return ln(this.map.keys(),t=>oe(t))}values(){return this.map.values()}get size(){return this.map.size}};var $e=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;var Dh=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;var Ph={}.toString;function Ds(r=32){if($e&&typeof $e.getRandomValues=="function")return $e.getRandomValues(new Uint8Array(r));throw new Error("crypto.getRandomValues must be defined")}function ze(r){if(isNaN(r)||r<=0)throw new F("random bytes length must be a Number bigger than 0","ERR_INVALID_LENGTH");return Ds(r)}var un=class extends ie{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 ce(r){let{name:t,metrics:e}=r,n;return e!=null?n=new un({name:t,metrics:e}):n=new ie,n}var ht=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=ut.encode(t.multihash.bytes);this.wantlist.set(n,e)}addBlockPresence(t,e){let n=ut.encode(t.multihash.bytes);this.blockPresences.set(n,e)}addBlock(t,e){let n=ut.encode(t.multihash.bytes);this.blocks.set(n,e)}};function Sa(r){let t=new Uint8Array(r.reduce((n,s)=>n+D(s),0)),e=0;for(let n of r)t=nt(n,t,e),e+=D(n);return t}var Us=Sa;function hn(r){return Us([r.version,r.code,r.multihash.code,r.multihash.digest.byteLength])}var He=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 ht,n=new Set;for(let[s,o]of this.wants.entries())try{let i=await this.blockstore.get(o.cid,t);o.wantType===C.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:hn(o.cid)})):(this.log("sending have for %c",o.cid),e.addBlockPresence(o.cid,{cid:o.cid.bytes,type:K.HaveBlock})):(this.log("sending block for %c",o.cid),n.add(s),e.addBlock(o.cid,{data:i,prefix:hn(o.cid)}))}catch(i){if(i.code!=="ERR_NOT_FOUND")throw i;if(this.log("do not have block for %c",o.cid),!o.sendDontHave||o.sentDontHave===!0)continue;o.sentDontHave=!0,e.addBlockPresence(o.cid,{cid:o.cid.bytes,type:K.DontHaveBlock})}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 We=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=ce({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 He({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=B.decode(s.cid),i=P(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===C.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??C.WantBlock,sendDontHave:s.sendDontHave??!1}))}}this.log("send blocks to peer"),await n.sendBlocksToPeer()}async receivedBlock(t,e){let n=P(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 La=lr(Ms(),1);var zt;(function(r){r[r.A=1]="A",r[r.CNAME=5]="CNAME",r[r.TXT=16]="TXT",r[r.AAAA=28]="AAAA"})(zt||(zt={}));var fn=lr(Cs(),1);var Ia=Math.LN2*Math.LN2,qe=class r{static create(t,e=.005){let n=Ta(t,e);return new r(n)}seeds;bits;buffer;constructor(t={}){t.seeds!=null?this.seeds=t.seeds:this.seeds=_a(t.hashes??8),this.bits=t.bits??1024,this.buffer=$(Math.ceil(this.bits/8))}add(t){typeof t=="string"&&(t=ot(t));for(let e=0;e<this.seeds.length;e++){let s=fn.default.x86.hash32(t,this.seeds[e])%this.bits;this.setbit(s)}}has(t){typeof t=="string"&&(t=ot(t));for(let e=0;e<this.seeds.length;e++){let s=fn.default.x86.hash32(t,this.seeds[e])%this.bits;if(!this.getbit(s))return!1}return!0}clear(){this.buffer.fill(0)}setbit(t){let e=0,n=t;for(;n>7;)e++,n-=8;let s=this.buffer[e];s|=1<<n,this.buffer[e]=s}getbit(t){let e=0,n=t;for(;n>7;)e++,n-=8;return(this.buffer[e]&1<<n)!==0}};function Ta(r,t=.005){let e=Math.round(-1*r*Math.log(t)/Ia),n=Math.round(e/r*Math.LN2);return{bits:e,hashes:n}}function _a(r){let t,e,n=[];for(let s=0;s<r;s++)for(t=new dt(ze(4)),n[s]=t.getUint32(0,!0),e=0;e<s;e++)if(n[s]===n[e]){s--;break}return n}var Tt=class extends rt{intialPeerSearchComplete;requests;name;log;logger;minProviders;maxProviders;providers;evictionFilter;constructor(t,e){super(),G(1/0,this),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=qe.create(this.maxProviders)}async retrieve(t,e={}){let n=ut.encode(t.multihash.bytes),s=this.requests.get(n);if(s!=null)return this.log("join existing request for %c",t),s;let o=Z();if(this.requests.set(n,o.promise),this.providers.length===0){let u=!1;this.intialPeerSearchComplete==null&&(u=!0,this.log=this.logger.forComponent(`${this.name}:${t}`),this.intialPeerSearchComplete=this.findProviders(t,this.minProviders,e)),await this.intialPeerSearchComplete,u&&this.log("found initial session peers for %c",t)}let i=!1,c=new Pt({concurrency:this.maxProviders});c.addEventListener("error",()=>{}),c.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)}),c.addEventListener("success",u=>{i=!0,o.resolve(u.detail.result)}),c.addEventListener("idle",()=>{i||e.signal?.aborted===!0||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 d=this.providers[Math.floor(Math.random()*this.providers.length)];this.evict(d)}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 l=u=>{c.add(async()=>this.queryProvider(t,u.detail,e),{provider:u.detail}).catch(d=>{e.signal?.aborted!==!0&&this.log.error("error retrieving session block for %c",t,d)})};this.addEventListener("provider",l),Promise.all([...this.providers].map(async u=>c.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)});try{return await o.promise}finally{this.removeEventListener("provider",l),c.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=Z(),o=0;return Promise.resolve().then(async()=>{this.log("finding %d-%d new provider(s) for %c",e,this.maxProviders,t);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 F(`Found ${o} of ${e} ${this.name} providers for ${t}`,"ERR_INSUFFICIENT_PROVIDERS_FOUND")}).catch(i=>{this.log.error("error searching routing for potential session peers for %c",t,i.errors??i),s.reject(i)}),s.promise}};var dn=class extends Tt{wantList;network;constructor(t,e){super(t,{...e,name:"helia:bitswap:session"}),this.wantList=t.wantList,this.network=t.network}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.toBytes()}equals(t,e){return t.equals(e)}};function Fs(r,t){return new dn(r,t)}var Ge=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 pn=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 Bs(r){let{name:t,metrics:e}=r,n;return e!=null?n=new pn({name:t,metrics:e}):n=new Map,n}function Da(r){if(!(r instanceof Uint8Array))throw new Error("arg needs to be a Uint8Array");let t=[];for(;r.length>0;){let e=tt(r);t.push(e),r=r.slice(D(e))}return t}var Os=Da;var Xe=class extends rt{peers;wants;network;log;sendMessagesDelay;sendMessagesTimeout;hashLoader;sendingMessages;constructor(t,e={}){super(),G(1/0,this),this.peers=ce({name:"helia_bitswap_peers",metrics:t.metrics}),this.wants=Bs({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=P(t.multihash.bytes,"base64"),s=this.wants.get(n);s==null&&(s={cid:t,priority:e.priority??1,wantType:e.wantType??C.WantBlock,cancel:!1,sendDontHave:!0},this.wants.set(n,s)),s.wantType===C.WantHave&&e.wantType===C.WantBlock&&(s.wantType=C.WantBlock),await this.sendMessagesDebounced();try{return e.wantType===C.WantBlock?(await Y(this,"block",e?.signal,{filter:c=>j(t.multihash.digest,c.detail.cid.multihash.digest),errorMessage:"Want was aborted"})).detail:(await Y(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=Z(),await Promise.all([...this.peers.entries()].map(async([t,e])=>{let n=new Set,s=new ht;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=P(t.multihash.bytes,"base64");return this.wants.has(e)}async wantSessionPresence(t,e,n={}){let s=new ht;return s.addWantlistEntry(t,{cid:t.bytes,sendDontHave:!0,wantType:C.WantHave,priority:1}),await this.network.sendMessage(e,s),(await Y(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:C.WantBlock})}async wantSessionBlock(t,e,n={}){let s=new ht;return s.addWantlistEntry(t,{cid:t.bytes,sendDontHave:!0,wantType:C.WantBlock,priority:1}),await this.network.sendMessage(e,s),(await Y(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=P(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=Os(s.prefix),i=o[0],c=o[1],l=o[2],u=l===St.code?St:await this.hashLoader?.getHasher(l);if(u==null){this.log.error("unknown hash algorithm",l);continue}let d=u.digest(s.data);d.then!=null&&(d=await d);let f=B.create(i===0?0:1,c,d);this.log("received block from %p for %c",t,f),this.safeDispatchEvent("block",{detail:{sender:t,cid:f,block:s.data}}),this.safeDispatchEvent("presence",{detail:{sender:t,cid:f,has:!0,block:s.data}});let x=P(f.multihash.bytes,"base64"),a=this.wants.get(x);a!=null&&(a.cancel=!0,n=!0)}for(let{cid:s,type:o}of e.blockPresences){let i=B.decode(s);this.log("received %s from %p for %c",o,t,i),this.safeDispatchEvent("presence",{detail:{sender:t,cid:i,has:o===K.HaveBlock}})}n&&await this.sendMessagesDebounced()}async peerConnected(t){let e=new Set,n=new ht(!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:C.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 Qe=class{log;logger;stats;network;blockstore;peerWantLists;wantList;constructor(t,e={}){this.logger=t.logger,this.log=t.logger.forComponent("helia:bitswap"),this.blockstore=t.blockstore,this.stats=new Ge(t),this.network=new Oe(t,e),this.peerWantLists=new We({...t,network:this.network},e),this.wantList=new Xe({...t,network:this.network},e)}createSession(t={}){return Fs({wantList:this.wantList,network:this.network,logger:this.logger},t)}async want(t,e={}){let n=new AbortController,s=On([n.signal,e.signal]);G(1/0,n.signal,s),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 $s=(r,t={})=>new Qe(r,t);var mn=class{bitswap;started;constructor(t,e={}){let{hashers:n}=t;this.bitswap=$s(t,{hashLoader:{getHasher:async s=>{let o;if(typeof s=="string"?o=Object.values(n).find(i=>i.name===s):o=n[s],o!=null)return o;throw new Error(`Could not load hasher for code/name "${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 zs(r={}){return t=>new mn(t,r)}var je=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,c=this.peekChar();if(c===void 0)return;let l=c==="0",u=2**(8*s)-1;for(;;){let d=this.readAtomically(()=>{let f=this.readChar();if(f===void 0)return;let x=Number.parseInt(f,t);if(!Number.isNaN(x))return x});if(d===void 0)break;if(o*=t,o+=d,o>u||(i+=1,e!==void 0&&i>e))return}if(i!==0)return!n&&l&&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),[c]=t(o.subarray(0,i));return e.set(o.subarray(0,c),16-c),e})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};var Vs=45,Pa=15,Vt=new je;function gn(r){if(!(r.length>Pa))return Vt.new(r).parseWith(()=>Vt.readIPv4Addr())}function wn(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>Vs))return Vt.new(r).parseWith(()=>Vt.readIPv6Addr())}function Ke(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>Vs))return Vt.new(r).parseWith(()=>Vt.readIPAddr())}function Ht(r){return!!gn(r)}function Wt(r){return!!wn(r)}function Je(r){return!!Ke(r)}var Ws=lr(Hs(),1),Ra=["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"],Ca=Ra.map(r=>new Ws.Netmask(r));function bn(r){for(let t of Ca)if(t.contains(r))return!0;return!1}function Ua(r){return/^::ffff:([0-9a-fA-F]{1,4}):([0-9a-fA-F]{1,4})$/.test(r)}function Na(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 bn(s)}function Ma(r){return/^::ffff:([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)}function Fa(r){let t=r.split(":"),e=t[t.length-1];return bn(e)}function Ba(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 qs(r){return Ht(r)?bn(r):Ua(r)?Na(r):Ma(r)?Fa(r):Wt(r)?Ba(r):void 0}var Gd=parseInt("0xFFFF",16),Xd=new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);var Qs=Ht,Ha=Wt,yn=function(r){let t=0;if(r=r.toString().trim(),Qs(r)){let e=new Uint8Array(t+4);return r.split(/\./g).forEach(n=>{e[t++]=parseInt(n,10)&255}),e}if(Ha(r)){let e=r.split(":",8),n;for(n=0;n<e.length;n++){let o=Qs(e[n]),i;o&&(i=yn(e[n]),e[n]=P(i.slice(0,2),"base16")),i!=null&&++n<8&&e.splice(n,0,P(i.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 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++){let o=parseInt(e[n],16);s[t++]=o>>8&255,s[t++]=o&255}return s}throw new Error("invalid ip address")},js=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 o=0;o<e;o++)s.push(r[t+o]);return s.join(".")}if(e===16){let s=[];for(let o=0;o<e;o+=2)s.push(n.getUint16(t+o).toString(16));return s.join(":").replace(/(^|:)0(:0)*:0(:|$)/,"$1::$3").replace(/:{3,4}/,"::")}return""};var qt={},xn={},qa=[[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"]];qa.forEach(r=>{let t=Ga(...r);xn[t.code]=t,qt[t.name]=t});function Ga(r,t,e,n,s){return{code:r,size:t,name:e,resolvable:!!n,path:!!s}}function S(r){if(typeof r=="number"){if(xn[r]!=null)return xn[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 Tp=S("ip4"),_p=S("ip6"),Dp=S("ipcidr");function An(r,t){switch(S(r).code){case 4:case 41:return Qa(t);case 42:return Sn(t);case 6:case 273:case 33:case 132:return Zs(t).toString();case 53:case 54:case 55:case 56:case 400:case 449:case 777:return Sn(t);case 421:return Za(t);case 444:return Js(t);case 445:return Js(t);case 466:return Ja(t);case 481:return globalThis.encodeURIComponent(Sn(t));default:return P(t,"base16")}}function kn(r,t){switch(S(r).code){case 4:return Ks(t);case 41:return Ks(t);case 42:return vn(t);case 6:case 273:case 33:case 132:return Ln(parseInt(t,10));case 53:case 54:case 55:case 56:case 400:case 449:case 777:return vn(t);case 421:return ja(t);case 444:return Ya(t);case 445:return tc(t);case 466:return Ka(t);case 481:return vn(globalThis.decodeURIComponent(t));default:return ot(t,"base16")}}var En=Object.values(wt).map(r=>r.decoder),Xa=function(){let r=En[0].or(En[1]);return En.slice(2).forEach(t=>r=r.or(t)),r}();function Ks(r){if(!Je(r))throw new Error("invalid ip address");return yn(r)}function Qa(r){let t=js(r,0,r.length);if(t==null)throw new Error("ipBuff is required");if(!Je(t))throw new Error("invalid ip address");return t}function Ln(r){let t=new ArrayBuffer(2);return new DataView(t).setUint16(0,r),new Uint8Array(t)}function Zs(r){return new DataView(r.buffer).getUint16(r.byteOffset)}function vn(r){let t=ot(r),e=Uint8Array.from(nt(t.length));return Q([e,t],e.length+t.length)}function Sn(r){let t=tt(r);if(r=r.slice(D(t)),r.length!==t)throw new Error("inconsistent lengths");return P(r)}function ja(r){let t;r[0]==="Q"||r[0]==="1"?t=Et(N.decode(`z${r}`)).bytes:t=B.parse(r).multihash.bytes;let e=Uint8Array.from(nt(t.length));return Q([e,t],e.length+t.length)}function Ka(r){let t=Xa.decode(r),e=Uint8Array.from(nt(t.length));return Q([e,t],e.length+t.length)}function Ja(r){let t=tt(r),e=r.slice(D(t));if(e.length!==t)throw new Error("inconsistent lengths");return"u"+P(e,"base64url")}function Za(r){let t=tt(r),e=r.slice(D(t));if(e.length!==t)throw new Error("inconsistent lengths");return P(e,"base58btc")}function Ya(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=lt.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=Ln(n);return Q([e,s],e.length+s.length)}function tc(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=lt.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=Ln(n);return Q([e,s],e.length+s.length)}function Js(r){let t=r.slice(0,r.length-2),e=r.slice(r.length-2),n=P(t,"base32"),s=Zs(e);return`${n}:${s}`}function Ys(r){r=In(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 o=0;o<s.length;o++){let i=s[o],c=S(i);if(c.size===0){t.push([c.code]),e.push([c.code]);continue}if(o++,o>=s.length)throw eo("invalid address: "+r);if(c.path===!0){n=In(s.slice(o).join("/")),t.push([c.code,kn(c.code,n)]),e.push([c.code,n]);break}let l=kn(c.code,s[o]);t.push([c.code,l]),e.push([c.code,An(c.code,l)])}return{string:to(e),bytes:_n(t),tuples:t,stringTuples:e,path:n}}function Tn(r){let t=[],e=[],n=null,s=0;for(;s<r.length;){let o=tt(r,s),i=D(o),c=S(o),l=ec(c,r.slice(s+i));if(l===0){t.push([o]),e.push([o]),s+=i;continue}let u=r.slice(s+i,s+i+l);if(s+=l+i,s>r.length)throw eo("Invalid address Uint8Array: "+P(r,"base16"));t.push([o,u]);let d=An(o,u);if(e.push([o,d]),c.path===!0){n=d;break}}return{bytes:Uint8Array.from(r),string:to(e),tuples:t,stringTuples:e,path:n}}function to(r){let t=[];return r.map(e=>{let n=S(e[0]);return t.push(n.name),e.length>1&&e[1]!=null&&t.push(e[1]),null}),In(t.join("/"))}function _n(r){return Q(r.map(t=>{let e=S(t[0]),n=Uint8Array.from(nt(e.code));return t.length>1&&t[1]!=null&&(n=Q([n,t[1]])),n}))}function ec(r,t){if(r.size>0)return r.size/8;if(r.size===0)return 0;{let e=tt(t instanceof Uint8Array?t:Uint8Array.from(t));return e+D(e)}}function In(r){return"/"+r.trim().split("/").filter(t=>t).join("/")}function eo(r){return new Error("Error parsing address: "+r)}var rc=Symbol.for("nodejs.util.inspect.custom"),Dn=Symbol.for("@multiformats/js-multiaddr/multiaddr"),nc=[S("dns").code,S("dns4").code,S("dns6").code,S("dnsaddr").code],Ze=class r{bytes;#t;#e;#r;#n;[Dn]=!0;constructor(t){t==null&&(t="");let e;if(t instanceof Uint8Array)e=Tn(t);else if(typeof t=="string"){if(t.length>0&&t.charAt(0)!=="/")throw new Error(`multiaddr "${t}" must start with a "/"`);e=Ys(t)}else if(no(t))e=Tn(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,o="",i=S("tcp"),c=S("udp"),l=S("ip4"),u=S("ip6"),d=S("dns6"),f=S("ip6zone");for(let[a,h]of this.stringTuples())a===f.code&&(o=`%${h??""}`),nc.includes(a)&&(e=i.name,s=443,n=`${h??""}${o}`,t=a===d.code?6:4),(a===i.code||a===c.code)&&(e=S(a).name,s=parseInt(h??"")),(a===l.code||a===u.code)&&(e=S(a).name,n=`${h??""}${o}`,t=a===u.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({},S(t)))}protoCodes(){return this.#e.map(([t])=>t)}protoNames(){return this.#e.map(([t])=>S(t).name)}tuples(){return this.#e}stringTuples(){return this.#r}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(_n(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"?P(N.decode(`z${n}`),"base58btc"):P(B.parse(n).multihash.bytes,"base58btc")}return null}catch{return null}}getPath(){return this.#n}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=ro.get(e.name);if(n==null)throw new F(`no available resolver for ${e.name}`,"ERR_NO_AVAILABLE_RESOLVER");return(await n(this,t)).map(o=>ue(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(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)}[rc](){return`Multiaddr(${this.#t})`}};var ro=new Map;function no(r){return!!r?.[Dn]}function ue(r){return new Ze(r)}var sc=r=>r.toString().split("/").slice(1),he=r=>({match:t=>t.length<1?!1:r(t[0])?t.slice(1):!1,pattern:"fn"}),L=r=>({match:t=>he(e=>e===r).match(t),pattern:r}),er=()=>({match:r=>he(t=>typeof t=="string").match(r),pattern:"{string}"}),rr=()=>({match:r=>he(t=>!isNaN(parseInt(t))).match(r),pattern:"{number}"}),O=()=>({match:r=>{if(r.length<2||r[0]!=="p2p"&&r[0]!=="ipfs")return!1;if(r[1].startsWith("Q")||r[1].startsWith("1"))try{N.decode(`z${r[1]}`)}catch{return!1}else return!1;return r.slice(2)},pattern:"/p2p/{peerid}"}),Ye=()=>({match:r=>{if(r.length<2||r[0]!=="certhash")return!1;try{$r.decode(r[1])}catch{return!1}return r.slice(2)},pattern:"/certhash/{certhash}"}),M=r=>({match:t=>{let e=r.match(t);return e===!1?t:e},pattern:`optional(${r.pattern})`}),J=(...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(", ")})`}),_=(...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 U(...r){function t(s){let o=sc(s);for(let i of r){let c=i.match(o);if(c===!1)return!1;o=c}return o}function e(s){return t(s)!==!1}function n(s){let o=t(s);return o===!1?!1:o.length===0}return{matches:e,exactMatch:n}}var Rn=_(L("dns4"),er()),Cn=_(L("dns6"),er()),Un=_(L("dnsaddr"),er()),so=_(L("dns"),er()),om=U(Rn),im=U(Cn),am=U(Un),oo=U(J(so,Un,Rn,Cn)),io=_(L("ip4"),he(Ht)),ao=_(L("ip6"),he(Wt)),co=J(io,ao),it=J(co,so,Rn,Cn,Un),cm=U(it),lm=U(io),um=U(ao),hm=U(co),Nn=_(it,L("tcp"),rr()),fe=_(it,L("udp"),rr()),fm=U(Nn),dm=U(fe),Mn=_(fe,L("quic")),nr=_(fe,L("quic-v1")),oc=J(Mn,nr),pm=U(Mn),mm=U(nr),Pn=J(it,Nn,fe,Mn,nr),lo=J(_(Pn,L("ws"),M(O()))),gm=U(lo),uo=J(_(Pn,L("wss"),M(O())),_(Pn,L("tls"),L("ws"),M(O()))),wm=U(uo),ho=_(fe,L("webrtc-direct"),M(Ye()),M(Ye()),M(O())),bm=U(ho),fo=_(nr,L("webtransport"),M(Ye()),M(Ye()),M(O())),ym=U(fo),tr=J(lo,uo,_(Nn,M(O())),_(oc,M(O())),_(it,M(O())),ho,fo,O()),xm=U(tr),ic=_(tr,L("p2p-circuit"),O()),Em=U(ic),ac=J(_(tr,L("p2p-circuit"),L("webrtc"),M(O())),_(tr,L("webrtc"),M(O())),L("webrtc")),vm=U(ac),cc=J(_(it,L("tcp"),rr(),L("http"),M(O())),_(it,L("http"),M(O()))),po=U(cc),lc=J(_(it,L("tcp"),J(_(L("443"),L("http")),_(rr(),L("https"))),M(O())),_(it,L("tls"),L("http"),M(O())),_(it,L("https"),M(O()))),mo=U(lc);var uc=[S("tcp").code,S("dns").code,S("dnsaddr").code,S("dns4").code,S("dns6").code];function go(r){let t;try{t=S("sni").code}catch{return null}for(let[e,n]of r)if(e===t&&n!==void 0)return n;return null}function wo(r){return r.some(([t,e])=>t===S("tls").code)}function W(r,t,e){let n=bo[S(r).name];if(n===void 0)throw new Error(`Can't interpret protocol ${S(r).name}`);let s=n(t,e);return r===S("ip6").code?`[${s}]`:s}var bo={ip4:(r,t)=>r,ip6:(r,t)=>t.length===0?r:`[${r}]`,tcp:(r,t)=>{let e=t.pop();if(e===void 0)throw new Error("Unexpected end of multiaddr");return`tcp://${W(e[0],e[1]??"",t)}:${r}`},udp:(r,t)=>{let e=t.pop();if(e===void 0)throw new Error("Unexpected end of multiaddr");return`udp://${W(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===void 0)throw new Error("Unexpected end of multiaddr");return`${W(e[0],e[1]??"",t)}/ipfs/${r}`},p2p:(r,t)=>{let e=t.pop();if(e===void 0)throw new Error("Unexpected end of multiaddr");return`${W(e[0],e[1]??"",t)}/p2p/${r}`},http:(r,t)=>{let e=wo(t),n=go(t);if(e&&n!==null)return`https://${n}`;let s=e?"https://":"http://",o=t.pop();if(o===void 0)throw new Error("Unexpected end of multiaddr");let i=W(o[0],o[1]??"",t);return i=i.replace("tcp://",""),`${s}${i}`},"http-path":(r,t)=>{let e=t.pop();if(e===void 0)throw new Error("Unexpected end of multiaddr");let n=W(e[0],e[1]??"",t),s=decodeURIComponent(r);return`${n}/${s}`},tls:(r,t)=>{let e=t.pop();if(e===void 0)throw new Error("Unexpected end of multiaddr");return W(e[0],e[1]??"",t)},sni:(r,t)=>{let e=t.pop();if(e===void 0)throw new Error("Unexpected end of multiaddr");return W(e[0],e[1]??"",t)},https:(r,t)=>{let e=t.pop();if(e===void 0)throw new Error("Unexpected end of multiaddr");let n=W(e[0],e[1]??"",t);return n=n.replace("tcp://",""),`https://${n}`},ws:(r,t)=>{let e=wo(t),n=go(t);if(e&&n!==null)return`wss://${n}`;let s=e?"wss://":"ws://",o=t.pop();if(o===void 0)throw new Error("Unexpected end of multiaddr");let i=W(o[0],o[1]??"",t);return i=i.replace("tcp://",""),`${s}${i}`},wss:(r,t)=>{let e=t.pop();if(e===void 0)throw new Error("Unexpected end of multiaddr");let n=W(e[0],e[1]??"",t);return n=n.replace("tcp://",""),`wss://${n}`},"p2p-websocket-star":(r,t)=>{let e=t.pop();if(e===void 0)throw new Error("Unexpected end of multiaddr");return`${W(e[0],e[1]??"",t)}/p2p-websocket-star`},"p2p-webrtc-star":(r,t)=>{let e=t.pop();if(e===void 0)throw new Error("Unexpected end of multiaddr");return`${W(e[0],e[1]??"",t)}/p2p-webrtc-star`},"p2p-webrtc-direct":(r,t)=>{let e=t.pop();if(e===void 0)throw new Error("Unexpected end of multiaddr");return`${W(e[0],e[1]??"",t)}/p2p-webrtc-direct`}};function yo(r,t){let n=ue(r).stringTuples(),s=n.pop();if(s===void 0)throw new Error("Unexpected end of multiaddr");let o=S(s[0]),i=bo[o.name];if(i==null)throw new Error(`No interpreter found for ${o.name}`);let c=i(s[1]??"",n);return t?.assumeHttp!==!1&&uc.includes(s[0])&&(c=c.replace(/^.*:\/\//,""),s[1]==="443"?c=`https://${c}`:c=`http://${c}`),(c.startsWith("http://")||c.startsWith("https://"))&&(c=new URL(c).toString(),c.endsWith("/")&&(c=c.substring(0,c.length-1))),c}var sr=class{url;#t=0;#e=0;#r=0;#n=0;#s=new Map;log;constructor(t,e){this.url=t instanceof URL?t:new URL(t),this.log=e.forComponent(`helia:trustless-gateway-block-broker:${this.url.hostname}`)}#o(t){let e=t.multihash.bytes;return ut.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.#o(t),o=new AbortController,i=()=>{o.abort()};e?.addEventListener("abort",i);try{let c=this.#s.get(s);return c==null&&(this.#t++,c=fetch(n.toString(),{signal:o.signal,headers:{Accept:"application/vnd.ipld.raw"},cache:"force-cache"}).then(async l=>{if(this.log("GET %s %d",n,l.status),!l.ok)throw this.#e++,new Error(`unable to fetch raw block for CID ${t} from gateway ${this.url}`);return this.#n++,new Uint8Array(await l.arrayBuffer())}),this.#s.set(s,c)),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",i),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}}};function hc(r,t,e){return r.filter(n=>{if(mo.matches(n)||t&&po.matches(n))return e||oo.matches(n)?!0:qs(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*or(r,t,e,n,s,o){for await(let i of t.findProviders(r,o)){let c=hc(i.multiaddrs,n,s);if(c.length===0)continue;let l=yo(c[0]);yield new sr(l,e)}}var Fn=class extends Tt{routing;allowInsecure;allowLocal;constructor(t,e){super(t,{...e,name:"helia:trustless-gateway:session"}),this.routing=t.routing,this.allowInsecure=e.allowInsecure??ir,this.allowLocal=e.allowLocal??ar}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*or(t,this.routing,this.logger,this.allowInsecure,this.allowLocal,e)}toEvictionKey(t){return t.url.toString()}equals(t,e){return t.url.toString()===e.url.toString()}};function xo(r,t){return new Fn(r,t)}var cr=class{allowInsecure;allowLocal;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??ir,this.allowLocal=e.allowLocal??ar}async retrieve(t,e={}){let n=[];for await(let s of or(t,this.routing,this.logger,this.allowInsecure,this.allowLocal,e)){this.log("getting block for %c from %s",t,s.url);try{let o=await s.getRawBlock(t,e.signal);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 xo({logger:this.logger,routing:this.routing},{...t,allowLocal:this.allowLocal,allowInsecure:this.allowInsecure})}};var ir=!1,ar=!1;function Eo(r={}){return t=>new cr(t,r)}return Io(fc);})();
3
3
  /*! Bundled license information:
4
4
 
5
5
  @noble/hashes/esm/utils.js:
@@ -1 +1 @@
1
- {"version":3,"file":"broker.d.ts","sourceRoot":"","sources":["../../../src/trustless-gateway/broker.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,+BAA+B,EAAE,0BAA0B,EAAE,sCAAsC,EAAE,MAAM,YAAY,CAAA;AACrI,OAAO,KAAK,EAAW,qBAAqB,EAAE,WAAW,EAAE,oBAAoB,EAAE,MAAM,kBAAkB,CAAA;AAEzG,OAAO,KAAK,EAAE,GAAG,EAAE,MAAM,kBAAkB,CAAA;AAE3C,MAAM,WAAW,oCAAqC,SAAQ,oBAAoB,CAAC,sCAAsC,CAAC;IACxH;;;;;OAKG;IACH,aAAa,CAAC,EAAE,OAAO,CAAA;IAEvB;;;;;OAKG;IACH,UAAU,CAAC,EAAE,OAAO,CAAA;CACrB;AAED;;;GAGG;AACH,qBAAa,2BAA4B,YAAW,WAAW,CAAC,sCAAsC,CAAC;IACrG,OAAO,CAAC,QAAQ,CAAC,aAAa,CAAS;IACvC,OAAO,CAAC,QAAQ,CAAC,UAAU,CAAS;IACpC,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAS;IACjC,OAAO,CAAC,QAAQ,CAAC,GAAG,CAAQ;IAC5B,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAiB;gBAE3B,UAAU,EAAE,0BAA0B,EAAE,IAAI,GAAE,+BAAoC;IAQzF,QAAQ,CAAE,GAAG,EAAE,GAAG,EAAE,OAAO,GAAE,qBAAqB,CAAC,sCAAsC,CAAM,GAAG,OAAO,CAAC,UAAU,CAAC;IA2C3H,aAAa,CAAE,OAAO,GAAE,oCAAyC,GAAG,WAAW,CAAC,sCAAsC,CAAC;CAMxH"}
1
+ {"version":3,"file":"broker.d.ts","sourceRoot":"","sources":["../../../src/trustless-gateway/broker.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,+BAA+B,EAAE,0BAA0B,EAAE,sCAAsC,EAAE,MAAM,YAAY,CAAA;AACrI,OAAO,KAAK,EAAW,qBAAqB,EAAE,WAAW,EAAE,oBAAoB,EAAE,MAAM,kBAAkB,CAAA;AAEzG,OAAO,KAAK,EAAE,GAAG,EAAE,MAAM,kBAAkB,CAAA;AAE3C,MAAM,WAAW,oCAAqC,SAAQ,oBAAoB,CAAC,sCAAsC,CAAC;IACxH;;;;;OAKG;IACH,aAAa,CAAC,EAAE,OAAO,CAAA;IAEvB;;;;;OAKG;IACH,UAAU,CAAC,EAAE,OAAO,CAAA;CACrB;AAED;;;GAGG;AACH,qBAAa,2BAA4B,YAAW,WAAW,CAAC,sCAAsC,CAAC;IACrG,OAAO,CAAC,QAAQ,CAAC,aAAa,CAAS;IACvC,OAAO,CAAC,QAAQ,CAAC,UAAU,CAAS;IACpC,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAS;IACjC,OAAO,CAAC,QAAQ,CAAC,GAAG,CAAQ;IAC5B,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAiB;gBAE3B,UAAU,EAAE,0BAA0B,EAAE,IAAI,GAAE,+BAAoC;IAQzF,QAAQ,CAAE,GAAG,EAAE,GAAG,EAAE,OAAO,GAAE,qBAAqB,CAAC,sCAAsC,CAAM,GAAG,OAAO,CAAC,UAAU,CAAC;IA2C3H,aAAa,CAAE,OAAO,GAAE,oCAAyC,GAAG,WAAW,CAAC,sCAAsC,CAAC;CAUxH"}
@@ -61,7 +61,11 @@ export class TrustlessGatewayBlockBroker {
61
61
  return createTrustlessGatewaySession({
62
62
  logger: this.logger,
63
63
  routing: this.routing
64
- }, options);
64
+ }, {
65
+ ...options,
66
+ allowLocal: this.allowLocal,
67
+ allowInsecure: this.allowInsecure
68
+ });
65
69
  }
66
70
  }
67
71
  //# sourceMappingURL=broker.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"broker.js","sourceRoot":"","sources":["../../../src/trustless-gateway/broker.ts"],"names":[],"mappings":"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"}
1
+ {"version":3,"file":"broker.js","sourceRoot":"","sources":["../../../src/trustless-gateway/broker.ts"],"names":[],"mappings":"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"}
@@ -1 +1 @@
1
- {"version":3,"file":"trustless-gateway.js","sourceRoot":"","sources":["../../../src/trustless-gateway/trustless-gateway.ts"],"names":[],"mappings":"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"}
1
+ {"version":3,"file":"trustless-gateway.js","sourceRoot":"","sources":["../../../src/trustless-gateway/trustless-gateway.ts"],"names":[],"mappings":"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"}
@@ -1 +1 @@
1
- {"version":3,"file":"utils.d.ts","sourceRoot":"","sources":["../../../src/trustless-gateway/utils.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,gBAAgB,EAAE,MAAM,wBAAwB,CAAA;AACzD,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,kBAAkB,CAAA;AAC/C,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,mBAAmB,CAAA;AACxD,OAAO,KAAK,EAAE,YAAY,EAAE,SAAS,EAAE,MAAM,yBAAyB,CAAA;AACtE,OAAO,KAAK,EAAE,GAAG,EAAE,MAAM,kBAAkB,CAAA;AAE3C,wBAAgB,uBAAuB,CAAE,UAAU,EAAE,SAAS,EAAE,EAAE,aAAa,EAAE,OAAO,EAAE,UAAU,EAAE,OAAO,GAAG,SAAS,EAAE,CAgB1H;AAED,wBAAwB,wBAAwB,CAAE,GAAG,EAAE,GAAG,EAAE,OAAO,EAAE,OAAO,EAAE,MAAM,EAAE,eAAe,EAAE,aAAa,EAAE,OAAO,EAAE,UAAU,EAAE,OAAO,EAAE,OAAO,CAAC,EAAE,YAAY,GAAG,cAAc,CAAC,gBAAgB,CAAC,CAiB5M"}
1
+ {"version":3,"file":"utils.d.ts","sourceRoot":"","sources":["../../../src/trustless-gateway/utils.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,gBAAgB,EAAE,MAAM,wBAAwB,CAAA;AACzD,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,kBAAkB,CAAA;AAC/C,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,mBAAmB,CAAA;AACxD,OAAO,KAAK,EAAE,YAAY,EAAE,SAAS,EAAE,MAAM,yBAAyB,CAAA;AACtE,OAAO,KAAK,EAAE,GAAG,EAAE,MAAM,kBAAkB,CAAA;AAE3C,wBAAgB,uBAAuB,CAAE,UAAU,EAAE,SAAS,EAAE,EAAE,aAAa,EAAE,OAAO,EAAE,UAAU,EAAE,OAAO,GAAG,SAAS,EAAE,CAwB1H;AAED,wBAAwB,wBAAwB,CAAE,GAAG,EAAE,GAAG,EAAE,OAAO,EAAE,OAAO,EAAE,MAAM,EAAE,eAAe,EAAE,aAAa,EAAE,OAAO,EAAE,UAAU,EAAE,OAAO,EAAE,OAAO,CAAC,EAAE,YAAY,GAAG,cAAc,CAAC,gBAAgB,CAAC,CAiB5M"}
@@ -13,6 +13,13 @@ export function filterNonHTTPMultiaddrs(multiaddrs, allowInsecure, allowLocal) {
13
13
  }
14
14
  return isPrivateIp(ma.toOptions().host) === false;
15
15
  }
16
+ // When allowInsecure is false and allowLocal is true, allow multiaddrs with "127.0.0.1", "localhost", or any subdomain ending with ".localhost"
17
+ if (!allowInsecure && allowLocal) {
18
+ const { host } = ma.toOptions();
19
+ if (host === '127.0.0.1' || host === 'localhost' || host.endsWith('.localhost')) {
20
+ return true;
21
+ }
22
+ }
16
23
  return false;
17
24
  });
18
25
  }
@@ -1 +1 @@
1
- {"version":3,"file":"utils.js","sourceRoot":"","sources":["../../../src/trustless-gateway/utils.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,0BAA0B,CAAA;AACtD,OAAO,EAAE,GAAG,EAAE,IAAI,EAAE,KAAK,EAAE,MAAM,iCAAiC,CAAA;AAClE,OAAO,EAAE,cAAc,EAAE,MAAM,gCAAgC,CAAA;AAC/D,OAAO,EAAE,gBAAgB,EAAE,MAAM,wBAAwB,CAAA;AAMzD,MAAM,UAAU,uBAAuB,CAAE,UAAuB,EAAE,aAAsB,EAAE,UAAmB;IAC3G,OAAO,UAAU,CAAC,MAAM,CAAC,EAAE,CAAC,EAAE;QAC5B,IAAI,KAAK,CAAC,OAAO,CAAC,EAAE,CAAC,IAAI,CAAC,aAAa,IAAI,IAAI,CAAC,OAAO,CAAC,EAAE,CAAC,CAAC,EAAE,CAAC;YAC7D,IAAI,UAAU,EAAE,CAAC;gBACf,OAAO,IAAI,CAAA;YACb,CAAC;YAED,IAAI,GAAG,CAAC,OAAO,CAAC,EAAE,CAAC,EAAE,CAAC;gBACpB,OAAO,IAAI,CAAA;YACb,CAAC;YAED,OAAO,WAAW,CAAC,EAAE,CAAC,SAAS,EAAE,CAAC,IAAI,CAAC,KAAK,KAAK,CAAA;QACnD,CAAC;QAED,OAAO,KAAK,CAAA;IACd,CAAC,CAAC,CAAA;AACJ,CAAC;AAED,MAAM,CAAC,KAAK,SAAU,CAAC,CAAC,wBAAwB,CAAE,GAAQ,EAAE,OAAgB,EAAE,MAAuB,EAAE,aAAsB,EAAE,UAAmB,EAAE,OAAsB;IACxK,IAAI,KAAK,EAAE,MAAM,QAAQ,IAAI,OAAO,CAAC,aAAa,CAAC,GAAG,EAAE,OAAO,CAAC,EAAE,CAAC;QACjE,4BAA4B;QAC5B,MAAM,aAAa,GAAG,uBAAuB,CAAC,QAAQ,CAAC,UAAU,EAAE,aAAa,EAAE,UAAU,CAAC,CAAA;QAE7F,IAAI,aAAa,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;YAC/B,SAAQ;QACV,CAAC;QAED,sBAAsB;QACtB,8BAA8B;QAC9B,+BAA+B;QAC/B,MAAM;QACN,MAAM,GAAG,GAAG,cAAc,CAAC,aAAa,CAAC,CAAC,CAAC,CAAC,CAAA;QAE5C,MAAM,IAAI,gBAAgB,CAAC,GAAG,EAAE,MAAM,CAAC,CAAA;IACzC,CAAC;AACH,CAAC"}
1
+ {"version":3,"file":"utils.js","sourceRoot":"","sources":["../../../src/trustless-gateway/utils.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,0BAA0B,CAAA;AACtD,OAAO,EAAE,GAAG,EAAE,IAAI,EAAE,KAAK,EAAE,MAAM,iCAAiC,CAAA;AAClE,OAAO,EAAE,cAAc,EAAE,MAAM,gCAAgC,CAAA;AAC/D,OAAO,EAAE,gBAAgB,EAAE,MAAM,wBAAwB,CAAA;AAMzD,MAAM,UAAU,uBAAuB,CAAE,UAAuB,EAAE,aAAsB,EAAE,UAAmB;IAC3G,OAAO,UAAU,CAAC,MAAM,CAAC,EAAE,CAAC,EAAE;QAC5B,IAAI,KAAK,CAAC,OAAO,CAAC,EAAE,CAAC,IAAI,CAAC,aAAa,IAAI,IAAI,CAAC,OAAO,CAAC,EAAE,CAAC,CAAC,EAAE,CAAC;YAC7D,IAAI,UAAU,EAAE,CAAC;gBACf,OAAO,IAAI,CAAA;YACb,CAAC;YAED,IAAI,GAAG,CAAC,OAAO,CAAC,EAAE,CAAC,EAAE,CAAC;gBACpB,OAAO,IAAI,CAAA;YACb,CAAC;YAED,OAAO,WAAW,CAAC,EAAE,CAAC,SAAS,EAAE,CAAC,IAAI,CAAC,KAAK,KAAK,CAAA;QACnD,CAAC;QAED,gJAAgJ;QAChJ,IAAI,CAAC,aAAa,IAAI,UAAU,EAAE,CAAC;YACjC,MAAM,EAAE,IAAI,EAAE,GAAG,EAAE,CAAC,SAAS,EAAE,CAAA;YAC/B,IAAI,IAAI,KAAK,WAAW,IAAI,IAAI,KAAK,WAAW,IAAI,IAAI,CAAC,QAAQ,CAAC,YAAY,CAAC,EAAE,CAAC;gBAChF,OAAO,IAAI,CAAA;YACb,CAAC;QACH,CAAC;QAED,OAAO,KAAK,CAAA;IACd,CAAC,CAAC,CAAA;AACJ,CAAC;AAED,MAAM,CAAC,KAAK,SAAU,CAAC,CAAC,wBAAwB,CAAE,GAAQ,EAAE,OAAgB,EAAE,MAAuB,EAAE,aAAsB,EAAE,UAAmB,EAAE,OAAsB;IACxK,IAAI,KAAK,EAAE,MAAM,QAAQ,IAAI,OAAO,CAAC,aAAa,CAAC,GAAG,EAAE,OAAO,CAAC,EAAE,CAAC;QACjE,4BAA4B;QAC5B,MAAM,aAAa,GAAG,uBAAuB,CAAC,QAAQ,CAAC,UAAU,EAAE,aAAa,EAAE,UAAU,CAAC,CAAA;QAE7F,IAAI,aAAa,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;YAC/B,SAAQ;QACV,CAAC;QAED,sBAAsB;QACtB,8BAA8B;QAC9B,+BAA+B;QAC/B,MAAM;QACN,MAAM,GAAG,GAAG,cAAc,CAAC,aAAa,CAAC,CAAC,CAAC,CAAC,CAAA;QAE5C,MAAM,IAAI,gBAAgB,CAAC,GAAG,EAAE,MAAM,CAAC,CAAA;IACzC,CAAC;AACH,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@helia/block-brokers",
3
- "version": "3.0.2",
3
+ "version": "3.0.3-ac4bdb8",
4
4
  "description": "Block brokers for Helia",
5
5
  "license": "Apache-2.0 OR MIT",
6
6
  "homepage": "https://github.com/ipfs/helia/tree/main/packages/block-brokers#readme",
@@ -53,9 +53,9 @@
53
53
  "test:electron-main": "aegir test -t electron-main"
54
54
  },
55
55
  "dependencies": {
56
- "@helia/bitswap": "^1.1.2",
57
- "@helia/interface": "^4.3.0",
58
- "@helia/utils": "^0.3.2",
56
+ "@helia/bitswap": "1.1.3-ac4bdb8",
57
+ "@helia/interface": "4.3.1-ac4bdb8",
58
+ "@helia/utils": "0.3.3-ac4bdb8",
59
59
  "@libp2p/interface": "^1.1.4",
60
60
  "@libp2p/utils": "^5.2.6",
61
61
  "@multiformats/multiaddr": "^12.2.1",
@@ -72,10 +72,10 @@
72
72
  "@multiformats/uri-to-multiaddr": "^8.0.0",
73
73
  "@types/polka": "^0.5.7",
74
74
  "@types/sinon": "^17.0.3",
75
- "aegir": "^42.2.5",
75
+ "aegir": "^44.0.1",
76
76
  "cors": "^2.8.5",
77
77
  "polka": "^0.5.2",
78
- "sinon": "^17.0.1",
78
+ "sinon": "^18.0.0",
79
79
  "sinon-ts": "^2.0.0",
80
80
  "uint8arrays": "^5.0.3"
81
81
  }
@@ -90,6 +90,10 @@ export class TrustlessGatewayBlockBroker implements BlockBroker<TrustlessGateway
90
90
  return createTrustlessGatewaySession({
91
91
  logger: this.logger,
92
92
  routing: this.routing
93
- }, options)
93
+ }, {
94
+ ...options,
95
+ allowLocal: this.allowLocal,
96
+ allowInsecure: this.allowInsecure
97
+ })
94
98
  }
95
99
  }
@@ -51,7 +51,7 @@ export class TrustlessGateway {
51
51
  * only one request per CID is made to a given gateway at a time, and that we
52
52
  * don't make multiple in-flight requests for the same CID to the same gateway.
53
53
  */
54
- #pendingResponses = new Map<string, Promise<Uint8Array>>()
54
+ readonly #pendingResponses = new Map<string, Promise<Uint8Array>>()
55
55
 
56
56
  private readonly log: Logger
57
57
 
@@ -21,6 +21,14 @@ export function filterNonHTTPMultiaddrs (multiaddrs: Multiaddr[], allowInsecure:
21
21
  return isPrivateIp(ma.toOptions().host) === false
22
22
  }
23
23
 
24
+ // When allowInsecure is false and allowLocal is true, allow multiaddrs with "127.0.0.1", "localhost", or any subdomain ending with ".localhost"
25
+ if (!allowInsecure && allowLocal) {
26
+ const { host } = ma.toOptions()
27
+ if (host === '127.0.0.1' || host === 'localhost' || host.endsWith('.localhost')) {
28
+ return true
29
+ }
30
+ }
31
+
24
32
  return false
25
33
  })
26
34
  }
@@ -1,4 +0,0 @@
1
- {
2
- "bitswap": "https://ipfs.github.io/helia/functions/_helia_block_brokers.bitswap.html",
3
- "trustlessGateway": "https://ipfs.github.io/helia/functions/_helia_block_brokers.trustlessGateway.html"
4
- }