@helia/block-brokers 2.0.3-7cd012a → 2.0.3-9c8a2c0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.min.js +1 -1
- package/package.json +3 -3
package/dist/index.min.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
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 di=Object.create;var me=Object.defineProperty;var pi=Object.getOwnPropertyDescriptor;var mi=Object.getOwnPropertyNames;var gi=Object.getPrototypeOf,wi=Object.prototype.hasOwnProperty;var Gt=(r,t)=>()=>(t||r((t={exports:{}}).exports,t),t.exports),V=(r,t)=>{for(var e in t)me(r,e,{get:t[e],enumerable:!0})},In=(r,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of mi(t))!wi.call(r,s)&&s!==e&&me(r,s,{get:()=>t[s],enumerable:!(n=pi(t,s))||n.enumerable});return r};var cr=(r,t,e)=>(e=r!=null?di(gi(r)):{},In(t||!r||!r.__esModule?me(e,"default",{value:r,enumerable:!0}):e,r)),bi=r=>In(me({},"__esModule",{value:!0}),r);var vs=Gt((Th,Es)=>{var $t=1e3,zt=$t*60,Vt=zt*60,wt=Vt*24,oa=wt*7,aa=wt*365.25;Es.exports=function(r,t){t=t||{};var e=typeof r;if(e==="string"&&r.length>0)return ca(r);if(e==="number"&&isFinite(r))return t.long?ua(r):la(r);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(r))};function ca(r){if(r=String(r),!(r.length>100)){var t=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(r);if(t){var e=parseFloat(t[1]),n=(t[2]||"ms").toLowerCase();switch(n){case"years":case"year":case"yrs":case"yr":case"y":return e*aa;case"weeks":case"week":case"w":return e*oa;case"days":case"day":case"d":return e*wt;case"hours":case"hour":case"hrs":case"hr":case"h":return e*Vt;case"minutes":case"minute":case"mins":case"min":case"m":return e*zt;case"seconds":case"second":case"secs":case"sec":case"s":return e*$t;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return e;default:return}}}}function la(r){var t=Math.abs(r);return t>=wt?Math.round(r/wt)+"d":t>=Vt?Math.round(r/Vt)+"h":t>=zt?Math.round(r/zt)+"m":t>=$t?Math.round(r/$t)+"s":r+"ms"}function ua(r){var t=Math.abs(r);return t>=wt?Ue(r,t,wt,"day"):t>=Vt?Ue(r,t,Vt,"hour"):t>=zt?Ue(r,t,zt,"minute"):t>=$t?Ue(r,t,$t,"second"):r+" ms"}function Ue(r,t,e,n){var s=t>=e*1.5;return Math.round(r/e)+" "+n+(s?"s":"")}});var As=Gt((Dh,Ss)=>{function ha(r){e.debug=e,e.default=e,e.coerce=c,e.disable=i,e.enable=s,e.enabled=o,e.humanize=vs(),e.destroy=l,Object.keys(r).forEach(h=>{e[h]=r[h]}),e.names=[],e.skips=[],e.formatters={};function t(h){let u=0;for(let f=0;f<h.length;f++)u=(u<<5)-u+h.charCodeAt(f),u|=0;return e.colors[Math.abs(u)%e.colors.length]}e.selectColor=t;function e(h){let u,f=null,g,p;function w(...d){if(!w.enabled)return;let E=w,L=Number(new Date),C=L-(u||L);E.diff=C,E.prev=u,E.curr=L,u=L,d[0]=e.coerce(d[0]),typeof d[0]!="string"&&d.unshift("%O");let F=0;d[0]=d[0].replace(/%([a-zA-Z%])/g,(X,z)=>{if(X==="%%")return"%";F++;let J=e.formatters[z];if(typeof J=="function"){let Lt=d[F];X=J.call(E,Lt),d.splice(F,1),F--}return X}),e.formatArgs.call(E,d),(E.log||e.log).apply(E,d)}return w.namespace=h,w.useColors=e.useColors(),w.color=e.selectColor(h),w.extend=n,w.destroy=e.destroy,Object.defineProperty(w,"enabled",{enumerable:!0,configurable:!1,get:()=>f!==null?f:(g!==e.namespaces&&(g=e.namespaces,p=e.enabled(h)),p),set:d=>{f=d}}),typeof e.init=="function"&&e.init(w),w}function n(h,u){let f=e(this.namespace+(typeof u>"u"?":":u)+h);return f.log=this.log,f}function s(h){e.save(h),e.namespaces=h,e.names=[],e.skips=[];let u,f=(typeof h=="string"?h:"").split(/[\s,]+/),g=f.length;for(u=0;u<g;u++)f[u]&&(h=f[u].replace(/\*/g,".*?"),h[0]==="-"?e.skips.push(new RegExp("^"+h.slice(1)+"$")):e.names.push(new RegExp("^"+h+"$")))}function i(){let h=[...e.names.map(a),...e.skips.map(a).map(u=>"-"+u)].join(",");return e.enable(""),h}function o(h){if(h[h.length-1]==="*")return!0;let u,f;for(u=0,f=e.skips.length;u<f;u++)if(e.skips[u].test(h))return!1;for(u=0,f=e.names.length;u<f;u++)if(e.names[u].test(h))return!0;return!1}function a(h){return h.toString().substring(2,h.toString().length-2).replace(/\.\*\?$/,"*")}function c(h){return h instanceof Error?h.stack||h.message:h}function l(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return e.enable(e.load()),e}Ss.exports=ha});var ks=Gt((q,Me)=>{q.formatArgs=da;q.save=pa;q.load=ma;q.useColors=fa;q.storage=ga();q.destroy=(()=>{let r=!1;return()=>{r||(r=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})();q.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function fa(){return typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs)?!0:typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)?!1:typeof document<"u"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&parseInt(RegExp.$1,10)>=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function da(r){if(r[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+r[0]+(this.useColors?"%c ":" ")+"+"+Me.exports.humanize(this.diff),!this.useColors)return;let t="color: "+this.color;r.splice(1,0,t,"color: inherit");let e=0,n=0;r[0].replace(/%[a-zA-Z%]/g,s=>{s!=="%%"&&(e++,s==="%c"&&(n=e))}),r.splice(n,0,t)}q.log=console.debug||console.log||(()=>{});function pa(r){try{r?q.storage.setItem("debug",r):q.storage.removeItem("debug")}catch{}}function ma(){let r;try{r=q.storage.getItem("debug")}catch{}return!r&&typeof process<"u"&&"env"in process&&(r=process.env.DEBUG),r}function ga(){try{return localStorage}catch{}}Me.exports=As()(q);var{formatters:wa}=Me.exports;wa.j=function(r){try{return JSON.stringify(r)}catch(t){return"[UnexpectedJSONParseError]: "+t.message}}});var _s=Gt((zh,Fs)=>{"use strict";function Ds(r,t){for(let e in t)Object.defineProperty(r,e,{value:t[e],enumerable:!0,configurable:!0});return r}function xa(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 Ds(r,e)}catch{e.message=r.message,e.stack=r.stack;let s=function(){};return s.prototype=Object.create(Object.getPrototypeOf(r)),Ds(new s,e)}}Fs.exports=xa});var si=Gt(de=>{(function(){var r,t,e,n,s,i,o,a;a=function(c){var l,h,u,f;return l=(c&255<<24)>>>24,h=(c&255<<16)>>>16,u=(c&65280)>>>8,f=c&255,[l,h,u,f].join(".")},o=function(c){var l,h,u,f,g,p;for(l=[],u=f=0;f<=3&&c.length!==0;u=++f){if(u>0){if(c[0]!==".")throw new Error("Invalid IP");c=c.substring(1)}p=t(c),g=p[0],h=p[1],c=c.substring(h),l.push(g)}if(c.length!==0)throw new Error("Invalid IP");switch(l.length){case 1:if(l[0]>4294967295)throw new Error("Invalid IP");return l[0]>>>0;case 2:if(l[0]>255||l[1]>16777215)throw new Error("Invalid IP");return(l[0]<<24|l[1])>>>0;case 3:if(l[0]>255||l[1]>255||l[2]>65535)throw new Error("Invalid IP");return(l[0]<<24|l[1]<<16|l[2])>>>0;case 4:if(l[0]>255||l[1]>255||l[2]>255||l[3]>255)throw new Error("Invalid IP");return(l[0]<<24|l[1]<<16|l[2]<<8|l[3])>>>0;default:throw new Error("Invalid IP")}},e=function(c){return c.charCodeAt(0)},n=e("0"),i=e("a"),s=e("A"),t=function(c){var l,h,u,f,g;for(f=0,l=10,h="9",u=0,c.length>1&&c[u]==="0"&&(c[u+1]==="x"||c[u+1]==="X"?(u+=2,l=16):"0"<=c[u+1]&&c[u+1]<="9"&&(u++,l=8,h="7")),g=u;u<c.length;){if("0"<=c[u]&&c[u]<=h)f=f*l+(e(c[u])-n)>>>0;else if(l===16)if("a"<=c[u]&&c[u]<="f")f=f*l+(10+e(c[u])-i)>>>0;else if("A"<=c[u]&&c[u]<="F")f=f*l+(10+e(c[u])-s)>>>0;else break;else break;if(f>4294967295)throw new Error("too large");u++}if(u===g)throw new Error("empty octet");return[f,u]},r=function(){function c(l,h){var u,f,g,p;if(typeof l!="string")throw new Error("Missing `net' parameter");if(h||(p=l.split("/",2),l=p[0],h=p[1]),h||(h=32),typeof h=="string"&&h.indexOf(".")>-1){try{this.maskLong=o(h)}catch(w){throw u=w,new Error("Invalid mask: "+h)}for(f=g=32;g>=0;f=--g)if(this.maskLong===4294967295<<32-f>>>0){this.bitmask=f;break}}else if(h||h===0)this.bitmask=parseInt(h,10),this.maskLong=0,this.bitmask>0&&(this.maskLong=4294967295<<32-this.bitmask>>>0);else throw new Error("Invalid mask: empty");try{this.netLong=(o(l)&this.maskLong)>>>0}catch(w){throw u=w,new Error("Invalid net address: "+l)}if(!(this.bitmask<=32))throw new Error("Invalid mask for ip4: "+h);this.size=Math.pow(2,32-this.bitmask),this.base=a(this.netLong),this.mask=a(this.maskLong),this.hostmask=a(~this.maskLong),this.first=this.bitmask<=30?a(this.netLong+1):this.base,this.last=this.bitmask<=30?a(this.netLong+this.size-2):a(this.netLong+this.size-1),this.broadcast=this.bitmask<=30?a(this.netLong+this.size-1):void 0}return c.prototype.contains=function(l){return typeof l=="string"&&(l.indexOf("/")>0||l.split(".").length!==4)&&(l=new c(l)),l instanceof c?this.contains(l.base)&&this.contains(l.broadcast||l.last):(o(l)&this.maskLong)>>>0===(this.netLong&this.maskLong)>>>0},c.prototype.next=function(l){return l==null&&(l=1),new c(a(this.netLong+this.size*l),this.mask)},c.prototype.forEach=function(l){var h,u,f;for(f=o(this.first),u=o(this.last),h=0;f<=u;)l(a(f),f,h),h++,f++},c.prototype.toString=function(){return this.base+"/"+this.bitmask},c}(),de.ip2long=o,de.long2ip=a,de.Netmask=r}).call(de)});var hc={};V(hc,{bitswap:()=>ni,trustlessGateway:()=>fi});var Ln=Symbol.for("@libp2p/peer-id");var et=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"},B=class extends Error{code;props;constructor(t,e,n){super(t),this.code=e,this.name=n?.name??"CodeError",this.props=n??{}}};var rt=(r,...t)=>{try{[...t]}catch{}};var Ct=class extends EventTarget{#t=new Map;constructor(){super(),rt(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:i})=>i!==e),this.#t.set(t,s))}dispatchEvent(t){let e=super.dispatchEvent(t),n=this.#t.get(t.type);return n==null||(n=n.filter(({once:s})=>!s),this.#t.set(t.type,n)),e}safeDispatchEvent(t,e={}){return this.dispatchEvent(new yi(t,e))}},lr=class extends Event{detail;constructor(t,e){super(t,e),this.detail=e?.detail}},yi=globalThis.CustomEvent??lr;function ge(r){let t=new globalThis.AbortController;function e(){t.abort();for(let i of r)i?.removeEventListener!=null&&i.removeEventListener("abort",e)}for(let i of r){if(i?.aborted===!0){e();break}i?.addEventListener!=null&&i.addEventListener("abort",e)}function n(){for(let i of r)i?.removeEventListener!=null&&i.removeEventListener("abort",e)}let s=t.signal;return s.clear=n,s}function _(){let r={};return r.promise=new Promise((t,e)=>{r.resolve=t,r.reject=e}),r}var we=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}},Tt=class{size;hwm;head;tail;constructor(t={}){this.hwm=t.splitLimit??16,this.head=new we(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 we(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 ur=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 xi(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 xi(r,t){t=t??{};let e=t.onEnd,n=new Tt,s,i,o,a=_(),c=async()=>{try{return n.isEmpty()?o?{done:!0}:await new Promise((d,E)=>{i=L=>{i=null,n.push(L);try{d(r(n))}catch(C){E(C)}return s}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=_()})}},l=d=>i!=null?i(d):(n.push(d),s),h=d=>(n=new Tt,i!=null?i({error:d}):(n.push({error:d}),s)),u=d=>{if(o)return s;if(t?.objectMode!==!0&&d?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return l({done:!1,value:d})},f=d=>o?s:(o=!0,d!=null?h(d):l({done:!0})),g=()=>(n=new Tt,f(),{done:!0}),p=d=>(f(d),{done:!0});if(s={[Symbol.asyncIterator](){return this},next:c,return:g,throw:p,push:u,end:f,get readableLength(){return n.size},onEmpty:async d=>{let E=d?.signal;if(E?.throwIfAborted(),n.isEmpty())return;let L,C;E!=null&&(L=new Promise((F,$)=>{C=()=>{$(new ur)},E.addEventListener("abort",C)}));try{await Promise.race([a.promise,L])}finally{C!=null&&E!=null&&E?.removeEventListener("abort",C)}}},e==null)return s;let w=s;return s={[Symbol.asyncIterator](){return this},next(){return w.next()},throw(d){return w.throw(d),e!=null&&(e(d),e=void 0),{done:!0}},return(){return w.return(),e!=null&&(e(),e=void 0),{done:!0}},push:u,end(d){return w.end(d),e!=null&&(e(d),e=void 0),s},get readableLength(){return w.readableLength},onEmpty:d=>w.onEmpty(d)},s}var hr=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 Ft(r,t,e,n){let s=new hr(n?.errorMessage,n?.errorCode);return e?.aborted===!0?Promise.reject(s):new Promise((i,o)=>{let a=l=>{try{if(n?.filter?.(l)===!1)return}catch(h){r.removeEventListener(t,a),e?.removeEventListener("abort",c),o(h);return}r.removeEventListener(t,a),e?.removeEventListener("abort",c),i(l)},c=()=>{r.removeEventListener(t,a),e?.removeEventListener("abort",c),o(s)};r.addEventListener(t,a),e?.addEventListener("abort",c)})}var be=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 ye(r,t,e){if(t==null)return r;if(t.aborted)return Promise.reject(new be(e?.errorMessage,e?.errorCode));let n,s=new be(e?.errorMessage,e?.errorCode);try{return await Promise.race([r,new Promise((i,o)=>{n=()=>{o(s)},t.addEventListener("abort",n)})])}finally{n!=null&&t.removeEventListener("abort",n)}}var xe=class{deferred;signal;where;constructor(t,e){this.signal=e,this.deferred=_(),this.where=t,this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(new et)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function Ei(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var Ee=class{id;fn;options;priority;recipients;status;timeline;controller;constructor(t,e,n=0){this.id=Ei(),this.status="queued",this.fn=t,this.priority=n,this.options=e,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,rt(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 et)}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 ye(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.signal?.removeEventListener("abort",this.onAbort)})}};function vi(r,t,e){let n=0,s=r.length;for(;s>0;){let i=Math.trunc(s/2),o=n+i;e(r[o],t)<=0?(n=++o,s-=i+1):s=i}return n}var ve=class extends Ct{concurrency;queue;pending;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.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){if(this.queue[this.size-1]?.priority>=t.priority){this.queue.push(t);return}let e=vi(this.queue,t,(n,s)=>s.priority-n.priority);this.queue.splice(e,0,t)}async add(t,e){e?.signal?.throwIfAborted();let n=new Ee(t,e,e?.priority),s=n.join(e).then(i=>(this.safeDispatchEvent("completed",{detail:i}),i)).catch(i=>{throw this.safeDispatchEvent("error",{detail:i}),i});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 et)}),this.clear()}async onEmpty(t){this.size!==0&&await Ft(this,"empty",t?.signal)}async onSizeLessThan(t,e){this.size<t||await Ft(this,"next",e?.signal,{filter:()=>this.size<t})}async onIdle(t){this.pending===0&&this.size===0||await Ft(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=c=>{c!=null?this.abort():this.clear(),e.end(c)},s=c=>{c.detail!=null&&e.push(c.detail)},i=c=>{n(c.detail)},o=()=>{n()},a=()=>{n(new B("Queue aborted","ERR_QUEUE_ABORTED"))};this.addEventListener("completed",s),this.addEventListener("error",i),this.addEventListener("idle",o),t?.signal?.addEventListener("abort",a);try{yield*e}finally{this.removeEventListener("completed",s),this.removeEventListener("error",i),this.removeEventListener("idle",o),t?.signal?.removeEventListener("abort",a),n()}}};var at=class extends ve{has(t){return this.find(t)!=null}find(t){return this.queue.find(e=>t.equals(e.options.peerId))}};var Se=class{index=0;input="";new(t){return this.index=0,this.input=t,this}readAtomically(t){let e=this.index,n=t();return n===void 0&&(this.index=e),n}parseWith(t){let e=t();if(this.index===this.input.length)return e}peekChar(){if(!(this.index>=this.input.length))return this.input[this.index]}readChar(){if(!(this.index>=this.input.length))return this.input[this.index++]}readGivenChar(t){return this.readAtomically(()=>{let e=this.readChar();if(e===t)return e})}readSeparator(t,e,n){return this.readAtomically(()=>{if(!(e>0&&this.readGivenChar(t)===void 0))return n()})}readNumber(t,e,n,s){return this.readAtomically(()=>{let i=0,o=0,a=this.peekChar();if(a===void 0)return;let c=a==="0",l=2**(8*s)-1;for(;;){let h=this.readAtomically(()=>{let u=this.readChar();if(u===void 0)return;let f=Number.parseInt(u,t);if(!Number.isNaN(f))return f});if(h===void 0)break;if(i*=t,i+=h,i>l||(o+=1,e!==void 0&&o>e))return}if(o!==0)return!n&&c&&o>1?void 0:i})}readIPv4Addr(){return this.readAtomically(()=>{let t=new Uint8Array(4);for(let e=0;e<t.length;e++){let n=this.readSeparator(".",e,()=>this.readNumber(10,3,!1,1));if(n===void 0)return;t[e]=n}return t})}readIPv6Addr(){let t=e=>{for(let n=0;n<e.length/2;n++){let s=n*2;if(n<e.length-3){let o=this.readSeparator(":",n,()=>this.readIPv4Addr());if(o!==void 0)return e[s]=o[0],e[s+1]=o[1],e[s+2]=o[2],e[s+3]=o[3],[s+4,!0]}let i=this.readSeparator(":",n,()=>this.readNumber(16,4,!0,2));if(i===void 0)return[s,!1];e[s]=i>>8,e[s+1]=i&255}return[e.length,!1]};return this.readAtomically(()=>{let e=new Uint8Array(16),[n,s]=t(e);if(n===16)return e;if(s||this.readGivenChar(":")===void 0||this.readGivenChar(":")===void 0)return;let i=new Uint8Array(14),o=16-(n+2),[a]=t(i.subarray(0,o));return e.set(i.subarray(0,a),16-a),e})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};var Cn=45,Si=15,_t=new Se;function fr(r){if(!(r.length>Si))return _t.new(r).parseWith(()=>_t.readIPv4Addr())}function dr(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>Cn))return _t.new(r).parseWith(()=>_t.readIPv6Addr())}function Ae(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>Cn))return _t.new(r).parseWith(()=>_t.readIPAddr())}function Pt(r){return!!fr(r)}function Rt(r){return!!dr(r)}function ke(r){return!!Ae(r)}var br={};V(br,{base58btc:()=>T,base58flickr:()=>Ti});var qc=new Uint8Array(0);function Tn(r,t){if(r===t)return!0;if(r.byteLength!==t.byteLength)return!1;for(let e=0;e<r.byteLength;e++)if(r[e]!==t[e])return!1;return!0}function st(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength);throw new Error("Unknown type, must be binary type")}function Dn(r){return new TextEncoder().encode(r)}function Fn(r){return new TextDecoder().decode(r)}function Ai(r,t){if(r.length>=255)throw new TypeError("Alphabet too long");for(var e=new Uint8Array(256),n=0;n<e.length;n++)e[n]=255;for(var s=0;s<r.length;s++){var i=r.charAt(s),o=i.charCodeAt(0);if(e[o]!==255)throw new TypeError(i+" is ambiguous");e[o]=s}var a=r.length,c=r.charAt(0),l=Math.log(a)/Math.log(256),h=Math.log(256)/Math.log(a);function u(p){if(p instanceof Uint8Array||(ArrayBuffer.isView(p)?p=new Uint8Array(p.buffer,p.byteOffset,p.byteLength):Array.isArray(p)&&(p=Uint8Array.from(p))),!(p instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(p.length===0)return"";for(var w=0,d=0,E=0,L=p.length;E!==L&&p[E]===0;)E++,w++;for(var C=(L-E)*h+1>>>0,F=new Uint8Array(C);E!==L;){for(var $=p[E],X=0,z=C-1;($!==0||X<d)&&z!==-1;z--,X++)$+=256*F[z]>>>0,F[z]=$%a>>>0,$=$/a>>>0;if($!==0)throw new Error("Non-zero carry");d=X,E++}for(var J=C-d;J!==C&&F[J]===0;)J++;for(var Lt=c.repeat(w);J<C;++J)Lt+=r.charAt(F[J]);return Lt}function f(p){if(typeof p!="string")throw new TypeError("Expected String");if(p.length===0)return new Uint8Array;var w=0;if(p[w]!==" "){for(var d=0,E=0;p[w]===c;)d++,w++;for(var L=(p.length-w)*l+1>>>0,C=new Uint8Array(L);p[w];){var F=e[p.charCodeAt(w)];if(F===255)return;for(var $=0,X=L-1;(F!==0||$<E)&&X!==-1;X--,$++)F+=a*C[X]>>>0,C[X]=F%256>>>0,F=F/256>>>0;if(F!==0)throw new Error("Non-zero carry");E=$,w++}if(p[w]!==" "){for(var z=L-E;z!==L&&C[z]===0;)z++;for(var J=new Uint8Array(d+(L-z)),Lt=d;z!==L;)J[Lt++]=C[z++];return J}}}function g(p){var w=f(p);if(w)return w;throw new Error(`Non-${t} character`)}return{encode:u,decodeUnsafe:f,decode:g}}var ki=Ai,Ii=ki,Pn=Ii;var pr=class{name;prefix;baseEncode;constructor(t,e,n){this.name=t,this.prefix=e,this.baseEncode=n}encode(t){if(t instanceof Uint8Array)return`${this.prefix}${this.baseEncode(t)}`;throw Error("Unknown type, must be binary type")}},mr=class{name;prefix;baseDecode;prefixCodePoint;constructor(t,e,n){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 Rn(this,t)}},gr=class{decoders;constructor(t){this.decoders=t}or(t){return Rn(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 Rn(r,t){return new gr({...r.decoders??{[r.prefix]:r},...t.decoders??{[t.prefix]:t}})}var wr=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 pr(t,e,n),this.decoder=new mr(t,e,s)}encode(t){return this.encoder.encode(t)}decode(t){return this.decoder.decode(t)}};function Nt({name:r,prefix:t,encode:e,decode:n}){return new wr(r,t,e,n)}function ct({name:r,prefix:t,alphabet:e}){let{encode:n,decode:s}=Pn(e,r);return Nt({prefix:t,name:r,encode:n,decode:i=>st(s(i))})}function Li(r,t,e,n){let s={};for(let h=0;h<t.length;++h)s[t[h]]=h;let i=r.length;for(;r[i-1]==="=";)--i;let o=new Uint8Array(i*e/8|0),a=0,c=0,l=0;for(let h=0;h<i;++h){let u=s[r[h]];if(u===void 0)throw new SyntaxError(`Non-${n} character`);c=c<<e|u,a+=e,a>=8&&(a-=8,o[l++]=255&c>>a)}if(a>=e||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return o}function Ci(r,t,e){let n=t[t.length-1]==="=",s=(1<<e)-1,i="",o=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],o+=8;o>e;)o-=e,i+=t[s&a>>o];if(o!==0&&(i+=t[s&a<<e-o]),n)for(;i.length*e&7;)i+="=";return i}function A({name:r,prefix:t,bitsPerChar:e,alphabet:n}){return Nt({prefix:t,name:r,encode(s){return Ci(s,n,e)},decode(s){return Li(s,n,e,r)}})}var T=ct({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Ti=ct({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var yr={};V(yr,{base32:()=>it,base32hex:()=>Pi,base32hexpad:()=>Ni,base32hexpadupper:()=>Ui,base32hexupper:()=>Ri,base32pad:()=>Fi,base32padupper:()=>_i,base32upper:()=>Di,base32z:()=>Mi});var it=A({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Di=A({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Fi=A({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),_i=A({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Pi=A({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Ri=A({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Ni=A({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Ui=A({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Mi=A({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Bi=Mn,Nn=128,Oi=127,$i=~Oi,zi=Math.pow(2,31);function Mn(r,t,e){t=t||[],e=e||0;for(var n=e;r>=zi;)t[e++]=r&255|Nn,r/=128;for(;r&$i;)t[e++]=r&255|Nn,r>>>=7;return t[e]=r|0,Mn.bytes=e-n+1,t}var Vi=xr,Hi=128,Un=127;function xr(r,n){var e=0,n=n||0,s=0,i=n,o,a=r.length;do{if(i>=a)throw xr.bytes=0,new RangeError("Could not decode varint");o=r[i++],e+=s<28?(o&Un)<<s:(o&Un)*Math.pow(2,s),s+=7}while(o>=Hi);return xr.bytes=i-n,e}var Wi=Math.pow(2,7),qi=Math.pow(2,14),Gi=Math.pow(2,21),ji=Math.pow(2,28),Qi=Math.pow(2,35),Xi=Math.pow(2,42),Ji=Math.pow(2,49),Ki=Math.pow(2,56),Yi=Math.pow(2,63),Zi=function(r){return r<Wi?1:r<qi?2:r<Gi?3:r<ji?4:r<Qi?5:r<Xi?6:r<Ji?7:r<Ki?8:r<Yi?9:10},to={encode:Bi,decode:Vi,encodingLength:Zi},eo=to,jt=eo;function Qt(r,t=0){return[jt.decode(r,t),jt.decode.bytes]}function Ut(r,t,e=0){return jt.encode(r,t,e),t}function Mt(r){return jt.encodingLength(r)}function lt(r,t){let e=t.byteLength,n=Mt(r),s=n+Mt(e),i=new Uint8Array(s+e);return Ut(r,i,0),Ut(e,i,n),i.set(t,s),new Bt(r,e,t,i)}function dt(r){let t=st(r),[e,n]=Qt(t),[s,i]=Qt(t.subarray(n)),o=t.subarray(n+i);if(o.byteLength!==s)throw new Error("Incorrect length");return new Bt(e,s,o,t)}function Bn(r,t){if(r===t)return!0;{let e=t;return r.code===e.code&&r.size===e.size&&e.bytes instanceof Uint8Array&&Tn(r.bytes,e.bytes)}}var Bt=class{code;size;digest;bytes;constructor(t,e,n,s){this.code=t,this.size=e,this.digest=n,this.bytes=s}};function On(r,t){let{bytes:e,version:n}=r;switch(n){case 0:return no(e,Er(r),t??T.encoder);default:return so(e,Er(r),t??it.encoder)}}var $n=new WeakMap;function Er(r){let t=$n.get(r);if(t==null){let e=new Map;return $n.set(r,e),e}return t}var D=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!==Xt)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(e.code!==io)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=lt(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&&Bn(t.multihash,n.multihash)}toString(t){return On(this,t)}toJSON(){return{"/":On(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(t){if(t==null)return null;let e=t;if(e instanceof r)return e;if(e["/"]!=null&&e["/"]===e.bytes||e.asCID===e){let{version:n,code:s,multihash:i,bytes:o}=e;return new r(n,s,i,o??zn(n,s,i.bytes))}else if(e[oo]===!0){let{version:n,multihash:s,code:i}=e,o=dt(s);return r.create(n,i,o)}else return null}static create(t,e,n){if(typeof e!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(t){case 0:{if(e!==Xt)throw new Error(`Version 0 CID must use dag-pb (code: ${Xt}) block encoding`);return new r(t,e,n,n.bytes)}case 1:{let s=zn(t,e,n.bytes);return new r(t,e,n,s)}default:throw new Error("Invalid version")}}static createV0(t){return r.create(0,Xt,t)}static createV1(t,e){return r.create(1,t,e)}static decode(t){let[e,n]=r.decodeFirst(t);if(n.length!==0)throw new Error("Incorrect length");return e}static decodeFirst(t){let e=r.inspectBytes(t),n=e.size-e.multihashSize,s=st(t.subarray(n,n+e.multihashSize));if(s.byteLength!==e.multihashSize)throw new Error("Incorrect length");let i=s.subarray(e.multihashSize-e.digestSize),o=new Bt(e.multihashCode,e.digestSize,i,s);return[e.version===0?r.createV0(o):r.createV1(e.codec,o),t.subarray(e.size)]}static inspectBytes(t){let e=0,n=()=>{let[u,f]=Qt(t.subarray(e));return e+=f,u},s=n(),i=Xt;if(s===18?(s=0,e=0):i=n(),s!==0&&s!==1)throw new RangeError(`Invalid CID version ${s}`);let o=e,a=n(),c=n(),l=e+c,h=l-o;return{version:s,codec:i,multihashCode:a,digestSize:c,multihashSize:h,size:l}}static parse(t,e){let[n,s]=ro(t,e),i=r.decode(s);if(i.version===0&&t[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return Er(i).set(n,t),i}};function ro(r,t){switch(r[0]){case"Q":{let e=t??T;return[T.prefix,e.decode(`${T.prefix}${r}`)]}case T.prefix:{let e=t??T;return[T.prefix,e.decode(r)]}case it.prefix:{let e=t??it;return[it.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 no(r,t,e){let{prefix:n}=e;if(n!==T.prefix)throw Error(`Cannot string encode V0 in ${e.name} encoding`);let s=t.get(n);if(s==null){let i=e.encode(r).slice(1);return t.set(n,i),i}else return s}function so(r,t,e){let{prefix:n}=e,s=t.get(n);if(s==null){let i=e.encode(r);return t.set(n,i),i}else return s}var Xt=112,io=18;function zn(r,t,e){let n=Mt(r),s=n+Mt(t),i=new Uint8Array(s+e.byteLength);return Ut(r,i,0),Ut(t,i,n),i.set(e,s),i}var oo=Symbol.for("@ipld/js-cid/CID");function mt(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 vr={};V(vr,{base10:()=>ao});var ao=ct({prefix:"9",name:"base10",alphabet:"0123456789"});var Sr={};V(Sr,{base16:()=>co,base16upper:()=>lo});var co=A({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),lo=A({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var Ar={};V(Ar,{base2:()=>uo});var uo=A({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var kr={};V(kr,{base256emoji:()=>go});var Vn=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}"),ho=Vn.reduce((r,t,e)=>(r[e]=t,r),[]),fo=Vn.reduce((r,t,e)=>(r[t.codePointAt(0)]=e,r),[]);function po(r){return r.reduce((t,e)=>(t+=ho[e],t),"")}function mo(r){let t=[];for(let e of r){let n=fo[e.codePointAt(0)];if(n===void 0)throw new Error(`Non-base256emoji character: ${e}`);t.push(n)}return new Uint8Array(t)}var go=Nt({prefix:"\u{1F680}",name:"base256emoji",encode:po,decode:mo});var Ir={};V(Ir,{base36:()=>wo,base36upper:()=>bo});var wo=ct({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),bo=ct({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var Cr={};V(Cr,{base64:()=>ut,base64pad:()=>yo,base64url:()=>Lr,base64urlpad:()=>xo});var ut=A({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),yo=A({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Lr=A({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),xo=A({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var Tr={};V(Tr,{base8:()=>Eo});var Eo=A({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var Dr={};V(Dr,{identity:()=>vo});var vo=Nt({prefix:"\0",name:"identity",encode:r=>Fn(r),decode:r=>Dn(r)});var gl=new TextEncoder,wl=new TextDecoder;var Fr={};V(Fr,{identity:()=>Le});var Hn=0,ko="identity",Wn=st;function Io(r){return lt(Hn,Wn(r))}var Le={code:Hn,name:ko,encode:Wn,digest:Io};var Rr={};V(Rr,{sha256:()=>gt,sha512:()=>Lo});function Pr({name:r,code:t,encode:e}){return new _r(r,t,e)}var _r=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?lt(this.code,e):e.then(n=>lt(this.code,n))}else throw Error("Unknown type, must be binary type")}};function Gn(r){return async t=>new Uint8Array(await crypto.subtle.digest(r,t))}var gt=Pr({name:"sha2-256",code:18,encode:Gn("SHA-256")}),Lo=Pr({name:"sha2-512",code:19,encode:Gn("SHA-512")});var ht={...Dr,...Ar,...Tr,...vr,...Sr,...yr,...Ir,...br,...Cr,...kr},Dl={...Rr,...Fr};function O(r=0){return new Uint8Array(r)}function R(r=0){return new Uint8Array(r)}function Qn(r,t,e,n){return{name:r,prefix:t,encoder:{name:r,prefix:t,encode:e},decoder:{decode:n}}}var jn=Qn("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),Nr=Qn("ascii","a",r=>{let t="a";for(let e=0;e<r.length;e++)t+=String.fromCharCode(r[e]);return t},r=>{r=r.substring(1);let t=R(r.length);for(let e=0;e<r.length;e++)t[e]=r.charCodeAt(e);return t}),Co={utf8:jn,"utf-8":jn,hex:ht.base16,latin1:Nr,ascii:Nr,binary:Nr,...ht},Ce=Co;function v(r,t="utf8"){let e=Ce[t];if(e==null)throw new Error(`Unsupported encoding "${t}"`);return e.encoder.encode(r).substring(1)}var To=Math.pow(2,7),Do=Math.pow(2,14),Fo=Math.pow(2,21),Ur=Math.pow(2,28),Mr=Math.pow(2,35),Br=Math.pow(2,42),Or=Math.pow(2,49),y=128,N=127;function S(r){if(r<To)return 1;if(r<Do)return 2;if(r<Fo)return 3;if(r<Ur)return 4;if(r<Mr)return 5;if(r<Br)return 6;if(r<Or)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function $r(r,t,e=0){switch(S(r)){case 8:t[e++]=r&255|y,r/=128;case 7:t[e++]=r&255|y,r/=128;case 6:t[e++]=r&255|y,r/=128;case 5:t[e++]=r&255|y,r/=128;case 4:t[e++]=r&255|y,r>>>=7;case 3:t[e++]=r&255|y,r>>>=7;case 2:t[e++]=r&255|y,r>>>=7;case 1:{t[e++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return t}function _o(r,t,e=0){switch(S(r)){case 8:t.set(e++,r&255|y),r/=128;case 7:t.set(e++,r&255|y),r/=128;case 6:t.set(e++,r&255|y),r/=128;case 5:t.set(e++,r&255|y),r/=128;case 4:t.set(e++,r&255|y),r>>>=7;case 3:t.set(e++,r&255|y),r>>>=7;case 2:t.set(e++,r&255|y),r>>>=7;case 1:{t.set(e++,r&255),r>>>=7;break}default:throw new Error("unreachable")}return t}function zr(r,t){let e=r[t],n=0;if(n+=e&N,e<y||(e=r[t+1],n+=(e&N)<<7,e<y)||(e=r[t+2],n+=(e&N)<<14,e<y)||(e=r[t+3],n+=(e&N)<<21,e<y)||(e=r[t+4],n+=(e&N)*Ur,e<y)||(e=r[t+5],n+=(e&N)*Mr,e<y)||(e=r[t+6],n+=(e&N)*Br,e<y)||(e=r[t+7],n+=(e&N)*Or,e<y))return n;throw new RangeError("Could not decode varint")}function Po(r,t){let e=r.get(t),n=0;if(n+=e&N,e<y||(e=r.get(t+1),n+=(e&N)<<7,e<y)||(e=r.get(t+2),n+=(e&N)<<14,e<y)||(e=r.get(t+3),n+=(e&N)<<21,e<y)||(e=r.get(t+4),n+=(e&N)*Ur,e<y)||(e=r.get(t+5),n+=(e&N)*Mr,e<y)||(e=r.get(t+6),n+=(e&N)*Br,e<y)||(e=r.get(t+7),n+=(e&N)*Or,e<y))return n;throw new RangeError("Could not decode varint")}function K(r,t,e=0){return t==null&&(t=R(S(r))),t instanceof Uint8Array?$r(r,t,e):_o(r,t,e)}function H(r,t=0){return r instanceof Uint8Array?zr(r,t):Po(r,t)}function Y(r,t){t==null&&(t=r.reduce((s,i)=>s+i.length,0));let e=R(t),n=0;for(let s of r)e.set(s,n),n+=s.length;return e}var Jl=parseInt("0xFFFF",16),Kl=new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);function Kt(r,t="utf8"){let e=Ce[t];if(e==null)throw new Error(`Unsupported encoding "${t}"`);return e.decoder.decode(`${e.prefix}${r}`)}var Kn=Pt,Bo=Rt,Vr=function(r){let t=0;if(r=r.toString().trim(),Kn(r)){let e=new Uint8Array(t+4);return r.split(/\./g).forEach(n=>{e[t++]=parseInt(n,10)&255}),e}if(Bo(r)){let e=r.split(":",8),n;for(n=0;n<e.length;n++){let i=Kn(e[n]),o;i&&(o=Vr(e[n]),e[n]=v(o.slice(0,2),"base16")),o!=null&&++n<8&&e.splice(n,0,v(o.slice(2,4),"base16"))}if(e[0]==="")for(;e.length<8;)e.unshift("0");else if(e[e.length-1]==="")for(;e.length<8;)e.push("0");else if(e.length<8){for(n=0;n<e.length&&e[n]!=="";n++);let i=[n,1];for(n=9-e.length;n>0;n--)i.push("0");e.splice.apply(e,i)}let s=new Uint8Array(t+16);for(n=0;n<e.length;n++){let i=parseInt(e[n],16);s[t++]=i>>8&255,s[t++]=i&255}return s}throw new Error("invalid ip address")},Yn=function(r,t=0,e){t=~~t,e=e??r.length-t;let n=new DataView(r.buffer);if(e===4){let s=[];for(let i=0;i<e;i++)s.push(r[t+i]);return s.join(".")}if(e===16){let s=[];for(let i=0;i<e;i+=2)s.push(n.getUint16(t+i).toString(16));return s.join(":").replace(/(^|:)0(:0)*:0(:|$)/,"$1::$3").replace(/:{3,4}/,"::")}return""};var Ot={},Hr={},$o=[[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"]];$o.forEach(r=>{let t=zo(...r);Hr[t.code]=t,Ot[t.name]=t});function zo(r,t,e,n,s){return{code:r,size:t,name:e,resolvable:!!n,path:!!s}}function m(r){if(typeof r=="number"){if(Hr[r]!=null)return Hr[r];throw new Error(`no protocol with code: ${r}`)}else if(typeof r=="string"){if(Ot[r]!=null)return Ot[r];throw new Error(`no protocol with name: ${r}`)}throw new Error(`invalid protocol id type: ${typeof r}`)}var Ru=m("ip4"),Nu=m("ip6"),Uu=m("ipcidr");function qr(r,t){switch(m(r).code){case 4:case 41:return Ho(t);case 42:return es(t);case 6:case 273:case 33:case 132:return ns(t).toString();case 53:case 54:case 55:case 56:case 400:case 449:case 777:return es(t);case 421:return jo(t);case 444:return rs(t);case 445:return rs(t);case 466:return Go(t);default:return v(t,"base16")}}function Gr(r,t){switch(m(r).code){case 4:return Zn(t);case 41:return Zn(t);case 42:return ts(t);case 6:case 273:case 33:case 132:return jr(parseInt(t,10));case 53:case 54:case 55:case 56:case 400:case 449:case 777:return ts(t);case 421:return Wo(t);case 444:return Qo(t);case 445:return Xo(t);case 466:return qo(t);default:return Kt(t,"base16")}}var Wr=Object.values(ht).map(r=>r.decoder),Vo=function(){let r=Wr[0].or(Wr[1]);return Wr.slice(2).forEach(t=>r=r.or(t)),r}();function Zn(r){if(!ke(r))throw new Error("invalid ip address");return Vr(r)}function Ho(r){let t=Yn(r,0,r.length);if(t==null)throw new Error("ipBuff is required");if(!ke(t))throw new Error("invalid ip address");return t}function jr(r){let t=new ArrayBuffer(2);return new DataView(t).setUint16(0,r),new Uint8Array(t)}function ns(r){return new DataView(r.buffer).getUint16(r.byteOffset)}function ts(r){let t=Kt(r),e=Uint8Array.from(K(t.length));return Y([e,t],e.length+t.length)}function es(r){let t=H(r);if(r=r.slice(S(t)),r.length!==t)throw new Error("inconsistent lengths");return v(r)}function Wo(r){let t;r[0]==="Q"||r[0]==="1"?t=dt(T.decode(`z${r}`)).bytes:t=D.parse(r).multihash.bytes;let e=Uint8Array.from(K(t.length));return Y([e,t],e.length+t.length)}function qo(r){let t=Vo.decode(r),e=Uint8Array.from(K(t.length));return Y([e,t],e.length+t.length)}function Go(r){let t=H(r),e=r.slice(S(t));if(e.length!==t)throw new Error("inconsistent lengths");return"u"+v(e,"base64url")}function jo(r){let t=H(r),e=r.slice(S(t));if(e.length!==t)throw new Error("inconsistent lengths");return v(e,"base58btc")}function Qo(r){let t=r.split(":");if(t.length!==2)throw new Error(`failed to parse onion addr: ["'${t.join('", "')}'"]' does not contain a port number`);if(t[0].length!==16)throw new Error(`failed to parse onion addr: ${t[0]} not a Tor onion address.`);let e=it.decode("b"+t[0]),n=parseInt(t[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let s=jr(n);return Y([e,s],e.length+s.length)}function Xo(r){let t=r.split(":");if(t.length!==2)throw new Error(`failed to parse onion addr: ["'${t.join('", "')}'"]' does not contain a port number`);if(t[0].length!==56)throw new Error(`failed to parse onion addr: ${t[0]} not a Tor onion3 address.`);let e=it.decode(`b${t[0]}`),n=parseInt(t[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let s=jr(n);return Y([e,s],e.length+s.length)}function rs(r){let t=r.slice(0,r.length-2),e=r.slice(r.length-2),n=v(t,"base32"),s=ns(e);return`${n}:${s}`}function ss(r){r=Qr(r);let t=[],e=[],n=null,s=r.split("/").slice(1);if(s.length===1&&s[0]==="")return{bytes:new Uint8Array,string:"/",tuples:[],stringTuples:[],path:null};for(let i=0;i<s.length;i++){let o=s[i],a=m(o);if(a.size===0){t.push([a.code]),e.push([a.code]);continue}if(i++,i>=s.length)throw os("invalid address: "+r);if(a.path===!0){n=Qr(s.slice(i).join("/")),t.push([a.code,Gr(a.code,n)]),e.push([a.code,n]);break}let c=Gr(a.code,s[i]);t.push([a.code,c]),e.push([a.code,qr(a.code,c)])}return{string:is(e),bytes:Jr(t),tuples:t,stringTuples:e,path:n}}function Xr(r){let t=[],e=[],n=null,s=0;for(;s<r.length;){let i=H(r,s),o=S(i),a=m(i),c=Jo(a,r.slice(s+o));if(c===0){t.push([i]),e.push([i]),s+=o;continue}let l=r.slice(s+o,s+o+c);if(s+=c+o,s>r.length)throw os("Invalid address Uint8Array: "+v(r,"base16"));t.push([i,l]);let h=qr(i,l);if(e.push([i,h]),a.path===!0){n=h;break}}return{bytes:Uint8Array.from(r),string:is(e),tuples:t,stringTuples:e,path:n}}function is(r){let t=[];return r.map(e=>{let n=m(e[0]);return t.push(n.name),e.length>1&&e[1]!=null&&t.push(e[1]),null}),Qr(t.join("/"))}function Jr(r){return Y(r.map(t=>{let e=m(t[0]),n=Uint8Array.from(K(e.code));return t.length>1&&t[1]!=null&&(n=Y([n,t[1]])),n}))}function Jo(r,t){if(r.size>0)return r.size/8;if(r.size===0)return 0;{let e=H(t instanceof Uint8Array?t:Uint8Array.from(t));return e+S(e)}}function Qr(r){return"/"+r.trim().split("/").filter(t=>t).join("/")}function os(r){return new Error("Error parsing address: "+r)}var Ko=Symbol.for("nodejs.util.inspect.custom"),Kr=Symbol.for("@multiformats/js-multiaddr/multiaddr"),Yo=[m("dns").code,m("dns4").code,m("dns6").code,m("dnsaddr").code],Te=class r{bytes;#t;#e;#r;#n;[Kr]=!0;constructor(t){t==null&&(t="");let e;if(t instanceof Uint8Array)e=Xr(t);else if(typeof t=="string"){if(t.length>0&&t.charAt(0)!=="/")throw new Error(`multiaddr "${t}" must start with a "/"`);e=ss(t)}else if(cs(t))e=Xr(t.bytes);else throw new Error("addr must be a string, Buffer, or another Multiaddr");this.bytes=e.bytes,this.#t=e.string,this.#e=e.tuples,this.#r=e.stringTuples,this.#n=e.path}toString(){return this.#t}toJSON(){return this.toString()}toOptions(){let t,e,n,s,i="",o=m("tcp"),a=m("udp"),c=m("ip4"),l=m("ip6"),h=m("dns6"),u=m("ip6zone");for(let[g,p]of this.stringTuples())g===u.code&&(i=`%${p??""}`),Yo.includes(g)&&(e=o.name,s=443,n=`${p??""}${i}`,t=g===h.code?6:4),(g===o.code||g===a.code)&&(e=m(g).name,s=parseInt(p??"")),(g===c.code||g===l.code)&&(e=m(g).name,n=`${p??""}${i}`,t=g===l.code?6:4);if(t==null||e==null||n==null||s==null)throw new Error('multiaddr must have a valid format: "/{ip4, ip6, dns4, dns6, dnsaddr}/{address}/{tcp, udp}/{port}".');return{family:t,host:n,transport:e,port:s}}protos(){return this.#e.map(([t])=>Object.assign({},m(t)))}protoCodes(){return this.#e.map(([t])=>t)}protoNames(){return this.#e.map(([t])=>m(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(Jr(e.slice(0,n)));return this}getPeerId(){try{let t=[];this.stringTuples().forEach(([n,s])=>{n===Ot.p2p.code&&t.push([n,s]),n===Ot["p2p-circuit"].code&&(t=[])});let e=t.pop();if(e?.[1]!=null){let n=e[1];return n[0]==="Q"||n[0]==="1"?v(T.decode(`z${n}`),"base58btc"):v(D.parse(n).multihash.bytes,"base58btc")}return null}catch{return null}}getPath(){return this.#n}equals(t){return mt(this.bytes,t.bytes)}async resolve(t){let e=this.protos().find(i=>i.resolvable);if(e==null)return[this];let n=as.get(e.name);if(n==null)throw new B(`no available resolver for ${e.name}`,"ERR_NO_AVAILABLE_RESOLVER");return(await n(this,t)).map(i=>Yt(i))}nodeAddress(){let t=this.toOptions();if(t.transport!=="tcp"&&t.transport!=="udp")throw new Error(`multiaddr must have a valid format - no protocol with name: "${t.transport}". Must have a valid transport protocol: "{tcp, udp}"`);return{family:t.family,address:t.host,port:t.port}}isThinWaistAddress(t){let e=(t??this).protos();return!(e.length!==2||e[0].code!==4&&e[0].code!==41||e[1].code!==6&&e[1].code!==273)}[Ko](){return`Multiaddr(${this.#t})`}};var as=new Map;function cs(r){return!!r?.[Kr]}function Yt(r){return new Te(r)}var Zo=r=>r.toString().split("/").slice(1),Zt=r=>({match:t=>t.length<1?!1:r(t[0])?t.slice(1):!1,pattern:"fn"}),b=r=>({match:t=>Zt(e=>e===r).match(t),pattern:r}),_e=()=>({match:r=>Zt(t=>typeof t=="string").match(r),pattern:"{string}"}),Pe=()=>({match:r=>Zt(t=>!isNaN(parseInt(t))).match(r),pattern:"{number}"}),P=()=>({match:r=>{if(r.length<2||r[0]!=="p2p"&&r[0]!=="ipfs")return!1;if(r[1].startsWith("Q")||r[1].startsWith("1"))try{T.decode(`z${r[1]}`)}catch{return!1}else return!1;return r.slice(2)},pattern:"/p2p/{peerid}"}),De=()=>({match:r=>{if(r.length<2||r[0]!=="certhash")return!1;try{Lr.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})`}),W=(...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(", ")})`}),x=(...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 I(...r){function t(s){let i=Zo(s);for(let o of r){let a=o.match(i);if(a===!1)return!1;i=a}return i}function e(s){return t(s)!==!1}function n(s){let i=t(s);return i===!1?!1:i.length===0}return{matches:e,exactMatch:n}}var Zr=x(b("dns4"),_e()),tn=x(b("dns6"),_e()),en=x(b("dnsaddr"),_e()),ls=x(b("dns"),_e()),hh=I(Zr),fh=I(tn),dh=I(en),us=I(W(ls,en,Zr,tn)),hs=x(b("ip4"),Zt(Pt)),fs=x(b("ip6"),Zt(Rt)),ds=W(hs,fs),nt=W(ds,ls,Zr,tn,en),ph=I(nt),mh=I(hs),gh=I(fs),wh=I(ds),Re=x(nt,b("tcp"),Pe()),te=x(nt,b("udp"),Pe()),ta=W(Re,te),bh=I(Re),yh=I(te),rn=x(te,b("quic")),Ne=x(te,b("quic-v1")),ea=W(rn,Ne),xh=I(rn),Eh=I(Ne),Yr=W(nt,Re,te,rn,Ne),ps=W(x(Yr,b("ws"),M(P()))),vh=I(ps),ms=W(x(Yr,b("wss"),M(P())),x(Yr,b("tls"),b("ws"),M(P()))),Sh=I(ms),gs=x(ta,b("webrtc-direct"),De(),M(De()),M(P())),Ah=I(gs),ws=x(Ne,b("webtransport"),De(),De(),M(P())),kh=I(ws),Fe=W(ps,ms,x(Re,M(P())),x(ea,M(P())),x(nt,M(P())),gs,ws,P()),Ih=I(Fe),ra=x(Fe,b("p2p-circuit"),P()),bs=I(ra),na=W(x(Fe,b("p2p-circuit"),b("webrtc"),P()),x(Fe,b("webrtc"),M(P())),b("webrtc")),Lh=I(na),sa=W(x(nt,b("tcp"),Pe(),b("http"),M(P())),x(nt,b("http"),M(P()))),ys=I(sa),ia=W(x(nt,b("tcp"),W(x(b("443"),b("http")),x(Pe(),b("https"))),M(P())),x(nt,b("tls"),b("http"),M(P())),x(nt,b("https"),M(P()))),xs=I(ia);var js=cr(ks(),1);function ba(r){return r[Symbol.asyncIterator]!=null}function ya(r){if(ba(r))return(async()=>{for await(let t of r);})();for(let t of r);}var Is=ya;var Cs=Symbol.for("@achingbrain/uint8arraylist");function Ls(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 Be(r){return!!r?.[Cs]}var G=class r{bufs;length;[Cs]=!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(Be(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(Be(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=Ls(this.bufs,t);return e.buf[e.index]}set(t,e){let n=Ls(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(Be(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 Y(n,s)}subarray(t,e){let{bufs:n,length:s}=this._subList(t,e);return n.length===1?n[0]:Y(n,s)}sublist(t,e){let{bufs:n,length:s}=this._subList(t,e),i=new r;return i.length=s,i.bufs=[...n],i}_subList(t,e){if(t=t??0,e=e??this.length,t<0&&(t=this.length+t),e<0&&(e=this.length+e),t<0||e>this.length)throw new RangeError("index is out of bounds");if(t===e)return{bufs:[],length:0};if(t===0&&e===this.length)return{bufs:this.bufs,length:this.length};let n=[],s=0;for(let i=0;i<this.bufs.length;i++){let o=this.bufs[i],a=s,c=a+o.byteLength;if(s=c,t>=c)continue;let l=t>=a&&t<c,h=e>a&&e<=c;if(l&&h){if(t===a&&e===c){n.push(o);break}let u=t-a;n.push(o.subarray(u,u+(e-t)));break}if(l){if(t===0){n.push(o);continue}n.push(o.subarray(t-a));continue}if(h){if(e===c){n.push(o);break}n.push(o.subarray(0,e-a));break}n.push(o)}return{bufs:n,length:e-t}}indexOf(t,e=0){if(!Be(t)&&!(t instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');let n=t instanceof Uint8Array?t:t.subarray();if(e=Number(e??0),isNaN(e)&&(e=0),e<0&&(e=this.length+e),e<0&&(e=0),t.length===0)return e>this.length?this.length:e;let s=n.byteLength;if(s===0)throw new TypeError("search must be at least 1 byte long");let i=256,o=new Int32Array(i);for(let u=0;u<i;u++)o[u]=-1;for(let u=0;u<s;u++)o[n[u]]=u;let a=o,c=this.byteLength-n.byteLength,l=n.byteLength-1,h;for(let u=e;u<=c;u+=h){h=0;for(let f=l;f>=0;f--){let g=this.get(u+f);if(n[f]!==g){h=Math.max(1,f-a[g]);break}}if(h===0)return u}return-1}getInt8(t){let e=this.subarray(t,t+1);return new DataView(e.buffer,e.byteOffset,e.byteLength).getInt8(0)}setInt8(t,e){let n=R(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt8(0,e),this.write(n,t)}getInt16(t,e){let n=this.subarray(t,t+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt16(0,e)}setInt16(t,e,n){let s=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=R(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint8(0,e),this.write(n,t)}getUint16(t,e){let n=this.subarray(t,t+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint16(0,e)}setUint16(t,e,n){let s=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(!mt(this.bufs[e],t.bufs[e]))return!1;return!0}static fromUint8Arrays(t,e){let n=new r;return n.bufs=t,e==null&&(e=t.reduce((s,i)=>s+i.byteLength,0)),n.length=e,n}};function Oe(r){return r[Symbol.asyncIterator]!=null}var $e=r=>{let t=S(r),e=R(t);return K(r,e),$e.bytes=t,e};$e.bytes=0;function Ts(r,t){t=t??{};let e=t.lengthEncoder??$e;function*n(s){let i=e(s.byteLength);i instanceof Uint8Array?yield i:yield*i,s instanceof Uint8Array?yield s:yield*s}return Oe(r)?async function*(){for await(let s of r)yield*n(s)}():function*(){for(let s of r)yield*n(s)}()}Ts.single=(r,t)=>{t=t??{};let e=t.lengthEncoder??$e;return new G(e(r.byteLength),r)};var Ht=cr(_s(),1);var Ea=8,va=1024*1024*4,bt;(function(r){r[r.LENGTH=0]="LENGTH",r[r.DATA=1]="DATA"})(bt||(bt={}));var nn=r=>{let t=H(r);return nn.bytes=S(t),t};nn.bytes=0;function ee(r,t){let e=new G,n=bt.LENGTH,s=-1,i=t?.lengthDecoder??nn,o=t?.maxLengthLength??Ea,a=t?.maxDataLength??va;function*c(){for(;e.byteLength>0;){if(n===bt.LENGTH)try{if(s=i(e),s<0)throw(0,Ht.default)(new Error("invalid message length"),"ERR_INVALID_MSG_LENGTH");if(s>a)throw(0,Ht.default)(new Error("message length too long"),"ERR_MSG_DATA_TOO_LONG");let l=i.bytes;e.consume(l),t?.onLength!=null&&t.onLength(s),n=bt.DATA}catch(l){if(l instanceof RangeError){if(e.byteLength>o)throw(0,Ht.default)(new Error("message length length too long"),"ERR_MSG_LENGTH_TOO_LONG");break}throw l}if(n===bt.DATA){if(e.byteLength<s)break;let l=e.sublist(0,s);e.consume(s),t?.onData!=null&&t.onData(l),yield l,n=bt.LENGTH}}}return Oe(r)?async function*(){for await(let l of r)e.append(l),yield*c();if(e.byteLength>0)throw(0,Ht.default)(new Error("unexpected end of input"),"ERR_UNEXPECTED_EOF")}():function*(){for(let l of r)e.append(l),yield*c();if(e.byteLength>0)throw(0,Ht.default)(new Error("unexpected end of input"),"ERR_UNEXPECTED_EOF")}()}ee.fromReader=(r,t)=>{let e=1,n=async function*(){for(;;)try{let{done:i,value:o}=await r.next(e);if(i===!0)return;o!=null&&(yield o)}catch(i){if(i.code==="ERR_UNDER_READ")return{done:!0,value:null};throw i}finally{e=1}}();return ee(n,{...t??{},onLength:i=>{e=i}})};var sn=class{readNext;haveNext;ended;nextResult;constructor(){this.ended=!1,this.readNext=_(),this.haveNext=_()}[Symbol.asyncIterator](){return this}async next(){if(this.nextResult==null&&await this.haveNext.promise,this.nextResult==null)throw new Error("HaveNext promise resolved but nextResult was undefined");let t=this.nextResult;return this.nextResult=void 0,this.readNext.resolve(),this.readNext=_(),t}async throw(t){return this.ended=!0,t!=null&&this.haveNext.reject(t),{done:!0,value:void 0}}async return(){let t={done:!0,value:void 0};return await this._push(void 0),t}async push(t,e){await this._push(t,e)}async end(t,e){t!=null?await this.throw(t):await this._push(void 0,e)}async _push(t,e){if(t!=null&&this.ended)throw new Error("Cannot push value onto an ended pushable");if(this.nextResult!=null&&(await this.readNext.promise,this.nextResult!=null))throw new Error("NeedNext promise resolved but nextResult was not consumed");t!=null?this.nextResult={done:!1,value:t}:(this.ended=!0,this.nextResult={done:!0,value:void 0}),this.haveNext.resolve(),this.haveNext=_(),await ye(this.readNext.promise,e?.signal,e)}};function Ps(){return new sn}var ze=class extends Error{code;constructor(t,e){super(t),this.code=e}},on=class extends ze{type;constructor(t){super(t,"ABORT_ERR"),this.type="aborted"}};function Rs(r,t){let e=Ps();r.sink(e).catch(async o=>{await e.end(o)}),r.sink=async o=>{for await(let a of o)await e.push(a);await e.end()};let n=r.source;r.source[Symbol.iterator]!=null?n=r.source[Symbol.iterator]():r.source[Symbol.asyncIterator]!=null&&(n=r.source[Symbol.asyncIterator]());let s=new G;return{read:async(o,a)=>{a?.signal?.throwIfAborted();let c,l=new Promise((h,u)=>{c=()=>{u(new on("Read aborted"))},a?.signal?.addEventListener("abort",c)});try{if(o==null){let{done:u,value:f}=await Promise.race([n.next(),l]);return u===!0?new G:f}for(;s.byteLength<o;){let{value:u,done:f}=await Promise.race([n.next(),l]);if(f===!0)throw new ze("unexpected end of input","ERR_UNEXPECTED_EOF");s.append(u)}let h=s.sublist(0,o);return s.consume(o),h}finally{c!=null&&a?.signal?.removeEventListener("abort",c)}},write:async(o,a)=>{a?.signal?.throwIfAborted(),o instanceof Uint8Array?await e.push(o,a):await e.push(o.subarray(),a)},unwrap:()=>{if(s.byteLength>0){let o=r.source;r.source=async function*(){t?.yieldBytes===!1?yield s:yield*s,yield*o}()}return r}}}var Ve=class extends Error{code;constructor(t,e){super(t),this.code=e}};function Ns(r,t={}){let e=Rs(r,t);t.maxDataLength!=null&&t.maxLengthLength==null&&(t.maxLengthLength=S(t.maxDataLength));let n=t?.lengthDecoder??H,s=t?.lengthEncoder??K;return{read:async o=>{let a=-1,c=new G;for(;;){c.append(await e.read(1,o));try{a=n(c)}catch(l){if(l instanceof RangeError)continue;throw l}if(t?.maxLengthLength!=null&&c.byteLength>t.maxLengthLength)throw new Ve("message length length too long","ERR_MSG_LENGTH_TOO_LONG");if(a>-1)break}if(t?.maxDataLength!=null&&a>t.maxDataLength)throw new Ve("message length too long","ERR_MSG_DATA_TOO_LONG");return e.read(a,o)},write:async(o,a)=>{await e.write(new G(s(o.byteLength),o),a)},writeV:async(o,a)=>{let c=new G(...o.flatMap(l=>[s(l.byteLength),l]));await e.write(c,a)},unwrap:()=>e.unwrap()}}function Aa(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 He=Aa;function ka(r){return r[Symbol.asyncIterator]!=null}function Ia(r,t){if(ka(r))return async function*(){for await(let a of r)yield t(a)}();let e=He(r),{value:n,done:s}=e.next();if(s===!0)return function*(){}();let i=t(n);if(typeof i.then=="function")return async function*(){yield await i;for await(let a of e)yield t(a)}();let o=t;return function*(){yield i;for(let a of e)yield o(a)}()}var yt=Ia;function La(r){return r[Symbol.asyncIterator]!=null}function Ca(...r){let t=[];for(let e of r)La(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 We=Ca;function re(r,...t){if(r==null)throw new Error("Empty pipeline");if(an(r)){let n=r;r=()=>n.source}else if(Ms(r)||Us(r)){let n=r;r=()=>n}let e=[r,...t];if(e.length>1&&an(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++)an(e[n])&&(e[n]=Da(e[n]));return Ta(...e)}var Ta=(...r)=>{let t;for(;r.length>0;)t=r.shift()(t);return t},Us=r=>r?.[Symbol.asyncIterator]!=null,Ms=r=>r?.[Symbol.iterator]!=null,an=r=>r==null?!1:r.sink!=null&&r.source!=null,Da=r=>t=>{let e=r.sink(t);if(e?.then!=null){let n=Dt({objectMode:!0});e.then(()=>{n.end()},o=>{n.end(o)});let s,i=r.source;if(Us(i))s=async function*(){yield*i,n.end()};else if(Ms(i))s=function*(){yield*i,n.end()};else throw new Error("Unknown duplex source type - must be Iterable or AsyncIterable");return We(n,s())}return r.source};function Fa(r){return r[Symbol.asyncIterator]!=null}function _a(r,t){return Fa(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 Bs=_a;var xt=class extends Event{constructor(t,e){super(t),this.detail=e}};var ne="/ipfs/bitswap/1.2.0";var cn=new Float32Array([-0]),ft=new Uint8Array(cn.buffer);function Os(r,t,e){cn[0]=r,t[e]=ft[0],t[e+1]=ft[1],t[e+2]=ft[2],t[e+3]=ft[3]}function $s(r,t){return ft[0]=r[t],ft[1]=r[t+1],ft[2]=r[t+2],ft[3]=r[t+3],cn[0]}var ln=new Float64Array([-0]),U=new Uint8Array(ln.buffer);function zs(r,t,e){ln[0]=r,t[e]=U[0],t[e+1]=U[1],t[e+2]=U[2],t[e+3]=U[3],t[e+4]=U[4],t[e+5]=U[5],t[e+6]=U[6],t[e+7]=U[7]}function Vs(r,t){return U[0]=r[t],U[1]=r[t+1],U[2]=r[t+2],U[3]=r[t+3],U[4]=r[t+4],U[5]=r[t+5],U[6]=r[t+6],U[7]=r[t+7],ln[0]}var Pa=BigInt(Number.MAX_SAFE_INTEGER),Ra=BigInt(Number.MIN_SAFE_INTEGER),j=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 Et;if(t<Pa&&t>Ra)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>Hs&&(s=0n,++n>Hs&&(n=0n))),new r(Number(s),Number(n))}static fromNumber(t){if(t===0)return Et;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):Et}},Et=new j(0,0);Et.toBigInt=function(){return 0n};Et.zzEncode=Et.zzDecode=function(){return this};Et.length=function(){return 1};var Hs=4294967296n;function Ws(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 qs(r,t,e){if(e-t<1)return"";let s,i=[],o=0,a;for(;t<e;)a=r[t++],a<128?i[o++]=a:a>191&&a<224?i[o++]=(a&31)<<6|r[t++]&63:a>239&&a<365?(a=((a&7)<<18|(r[t++]&63)<<12|(r[t++]&63)<<6|r[t++]&63)-65536,i[o++]=55296+(a>>10),i[o++]=56320+(a&1023)):i[o++]=(a&15)<<12|(r[t++]&63)<<6|r[t++]&63,o>8191&&((s??(s=[])).push(String.fromCharCode.apply(String,i)),o=0);return s!=null?(o>0&&s.push(String.fromCharCode.apply(String,i.slice(0,o))),s.join("")):String.fromCharCode.apply(String,i.slice(0,o))}function un(r,t,e){let n=e,s,i;for(let o=0;o<r.length;++o)s=r.charCodeAt(o),s<128?t[e++]=s:s<2048?(t[e++]=s>>6|192,t[e++]=s&63|128):(s&64512)===55296&&((i=r.charCodeAt(o+1))&64512)===56320?(s=65536+((s&1023)<<10)+(i&1023),++o,t[e++]=s>>18|240,t[e++]=s>>12&63|128,t[e++]=s>>6&63|128,t[e++]=s&63|128):(t[e++]=s>>12|224,t[e++]=s>>6&63|128,t[e++]=s&63|128);return e-n}function tt(r,t){return RangeError(`index out of range: ${r.pos} + ${t??1} > ${r.len}`)}function qe(r,t){return(r[t-4]|r[t-3]<<8|r[t-2]<<16|r[t-1]<<24)>>>0}var hn=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,tt(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 tt(this,4);return qe(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw tt(this,4);return qe(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw tt(this,4);let t=$s(this.buf,this.pos);return this.pos+=4,t}double(){if(this.pos+8>this.len)throw tt(this,4);let t=Vs(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 tt(this,t);return this.pos+=t,e===n?new Uint8Array(0):this.buf.subarray(e,n)}string(){let t=this.bytes();return qs(t,0,t.length)}skip(t){if(typeof t=="number"){if(this.pos+t>this.len)throw tt(this,t);this.pos+=t}else do if(this.pos>=this.len)throw tt(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 j(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 tt(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 tt(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 tt(this,8);let t=qe(this.buf,this.pos+=4),e=qe(this.buf,this.pos+=4);return new j(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=zr(this.buf,this.pos);return this.pos+=S(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 fn(r){return new hn(r instanceof Uint8Array?r:r.subarray())}function vt(r,t,e){let n=fn(r);return t.decode(n,void 0,e)}function dn(r){let t=r??8192,e=t>>>1,n,s=t;return function(o){if(o<1||o>e)return R(o);s+o>t&&(n=R(t),s=0);let a=n.subarray(s,s+=o);return s&7&&(s=(s|7)+1),a}}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 pn(){}var gn=class{head;tail;len;next;constructor(t){this.head=t.head,this.tail=t.tail,this.len=t.len,this.next=t.states}},Na=dn();function Ua(r){return globalThis.Buffer!=null?R(r):Na(r)}var ie=class{len;head;tail;states;constructor(){this.len=0,this.head=new St(pn,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 wn((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(Ge,10,j.fromNumber(t)):this.uint32(t)}sint32(t){return this.uint32((t<<1^t>>31)>>>0)}uint64(t){let e=j.fromBigInt(t);return this._push(Ge,e.length(),e)}uint64Number(t){return this._push($r,S(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=j.fromBigInt(t).zzEncode();return this._push(Ge,e.length(),e)}sint64Number(t){let e=j.fromNumber(t).zzEncode();return this._push(Ge,e.length(),e)}sint64String(t){return this.sint64(BigInt(t))}bool(t){return this._push(mn,1,t?1:0)}fixed32(t){return this._push(se,4,t>>>0)}sfixed32(t){return this.fixed32(t)}fixed64(t){let e=j.fromBigInt(t);return this._push(se,4,e.lo)._push(se,4,e.hi)}fixed64Number(t){let e=j.fromNumber(t);return this._push(se,4,e.lo)._push(se,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(Os,4,t)}double(t){return this._push(zs,8,t)}bytes(t){let e=t.length>>>0;return e===0?this._push(mn,1,0):this.uint32(e)._push(Ba,e,t)}string(t){let e=Ws(t);return e!==0?this.uint32(e)._push(un,e,t):this._push(mn,1,0)}fork(){return this.states=new gn(this),this.head=this.tail=new St(pn,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(pn,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=Ua(this.len),n=0;for(;t!=null;)t.fn(t.val,e,n),n+=t.len,t=t.next;return e}};function mn(r,t,e){t[e]=r&255}function Ma(r,t,e){for(;r>127;)t[e++]=r&127|128,r>>>=7;t[e]=r}var wn=class extends St{next;constructor(t,e){super(Ma,t,e),this.next=void 0}};function Ge(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 se(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 Ba(r,t,e){t.set(r,e)}globalThis.Buffer!=null&&(ie.prototype.bytes=function(r){let t=r.length>>>0;return this.uint32(t),t>0&&this._push(Oa,t,r),this},ie.prototype.string=function(r){let t=globalThis.Buffer.byteLength(r);return this.uint32(t),t>0&&this._push($a,t,r),this});function Oa(r,t,e){t.set(r,e)}function $a(r,t,e){r.length<40?un(r,t,e):t.utf8Write!=null?t.utf8Write(r,e):t.set(Kt(r),e)}function bn(){return new ie}function At(r,t){let e=bn();return t.encode(r,e,{lengthDelimited:!1}),e.finish()}var Wt;(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"})(Wt||(Wt={}));function je(r,t,e,n){return{name:r,type:t,encode:e,decode:n}}function Qe(r){function t(s){if(r[s.toString()]==null)throw new Error("Invalid enum value");return r[s]}let e=function(i,o){let a=t(i);o.int32(a)},n=function(i){let o=i.int32();return t(o)};return je("enum",Wt.VARINT,e,n)}function kt(r,t){return je("message",Wt.LENGTH_DELIMITED,r,t)}var k;(function(r){r.WantBlock="WantBlock",r.WantHave="WantHave"})(k||(k={}));var yn;(function(r){r[r.WantBlock=0]="WantBlock",r[r.WantHave=1]="WantHave"})(yn||(yn={}));(function(r){r.codec=()=>Qe(yn)})(k||(k={}));var Xe;(function(r){let t;r.codec=()=>(t==null&&(t=kt((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),k.codec().encode(e.wantType,n)),e.sendDontHave!=null&&(n.uint32(40),n.bool(e.sendDontHave)),s.lengthDelimited!==!1&&n.ldelim()},(e,n)=>{let s={cid:O(0),priority:0},i=n==null?e.len:e.pos+n;for(;e.pos<i;){let o=e.uint32();switch(o>>>3){case 1:{s.cid=e.bytes();break}case 2:{s.priority=e.int32();break}case 3:{s.cancel=e.bool();break}case 4:{s.wantType=k.codec().decode(e);break}case 5:{s.sendDontHave=e.bool();break}default:{e.skipType(o&7);break}}}return s})),t),r.encode=e=>At(e,r.codec()),r.decode=e=>vt(e,r.codec())})(Xe||(Xe={}));var Je;(function(r){let t;r.codec=()=>(t==null&&(t=kt((e,n,s={})=>{if(s.lengthDelimited!==!1&&n.fork(),e.entries!=null)for(let i of e.entries)n.uint32(10),Xe.codec().encode(i,n);e.full!=null&&(n.uint32(16),n.bool(e.full)),s.lengthDelimited!==!1&&n.ldelim()},(e,n)=>{let s={entries:[]},i=n==null?e.len:e.pos+n;for(;e.pos<i;){let o=e.uint32();switch(o>>>3){case 1:{s.entries.push(Xe.codec().decode(e,e.uint32()));break}case 2:{s.full=e.bool();break}default:{e.skipType(o&7);break}}}return s})),t),r.encode=e=>At(e,r.codec()),r.decode=e=>vt(e,r.codec())})(Je||(Je={}));var Ke;(function(r){let t;r.codec=()=>(t==null&&(t=kt((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)=>{let s={prefix:O(0),data:O(0)},i=n==null?e.len:e.pos+n;for(;e.pos<i;){let o=e.uint32();switch(o>>>3){case 1:{s.prefix=e.bytes();break}case 2:{s.data=e.bytes();break}default:{e.skipType(o&7);break}}}return s})),t),r.encode=e=>At(e,r.codec()),r.decode=e=>vt(e,r.codec())})(Ke||(Ke={}));var Z;(function(r){r.HaveBlock="HaveBlock",r.DontHaveBlock="DontHaveBlock"})(Z||(Z={}));var Ye;(function(r){r[r.HaveBlock=0]="HaveBlock",r[r.DontHaveBlock=1]="DontHaveBlock"})(Ye||(Ye={}));(function(r){r.codec=()=>Qe(Ye)})(Z||(Z={}));var Ze;(function(r){let t;r.codec=()=>(t==null&&(t=kt((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&&Ye[e.type]!==0&&(n.uint32(16),Z.codec().encode(e.type,n)),s.lengthDelimited!==!1&&n.ldelim()},(e,n)=>{let s={cid:O(0),type:Z.HaveBlock},i=n==null?e.len:e.pos+n;for(;e.pos<i;){let o=e.uint32();switch(o>>>3){case 1:{s.cid=e.bytes();break}case 2:{s.type=Z.codec().decode(e);break}default:{e.skipType(o&7);break}}}return s})),t),r.encode=e=>At(e,r.codec()),r.decode=e=>vt(e,r.codec())})(Ze||(Ze={}));var oe;(function(r){let t;r.codec=()=>(t==null&&(t=kt((e,n,s={})=>{if(s.lengthDelimited!==!1&&n.fork(),e.wantlist!=null&&(n.uint32(10),Je.codec().encode(e.wantlist,n)),e.blocks!=null)for(let i of e.blocks)n.uint32(26),Ke.codec().encode(i,n);if(e.blockPresences!=null)for(let i of e.blockPresences)n.uint32(34),Ze.codec().encode(i,n);e.pendingBytes!=null&&e.pendingBytes!==0&&(n.uint32(40),n.int32(e.pendingBytes)),s.lengthDelimited!==!1&&n.ldelim()},(e,n)=>{let s={blocks:[],blockPresences:[],pendingBytes:0},i=n==null?e.len:e.pos+n;for(;e.pos<i;){let o=e.uint32();switch(o>>>3){case 1:{s.wantlist=Je.codec().decode(e,e.uint32());break}case 3:{s.blocks.push(Ke.codec().decode(e,e.uint32()));break}case 4:{s.blockPresences.push(Ze.codec().decode(e,e.uint32()));break}case 5:{s.pendingBytes=e.int32();break}default:{e.skipType(o&7);break}}}return s})),t),r.encode=e=>At(e,r.codec()),r.decode=e=>vt(e,r.codec())})(oe||(oe={}));js.default.formatters.B=r=>r==null?"undefined":JSON.stringify({blocks:r.blocks?.map(t=>({data:`${v(t.data,"base64").substring(0,10)}...`,prefix:v(t.prefix,"base64")})),blockPresences:r.blockPresences?.map(t=>({...t,cid:D.decode(t.cid).toString()})),wantlist:r.wantlist==null?void 0:{full:r.wantlist.full,entries:r.wantlist.entries.map(t=>({...t,cid:D.decode(t.cid).toString()}))}},null,2);var tr=class extends Ct{log;libp2p;routing;protocols;running;maxInboundStreams;maxOutboundStreams;messageReceiveTimeout;registrarIds;metrics;sendQueue;messageSendTimeout;runOnTransientConnections;constructor(t,e={}){super(),this.log=t.logger.forComponent("helia:bitswap:network"),this.libp2p=t.libp2p,this.routing=t.routing,this.protocols=e.protocols??[ne],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.messageSendTimeout=e.messageSendTimeout??5e3,this.runOnTransientConnections=e.runOnTransientConnections??!1,t.metrics!=null&&(this.metrics={blocksSent:t.metrics?.registerMetricGroup("ipfs_bitswap_sent_blocks"),dataSent:t.metrics?.registerMetricGroup("ipfs_bitswap_sent_data_bytes")}),this.sendQueue=new at({concurrency:e.messageSendConcurrency,metrics:t.metrics,metricName:"ipfs_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.abort(new B("Incoming Bitswap stream timed out","ERR_TIMEOUT"))},i=AbortSignal.timeout(this.messageReceiveTimeout);rt(1/0,i),i.addEventListener("abort",s),await re(e,o=>ee(o),async o=>{for await(let a of o)try{let c=oe.decode(a);this.log("incoming new bitswap %s message from %p %B",e.protocol,n.remotePeer,c),this.safeDispatchEvent("bitswap:message",{detail:{peer:n.remotePeer,message:c}}),i.removeEventListener("abort",s),i=AbortSignal.timeout(this.messageReceiveTimeout),rt(1/0,i),i.addEventListener("abort",s)}catch(c){this.log.error("error reading incoming bitswap message from %p",n.remotePeer,c),e.abort(c);break}})}).catch(s=>{this.log.error("error handling incoming stream from %p",n.remotePeer,s),e.abort(s)})}async*findProviders(t,e){e?.onProgress?.(new xt("bitswap:network:find-providers",t));for await(let n of this.routing.findProviders(t,e)){if(!this.runOnTransientConnections){let s=!1;for(let i of n.multiaddrs)if(i.getPeerId()==null&&(i=i.encapsulate(`/p2p/${n.id}`)),!bs.exactMatch(i)){s=!0;break}if(!s)continue}n.protocols?.includes("transport-bitswap")!==!1&&(yield n)}}async findAndConnect(t,e){await Is(Bs(yt(this.findProviders(t,e),async n=>this.connectTo(n.id,e)),e?.maxProviders??3)).catch(n=>{this.log.error(n)})}async sendMessage(t,e,n){if(!this.running)throw new Error("network isn't running");let s={wantlist:{full:e.wantlist?.full??!1,entries:e.wantlist?.entries??[]},blocks:e.blocks??[],blockPresences:e.blockPresences??[],pendingBytes:e.pendingBytes??0},i=ge([AbortSignal.timeout(this.messageSendTimeout),n?.signal]);rt(1/0,i);try{let o=this.sendQueue.find(t);if(o?.status==="queued"){o.options.message=ja(o.options.message,s),await o.join({signal:i});return}await this.sendQueue.add(async a=>{let c=a?.message;if(c==null)throw new B("No message to send","ERR_NO_MESSAGE");this.log("sendMessage to %p %B",t,c),a?.onProgress?.(new xt("bitswap:network:send-wantlist",t));let l=await this.libp2p.dialProtocol(t,ne,a);try{let h=Ns(l);await h.write(oe.encode(c),a),await h.unwrap().close(a)}catch(h){a?.onProgress?.(new xt("bitswap:network:send-wantlist:error",{peer:t,error:h})),this.log.error("error sending message to %p",t,h),l.abort(h)}this._updateSentStats(t,c.blocks)},{peerId:t,signal:i,message:s})}finally{i.clear()}}async connectTo(t,e){if(!this.running)throw new B("Network isn't running","ERR_NOT_STARTED");e?.onProgress?.(new xt("bitswap:network:dial",t));let[n]=await Promise.all([this.libp2p.dial(t,e),Ft(this.libp2p,"peer:identify",e?.signal,{filter:s=>{if(!s.detail.peerId.equals(t))return!1;if(s.detail.protocols.includes(ne))return!0;throw new B(`${t} did not support ${ne}`,"ERR_BITSWAP_UNSUPPORTED_BY_PEER")}})]);return n}_updateSentStats(t,e=[]){if(this.metrics!=null){let n=0;for(let s of e.values())n+=s.data.byteLength;this.metrics.dataSent.increment({global:n,[t.toString()]:n}),this.metrics.blocksSent.increment({global:e.length,[t.toString()]:e.length})}}};function ja(r,t){let e=new Map((r.wantlist?.entries??[]).map(o=>[ut.encode(o.cid),o]));for(let o of t.wantlist?.entries??[]){let a=ut.encode(o.cid),c=e.get(a);c!=null&&(c.priority>o.priority&&(o.priority=c.priority),o.cancel=o.cancel??c.cancel,o.wantType=o.wantType??c.wantType,o.sendDontHave=o.sendDontHave??c.sendDontHave),e.set(a,o)}let n=new Map(r.blockPresences.map(o=>[ut.encode(o.cid),o]));for(let o of t.blockPresences){let a=ut.encode(o.cid);n.set(a,o)}let s=new Map(r.blocks.map(o=>[ut.encode(o.data),o]));for(let o of t.blocks){let a=ut.encode(o.data);s.set(a,o)}return{wantlist:{full:r.wantlist?.full??t.wantlist?.full??!1,entries:[...e.values()]},blockPresences:[...n.values()],blocks:[...s.values()],pendingBytes:r.pendingBytes+t.pendingBytes}}var Qa=Symbol.for("nodejs.util.inspect.custom"),Qs=Object.values(ht).map(r=>r.decoder).reduce((r,t)=>r.or(t),ht.identity.decoder),Xs=114,Js=36,Ks=37,ae=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()})`}[Ln]=!0;toString(){return this.string==null&&(this.string=T.encode(this.multihash.bytes).slice(1)),this.string}toCID(){return D.createV1(Xs,this.multihash)}toBytes(){return this.multihash.bytes}toJSON(){return this.toString()}equals(t){if(t==null)return!1;if(t instanceof Uint8Array)return mt(this.multihash.bytes,t);if(typeof t=="string")return ot(t).equals(this);if(t?.multihash?.bytes!=null)return mt(this.multihash.bytes,t.multihash.bytes);throw new Error("not valid Id")}[Qa](){return`PeerId(${this.toString()})`}},ce=class extends ae{type="RSA";publicKey;constructor(t){super({...t,type:"RSA"}),this.publicKey=t.publicKey}},le=class extends ae{type="Ed25519";publicKey;constructor(t){super({...t,type:"Ed25519"}),this.publicKey=t.multihash.digest}},ue=class extends ae{type="secp256k1";publicKey;constructor(t){super({...t,type:"secp256k1"}),this.publicKey=t.multihash.digest}};function ot(r,t){if(t=t??Qs,r.charAt(0)==="1"||r.charAt(0)==="Q"){let e=dt(T.decode(`z${r}`));return r.startsWith("12D")?new le({multihash:e}):r.startsWith("16U")?new ue({multihash:e}):new ce({multihash:e})}return Xa(Qs.decode(r))}function Xa(r){try{let t=dt(r);if(t.code===Le.code){if(t.digest.length===Js)return new le({multihash:t});if(t.digest.length===Ks)return new ue({multihash:t})}if(t.code===gt.code)return new ce({multihash:t})}catch{return Ja(D.decode(r))}throw new Error("Supplied PeerID CID is invalid")}function Ja(r){if(r==null||r.multihash==null||r.version==null||r.version===1&&r.code!==Xs)throw new Error("Supplied PeerID CID is invalid");let t=r.multihash;if(t.code===gt.code)return new ce({multihash:r.multihash});if(t.code===Le.code){if(t.digest.length===Js)return new le({multihash:r.multihash});if(t.digest.length===Ks)return new ue({multihash:r.multihash})}throw new Error("Supplied PeerID CID is invalid")}function qt(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 he=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 qt(this.map.entries(),t=>[ot(t[0]),t[1]])}forEach(t){this.map.forEach((e,n)=>{t(e,ot(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 qt(this.map.keys(),t=>ot(t))}values(){return this.map.values()}get size(){return this.map.size}};var It=class r{set;constructor(t){if(this.set=new Set,t!=null)for(let e of t)this.set.add(e.toString())}get size(){return this.set.size}[Symbol.iterator](){return this.values()}add(t){this.set.add(t.toString())}clear(){this.set.clear()}delete(t){this.set.delete(t.toString())}entries(){return qt(this.set.entries(),t=>{let e=ot(t[0]);return[e,e]})}forEach(t){this.set.forEach(e=>{let n=ot(e);t(n,n,this)})}has(t){return this.set.has(t.toString())}values(){return qt(this.set.values(),t=>ot(t))}intersection(t){let e=new r;for(let n of t)this.has(n)&&e.add(n);return e}difference(t){let e=new r;for(let n of this)t.has(n)||e.add(n);return e}union(t){let e=new r;for(let n of t)e.add(n);for(let n of this)e.add(n);return e}};var xn=class extends he{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 fe(r){let{name:t,metrics:e}=r,n;return e!=null?n=new xn({name:t,metrics:e}):n=new he,n}function Ka(r){let t=new Uint8Array(r.reduce((n,s)=>n+S(s),0)),e=0;for(let n of r)t=K(n,t,e),e+=S(n);return t}var Ys=Ka;function En(r){return Ys([r.version,r.code,r.multihash.code,r.multihash.digest.byteLength])}var er=class{peerId;blockstore;network;wants;exchangeCount;bytesSent;bytesReceived;lastExchange;maxSizeReplaceHasWithBlock;constructor(t,e){this.peerId=t.peerId,this.blockstore=t.blockstore,this.network=t.network,this.wants=new Map,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={blockPresences:[],blocks:[]},n=new Set;for(let[s,i]of this.wants.entries()){if(!await this.blockstore.has(i.cid,t)){if(!i.sendDontHave||i.sentDontHave===!0)continue;i.sentDontHave=!0,e.blockPresences.push({cid:i.cid.bytes,type:Z.DontHaveBlock});continue}let a=await this.blockstore.get(i.cid,t);i.wantType===k.WantHave?a.byteLength<this.maxSizeReplaceHasWithBlock?(n.add(s),e.blocks.push({data:a,prefix:En(i.cid)})):e.blockPresences.push({cid:i.cid.bytes,type:Z.HaveBlock}):(n.add(s),e.blocks.push({data:a,prefix:En(i.cid)}))}if(e.blocks.length>0||e.blockPresences.length>0){await this.network.sendMessage(this.peerId,e,t),this.sentBytes(e.blocks.reduce((s,i)=>s+i.data.byteLength,0));for(let s of n)this.wants.delete(s)}}};var rr=class{blockstore;network;ledgerMap;maxSizeReplaceHasWithBlock;log;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.ledgerMap=fe({name:"ipfs_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 er({peerId:t,blockstore:this.blockstore,network:this.network},{maxSizeReplaceHasWithBlock:this.maxSizeReplaceHasWithBlock}),this.ledgerMap.set(t,n)),n.receivedBytes(e.blocks?.reduce((s,i)=>s+i.data.byteLength,0)??0),e.wantlist!=null){e.wantlist.full===!0&&n.wants.clear();for(let s of e.wantlist.entries){let i=D.decode(s.cid),o=v(i.multihash.bytes,"base64");s.cancel===!0?(this.log("peer %p cancelled want of block for %c",t,i),n.wants.delete(o)):(s.wantType===k.WantHave?this.log("peer %p wanted block presence for %c",t,i):this.log("peer %p wanted block for %c",t,i),n.wants.set(o,{cid:i,priority:s.priority,wantType:s.wantType??k.WantBlock,sendDontHave:s.sendDontHave??!1}))}}await n.sendBlocksToPeer()}async receivedBlock(t,e){let n=v(t.multihash.bytes,"base64"),s=[];for(let i of this.ledgerMap.values())i.wants.has(n)&&s.push(i);await Promise.all(s.map(async i=>i.sendBlocksToPeer(e)))}peerDisconnected(t){this.ledgerMap.delete(t)}};var vn=class{root;peers;log;wantList;network;queue;maxProviders;constructor(t,e){this.peers=new It,this.root=e.root,this.maxProviders=e.maxProviders,this.log=t.logger.forComponent(`helia:bitswap:session:${e.root}`),this.wantList=t.wantList,this.network=t.network,this.queue=new at({concurrency:e.queryConcurrency}),this.queue.addEventListener("error",n=>{this.log.error("error querying peer for %c",this.root,n.detail)})}async want(t,e={}){if(this.peers.size===0)throw new B("Bitswap session had no peers","ERR_NO_SESSION_PEERS");this.log("sending WANT-BLOCK for %c to",t,this.peers);let n=await Promise.any([...this.peers].map(async s=>this.wantList.wantBlock(t,{peerId:s,...e})));return this.log("received block for %c from %p",t,n.sender),n.block}async findNewProviders(t,e,n={}){let s=_(),i=0;this.log("find %d-%d new provider(s) for %c",e,this.maxProviders,t);let o=We([...this.wantList.peers.keys()],yt(this.network.findProviders(t,n),a=>a.id));return Promise.resolve().then(async()=>{for await(let a of o)await this.queue.add(async()=>{try{if(this.log("asking potential session peer %p if they have %c",a,t),!(await this.wantList.wantPresence(t,{peerId:a,...n})).has){this.log("potential session peer %p did not have %c",a,t);return}this.log("potential session peer %p had %c",a,t),i++,this.peers.add(a),i===e&&(this.log("found %d session peers",i),s.resolve()),i===this.maxProviders&&(this.log("found max provider session peers",i),this.queue.clear())}catch(c){this.log.error("error querying potential session peer %p for %c",a,t,c.errors??c)}},{peerId:a});this.log("found %d session peers total",i),e>0&&s.reject(new B(`Found ${i} of ${e} providers`,"ERR_NO_PROVIDERS_FOUND"))}),s.promise}};async function Zs(r,t){let e=new vn(r,t);return await e.findNewProviders(t.root,t.minProviders,{signal:t.signal}),e}var nr=class{blocksReceived;duplicateBlocksReceived;dataReceived;duplicateDataReceived;constructor(t){this.blocksReceived=t.metrics?.registerMetricGroup("ipfs_bitswap_received_blocks"),this.duplicateBlocksReceived=t.metrics?.registerMetricGroup("ipfs_bitswap_duplicate_received_blocks"),this.dataReceived=t.metrics?.registerMetricGroup("ipfs_bitswap_data_received_bytes"),this.duplicateDataReceived=t.metrics?.registerMetricGroup("ipfs_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 Sn=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 ti(r){let{name:t,metrics:e}=r,n;return e!=null?n=new Sn({name:t,metrics:e}):n=new Map,n}function Ya(r){return r[Symbol.asyncIterator]!=null}function Za(r){if(Ya(r))return(async()=>{let e=[];for await(let n of r)e.push(n);return e})();let t=[];for(let e of r)t.push(e);return t}var An=Za;function tc(r){return r[Symbol.asyncIterator]!=null}function ec(r,t){if(tc(r))return async function*(){for await(let a of r)await t(a)&&(yield a)}();let e=He(r),{value:n,done:s}=e.next();if(s===!0)return function*(){}();let i=t(n);if(typeof i.then=="function")return async function*(){await i&&(yield n);for await(let a of e)await t(a)&&(yield a)}();let o=t;return function*(){i===!0&&(yield n);for(let a of e)o(a)&&(yield a)}()}var sr=ec;function rc(r){if(!(r instanceof Uint8Array))throw new Error("arg needs to be a Uint8Array");let t=[];for(;r.length>0;){let e=H(r);t.push(e),r=r.slice(S(e))}return t}var ei=rc;var ir=class{peers;wants;network;log;sendMessagesDelay;sendMessagesTimeout;hashLoader;constructor(t,e={}){this.peers=fe({name:"ipfs_bitswap_peers",metrics:t.metrics}),this.wants=ti({name:"ipfs_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=v(t.multihash.bytes,"base64"),s=this.wants.get(n);s==null&&(s={cid:t,session:new It,priority:e.priority??1,wantType:e.wantType??k.WantBlock,cancel:!1,sendDontHave:!0,blockWantListeners:[],blockPresenceListeners:[]},e.peerId!=null&&s.session.add(e.peerId),this.wants.set(n,s)),s.wantType===k.WantHave&&e.wantType===k.WantBlock&&(s.wantType=k.WantBlock),s.session.size>0&&(e.peerId!=null&&s.session.add(e.peerId),e.peerId==null&&s.session.clear());let i;if(e.wantType===k.WantBlock){let a=i=_();s.blockWantListeners.push(a)}else{let a=i=_();s.blockPresenceListeners.push(a)}let o=()=>{this.log("want for %c was aborted, cancelling want",t),s!=null&&(s.cancel=!0),i.reject(new et("Want was aborted"))};e.signal?.addEventListener("abort",o),clearTimeout(this.sendMessagesTimeout),this.sendMessagesTimeout=setTimeout(()=>{this.sendMessages().catch(a=>{this.log("error sending messages to peers",a)})},this.sendMessagesDelay);try{return await i.promise}finally{e.signal?.removeEventListener("abort",o),e.wantType===k.WantBlock?s.blockWantListeners=s.blockWantListeners.filter(a=>a!==i):s.blockPresenceListeners=s.blockPresenceListeners.filter(a=>a!==i)}}async sendMessages(){for(let[t,e]of this.peers){let n=new Set,s={wantlist:{full:!1,entries:re(this.wants.entries(),i=>sr(i,([o,a])=>{if(a.session.size>0&&!a.session.has(t))return!1;let c=e.has(o);return a.cancel?c:!c}),i=>yt(i,([o,a])=>(n.add(o),{cid:a.cid.bytes,priority:a.priority,wantType:a.wantType,cancel:a.cancel,sendDontHave:a.sendDontHave})),i=>An(i))}};if(s.wantlist?.entries.length===0)return;try{await this.network.sendMessage(t,s);for(let i of n)e.add(i)}catch(i){this.log.error("error sending full wantlist to new peer",i)}}for(let[t,e]of this.wants)if(e.cancel){this.wants.delete(t);for(let n of this.peers.values())n.delete(t)}}has(t){let e=v(t.multihash.bytes,"base64");return this.wants.has(e)}async wantPresence(t,e={}){if(e.peerId!=null&&this.peers.get(e.peerId)==null){let n=v(t.multihash.bytes,"base64");try{this.peers.set(e.peerId,new Set([n])),await this.network.sendMessage(e.peerId,{wantlist:{full:!1,entries:[{cid:t.bytes,sendDontHave:!0,wantType:k.WantHave,priority:1}]}})}catch(s){throw this.peers.delete(e.peerId),s}}return this.addEntry(t,{...e,wantType:k.WantHave})}async wantBlock(t,e={}){return this.addEntry(t,{...e,wantType:k.WantBlock})}async receiveMessage(t,e){this.log("received message from %p",t);let n=[],s=[];for(let i of e.blocks){if(i.prefix==null||i.data==null)continue;this.log("received block");let o=ei(i.prefix),a=o[0],c=o[1],l=o[2],h=l===gt.code?gt:await this.hashLoader?.getHasher(l);if(h==null){this.log.error("unknown hash algorithm",l);continue}let u=await h.digest(i.data),f=D.create(a===0?0:1,c,u);this.log("received block from %p for %c",t,f),n.push({sender:t,cid:f,block:i.data}),s.push({sender:t,cid:f,has:!0})}for(let{cid:i,type:o}of e.blockPresences){let a=D.decode(i);this.log("received %s from %p for %c",o,t,a),s.push({sender:t,cid:a,has:o===Z.HaveBlock})}for(let i of n){let o=v(i.cid.multihash.bytes,"base64"),a=this.wants.get(o);if(a==null)return;let c=a.blockWantListeners;a.blockWantListeners=[],c.forEach(l=>{l.resolve(i)}),a.cancel=!0}for(let i of s){let o=v(i.cid.multihash.bytes,"base64"),a=this.wants.get(o);if(a==null)return;let c=a.blockPresenceListeners;a.blockPresenceListeners=[],c.forEach(l=>{l.resolve(i)})}}async peerConnected(t){let e=new Set,n={wantlist:{full:!0,entries:re(this.wants.entries(),s=>sr(s,([i,o])=>!o.cancel&&o.session.size>0&&!o.session.has(t)),s=>sr(s,([i,o])=>!o.cancel),s=>yt(s,([i,o])=>(e.add(i),{cid:o.cid.bytes,priority:1,wantType:k.WantBlock,cancel:!1,sendDontHave:!1})),s=>An(s))}};if(n.wantlist?.entries.length===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()}};var or=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 nr(t),this.network=new tr(t,e),this.peerWantLists=new rr({...t,network:this.network},e),this.wantList=new ir({...t,network:this.network},e)}async createSession(t,e){let n=e?.minProviders??1,s=e?.maxProviders??5;return Zs({wantList:this.wantList,network:this.network,logger:this.logger},{root:t,queryConcurrency:e?.providerQueryConcurrency??5,minProviders:n,maxProviders:s,connectedPeers:e?.queryConnectedPeers!==!1?[...this.wantList.peers.keys()]:[],signal:e?.signal})}async want(t,e={}){let n=new AbortController,s=ge([n.signal,e.signal]);rt(1/0,n.signal,s),this.network.findAndConnect(t,{...e,signal:s}).catch(i=>{n.signal.aborted||this.log.error("error during finding and connect for cid %c",t,i)});try{return(await this.wantList.wantBlock(t,{...e,signal:s})).block}finally{n.abort(),s.clear()}}async notify(t,e,n={}){await this.peerWantLists.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 ri=(r,t={})=>new or(r,t);var kn=class{bitswap;started;constructor(t,e={}){let{hashers:n}=t;this.bitswap=ri(t,{hashLoader:{getHasher:async s=>{let i;if(typeof s=="string"?i=Object.values(n).find(o=>o.name===s):i=n[s],i!=null)return i;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)}async createSession(t,e){let n=await this.bitswap.createSession(t,e);return{announce:async(s,i,o)=>{await this.bitswap.notify(s,i,o)},retrieve:async(s,i)=>n.want(s,i)}}};function ni(r={}){return t=>new kn(t,r)}var ii=cr(si(),1),oc=["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"],ac=oc.map(r=>new ii.Netmask(r));function cc(r){for(let t of ac)if(t.contains(r))return!0;return!1}function lc(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 oi(r){return Pt(r)?cc(r):Rt(r)?lc(r):void 0}var uc=[m("tcp").code,m("dns").code,m("dnsaddr").code,m("dns4").code,m("dns6").code];function ai(r){let t;try{t=m("sni").code}catch{return null}for(let[e,n]of r)if(e===t&&n!==void 0)return n;return null}function ci(r){return r.some(([t,e])=>t===m("tls").code)}function Q(r,t,e){let n=li[m(r).name];if(n===void 0)throw new Error(`Can't interpret protocol ${m(r).name}`);let s=n(t,e);return r===m("ip6").code?`[${s}]`:s}var li={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=ci(t),n=ai(t);if(e&&n!==null)return`https://${n}`;let s=e?"https://":"http://",i=t.pop();if(i===void 0)throw new Error("Unexpected end of multiaddr");let o=Q(i[0],i[1]??"",t);return o=o.replace("tcp://",""),`${s}${o}`},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=ci(t),n=ai(t);if(e&&n!==null)return`wss://${n}`;let s=e?"wss://":"ws://",i=t.pop();if(i===void 0)throw new Error("Unexpected end of multiaddr");let o=Q(i[0],i[1]??"",t);return o=o.replace("tcp://",""),`${s}${o}`},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 ui(r,t){let n=Yt(r).stringTuples(),s=n.pop();if(s===void 0)throw new Error("Unexpected end of multiaddr");let i=m(s[0]),o=li[i.name];if(o==null)throw new Error(`No interpreter found for ${i.name}`);let a=o(s[1]??"",n);return t?.assumeHttp!==!1&&uc.includes(s[0])&&(a=a.replace(/^.*:\/\//,""),s[1]==="443"?a=`https://${a}`:a=`http://${a}`),(a.startsWith("http://")||a.startsWith("https://"))&&(a=new URL(a).toString(),a.endsWith("/")&&(a=a.substring(0,a.length-1))),a}var pe=class{url;#t=0;#e=0;#r=0;#n=0;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}`)}async getRawBlock(t,e){let n=this.url;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`);try{this.#t++;let s=await fetch(n.toString(),{signal:e,headers:{Accept:"application/vnd.ipld.raw"},cache:"force-cache"});if(this.log("GET %s %d",n,s.status),!s.ok)throw this.#e++,new Error(`unable to fetch raw block for CID ${t} from gateway ${this.url}`);return this.#n++,new Uint8Array(await s.arrayBuffer())}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}`))}}reliability(){return this.#t===0?1:this.#r>0?-1/0:this.#n/(this.#t+this.#e*3)}incrementInvalidBlocks(){this.#r++}};var ar=class r{components;gateways;routing;log;constructor(t,e={}){this.components=t,this.log=t.logger.forComponent("helia:trustless-gateway-block-broker"),this.routing=t.routing,this.gateways=(e.gateways??hi).map(n=>new pe(n,t.logger))}addGateway(t){this.gateways.push(new pe(t,this.components.logger))}async retrieve(t,e={}){let n=this.gateways.sort((i,o)=>o.reliability()-i.reliability()),s=[];for(let i of n){this.log("getting block for %c from %s",t,i.url);try{let o=await i.getRawBlock(t,e.signal);this.log.trace("got block for %c from %s",t,i.url);try{await e.validateFn?.(o)}catch(a){throw this.log.error("failed to validate block for %c from %s",t,i.url,a),i.incrementInvalidBlocks(),new Error(`Block for CID ${t} from gateway ${i.url} failed validation`)}return o}catch(o){if(this.log.error("failed to get block for %c from %s",t,i.url,o),o instanceof Error?s.push(o):s.push(new Error(`Unable to fetch raw block for CID ${t} from gateway ${i.url}`)),e.signal?.aborted===!0){this.log.trace("request aborted while fetching raw block for CID %c from gateway %s",t,i.url);break}}}throw s.length>0?new AggregateError(s,`Unable to fetch raw block for CID ${t} from any gateway`):new Error(`Unable to fetch raw block for CID ${t} from any gateway`)}async createSession(t,e={}){let n=[],s=e.minProviders??1,i=e.minProviders??5,o=_(),a=new r(this.components,{gateways:n});this.log("finding transport-ipfs-gateway-http providers for cid %c",t);let c=new at({concurrency:e.providerQueryConcurrency??5});return Promise.resolve().then(async()=>{for await(let l of this.routing.findProviders(t,e)){let h=l.multiaddrs.filter(u=>xs.matches(u)||e.allowInsecure===!0&&ys.matches(u)?e.allowLocal===!0||us.matches(u)?!0:oi(u.toOptions().host)===!1:!1);h.length!==0&&(this.log("found transport-ipfs-gateway-http provider %p for cid %c",l.id,t),c.add(async()=>{for(let u of h){let f;try{f=ui(u);let g=`${f}/ipfs/${t.toString()}?format=raw`,p=await fetch(g,{method:"HEAD",headers:{Accept:"application/vnd.ipld.raw","Cache-Control":e.cacheControl??"only-if-cached"},signal:AbortSignal.timeout(e.providerQueryTimeout??5e3)});this.log("HEAD %s %d",g,p.status),n.push(f),a.addGateway(f),this.log("found %d transport-ipfs-gateway-http providers for cid %c",n.length,t),n.length===s&&o.resolve(a),n.length===i&&c.clear()}catch(g){this.log.error("could not fetch %c from %a",t,f??u,g)}}}))}}).catch(l=>{this.log.error("error creating session for %c",t,l)}),o.promise}};var hi=["https://trustless-gateway.link","https://cloudflare-ipfs.com","https://4everland.io"];function fi(r={}){return t=>new ar(t,r)}return bi(hc);})();
|
|
2
|
+
"use strict";var HeliaBlockBrokers=(()=>{var di=Object.create;var me=Object.defineProperty;var pi=Object.getOwnPropertyDescriptor;var mi=Object.getOwnPropertyNames;var gi=Object.getPrototypeOf,wi=Object.prototype.hasOwnProperty;var Gt=(r,t)=>()=>(t||r((t={exports:{}}).exports,t),t.exports),V=(r,t)=>{for(var e in t)me(r,e,{get:t[e],enumerable:!0})},In=(r,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of mi(t))!wi.call(r,s)&&s!==e&&me(r,s,{get:()=>t[s],enumerable:!(n=pi(t,s))||n.enumerable});return r};var cr=(r,t,e)=>(e=r!=null?di(gi(r)):{},In(t||!r||!r.__esModule?me(e,"default",{value:r,enumerable:!0}):e,r)),bi=r=>In(me({},"__esModule",{value:!0}),r);var vs=Gt((Th,Es)=>{var $t=1e3,zt=$t*60,Vt=zt*60,yt=Vt*24,oa=yt*7,aa=yt*365.25;Es.exports=function(r,t){t=t||{};var e=typeof r;if(e==="string"&&r.length>0)return ca(r);if(e==="number"&&isFinite(r))return t.long?ua(r):la(r);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(r))};function ca(r){if(r=String(r),!(r.length>100)){var t=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(r);if(t){var e=parseFloat(t[1]),n=(t[2]||"ms").toLowerCase();switch(n){case"years":case"year":case"yrs":case"yr":case"y":return e*aa;case"weeks":case"week":case"w":return e*oa;case"days":case"day":case"d":return e*yt;case"hours":case"hour":case"hrs":case"hr":case"h":return e*Vt;case"minutes":case"minute":case"mins":case"min":case"m":return e*zt;case"seconds":case"second":case"secs":case"sec":case"s":return e*$t;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return e;default:return}}}}function la(r){var t=Math.abs(r);return t>=yt?Math.round(r/yt)+"d":t>=Vt?Math.round(r/Vt)+"h":t>=zt?Math.round(r/zt)+"m":t>=$t?Math.round(r/$t)+"s":r+"ms"}function ua(r){var t=Math.abs(r);return t>=yt?Ue(r,t,yt,"day"):t>=Vt?Ue(r,t,Vt,"hour"):t>=zt?Ue(r,t,zt,"minute"):t>=$t?Ue(r,t,$t,"second"):r+" ms"}function Ue(r,t,e,n){var s=t>=e*1.5;return Math.round(r/e)+" "+n+(s?"s":"")}});var As=Gt((Fh,Ss)=>{function ha(r){e.debug=e,e.default=e,e.coerce=c,e.disable=i,e.enable=s,e.enabled=o,e.humanize=vs(),e.destroy=l,Object.keys(r).forEach(h=>{e[h]=r[h]}),e.names=[],e.skips=[],e.formatters={};function t(h){let u=0;for(let f=0;f<h.length;f++)u=(u<<5)-u+h.charCodeAt(f),u|=0;return e.colors[Math.abs(u)%e.colors.length]}e.selectColor=t;function e(h){let u,f=null,m,p;function w(...d){if(!w.enabled)return;let E=w,L=Number(new Date),C=L-(u||L);E.diff=C,E.prev=u,E.curr=L,u=L,d[0]=e.coerce(d[0]),typeof d[0]!="string"&&d.unshift("%O");let F=0;d[0]=d[0].replace(/%([a-zA-Z%])/g,(X,z)=>{if(X==="%%")return"%";F++;let J=e.formatters[z];if(typeof J=="function"){let Dt=d[F];X=J.call(E,Dt),d.splice(F,1),F--}return X}),e.formatArgs.call(E,d),(E.log||e.log).apply(E,d)}return w.namespace=h,w.useColors=e.useColors(),w.color=e.selectColor(h),w.extend=n,w.destroy=e.destroy,Object.defineProperty(w,"enabled",{enumerable:!0,configurable:!1,get:()=>f!==null?f:(m!==e.namespaces&&(m=e.namespaces,p=e.enabled(h)),p),set:d=>{f=d}}),typeof e.init=="function"&&e.init(w),w}function n(h,u){let f=e(this.namespace+(typeof u>"u"?":":u)+h);return f.log=this.log,f}function s(h){e.save(h),e.namespaces=h,e.names=[],e.skips=[];let u,f=(typeof h=="string"?h:"").split(/[\s,]+/),m=f.length;for(u=0;u<m;u++)f[u]&&(h=f[u].replace(/\*/g,".*?"),h[0]==="-"?e.skips.push(new RegExp("^"+h.slice(1)+"$")):e.names.push(new RegExp("^"+h+"$")))}function i(){let h=[...e.names.map(a),...e.skips.map(a).map(u=>"-"+u)].join(",");return e.enable(""),h}function o(h){if(h[h.length-1]==="*")return!0;let u,f;for(u=0,f=e.skips.length;u<f;u++)if(e.skips[u].test(h))return!1;for(u=0,f=e.names.length;u<f;u++)if(e.names[u].test(h))return!0;return!1}function a(h){return h.toString().substring(2,h.toString().length-2).replace(/\.\*\?$/,"*")}function c(h){return h instanceof Error?h.stack||h.message:h}function l(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return e.enable(e.load()),e}Ss.exports=ha});var ks=Gt((W,Me)=>{W.formatArgs=da;W.save=pa;W.load=ma;W.useColors=fa;W.storage=ga();W.destroy=(()=>{let r=!1;return()=>{r||(r=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})();W.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function fa(){return typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs)?!0:typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)?!1:typeof document<"u"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&parseInt(RegExp.$1,10)>=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function da(r){if(r[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+r[0]+(this.useColors?"%c ":" ")+"+"+Me.exports.humanize(this.diff),!this.useColors)return;let t="color: "+this.color;r.splice(1,0,t,"color: inherit");let e=0,n=0;r[0].replace(/%[a-zA-Z%]/g,s=>{s!=="%%"&&(e++,s==="%c"&&(n=e))}),r.splice(n,0,t)}W.log=console.debug||console.log||(()=>{});function pa(r){try{r?W.storage.setItem("debug",r):W.storage.removeItem("debug")}catch{}}function ma(){let r;try{r=W.storage.getItem("debug")}catch{}return!r&&typeof process<"u"&&"env"in process&&(r=process.env.DEBUG),r}function ga(){try{return localStorage}catch{}}Me.exports=As()(W);var{formatters:wa}=Me.exports;wa.j=function(r){try{return JSON.stringify(r)}catch(t){return"[UnexpectedJSONParseError]: "+t.message}}});var _s=Gt((Vh,Fs)=>{"use strict";function Ts(r,t){for(let e in t)Object.defineProperty(r,e,{value:t[e],enumerable:!0,configurable:!0});return r}function xa(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 Ts(r,e)}catch{e.message=r.message,e.stack=r.stack;let s=function(){};return s.prototype=Object.create(Object.getPrototypeOf(r)),Ts(new s,e)}}Fs.exports=xa});var si=Gt(de=>{(function(){var r,t,e,n,s,i,o,a;a=function(c){var l,h,u,f;return l=(c&255<<24)>>>24,h=(c&255<<16)>>>16,u=(c&65280)>>>8,f=c&255,[l,h,u,f].join(".")},o=function(c){var l,h,u,f,m,p;for(l=[],u=f=0;f<=3&&c.length!==0;u=++f){if(u>0){if(c[0]!==".")throw new Error("Invalid IP");c=c.substring(1)}p=t(c),m=p[0],h=p[1],c=c.substring(h),l.push(m)}if(c.length!==0)throw new Error("Invalid IP");switch(l.length){case 1:if(l[0]>4294967295)throw new Error("Invalid IP");return l[0]>>>0;case 2:if(l[0]>255||l[1]>16777215)throw new Error("Invalid IP");return(l[0]<<24|l[1])>>>0;case 3:if(l[0]>255||l[1]>255||l[2]>65535)throw new Error("Invalid IP");return(l[0]<<24|l[1]<<16|l[2])>>>0;case 4:if(l[0]>255||l[1]>255||l[2]>255||l[3]>255)throw new Error("Invalid IP");return(l[0]<<24|l[1]<<16|l[2]<<8|l[3])>>>0;default:throw new Error("Invalid IP")}},e=function(c){return c.charCodeAt(0)},n=e("0"),i=e("a"),s=e("A"),t=function(c){var l,h,u,f,m;for(f=0,l=10,h="9",u=0,c.length>1&&c[u]==="0"&&(c[u+1]==="x"||c[u+1]==="X"?(u+=2,l=16):"0"<=c[u+1]&&c[u+1]<="9"&&(u++,l=8,h="7")),m=u;u<c.length;){if("0"<=c[u]&&c[u]<=h)f=f*l+(e(c[u])-n)>>>0;else if(l===16)if("a"<=c[u]&&c[u]<="f")f=f*l+(10+e(c[u])-i)>>>0;else if("A"<=c[u]&&c[u]<="F")f=f*l+(10+e(c[u])-s)>>>0;else break;else break;if(f>4294967295)throw new Error("too large");u++}if(u===m)throw new Error("empty octet");return[f,u]},r=function(){function c(l,h){var u,f,m,p;if(typeof l!="string")throw new Error("Missing `net' parameter");if(h||(p=l.split("/",2),l=p[0],h=p[1]),h||(h=32),typeof h=="string"&&h.indexOf(".")>-1){try{this.maskLong=o(h)}catch(w){throw u=w,new Error("Invalid mask: "+h)}for(f=m=32;m>=0;f=--m)if(this.maskLong===4294967295<<32-f>>>0){this.bitmask=f;break}}else if(h||h===0)this.bitmask=parseInt(h,10),this.maskLong=0,this.bitmask>0&&(this.maskLong=4294967295<<32-this.bitmask>>>0);else throw new Error("Invalid mask: empty");try{this.netLong=(o(l)&this.maskLong)>>>0}catch(w){throw u=w,new Error("Invalid net address: "+l)}if(!(this.bitmask<=32))throw new Error("Invalid mask for ip4: "+h);this.size=Math.pow(2,32-this.bitmask),this.base=a(this.netLong),this.mask=a(this.maskLong),this.hostmask=a(~this.maskLong),this.first=this.bitmask<=30?a(this.netLong+1):this.base,this.last=this.bitmask<=30?a(this.netLong+this.size-2):a(this.netLong+this.size-1),this.broadcast=this.bitmask<=30?a(this.netLong+this.size-1):void 0}return c.prototype.contains=function(l){return typeof l=="string"&&(l.indexOf("/")>0||l.split(".").length!==4)&&(l=new c(l)),l instanceof c?this.contains(l.base)&&this.contains(l.broadcast||l.last):(o(l)&this.maskLong)>>>0===(this.netLong&this.maskLong)>>>0},c.prototype.next=function(l){return l==null&&(l=1),new c(a(this.netLong+this.size*l),this.mask)},c.prototype.forEach=function(l){var h,u,f;for(f=o(this.first),u=o(this.last),h=0;f<=u;)l(a(f),f,h),h++,f++},c.prototype.toString=function(){return this.base+"/"+this.bitmask},c}(),de.ip2long=o,de.long2ip=a,de.Netmask=r}).call(de)});var fc={};V(fc,{bitswap:()=>ni,trustlessGateway:()=>fi});var Ln=Symbol.for("@libp2p/peer-id");var ct=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"},B=class extends Error{code;props;constructor(t,e,n){super(t),this.code=e,this.name=n?.name??"CodeError",this.props=n??{}}};var K=(r,...t)=>{try{[...t]}catch{}};var lt=class extends EventTarget{#t=new Map;constructor(){super(),K(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:i})=>i!==e),this.#t.set(t,s))}dispatchEvent(t){let e=super.dispatchEvent(t),n=this.#t.get(t.type);return n==null||(n=n.filter(({once:s})=>!s),this.#t.set(t.type,n)),e}safeDispatchEvent(t,e={}){return this.dispatchEvent(new yi(t,e))}},lr=class extends Event{detail;constructor(t,e){super(t,e),this.detail=e?.detail}},yi=globalThis.CustomEvent??lr;function ge(r){let t=new globalThis.AbortController;function e(){t.abort();for(let i of r)i?.removeEventListener!=null&&i.removeEventListener("abort",e)}for(let i of r){if(i?.aborted===!0){e();break}i?.addEventListener!=null&&i.addEventListener("abort",e)}function n(){for(let i of r)i?.removeEventListener!=null&&i.removeEventListener("abort",e)}let s=t.signal;return s.clear=n,s}function _(){let r={};return r.promise=new Promise((t,e)=>{r.resolve=t,r.reject=e}),r}var we=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}},Tt=class{size;hwm;head;tail;constructor(t={}){this.hwm=t.splitLimit??16,this.head=new we(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 we(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 ur=class extends Error{type;code;constructor(t,e){super(t??"The operation was aborted"),this.type="aborted",this.code=e??"ABORT_ERR"}};function Ft(r={}){return xi(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 xi(r,t){t=t??{};let e=t.onEnd,n=new Tt,s,i,o,a=_(),c=async()=>{try{return n.isEmpty()?o?{done:!0}:await new Promise((d,E)=>{i=L=>{i=null,n.push(L);try{d(r(n))}catch(C){E(C)}return s}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=_()})}},l=d=>i!=null?i(d):(n.push(d),s),h=d=>(n=new Tt,i!=null?i({error:d}):(n.push({error:d}),s)),u=d=>{if(o)return s;if(t?.objectMode!==!0&&d?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return l({done:!1,value:d})},f=d=>o?s:(o=!0,d!=null?h(d):l({done:!0})),m=()=>(n=new Tt,f(),{done:!0}),p=d=>(f(d),{done:!0});if(s={[Symbol.asyncIterator](){return this},next:c,return:m,throw:p,push:u,end:f,get readableLength(){return n.size},onEmpty:async d=>{let E=d?.signal;if(E?.throwIfAborted(),n.isEmpty())return;let L,C;E!=null&&(L=new Promise((F,$)=>{C=()=>{$(new ur)},E.addEventListener("abort",C)}));try{await Promise.race([a.promise,L])}finally{C!=null&&E!=null&&E?.removeEventListener("abort",C)}}},e==null)return s;let w=s;return s={[Symbol.asyncIterator](){return this},next(){return w.next()},throw(d){return w.throw(d),e!=null&&(e(d),e=void 0),{done:!0}},return(){return w.return(),e!=null&&(e(),e=void 0),{done:!0}},push:u,end(d){return w.end(d),e!=null&&(e(d),e=void 0),s},get readableLength(){return w.readableLength},onEmpty:d=>w.onEmpty(d)},s}var hr=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 nt(r,t,e,n){let s=new hr(n?.errorMessage,n?.errorCode);return e?.aborted===!0?Promise.reject(s):new Promise((i,o)=>{let a=l=>{try{if(n?.filter?.(l)===!1)return}catch(h){r.removeEventListener(t,a),e?.removeEventListener("abort",c),o(h);return}r.removeEventListener(t,a),e?.removeEventListener("abort",c),i(l)},c=()=>{r.removeEventListener(t,a),e?.removeEventListener("abort",c),o(s)};r.addEventListener(t,a),e?.addEventListener("abort",c)})}var be=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 ye(r,t,e){if(t==null)return r;if(t.aborted)return Promise.reject(new be(e?.errorMessage,e?.errorCode));let n,s=new be(e?.errorMessage,e?.errorCode);try{return await Promise.race([r,new Promise((i,o)=>{n=()=>{o(s)},t.addEventListener("abort",n)})])}finally{n!=null&&t.removeEventListener("abort",n)}}var xe=class{deferred;signal;where;constructor(t,e){this.signal=e,this.deferred=_(),this.where=t,this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(new ct)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function Ei(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var Ee=class{id;fn;options;priority;recipients;status;timeline;controller;constructor(t,e,n=0){this.id=Ei(),this.status="queued",this.fn=t,this.priority=n,this.options=e,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,K(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 ct)}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 ye(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.signal?.removeEventListener("abort",this.onAbort)})}};function vi(r,t,e){let n=0,s=r.length;for(;s>0;){let i=Math.trunc(s/2),o=n+i;e(r[o],t)<=0?(n=++o,s-=i+1):s=i}return n}var ve=class extends lt{concurrency;queue;pending;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.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){if(this.queue[this.size-1]?.priority>=t.priority){this.queue.push(t);return}let e=vi(this.queue,t,(n,s)=>s.priority-n.priority);this.queue.splice(e,0,t)}async add(t,e){e?.signal?.throwIfAborted();let n=new Ee(t,e,e?.priority),s=n.join(e).then(i=>(this.safeDispatchEvent("completed",{detail:i}),this.safeDispatchEvent("success",{detail:{job:n,result:i}}),i)).catch(i=>{throw this.safeDispatchEvent("error",{detail:i}),this.safeDispatchEvent("failure",{detail:{job:n,error:i}}),i});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 ct)}),this.clear()}async onEmpty(t){this.size!==0&&await nt(this,"empty",t?.signal)}async onSizeLessThan(t,e){this.size<t||await nt(this,"next",e?.signal,{filter:()=>this.size<t})}async onIdle(t){this.pending===0&&this.size===0||await nt(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=Ft({objectMode:!0}),n=c=>{c!=null?this.abort():this.clear(),e.end(c)},s=c=>{c.detail!=null&&e.push(c.detail)},i=c=>{n(c.detail)},o=()=>{n()},a=()=>{n(new B("Queue aborted","ERR_QUEUE_ABORTED"))};this.addEventListener("completed",s),this.addEventListener("error",i),this.addEventListener("idle",o),t?.signal?.addEventListener("abort",a);try{yield*e}finally{this.removeEventListener("completed",s),this.removeEventListener("error",i),this.removeEventListener("idle",o),t?.signal?.removeEventListener("abort",a),n()}}};var ut=class extends ve{has(t){return this.find(t)!=null}find(t){return this.queue.find(e=>t.equals(e.options.peerId))}};var Se=class{index=0;input="";new(t){return this.index=0,this.input=t,this}readAtomically(t){let e=this.index,n=t();return n===void 0&&(this.index=e),n}parseWith(t){let e=t();if(this.index===this.input.length)return e}peekChar(){if(!(this.index>=this.input.length))return this.input[this.index]}readChar(){if(!(this.index>=this.input.length))return this.input[this.index++]}readGivenChar(t){return this.readAtomically(()=>{let e=this.readChar();if(e===t)return e})}readSeparator(t,e,n){return this.readAtomically(()=>{if(!(e>0&&this.readGivenChar(t)===void 0))return n()})}readNumber(t,e,n,s){return this.readAtomically(()=>{let i=0,o=0,a=this.peekChar();if(a===void 0)return;let c=a==="0",l=2**(8*s)-1;for(;;){let h=this.readAtomically(()=>{let u=this.readChar();if(u===void 0)return;let f=Number.parseInt(u,t);if(!Number.isNaN(f))return f});if(h===void 0)break;if(i*=t,i+=h,i>l||(o+=1,e!==void 0&&o>e))return}if(o!==0)return!n&&c&&o>1?void 0:i})}readIPv4Addr(){return this.readAtomically(()=>{let t=new Uint8Array(4);for(let e=0;e<t.length;e++){let n=this.readSeparator(".",e,()=>this.readNumber(10,3,!1,1));if(n===void 0)return;t[e]=n}return t})}readIPv6Addr(){let t=e=>{for(let n=0;n<e.length/2;n++){let s=n*2;if(n<e.length-3){let o=this.readSeparator(":",n,()=>this.readIPv4Addr());if(o!==void 0)return e[s]=o[0],e[s+1]=o[1],e[s+2]=o[2],e[s+3]=o[3],[s+4,!0]}let i=this.readSeparator(":",n,()=>this.readNumber(16,4,!0,2));if(i===void 0)return[s,!1];e[s]=i>>8,e[s+1]=i&255}return[e.length,!1]};return this.readAtomically(()=>{let e=new Uint8Array(16),[n,s]=t(e);if(n===16)return e;if(s||this.readGivenChar(":")===void 0||this.readGivenChar(":")===void 0)return;let i=new Uint8Array(14),o=16-(n+2),[a]=t(i.subarray(0,o));return e.set(i.subarray(0,a),16-a),e})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};var Cn=45,Si=15,_t=new Se;function fr(r){if(!(r.length>Si))return _t.new(r).parseWith(()=>_t.readIPv4Addr())}function dr(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>Cn))return _t.new(r).parseWith(()=>_t.readIPv6Addr())}function Ae(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>Cn))return _t.new(r).parseWith(()=>_t.readIPAddr())}function Pt(r){return!!fr(r)}function Rt(r){return!!dr(r)}function ke(r){return!!Ae(r)}var br={};V(br,{base58btc:()=>D,base58flickr:()=>Di});var Gc=new Uint8Array(0);function Dn(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 it(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 Tn(r){return new TextEncoder().encode(r)}function Fn(r){return new TextDecoder().decode(r)}function Ai(r,t){if(r.length>=255)throw new TypeError("Alphabet too long");for(var e=new Uint8Array(256),n=0;n<e.length;n++)e[n]=255;for(var s=0;s<r.length;s++){var i=r.charAt(s),o=i.charCodeAt(0);if(e[o]!==255)throw new TypeError(i+" is ambiguous");e[o]=s}var a=r.length,c=r.charAt(0),l=Math.log(a)/Math.log(256),h=Math.log(256)/Math.log(a);function u(p){if(p instanceof Uint8Array||(ArrayBuffer.isView(p)?p=new Uint8Array(p.buffer,p.byteOffset,p.byteLength):Array.isArray(p)&&(p=Uint8Array.from(p))),!(p instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(p.length===0)return"";for(var w=0,d=0,E=0,L=p.length;E!==L&&p[E]===0;)E++,w++;for(var C=(L-E)*h+1>>>0,F=new Uint8Array(C);E!==L;){for(var $=p[E],X=0,z=C-1;($!==0||X<d)&&z!==-1;z--,X++)$+=256*F[z]>>>0,F[z]=$%a>>>0,$=$/a>>>0;if($!==0)throw new Error("Non-zero carry");d=X,E++}for(var J=C-d;J!==C&&F[J]===0;)J++;for(var Dt=c.repeat(w);J<C;++J)Dt+=r.charAt(F[J]);return Dt}function f(p){if(typeof p!="string")throw new TypeError("Expected String");if(p.length===0)return new Uint8Array;var w=0;if(p[w]!==" "){for(var d=0,E=0;p[w]===c;)d++,w++;for(var L=(p.length-w)*l+1>>>0,C=new Uint8Array(L);p[w];){var F=e[p.charCodeAt(w)];if(F===255)return;for(var $=0,X=L-1;(F!==0||$<E)&&X!==-1;X--,$++)F+=a*C[X]>>>0,C[X]=F%256>>>0,F=F/256>>>0;if(F!==0)throw new Error("Non-zero carry");E=$,w++}if(p[w]!==" "){for(var z=L-E;z!==L&&C[z]===0;)z++;for(var J=new Uint8Array(d+(L-z)),Dt=d;z!==L;)J[Dt++]=C[z++];return J}}}function m(p){var w=f(p);if(w)return w;throw new Error(`Non-${t} character`)}return{encode:u,decodeUnsafe:f,decode:m}}var ki=Ai,Ii=ki,Pn=Ii;var pr=class{name;prefix;baseEncode;constructor(t,e,n){this.name=t,this.prefix=e,this.baseEncode=n}encode(t){if(t instanceof Uint8Array)return`${this.prefix}${this.baseEncode(t)}`;throw Error("Unknown type, must be binary type")}},mr=class{name;prefix;baseDecode;prefixCodePoint;constructor(t,e,n){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 Rn(this,t)}},gr=class{decoders;constructor(t){this.decoders=t}or(t){return Rn(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 Rn(r,t){return new gr({...r.decoders??{[r.prefix]:r},...t.decoders??{[t.prefix]:t}})}var wr=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 pr(t,e,n),this.decoder=new mr(t,e,s)}encode(t){return this.encoder.encode(t)}decode(t){return this.decoder.decode(t)}};function Nt({name:r,prefix:t,encode:e,decode:n}){return new wr(r,t,e,n)}function ht({name:r,prefix:t,alphabet:e}){let{encode:n,decode:s}=Pn(e,r);return Nt({prefix:t,name:r,encode:n,decode:i=>it(s(i))})}function Li(r,t,e,n){let s={};for(let h=0;h<t.length;++h)s[t[h]]=h;let i=r.length;for(;r[i-1]==="=";)--i;let o=new Uint8Array(i*e/8|0),a=0,c=0,l=0;for(let h=0;h<i;++h){let u=s[r[h]];if(u===void 0)throw new SyntaxError(`Non-${n} character`);c=c<<e|u,a+=e,a>=8&&(a-=8,o[l++]=255&c>>a)}if(a>=e||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return o}function Ci(r,t,e){let n=t[t.length-1]==="=",s=(1<<e)-1,i="",o=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],o+=8;o>e;)o-=e,i+=t[s&a>>o];if(o!==0&&(i+=t[s&a<<e-o]),n)for(;i.length*e&7;)i+="=";return i}function A({name:r,prefix:t,bitsPerChar:e,alphabet:n}){return Nt({prefix:t,name:r,encode(s){return Ci(s,n,e)},decode(s){return Li(s,n,e,r)}})}var D=ht({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Di=ht({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var yr={};V(yr,{base32:()=>ot,base32hex:()=>Pi,base32hexpad:()=>Ni,base32hexpadupper:()=>Ui,base32hexupper:()=>Ri,base32pad:()=>Fi,base32padupper:()=>_i,base32upper:()=>Ti,base32z:()=>Mi});var ot=A({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Ti=A({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Fi=A({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),_i=A({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Pi=A({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Ri=A({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Ni=A({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Ui=A({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Mi=A({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Bi=Mn,Nn=128,Oi=127,$i=~Oi,zi=Math.pow(2,31);function Mn(r,t,e){t=t||[],e=e||0;for(var n=e;r>=zi;)t[e++]=r&255|Nn,r/=128;for(;r&$i;)t[e++]=r&255|Nn,r>>>=7;return t[e]=r|0,Mn.bytes=e-n+1,t}var Vi=xr,Hi=128,Un=127;function xr(r,n){var e=0,n=n||0,s=0,i=n,o,a=r.length;do{if(i>=a)throw xr.bytes=0,new RangeError("Could not decode varint");o=r[i++],e+=s<28?(o&Un)<<s:(o&Un)*Math.pow(2,s),s+=7}while(o>=Hi);return xr.bytes=i-n,e}var qi=Math.pow(2,7),Wi=Math.pow(2,14),Gi=Math.pow(2,21),Qi=Math.pow(2,28),ji=Math.pow(2,35),Xi=Math.pow(2,42),Ji=Math.pow(2,49),Ki=Math.pow(2,56),Yi=Math.pow(2,63),Zi=function(r){return r<qi?1:r<Wi?2:r<Gi?3:r<Qi?4:r<ji?5:r<Xi?6:r<Ji?7:r<Ki?8:r<Yi?9:10},to={encode:Bi,decode:Vi,encodingLength:Zi},eo=to,Qt=eo;function jt(r,t=0){return[Qt.decode(r,t),Qt.decode.bytes]}function Ut(r,t,e=0){return Qt.encode(r,t,e),t}function Mt(r){return Qt.encodingLength(r)}function ft(r,t){let e=t.byteLength,n=Mt(r),s=n+Mt(e),i=new Uint8Array(s+e);return Ut(r,i,0),Ut(e,i,n),i.set(t,s),new Bt(r,e,t,i)}function gt(r){let t=it(r),[e,n]=jt(t),[s,i]=jt(t.subarray(n)),o=t.subarray(n+i);if(o.byteLength!==s)throw new Error("Incorrect length");return new Bt(e,s,o,t)}function Bn(r,t){if(r===t)return!0;{let e=t;return r.code===e.code&&r.size===e.size&&e.bytes instanceof Uint8Array&&Dn(r.bytes,e.bytes)}}var Bt=class{code;size;digest;bytes;constructor(t,e,n,s){this.code=t,this.size=e,this.digest=n,this.bytes=s}};function On(r,t){let{bytes:e,version:n}=r;switch(n){case 0:return no(e,Er(r),t??D.encoder);default:return so(e,Er(r),t??ot.encoder)}}var $n=new WeakMap;function Er(r){let t=$n.get(r);if(t==null){let e=new Map;return $n.set(r,e),e}return t}var T=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!==Xt)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(e.code!==io)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=ft(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&&Bn(t.multihash,n.multihash)}toString(t){return On(this,t)}toJSON(){return{"/":On(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(t){if(t==null)return null;let e=t;if(e instanceof r)return e;if(e["/"]!=null&&e["/"]===e.bytes||e.asCID===e){let{version:n,code:s,multihash:i,bytes:o}=e;return new r(n,s,i,o??zn(n,s,i.bytes))}else if(e[oo]===!0){let{version:n,multihash:s,code:i}=e,o=gt(s);return r.create(n,i,o)}else return null}static create(t,e,n){if(typeof e!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(t){case 0:{if(e!==Xt)throw new Error(`Version 0 CID must use dag-pb (code: ${Xt}) block encoding`);return new r(t,e,n,n.bytes)}case 1:{let s=zn(t,e,n.bytes);return new r(t,e,n,s)}default:throw new Error("Invalid version")}}static createV0(t){return r.create(0,Xt,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=it(t.subarray(n,n+e.multihashSize));if(s.byteLength!==e.multihashSize)throw new Error("Incorrect length");let i=s.subarray(e.multihashSize-e.digestSize),o=new Bt(e.multihashCode,e.digestSize,i,s);return[e.version===0?r.createV0(o):r.createV1(e.codec,o),t.subarray(e.size)]}static inspectBytes(t){let e=0,n=()=>{let[u,f]=jt(t.subarray(e));return e+=f,u},s=n(),i=Xt;if(s===18?(s=0,e=0):i=n(),s!==0&&s!==1)throw new RangeError(`Invalid CID version ${s}`);let o=e,a=n(),c=n(),l=e+c,h=l-o;return{version:s,codec:i,multihashCode:a,digestSize:c,multihashSize:h,size:l}}static parse(t,e){let[n,s]=ro(t,e),i=r.decode(s);if(i.version===0&&t[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return Er(i).set(n,t),i}};function ro(r,t){switch(r[0]){case"Q":{let e=t??D;return[D.prefix,e.decode(`${D.prefix}${r}`)]}case D.prefix:{let e=t??D;return[D.prefix,e.decode(r)]}case ot.prefix:{let e=t??ot;return[ot.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 no(r,t,e){let{prefix:n}=e;if(n!==D.prefix)throw Error(`Cannot string encode V0 in ${e.name} encoding`);let s=t.get(n);if(s==null){let i=e.encode(r).slice(1);return t.set(n,i),i}else return s}function so(r,t,e){let{prefix:n}=e,s=t.get(n);if(s==null){let i=e.encode(r);return t.set(n,i),i}else return s}var Xt=112,io=18;function zn(r,t,e){let n=Mt(r),s=n+Mt(t),i=new Uint8Array(s+e.byteLength);return Ut(r,i,0),Ut(t,i,n),i.set(e,s),i}var oo=Symbol.for("@ipld/js-cid/CID");function et(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 vr={};V(vr,{base10:()=>ao});var ao=ht({prefix:"9",name:"base10",alphabet:"0123456789"});var Sr={};V(Sr,{base16:()=>co,base16upper:()=>lo});var co=A({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),lo=A({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var Ar={};V(Ar,{base2:()=>uo});var uo=A({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var kr={};V(kr,{base256emoji:()=>go});var Vn=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}"),ho=Vn.reduce((r,t,e)=>(r[e]=t,r),[]),fo=Vn.reduce((r,t,e)=>(r[t.codePointAt(0)]=e,r),[]);function po(r){return r.reduce((t,e)=>(t+=ho[e],t),"")}function mo(r){let t=[];for(let e of r){let n=fo[e.codePointAt(0)];if(n===void 0)throw new Error(`Non-base256emoji character: ${e}`);t.push(n)}return new Uint8Array(t)}var go=Nt({prefix:"\u{1F680}",name:"base256emoji",encode:po,decode:mo});var Ir={};V(Ir,{base36:()=>wo,base36upper:()=>bo});var wo=ht({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),bo=ht({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var Cr={};V(Cr,{base64:()=>dt,base64pad:()=>yo,base64url:()=>Lr,base64urlpad:()=>xo});var dt=A({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),yo=A({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Lr=A({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),xo=A({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var Dr={};V(Dr,{base8:()=>Eo});var Eo=A({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var Tr={};V(Tr,{identity:()=>vo});var vo=Nt({prefix:"\0",name:"identity",encode:r=>Fn(r),decode:r=>Tn(r)});var wl=new TextEncoder,bl=new TextDecoder;var Fr={};V(Fr,{identity:()=>Le});var Hn=0,ko="identity",qn=it;function Io(r){return ft(Hn,qn(r))}var Le={code:Hn,name:ko,encode:qn,digest:Io};var Rr={};V(Rr,{sha256:()=>bt,sha512:()=>Lo});function Pr({name:r,code:t,encode:e}){return new _r(r,t,e)}var _r=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?ft(this.code,e):e.then(n=>ft(this.code,n))}else throw Error("Unknown type, must be binary type")}};function Gn(r){return async t=>new Uint8Array(await crypto.subtle.digest(r,t))}var bt=Pr({name:"sha2-256",code:18,encode:Gn("SHA-256")}),Lo=Pr({name:"sha2-512",code:19,encode:Gn("SHA-512")});var pt={...Tr,...Ar,...Dr,...vr,...Sr,...yr,...Ir,...br,...Cr,...kr},Fl={...Rr,...Fr};function O(r=0){return new Uint8Array(r)}function R(r=0){return new Uint8Array(r)}function jn(r,t,e,n){return{name:r,prefix:t,encoder:{name:r,prefix:t,encode:e},decoder:{decode:n}}}var Qn=jn("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),Nr=jn("ascii","a",r=>{let t="a";for(let e=0;e<r.length;e++)t+=String.fromCharCode(r[e]);return t},r=>{r=r.substring(1);let t=R(r.length);for(let e=0;e<r.length;e++)t[e]=r.charCodeAt(e);return t}),Co={utf8:Qn,"utf-8":Qn,hex:pt.base16,latin1:Nr,ascii:Nr,binary:Nr,...pt},Ce=Co;function v(r,t="utf8"){let e=Ce[t];if(e==null)throw new Error(`Unsupported encoding "${t}"`);return e.encoder.encode(r).substring(1)}var Do=Math.pow(2,7),To=Math.pow(2,14),Fo=Math.pow(2,21),Ur=Math.pow(2,28),Mr=Math.pow(2,35),Br=Math.pow(2,42),Or=Math.pow(2,49),y=128,N=127;function S(r){if(r<Do)return 1;if(r<To)return 2;if(r<Fo)return 3;if(r<Ur)return 4;if(r<Mr)return 5;if(r<Br)return 6;if(r<Or)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function $r(r,t,e=0){switch(S(r)){case 8:t[e++]=r&255|y,r/=128;case 7:t[e++]=r&255|y,r/=128;case 6:t[e++]=r&255|y,r/=128;case 5:t[e++]=r&255|y,r/=128;case 4:t[e++]=r&255|y,r>>>=7;case 3:t[e++]=r&255|y,r>>>=7;case 2:t[e++]=r&255|y,r>>>=7;case 1:{t[e++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return t}function _o(r,t,e=0){switch(S(r)){case 8:t.set(e++,r&255|y),r/=128;case 7:t.set(e++,r&255|y),r/=128;case 6:t.set(e++,r&255|y),r/=128;case 5:t.set(e++,r&255|y),r/=128;case 4:t.set(e++,r&255|y),r>>>=7;case 3:t.set(e++,r&255|y),r>>>=7;case 2:t.set(e++,r&255|y),r>>>=7;case 1:{t.set(e++,r&255),r>>>=7;break}default:throw new Error("unreachable")}return t}function zr(r,t){let e=r[t],n=0;if(n+=e&N,e<y||(e=r[t+1],n+=(e&N)<<7,e<y)||(e=r[t+2],n+=(e&N)<<14,e<y)||(e=r[t+3],n+=(e&N)<<21,e<y)||(e=r[t+4],n+=(e&N)*Ur,e<y)||(e=r[t+5],n+=(e&N)*Mr,e<y)||(e=r[t+6],n+=(e&N)*Br,e<y)||(e=r[t+7],n+=(e&N)*Or,e<y))return n;throw new RangeError("Could not decode varint")}function Po(r,t){let e=r.get(t),n=0;if(n+=e&N,e<y||(e=r.get(t+1),n+=(e&N)<<7,e<y)||(e=r.get(t+2),n+=(e&N)<<14,e<y)||(e=r.get(t+3),n+=(e&N)<<21,e<y)||(e=r.get(t+4),n+=(e&N)*Ur,e<y)||(e=r.get(t+5),n+=(e&N)*Mr,e<y)||(e=r.get(t+6),n+=(e&N)*Br,e<y)||(e=r.get(t+7),n+=(e&N)*Or,e<y))return n;throw new RangeError("Could not decode varint")}function Y(r,t,e=0){return t==null&&(t=R(S(r))),t instanceof Uint8Array?$r(r,t,e):_o(r,t,e)}function H(r,t=0){return r instanceof Uint8Array?zr(r,t):Po(r,t)}function Z(r,t){t==null&&(t=r.reduce((s,i)=>s+i.length,0));let e=R(t),n=0;for(let s of r)e.set(s,n),n+=s.length;return e}var Kl=parseInt("0xFFFF",16),Yl=new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);function Kt(r,t="utf8"){let e=Ce[t];if(e==null)throw new Error(`Unsupported encoding "${t}"`);return e.decoder.decode(`${e.prefix}${r}`)}var Kn=Pt,Bo=Rt,Vr=function(r){let t=0;if(r=r.toString().trim(),Kn(r)){let e=new Uint8Array(t+4);return r.split(/\./g).forEach(n=>{e[t++]=parseInt(n,10)&255}),e}if(Bo(r)){let e=r.split(":",8),n;for(n=0;n<e.length;n++){let i=Kn(e[n]),o;i&&(o=Vr(e[n]),e[n]=v(o.slice(0,2),"base16")),o!=null&&++n<8&&e.splice(n,0,v(o.slice(2,4),"base16"))}if(e[0]==="")for(;e.length<8;)e.unshift("0");else if(e[e.length-1]==="")for(;e.length<8;)e.push("0");else if(e.length<8){for(n=0;n<e.length&&e[n]!=="";n++);let i=[n,1];for(n=9-e.length;n>0;n--)i.push("0");e.splice.apply(e,i)}let s=new Uint8Array(t+16);for(n=0;n<e.length;n++){let i=parseInt(e[n],16);s[t++]=i>>8&255,s[t++]=i&255}return s}throw new Error("invalid ip address")},Yn=function(r,t=0,e){t=~~t,e=e??r.length-t;let n=new DataView(r.buffer);if(e===4){let s=[];for(let i=0;i<e;i++)s.push(r[t+i]);return s.join(".")}if(e===16){let s=[];for(let i=0;i<e;i+=2)s.push(n.getUint16(t+i).toString(16));return s.join(":").replace(/(^|:)0(:0)*:0(:|$)/,"$1::$3").replace(/:{3,4}/,"::")}return""};var Ot={},Hr={},$o=[[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"]];$o.forEach(r=>{let t=zo(...r);Hr[t.code]=t,Ot[t.name]=t});function zo(r,t,e,n,s){return{code:r,size:t,name:e,resolvable:!!n,path:!!s}}function g(r){if(typeof r=="number"){if(Hr[r]!=null)return Hr[r];throw new Error(`no protocol with code: ${r}`)}else if(typeof r=="string"){if(Ot[r]!=null)return Ot[r];throw new Error(`no protocol with name: ${r}`)}throw new Error(`invalid protocol id type: ${typeof r}`)}var Nu=g("ip4"),Uu=g("ip6"),Mu=g("ipcidr");function Wr(r,t){switch(g(r).code){case 4:case 41:return Ho(t);case 42:return es(t);case 6:case 273:case 33:case 132:return ns(t).toString();case 53:case 54:case 55:case 56:case 400:case 449:case 777:return es(t);case 421:return Qo(t);case 444:return rs(t);case 445:return rs(t);case 466:return Go(t);default:return v(t,"base16")}}function Gr(r,t){switch(g(r).code){case 4:return Zn(t);case 41:return Zn(t);case 42:return ts(t);case 6:case 273:case 33:case 132:return Qr(parseInt(t,10));case 53:case 54:case 55:case 56:case 400:case 449:case 777:return ts(t);case 421:return qo(t);case 444:return jo(t);case 445:return Xo(t);case 466:return Wo(t);default:return Kt(t,"base16")}}var qr=Object.values(pt).map(r=>r.decoder),Vo=function(){let r=qr[0].or(qr[1]);return qr.slice(2).forEach(t=>r=r.or(t)),r}();function Zn(r){if(!ke(r))throw new Error("invalid ip address");return Vr(r)}function Ho(r){let t=Yn(r,0,r.length);if(t==null)throw new Error("ipBuff is required");if(!ke(t))throw new Error("invalid ip address");return t}function Qr(r){let t=new ArrayBuffer(2);return new DataView(t).setUint16(0,r),new Uint8Array(t)}function ns(r){return new DataView(r.buffer).getUint16(r.byteOffset)}function ts(r){let t=Kt(r),e=Uint8Array.from(Y(t.length));return Z([e,t],e.length+t.length)}function es(r){let t=H(r);if(r=r.slice(S(t)),r.length!==t)throw new Error("inconsistent lengths");return v(r)}function qo(r){let t;r[0]==="Q"||r[0]==="1"?t=gt(D.decode(`z${r}`)).bytes:t=T.parse(r).multihash.bytes;let e=Uint8Array.from(Y(t.length));return Z([e,t],e.length+t.length)}function Wo(r){let t=Vo.decode(r),e=Uint8Array.from(Y(t.length));return Z([e,t],e.length+t.length)}function Go(r){let t=H(r),e=r.slice(S(t));if(e.length!==t)throw new Error("inconsistent lengths");return"u"+v(e,"base64url")}function Qo(r){let t=H(r),e=r.slice(S(t));if(e.length!==t)throw new Error("inconsistent lengths");return v(e,"base58btc")}function jo(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=ot.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=Qr(n);return Z([e,s],e.length+s.length)}function Xo(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=ot.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=Qr(n);return Z([e,s],e.length+s.length)}function rs(r){let t=r.slice(0,r.length-2),e=r.slice(r.length-2),n=v(t,"base32"),s=ns(e);return`${n}:${s}`}function ss(r){r=jr(r);let t=[],e=[],n=null,s=r.split("/").slice(1);if(s.length===1&&s[0]==="")return{bytes:new Uint8Array,string:"/",tuples:[],stringTuples:[],path:null};for(let i=0;i<s.length;i++){let o=s[i],a=g(o);if(a.size===0){t.push([a.code]),e.push([a.code]);continue}if(i++,i>=s.length)throw os("invalid address: "+r);if(a.path===!0){n=jr(s.slice(i).join("/")),t.push([a.code,Gr(a.code,n)]),e.push([a.code,n]);break}let c=Gr(a.code,s[i]);t.push([a.code,c]),e.push([a.code,Wr(a.code,c)])}return{string:is(e),bytes:Jr(t),tuples:t,stringTuples:e,path:n}}function Xr(r){let t=[],e=[],n=null,s=0;for(;s<r.length;){let i=H(r,s),o=S(i),a=g(i),c=Jo(a,r.slice(s+o));if(c===0){t.push([i]),e.push([i]),s+=o;continue}let l=r.slice(s+o,s+o+c);if(s+=c+o,s>r.length)throw os("Invalid address Uint8Array: "+v(r,"base16"));t.push([i,l]);let h=Wr(i,l);if(e.push([i,h]),a.path===!0){n=h;break}}return{bytes:Uint8Array.from(r),string:is(e),tuples:t,stringTuples:e,path:n}}function is(r){let t=[];return r.map(e=>{let n=g(e[0]);return t.push(n.name),e.length>1&&e[1]!=null&&t.push(e[1]),null}),jr(t.join("/"))}function Jr(r){return Z(r.map(t=>{let e=g(t[0]),n=Uint8Array.from(Y(e.code));return t.length>1&&t[1]!=null&&(n=Z([n,t[1]])),n}))}function Jo(r,t){if(r.size>0)return r.size/8;if(r.size===0)return 0;{let e=H(t instanceof Uint8Array?t:Uint8Array.from(t));return e+S(e)}}function jr(r){return"/"+r.trim().split("/").filter(t=>t).join("/")}function os(r){return new Error("Error parsing address: "+r)}var Ko=Symbol.for("nodejs.util.inspect.custom"),Kr=Symbol.for("@multiformats/js-multiaddr/multiaddr"),Yo=[g("dns").code,g("dns4").code,g("dns6").code,g("dnsaddr").code],De=class r{bytes;#t;#e;#r;#n;[Kr]=!0;constructor(t){t==null&&(t="");let e;if(t instanceof Uint8Array)e=Xr(t);else if(typeof t=="string"){if(t.length>0&&t.charAt(0)!=="/")throw new Error(`multiaddr "${t}" must start with a "/"`);e=ss(t)}else if(cs(t))e=Xr(t.bytes);else throw new Error("addr must be a string, Buffer, or another Multiaddr");this.bytes=e.bytes,this.#t=e.string,this.#e=e.tuples,this.#r=e.stringTuples,this.#n=e.path}toString(){return this.#t}toJSON(){return this.toString()}toOptions(){let t,e,n,s,i="",o=g("tcp"),a=g("udp"),c=g("ip4"),l=g("ip6"),h=g("dns6"),u=g("ip6zone");for(let[m,p]of this.stringTuples())m===u.code&&(i=`%${p??""}`),Yo.includes(m)&&(e=o.name,s=443,n=`${p??""}${i}`,t=m===h.code?6:4),(m===o.code||m===a.code)&&(e=g(m).name,s=parseInt(p??"")),(m===c.code||m===l.code)&&(e=g(m).name,n=`${p??""}${i}`,t=m===l.code?6:4);if(t==null||e==null||n==null||s==null)throw new Error('multiaddr must have a valid format: "/{ip4, ip6, dns4, dns6, dnsaddr}/{address}/{tcp, udp}/{port}".');return{family:t,host:n,transport:e,port:s}}protos(){return this.#e.map(([t])=>Object.assign({},g(t)))}protoCodes(){return this.#e.map(([t])=>t)}protoNames(){return this.#e.map(([t])=>g(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(Jr(e.slice(0,n)));return this}getPeerId(){try{let t=[];this.stringTuples().forEach(([n,s])=>{n===Ot.p2p.code&&t.push([n,s]),n===Ot["p2p-circuit"].code&&(t=[])});let e=t.pop();if(e?.[1]!=null){let n=e[1];return n[0]==="Q"||n[0]==="1"?v(D.decode(`z${n}`),"base58btc"):v(T.parse(n).multihash.bytes,"base58btc")}return null}catch{return null}}getPath(){return this.#n}equals(t){return et(this.bytes,t.bytes)}async resolve(t){let e=this.protos().find(i=>i.resolvable);if(e==null)return[this];let n=as.get(e.name);if(n==null)throw new B(`no available resolver for ${e.name}`,"ERR_NO_AVAILABLE_RESOLVER");return(await n(this,t)).map(i=>Yt(i))}nodeAddress(){let t=this.toOptions();if(t.transport!=="tcp"&&t.transport!=="udp")throw new Error(`multiaddr must have a valid format - no protocol with name: "${t.transport}". Must have a valid transport protocol: "{tcp, udp}"`);return{family:t.family,address:t.host,port:t.port}}isThinWaistAddress(t){let e=(t??this).protos();return!(e.length!==2||e[0].code!==4&&e[0].code!==41||e[1].code!==6&&e[1].code!==273)}[Ko](){return`Multiaddr(${this.#t})`}};var as=new Map;function cs(r){return!!r?.[Kr]}function Yt(r){return new De(r)}var Zo=r=>r.toString().split("/").slice(1),Zt=r=>({match:t=>t.length<1?!1:r(t[0])?t.slice(1):!1,pattern:"fn"}),b=r=>({match:t=>Zt(e=>e===r).match(t),pattern:r}),_e=()=>({match:r=>Zt(t=>typeof t=="string").match(r),pattern:"{string}"}),Pe=()=>({match:r=>Zt(t=>!isNaN(parseInt(t))).match(r),pattern:"{number}"}),P=()=>({match:r=>{if(r.length<2||r[0]!=="p2p"&&r[0]!=="ipfs")return!1;if(r[1].startsWith("Q")||r[1].startsWith("1"))try{D.decode(`z${r[1]}`)}catch{return!1}else return!1;return r.slice(2)},pattern:"/p2p/{peerid}"}),Te=()=>({match:r=>{if(r.length<2||r[0]!=="certhash")return!1;try{Lr.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})`}),q=(...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(", ")})`}),x=(...r)=>({match:t=>{for(let e of r){let n=e.match(t);if(n===!1)return!1;t=n}return t},pattern:`and(${r.map(t=>t.pattern).join(", ")})`});function k(...r){function t(s){let i=Zo(s);for(let o of r){let a=o.match(i);if(a===!1)return!1;i=a}return i}function e(s){return t(s)!==!1}function n(s){let i=t(s);return i===!1?!1:i.length===0}return{matches:e,exactMatch:n}}var Zr=x(b("dns4"),_e()),tn=x(b("dns6"),_e()),en=x(b("dnsaddr"),_e()),ls=x(b("dns"),_e()),fh=k(Zr),dh=k(tn),ph=k(en),us=k(q(ls,en,Zr,tn)),hs=x(b("ip4"),Zt(Pt)),fs=x(b("ip6"),Zt(Rt)),ds=q(hs,fs),st=q(ds,ls,Zr,tn,en),mh=k(st),gh=k(hs),wh=k(fs),bh=k(ds),Re=x(st,b("tcp"),Pe()),te=x(st,b("udp"),Pe()),ta=q(Re,te),yh=k(Re),xh=k(te),rn=x(te,b("quic")),Ne=x(te,b("quic-v1")),ea=q(rn,Ne),Eh=k(rn),vh=k(Ne),Yr=q(st,Re,te,rn,Ne),ps=q(x(Yr,b("ws"),M(P()))),Sh=k(ps),ms=q(x(Yr,b("wss"),M(P())),x(Yr,b("tls"),b("ws"),M(P()))),Ah=k(ms),gs=x(ta,b("webrtc-direct"),Te(),M(Te()),M(P())),kh=k(gs),ws=x(Ne,b("webtransport"),Te(),Te(),M(P())),Ih=k(ws),Fe=q(ps,ms,x(Re,M(P())),x(ea,M(P())),x(st,M(P())),gs,ws,P()),Lh=k(Fe),ra=x(Fe,b("p2p-circuit"),P()),bs=k(ra),na=q(x(Fe,b("p2p-circuit"),b("webrtc"),P()),x(Fe,b("webrtc"),M(P())),b("webrtc")),Ch=k(na),sa=q(x(st,b("tcp"),Pe(),b("http"),M(P())),x(st,b("http"),M(P()))),ys=k(sa),ia=q(x(st,b("tcp"),q(x(b("443"),b("http")),x(Pe(),b("https"))),M(P())),x(st,b("tls"),b("http"),M(P())),x(st,b("https"),M(P()))),xs=k(ia);var Qs=cr(ks(),1);function ba(r){return r[Symbol.asyncIterator]!=null}function ya(r){if(ba(r))return(async()=>{for await(let t of r);})();for(let t of r);}var Is=ya;var Cs=Symbol.for("@achingbrain/uint8arraylist");function Ls(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 Be(r){return!!r?.[Cs]}var G=class r{bufs;length;[Cs]=!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(Be(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(Be(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=Ls(this.bufs,t);return e.buf[e.index]}set(t,e){let n=Ls(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(Be(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 Z(n,s)}subarray(t,e){let{bufs:n,length:s}=this._subList(t,e);return n.length===1?n[0]:Z(n,s)}sublist(t,e){let{bufs:n,length:s}=this._subList(t,e),i=new r;return i.length=s,i.bufs=[...n],i}_subList(t,e){if(t=t??0,e=e??this.length,t<0&&(t=this.length+t),e<0&&(e=this.length+e),t<0||e>this.length)throw new RangeError("index is out of bounds");if(t===e)return{bufs:[],length:0};if(t===0&&e===this.length)return{bufs:this.bufs,length:this.length};let n=[],s=0;for(let i=0;i<this.bufs.length;i++){let o=this.bufs[i],a=s,c=a+o.byteLength;if(s=c,t>=c)continue;let l=t>=a&&t<c,h=e>a&&e<=c;if(l&&h){if(t===a&&e===c){n.push(o);break}let u=t-a;n.push(o.subarray(u,u+(e-t)));break}if(l){if(t===0){n.push(o);continue}n.push(o.subarray(t-a));continue}if(h){if(e===c){n.push(o);break}n.push(o.subarray(0,e-a));break}n.push(o)}return{bufs:n,length:e-t}}indexOf(t,e=0){if(!Be(t)&&!(t instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');let n=t instanceof Uint8Array?t:t.subarray();if(e=Number(e??0),isNaN(e)&&(e=0),e<0&&(e=this.length+e),e<0&&(e=0),t.length===0)return e>this.length?this.length:e;let s=n.byteLength;if(s===0)throw new TypeError("search must be at least 1 byte long");let i=256,o=new Int32Array(i);for(let u=0;u<i;u++)o[u]=-1;for(let u=0;u<s;u++)o[n[u]]=u;let a=o,c=this.byteLength-n.byteLength,l=n.byteLength-1,h;for(let u=e;u<=c;u+=h){h=0;for(let f=l;f>=0;f--){let m=this.get(u+f);if(n[f]!==m){h=Math.max(1,f-a[m]);break}}if(h===0)return u}return-1}getInt8(t){let e=this.subarray(t,t+1);return new DataView(e.buffer,e.byteOffset,e.byteLength).getInt8(0)}setInt8(t,e){let n=R(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt8(0,e),this.write(n,t)}getInt16(t,e){let n=this.subarray(t,t+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt16(0,e)}setInt16(t,e,n){let s=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=R(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint8(0,e),this.write(n,t)}getUint16(t,e){let n=this.subarray(t,t+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint16(0,e)}setUint16(t,e,n){let s=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(!et(this.bufs[e],t.bufs[e]))return!1;return!0}static fromUint8Arrays(t,e){let n=new r;return n.bufs=t,e==null&&(e=t.reduce((s,i)=>s+i.byteLength,0)),n.length=e,n}};function Oe(r){return r[Symbol.asyncIterator]!=null}var $e=r=>{let t=S(r),e=R(t);return Y(r,e),$e.bytes=t,e};$e.bytes=0;function Ds(r,t){t=t??{};let e=t.lengthEncoder??$e;function*n(s){let i=e(s.byteLength);i instanceof Uint8Array?yield i:yield*i,s instanceof Uint8Array?yield s:yield*s}return Oe(r)?async function*(){for await(let s of r)yield*n(s)}():function*(){for(let s of r)yield*n(s)}()}Ds.single=(r,t)=>{t=t??{};let e=t.lengthEncoder??$e;return new G(e(r.byteLength),r)};var Ht=cr(_s(),1);var Ea=8,va=1024*1024*4,xt;(function(r){r[r.LENGTH=0]="LENGTH",r[r.DATA=1]="DATA"})(xt||(xt={}));var nn=r=>{let t=H(r);return nn.bytes=S(t),t};nn.bytes=0;function ee(r,t){let e=new G,n=xt.LENGTH,s=-1,i=t?.lengthDecoder??nn,o=t?.maxLengthLength??Ea,a=t?.maxDataLength??va;function*c(){for(;e.byteLength>0;){if(n===xt.LENGTH)try{if(s=i(e),s<0)throw(0,Ht.default)(new Error("invalid message length"),"ERR_INVALID_MSG_LENGTH");if(s>a)throw(0,Ht.default)(new Error("message length too long"),"ERR_MSG_DATA_TOO_LONG");let l=i.bytes;e.consume(l),t?.onLength!=null&&t.onLength(s),n=xt.DATA}catch(l){if(l instanceof RangeError){if(e.byteLength>o)throw(0,Ht.default)(new Error("message length length too long"),"ERR_MSG_LENGTH_TOO_LONG");break}throw l}if(n===xt.DATA){if(e.byteLength<s)break;let l=e.sublist(0,s);e.consume(s),t?.onData!=null&&t.onData(l),yield l,n=xt.LENGTH}}}return Oe(r)?async function*(){for await(let l of r)e.append(l),yield*c();if(e.byteLength>0)throw(0,Ht.default)(new Error("unexpected end of input"),"ERR_UNEXPECTED_EOF")}():function*(){for(let l of r)e.append(l),yield*c();if(e.byteLength>0)throw(0,Ht.default)(new Error("unexpected end of input"),"ERR_UNEXPECTED_EOF")}()}ee.fromReader=(r,t)=>{let e=1,n=async function*(){for(;;)try{let{done:i,value:o}=await r.next(e);if(i===!0)return;o!=null&&(yield o)}catch(i){if(i.code==="ERR_UNDER_READ")return{done:!0,value:null};throw i}finally{e=1}}();return ee(n,{...t??{},onLength:i=>{e=i}})};var sn=class{readNext;haveNext;ended;nextResult;constructor(){this.ended=!1,this.readNext=_(),this.haveNext=_()}[Symbol.asyncIterator](){return this}async next(){if(this.nextResult==null&&await this.haveNext.promise,this.nextResult==null)throw new Error("HaveNext promise resolved but nextResult was undefined");let t=this.nextResult;return this.nextResult=void 0,this.readNext.resolve(),this.readNext=_(),t}async throw(t){return this.ended=!0,t!=null&&this.haveNext.reject(t),{done:!0,value:void 0}}async return(){let t={done:!0,value:void 0};return await this._push(void 0),t}async push(t,e){await this._push(t,e)}async end(t,e){t!=null?await this.throw(t):await this._push(void 0,e)}async _push(t,e){if(t!=null&&this.ended)throw new Error("Cannot push value onto an ended pushable");if(this.nextResult!=null&&(await this.readNext.promise,this.nextResult!=null))throw new Error("NeedNext promise resolved but nextResult was not consumed");t!=null?this.nextResult={done:!1,value:t}:(this.ended=!0,this.nextResult={done:!0,value:void 0}),this.haveNext.resolve(),this.haveNext=_(),await ye(this.readNext.promise,e?.signal,e)}};function Ps(){return new sn}var ze=class extends Error{code;constructor(t,e){super(t),this.code=e}},on=class extends ze{type;constructor(t){super(t,"ABORT_ERR"),this.type="aborted"}};function Rs(r,t){let e=Ps();r.sink(e).catch(async o=>{await e.end(o)}),r.sink=async o=>{for await(let a of o)await e.push(a);await e.end()};let n=r.source;r.source[Symbol.iterator]!=null?n=r.source[Symbol.iterator]():r.source[Symbol.asyncIterator]!=null&&(n=r.source[Symbol.asyncIterator]());let s=new G;return{read:async(o,a)=>{a?.signal?.throwIfAborted();let c,l=new Promise((h,u)=>{c=()=>{u(new on("Read aborted"))},a?.signal?.addEventListener("abort",c)});try{if(o==null){let{done:u,value:f}=await Promise.race([n.next(),l]);return u===!0?new G:f}for(;s.byteLength<o;){let{value:u,done:f}=await Promise.race([n.next(),l]);if(f===!0)throw new ze("unexpected end of input","ERR_UNEXPECTED_EOF");s.append(u)}let h=s.sublist(0,o);return s.consume(o),h}finally{c!=null&&a?.signal?.removeEventListener("abort",c)}},write:async(o,a)=>{a?.signal?.throwIfAborted(),o instanceof Uint8Array?await e.push(o,a):await e.push(o.subarray(),a)},unwrap:()=>{if(s.byteLength>0){let o=r.source;r.source=async function*(){t?.yieldBytes===!1?yield s:yield*s,yield*o}()}return r}}}var Ve=class extends Error{code;constructor(t,e){super(t),this.code=e}};function Ns(r,t={}){let e=Rs(r,t);t.maxDataLength!=null&&t.maxLengthLength==null&&(t.maxLengthLength=S(t.maxDataLength));let n=t?.lengthDecoder??H,s=t?.lengthEncoder??Y;return{read:async o=>{let a=-1,c=new G;for(;;){c.append(await e.read(1,o));try{a=n(c)}catch(l){if(l instanceof RangeError)continue;throw l}if(t?.maxLengthLength!=null&&c.byteLength>t.maxLengthLength)throw new Ve("message length length too long","ERR_MSG_LENGTH_TOO_LONG");if(a>-1)break}if(t?.maxDataLength!=null&&a>t.maxDataLength)throw new Ve("message length too long","ERR_MSG_DATA_TOO_LONG");return e.read(a,o)},write:async(o,a)=>{await e.write(new G(s(o.byteLength),o),a)},writeV:async(o,a)=>{let c=new G(...o.flatMap(l=>[s(l.byteLength),l]));await e.write(c,a)},unwrap:()=>e.unwrap()}}function Aa(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 He=Aa;function ka(r){return r[Symbol.asyncIterator]!=null}function Ia(r,t){if(ka(r))return async function*(){for await(let a of r)yield t(a)}();let e=He(r),{value:n,done:s}=e.next();if(s===!0)return function*(){}();let i=t(n);if(typeof i.then=="function")return async function*(){yield await i;for await(let a of e)yield t(a)}();let o=t;return function*(){yield i;for(let a of e)yield o(a)}()}var Et=Ia;function La(r){return r[Symbol.asyncIterator]!=null}function Ca(...r){let t=[];for(let e of r)La(e)||t.push(e);return t.length===r.length?function*(){for(let e of t)yield*e}():async function*(){let e=Ft({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 qe=Ca;function re(r,...t){if(r==null)throw new Error("Empty pipeline");if(an(r)){let n=r;r=()=>n.source}else if(Ms(r)||Us(r)){let n=r;r=()=>n}let e=[r,...t];if(e.length>1&&an(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++)an(e[n])&&(e[n]=Ta(e[n]));return Da(...e)}var Da=(...r)=>{let t;for(;r.length>0;)t=r.shift()(t);return t},Us=r=>r?.[Symbol.asyncIterator]!=null,Ms=r=>r?.[Symbol.iterator]!=null,an=r=>r==null?!1:r.sink!=null&&r.source!=null,Ta=r=>t=>{let e=r.sink(t);if(e?.then!=null){let n=Ft({objectMode:!0});e.then(()=>{n.end()},o=>{n.end(o)});let s,i=r.source;if(Us(i))s=async function*(){yield*i,n.end()};else if(Ms(i))s=function*(){yield*i,n.end()};else throw new Error("Unknown duplex source type - must be Iterable or AsyncIterable");return qe(n,s())}return r.source};function Fa(r){return r[Symbol.asyncIterator]!=null}function _a(r,t){return Fa(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 Bs=_a;var vt=class extends Event{constructor(t,e){super(t),this.detail=e}};var ne="/ipfs/bitswap/1.2.0";var cn=new Float32Array([-0]),mt=new Uint8Array(cn.buffer);function Os(r,t,e){cn[0]=r,t[e]=mt[0],t[e+1]=mt[1],t[e+2]=mt[2],t[e+3]=mt[3]}function $s(r,t){return mt[0]=r[t],mt[1]=r[t+1],mt[2]=r[t+2],mt[3]=r[t+3],cn[0]}var ln=new Float64Array([-0]),U=new Uint8Array(ln.buffer);function zs(r,t,e){ln[0]=r,t[e]=U[0],t[e+1]=U[1],t[e+2]=U[2],t[e+3]=U[3],t[e+4]=U[4],t[e+5]=U[5],t[e+6]=U[6],t[e+7]=U[7]}function Vs(r,t){return U[0]=r[t],U[1]=r[t+1],U[2]=r[t+2],U[3]=r[t+3],U[4]=r[t+4],U[5]=r[t+5],U[6]=r[t+6],U[7]=r[t+7],ln[0]}var Pa=BigInt(Number.MAX_SAFE_INTEGER),Ra=BigInt(Number.MIN_SAFE_INTEGER),Q=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 St;if(t<Pa&&t>Ra)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>Hs&&(s=0n,++n>Hs&&(n=0n))),new r(Number(s),Number(n))}static fromNumber(t){if(t===0)return St;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):St}},St=new Q(0,0);St.toBigInt=function(){return 0n};St.zzEncode=St.zzDecode=function(){return this};St.length=function(){return 1};var Hs=4294967296n;function qs(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 Ws(r,t,e){if(e-t<1)return"";let s,i=[],o=0,a;for(;t<e;)a=r[t++],a<128?i[o++]=a:a>191&&a<224?i[o++]=(a&31)<<6|r[t++]&63:a>239&&a<365?(a=((a&7)<<18|(r[t++]&63)<<12|(r[t++]&63)<<6|r[t++]&63)-65536,i[o++]=55296+(a>>10),i[o++]=56320+(a&1023)):i[o++]=(a&15)<<12|(r[t++]&63)<<6|r[t++]&63,o>8191&&((s??(s=[])).push(String.fromCharCode.apply(String,i)),o=0);return s!=null?(o>0&&s.push(String.fromCharCode.apply(String,i.slice(0,o))),s.join("")):String.fromCharCode.apply(String,i.slice(0,o))}function un(r,t,e){let n=e,s,i;for(let o=0;o<r.length;++o)s=r.charCodeAt(o),s<128?t[e++]=s:s<2048?(t[e++]=s>>6|192,t[e++]=s&63|128):(s&64512)===55296&&((i=r.charCodeAt(o+1))&64512)===56320?(s=65536+((s&1023)<<10)+(i&1023),++o,t[e++]=s>>18|240,t[e++]=s>>12&63|128,t[e++]=s>>6&63|128,t[e++]=s&63|128):(t[e++]=s>>12|224,t[e++]=s>>6&63|128,t[e++]=s&63|128);return e-n}function rt(r,t){return RangeError(`index out of range: ${r.pos} + ${t??1} > ${r.len}`)}function We(r,t){return(r[t-4]|r[t-3]<<8|r[t-2]<<16|r[t-1]<<24)>>>0}var hn=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,rt(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 rt(this,4);return We(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw rt(this,4);return We(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw rt(this,4);let t=$s(this.buf,this.pos);return this.pos+=4,t}double(){if(this.pos+8>this.len)throw rt(this,4);let t=Vs(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 rt(this,t);return this.pos+=t,e===n?new Uint8Array(0):this.buf.subarray(e,n)}string(){let t=this.bytes();return Ws(t,0,t.length)}skip(t){if(typeof t=="number"){if(this.pos+t>this.len)throw rt(this,t);this.pos+=t}else do if(this.pos>=this.len)throw rt(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 Q(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 rt(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 rt(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 rt(this,8);let t=We(this.buf,this.pos+=4),e=We(this.buf,this.pos+=4);return new Q(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=zr(this.buf,this.pos);return this.pos+=S(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 fn(r){return new hn(r instanceof Uint8Array?r:r.subarray())}function At(r,t,e){let n=fn(r);return t.decode(n,void 0,e)}function dn(r){let t=r??8192,e=t>>>1,n,s=t;return function(o){if(o<1||o>e)return R(o);s+o>t&&(n=R(t),s=0);let a=n.subarray(s,s+=o);return s&7&&(s=(s|7)+1),a}}var kt=class{fn;len;next;val;constructor(t,e,n){this.fn=t,this.len=e,this.next=void 0,this.val=n}};function pn(){}var gn=class{head;tail;len;next;constructor(t){this.head=t.head,this.tail=t.tail,this.len=t.len,this.next=t.states}},Na=dn();function Ua(r){return globalThis.Buffer!=null?R(r):Na(r)}var ie=class{len;head;tail;states;constructor(){this.len=0,this.head=new kt(pn,0,0),this.tail=this.head,this.states=null}_push(t,e,n){return this.tail=this.tail.next=new kt(t,e,n),this.len+=e,this}uint32(t){return this.len+=(this.tail=this.tail.next=new wn((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(Ge,10,Q.fromNumber(t)):this.uint32(t)}sint32(t){return this.uint32((t<<1^t>>31)>>>0)}uint64(t){let e=Q.fromBigInt(t);return this._push(Ge,e.length(),e)}uint64Number(t){return this._push($r,S(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=Q.fromBigInt(t).zzEncode();return this._push(Ge,e.length(),e)}sint64Number(t){let e=Q.fromNumber(t).zzEncode();return this._push(Ge,e.length(),e)}sint64String(t){return this.sint64(BigInt(t))}bool(t){return this._push(mn,1,t?1:0)}fixed32(t){return this._push(se,4,t>>>0)}sfixed32(t){return this.fixed32(t)}fixed64(t){let e=Q.fromBigInt(t);return this._push(se,4,e.lo)._push(se,4,e.hi)}fixed64Number(t){let e=Q.fromNumber(t);return this._push(se,4,e.lo)._push(se,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(Os,4,t)}double(t){return this._push(zs,8,t)}bytes(t){let e=t.length>>>0;return e===0?this._push(mn,1,0):this.uint32(e)._push(Ba,e,t)}string(t){let e=qs(t);return e!==0?this.uint32(e)._push(un,e,t):this._push(mn,1,0)}fork(){return this.states=new gn(this),this.head=this.tail=new kt(pn,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 kt(pn,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=Ua(this.len),n=0;for(;t!=null;)t.fn(t.val,e,n),n+=t.len,t=t.next;return e}};function mn(r,t,e){t[e]=r&255}function Ma(r,t,e){for(;r>127;)t[e++]=r&127|128,r>>>=7;t[e]=r}var wn=class extends kt{next;constructor(t,e){super(Ma,t,e),this.next=void 0}};function Ge(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 se(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 Ba(r,t,e){t.set(r,e)}globalThis.Buffer!=null&&(ie.prototype.bytes=function(r){let t=r.length>>>0;return this.uint32(t),t>0&&this._push(Oa,t,r),this},ie.prototype.string=function(r){let t=globalThis.Buffer.byteLength(r);return this.uint32(t),t>0&&this._push($a,t,r),this});function Oa(r,t,e){t.set(r,e)}function $a(r,t,e){r.length<40?un(r,t,e):t.utf8Write!=null?t.utf8Write(r,e):t.set(Kt(r),e)}function bn(){return new ie}function It(r,t){let e=bn();return t.encode(r,e,{lengthDelimited:!1}),e.finish()}var qt;(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"})(qt||(qt={}));function Qe(r,t,e,n){return{name:r,type:t,encode:e,decode:n}}function je(r){function t(s){if(r[s.toString()]==null)throw new Error("Invalid enum value");return r[s]}let e=function(i,o){let a=t(i);o.int32(a)},n=function(i){let o=i.int32();return t(o)};return Qe("enum",qt.VARINT,e,n)}function Lt(r,t){return Qe("message",qt.LENGTH_DELIMITED,r,t)}var I;(function(r){r.WantBlock="WantBlock",r.WantHave="WantHave"})(I||(I={}));var yn;(function(r){r[r.WantBlock=0]="WantBlock",r[r.WantHave=1]="WantHave"})(yn||(yn={}));(function(r){r.codec=()=>je(yn)})(I||(I={}));var Xe;(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),I.codec().encode(e.wantType,n)),e.sendDontHave!=null&&(n.uint32(40),n.bool(e.sendDontHave)),s.lengthDelimited!==!1&&n.ldelim()},(e,n)=>{let s={cid:O(0),priority:0},i=n==null?e.len:e.pos+n;for(;e.pos<i;){let o=e.uint32();switch(o>>>3){case 1:{s.cid=e.bytes();break}case 2:{s.priority=e.int32();break}case 3:{s.cancel=e.bool();break}case 4:{s.wantType=I.codec().decode(e);break}case 5:{s.sendDontHave=e.bool();break}default:{e.skipType(o&7);break}}}return s})),t),r.encode=e=>It(e,r.codec()),r.decode=e=>At(e,r.codec())})(Xe||(Xe={}));var Je;(function(r){let t;r.codec=()=>(t==null&&(t=Lt((e,n,s={})=>{if(s.lengthDelimited!==!1&&n.fork(),e.entries!=null)for(let i of e.entries)n.uint32(10),Xe.codec().encode(i,n);e.full!=null&&(n.uint32(16),n.bool(e.full)),s.lengthDelimited!==!1&&n.ldelim()},(e,n)=>{let s={entries:[]},i=n==null?e.len:e.pos+n;for(;e.pos<i;){let o=e.uint32();switch(o>>>3){case 1:{s.entries.push(Xe.codec().decode(e,e.uint32()));break}case 2:{s.full=e.bool();break}default:{e.skipType(o&7);break}}}return s})),t),r.encode=e=>It(e,r.codec()),r.decode=e=>At(e,r.codec())})(Je||(Je={}));var Ke;(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)=>{let s={prefix:O(0),data:O(0)},i=n==null?e.len:e.pos+n;for(;e.pos<i;){let o=e.uint32();switch(o>>>3){case 1:{s.prefix=e.bytes();break}case 2:{s.data=e.bytes();break}default:{e.skipType(o&7);break}}}return s})),t),r.encode=e=>It(e,r.codec()),r.decode=e=>At(e,r.codec())})(Ke||(Ke={}));var tt;(function(r){r.HaveBlock="HaveBlock",r.DontHaveBlock="DontHaveBlock"})(tt||(tt={}));var Ye;(function(r){r[r.HaveBlock=0]="HaveBlock",r[r.DontHaveBlock=1]="DontHaveBlock"})(Ye||(Ye={}));(function(r){r.codec=()=>je(Ye)})(tt||(tt={}));var Ze;(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&&Ye[e.type]!==0&&(n.uint32(16),tt.codec().encode(e.type,n)),s.lengthDelimited!==!1&&n.ldelim()},(e,n)=>{let s={cid:O(0),type:tt.HaveBlock},i=n==null?e.len:e.pos+n;for(;e.pos<i;){let o=e.uint32();switch(o>>>3){case 1:{s.cid=e.bytes();break}case 2:{s.type=tt.codec().decode(e);break}default:{e.skipType(o&7);break}}}return s})),t),r.encode=e=>It(e,r.codec()),r.decode=e=>At(e,r.codec())})(Ze||(Ze={}));var oe;(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),Je.codec().encode(e.wantlist,n)),e.blocks!=null)for(let i of e.blocks)n.uint32(26),Ke.codec().encode(i,n);if(e.blockPresences!=null)for(let i of e.blockPresences)n.uint32(34),Ze.codec().encode(i,n);e.pendingBytes!=null&&e.pendingBytes!==0&&(n.uint32(40),n.int32(e.pendingBytes)),s.lengthDelimited!==!1&&n.ldelim()},(e,n)=>{let s={blocks:[],blockPresences:[],pendingBytes:0},i=n==null?e.len:e.pos+n;for(;e.pos<i;){let o=e.uint32();switch(o>>>3){case 1:{s.wantlist=Je.codec().decode(e,e.uint32());break}case 3:{s.blocks.push(Ke.codec().decode(e,e.uint32()));break}case 4:{s.blockPresences.push(Ze.codec().decode(e,e.uint32()));break}case 5:{s.pendingBytes=e.int32();break}default:{e.skipType(o&7);break}}}return s})),t),r.encode=e=>It(e,r.codec()),r.decode=e=>At(e,r.codec())})(oe||(oe={}));Qs.default.formatters.B=r=>r==null?"undefined":JSON.stringify({blocks:r.blocks?.map(t=>({data:`${v(t.data,"base64").substring(0,10)}...`,prefix:v(t.prefix,"base64")})),blockPresences:r.blockPresences?.map(t=>({...t,cid:T.decode(t.cid).toString()})),wantlist:r.wantlist==null?void 0:{full:r.wantlist.full,entries:r.wantlist.entries.map(t=>({...t,cid:T.decode(t.cid).toString()}))}},null,2);var tr=class extends lt{log;libp2p;routing;protocols;running;maxInboundStreams;maxOutboundStreams;messageReceiveTimeout;registrarIds;metrics;sendQueue;messageSendTimeout;runOnTransientConnections;constructor(t,e={}){super(),this.log=t.logger.forComponent("helia:bitswap:network"),this.libp2p=t.libp2p,this.routing=t.routing,this.protocols=e.protocols??[ne],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.messageSendTimeout=e.messageSendTimeout??5e3,this.runOnTransientConnections=e.runOnTransientConnections??!1,this.metrics={blocksSent:t.libp2p.metrics?.registerCounter("ipfs_bitswap_sent_blocks_total"),dataSent:t.libp2p.metrics?.registerCounter("ipfs_bitswap_sent_data_bytes_total")},this.sendQueue=new ut({concurrency:e.messageSendConcurrency??50,metrics:t.libp2p.metrics,metricName:"ipfs_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.abort(new B("Incoming Bitswap stream timed out","ERR_TIMEOUT"))},i=AbortSignal.timeout(this.messageReceiveTimeout);K(1/0,i),i.addEventListener("abort",s),await re(e,o=>ee(o),async o=>{for await(let a of o)try{let c=oe.decode(a);this.log("incoming new bitswap %s message from %p %B",e.protocol,n.remotePeer,c),this.safeDispatchEvent("bitswap:message",{detail:{peer:n.remotePeer,message:c}}),i.removeEventListener("abort",s),i=AbortSignal.timeout(this.messageReceiveTimeout),K(1/0,i),i.addEventListener("abort",s)}catch(c){this.log.error("error reading incoming bitswap message from %p",n.remotePeer,c),e.abort(c);break}})}).catch(s=>{this.log.error("error handling incoming stream from %p",n.remotePeer,s),e.abort(s)})}async*findProviders(t,e){e?.onProgress?.(new vt("bitswap:network:find-providers",t));for await(let n of this.routing.findProviders(t,e)){if(!this.runOnTransientConnections){let s=!1;for(let i of n.multiaddrs)if(i.getPeerId()==null&&(i=i.encapsulate(`/p2p/${n.id}`)),!bs.exactMatch(i)){s=!0;break}if(!s)continue}n.protocols?.includes("transport-bitswap")!==!1&&(yield n)}}async findAndConnect(t,e){await Is(Et(Bs(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={wantlist:{full:e.wantlist?.full??!1,entries:e.wantlist?.entries??[]},blocks:e.blocks??[],blockPresences:e.blockPresences??[],pendingBytes:e.pendingBytes??0},i=ge([AbortSignal.timeout(this.messageSendTimeout),n?.signal]);K(1/0,i);try{let o=this.sendQueue.queue.find(a=>t.equals(a.options.peerId)&&a.status==="queued");if(o!=null){o.options.message=ja(o.options.message,s),await o.join({signal:i});return}await this.sendQueue.add(async a=>{let c=a?.message;if(c==null)throw new B("No message to send","ERR_NO_MESSAGE");this.log("sendMessage to %p %B",t,c),a?.onProgress?.(new vt("bitswap:network:send-wantlist",t));let l=await this.libp2p.dialProtocol(t,ne,a);try{let h=Ns(l);await h.write(oe.encode(c),a),await h.unwrap().close(a)}catch(h){a?.onProgress?.(new vt("bitswap:network:send-wantlist:error",{peer:t,error:h})),this.log.error("error sending message to %p",t,h),l.abort(h)}this._updateSentStats(c.blocks)},{peerId:t,signal:i,message:s})}finally{i.clear()}}async connectTo(t,e){if(!this.running)throw new B("Network isn't running","ERR_NOT_STARTED");e?.onProgress?.(new vt("bitswap:network:dial",t));let[n]=await Promise.all([this.libp2p.dial(t,e),nt(this.libp2p,"peer:identify",e?.signal,{filter:s=>{if(!s.detail.peerId.equals(t))return!1;if(s.detail.protocols.includes(ne))return!0;throw new B(`${t} did not support ${ne}`,"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.length)}};function ja(r,t){let e=new Map((r.wantlist?.entries??[]).map(o=>[dt.encode(o.cid),o]));for(let o of t.wantlist?.entries??[]){let a=dt.encode(o.cid),c=e.get(a);c!=null&&(c.priority>o.priority&&(o.priority=c.priority),o.cancel=o.cancel??c.cancel,o.wantType=o.wantType??c.wantType,o.sendDontHave=o.sendDontHave??c.sendDontHave),e.set(a,o)}let n=new Map(r.blockPresences.map(o=>[dt.encode(o.cid),o]));for(let o of t.blockPresences){let a=dt.encode(o.cid);n.set(a,o)}let s=new Map(r.blocks.map(o=>[dt.encode(o.data),o]));for(let o of t.blocks){let a=dt.encode(o.data);s.set(a,o)}return{wantlist:{full:r.wantlist?.full??t.wantlist?.full??!1,entries:[...e.values()]},blockPresences:[...n.values()],blocks:[...s.values()],pendingBytes:r.pendingBytes+t.pendingBytes}}var Xa=Symbol.for("nodejs.util.inspect.custom"),js=Object.values(pt).map(r=>r.decoder).reduce((r,t)=>r.or(t),pt.identity.decoder),Xs=114,Js=36,Ks=37,ae=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()})`}[Ln]=!0;toString(){return this.string==null&&(this.string=D.encode(this.multihash.bytes).slice(1)),this.string}toCID(){return T.createV1(Xs,this.multihash)}toBytes(){return this.multihash.bytes}toJSON(){return this.toString()}equals(t){if(t==null)return!1;if(t instanceof Uint8Array)return et(this.multihash.bytes,t);if(typeof t=="string")return at(t).equals(this);if(t?.multihash?.bytes!=null)return et(this.multihash.bytes,t.multihash.bytes);throw new Error("not valid Id")}[Xa](){return`PeerId(${this.toString()})`}},ce=class extends ae{type="RSA";publicKey;constructor(t){super({...t,type:"RSA"}),this.publicKey=t.publicKey}},le=class extends ae{type="Ed25519";publicKey;constructor(t){super({...t,type:"Ed25519"}),this.publicKey=t.multihash.digest}},ue=class extends ae{type="secp256k1";publicKey;constructor(t){super({...t,type:"secp256k1"}),this.publicKey=t.multihash.digest}};function at(r,t){if(t=t??js,r.charAt(0)==="1"||r.charAt(0)==="Q"){let e=gt(D.decode(`z${r}`));return r.startsWith("12D")?new le({multihash:e}):r.startsWith("16U")?new ue({multihash:e}):new ce({multihash:e})}return Ja(js.decode(r))}function Ja(r){try{let t=gt(r);if(t.code===Le.code){if(t.digest.length===Js)return new le({multihash:t});if(t.digest.length===Ks)return new ue({multihash:t})}if(t.code===bt.code)return new ce({multihash:t})}catch{return Ka(T.decode(r))}throw new Error("Supplied PeerID CID is invalid")}function Ka(r){if(r==null||r.multihash==null||r.version==null||r.version===1&&r.code!==Xs)throw new Error("Supplied PeerID CID is invalid");let t=r.multihash;if(t.code===bt.code)return new ce({multihash:r.multihash});if(t.code===Le.code){if(t.digest.length===Js)return new le({multihash:r.multihash});if(t.digest.length===Ks)return new ue({multihash:r.multihash})}throw new Error("Supplied PeerID CID is invalid")}function Wt(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 he=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 Wt(this.map.entries(),t=>[at(t[0]),t[1]])}forEach(t){this.map.forEach((e,n)=>{t(e,at(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 Wt(this.map.keys(),t=>at(t))}values(){return this.map.values()}get size(){return this.map.size}};var Ct=class r{set;constructor(t){if(this.set=new Set,t!=null)for(let e of t)this.set.add(e.toString())}get size(){return this.set.size}[Symbol.iterator](){return this.values()}add(t){this.set.add(t.toString())}clear(){this.set.clear()}delete(t){this.set.delete(t.toString())}entries(){return Wt(this.set.entries(),t=>{let e=at(t[0]);return[e,e]})}forEach(t){this.set.forEach(e=>{let n=at(e);t(n,n,this)})}has(t){return this.set.has(t.toString())}values(){return Wt(this.set.values(),t=>at(t))}intersection(t){let e=new r;for(let n of t)this.has(n)&&e.add(n);return e}difference(t){let e=new r;for(let n of this)t.has(n)||e.add(n);return e}union(t){let e=new r;for(let n of t)e.add(n);for(let n of this)e.add(n);return e}};var xn=class extends he{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 fe(r){let{name:t,metrics:e}=r,n;return e!=null?n=new xn({name:t,metrics:e}):n=new he,n}function Ya(r){let t=new Uint8Array(r.reduce((n,s)=>n+S(s),0)),e=0;for(let n of r)t=Y(n,t,e),e+=S(n);return t}var Ys=Ya;function En(r){return Ys([r.version,r.code,r.multihash.code,r.multihash.digest.byteLength])}var er=class{peerId;blockstore;network;wants;exchangeCount;bytesSent;bytesReceived;lastExchange;maxSizeReplaceHasWithBlock;constructor(t,e){this.peerId=t.peerId,this.blockstore=t.blockstore,this.network=t.network,this.wants=new Map,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={blockPresences:[],blocks:[]},n=new Set;for(let[s,i]of this.wants.entries()){if(!await this.blockstore.has(i.cid,t)){if(!i.sendDontHave||i.sentDontHave===!0)continue;i.sentDontHave=!0,e.blockPresences.push({cid:i.cid.bytes,type:tt.DontHaveBlock});continue}let a=await this.blockstore.get(i.cid,t);i.wantType===I.WantHave?a.byteLength<this.maxSizeReplaceHasWithBlock?(n.add(s),e.blocks.push({data:a,prefix:En(i.cid)})):e.blockPresences.push({cid:i.cid.bytes,type:tt.HaveBlock}):(n.add(s),e.blocks.push({data:a,prefix:En(i.cid)}))}if(e.blocks.length>0||e.blockPresences.length>0){await this.network.sendMessage(this.peerId,e,t),this.sentBytes(e.blocks.reduce((s,i)=>s+i.data.byteLength,0));for(let s of n)this.wants.delete(s)}}};var rr=class{blockstore;network;ledgerMap;maxSizeReplaceHasWithBlock;log;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.ledgerMap=fe({name:"ipfs_bitswap_ledger_map",metrics:t.libp2p.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 er({peerId:t,blockstore:this.blockstore,network:this.network},{maxSizeReplaceHasWithBlock:this.maxSizeReplaceHasWithBlock}),this.ledgerMap.set(t,n)),n.receivedBytes(e.blocks?.reduce((s,i)=>s+i.data.byteLength,0)??0),e.wantlist!=null){e.wantlist.full===!0&&n.wants.clear();for(let s of e.wantlist.entries){let i=T.decode(s.cid),o=v(i.multihash.bytes,"base64");s.cancel===!0?(this.log("peer %p cancelled want of block for %c",t,i),n.wants.delete(o)):(s.wantType===I.WantHave?this.log("peer %p wanted block presence for %c",t,i):this.log("peer %p wanted block for %c",t,i),n.wants.set(o,{cid:i,priority:s.priority,wantType:s.wantType??I.WantBlock,sendDontHave:s.sendDontHave??!1}))}}await n.sendBlocksToPeer()}async receivedBlock(t,e){let n=v(t.multihash.bytes,"base64"),s=[];for(let i of this.ledgerMap.values())i.wants.has(n)&&s.push(i);await Promise.all(s.map(async i=>i.sendBlocksToPeer(e)))}peerDisconnected(t){this.ledgerMap.delete(t)}};var vn=class{root;peers;log;wantList;network;queue;maxProviders;constructor(t,e){this.peers=new Ct,this.root=e.root,this.maxProviders=e.maxProviders,this.log=t.logger.forComponent(`helia:bitswap:session:${e.root}`),this.wantList=t.wantList,this.network=t.network,this.queue=new ut({concurrency:e.queryConcurrency}),this.queue.addEventListener("error",n=>{this.log.error("error querying peer for %c",this.root,n.detail)})}async want(t,e={}){if(this.peers.size===0)throw new B("Bitswap session had no peers","ERR_NO_SESSION_PEERS");this.log("sending WANT-BLOCK for %c to",t,this.peers);let n=await Promise.any([...this.peers].map(async s=>this.wantList.wantBlock(t,{peerId:s,...e})));return this.log("received block for %c from %p",t,n.sender),n.block}async findNewProviders(t,e,n={}){let s=_(),i=0;this.log("find %d-%d new provider(s) for %c",e,this.maxProviders,t);let o=qe([...this.wantList.peers.keys()],Et(this.network.findProviders(t,n),a=>a.id));return Promise.resolve().then(async()=>{for await(let a of o){if(i===this.maxProviders){this.queue.clear();break}await this.queue.add(async()=>{try{if(this.log("asking potential session peer %p if they have %c",a,t),!(await this.wantList.wantPresence(t,{peerId:a,...n})).has){this.log("potential session peer %p did not have %c",a,t);return}this.log("potential session peer %p had %c",a,t),i++,this.peers.add(a),i===e&&(this.log("found %d session peers",i),s.resolve()),i===this.maxProviders&&(this.log("found max provider session peers",i),this.queue.clear())}catch(c){this.log.error("error querying potential session peer %p for %c",a,t,c.errors??c)}},{peerId:a})}this.log("found %d session peers total",i),e>0&&s.reject(new B(`Found ${i} of ${e} providers`,"ERR_NO_PROVIDERS_FOUND"))}),s.promise}};async function Zs(r,t){let e=new vn(r,t);return await e.findNewProviders(t.root,t.minProviders,{signal:t.signal}),e}var nr=class{blocksReceived;duplicateBlocksReceived;dataReceived;duplicateDataReceived;constructor(t){this.blocksReceived=t.libp2p.metrics?.registerMetricGroup("ipfs_bitswap_received_blocks"),this.duplicateBlocksReceived=t.libp2p.metrics?.registerMetricGroup("ipfs_bitswap_duplicate_received_blocks"),this.dataReceived=t.libp2p.metrics?.registerMetricGroup("ipfs_bitswap_data_received_bytes"),this.duplicateDataReceived=t.libp2p.metrics?.registerMetricGroup("ipfs_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 Sn=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 ti(r){let{name:t,metrics:e}=r,n;return e!=null?n=new Sn({name:t,metrics:e}):n=new Map,n}function Za(r){return r[Symbol.asyncIterator]!=null}function tc(r){if(Za(r))return(async()=>{let e=[];for await(let n of r)e.push(n);return e})();let t=[];for(let e of r)t.push(e);return t}var An=tc;function ec(r){return r[Symbol.asyncIterator]!=null}function rc(r,t){if(ec(r))return async function*(){for await(let a of r)await t(a)&&(yield a)}();let e=He(r),{value:n,done:s}=e.next();if(s===!0)return function*(){}();let i=t(n);if(typeof i.then=="function")return async function*(){await i&&(yield n);for await(let a of e)await t(a)&&(yield a)}();let o=t;return function*(){i===!0&&(yield n);for(let a of e)o(a)&&(yield a)}()}var sr=rc;function nc(r){if(!(r instanceof Uint8Array))throw new Error("arg needs to be a Uint8Array");let t=[];for(;r.length>0;){let e=H(r);t.push(e),r=r.slice(S(e))}return t}var ei=nc;var ir=class extends lt{peers;wants;network;log;sendMessagesDelay;sendMessagesTimeout;hashLoader;sendingMessages;constructor(t,e={}){super(),K(1/0,this),this.peers=fe({name:"ipfs_bitswap_peers",metrics:t.libp2p.metrics}),this.wants=ti({name:"ipfs_bitswap_wantlist",metrics:t.libp2p.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=v(t.multihash.bytes,"base64"),s=this.wants.get(n);s==null&&(s={cid:t,session:new Ct,priority:e.priority??1,wantType:e.wantType??I.WantBlock,cancel:!1,sendDontHave:!0},e.peerId!=null&&s.session.add(e.peerId),this.wants.set(n,s)),s.wantType===I.WantHave&&e.wantType===I.WantBlock&&(s.wantType=I.WantBlock),s.session.size>0&&(e.peerId!=null&&s.session.add(e.peerId),e.peerId==null&&s.session.clear()),await this.sendMessagesDebounced();try{return e.wantType===I.WantBlock?(await nt(this,"block",e?.signal,{filter:a=>et(t.multihash.digest,a.detail.cid.multihash.digest),errorMessage:"Want was aborted"})).detail:(await nt(this,"presence",e?.signal,{filter:o=>et(t.multihash.digest,o.detail.cid.multihash.digest),errorMessage:"Want was aborted"})).detail}finally{e.signal?.aborted===!0&&(this.log("want for %c was aborted, cancelling want",t),s.cancel=!0,await this.sendMessagesDebounced())}}async sendMessagesDebounced(){await this.sendingMessages?.promise,clearTimeout(this.sendMessagesTimeout),this.sendMessagesTimeout=setTimeout(()=>{this.sendMessages().catch(t=>{this.log("error sending messages to peers",t)})},this.sendMessagesDelay)}async sendMessages(){this.sendingMessages=_(),await Promise.all([...this.peers.entries()].map(async([t,e])=>{let n=new Set,s={wantlist:{full:!1,entries:re(this.wants.entries(),i=>sr(i,([o,a])=>{if(a.session.size>0&&!a.session.has(t))return!1;let c=e.has(o);return a.cancel?c:!c}),i=>Et(i,([o,a])=>(n.add(o),{cid:a.cid.bytes,priority:a.priority,wantType:a.wantType,cancel:a.cancel,sendDontHave:a.sendDontHave})),i=>An(i))}};if(s.wantlist?.entries.length!==0)try{await this.network.sendMessage(t,s);for(let i of n)e.add(i)}catch(i){this.log.error("error sending full wantlist to new peer",i)}})).catch(t=>{this.log.error("error sending messages",t)});for(let[t,e]of this.wants)if(e.cancel){this.wants.delete(t);for(let n of this.peers.values())n.delete(t)}this.sendingMessages.resolve()}has(t){let e=v(t.multihash.bytes,"base64");return this.wants.has(e)}async wantPresence(t,e={}){if(e.peerId!=null){let n=e.peerId;return await this.network.sendMessage(e.peerId,{wantlist:{full:!1,entries:[{cid:t.bytes,sendDontHave:!0,wantType:I.WantHave,priority:1}]}}),(await nt(this,"presence",e.signal,{filter:i=>n.equals(i.detail.sender)&&et(t.multihash.digest,i.detail.cid.multihash.digest)})).detail}return this.addEntry(t,{...e,wantType:I.WantHave})}async wantBlock(t,e={}){return this.addEntry(t,{...e,wantType:I.WantBlock})}async receivedBlock(t,e){let n=v(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",t);let n=!1;for(let s of e.blocks){if(s.prefix==null||s.data==null)continue;let i=ei(s.prefix),o=i[0],a=i[1],c=i[2],l=c===bt.code?bt:await this.hashLoader?.getHasher(c);if(l==null){this.log.error("unknown hash algorithm",c);continue}let h=await l.digest(s.data),u=T.create(o===0?0:1,a,h);this.log("received block from %p for %c",t,u),this.safeDispatchEvent("block",{detail:{sender:t,cid:u,block:s.data}}),this.safeDispatchEvent("presence",{detail:{sender:t,cid:u,has:!0,block:s.data}});let f=v(u.multihash.bytes,"base64"),m=this.wants.get(f);if(m==null)return;m.cancel=!0,n=!0}for(let{cid:s,type:i}of e.blockPresences){let o=T.decode(s);this.log("received %s from %p for %c",i,t,o),this.safeDispatchEvent("presence",{detail:{sender:t,cid:o,has:i===tt.HaveBlock}})}n&&await this.sendMessagesDebounced()}async peerConnected(t){let e=new Set,n={wantlist:{full:!0,entries:re(this.wants.entries(),s=>sr(s,([i,o])=>!o.cancel&&o.session.size>0&&!o.session.has(t)),s=>sr(s,([i,o])=>!o.cancel),s=>Et(s,([i,o])=>(e.add(i),{cid:o.cid.bytes,priority:1,wantType:I.WantBlock,cancel:!1,sendDontHave:!1})),s=>An(s))}};if(n.wantlist?.entries.length===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()}};var or=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 nr(t),this.network=new tr(t,e),this.peerWantLists=new rr({...t,network:this.network},e),this.wantList=new ir({...t,network:this.network},e)}async createSession(t,e){let n=e?.minProviders??1,s=e?.maxProviders??5;return Zs({wantList:this.wantList,network:this.network,logger:this.logger},{root:t,queryConcurrency:e?.providerQueryConcurrency??5,minProviders:n,maxProviders:s,connectedPeers:e?.queryConnectedPeers!==!1?[...this.wantList.peers.keys()]:[],signal:e?.signal})}async want(t,e={}){let n=new AbortController,s=ge([n.signal,e.signal]);K(1/0,n.signal,s),this.network.findAndConnect(t,{...e,signal:s}).catch(i=>{n.signal.aborted||this.log.error("error during finding and connect for cid %c",t,i)});try{return(await this.wantList.wantBlock(t,{...e,signal:s})).block}finally{n.abort(),s.clear()}}async notify(t,e,n={}){await Promise.all([this.peerWantLists.receivedBlock(t,n),this.wantList.receivedBlock(t,n)])}getWantlist(){return[...this.wantList.wants.values()].filter(t=>!t.cancel).map(t=>({cid:t.cid,priority:t.priority,wantType:t.wantType}))}getPeerWantlist(t){return this.peerWantLists.wantListForPeer(t)}async start(){this.wantList.start(),await this.network.start()}async stop(){this.wantList.stop(),await this.network.stop()}};var ri=(r,t={})=>new or(r,t);var kn=class{bitswap;started;constructor(t,e={}){let{hashers:n}=t;this.bitswap=ri(t,{hashLoader:{getHasher:async s=>{let i;if(typeof s=="string"?i=Object.values(n).find(o=>o.name===s):i=n[s],i!=null)return i;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)}async createSession(t,e){let n=await this.bitswap.createSession(t,e);return{announce:async(s,i,o)=>{await this.bitswap.notify(s,i,o)},retrieve:async(s,i)=>n.want(s,i)}}};function ni(r={}){return t=>new kn(t,r)}var ii=cr(si(),1),ac=["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"],cc=ac.map(r=>new ii.Netmask(r));function lc(r){for(let t of cc)if(t.contains(r))return!0;return!1}function uc(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 oi(r){return Pt(r)?lc(r):Rt(r)?uc(r):void 0}var hc=[g("tcp").code,g("dns").code,g("dnsaddr").code,g("dns4").code,g("dns6").code];function ai(r){let t;try{t=g("sni").code}catch{return null}for(let[e,n]of r)if(e===t&&n!==void 0)return n;return null}function ci(r){return r.some(([t,e])=>t===g("tls").code)}function j(r,t,e){let n=li[g(r).name];if(n===void 0)throw new Error(`Can't interpret protocol ${g(r).name}`);let s=n(t,e);return r===g("ip6").code?`[${s}]`:s}var li={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://${j(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://${j(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`${j(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`${j(e[0],e[1]??"",t)}/p2p/${r}`},http:(r,t)=>{let e=ci(t),n=ai(t);if(e&&n!==null)return`https://${n}`;let s=e?"https://":"http://",i=t.pop();if(i===void 0)throw new Error("Unexpected end of multiaddr");let o=j(i[0],i[1]??"",t);return o=o.replace("tcp://",""),`${s}${o}`},tls:(r,t)=>{let e=t.pop();if(e===void 0)throw new Error("Unexpected end of multiaddr");return j(e[0],e[1]??"",t)},sni:(r,t)=>{let e=t.pop();if(e===void 0)throw new Error("Unexpected end of multiaddr");return j(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=j(e[0],e[1]??"",t);return n=n.replace("tcp://",""),`https://${n}`},ws:(r,t)=>{let e=ci(t),n=ai(t);if(e&&n!==null)return`wss://${n}`;let s=e?"wss://":"ws://",i=t.pop();if(i===void 0)throw new Error("Unexpected end of multiaddr");let o=j(i[0],i[1]??"",t);return o=o.replace("tcp://",""),`${s}${o}`},wss:(r,t)=>{let e=t.pop();if(e===void 0)throw new Error("Unexpected end of multiaddr");let n=j(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`${j(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`${j(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`${j(e[0],e[1]??"",t)}/p2p-webrtc-direct`}};function ui(r,t){let n=Yt(r).stringTuples(),s=n.pop();if(s===void 0)throw new Error("Unexpected end of multiaddr");let i=g(s[0]),o=li[i.name];if(o==null)throw new Error(`No interpreter found for ${i.name}`);let a=o(s[1]??"",n);return t?.assumeHttp!==!1&&hc.includes(s[0])&&(a=a.replace(/^.*:\/\//,""),s[1]==="443"?a=`https://${a}`:a=`http://${a}`),(a.startsWith("http://")||a.startsWith("https://"))&&(a=new URL(a).toString(),a.endsWith("/")&&(a=a.substring(0,a.length-1))),a}var pe=class{url;#t=0;#e=0;#r=0;#n=0;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}`)}async getRawBlock(t,e){let n=this.url;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`);try{this.#t++;let s=await fetch(n.toString(),{signal:e,headers:{Accept:"application/vnd.ipld.raw"},cache:"force-cache"});if(this.log("GET %s %d",n,s.status),!s.ok)throw this.#e++,new Error(`unable to fetch raw block for CID ${t} from gateway ${this.url}`);return this.#n++,new Uint8Array(await s.arrayBuffer())}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}`))}}reliability(){return this.#t===0?1:this.#r>0?-1/0:this.#n/(this.#t+this.#e*3)}incrementInvalidBlocks(){this.#r++}};var ar=class r{components;gateways;routing;log;constructor(t,e={}){this.components=t,this.log=t.logger.forComponent("helia:trustless-gateway-block-broker"),this.routing=t.routing,this.gateways=(e.gateways??hi).map(n=>new pe(n,t.logger))}addGateway(t){this.gateways.push(new pe(t,this.components.logger))}async retrieve(t,e={}){let n=this.gateways.sort((i,o)=>o.reliability()-i.reliability()),s=[];for(let i of n){this.log("getting block for %c from %s",t,i.url);try{let o=await i.getRawBlock(t,e.signal);this.log.trace("got block for %c from %s",t,i.url);try{await e.validateFn?.(o)}catch(a){throw this.log.error("failed to validate block for %c from %s",t,i.url,a),i.incrementInvalidBlocks(),new Error(`Block for CID ${t} from gateway ${i.url} failed validation`)}return o}catch(o){if(this.log.error("failed to get block for %c from %s",t,i.url,o),o instanceof Error?s.push(o):s.push(new Error(`Unable to fetch raw block for CID ${t} from gateway ${i.url}`)),e.signal?.aborted===!0){this.log.trace("request aborted while fetching raw block for CID %c from gateway %s",t,i.url);break}}}throw s.length>0?new AggregateError(s,`Unable to fetch raw block for CID ${t} from any gateway`):new Error(`Unable to fetch raw block for CID ${t} from any gateway`)}async createSession(t,e={}){let n=[],s=e.minProviders??1,i=e.minProviders??5,o=_(),a=new r(this.components,{gateways:n});this.log("finding transport-ipfs-gateway-http providers for cid %c",t);let c=new ut({concurrency:e.providerQueryConcurrency??5});return Promise.resolve().then(async()=>{for await(let l of this.routing.findProviders(t,e)){let h=l.multiaddrs.filter(u=>xs.matches(u)||e.allowInsecure===!0&&ys.matches(u)?e.allowLocal===!0||us.matches(u)?!0:oi(u.toOptions().host)===!1:!1);h.length!==0&&(this.log("found transport-ipfs-gateway-http provider %p for cid %c",l.id,t),c.add(async()=>{for(let u of h){let f;try{f=ui(u);let m=`${f}/ipfs/${t.toString()}?format=raw`,p=await fetch(m,{method:"HEAD",headers:{Accept:"application/vnd.ipld.raw","Cache-Control":e.cacheControl??"only-if-cached"},signal:AbortSignal.timeout(e.providerQueryTimeout??5e3)});this.log("HEAD %s %d",m,p.status),n.push(f),a.addGateway(f),this.log("found %d transport-ipfs-gateway-http providers for cid %c",n.length,t),n.length===s&&o.resolve(a),n.length===i&&c.clear()}catch(m){this.log.error("could not fetch %c from %a",t,f??u,m)}}}))}}).catch(l=>{this.log.error("error creating session for %c",t,l)}),o.promise}};var hi=["https://trustless-gateway.link","https://cloudflare-ipfs.com","https://4everland.io"];function fi(r={}){return t=>new ar(t,r)}return bi(fc);})();
|
|
3
3
|
return HeliaBlockBrokers}));
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@helia/block-brokers",
|
|
3
|
-
"version": "2.0.3-
|
|
3
|
+
"version": "2.0.3-9c8a2c0",
|
|
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,8 +53,8 @@
|
|
|
53
53
|
"test:electron-main": "aegir test -t electron-main"
|
|
54
54
|
},
|
|
55
55
|
"dependencies": {
|
|
56
|
-
"@helia/bitswap": "0.0.0-
|
|
57
|
-
"@helia/interface": "4.1.0-
|
|
56
|
+
"@helia/bitswap": "0.0.0-9c8a2c0",
|
|
57
|
+
"@helia/interface": "4.1.0-9c8a2c0",
|
|
58
58
|
"@libp2p/interface": "^1.1.4",
|
|
59
59
|
"@libp2p/utils": "^5.2.6",
|
|
60
60
|
"@multiformats/multiaddr-matcher": "^1.2.0",
|