@helia/block-brokers 4.0.4 → 4.1.0-313e2c1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.min.js +1 -1
- package/dist/src/trustless-gateway/broker.d.ts +6 -0
- package/dist/src/trustless-gateway/broker.d.ts.map +1 -1
- package/dist/src/trustless-gateway/broker.js +5 -2
- package/dist/src/trustless-gateway/broker.js.map +1 -1
- package/dist/src/trustless-gateway/index.d.ts +5 -0
- package/dist/src/trustless-gateway/index.d.ts.map +1 -1
- package/dist/src/trustless-gateway/index.js.map +1 -1
- package/dist/src/trustless-gateway/session.d.ts +1 -0
- package/dist/src/trustless-gateway/session.d.ts.map +1 -1
- package/dist/src/trustless-gateway/session.js +3 -1
- package/dist/src/trustless-gateway/session.js.map +1 -1
- package/dist/src/trustless-gateway/trustless-gateway.d.ts +9 -1
- package/dist/src/trustless-gateway/trustless-gateway.d.ts.map +1 -1
- package/dist/src/trustless-gateway/trustless-gateway.js +7 -3
- package/dist/src/trustless-gateway/trustless-gateway.js.map +1 -1
- package/dist/src/trustless-gateway/utils.d.ts +5 -2
- package/dist/src/trustless-gateway/utils.d.ts.map +1 -1
- package/dist/src/trustless-gateway/utils.js +2 -2
- package/dist/src/trustless-gateway/utils.js.map +1 -1
- package/package.json +5 -5
- package/src/trustless-gateway/broker.ts +10 -2
- package/src/trustless-gateway/index.ts +5 -0
- package/src/trustless-gateway/session.ts +4 -2
- package/src/trustless-gateway/trustless-gateway.ts +18 -3
- package/src/trustless-gateway/utils.ts +7 -3
- package/dist/typedoc-urls.json +0 -9
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 go=Object.create;var he=Object.defineProperty;var wo=Object.getOwnPropertyDescriptor;var bo=Object.getOwnPropertyNames;var yo=Object.getPrototypeOf,xo=Object.prototype.hasOwnProperty;var Bn=(r,t)=>()=>(t||r((t={exports:{}}).exports,t),t.exports),z=(r,t)=>{for(var e in t)he(r,e,{get:t[e],enumerable:!0})},Rn=(r,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of bo(t))!xo.call(r,s)&&s!==e&&he(r,s,{get:()=>t[s],enumerable:!(n=wo(t,s))||n.enumerable});return r};var zn=(r,t,e)=>(e=r!=null?go(yo(r)):{},Rn(t||!r||!r.__esModule?he(e,"default",{value:r,enumerable:!0}):e,r)),Eo=r=>Rn(he({},"__esModule",{value:!0}),r);var Ps=Bn((Ef,Ds)=>{Ds.exports=function(r){if(!r)throw Error("hashlru must have a max value, of type number, greater than 0");var t=0,e=Object.create(null),n=Object.create(null);function s(o,i){e[o]=i,t++,t>=r&&(t=0,n=e,e=Object.create(null))}return{has:function(o){return e[o]!==void 0||n[o]!==void 0},remove:function(o){e[o]!==void 0&&(e[o]=void 0),n[o]!==void 0&&(n[o]=void 0)},get:function(o){var i=e[o];if(i!==void 0)return i;if((i=n[o])!==void 0)return s(o,i),i},set:function(o,i){e[o]!==void 0?e[o]=i:s(o,i)},clear:function(){e=Object.create(null),n=Object.create(null)}}}});var Rs=Bn(oe=>{(function(){var r,t,e,n,s,o,i,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(".")},i=function(c){var l,h,u,f,m,d;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)}d=t(c),m=d[0],h=d[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"),o=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])-o)>>>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,d;if(typeof l!="string")throw new Error("Missing `net' parameter");if(h||(d=l.split("/",2),l=d[0],h=d[1]),h||(h=32),typeof h=="string"&&h.indexOf(".")>-1){try{this.maskLong=i(h)}catch(v){throw u=v,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=(i(l)&this.maskLong)>>>0}catch(v){throw u=v,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):(i(l)&this.maskLong)>>>0===(this.netLong&this.maskLong)>>>0},c.prototype.next=function(l){return l==null&&(l=1),new c(a(this.netLong+this.size*l),this.mask)},c.prototype.forEach=function(l){var h,u,f;for(f=i(this.first),u=i(this.last),h=0;f<=u;)l(a(f),f,h),h++,f++},c.prototype.toString=function(){return this.base+"/"+this.bitmask},c}(),oe.ip2long=i,oe.long2ip=a,oe.Netmask=r}).call(oe)});var lc={};z(lc,{bitswap:()=>Ns,trustlessGateway:()=>mo});var nt=class extends Error{static name="AbortError";constructor(t="The operation was aborted"){super(t),this.name="AbortError"}};var fe=class extends Error{static name="InvalidParametersError";constructor(t="Invalid parameters"){super(t),this.name="InvalidParametersError"}};var de=class extends Error{static name="UnsupportedProtocolError";constructor(t="Unsupported protocol error"){super(t),this.name="UnsupportedProtocolError"}};var pe=class extends Error{static name="TimeoutError";constructor(t="Timed out"){super(t),this.name="TimeoutError"}},me=class extends Error{static name="NotStartedError";constructor(t="Not started"){super(t),this.name="NotStartedError"}};var Y=class extends EventTarget{#t=new Map;constructor(){super()}listenerCount(t){let e=this.#t.get(t);return e==null?0:e.length}addEventListener(t,e,n){super.addEventListener(t,e,n);let s=this.#t.get(t);s==null&&(s=[],this.#t.set(t,s)),s.push({callback:e,once:(n!==!0&&n!==!1&&n?.once)??!1})}removeEventListener(t,e,n){super.removeEventListener(t.toString(),e??null,n);let s=this.#t.get(t);s!=null&&(s=s.filter(({callback:o})=>o!==e),this.#t.set(t,s))}dispatchEvent(t){let e=super.dispatchEvent(t),n=this.#t.get(t.type);return n==null||(n=n.filter(({once:s})=>!s),this.#t.set(t.type,n)),e}safeDispatchEvent(t,e={}){return this.dispatchEvent(new CustomEvent(t,e))}};function On(r){let t=new globalThis.AbortController;function e(){t.abort();for(let o of r)o?.removeEventListener!=null&&o.removeEventListener("abort",e)}for(let o of r){if(o?.aborted===!0){e();break}o?.addEventListener!=null&&o.addEventListener("abort",e)}function n(){for(let o of r)o?.removeEventListener!=null&&o.removeEventListener("abort",e)}let s=t.signal;return s.clear=n,s}function G(){let r={};return r.promise=new Promise((t,e)=>{r.resolve=t,r.reject=e}),r}var ge=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}},kt=class{size;hwm;head;tail;constructor(t={}){this.hwm=t.splitLimit??16,this.head=new ge(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 ge(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 At(r={}){return vo(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 vo(r,t){t=t??{};let e=t.onEnd,n=new kt,s,o,i,a=G(),c=async()=>{try{return n.isEmpty()?i?{done:!0}:await new Promise((g,L)=>{o=B=>{o=null,n.push(B);try{g(r(n))}catch(T){L(T)}return s}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=G()})}},l=g=>o!=null?o(g):(n.push(g),s),h=g=>(n=new kt,o!=null?o({error:g}):(n.push({error:g}),s)),u=g=>{if(i)return s;if(t?.objectMode!==!0&&g?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return l({done:!1,value:g})},f=g=>i?s:(i=!0,g!=null?h(g):l({done:!0})),m=()=>(n=new kt,f(),{done:!0}),d=g=>(f(g),{done:!0});if(s={[Symbol.asyncIterator](){return this},next:c,return:m,throw:d,push:u,end:f,get readableLength(){return n.size},onEmpty:async g=>{let L=g?.signal;if(L?.throwIfAborted(),n.isEmpty())return;let B,T;L!=null&&(B=new Promise((R,V)=>{T=()=>{V(new ur)},L.addEventListener("abort",T)}));try{await Promise.race([a.promise,B])}finally{T!=null&&L!=null&&L?.removeEventListener("abort",T)}}},e==null)return s;let v=s;return s={[Symbol.asyncIterator](){return this},next(){return v.next()},throw(g){return v.throw(g),e!=null&&(e(g),e=void 0),{done:!0}},return(){return v.return(),e!=null&&(e(),e=void 0),{done:!0}},push:u,end(g){return v.end(g),e!=null&&(e(g),e=void 0),s},get readableLength(){return v.readableLength},onEmpty:g=>v.onEmpty(g)},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 X(r,t,e,n){let s=new hr(n?.errorMessage,n?.errorCode);return e?.aborted===!0?Promise.reject(s):new Promise((o,i)=>{function a(){e?.removeEventListener("abort",h),r.removeEventListener(t,c),n?.errorEvent!=null&&r.removeEventListener(n.errorEvent,l)}let c=u=>{try{if(n?.filter?.(u)===!1)return}catch(f){a(),i(f);return}a(),o(u)},l=u=>{a(),i(u.detail)},h=()=>{a(),i(s)};e?.addEventListener("abort",h),r.addEventListener(t,c),n?.errorEvent!=null&&r.addEventListener(n.errorEvent,l)})}var we=class extends Error{static name="QueueFullError";constructor(t="The queue was full"){super(t),this.name="QueueFullError"}};var be=class extends Error{type;code;constructor(t,e,n){super(t??"The operation was aborted"),this.type="aborted",this.name=n??"AbortError",this.code=e??"ABORT_ERR"}};async function $n(r,t,e){if(t==null)return r;if(t.aborted)return Promise.reject(new be(e?.errorMessage,e?.errorCode,e?.errorName));let n,s=new be(e?.errorMessage,e?.errorCode,e?.errorName);try{return await Promise.race([r,new Promise((o,i)=>{n=()=>{i(s)},t.addEventListener("abort",n)})])}finally{n!=null&&t.removeEventListener("abort",n)}}var ye=class{deferred;signal;constructor(t){this.signal=t,this.deferred=G(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new nt)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function _o(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var xe=class{id;fn;options;recipients;status;timeline;controller;constructor(t,e){this.id=_o(),this.status="queued",this.fn=t,this.options=e,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,this.controller.signal,this.onAbort=this.onAbort.bind(this)}abort(t){this.controller.abort(t)}onAbort(){this.recipients.reduce((e,n)=>e&&n.signal?.aborted===!0,!0)&&(this.controller.abort(new nt),this.cleanup())}async join(t={}){let e=new ye(t.signal);return this.recipients.push(e),t.signal?.addEventListener("abort",this.onAbort),e.deferred.promise}async run(){this.status="running",this.timeline.started=Date.now();try{this.controller.signal.throwIfAborted();let t=await $n(this.fn({...this.options??{},signal:this.controller.signal}),this.controller.signal);this.recipients.forEach(e=>{e.deferred.resolve(t)}),this.status="complete"}catch(t){this.recipients.forEach(e=>{e.deferred.reject(t)}),this.status="errored"}finally{this.timeline.finished=Date.now(),this.cleanup()}}cleanup(){this.recipients.forEach(t=>{t.cleanup(),t.signal?.removeEventListener("abort",this.onAbort)})}};var It=class extends Y{concurrency;maxSize;queue;pending;sort;constructor(t={}){super(),this.concurrency=t.concurrency??Number.POSITIVE_INFINITY,this.maxSize=t.maxSize??Number.POSITIVE_INFINITY,this.pending=0,t.metricName!=null&&t.metrics?.registerMetricGroup(t.metricName,{calculate:()=>({size:this.queue.length,running:this.pending,queued:this.queue.length-this.pending})}),this.sort=t.sort,this.queue=[]}tryToStartAnother(){if(this.size===0)return queueMicrotask(()=>{this.safeDispatchEvent("empty")}),this.running===0&&queueMicrotask(()=>{this.safeDispatchEvent("idle")}),!1;if(this.pending<this.concurrency){let t;for(let e of this.queue)if(e.status==="queued"){t=e;break}return t==null?!1:(this.safeDispatchEvent("active"),this.pending++,t.run().finally(()=>{for(let e=0;e<this.queue.length;e++)if(this.queue[e]===t){this.queue.splice(e,1);break}this.pending--,this.tryToStartAnother(),this.safeDispatchEvent("next")}),!0)}return!1}enqueue(t){this.queue.push(t),this.sort!=null&&this.queue.sort(this.sort)}async add(t,e){if(e?.signal?.throwIfAborted(),this.size===this.maxSize)throw new we;let n=new xe(t,e);return this.enqueue(n),this.safeDispatchEvent("add"),this.tryToStartAnother(),n.join(e).then(s=>(this.safeDispatchEvent("completed",{detail:s}),this.safeDispatchEvent("success",{detail:{job:n,result:s}}),s)).catch(s=>{if(n.status==="queued"){for(let o=0;o<this.queue.length;o++)if(this.queue[o]===n){this.queue.splice(o,1);break}}throw this.safeDispatchEvent("error",{detail:s}),this.safeDispatchEvent("failure",{detail:{job:n,error:s}}),s})}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(t=>{t.abort(new nt)}),this.clear()}async onEmpty(t){this.size!==0&&await X(this,"empty",t?.signal)}async onSizeLessThan(t,e){this.size<t||await X(this,"next",e?.signal,{filter:()=>this.size<t})}async onIdle(t){this.pending===0&&this.size===0||await X(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=At({objectMode:!0}),n=c=>{c!=null?this.abort():this.clear(),e.end(c)},s=c=>{c.detail!=null&&e.push(c.detail)},o=c=>{n(c.detail)},i=()=>{n()},a=()=>{n(new nt("Queue aborted"))};this.addEventListener("completed",s),this.addEventListener("error",o),this.addEventListener("idle",i),t?.signal?.addEventListener("abort",a);try{yield*e}finally{this.removeEventListener("completed",s),this.removeEventListener("error",o),this.removeEventListener("idle",i),t?.signal?.removeEventListener("abort",a),n()}}};var Ee=class extends It{has(t){return this.find(t)!=null}find(t){return this.queue.find(e=>t.equals(e.options.peerId))}};function So(r){return r[Symbol.asyncIterator]!=null}function ko(r){if(So(r))return(async()=>{for await(let t of r);})();for(let t of r);}var dr=ko;function P(r=0){return new Uint8Array(r)}function F(r=0){return new Uint8Array(r)}var Ao=Math.pow(2,7),Io=Math.pow(2,14),Lo=Math.pow(2,21),pr=Math.pow(2,28),mr=Math.pow(2,35),gr=Math.pow(2,42),wr=Math.pow(2,49),x=128,C=127;function _(r){if(r<Ao)return 1;if(r<Io)return 2;if(r<Lo)return 3;if(r<pr)return 4;if(r<mr)return 5;if(r<gr)return 6;if(r<wr)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function br(r,t,e=0){switch(_(r)){case 8:t[e++]=r&255|x,r/=128;case 7:t[e++]=r&255|x,r/=128;case 6:t[e++]=r&255|x,r/=128;case 5:t[e++]=r&255|x,r/=128;case 4:t[e++]=r&255|x,r>>>=7;case 3:t[e++]=r&255|x,r>>>=7;case 2:t[e++]=r&255|x,r>>>=7;case 1:{t[e++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return t}function To(r,t,e=0){switch(_(r)){case 8:t.set(e++,r&255|x),r/=128;case 7:t.set(e++,r&255|x),r/=128;case 6:t.set(e++,r&255|x),r/=128;case 5:t.set(e++,r&255|x),r/=128;case 4:t.set(e++,r&255|x),r>>>=7;case 3:t.set(e++,r&255|x),r>>>=7;case 2:t.set(e++,r&255|x),r>>>=7;case 1:{t.set(e++,r&255),r>>>=7;break}default:throw new Error("unreachable")}return t}function yr(r,t){let e=r[t],n=0;if(n+=e&C,e<x||(e=r[t+1],n+=(e&C)<<7,e<x)||(e=r[t+2],n+=(e&C)<<14,e<x)||(e=r[t+3],n+=(e&C)<<21,e<x)||(e=r[t+4],n+=(e&C)*pr,e<x)||(e=r[t+5],n+=(e&C)*mr,e<x)||(e=r[t+6],n+=(e&C)*gr,e<x)||(e=r[t+7],n+=(e&C)*wr,e<x))return n;throw new RangeError("Could not decode varint")}function Do(r,t){let e=r.get(t),n=0;if(n+=e&C,e<x||(e=r.get(t+1),n+=(e&C)<<7,e<x)||(e=r.get(t+2),n+=(e&C)<<14,e<x)||(e=r.get(t+3),n+=(e&C)<<21,e<x)||(e=r.get(t+4),n+=(e&C)*pr,e<x)||(e=r.get(t+5),n+=(e&C)*mr,e<x)||(e=r.get(t+6),n+=(e&C)*gr,e<x)||(e=r.get(t+7),n+=(e&C)*wr,e<x))return n;throw new RangeError("Could not decode varint")}function tt(r,t,e=0){return t==null&&(t=F(_(r))),t instanceof Uint8Array?br(r,t,e):To(r,t,e)}function Q(r,t=0){return r instanceof Uint8Array?yr(r,t):Do(r,t)}function H(r,t){t==null&&(t=r.reduce((s,o)=>s+o.length,0));let e=F(t),n=0;for(let s of r)e.set(s,n),n+=s.length;return e}function j(r,t){if(r===t)return!0;if(r.byteLength!==t.byteLength)return!1;for(let e=0;e<r.byteLength;e++)if(r[e]!==t[e])return!1;return!0}var Hn=Symbol.for("@achingbrain/uint8arraylist");function Vn(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 _e(r){return!!r?.[Hn]}var Lt=class r{bufs;length;[Hn]=!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(_e(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(_e(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=Vn(this.bufs,t);return e.buf[e.index]}set(t,e){let n=Vn(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(_e(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 H(n,s)}subarray(t,e){let{bufs:n,length:s}=this._subList(t,e);return n.length===1?n[0]:H(n,s)}sublist(t,e){let{bufs:n,length:s}=this._subList(t,e),o=new r;return o.length=s,o.bufs=[...n],o}_subList(t,e){if(t=t??0,e=e??this.length,t<0&&(t=this.length+t),e<0&&(e=this.length+e),t<0||e>this.length)throw new RangeError("index is out of bounds");if(t===e)return{bufs:[],length:0};if(t===0&&e===this.length)return{bufs:this.bufs,length:this.length};let n=[],s=0;for(let o=0;o<this.bufs.length;o++){let i=this.bufs[o],a=s,c=a+i.byteLength;if(s=c,t>=c)continue;let l=t>=a&&t<c,h=e>a&&e<=c;if(l&&h){if(t===a&&e===c){n.push(i);break}let u=t-a;n.push(i.subarray(u,u+(e-t)));break}if(l){if(t===0){n.push(i);continue}n.push(i.subarray(t-a));continue}if(h){if(e===c){n.push(i);break}n.push(i.subarray(0,e-a));break}n.push(i)}return{bufs:n,length:e-t}}indexOf(t,e=0){if(!_e(t)&&!(t instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');let n=t instanceof Uint8Array?t:t.subarray();if(e=Number(e??0),isNaN(e)&&(e=0),e<0&&(e=this.length+e),e<0&&(e=0),t.length===0)return e>this.length?this.length:e;let s=n.byteLength;if(s===0)throw new TypeError("search must be at least 1 byte long");let o=256,i=new Int32Array(o);for(let u=0;u<o;u++)i[u]=-1;for(let u=0;u<s;u++)i[n[u]]=u;let a=i,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=F(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=P(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=P(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=P(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=F(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=P(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=P(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=P(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=P(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=P(8);new DataView(s.buffer,s.byteOffset,s.byteLength).setFloat64(0,e,n),this.write(s,t)}equals(t){if(t==null||!(t instanceof r)||t.bufs.length!==this.bufs.length)return!1;for(let e=0;e<this.bufs.length;e++)if(!j(this.bufs[e],t.bufs[e]))return!1;return!0}static fromUint8Arrays(t,e){let n=new r;return n.bufs=t,e==null&&(e=t.reduce((s,o)=>s+o.byteLength,0)),n.length=e,n}};function Se(r){return r[Symbol.asyncIterator]!=null}var ke=r=>{let t=_(r),e=F(t);return tt(r,e),ke.bytes=t,e};ke.bytes=0;function Ae(r,t){t=t??{};let e=t.lengthEncoder??ke;function*n(s){let o=e(s.byteLength);o instanceof Uint8Array?yield o:yield*o,s instanceof Uint8Array?yield s:yield*s}return Se(r)?async function*(){for await(let s of r)yield*n(s)}():function*(){for(let s of r)yield*n(s)}()}Ae.single=(r,t)=>{t=t??{};let e=t.lengthEncoder??ke;return new Lt(e(r.byteLength),r)};var Ie=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},Le=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},Te=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"},qt=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};var Po=8,Fo=1024*1024*4,ft;(function(r){r[r.LENGTH=0]="LENGTH",r[r.DATA=1]="DATA"})(ft||(ft={}));var xr=r=>{let t=Q(r);return xr.bytes=_(t),t};xr.bytes=0;function Wt(r,t){let e=new Lt,n=ft.LENGTH,s=-1,o=t?.lengthDecoder??xr,i=t?.maxLengthLength??Po,a=t?.maxDataLength??Fo;function*c(){for(;e.byteLength>0;){if(n===ft.LENGTH)try{if(s=o(e),s<0)throw new Ie("Invalid message length");if(s>a)throw new Le("Message length too long");let l=o.bytes;e.consume(l),t?.onLength!=null&&t.onLength(s),n=ft.DATA}catch(l){if(l instanceof RangeError){if(e.byteLength>i)throw new Te("Message length length too long");break}throw l}if(n===ft.DATA){if(e.byteLength<s)break;let l=e.sublist(0,s);e.consume(s),t?.onData!=null&&t.onData(l),yield l,n=ft.LENGTH}}}return Se(r)?async function*(){for await(let l of r)e.append(l),yield*c();if(e.byteLength>0)throw new qt("Unexpected end of input")}():function*(){for(let l of r)e.append(l),yield*c();if(e.byteLength>0)throw new qt("Unexpected end of input")}()}Wt.fromReader=(r,t)=>{let e=1,n=async function*(){for(;;)try{let{done:o,value:i}=await r.next(e);if(o===!0)return;i!=null&&(yield i)}catch(o){if(o.code==="ERR_UNDER_READ")return{done:!0,value:null};throw o}finally{e=1}}();return Wt(n,{...t??{},onLength:o=>{e=o}})};function Mo(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 qn=Mo;function Uo(r){return r[Symbol.asyncIterator]!=null}function No(r,t){let e=0;if(Uo(r))return async function*(){for await(let c of r)yield t(c,e++)}();let n=qn(r),{value:s,done:o}=n.next();if(o===!0)return function*(){}();let i=t(s,e++);if(typeof i.then=="function")return async function*(){yield await i;for await(let c of n)yield t(c,e++)}();let a=t;return function*(){yield i;for(let c of n)yield a(c,e++)}()}var Wn=No;function Bo(r){return r[Symbol.asyncIterator]!=null}function Ro(...r){let t=[];for(let e of r)Bo(e)||t.push(e);return t.length===r.length?function*(){for(let e of t)yield*e}():async function*(){let e=At({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 Gn=Ro;function vr(r,...t){if(r==null)throw new Error("Empty pipeline");if(Er(r)){let n=r;r=()=>n.source}else if(Qn(r)||Xn(r)){let n=r;r=()=>n}let e=[r,...t];if(e.length>1&&Er(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++)Er(e[n])&&(e[n]=Oo(e[n]));return zo(...e)}var zo=(...r)=>{let t;for(;r.length>0;)t=r.shift()(t);return t},Xn=r=>r?.[Symbol.asyncIterator]!=null,Qn=r=>r?.[Symbol.iterator]!=null,Er=r=>r==null?!1:r.sink!=null&&r.source!=null,Oo=r=>t=>{let e=r.sink(t);if(e?.then!=null){let n=At({objectMode:!0});e.then(()=>{n.end()},i=>{n.end(i)});let s,o=r.source;if(Xn(o))s=async function*(){yield*o,n.end()};else if(Qn(o))s=function*(){yield*o,n.end()};else throw new Error("Unknown duplex source type - must be Iterable or AsyncIterable");return Gn(n,s())}return r.source};function $o(r){return r[Symbol.asyncIterator]!=null}function Vo(r,t){return $o(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 jn=Vo;var et=class extends Event{type;detail;constructor(t,e){super(t),this.type=t,this.detail=e}};var Gt="/ipfs/bitswap/1.2.0";var _r=new Float32Array([-0]),ut=new Uint8Array(_r.buffer);function Kn(r,t,e){_r[0]=r,t[e]=ut[0],t[e+1]=ut[1],t[e+2]=ut[2],t[e+3]=ut[3]}function Jn(r,t){return ut[0]=r[t],ut[1]=r[t+1],ut[2]=r[t+2],ut[3]=r[t+3],_r[0]}var Sr=new Float64Array([-0]),M=new Uint8Array(Sr.buffer);function Zn(r,t,e){Sr[0]=r,t[e]=M[0],t[e+1]=M[1],t[e+2]=M[2],t[e+3]=M[3],t[e+4]=M[4],t[e+5]=M[5],t[e+6]=M[6],t[e+7]=M[7]}function Yn(r,t){return M[0]=r[t],M[1]=r[t+1],M[2]=r[t+2],M[3]=r[t+3],M[4]=r[t+4],M[5]=r[t+5],M[6]=r[t+6],M[7]=r[t+7],Sr[0]}var Ho=BigInt(Number.MAX_SAFE_INTEGER),qo=BigInt(Number.MIN_SAFE_INTEGER),O=class r{lo;hi;constructor(t,e){this.lo=t|0,this.hi=e|0}toNumber(t=!1){if(!t&&this.hi>>>31>0){let e=~this.lo+1>>>0,n=~this.hi>>>0;return e===0&&(n=n+1>>>0),-(e+n*4294967296)}return this.lo+this.hi*4294967296}toBigInt(t=!1){if(t)return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n);if(this.hi>>>31){let e=~this.lo+1>>>0,n=~this.hi>>>0;return e===0&&(n=n+1>>>0),-(BigInt(e)+(BigInt(n)<<32n))}return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n)}toString(t=!1){return this.toBigInt(t).toString()}zzEncode(){let t=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^t)>>>0,this.lo=(this.lo<<1^t)>>>0,this}zzDecode(){let t=-(this.lo&1);return this.lo=((this.lo>>>1|this.hi<<31)^t)>>>0,this.hi=(this.hi>>>1^t)>>>0,this}length(){let t=this.lo,e=(this.lo>>>28|this.hi<<4)>>>0,n=this.hi>>>24;return n===0?e===0?t<16384?t<128?1:2:t<2097152?3:4:e<16384?e<128?5:6:e<2097152?7:8:n<128?9:10}static fromBigInt(t){if(t===0n)return dt;if(t<Ho&&t>qo)return this.fromNumber(Number(t));let e=t<0n;e&&(t=-t);let n=t>>32n,s=t-(n<<32n);return e&&(n=~n|0n,s=~s|0n,++s>ts&&(s=0n,++n>ts&&(n=0n))),new r(Number(s),Number(n))}static fromNumber(t){if(t===0)return dt;let e=t<0;e&&(t=-t);let n=t>>>0,s=(t-n)/4294967296>>>0;return e&&(s=~s>>>0,n=~n>>>0,++n>4294967295&&(n=0,++s>4294967295&&(s=0))),new r(n,s)}static from(t){return typeof t=="number"?r.fromNumber(t):typeof t=="bigint"?r.fromBigInt(t):typeof t=="string"?r.fromBigInt(BigInt(t)):t.low!=null||t.high!=null?new r(t.low>>>0,t.high>>>0):dt}},dt=new O(0,0);dt.toBigInt=function(){return 0n};dt.zzEncode=dt.zzDecode=function(){return this};dt.length=function(){return 1};var ts=4294967296n;function es(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 rs(r,t,e){if(e-t<1)return"";let s,o=[],i=0,a;for(;t<e;)a=r[t++],a<128?o[i++]=a:a>191&&a<224?o[i++]=(a&31)<<6|r[t++]&63:a>239&&a<365?(a=((a&7)<<18|(r[t++]&63)<<12|(r[t++]&63)<<6|r[t++]&63)-65536,o[i++]=55296+(a>>10),o[i++]=56320+(a&1023)):o[i++]=(a&15)<<12|(r[t++]&63)<<6|r[t++]&63,i>8191&&((s??(s=[])).push(String.fromCharCode.apply(String,o)),i=0);return s!=null?(i>0&&s.push(String.fromCharCode.apply(String,o.slice(0,i))),s.join("")):String.fromCharCode.apply(String,o.slice(0,i))}function kr(r,t,e){let n=e,s,o;for(let i=0;i<r.length;++i)s=r.charCodeAt(i),s<128?t[e++]=s:s<2048?(t[e++]=s>>6|192,t[e++]=s&63|128):(s&64512)===55296&&((o=r.charCodeAt(i+1))&64512)===56320?(s=65536+((s&1023)<<10)+(o&1023),++i,t[e++]=s>>18|240,t[e++]=s>>12&63|128,t[e++]=s>>6&63|128,t[e++]=s&63|128):(t[e++]=s>>12|224,t[e++]=s>>6&63|128,t[e++]=s&63|128);return e-n}function K(r,t){return RangeError(`index out of range: ${r.pos} + ${t??1} > ${r.len}`)}function De(r,t){return(r[t-4]|r[t-3]<<8|r[t-2]<<16|r[t-1]<<24)>>>0}var Ar=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,K(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 K(this,4);return De(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw K(this,4);return De(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw K(this,4);let t=Jn(this.buf,this.pos);return this.pos+=4,t}double(){if(this.pos+8>this.len)throw K(this,4);let t=Yn(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 K(this,t);return this.pos+=t,e===n?new Uint8Array(0):this.buf.subarray(e,n)}string(){let t=this.bytes();return rs(t,0,t.length)}skip(t){if(typeof t=="number"){if(this.pos+t>this.len)throw K(this,t);this.pos+=t}else do if(this.pos>=this.len)throw K(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 O(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 K(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 K(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 K(this,8);let t=De(this.buf,this.pos+=4),e=De(this.buf,this.pos+=4);return new O(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=yr(this.buf,this.pos);return this.pos+=_(t),t}uint64String(){return this.readLongVarint().toString(!0)}sint64(){return this.readLongVarint().zzDecode().toBigInt()}sint64Number(){return this.readLongVarint().zzDecode().toNumber()}sint64String(){return this.readLongVarint().zzDecode().toString()}fixed64(){return this.readFixed64().toBigInt()}fixed64Number(){return this.readFixed64().toNumber()}fixed64String(){return this.readFixed64().toString()}sfixed64(){return this.readFixed64().toBigInt()}sfixed64Number(){return this.readFixed64().toNumber()}sfixed64String(){return this.readFixed64().toString()}};function Ir(r){return new Ar(r instanceof Uint8Array?r:r.subarray())}function pt(r,t,e){let n=Ir(r);return t.decode(n,void 0,e)}var Fr={};z(Fr,{base10:()=>Ko});var Il=new Uint8Array(0);function ss(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 os(r){return new TextEncoder().encode(r)}function is(r){return new TextDecoder().decode(r)}function Wo(r,t){if(r.length>=255)throw new TypeError("Alphabet too long");for(var e=new Uint8Array(256),n=0;n<e.length;n++)e[n]=255;for(var s=0;s<r.length;s++){var o=r.charAt(s),i=o.charCodeAt(0);if(e[i]!==255)throw new TypeError(o+" is ambiguous");e[i]=s}var a=r.length,c=r.charAt(0),l=Math.log(a)/Math.log(256),h=Math.log(256)/Math.log(a);function u(d){if(d instanceof Uint8Array||(ArrayBuffer.isView(d)?d=new Uint8Array(d.buffer,d.byteOffset,d.byteLength):Array.isArray(d)&&(d=Uint8Array.from(d))),!(d instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(d.length===0)return"";for(var v=0,g=0,L=0,B=d.length;L!==B&&d[L]===0;)L++,v++;for(var T=(B-L)*h+1>>>0,R=new Uint8Array(T);L!==B;){for(var V=d[L],lt=0,W=T-1;(V!==0||lt<g)&&W!==-1;W--,lt++)V+=256*R[W]>>>0,R[W]=V%a>>>0,V=V/a>>>0;if(V!==0)throw new Error("Non-zero carry");g=lt,L++}for(var rt=T-g;rt!==T&&R[rt]===0;)rt++;for(var ue=c.repeat(v);rt<T;++rt)ue+=r.charAt(R[rt]);return ue}function f(d){if(typeof d!="string")throw new TypeError("Expected String");if(d.length===0)return new Uint8Array;var v=0;if(d[v]!==" "){for(var g=0,L=0;d[v]===c;)g++,v++;for(var B=(d.length-v)*l+1>>>0,T=new Uint8Array(B);d[v];){var R=e[d.charCodeAt(v)];if(R===255)return;for(var V=0,lt=B-1;(R!==0||V<L)&<!==-1;lt--,V++)R+=a*T[lt]>>>0,T[lt]=R%256>>>0,R=R/256>>>0;if(R!==0)throw new Error("Non-zero carry");L=V,v++}if(d[v]!==" "){for(var W=B-L;W!==B&&T[W]===0;)W++;for(var rt=new Uint8Array(g+(B-W)),ue=g;W!==B;)rt[ue++]=T[W++];return rt}}}function m(d){var v=f(d);if(v)return v;throw new Error(`Non-${t} character`)}return{encode:u,decodeUnsafe:f,decode:m}}var Go=Wo,Xo=Go,cs=Xo;var Lr=class{name;prefix;baseEncode;constructor(t,e,n){this.name=t,this.prefix=e,this.baseEncode=n}encode(t){if(t instanceof Uint8Array)return`${this.prefix}${this.baseEncode(t)}`;throw Error("Unknown type, must be binary type")}},Tr=class{name;prefix;baseDecode;prefixCodePoint;constructor(t,e,n){this.name=t,this.prefix=e;let s=e.codePointAt(0);if(s===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=s,this.baseDecode=n}decode(t){if(typeof t=="string"){if(t.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(t)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(t.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(t){return ls(this,t)}},Dr=class{decoders;constructor(t){this.decoders=t}or(t){return ls(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 ls(r,t){return new Dr({...r.decoders??{[r.prefix]:r},...t.decoders??{[t.prefix]:t}})}var Pr=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(t,e,n,s){this.name=t,this.prefix=e,this.baseEncode=n,this.baseDecode=s,this.encoder=new Lr(t,e,n),this.decoder=new Tr(t,e,s)}encode(t){return this.encoder.encode(t)}decode(t){return this.decoder.decode(t)}};function Tt({name:r,prefix:t,encode:e,decode:n}){return new Pr(r,t,e,n)}function ht({name:r,prefix:t,alphabet:e}){let{encode:n,decode:s}=cs(e,r);return Tt({prefix:t,name:r,encode:n,decode:o=>st(s(o))})}function Qo(r,t,e,n){let s={};for(let h=0;h<t.length;++h)s[t[h]]=h;let o=r.length;for(;r[o-1]==="=";)--o;let i=new Uint8Array(o*e/8|0),a=0,c=0,l=0;for(let h=0;h<o;++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,i[l++]=255&c>>a)}if(a>=e||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return i}function jo(r,t,e){let n=t[t.length-1]==="=",s=(1<<e)-1,o="",i=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],i+=8;i>e;)i-=e,o+=t[s&a>>i];if(i!==0&&(o+=t[s&a<<e-i]),n)for(;o.length*e&7;)o+="=";return o}function A({name:r,prefix:t,bitsPerChar:e,alphabet:n}){return Tt({prefix:t,name:r,encode(s){return jo(s,n,e)},decode(s){return Qo(s,n,e,r)}})}var Ko=ht({prefix:"9",name:"base10",alphabet:"0123456789"});var Cr={};z(Cr,{base16:()=>Jo,base16upper:()=>Zo});var Jo=A({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),Zo=A({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var Mr={};z(Mr,{base2:()=>Yo});var Yo=A({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var Ur={};z(Ur,{base256emoji:()=>si});var us=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}"),ti=us.reduce((r,t,e)=>(r[e]=t,r),[]),ei=us.reduce((r,t,e)=>{let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);return r[n]=e,r},[]);function ri(r){return r.reduce((t,e)=>(t+=ti[e],t),"")}function ni(r){let t=[];for(let e of r){let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);let s=ei[n];if(s==null)throw new Error(`Non-base256emoji character: ${e}`);t.push(s)}return new Uint8Array(t)}var si=Tt({prefix:"\u{1F680}",name:"base256emoji",encode:ri,decode:ni});var Nr={};z(Nr,{base32:()=>ot,base32hex:()=>ci,base32hexpad:()=>ui,base32hexpadupper:()=>hi,base32hexupper:()=>li,base32pad:()=>ii,base32padupper:()=>ai,base32upper:()=>oi,base32z:()=>fi});var ot=A({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),oi=A({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),ii=A({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),ai=A({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),ci=A({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),li=A({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),ui=A({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),hi=A({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),fi=A({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Br={};z(Br,{base36:()=>Xt,base36upper:()=>di});var Xt=ht({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),di=ht({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var Rr={};z(Rr,{base58btc:()=>D,base58flickr:()=>pi});var D=ht({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),pi=ht({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var Or={};z(Or,{base64:()=>it,base64pad:()=>mi,base64url:()=>zr,base64urlpad:()=>gi});var it=A({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),mi=A({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),zr=A({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),gi=A({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var $r={};z($r,{base8:()=>wi});var wi=A({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var Vr={};z(Vr,{identity:()=>bi});var bi=Tt({prefix:"\0",name:"identity",encode:r=>is(r),decode:r=>os(r)});var Hl=new TextEncoder,ql=new TextDecoder;var qr={};z(qr,{identity:()=>$i});var Ei=ds,hs=128,vi=127,_i=~vi,Si=Math.pow(2,31);function ds(r,t,e){t=t||[],e=e||0;for(var n=e;r>=Si;)t[e++]=r&255|hs,r/=128;for(;r&_i;)t[e++]=r&255|hs,r>>>=7;return t[e]=r|0,ds.bytes=e-n+1,t}var ki=Hr,Ai=128,fs=127;function Hr(r,n){var e=0,n=n||0,s=0,o=n,i,a=r.length;do{if(o>=a)throw Hr.bytes=0,new RangeError("Could not decode varint");i=r[o++],e+=s<28?(i&fs)<<s:(i&fs)*Math.pow(2,s),s+=7}while(i>=Ai);return Hr.bytes=o-n,e}var Ii=Math.pow(2,7),Li=Math.pow(2,14),Ti=Math.pow(2,21),Di=Math.pow(2,28),Pi=Math.pow(2,35),Fi=Math.pow(2,42),Ci=Math.pow(2,49),Mi=Math.pow(2,56),Ui=Math.pow(2,63),Ni=function(r){return r<Ii?1:r<Li?2:r<Ti?3:r<Di?4:r<Pi?5:r<Fi?6:r<Ci?7:r<Mi?8:r<Ui?9:10},Bi={encode:Ei,decode:ki,encodingLength:Ni},Ri=Bi,Qt=Ri;function jt(r,t=0){return[Qt.decode(r,t),Qt.decode.bytes]}function Dt(r,t,e=0){return Qt.encode(r,t,e),t}function Pt(r){return Qt.encodingLength(r)}function mt(r,t){let e=t.byteLength,n=Pt(r),s=n+Pt(e),o=new Uint8Array(s+e);return Dt(r,o,0),Dt(e,o,n),o.set(t,s),new Ft(r,e,t,o)}function Kt(r){let t=st(r),[e,n]=jt(t),[s,o]=jt(t.subarray(n)),i=t.subarray(n+o);if(i.byteLength!==s)throw new Error("Incorrect length");return new Ft(e,s,i,t)}function ps(r,t){if(r===t)return!0;{let e=t;return r.code===e.code&&r.size===e.size&&e.bytes instanceof Uint8Array&&ss(r.bytes,e.bytes)}}var Ft=class{code;size;digest;bytes;constructor(t,e,n,s){this.code=t,this.size=e,this.digest=n,this.bytes=s}};var ms=0,zi="identity",gs=st;function Oi(r){return mt(ms,gs(r))}var $i={code:ms,name:zi,encode:gs,digest:Oi};var Xr={};z(Xr,{sha256:()=>Fe,sha512:()=>Vi});function Gr({name:r,code:t,encode:e}){return new Wr(r,t,e)}var Wr=class{name;code;encode;constructor(t,e,n){this.name=t,this.code=e,this.encode=n}digest(t){if(t instanceof Uint8Array){let e=this.encode(t);return e instanceof Uint8Array?mt(this.code,e):e.then(n=>mt(this.code,n))}else throw Error("Unknown type, must be binary type")}};function bs(r){return async t=>new Uint8Array(await crypto.subtle.digest(r,t))}var Fe=Gr({name:"sha2-256",code:18,encode:bs("SHA-256")}),Vi=Gr({name:"sha2-512",code:19,encode:bs("SHA-512")});function ys(r,t){let{bytes:e,version:n}=r;switch(n){case 0:return qi(e,Qr(r),t??D.encoder);default:return Wi(e,Qr(r),t??ot.encoder)}}var xs=new WeakMap;function Qr(r){let t=xs.get(r);if(t==null){let e=new Map;return xs.set(r,e),e}return t}var $=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!==Jt)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(e.code!==Gi)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return r.createV0(e)}default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}toV1(){switch(this.version){case 0:{let{code:t,digest:e}=this.multihash,n=mt(t,e);return r.createV1(this.code,n)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(t){return r.equals(this,t)}static equals(t,e){let n=e;return n!=null&&t.code===n.code&&t.version===n.version&&ps(t.multihash,n.multihash)}toString(t){return ys(this,t)}toJSON(){return{"/":ys(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(t){if(t==null)return null;let e=t;if(e instanceof r)return e;if(e["/"]!=null&&e["/"]===e.bytes||e.asCID===e){let{version:n,code:s,multihash:o,bytes:i}=e;return new r(n,s,o,i??Es(n,s,o.bytes))}else if(e[Xi]===!0){let{version:n,multihash:s,code:o}=e,i=Kt(s);return r.create(n,o,i)}else return null}static create(t,e,n){if(typeof e!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(t){case 0:{if(e!==Jt)throw new Error(`Version 0 CID must use dag-pb (code: ${Jt}) block encoding`);return new r(t,e,n,n.bytes)}case 1:{let s=Es(t,e,n.bytes);return new r(t,e,n,s)}default:throw new Error("Invalid version")}}static createV0(t){return r.create(0,Jt,t)}static createV1(t,e){return r.create(1,t,e)}static decode(t){let[e,n]=r.decodeFirst(t);if(n.length!==0)throw new Error("Incorrect length");return e}static decodeFirst(t){let e=r.inspectBytes(t),n=e.size-e.multihashSize,s=st(t.subarray(n,n+e.multihashSize));if(s.byteLength!==e.multihashSize)throw new Error("Incorrect length");let o=s.subarray(e.multihashSize-e.digestSize),i=new Ft(e.multihashCode,e.digestSize,o,s);return[e.version===0?r.createV0(i):r.createV1(e.codec,i),t.subarray(e.size)]}static inspectBytes(t){let e=0,n=()=>{let[u,f]=jt(t.subarray(e));return e+=f,u},s=n(),o=Jt;if(s===18?(s=0,e=0):o=n(),s!==0&&s!==1)throw new RangeError(`Invalid CID version ${s}`);let i=e,a=n(),c=n(),l=e+c,h=l-i;return{version:s,codec:o,multihashCode:a,digestSize:c,multihashSize:h,size:l}}static parse(t,e){let[n,s]=Hi(t,e),o=r.decode(s);if(o.version===0&&t[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return Qr(o).set(n,t),o}};function Hi(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)]}case Xt.prefix:{let e=t??Xt;return[Xt.prefix,e.decode(r)]}default:{if(t==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[r[0],t.decode(r)]}}}function qi(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 o=e.encode(r).slice(1);return t.set(n,o),o}else return s}function Wi(r,t,e){let{prefix:n}=e,s=t.get(n);if(s==null){let o=e.encode(r);return t.set(n,o),o}else return s}var Jt=112,Gi=18;function Es(r,t,e){let n=Pt(r),s=n+Pt(t),o=new Uint8Array(s+e.byteLength);return Dt(r,o,0),Dt(t,o,n),o.set(e,s),o}var Xi=Symbol.for("@ipld/js-cid/CID");var Zt={...Vr,...Mr,...$r,...Fr,...Cr,...Nr,...Br,...Rr,...Or,...Ur},fu={...Xr,...qr};function _s(r,t,e,n){return{name:r,prefix:t,encoder:{name:r,prefix:t,encode:e},decoder:{decode:n}}}var vs=_s("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),jr=_s("ascii","a",r=>{let t="a";for(let e=0;e<r.length;e++)t+=String.fromCharCode(r[e]);return t},r=>{r=r.substring(1);let t=F(r.length);for(let e=0;e<r.length;e++)t[e]=r.charCodeAt(e);return t}),Qi={utf8:vs,"utf-8":vs,hex:Zt.base16,latin1:jr,ascii:jr,binary:jr,...Zt},Ce=Qi;function U(r,t="utf8"){let e=Ce[t];if(e==null)throw new Error(`Unsupported encoding "${t}"`);return e.decoder.decode(`${e.prefix}${r}`)}function Kr(r){let t=r??8192,e=t>>>1,n,s=t;return function(i){if(i<1||i>e)return F(i);s+i>t&&(n=F(t),s=0);let a=n.subarray(s,s+=i);return s&7&&(s=(s|7)+1),a}}var wt=class{fn;len;next;val;constructor(t,e,n){this.fn=t,this.len=e,this.next=void 0,this.val=n}};function Jr(){}var Yr=class{head;tail;len;next;constructor(t){this.head=t.head,this.tail=t.tail,this.len=t.len,this.next=t.states}},ji=Kr();function Ki(r){return globalThis.Buffer!=null?F(r):ji(r)}var te=class{len;head;tail;states;constructor(){this.len=0,this.head=new wt(Jr,0,0),this.tail=this.head,this.states=null}_push(t,e,n){return this.tail=this.tail.next=new wt(t,e,n),this.len+=e,this}uint32(t){return this.len+=(this.tail=this.tail.next=new tn((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(Me,10,O.fromNumber(t)):this.uint32(t)}sint32(t){return this.uint32((t<<1^t>>31)>>>0)}uint64(t){let e=O.fromBigInt(t);return this._push(Me,e.length(),e)}uint64Number(t){return this._push(br,_(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=O.fromBigInt(t).zzEncode();return this._push(Me,e.length(),e)}sint64Number(t){let e=O.fromNumber(t).zzEncode();return this._push(Me,e.length(),e)}sint64String(t){return this.sint64(BigInt(t))}bool(t){return this._push(Zr,1,t?1:0)}fixed32(t){return this._push(Yt,4,t>>>0)}sfixed32(t){return this.fixed32(t)}fixed64(t){let e=O.fromBigInt(t);return this._push(Yt,4,e.lo)._push(Yt,4,e.hi)}fixed64Number(t){let e=O.fromNumber(t);return this._push(Yt,4,e.lo)._push(Yt,4,e.hi)}fixed64String(t){return this.fixed64(BigInt(t))}sfixed64(t){return this.fixed64(t)}sfixed64Number(t){return this.fixed64Number(t)}sfixed64String(t){return this.fixed64String(t)}float(t){return this._push(Kn,4,t)}double(t){return this._push(Zn,8,t)}bytes(t){let e=t.length>>>0;return e===0?this._push(Zr,1,0):this.uint32(e)._push(Zi,e,t)}string(t){let e=es(t);return e!==0?this.uint32(e)._push(kr,e,t):this._push(Zr,1,0)}fork(){return this.states=new Yr(this),this.head=this.tail=new wt(Jr,0,0),this.len=0,this}reset(){return this.states!=null?(this.head=this.states.head,this.tail=this.states.tail,this.len=this.states.len,this.states=this.states.next):(this.head=this.tail=new wt(Jr,0,0),this.len=0),this}ldelim(){let t=this.head,e=this.tail,n=this.len;return this.reset().uint32(n),n!==0&&(this.tail.next=t.next,this.tail=e,this.len+=n),this}finish(){let t=this.head.next,e=Ki(this.len),n=0;for(;t!=null;)t.fn(t.val,e,n),n+=t.len,t=t.next;return e}};function Zr(r,t,e){t[e]=r&255}function Ji(r,t,e){for(;r>127;)t[e++]=r&127|128,r>>>=7;t[e]=r}var tn=class extends wt{next;constructor(t,e){super(Ji,t,e),this.next=void 0}};function Me(r,t,e){for(;r.hi!==0;)t[e++]=r.lo&127|128,r.lo=(r.lo>>>7|r.hi<<25)>>>0,r.hi>>>=7;for(;r.lo>127;)t[e++]=r.lo&127|128,r.lo=r.lo>>>7;t[e++]=r.lo}function Yt(r,t,e){t[e]=r&255,t[e+1]=r>>>8&255,t[e+2]=r>>>16&255,t[e+3]=r>>>24}function Zi(r,t,e){t.set(r,e)}globalThis.Buffer!=null&&(te.prototype.bytes=function(r){let t=r.length>>>0;return this.uint32(t),t>0&&this._push(Yi,t,r),this},te.prototype.string=function(r){let t=globalThis.Buffer.byteLength(r);return this.uint32(t),t>0&&this._push(ta,t,r),this});function Yi(r,t,e){t.set(r,e)}function ta(r,t,e){r.length<40?kr(r,t,e):t.utf8Write!=null?t.utf8Write(r,e):t.set(U(r),e)}function en(){return new te}function bt(r,t){let e=en();return t.encode(r,e,{lengthDelimited:!1}),e.finish()}var Ct;(function(r){r[r.VARINT=0]="VARINT",r[r.BIT64=1]="BIT64",r[r.LENGTH_DELIMITED=2]="LENGTH_DELIMITED",r[r.START_GROUP=3]="START_GROUP",r[r.END_GROUP=4]="END_GROUP",r[r.BIT32=5]="BIT32"})(Ct||(Ct={}));function Ue(r,t,e,n){return{name:r,type:t,encode:e,decode:n}}function Ne(r){function t(s){if(r[s.toString()]==null)throw new Error("Invalid enum value");return r[s]}let e=function(o,i){let a=t(o);i.int32(a)},n=function(o){let i=o.int32();return t(i)};return Ue("enum",Ct.VARINT,e,n)}function yt(r,t){return Ue("message",Ct.LENGTH_DELIMITED,r,t)}var Mt=class extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"};var I;(function(r){r.WantBlock="WantBlock",r.WantHave="WantHave"})(I||(I={}));var rn;(function(r){r[r.WantBlock=0]="WantBlock",r[r.WantHave=1]="WantHave"})(rn||(rn={}));(function(r){r.codec=()=>Ne(rn)})(I||(I={}));var Ut;(function(r){let t;r.codec=()=>(t==null&&(t=yt((e,n,s={})=>{s.lengthDelimited!==!1&&n.fork(),e.cid!=null&&e.cid.byteLength>0&&(n.uint32(10),n.bytes(e.cid)),e.priority!=null&&e.priority!==0&&(n.uint32(16),n.int32(e.priority)),e.cancel!=null&&(n.uint32(24),n.bool(e.cancel)),e.wantType!=null&&(n.uint32(32),I.codec().encode(e.wantType,n)),e.sendDontHave!=null&&(n.uint32(40),n.bool(e.sendDontHave)),s.lengthDelimited!==!1&&n.ldelim()},(e,n,s={})=>{let o={cid:P(0),priority:0},i=n==null?e.len:e.pos+n;for(;e.pos<i;){let a=e.uint32();switch(a>>>3){case 1:{o.cid=e.bytes();break}case 2:{o.priority=e.int32();break}case 3:{o.cancel=e.bool();break}case 4:{o.wantType=I.codec().decode(e);break}case 5:{o.sendDontHave=e.bool();break}default:{e.skipType(a&7);break}}}return o})),t),r.encode=e=>bt(e,r.codec()),r.decode=(e,n)=>pt(e,r.codec(),n)})(Ut||(Ut={}));var Be;(function(r){let t;r.codec=()=>(t==null&&(t=yt((e,n,s={})=>{if(s.lengthDelimited!==!1&&n.fork(),e.entries!=null)for(let o of e.entries)n.uint32(10),Ut.codec().encode(o,n);e.full!=null&&(n.uint32(16),n.bool(e.full)),s.lengthDelimited!==!1&&n.ldelim()},(e,n,s={})=>{let o={entries:[]},i=n==null?e.len:e.pos+n;for(;e.pos<i;){let a=e.uint32();switch(a>>>3){case 1:{if(s.limits?.entries!=null&&o.entries.length===s.limits.entries)throw new Mt('Decode error - map field "entries" had too many elements');o.entries.push(Ut.codec().decode(e,e.uint32(),{limits:s.limits?.entries$}));break}case 2:{o.full=e.bool();break}default:{e.skipType(a&7);break}}}return o})),t),r.encode=e=>bt(e,r.codec()),r.decode=(e,n)=>pt(e,r.codec(),n)})(Be||(Be={}));var Nt;(function(r){let t;r.codec=()=>(t==null&&(t=yt((e,n,s={})=>{s.lengthDelimited!==!1&&n.fork(),e.prefix!=null&&e.prefix.byteLength>0&&(n.uint32(10),n.bytes(e.prefix)),e.data!=null&&e.data.byteLength>0&&(n.uint32(18),n.bytes(e.data)),s.lengthDelimited!==!1&&n.ldelim()},(e,n,s={})=>{let o={prefix:P(0),data:P(0)},i=n==null?e.len:e.pos+n;for(;e.pos<i;){let a=e.uint32();switch(a>>>3){case 1:{o.prefix=e.bytes();break}case 2:{o.data=e.bytes();break}default:{e.skipType(a&7);break}}}return o})),t),r.encode=e=>bt(e,r.codec()),r.decode=(e,n)=>pt(e,r.codec(),n)})(Nt||(Nt={}));var q;(function(r){r.HaveBlock="HaveBlock",r.DontHaveBlock="DontHaveBlock"})(q||(q={}));var Re;(function(r){r[r.HaveBlock=0]="HaveBlock",r[r.DontHaveBlock=1]="DontHaveBlock"})(Re||(Re={}));(function(r){r.codec=()=>Ne(Re)})(q||(q={}));var Bt;(function(r){let t;r.codec=()=>(t==null&&(t=yt((e,n,s={})=>{s.lengthDelimited!==!1&&n.fork(),e.cid!=null&&e.cid.byteLength>0&&(n.uint32(10),n.bytes(e.cid)),e.type!=null&&Re[e.type]!==0&&(n.uint32(16),q.codec().encode(e.type,n)),s.lengthDelimited!==!1&&n.ldelim()},(e,n,s={})=>{let o={cid:P(0),type:q.HaveBlock},i=n==null?e.len:e.pos+n;for(;e.pos<i;){let a=e.uint32();switch(a>>>3){case 1:{o.cid=e.bytes();break}case 2:{o.type=q.codec().decode(e);break}default:{e.skipType(a&7);break}}}return o})),t),r.encode=e=>bt(e,r.codec()),r.decode=(e,n)=>pt(e,r.codec(),n)})(Bt||(Bt={}));var xt;(function(r){let t;r.codec=()=>(t==null&&(t=yt((e,n,s={})=>{if(s.lengthDelimited!==!1&&n.fork(),e.wantlist!=null&&(n.uint32(10),Be.codec().encode(e.wantlist,n)),e.blocks!=null)for(let o of e.blocks)n.uint32(26),Nt.codec().encode(o,n);if(e.blockPresences!=null)for(let o of e.blockPresences)n.uint32(34),Bt.codec().encode(o,n);e.pendingBytes!=null&&e.pendingBytes!==0&&(n.uint32(40),n.int32(e.pendingBytes)),s.lengthDelimited!==!1&&n.ldelim()},(e,n,s={})=>{let o={blocks:[],blockPresences:[],pendingBytes:0},i=n==null?e.len:e.pos+n;for(;e.pos<i;){let a=e.uint32();switch(a>>>3){case 1:{o.wantlist=Be.codec().decode(e,e.uint32(),{limits:s.limits?.wantlist});break}case 3:{if(s.limits?.blocks!=null&&o.blocks.length===s.limits.blocks)throw new Mt('Decode error - map field "blocks" had too many elements');o.blocks.push(Nt.codec().decode(e,e.uint32(),{limits:s.limits?.blocks$}));break}case 4:{if(s.limits?.blockPresences!=null&&o.blockPresences.length===s.limits.blockPresences)throw new Mt('Decode error - map field "blockPresences" had too many elements');o.blockPresences.push(Bt.codec().decode(e,e.uint32(),{limits:s.limits?.blockPresences$}));break}case 5:{o.pendingBytes=e.int32();break}default:{e.skipType(a&7);break}}}return o})),t),r.encode=e=>bt(e,r.codec()),r.decode=(e,n)=>pt(e,r.codec(),n)})(xt||(xt={}));function Ss(r,t){for(let[e,n]of t.wantlist.entries()){let s=r.wantlist.get(e);s!=null&&(s.priority>n.priority&&(n.priority=s.priority),n.cancel=n.cancel??s.cancel,n.wantType=n.wantType??s.wantType,n.sendDontHave=n.sendDontHave??s.sendDontHave),r.wantlist.set(e,n)}for(let[e,n]of t.blockPresences.entries())r.blockPresences.set(e,n);for(let[e,n]of t.blocks.entries())r.blocks.set(e,n);return t.full&&!r.full&&(r.full=!0),r}var ze=class extends Error{static name="BlockTooLargeError";constructor(t="Block too large"){super(t),this.name="BlockTooLargeError"}};var ea=4193648,ra=ea+16;function*ks(r,t){let e=[...r.wantlist.values()],n=[...r.blockPresences.values()],s=[...r.blocks.values()],o=0,i=0,a=0,c=!1;for(;;){let l={wantlist:{full:r.full??!1,entries:[]},blockPresences:[],blocks:[],pendingBytes:0},h=xt.encode(l).byteLength,{added:u,hasMore:f,newSize:m}=nn(s,l.blocks,a,t,h,na);a+=u,h=m;let d=f;({added:u,hasMore:f,newSize:m}=nn(n,l.blockPresences,i,t,h,sa)),i+=u,h=m;let v=f;if({added:u,hasMore:f,newSize:m}=nn(e,l.wantlist.entries,o,t,h,oa),o+=u,h=m,c=!d&&!v&&!f,c||(l.wantlist.full=!1),yield xt.encode(l),c)break}}function nn(r,t,e,n,s,o){let i=0,a=!1;for(let c=e;c<r.length;c++){let l=r[c],h=o(l);if(h>ra)throw new ze("Cannot send block as after encoding it is over the max message size");let u=s+h;if(u>n){a=!0;break}t.push(l),i++,s=u}return{hasMore:a,added:i,newSize:s}}function na(r){return sn(3,Nt.encode(r))}function sa(r){return sn(4,Bt.encode(r))}function oa(r){return sn(1,Ut.encode(r))}function sn(r,t){let e=_(r),n=_(t.byteLength);return e+n+t.byteLength}var Oe=class extends Y{log;libp2p;routing;protocols;running;maxInboundStreams;maxOutboundStreams;messageReceiveTimeout;registrarIds;metrics;sendQueue;runOnLimitedConnections;maxOutgoingMessageSize;maxIncomingMessageSize;constructor(t,e={}){super(),this.log=t.logger.forComponent("helia:bitswap:network"),this.libp2p=t.libp2p,this.routing=t.routing,this.protocols=e.protocols??[Gt],this.registrarIds=[],this.running=!1,this._onStream=this._onStream.bind(this),this.maxInboundStreams=e.maxInboundStreams??1024,this.maxOutboundStreams=e.maxOutboundStreams??1024,this.messageReceiveTimeout=e.messageReceiveTimeout??5e3,this.runOnLimitedConnections=e.runOnLimitedConnections??!1,this.maxIncomingMessageSize=e.maxIncomingMessageSize??4194304,this.maxOutgoingMessageSize=e.maxOutgoingMessageSize??e.maxIncomingMessageSize??4194304,this.metrics={blocksSent:t.metrics?.registerCounter("helia_bitswap_sent_blocks_total"),dataSent:t.metrics?.registerCounter("helia_bitswap_sent_data_bytes_total")},this.sendQueue=new Ee({concurrency:e.messageSendConcurrency??50,metrics:t.metrics,metricName:"helia_bitswap_message_send_queue"}),this.sendQueue.addEventListener("error",n=>{this.log.error("error sending wantlist to peer",n.detail)})}async start(){if(this.running)return;this.running=!0,await this.libp2p.handle(this.protocols,this._onStream,{maxInboundStreams:this.maxInboundStreams,maxOutboundStreams:this.maxOutboundStreams,runOnLimitedConnection:this.runOnLimitedConnections});let t={onConnect:e=>{this.safeDispatchEvent("peer:connected",{detail:e})},onDisconnect:e=>{this.safeDispatchEvent("peer:disconnected",{detail:e})}};this.registrarIds=[];for(let e of this.protocols)this.registrarIds.push(await this.libp2p.register(e,t));this.libp2p.getConnections().forEach(e=>{this.safeDispatchEvent("peer:connected",{detail:e.remotePeer})})}async stop(){if(this.running=!1,await this.libp2p.unhandle(this.protocols),this.registrarIds!=null){for(let t of this.registrarIds)this.libp2p.unregister(t);this.registrarIds=[]}}_onStream(t){if(!this.running)return;let{stream:e,connection:n}=t;Promise.resolve().then(async()=>{this.log("incoming new bitswap %s stream from %p",e.protocol,n.remotePeer);let s=()=>{e.status==="open"?e.abort(new pe(`Incoming Bitswap stream timed out after ${this.messageReceiveTimeout}ms`)):this.log("stream aborted with status %s",e.status)},o=AbortSignal.timeout(this.messageReceiveTimeout);o.addEventListener("abort",s),await e.closeWrite(),await vr(e,i=>Wt(i,{maxDataLength:this.maxIncomingMessageSize}),async i=>{for await(let a of i)try{let c=xt.decode(a);this.log("incoming new bitswap %s message from %p on stream",e.protocol,n.remotePeer,e.id),this.safeDispatchEvent("bitswap:message",{detail:{peer:n.remotePeer,message:c}}),o.removeEventListener("abort",s),o=AbortSignal.timeout(this.messageReceiveTimeout),o.addEventListener("abort",s)}catch(c){this.log.error("error reading incoming bitswap message from %p on stream",n.remotePeer,e.id,c),e.abort(c);break}})}).catch(s=>{this.log.error("error handling incoming stream from %p",n.remotePeer,s),e.abort(s)})}async*findProviders(t,e){e?.onProgress?.(new et("bitswap:network:find-providers",t));for await(let n of this.routing.findProviders(t,e))await this.libp2p.isDialable(n.multiaddrs,{runOnLimitedConnection:this.runOnLimitedConnections})&&(yield n)}async findAndConnect(t,e){await dr(Wn(jn(this.findProviders(t,e),e?.maxProviders??3),async n=>this.connectTo(n.id,e))).catch(n=>{this.log.error(n)})}async sendMessage(t,e,n){if(!this.running)throw new Error("network isn't running");let s=this.sendQueue.queue.find(o=>t.equals(o.options.peerId)&&o.status==="queued");if(s!=null){s.options.message=Ss(s.options.message,e),await s.join({signal:n?.signal});return}await this.sendQueue.add(async o=>{let i=o?.message;if(i==null)throw new fe("No message to send");this.log("sendMessage to %p",t),o?.onProgress?.(new et("bitswap:network:send-wantlist",t));let a=await this.libp2p.dialProtocol(t,Gt,o);await a.closeRead();try{await vr(ks(i,this.maxOutgoingMessageSize),c=>Ae(c),a),await a.close(o)}catch(c){o?.onProgress?.(new et("bitswap:network:send-wantlist:error",{peer:t,error:c})),this.log.error("error sending message to %p",t,c),a.abort(c)}this._updateSentStats(i.blocks)},{peerId:t,signal:n?.signal,message:e})}async connectTo(t,e){if(!this.running)throw new me("Network isn't running");e?.onProgress?.(new et("bitswap:network:dial",t));let[n]=await Promise.all([this.libp2p.dial(t,e),X(this.libp2p,"peer:identify",e?.signal,{filter:s=>{if(!s.detail.peerId.equals(t))return!1;if(s.detail.protocols.includes(Gt))return!0;throw new de(`${t} did not support ${Gt}`)}})]);return n}_updateSentStats(t){let e=0;for(let n of t.values())e+=n.data.byteLength;this.metrics.dataSent?.increment(e),this.metrics.blocksSent?.increment(t.size)}};function S(r,t="utf8"){let e=Ce[t];if(e==null)throw new Error(`Unsupported encoding "${t}"`);return e.encoder.encode(r).substring(1)}function $e(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 ee=class{map;constructor(t){if(this.map=new Map,t!=null)for(let[e,n]of t.entries())this.map.set(e.toString(),{key:e,value:n})}[Symbol.iterator](){return this.entries()}clear(){this.map.clear()}delete(t){return this.map.delete(t.toString())}entries(){return $e(this.map.entries(),t=>[t[1].key,t[1].value])}forEach(t){this.map.forEach((e,n)=>{t(e.value,e.key,this)})}get(t){return this.map.get(t.toString())?.value}has(t){return this.map.has(t.toString())}set(t,e){this.map.set(t.toString(),{key:t,value:e})}keys(){return $e(this.map.values(),t=>t.key)}values(){return $e(this.map.values(),t=>t.value)}get size(){return this.map.size}};var on={32:16777619n,64:1099511628211n,128:309485009821345068724781371n,256:374144419156711147060143317175368453031918731002211n,512:35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759n,1024:5016456510113118655434598811035278955030765345404790744303017523831112055108147451509157692220295382716162651878526895249385292291816524375083746691371804094271873160484737966720260389217684476157468082573n},As={32:2166136261n,64:14695981039346656037n,128:144066263297769815596495629667062367629n,256:100029257958052580907070968620625704837092796014241193945225284501741471925557n,512:9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785n,1024:14197795064947621068722070641403218320880622795441933960878474914617582723252296732303717722150864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915n},Is=new globalThis.TextEncoder;function pa(r,t){let e=on[t],n=As[t];for(let s=0;s<r.length;s++)n^=BigInt(r[s]),n=BigInt.asUintN(t,n*e);return n}function ma(r,t,e){if(e.length===0)throw new Error("The `utf8Buffer` option must have a length greater than zero");let n=on[t],s=As[t],o=r;for(;o.length>0;){let i=Is.encodeInto(o,e);o=o.slice(i.read);for(let a=0;a<i.written;a++)s^=BigInt(e[a]),s=BigInt.asUintN(t,s*n)}return s}function an(r,{size:t=32,utf8Buffer:e}={}){if(!on[t])throw new Error("The `size` option must be one of 32, 64, 128, 256, 512, or 1024");if(typeof r=="string"){if(e)return ma(r,t,e);r=Is.encode(r)}return pa(r,t)}var re={hash:r=>Number(an(r,{size:32})),hashV:(r,t)=>ga(re.hash(r,t))};function ga(r){let t=r.toString(16);return t.length%2===1&&(t=`0${t}`),U(t,"base16")}var cn=64,J=class{fp;h;seed;constructor(t,e,n,s=2){if(s>cn)throw new TypeError("Invalid Fingerprint Size");let o=e.hashV(t,n),i=P(s);for(let a=0;a<i.length;a++)i[a]=o[a];i.length===0&&(i[0]=7),this.fp=i,this.h=e,this.seed=n}hash(){return this.h.hash(this.fp,this.seed)}equals(t){return t?.fp instanceof Uint8Array?j(this.fp,t.fp):!1}};function Et(r,t){return Math.floor(Math.random()*(t-r))+r}var vt=class{contents;constructor(t){this.contents=new Array(t).fill(null)}has(t){if(!(t instanceof J))throw new TypeError("Invalid Fingerprint");return this.contents.some(e=>t.equals(e))}add(t){if(!(t instanceof J))throw new TypeError("Invalid Fingerprint");for(let e=0;e<this.contents.length;e++)if(this.contents[e]==null)return this.contents[e]=t,!0;return!0}swap(t){if(!(t instanceof J))throw new TypeError("Invalid Fingerprint");let e=Et(0,this.contents.length-1),n=this.contents[e];return this.contents[e]=t,n}remove(t){if(!(t instanceof J))throw new TypeError("Invalid Fingerprint");let e=this.contents.findIndex(n=>t.equals(n));return e>-1?(this.contents[e]=null,!0):!1}};var wa=500,ne=class{bucketSize;filterSize;fingerprintSize;buckets;count;hash;seed;constructor(t){this.filterSize=t.filterSize,this.bucketSize=t.bucketSize??4,this.fingerprintSize=t.fingerprintSize??2,this.count=0,this.buckets=[],this.hash=t.hash??re,this.seed=t.seed??Et(0,Math.pow(2,10))}add(t){typeof t=="string"&&(t=U(t));let e=new J(t,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(t,this.seed)%this.filterSize,s=(n^e.hash())%this.filterSize;if(this.buckets[n]==null&&(this.buckets[n]=new vt(this.bucketSize)),this.buckets[s]==null&&(this.buckets[s]=new vt(this.bucketSize)),this.buckets[n].add(e)||this.buckets[s].add(e))return this.count++,!0;let o=[n,s],i=o[Et(0,o.length-1)];this.buckets[i]==null&&(this.buckets[i]=new vt(this.bucketSize));for(let a=0;a<wa;a++){let c=this.buckets[i].swap(e);if(c!=null&&(i=(i^c.hash())%this.filterSize,this.buckets[i]==null&&(this.buckets[i]=new vt(this.bucketSize)),this.buckets[i].add(c)))return this.count++,!0}return!1}has(t){typeof t=="string"&&(t=U(t));let e=new J(t,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(t,this.seed)%this.filterSize,s=this.buckets[n]?.has(e)??!1;if(s)return s;let o=(n^e.hash())%this.filterSize;return this.buckets[o]?.has(e)??!1}remove(t){typeof t=="string"&&(t=U(t));let e=new J(t,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(t,this.seed)%this.filterSize,s=this.buckets[n]?.remove(e)??!1;if(s)return this.count--,s;let o=(n^e.hash())%this.filterSize,i=this.buckets[o]?.remove(e)??!1;return i&&this.count--,i}get reliable(){return Math.floor(100*(this.count/this.filterSize))<=90}},ba={1:.5,2:.84,4:.95,8:.98};function ya(r=.001){return r>.002?2:r>1e-5?4:8}function Ls(r,t=.001){let e=ya(t),n=ba[e],s=Math.round(r/n),o=Math.min(Math.ceil(Math.log2(1/t)+Math.log2(2*e)),cn);return{filterSize:s,bucketSize:e,fingerprintSize:o}}var Ve=class{filterSize;bucketSize;fingerprintSize;scale;filterSeries;hash;seed;constructor(t){this.bucketSize=t.bucketSize??4,this.filterSize=t.filterSize??(1<<18)/this.bucketSize,this.fingerprintSize=t.fingerprintSize??2,this.scale=t.scale??2,this.hash=t.hash??re,this.seed=t.seed??Et(0,Math.pow(2,10)),this.filterSeries=[new ne({filterSize:this.filterSize,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed})]}add(t){if(typeof t=="string"&&(t=U(t)),this.has(t))return!0;let e=this.filterSeries.find(n=>n.reliable);if(e==null){let n=this.filterSize*Math.pow(this.scale,this.filterSeries.length);e=new ne({filterSize:n,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed}),this.filterSeries.push(e)}return e.add(t)}has(t){typeof t=="string"&&(t=U(t));for(let e=0;e<this.filterSeries.length;e++)if(this.filterSeries[e].has(t))return!0;return!1}remove(t){typeof t=="string"&&(t=U(t));for(let e=0;e<this.filterSeries.length;e++)if(this.filterSeries[e].remove(t))return!0;return!1}get count(){return this.filterSeries.reduce((t,e)=>t+e.count,0)}};function ln(r,t=.001,e){return new Ve({...Ls(r,t),...e??{}})}var un=class extends ee{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 se(r){let{name:t,metrics:e}=r,n;return e!=null?n=new un({name:t,metrics:e}):n=new ee,n}var at=class{full;pendingBytes;wantlist;blocks;blockPresences;constructor(t=!1,e=0){this.full=t,this.wantlist=new Map,this.blocks=new Map,this.blockPresences=new Map,this.pendingBytes=0}addWantlistEntry(t,e){let n=it.encode(t.multihash.bytes);this.wantlist.set(n,e)}addBlockPresence(t,e){let n=it.encode(t.multihash.bytes);this.blockPresences.set(n,e)}addBlock(t,e){let n=it.encode(t.multihash.bytes);this.blocks.set(n,e)}};function xa(r){let t=new Uint8Array(r.reduce((n,s)=>n+_(s),0)),e=0;for(let n of r)t=tt(n,t,e),e+=_(n);return t}var Ts=xa;function hn(r){return Ts([r.version,r.code,r.multihash.code,r.multihash.digest.byteLength])}var He=class{peerId;blockstore;network;wants;exchangeCount;bytesSent;bytesReceived;lastExchange;maxSizeReplaceHasWithBlock;log;constructor(t,e){this.peerId=t.peerId,this.blockstore=t.blockstore,this.network=t.network,this.wants=new Map,this.log=t.logger.forComponent(`helia:bitswap:ledger:${t.peerId}`),this.exchangeCount=0,this.bytesSent=0,this.bytesReceived=0,this.maxSizeReplaceHasWithBlock=e.maxSizeReplaceHasWithBlock??1024}sentBytes(t){this.exchangeCount++,this.lastExchange=new Date().getTime(),this.bytesSent+=t}receivedBytes(t){this.exchangeCount++,this.lastExchange=new Date().getTime(),this.bytesReceived+=t}debtRatio(){return this.bytesSent/(this.bytesReceived+1)}async sendBlocksToPeer(t){let e=new at,n=new Set;for(let[s,o]of this.wants.entries())try{let i=await this.blockstore.get(o.cid,t);o.wantType===I.WantHave?i.byteLength<this.maxSizeReplaceHasWithBlock?(this.log("sending have and block for %c",o.cid),n.add(s),e.addBlock(o.cid,{data:i,prefix:hn(o.cid)})):(this.log("sending have for %c",o.cid),e.addBlockPresence(o.cid,{cid:o.cid.bytes,type:q.HaveBlock})):(this.log("sending block for %c",o.cid),n.add(s),e.addBlock(o.cid,{data:i,prefix:hn(o.cid)}))}catch(i){if(i.name!=="NotFoundError")throw i;if(this.log("do not have block for %c",o.cid),!o.sendDontHave||o.sentDontHave===!0)continue;o.sentDontHave=!0,e.addBlockPresence(o.cid,{cid:o.cid.bytes,type:q.DontHaveBlock})}if(e.blocks.size>0||e.blockPresences.size>0){this.log("sending message"),await this.network.sendMessage(this.peerId,e,t),this.log("sent message"),this.sentBytes([...e.blocks.values()].reduce((s,o)=>s+o.data.byteLength,0));for(let s of n)this.wants.delete(s)}}};var qe=class{blockstore;network;ledgerMap;maxSizeReplaceHasWithBlock;log;logger;constructor(t,e={}){this.blockstore=t.blockstore,this.network=t.network,this.maxSizeReplaceHasWithBlock=e.maxSizeReplaceHasWithBlock,this.log=t.logger.forComponent("helia:bitswap:peer-want-lists"),this.logger=t.logger,this.ledgerMap=se({name:"helia_bitswap_ledger_map",metrics:t.metrics}),this.network.addEventListener("bitswap:message",n=>{this.receiveMessage(n.detail.peer,n.detail.message).catch(s=>{this.log.error("error receiving bitswap message from %p",n.detail.peer,s)})}),this.network.addEventListener("peer:disconnected",n=>{this.peerDisconnected(n.detail)})}ledgerForPeer(t){let e=this.ledgerMap.get(t);if(e!=null)return{peer:e.peerId,value:e.debtRatio(),sent:e.bytesSent,received:e.bytesReceived,exchanged:e.exchangeCount}}wantListForPeer(t){let e=this.ledgerMap.get(t);if(e!=null)return[...e.wants.values()]}peers(){return Array.from(this.ledgerMap.values()).map(t=>t.peerId)}async receiveMessage(t,e){let n=this.ledgerMap.get(t);if(n==null&&(n=new He({peerId:t,blockstore:this.blockstore,network:this.network,logger:this.logger},{maxSizeReplaceHasWithBlock:this.maxSizeReplaceHasWithBlock}),this.ledgerMap.set(t,n)),n.receivedBytes(e.blocks?.reduce((s,o)=>s+o.data.byteLength,0)??0),e.wantlist!=null){e.wantlist.full===!0&&n.wants.clear();for(let s of e.wantlist.entries){let o=$.decode(s.cid),i=S(o.multihash.bytes,"base64");s.cancel===!0?(this.log("peer %p cancelled want of block for %c",t,o),n.wants.delete(i)):(s.wantType===I.WantHave?this.log("peer %p wanted block presence for %c",t,o):this.log("peer %p wanted block for %c",t,o),n.wants.set(i,{cid:o,priority:s.priority,wantType:s.wantType??I.WantBlock,sendDontHave:s.sendDontHave??!1}))}}this.log("send blocks to peer"),await n.sendBlocksToPeer()}async receivedBlock(t,e){let n=S(t.multihash.bytes,"base64"),s=[];for(let o of this.ledgerMap.values())o.wants.has(n)&&s.push(o);await Promise.all(s.map(async o=>o.sendBlocksToPeer(e)))}peerDisconnected(t){this.ledgerMap.delete(t)}};var _a=zn(Ps(),1);var Rt;(function(r){r[r.A=1]="A",r[r.CNAME=5]="CNAME",r[r.TXT=16]="TXT",r[r.AAAA=28]="AAAA"})(Rt||(Rt={}));var We=class extends Error{static name="InsufficientProvidersError";constructor(t="Insufficient providers found"){super(t),this.name="InsufficientProvidersError"}};var _t=class extends Y{intialPeerSearchComplete;requests;name;log;logger;minProviders;maxProviders;providers;evictionFilter;constructor(t,e){super(),this.name=e.name,this.logger=t.logger,this.log=t.logger.forComponent(this.name),this.requests=new Map,this.minProviders=e.minProviders??1,this.maxProviders=e.maxProviders??5,this.providers=[],this.evictionFilter=ln(this.maxProviders)}async retrieve(t,e={}){let n=it.encode(t.multihash.bytes),s=this.requests.get(n);if(s!=null)return this.log("join existing request for %c",t),s;let o=G();if(this.requests.set(n,o.promise),this.providers.length===0){let l=!1;this.intialPeerSearchComplete==null&&(l=!0,this.log=this.logger.forComponent(`${this.name}:${t}`),this.intialPeerSearchComplete=this.findProviders(t,this.minProviders,e)),await this.intialPeerSearchComplete,l&&this.log("found initial session peers for %c",t)}let i=!1,a=new It({concurrency:this.maxProviders});a.addEventListener("error",()=>{}),a.addEventListener("failure",l=>{this.log.error("error querying provider %o, evicting from session",l.detail.job.options.provider,l.detail.error),this.evict(l.detail.job.options.provider)}),a.addEventListener("success",l=>{i=!0,o.resolve(l.detail.result)}),a.addEventListener("idle",()=>{i||e.signal?.aborted===!0||Promise.resolve().then(async()=>{this.log("no session peers had block for for %c, finding new providers",t);for(let l=0;l<this.minProviders&&this.providers.length!==0;l++){let h=this.providers[Math.floor(Math.random()*this.providers.length)];this.evict(h)}await this.findProviders(t,this.minProviders,e),this.log("found new providers re-retrieving %c",t),this.requests.delete(n),o.resolve(await this.retrieve(t,e))}).catch(l=>{this.log.error("could not find new providers for %c",t,l),o.reject(l)})});let c=l=>{a.add(async()=>this.queryProvider(t,l.detail,e),{provider:l.detail}).catch(h=>{e.signal?.aborted!==!0&&this.log.error("error retrieving session block for %c",t,h)})};this.addEventListener("provider",c),Promise.all([...this.providers].map(async l=>a.add(async()=>this.queryProvider(t,l,e),{provider:l}))).catch(l=>{e.signal?.aborted!==!0&&this.log.error("error retrieving session block for %c",t,l)});try{return await o.promise}finally{this.removeEventListener("provider",c),a.clear(),this.requests.delete(n)}}evict(t){this.evictionFilter.add(this.toEvictionKey(t));let e=this.providers.findIndex(n=>this.equals(n,t));e!==-1&&this.providers.splice(e,1)}isEvicted(t){return this.evictionFilter.has(this.toEvictionKey(t))}hasProvider(t){return!!(this.providers.find(e=>this.equals(e,t))!=null||this.isEvicted(t))}async findProviders(t,e,n){let s=G(),o=0;return Promise.resolve().then(async()=>{this.log("finding %d-%d new provider(s) for %c",e,this.maxProviders,t);for await(let i of this.findNewProviders(t,n)){if(o===this.maxProviders||n.signal?.aborted===!0)break;if(!this.hasProvider(i)&&(this.log("found %d/%d new providers",o,this.maxProviders),this.providers.push(i),this.safeDispatchEvent("provider",{detail:i}),o++,o===e&&(this.log("session is ready"),s.resolve()),this.providers.length===this.maxProviders)){this.log("found max session peers",o);break}}if(this.log("found %d/%d new session peers",o,this.maxProviders),o<e)throw new We(`Found ${o} of ${e} ${this.name} providers for ${t}`)}).catch(i=>{this.log.error("error searching routing for potential session peers for %c",t,i.errors??i),s.reject(i)}),s.promise}};var fn=class extends _t{wantList;network;constructor(t,e){super(t,{...e,name:"helia:bitswap:session"}),this.wantList=t.wantList,this.network=t.network}async queryProvider(t,e,n){this.log("sending WANT-BLOCK for %c to %p",t,e);let s=await this.wantList.wantSessionBlock(t,e,n);if(this.log("%p %s %c",e,s.has?"has":"does not have",t),s.has&&s.block!=null)return s.block;throw new Error("Provider did not have block")}async*findNewProviders(t,e={}){for await(let n of this.network.findProviders(t,e))yield n.id}toEvictionKey(t){return t.toMultihash().bytes}equals(t,e){return t.equals(e)}};function Fs(r,t){return new fn(r,t)}var Ge=class{blocksReceived;duplicateBlocksReceived;dataReceived;duplicateDataReceived;constructor(t){this.blocksReceived=t.metrics?.registerMetricGroup("helia_bitswap_received_blocks"),this.duplicateBlocksReceived=t.metrics?.registerMetricGroup("helia_bitswap_duplicate_received_blocks"),this.dataReceived=t.metrics?.registerMetricGroup("helia_bitswap_data_received_bytes"),this.duplicateDataReceived=t.metrics?.registerMetricGroup("helia_bitswap_duplicate_data_received_bytes")}updateBlocksReceived(t=1,e){let n={global:t};e!=null&&(n[e.toString()]=t),this.blocksReceived?.increment(n)}updateDuplicateBlocksReceived(t=1,e){let n={global:t};e!=null&&(n[e.toString()]=t),this.duplicateBlocksReceived?.increment(n)}updateDataReceived(t,e){let n={global:t};e!=null&&(n[e.toString()]=t),this.dataReceived?.increment(n)}updateDuplicateDataReceived(t,e){let n={global:t};e!=null&&(n[e.toString()]=t),this.duplicateDataReceived?.increment(n)}};var dn=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 Cs(r){let{name:t,metrics:e}=r,n;return e!=null?n=new dn({name:t,metrics:e}):n=new Map,n}function Aa(r){if(!(r instanceof Uint8Array))throw new Error("arg needs to be a Uint8Array");let t=[];for(;r.length>0;){let e=Q(r);t.push(e),r=r.slice(_(e))}return t}var Ms=Aa;var Xe=class extends Y{peers;wants;network;log;sendMessagesDelay;sendMessagesTimeout;hashLoader;sendingMessages;constructor(t,e={}){super(),this.peers=se({name:"helia_bitswap_peers",metrics:t.metrics}),this.wants=Cs({name:"helia_bitswap_wantlist",metrics:t.metrics}),this.network=t.network,this.sendMessagesDelay=e.sendMessagesDelay??10,this.log=t.logger.forComponent("helia:bitswap:wantlist"),this.hashLoader=e.hashLoader,this.network.addEventListener("bitswap:message",n=>{this.receiveMessage(n.detail.peer,n.detail.message).catch(s=>{this.log.error("error receiving bitswap message from %p",n.detail.peer,s)})}),this.network.addEventListener("peer:connected",n=>{this.peerConnected(n.detail).catch(s=>{this.log.error("error processing newly connected bitswap peer %p",n.detail,s)})}),this.network.addEventListener("peer:disconnected",n=>{this.peerDisconnected(n.detail)})}async addEntry(t,e){let n=S(t.multihash.bytes,"base64"),s=this.wants.get(n);s==null&&(s={cid:t,priority:e.priority??1,wantType:e.wantType??I.WantBlock,cancel:!1,sendDontHave:!0},this.wants.set(n,s)),s.wantType===I.WantHave&&e.wantType===I.WantBlock&&(s.wantType=I.WantBlock),await this.sendMessagesDebounced();try{return e.wantType===I.WantBlock?(await X(this,"block",e?.signal,{filter:a=>j(t.multihash.digest,a.detail.cid.multihash.digest),errorMessage:"Want was aborted"})).detail:(await X(this,"presence",e?.signal,{filter:i=>j(t.multihash.digest,i.detail.cid.multihash.digest),errorMessage:"Want was aborted"})).detail}finally{e.signal?.aborted===!0&&(this.log("want for %c was aborted, cancelling want",t),s.cancel=!0,await this.sendMessagesDebounced())}}async sendMessagesDebounced(){await this.sendingMessages?.promise,clearTimeout(this.sendMessagesTimeout),this.sendMessagesTimeout=setTimeout(()=>{this.sendMessages().catch(t=>{this.log("error sending messages to peers",t)})},this.sendMessagesDelay)}async sendMessages(){this.sendingMessages=G(),await Promise.all([...this.peers.entries()].map(async([t,e])=>{let n=new Set,s=new at;for(let[o,i]of this.wants.entries())e.has(o)||i.cancel||(n.add(o),s.addWantlistEntry(i.cid,{cid:i.cid.bytes,priority:i.priority,wantType:i.wantType,cancel:i.cancel,sendDontHave:i.sendDontHave}));if(s.wantlist.size!==0)try{await this.network.sendMessage(t,s);for(let o of n)e.add(o)}catch(o){this.log.error("error sending full wantlist to new peer",o)}})).catch(t=>{this.log.error("error sending messages",t)});for(let[t,e]of this.wants)if(e.cancel){this.wants.delete(t);for(let n of this.peers.values())n.delete(t)}this.sendingMessages.resolve()}has(t){let e=S(t.multihash.bytes,"base64");return this.wants.has(e)}async wantSessionPresence(t,e,n={}){let s=new at;return s.addWantlistEntry(t,{cid:t.bytes,sendDontHave:!0,wantType:I.WantHave,priority:1}),await this.network.sendMessage(e,s),(await X(this,"presence",n.signal,{filter:i=>e.equals(i.detail.sender)&&j(t.multihash.digest,i.detail.cid.multihash.digest)})).detail}async wantBlock(t,e={}){return this.addEntry(t,{...e,wantType:I.WantBlock})}async wantSessionBlock(t,e,n={}){let s=new at;return s.addWantlistEntry(t,{cid:t.bytes,sendDontHave:!0,wantType:I.WantBlock,priority:1}),await this.network.sendMessage(e,s),(await X(this,"presence",n.signal,{filter:i=>e.equals(i.detail.sender)&&j(t.multihash.digest,i.detail.cid.multihash.digest)})).detail}async receivedBlock(t,e){let n=S(t.multihash.bytes,"base64"),s=this.wants.get(n);s!=null&&(s.cancel=!0,await this.sendMessagesDebounced())}async receiveMessage(t,e){this.log("received message from %p with %d blocks",t,e.blocks.length);let n=!1;for(let s of e.blocks){if(s.prefix==null||s.data==null)continue;let o=Ms(s.prefix),i=o[0],a=o[1],c=o[2],l=c===Fe.code?Fe:await this.hashLoader?.getHasher(c);if(l==null){this.log.error("unknown hash algorithm",c);continue}let h=l.digest(s.data);h.then!=null&&(h=await h);let u=$.create(i===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=S(u.multihash.bytes,"base64"),m=this.wants.get(f);m!=null&&(m.cancel=!0,n=!0)}for(let{cid:s,type:o}of e.blockPresences){let i=$.decode(s);this.log("received %s from %p for %c",o,t,i),this.safeDispatchEvent("presence",{detail:{sender:t,cid:i,has:o===q.HaveBlock}})}n&&await this.sendMessagesDebounced()}async peerConnected(t){let e=new Set,n=new at(!0);for(let[s,o]of this.wants.entries())o.cancel||(e.add(s),n.addWantlistEntry(o.cid,{cid:o.cid.bytes,priority:1,wantType:I.WantBlock,cancel:!1,sendDontHave:!1}));if(n.wantlist.size===0){this.peers.set(t,e);return}try{await this.network.sendMessage(t,n),this.peers.set(t,e)}catch(s){this.log.error("error sending full wantlist to new peer %p",t,s)}}peerDisconnected(t){this.peers.delete(t)}start(){}stop(){this.peers.clear(),clearTimeout(this.sendMessagesTimeout)}};var Qe=class{log;logger;stats;network;blockstore;peerWantLists;wantList;constructor(t,e={}){this.logger=t.logger,this.log=t.logger.forComponent("helia:bitswap"),this.blockstore=t.blockstore,this.stats=new Ge(t),this.network=new Oe(t,e),this.peerWantLists=new qe({...t,network:this.network},e),this.wantList=new Xe({...t,network:this.network},e)}createSession(t={}){return Fs({wantList:this.wantList,network:this.network,logger:this.logger},t)}async want(t,e={}){let n=new AbortController,s=On([n.signal,e.signal]);n.signal,this.network.findAndConnect(t,{...e,signal:s}).catch(o=>{n.signal.aborted||this.log.error("error during finding and connect for cid %c",t,o)});try{return(await this.wantList.wantBlock(t,{...e,signal:s})).block}finally{n.abort(),s.clear()}}async notify(t,e,n={}){await Promise.all([this.peerWantLists.receivedBlock(t,n),this.wantList.receivedBlock(t,n)])}getWantlist(){return[...this.wantList.wants.values()].filter(t=>!t.cancel).map(t=>({cid:t.cid,priority:t.priority,wantType:t.wantType}))}getPeerWantlist(t){return this.peerWantLists.wantListForPeer(t)}async start(){this.wantList.start(),await this.network.start()}async stop(){this.wantList.stop(),await this.network.stop()}};var Us=(r,t={})=>new Qe(r,t);var pn=class{bitswap;started;constructor(t,e={}){let{getHasher:n}=t;this.bitswap=Us(t,{hashLoader:{getHasher:async s=>n(s)},...e}),this.started=!1}isStarted(){return this.started}async start(){await this.bitswap.start(),this.started=!0}async stop(){await this.bitswap.stop(),this.started=!1}async announce(t,e,n){await this.bitswap.notify(t,e,n)}async retrieve(t,e={}){return this.bitswap.want(t,e)}createSession(t){let e=this.bitswap.createSession(t);return{announce:async(n,s,o)=>{await this.bitswap.notify(n,s,o)},retrieve:async(n,s)=>e.retrieve(n,s)}}};function Ns(r={}){return t=>new pn(t,r)}var je=class{index=0;input="";new(t){return this.index=0,this.input=t,this}readAtomically(t){let e=this.index,n=t();return n===void 0&&(this.index=e),n}parseWith(t){let e=t();if(this.index===this.input.length)return e}peekChar(){if(!(this.index>=this.input.length))return this.input[this.index]}readChar(){if(!(this.index>=this.input.length))return this.input[this.index++]}readGivenChar(t){return this.readAtomically(()=>{let e=this.readChar();if(e===t)return e})}readSeparator(t,e,n){return this.readAtomically(()=>{if(!(e>0&&this.readGivenChar(t)===void 0))return n()})}readNumber(t,e,n,s){return this.readAtomically(()=>{let o=0,i=0,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(o*=t,o+=h,o>l||(i+=1,e!==void 0&&i>e))return}if(i!==0)return!n&&c&&i>1?void 0:o})}readIPv4Addr(){return this.readAtomically(()=>{let t=new Uint8Array(4);for(let e=0;e<t.length;e++){let n=this.readSeparator(".",e,()=>this.readNumber(10,3,!1,1));if(n===void 0)return;t[e]=n}return t})}readIPv6Addr(){let t=e=>{for(let n=0;n<e.length/2;n++){let s=n*2;if(n<e.length-3){let i=this.readSeparator(":",n,()=>this.readIPv4Addr());if(i!==void 0)return e[s]=i[0],e[s+1]=i[1],e[s+2]=i[2],e[s+3]=i[3],[s+4,!0]}let o=this.readSeparator(":",n,()=>this.readNumber(16,4,!0,2));if(o===void 0)return[s,!1];e[s]=o>>8,e[s+1]=o&255}return[e.length,!1]};return this.readAtomically(()=>{let e=new Uint8Array(16),[n,s]=t(e);if(n===16)return e;if(s||this.readGivenChar(":")===void 0||this.readGivenChar(":")===void 0)return;let o=new Uint8Array(14),i=16-(n+2),[a]=t(o.subarray(0,i));return e.set(o.subarray(0,a),16-a),e})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};var Bs=45,Ia=15,zt=new je;function mn(r){if(!(r.length>Ia))return zt.new(r).parseWith(()=>zt.readIPv4Addr())}function gn(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>Bs))return zt.new(r).parseWith(()=>zt.readIPv6Addr())}function Ke(r,t=!1){if(r.includes("%")&&(r=r.split("%")[0]),r.length>Bs)return;let e=zt.new(r).parseWith(()=>zt.readIPAddr());if(e)return t&&e.length===4?Uint8Array.from([0,0,0,0,0,0,0,0,0,0,255,255,e[0],e[1],e[2],e[3]]):e}function Ot(r){return!!mn(r)}function $t(r){return!!gn(r)}function Je(r){return!!Ke(r)}var zs=zn(Rs(),1),La=["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"],Ta=La.map(r=>new zs.Netmask(r));function wn(r){for(let t of Ta)if(t.contains(r))return!0;return!1}function Da(r){return/^::ffff:([0-9a-fA-F]{1,4}):([0-9a-fA-F]{1,4})$/.test(r)}function Pa(r){let t=r.split(":");if(t.length<2)return!1;let e=t[t.length-1].padStart(4,"0"),n=t[t.length-2].padStart(4,"0"),s=`${parseInt(n.substring(0,2),16)}.${parseInt(n.substring(2),16)}.${parseInt(e.substring(0,2),16)}.${parseInt(e.substring(2),16)}`;return wn(s)}function Fa(r){return/^::ffff:([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)}function Ca(r){let t=r.split(":"),e=t[t.length-1];return wn(e)}function Ma(r){return/^::$/.test(r)||/^::1$/.test(r)||/^64:ff9b::([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)||/^100::([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^2001::([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^2001:2[0-9a-fA-F]:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^2001:db8:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^2002:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^f[c-d]([0-9a-fA-F]{2,2}):/i.test(r)||/^fe[8-9a-bA-B][0-9a-fA-F]:/i.test(r)||/^ff([0-9a-fA-F]{2,2}):/i.test(r)}function Os(r){return Ot(r)?wn(r):Da(r)?Pa(r):Fa(r)?Ca(r):$t(r)?Ma(r):void 0}var Ua=r=>r.toString().split("/").slice(1),Vt=r=>({match:t=>t.length<1?!1:r(t[0])?t.slice(1):!1,pattern:"fn"}),w=r=>({match:t=>Vt(e=>e===r).match(t),pattern:r}),St=()=>({match:r=>Vt(t=>typeof t=="string").match(r),pattern:"{string}"}),ie=()=>({match:r=>Vt(t=>!isNaN(parseInt(t))).match(r),pattern:"{number}"}),E=()=>({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}"}),ae=()=>({match:r=>{if(r.length<2||r[0]!=="certhash")return!1;try{zr.decode(r[1])}catch{return!1}return r.slice(2)},pattern:"/certhash/{certhash}"}),y=r=>({match:t=>{let e=r.match(t);return e===!1?t:e},pattern:`optional(${r.pattern})`}),N=(...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(", ")})`}),b=(...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 o=Ua(s);for(let i of r){let a=i.match(o);if(a===!1)return!1;o=a}return o}function e(s){return t(s)!==!1}function n(s){let o=t(s);return o===!1?!1:o.length===0}return{matchers:r,matches:e,exactMatch:n}}var Ye=b(w("dns4"),St()),tr=b(w("dns6"),St()),er=b(w("dnsaddr"),St()),yn=b(w("dns"),St()),Od=k(Ye,y(E())),$d=k(tr,y(E())),Vd=k(er,y(E())),$s=k(N(yn,er,Ye,tr),y(E())),Vs=b(w("ip4"),Vt(Ot)),Hs=b(w("ip6"),Vt($t)),xn=N(Vs,Hs),ct=N(xn,yn,Ye,tr,er),Hd=k(N(xn,b(N(yn,er,Ye,tr),y(E())))),qd=k(Vs),Wd=k(Hs),Gd=k(xn),En=b(ct,w("tcp"),ie()),ce=b(ct,w("udp"),ie()),Xd=k(b(En,y(E()))),Qd=k(ce),vn=b(ce,w("quic"),y(E())),rr=b(ce,w("quic-v1"),y(E())),Na=N(vn,rr),jd=k(vn),Kd=k(rr),bn=N(ct,En,ce,vn,rr),qs=N(b(bn,w("ws"),y(E()))),Jd=k(qs),Ws=N(b(bn,w("wss"),y(E())),b(bn,w("tls"),y(b(w("sni"),St())),w("ws"),y(E()))),Zd=k(Ws),Gs=b(ce,w("webrtc-direct"),y(ae()),y(ae()),y(E())),Yd=k(Gs),Xs=b(rr,w("webtransport"),y(ae()),y(ae()),y(E())),tp=k(Xs),Ze=N(qs,Ws,b(En,y(E())),b(Na,y(E())),b(ct,y(E())),Gs,Xs,E()),ep=k(Ze),Ba=b(Ze,w("p2p-circuit"),E()),rp=k(Ba),Ra=N(b(Ze,w("p2p-circuit"),w("webrtc"),y(E())),b(Ze,w("webrtc"),y(E())),b(w("webrtc"),y(E()))),np=k(Ra),za=N(b(ct,w("tcp"),ie(),w("http"),y(E())),b(ct,w("http"),y(E()))),Qs=k(za),Oa=N(b(ct,w("tcp"),N(b(w("443"),w("http")),b(ie(),w("https"))),y(E())),b(ct,w("tls"),w("http"),y(E())),b(ct,w("https"),y(E()))),js=k(Oa),$a=N(b(w("memory"),St(),y(E()))),sp=k($a);var fp=parseInt("0xFFFF",16),dp=new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);var Zs=Ot,Ga=$t,_n=function(r){let t=0;if(r=r.toString().trim(),Zs(r)){let e=new Uint8Array(t+4);return r.split(/\./g).forEach(n=>{e[t++]=parseInt(n,10)&255}),e}if(Ga(r)){let e=r.split(":",8),n;for(n=0;n<e.length;n++){let o=Zs(e[n]),i;o&&(i=_n(e[n]),e[n]=S(i.slice(0,2),"base16")),i!=null&&++n<8&&e.splice(n,0,S(i.slice(2,4),"base16"))}if(e[0]==="")for(;e.length<8;)e.unshift("0");else if(e[e.length-1]==="")for(;e.length<8;)e.push("0");else if(e.length<8){for(n=0;n<e.length&&e[n]!=="";n++);let o=[n,1];for(n=9-e.length;n>0;n--)o.push("0");e.splice.apply(e,o)}let s=new Uint8Array(t+16);for(n=0;n<e.length;n++){let o=parseInt(e[n],16);s[t++]=o>>8&255,s[t++]=o&255}return s}throw new Error("invalid ip address")},Ys=function(r,t=0,e){t=~~t,e=e??r.length-t;let n=new DataView(r.buffer);if(e===4){let s=[];for(let o=0;o<e;o++)s.push(r[t+o]);return s.join(".")}if(e===16){let s=[];for(let o=0;o<e;o+=2)s.push(n.getUint16(t+o).toString(16));return s.join(":").replace(/(^|:)0(:0)*:0(:|$)/,"$1::$3").replace(/:{3,4}/,"::")}return""};var Ht={},Sn={},Qa=[[4,32,"ip4"],[6,16,"tcp"],[33,16,"dccp"],[41,128,"ip6"],[42,-1,"ip6zone"],[43,8,"ipcidr"],[53,-1,"dns",!0],[54,-1,"dns4",!0],[55,-1,"dns6",!0],[56,-1,"dnsaddr",!0],[132,16,"sctp"],[273,16,"udp"],[275,0,"p2p-webrtc-star"],[276,0,"p2p-webrtc-direct"],[277,0,"p2p-stardust"],[280,0,"webrtc-direct"],[281,0,"webrtc"],[290,0,"p2p-circuit"],[301,0,"udt"],[302,0,"utp"],[400,-1,"unix",!1,!0],[421,-1,"ipfs"],[421,-1,"p2p"],[443,0,"https"],[444,96,"onion"],[445,296,"onion3"],[446,-1,"garlic64"],[448,0,"tls"],[449,-1,"sni"],[460,0,"quic"],[461,0,"quic-v1"],[465,0,"webtransport"],[466,-1,"certhash"],[477,0,"ws"],[478,0,"wss"],[479,0,"p2p-websocket-star"],[480,0,"http"],[481,-1,"http-path"],[777,-1,"memory"]];Qa.forEach(r=>{let t=ja(...r);Sn[t.code]=t,Ht[t.name]=t});function ja(r,t,e,n,s){return{code:r,size:t,name:e,resolvable:!!n,path:!!s}}function p(r){if(typeof r=="number"){if(Sn[r]!=null)return Sn[r];throw new Error(`no protocol with code: ${r}`)}else if(typeof r=="string"){if(Ht[r]!=null)return Ht[r];throw new Error(`no protocol with name: ${r}`)}throw new Error(`invalid protocol id type: ${typeof r}`)}var Qp=p("ip4"),jp=p("ip6"),Kp=p("ipcidr");function Ln(r,t){switch(p(r).code){case 4:case 41:return Ja(t);case 42:return In(t);case 43:return S(t,"base10");case 6:case 273:case 33:case 132:return ro(t).toString();case 53:case 54:case 55:case 56:case 400:case 449:case 777:return In(t);case 421:return ec(t);case 444:return eo(t);case 445:return eo(t);case 466:return tc(t);case 481:return globalThis.encodeURIComponent(In(t));default:return S(t,"base16")}}function Tn(r,t){switch(p(r).code){case 4:return to(t);case 41:return to(t);case 42:return An(t);case 43:return U(t,"base10");case 6:case 273:case 33:case 132:return Dn(parseInt(t,10));case 53:case 54:case 55:case 56:case 400:case 449:case 777:return An(t);case 421:return Za(t);case 444:return rc(t);case 445:return nc(t);case 466:return Ya(t);case 481:return An(globalThis.decodeURIComponent(t));default:return U(t,"base16")}}var kn=Object.values(Zt).map(r=>r.decoder),Ka=function(){let r=kn[0].or(kn[1]);return kn.slice(2).forEach(t=>r=r.or(t)),r}();function to(r){if(!Je(r))throw new Error("invalid ip address");return _n(r)}function Ja(r){let t=Ys(r,0,r.length);if(t==null)throw new Error("ipBuff is required");if(!Je(t))throw new Error("invalid ip address");return t}function Dn(r){let t=new ArrayBuffer(2);return new DataView(t).setUint16(0,r),new Uint8Array(t)}function ro(r){return new DataView(r.buffer).getUint16(r.byteOffset)}function An(r){let t=U(r),e=Uint8Array.from(tt(t.length));return H([e,t],e.length+t.length)}function In(r){let t=Q(r);if(r=r.slice(_(t)),r.length!==t)throw new Error("inconsistent lengths");return S(r)}function Za(r){let t;r[0]==="Q"||r[0]==="1"?t=Kt(D.decode(`z${r}`)).bytes:t=$.parse(r).multihash.bytes;let e=Uint8Array.from(tt(t.length));return H([e,t],e.length+t.length)}function Ya(r){let t=Ka.decode(r),e=Uint8Array.from(tt(t.length));return H([e,t],e.length+t.length)}function tc(r){let t=Q(r),e=r.slice(_(t));if(e.length!==t)throw new Error("inconsistent lengths");return"u"+S(e,"base64url")}function ec(r){let t=Q(r),e=r.slice(_(t));if(e.length!==t)throw new Error("inconsistent lengths");return S(e,"base58btc")}function rc(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=Dn(n);return H([e,s],e.length+s.length)}function nc(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=Dn(n);return H([e,s],e.length+s.length)}function eo(r){let t=r.slice(0,r.length-2),e=r.slice(r.length-2),n=S(t,"base32"),s=ro(e);return`${n}:${s}`}function no(r){r=Pn(r);let t=[],e=[],n=null,s=r.split("/").slice(1);if(s.length===1&&s[0]==="")return{bytes:new Uint8Array,string:"/",tuples:[],stringTuples:[],path:null};for(let o=0;o<s.length;o++){let i=s[o],a=p(i);if(a.size===0){t.push([a.code]),e.push([a.code]);continue}if(o++,o>=s.length)throw new nr("invalid address: "+r);if(a.path===!0){n=Pn(s.slice(o).join("/")),t.push([a.code,Tn(a.code,n)]),e.push([a.code,n]);break}let c=Tn(a.code,s[o]);t.push([a.code,c]),e.push([a.code,Ln(a.code,c)])}return{string:so(e),bytes:Cn(t),tuples:t,stringTuples:e,path:n}}function Fn(r){let t=[],e=[],n=null,s=0;for(;s<r.length;){let o=Q(r,s),i=_(o),a=p(o),c=sc(a,r.slice(s+i));if(c===0){t.push([o]),e.push([o]),s+=i;continue}let l=r.slice(s+i,s+i+c);if(s+=c+i,s>r.length)throw new nr("Invalid address Uint8Array: "+S(r,"base16"));t.push([o,l]);let h=Ln(o,l);if(e.push([o,h]),a.path===!0){n=h;break}}return{bytes:Uint8Array.from(r),string:so(e),tuples:t,stringTuples:e,path:n}}function so(r){let t=[];return r.map(e=>{let n=p(e[0]);return t.push(n.name),e.length>1&&e[1]!=null&&t.push(e[1]),null}),Pn(t.join("/"))}function Cn(r){return H(r.map(t=>{let e=p(t[0]),n=Uint8Array.from(tt(e.code));return t.length>1&&t[1]!=null&&(n=H([n,t[1]])),n}))}function sc(r,t){if(r.size>0)return r.size/8;if(r.size===0)return 0;{let e=Q(t instanceof Uint8Array?t:Uint8Array.from(t));return e+_(e)}}function Pn(r){return"/"+r.trim().split("/").filter(t=>t).join("/")}var nr=class extends Error{static name="ParseError";name="ParseError";constructor(t){super(`Error parsing address: ${t}`)}};var oc=Symbol.for("nodejs.util.inspect.custom"),Un=Symbol.for("@multiformats/js-multiaddr/multiaddr"),ic=[p("dns").code,p("dns4").code,p("dns6").code,p("dnsaddr").code],Mn=class extends Error{constructor(t="No available resolver"){super(t),this.name="NoAvailableResolverError"}},sr=class r{bytes;#t;#e;#r;#n;[Un]=!0;constructor(t){t==null&&(t="");let e;if(t instanceof Uint8Array)e=Fn(t);else if(typeof t=="string"){if(t.length>0&&t.charAt(0)!=="/")throw new Error(`multiaddr "${t}" must start with a "/"`);e=no(t)}else if(io(t))e=Fn(t.bytes);else throw new Error("addr must be a string, Buffer, or another Multiaddr");this.bytes=e.bytes,this.#t=e.string,this.#e=e.tuples,this.#r=e.stringTuples,this.#n=e.path}toString(){return this.#t}toJSON(){return this.toString()}toOptions(){let t,e,n,s,o="",i=p("tcp"),a=p("udp"),c=p("ip4"),l=p("ip6"),h=p("dns6"),u=p("ip6zone");for(let[m,d]of this.stringTuples())m===u.code&&(o=`%${d??""}`),ic.includes(m)&&(e=i.name==="tcp"?"tcp":"udp",s=443,n=`${d??""}${o}`,t=m===h.code?6:4),(m===i.code||m===a.code)&&(e=p(m).name==="tcp"?"tcp":"udp",s=parseInt(d??"")),(m===c.code||m===l.code)&&(e=p(m).name==="tcp"?"tcp":"udp",n=`${d??""}${o}`,t=m===l.code?6:4);if(t==null||e==null||n==null||s==null)throw new Error('multiaddr must have a valid format: "/{ip4, ip6, dns4, dns6, dnsaddr}/{address}/{tcp, udp}/{port}".');return{family:t,host:n,transport:e,port:s}}protos(){return this.#e.map(([t])=>Object.assign({},p(t)))}protoCodes(){return this.#e.map(([t])=>t)}protoNames(){return this.#e.map(([t])=>p(t).name)}tuples(){return this.#e.map(([t,e])=>e==null?[t]:[t,e])}stringTuples(){return this.#r.map(([t,e])=>e==null?[t]:[t,e])}encapsulate(t){return t=new r(t),new r(this.toString()+t.toString())}decapsulate(t){let e=t.toString(),n=this.toString(),s=n.lastIndexOf(e);if(s<0)throw new Error(`Address ${this.toString()} does not contain subaddress: ${t.toString()}`);return new r(n.slice(0,s))}decapsulateCode(t){let e=this.tuples();for(let n=e.length-1;n>=0;n--)if(e[n][0]===t)return new r(Cn(e.slice(0,n)));return this}getPeerId(){try{let t=[];this.stringTuples().forEach(([n,s])=>{n===Ht.p2p.code&&t.push([n,s]),n===Ht["p2p-circuit"].code&&(t=[])});let e=t.pop();if(e?.[1]!=null){let n=e[1];return n[0]==="Q"||n[0]==="1"?S(D.decode(`z${n}`),"base58btc"):S($.parse(n).multihash.bytes,"base58btc")}return null}catch{return null}}getPath(){return this.#n}equals(t){return j(this.bytes,t.bytes)}async resolve(t){let e=this.protos().find(o=>o.resolvable);if(e==null)return[this];let n=oo.get(e.name);if(n==null)throw new Mn(`no available resolver for ${e.name}`);return(await n(this,t)).map(o=>le(o))}nodeAddress(){let t=this.toOptions();if(t.transport!=="tcp"&&t.transport!=="udp")throw new Error(`multiaddr must have a valid format - no protocol with name: "${t.transport}". Must have a valid transport protocol: "{tcp, udp}"`);return{family:t.family,address:t.host,port:t.port}}isThinWaistAddress(t){let e=(t??this).protos();return!(e.length!==2||e[0].code!==4&&e[0].code!==41||e[1].code!==6&&e[1].code!==273)}[oc](){return`Multiaddr(${this.#t})`}};var oo=new Map;function io(r){return!!r?.[Un]}function le(r){return new sr(r)}var ac=[p("tcp").code,p("dns").code,p("dnsaddr").code,p("dns4").code,p("dns6").code];function ao(r){return uo("sni",r)?.[1]}function co(r){let t=uo("tcp",r)?.[1];return t==null?"":`:${t}`}function uo(r,t){let e;try{e=p(r).code}catch{return}for(let[n,s]of t)if(n===e&&s!=null)return[n,s]}function lo(r){return r.some(([t,e])=>t===p("tls").code)}function Z(r,t,e){let n=ho[p(r).name];if(n==null)throw new Error(`Can't interpret protocol ${p(r).name}`);let s=n(t,e);return r===p("ip6").code?`[${s}]`:s}var ho={ip4:(r,t)=>r,ip6:(r,t)=>t.length===0?r:`[${r}]`,tcp:(r,t)=>{let e=t.pop();if(e==null)throw new Error("Unexpected end of multiaddr");return`tcp://${Z(e[0],e[1]??"",t)}:${r}`},udp:(r,t)=>{let e=t.pop();if(e==null)throw new Error("Unexpected end of multiaddr");return`udp://${Z(e[0],e[1]??"",t)}:${r}`},dnsaddr:(r,t)=>r,dns4:(r,t)=>r,dns6:(r,t)=>r,dns:(r,t)=>r,ipfs:(r,t)=>{let e=t.pop();if(e==null)throw new Error("Unexpected end of multiaddr");return`${Z(e[0],e[1]??"",t)}`},p2p:(r,t)=>{let e=t.pop();if(e==null)throw new Error("Unexpected end of multiaddr");return`${Z(e[0],e[1]??"",t)}`},http:(r,t)=>{let e=lo(t),n=ao(t),s=co(t);if(e&&n!=null)return`https://${n}${s}`;let o=e?"https://":"http://",i=t.pop();if(i==null)throw new Error("Unexpected end of multiaddr");let a=Z(i[0],i[1]??"",t);return a=a.replace("tcp://",""),`${o}${a}`},"http-path":(r,t)=>{let e=t.pop();if(e==null)throw new Error("Unexpected end of multiaddr");let n=Z(e[0],e[1]??"",t),s=decodeURIComponent(r);return`${n}/${s}`},tls:(r,t)=>{let e=t.pop();if(e==null)throw new Error("Unexpected end of multiaddr");return Z(e[0],e[1]??"",t)},sni:(r,t)=>{let e=t.pop();if(e==null)throw new Error("Unexpected end of multiaddr");return Z(e[0],e[1]??"",t)},https:(r,t)=>{let e=t.pop();if(e==null)throw new Error("Unexpected end of multiaddr");let n=Z(e[0],e[1]??"",t);return n=n.replace("tcp://",""),`https://${n}`},ws:(r,t)=>{let e=lo(t),n=ao(t),s=co(t);if(e&&n!=null)return`wss://${n}${s}`;let o=e?"wss://":"ws://",i=t.pop();if(i==null)throw new Error("Unexpected end of multiaddr");let a=Z(i[0],i[1]??"",t);return a=a.replace("tcp://",""),`${o}${a}`},wss:(r,t)=>{let e=t.pop();if(e==null)throw new Error("Unexpected end of multiaddr");let n=Z(e[0],e[1]??"",t);return n=n.replace("tcp://",""),`wss://${n}`}};function fo(r,t){let n=le(r).stringTuples(),s=n.pop();if(s==null)throw new Error("Unexpected end of multiaddr");let o=p(s[0]),i=ho[o.name];if(i==null)throw new Error(`No interpreter found for ${o.name}`);let a=i(s[1]??"",n);return t?.assumeHttp!==!1&&ac.includes(s[0])&&(a=a.replace(/^.*:\/\//,""),s[1]==="443"?a=`https://${a}`:a=`http://${a}`),(a.startsWith("http://")||a.startsWith("https://")||a.startsWith("ws://")||a.startsWith("wss://"))&&(a=new URL(a).toString(),a.endsWith("/")&&(a=a.substring(0,a.length-1))),a}var or=class{url;#t=0;#e=0;#r=0;#n=0;#s=new Map;log;constructor(t,e){this.url=t instanceof URL?t:new URL(t),this.log=e.forComponent(`helia:trustless-gateway-block-broker:${this.url.hostname}`)}#o(t){let e=t.multihash.bytes;return it.encode(e)}async getRawBlock(t,e){let n=new URL(this.url.toString());if(n.pathname=`/ipfs/${t.toString()}`,n.search="?format=raw",e?.aborted===!0)throw new Error(`Signal to fetch raw block for CID ${t} from gateway ${this.url} was aborted prior to fetch`);let s=this.#o(t),o=new AbortController,i=()=>{o.abort()};e?.addEventListener("abort",i);try{let a=this.#s.get(s);return a==null&&(this.#t++,a=fetch(n.toString(),{signal:o.signal,headers:{Accept:"application/vnd.ipld.raw"},cache:"force-cache"}).then(async c=>{if(this.log("GET %s %d",n,c.status),!c.ok)throw this.#e++,new Error(`unable to fetch raw block for CID ${t} from gateway ${this.url}`);return this.#n++,new Uint8Array(await c.arrayBuffer())}),this.#s.set(s,a)),await a}catch{throw e?.aborted===!0?new Error(`fetching raw block for CID ${t} from gateway ${this.url} was aborted`):(this.#e++,new Error(`unable to fetch raw block for CID ${t}`))}finally{e?.removeEventListener("abort",i),this.#s.delete(s)}}reliability(){return this.#t===0?1:this.#r>0?-1/0:this.#n/(this.#t+this.#e*3)}incrementInvalidBlocks(){this.#r++}getStats(){return{attempts:this.#t,errors:this.#e,invalidBlocks:this.#r,successes:this.#n,pendingResponses:this.#s.size}}};function cc(r,t,e){return r.filter(n=>{if(js.matches(n)||t&&Qs.matches(n))return e||$s.matches(n)?!0:Os(n.toOptions().host)===!1;if(!t&&e){let{host:s}=n.toOptions();if(s==="127.0.0.1"||s==="localhost"||s.endsWith(".localhost"))return!0}return!1})}async function*ir(r,t,e,n,s,o){for await(let i of t.findProviders(r,o)){let a=cc(i.multiaddrs,n,s);if(a.length===0)continue;let c=fo(a[0]);yield new or(c,e)}}var Nn=class extends _t{routing;allowInsecure;allowLocal;constructor(t,e){super(t,{...e,name:"helia:trustless-gateway:session"}),this.routing=t.routing,this.allowInsecure=e.allowInsecure??ar,this.allowLocal=e.allowLocal??cr}async queryProvider(t,e,n){this.log("fetching BLOCK for %c from %s",t,e.url);let s=await e.getRawBlock(t,n.signal);return this.log.trace("got block for %c from %s",t,e.url),await n.validateFn?.(s),s}async*findNewProviders(t,e={}){yield*ir(t,this.routing,this.logger,this.allowInsecure,this.allowLocal,e)}toEvictionKey(t){return t.url.toString()}equals(t,e){return t.url.toString()===e.url.toString()}};function po(r,t){return new Nn(r,t)}var lr=class{allowInsecure;allowLocal;routing;log;logger;constructor(t,e={}){this.log=t.logger.forComponent("helia:trustless-gateway-block-broker"),this.logger=t.logger,this.routing=t.routing,this.allowInsecure=e.allowInsecure??ar,this.allowLocal=e.allowLocal??cr}async retrieve(t,e={}){let n=[];for await(let s of ir(t,this.routing,this.logger,this.allowInsecure,this.allowLocal,e)){this.log("getting block for %c from %s",t,s.url);try{let o=await s.getRawBlock(t,e.signal);this.log.trace("got block for %c from %s",t,s.url);try{await e.validateFn?.(o)}catch(i){this.log.error("failed to validate block for %c from %s",t,s.url,i);continue}return o}catch(o){if(this.log.error("failed to get block for %c from %s",t,s.url,o),o instanceof Error?n.push(o):n.push(new Error(`Unable to fetch raw block for CID ${t} from gateway ${s.url}`)),e.signal?.aborted===!0){this.log.trace("request aborted while fetching raw block for CID %c from gateway %s",t,s.url);break}}}throw n.length>0?new AggregateError(n,`Unable to fetch raw block for CID ${t} from any gateway`):new Error(`Unable to fetch raw block for CID ${t} from any gateway`)}createSession(t={}){return po({logger:this.logger,routing:this.routing},{...t,allowLocal:this.allowLocal,allowInsecure:this.allowInsecure})}};var ar=!1,cr=!1;function mo(r={}){return t=>new lr(t,r)}return Eo(lc);})();
|
|
2
|
+
"use strict";var HeliaBlockBrokers=(()=>{var xo=Object.create;var he=Object.defineProperty;var Eo=Object.getOwnPropertyDescriptor;var vo=Object.getOwnPropertyNames;var _o=Object.getPrototypeOf,So=Object.prototype.hasOwnProperty;var On=(r,t)=>()=>(t||r((t={exports:{}}).exports,t),t.exports),O=(r,t)=>{for(var e in t)he(r,e,{get:t[e],enumerable:!0})},$n=(r,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of vo(t))!So.call(r,s)&&s!==e&&he(r,s,{get:()=>t[s],enumerable:!(n=Eo(t,s))||n.enumerable});return r};var qn=(r,t,e)=>(e=r!=null?xo(_o(r)):{},$n(t||!r||!r.__esModule?he(e,"default",{value:r,enumerable:!0}):e,r)),ko=r=>$n(he({},"__esModule",{value:!0}),r);var Ms=On((Mf,Cs)=>{Cs.exports=function(r){if(!r)throw Error("hashlru must have a max value, of type number, greater than 0");var t=0,e=Object.create(null),n=Object.create(null);function s(o,i){e[o]=i,t++,t>=r&&(t=0,n=e,e=Object.create(null))}return{has:function(o){return e[o]!==void 0||n[o]!==void 0},remove:function(o){e[o]!==void 0&&(e[o]=void 0),n[o]!==void 0&&(n[o]=void 0)},get:function(o){var i=e[o];if(i!==void 0)return i;if((i=n[o])!==void 0)return s(o,i),i},set:function(o,i){e[o]!==void 0?e[o]=i:s(o,i)},clear:function(){e=Object.create(null),n=Object.create(null)}}}});var qs=On(oe=>{(function(){var r,t,e,n,s,o,i,a;a=function(c){var l,u,h,f;return l=(c&255<<24)>>>24,u=(c&255<<16)>>>16,h=(c&65280)>>>8,f=c&255,[l,u,h,f].join(".")},i=function(c){var l,u,h,f,m,d;for(l=[],h=f=0;f<=3&&c.length!==0;h=++f){if(h>0){if(c[0]!==".")throw new Error("Invalid IP");c=c.substring(1)}d=t(c),m=d[0],u=d[1],c=c.substring(u),l.push(m)}if(c.length!==0)throw new Error("Invalid IP");switch(l.length){case 1:if(l[0]>4294967295)throw new Error("Invalid IP");return l[0]>>>0;case 2:if(l[0]>255||l[1]>16777215)throw new Error("Invalid IP");return(l[0]<<24|l[1])>>>0;case 3:if(l[0]>255||l[1]>255||l[2]>65535)throw new Error("Invalid IP");return(l[0]<<24|l[1]<<16|l[2])>>>0;case 4:if(l[0]>255||l[1]>255||l[2]>255||l[3]>255)throw new Error("Invalid IP");return(l[0]<<24|l[1]<<16|l[2]<<8|l[3])>>>0;default:throw new Error("Invalid IP")}},e=function(c){return c.charCodeAt(0)},n=e("0"),o=e("a"),s=e("A"),t=function(c){var l,u,h,f,m;for(f=0,l=10,u="9",h=0,c.length>1&&c[h]==="0"&&(c[h+1]==="x"||c[h+1]==="X"?(h+=2,l=16):"0"<=c[h+1]&&c[h+1]<="9"&&(h++,l=8,u="7")),m=h;h<c.length;){if("0"<=c[h]&&c[h]<=u)f=f*l+(e(c[h])-n)>>>0;else if(l===16)if("a"<=c[h]&&c[h]<="f")f=f*l+(10+e(c[h])-o)>>>0;else if("A"<=c[h]&&c[h]<="F")f=f*l+(10+e(c[h])-s)>>>0;else break;else break;if(f>4294967295)throw new Error("too large");h++}if(h===m)throw new Error("empty octet");return[f,h]},r=function(){function c(l,u){var h,f,m,d;if(typeof l!="string")throw new Error("Missing `net' parameter");if(u||(d=l.split("/",2),l=d[0],u=d[1]),u||(u=32),typeof u=="string"&&u.indexOf(".")>-1){try{this.maskLong=i(u)}catch(v){throw h=v,new Error("Invalid mask: "+u)}for(f=m=32;m>=0;f=--m)if(this.maskLong===4294967295<<32-f>>>0){this.bitmask=f;break}}else if(u||u===0)this.bitmask=parseInt(u,10),this.maskLong=0,this.bitmask>0&&(this.maskLong=4294967295<<32-this.bitmask>>>0);else throw new Error("Invalid mask: empty");try{this.netLong=(i(l)&this.maskLong)>>>0}catch(v){throw h=v,new Error("Invalid net address: "+l)}if(!(this.bitmask<=32))throw new Error("Invalid mask for ip4: "+u);this.size=Math.pow(2,32-this.bitmask),this.base=a(this.netLong),this.mask=a(this.maskLong),this.hostmask=a(~this.maskLong),this.first=this.bitmask<=30?a(this.netLong+1):this.base,this.last=this.bitmask<=30?a(this.netLong+this.size-2):a(this.netLong+this.size-1),this.broadcast=this.bitmask<=30?a(this.netLong+this.size-1):void 0}return c.prototype.contains=function(l){return typeof l=="string"&&(l.indexOf("/")>0||l.split(".").length!==4)&&(l=new c(l)),l instanceof c?this.contains(l.base)&&this.contains(l.broadcast||l.last):(i(l)&this.maskLong)>>>0===(this.netLong&this.maskLong)>>>0},c.prototype.next=function(l){return l==null&&(l=1),new c(a(this.netLong+this.size*l),this.mask)},c.prototype.forEach=function(l){var u,h,f;for(f=i(this.first),h=i(this.last),u=0;f<=h;)l(a(f),f,u),u++,f++},c.prototype.toString=function(){return this.base+"/"+this.bitmask},c}(),oe.ip2long=i,oe.long2ip=a,oe.Netmask=r}).call(oe)});var gc={};O(gc,{bitswap:()=>Os,trustlessGateway:()=>yo});var X=class extends Error{static name="AbortError";constructor(t="The operation was aborted"){super(t),this.name="AbortError"}};var fe=class extends Error{static name="InvalidParametersError";constructor(t="Invalid parameters"){super(t),this.name="InvalidParametersError"}};var de=class extends Error{static name="UnsupportedProtocolError";constructor(t="Unsupported protocol error"){super(t),this.name="UnsupportedProtocolError"}};var pe=class extends Error{static name="TimeoutError";constructor(t="Timed out"){super(t),this.name="TimeoutError"}},me=class extends Error{static name="NotStartedError";constructor(t="Not started"){super(t),this.name="NotStartedError"}};var tt=class extends EventTarget{#t=new Map;constructor(){super()}listenerCount(t){let e=this.#t.get(t);return e==null?0:e.length}addEventListener(t,e,n){super.addEventListener(t,e,n);let s=this.#t.get(t);s==null&&(s=[],this.#t.set(t,s)),s.push({callback:e,once:(n!==!0&&n!==!1&&n?.once)??!1})}removeEventListener(t,e,n){super.removeEventListener(t.toString(),e??null,n);let s=this.#t.get(t);s!=null&&(s=s.filter(({callback:o})=>o!==e),this.#t.set(t,s))}dispatchEvent(t){let e=super.dispatchEvent(t),n=this.#t.get(t.type);return n==null||(n=n.filter(({once:s})=>!s),this.#t.set(t.type,n)),e}safeDispatchEvent(t,e={}){return this.dispatchEvent(new CustomEvent(t,e))}};function Hn(r){let t=new globalThis.AbortController;function e(){t.abort();for(let o of r)o?.removeEventListener!=null&&o.removeEventListener("abort",e)}for(let o of r){if(o?.aborted===!0){e();break}o?.addEventListener!=null&&o.addEventListener("abort",e)}function n(){for(let o of r)o?.removeEventListener!=null&&o.removeEventListener("abort",e)}let s=t.signal;return s.clear=n,s}function P(){let r={};return r.promise=new Promise((t,e)=>{r.resolve=t,r.reject=e}),r}var ge=class{buffer;mask;top;btm;next;constructor(t){if(!(t>0)||(t-1&t)!==0)throw new Error("Max size for a FixedFIFO should be a power of two");this.buffer=new Array(t),this.mask=t-1,this.top=0,this.btm=0,this.next=null}push(t){return this.buffer[this.top]!==void 0?!1:(this.buffer[this.top]=t,this.top=this.top+1&this.mask,!0)}shift(){let t=this.buffer[this.btm];if(t!==void 0)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,t}isEmpty(){return this.buffer[this.btm]===void 0}},kt=class{size;hwm;head;tail;constructor(t={}){this.hwm=t.splitLimit??16,this.head=new ge(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 ge(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 dr=class extends Error{type;code;constructor(t,e){super(t??"The operation was aborted"),this.type="aborted",this.code=e??"ABORT_ERR"}};function we(r={}){return Io(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 Io(r,t){t=t??{};let e=t.onEnd,n=new kt,s,o,i,a=P(),c=async()=>{try{return n.isEmpty()?i?{done:!0}:await new Promise((g,L)=>{o=B=>{o=null,n.push(B);try{g(r(n))}catch(T){L(T)}return s}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=P()})}},l=g=>o!=null?o(g):(n.push(g),s),u=g=>(n=new kt,o!=null?o({error:g}):(n.push({error:g}),s)),h=g=>{if(i)return s;if(t?.objectMode!==!0&&g?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return l({done:!1,value:g})},f=g=>i?s:(i=!0,g!=null?u(g):l({done:!0})),m=()=>(n=new kt,f(),{done:!0}),d=g=>(f(g),{done:!0});if(s={[Symbol.asyncIterator](){return this},next:c,return:m,throw:d,push:h,end:f,get readableLength(){return n.size},onEmpty:async g=>{let L=g?.signal;if(L?.throwIfAborted(),n.isEmpty())return;let B,T;L!=null&&(B=new Promise((z,H)=>{T=()=>{H(new dr)},L.addEventListener("abort",T)}));try{await Promise.race([a.promise,B])}finally{T!=null&&L!=null&&L?.removeEventListener("abort",T)}}},e==null)return s;let v=s;return s={[Symbol.asyncIterator](){return this},next(){return v.next()},throw(g){return v.throw(g),e!=null&&(e(g),e=void 0),{done:!0}},return(){return v.return(),e!=null&&(e(),e=void 0),{done:!0}},push:h,end(g){return v.end(g),e!=null&&(e(g),e=void 0),s},get readableLength(){return v.readableLength},onEmpty:g=>v.onEmpty(g)},s}var pr=class extends Error{type;code;constructor(t,e){super(t??"The operation was aborted"),this.type="aborted",this.name="AbortError",this.code=e??"ABORT_ERR"}};async function Q(r,t,e,n){let s=new pr(n?.errorMessage,n?.errorCode);return e?.aborted===!0?Promise.reject(s):new Promise((o,i)=>{function a(){e?.removeEventListener("abort",u),r.removeEventListener(t,c),n?.errorEvent!=null&&r.removeEventListener(n.errorEvent,l)}let c=h=>{try{if(n?.filter?.(h)===!1)return}catch(f){a(),i(f);return}a(),o(h)},l=h=>{a(),i(h.detail)},u=()=>{a(),i(s)};e?.addEventListener("abort",u),r.addEventListener(t,c),n?.errorEvent!=null&&r.addEventListener(n.errorEvent,l)})}var be=class extends Error{static name="QueueFullError";constructor(t="The queue was full"){super(t),this.name="QueueFullError"}};var ye=class extends Error{type;code;constructor(t,e,n){super(t??"The operation was aborted"),this.type="aborted",this.name=n??"AbortError",this.code=e??"ABORT_ERR"}};async function xe(r,t,e){if(t==null)return r;if(t.aborted)return r.catch(()=>{}),Promise.reject(new ye(e?.errorMessage,e?.errorCode,e?.errorName));let n,s=new ye(e?.errorMessage,e?.errorCode,e?.errorName);try{return await Promise.race([r,new Promise((o,i)=>{n=()=>{i(s)},t.addEventListener("abort",n)})])}finally{n!=null&&t.removeEventListener("abort",n)}}var Ee=class{deferred;signal;constructor(t){this.signal=t,this.deferred=P(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new X)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function Ao(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var ve=class{id;fn;options;recipients;status;timeline;controller;constructor(t,e){this.id=Ao(),this.status="queued",this.fn=t,this.options=e,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,this.controller.signal,this.onAbort=this.onAbort.bind(this)}abort(t){this.controller.abort(t)}onAbort(){this.recipients.reduce((e,n)=>e&&n.signal?.aborted===!0,!0)&&(this.controller.abort(new X),this.cleanup())}async join(t={}){let e=new Ee(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 xe(this.fn({...this.options??{},signal:this.controller.signal}),this.controller.signal);this.recipients.forEach(e=>{e.deferred.resolve(t)}),this.status="complete"}catch(t){this.recipients.forEach(e=>{e.deferred.reject(t)}),this.status="errored"}finally{this.timeline.finished=Date.now(),this.cleanup()}}cleanup(){this.recipients.forEach(t=>{t.cleanup(),t.signal?.removeEventListener("abort",this.onAbort)})}};var It=class extends tt{concurrency;maxSize;queue;pending;sort;constructor(t={}){super(),this.concurrency=t.concurrency??Number.POSITIVE_INFINITY,this.maxSize=t.maxSize??Number.POSITIVE_INFINITY,this.pending=0,t.metricName!=null&&t.metrics?.registerMetricGroup(t.metricName,{calculate:()=>({size:this.queue.length,running:this.pending,queued:this.queue.length-this.pending})}),this.sort=t.sort,this.queue=[]}tryToStartAnother(){if(this.size===0)return queueMicrotask(()=>{this.safeDispatchEvent("empty")}),this.running===0&&queueMicrotask(()=>{this.safeDispatchEvent("idle")}),!1;if(this.pending<this.concurrency){let t;for(let e of this.queue)if(e.status==="queued"){t=e;break}return t==null?!1:(this.safeDispatchEvent("active"),this.pending++,t.run().finally(()=>{for(let e=0;e<this.queue.length;e++)if(this.queue[e]===t){this.queue.splice(e,1);break}this.pending--,this.tryToStartAnother(),this.safeDispatchEvent("next")}),!0)}return!1}enqueue(t){this.queue.push(t),this.sort!=null&&this.queue.sort(this.sort)}async add(t,e){if(e?.signal?.throwIfAborted(),this.size===this.maxSize)throw new be;let n=new ve(t,e);return this.enqueue(n),this.safeDispatchEvent("add"),this.tryToStartAnother(),n.join(e).then(s=>(this.safeDispatchEvent("completed",{detail:s}),this.safeDispatchEvent("success",{detail:{job:n,result:s}}),s)).catch(s=>{if(n.status==="queued"){for(let o=0;o<this.queue.length;o++)if(this.queue[o]===n){this.queue.splice(o,1);break}}throw this.safeDispatchEvent("error",{detail:s}),this.safeDispatchEvent("failure",{detail:{job:n,error:s}}),s})}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(t=>{t.abort(new X)}),this.clear()}async onEmpty(t){this.size!==0&&await Q(this,"empty",t?.signal)}async onSizeLessThan(t,e){this.size<t||await Q(this,"next",e?.signal,{filter:()=>this.size<t})}async onIdle(t){this.pending===0&&this.size===0||await Q(this,"idle",t?.signal)}get size(){return this.queue.length}get queued(){return this.queue.length-this.pending}get running(){return this.pending}async*toGenerator(t){t?.signal?.throwIfAborted();let e=we({objectMode:!0}),n=c=>{c!=null?this.abort():this.clear(),e.end(c)},s=c=>{c.detail!=null&&e.push(c.detail)},o=c=>{n(c.detail)},i=()=>{n()},a=()=>{n(new X("Queue aborted"))};this.addEventListener("completed",s),this.addEventListener("error",o),this.addEventListener("idle",i),t?.signal?.addEventListener("abort",a);try{yield*e}finally{this.removeEventListener("completed",s),this.removeEventListener("error",o),this.removeEventListener("idle",i),t?.signal?.removeEventListener("abort",a),n()}}};var _e=class extends It{has(t){return this.find(t)!=null}find(t){return this.queue.find(e=>t.equals(e.options.peerId))}};function Lo(r){return r[Symbol.asyncIterator]!=null}function To(r){if(Lo(r))return(async()=>{for await(let t of r);})();for(let t of r);}var gr=To;function N(r=0){return new Uint8Array(r)}function F(r=0){return new Uint8Array(r)}var Do=Math.pow(2,7),Po=Math.pow(2,14),No=Math.pow(2,21),wr=Math.pow(2,28),br=Math.pow(2,35),yr=Math.pow(2,42),xr=Math.pow(2,49),x=128,C=127;function _(r){if(r<Do)return 1;if(r<Po)return 2;if(r<No)return 3;if(r<wr)return 4;if(r<br)return 5;if(r<yr)return 6;if(r<xr)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function Er(r,t,e=0){switch(_(r)){case 8:t[e++]=r&255|x,r/=128;case 7:t[e++]=r&255|x,r/=128;case 6:t[e++]=r&255|x,r/=128;case 5:t[e++]=r&255|x,r/=128;case 4:t[e++]=r&255|x,r>>>=7;case 3:t[e++]=r&255|x,r>>>=7;case 2:t[e++]=r&255|x,r>>>=7;case 1:{t[e++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return t}function Fo(r,t,e=0){switch(_(r)){case 8:t.set(e++,r&255|x),r/=128;case 7:t.set(e++,r&255|x),r/=128;case 6:t.set(e++,r&255|x),r/=128;case 5:t.set(e++,r&255|x),r/=128;case 4:t.set(e++,r&255|x),r>>>=7;case 3:t.set(e++,r&255|x),r>>>=7;case 2:t.set(e++,r&255|x),r>>>=7;case 1:{t.set(e++,r&255),r>>>=7;break}default:throw new Error("unreachable")}return t}function vr(r,t){let e=r[t],n=0;if(n+=e&C,e<x||(e=r[t+1],n+=(e&C)<<7,e<x)||(e=r[t+2],n+=(e&C)<<14,e<x)||(e=r[t+3],n+=(e&C)<<21,e<x)||(e=r[t+4],n+=(e&C)*wr,e<x)||(e=r[t+5],n+=(e&C)*br,e<x)||(e=r[t+6],n+=(e&C)*yr,e<x)||(e=r[t+7],n+=(e&C)*xr,e<x))return n;throw new RangeError("Could not decode varint")}function Co(r,t){let e=r.get(t),n=0;if(n+=e&C,e<x||(e=r.get(t+1),n+=(e&C)<<7,e<x)||(e=r.get(t+2),n+=(e&C)<<14,e<x)||(e=r.get(t+3),n+=(e&C)<<21,e<x)||(e=r.get(t+4),n+=(e&C)*wr,e<x)||(e=r.get(t+5),n+=(e&C)*br,e<x)||(e=r.get(t+6),n+=(e&C)*yr,e<x)||(e=r.get(t+7),n+=(e&C)*xr,e<x))return n;throw new RangeError("Could not decode varint")}function et(r,t,e=0){return t==null&&(t=F(_(r))),t instanceof Uint8Array?Er(r,t,e):Fo(r,t,e)}function j(r,t=0){return r instanceof Uint8Array?vr(r,t):Co(r,t)}function V(r,t){t==null&&(t=r.reduce((s,o)=>s+o.length,0));let e=F(t),n=0;for(let s of r)e.set(s,n),n+=s.length;return e}function K(r,t){if(r===t)return!0;if(r.byteLength!==t.byteLength)return!1;for(let e=0;e<r.byteLength;e++)if(r[e]!==t[e])return!1;return!0}var Wn=Symbol.for("@achingbrain/uint8arraylist");function Vn(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 ke(r){return!!r?.[Wn]}var At=class r{bufs;length;[Wn]=!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(ke(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(ke(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=Vn(this.bufs,t);return e.buf[e.index]}set(t,e){let n=Vn(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(ke(t))for(let n=0;n<t.length;n++)this.set(e+n,t.get(n));else throw new Error("Could not write value, must be an Uint8Array or a Uint8ArrayList")}consume(t){if(t=Math.trunc(t),!(Number.isNaN(t)||t<=0)){if(t===this.byteLength){this.bufs=[],this.length=0;return}for(;this.bufs.length>0;)if(t>=this.bufs[0].byteLength)t-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift();else{this.bufs[0]=this.bufs[0].subarray(t),this.length-=t;break}}}slice(t,e){let{bufs:n,length:s}=this._subList(t,e);return V(n,s)}subarray(t,e){let{bufs:n,length:s}=this._subList(t,e);return n.length===1?n[0]:V(n,s)}sublist(t,e){let{bufs:n,length:s}=this._subList(t,e),o=new r;return o.length=s,o.bufs=[...n],o}_subList(t,e){if(t=t??0,e=e??this.length,t<0&&(t=this.length+t),e<0&&(e=this.length+e),t<0||e>this.length)throw new RangeError("index is out of bounds");if(t===e)return{bufs:[],length:0};if(t===0&&e===this.length)return{bufs:this.bufs,length:this.length};let n=[],s=0;for(let o=0;o<this.bufs.length;o++){let i=this.bufs[o],a=s,c=a+i.byteLength;if(s=c,t>=c)continue;let l=t>=a&&t<c,u=e>a&&e<=c;if(l&&u){if(t===a&&e===c){n.push(i);break}let h=t-a;n.push(i.subarray(h,h+(e-t)));break}if(l){if(t===0){n.push(i);continue}n.push(i.subarray(t-a));continue}if(u){if(e===c){n.push(i);break}n.push(i.subarray(0,e-a));break}n.push(i)}return{bufs:n,length:e-t}}indexOf(t,e=0){if(!ke(t)&&!(t instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');let n=t instanceof Uint8Array?t:t.subarray();if(e=Number(e??0),isNaN(e)&&(e=0),e<0&&(e=this.length+e),e<0&&(e=0),t.length===0)return e>this.length?this.length:e;let s=n.byteLength;if(s===0)throw new TypeError("search must be at least 1 byte long");let o=256,i=new Int32Array(o);for(let h=0;h<o;h++)i[h]=-1;for(let h=0;h<s;h++)i[n[h]]=h;let a=i,c=this.byteLength-n.byteLength,l=n.byteLength-1,u;for(let h=e;h<=c;h+=u){u=0;for(let f=l;f>=0;f--){let m=this.get(h+f);if(n[f]!==m){u=Math.max(1,f-a[m]);break}}if(u===0)return h}return-1}getInt8(t){let e=this.subarray(t,t+1);return new DataView(e.buffer,e.byteOffset,e.byteLength).getInt8(0)}setInt8(t,e){let n=F(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt8(0,e),this.write(n,t)}getInt16(t,e){let n=this.subarray(t,t+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt16(0,e)}setInt16(t,e,n){let s=N(2);new DataView(s.buffer,s.byteOffset,s.byteLength).setInt16(0,e,n),this.write(s,t)}getInt32(t,e){let n=this.subarray(t,t+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt32(0,e)}setInt32(t,e,n){let s=N(4);new DataView(s.buffer,s.byteOffset,s.byteLength).setInt32(0,e,n),this.write(s,t)}getBigInt64(t,e){let n=this.subarray(t,t+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigInt64(0,e)}setBigInt64(t,e,n){let s=N(8);new DataView(s.buffer,s.byteOffset,s.byteLength).setBigInt64(0,e,n),this.write(s,t)}getUint8(t){let e=this.subarray(t,t+1);return new DataView(e.buffer,e.byteOffset,e.byteLength).getUint8(0)}setUint8(t,e){let n=F(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint8(0,e),this.write(n,t)}getUint16(t,e){let n=this.subarray(t,t+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint16(0,e)}setUint16(t,e,n){let s=N(2);new DataView(s.buffer,s.byteOffset,s.byteLength).setUint16(0,e,n),this.write(s,t)}getUint32(t,e){let n=this.subarray(t,t+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint32(0,e)}setUint32(t,e,n){let s=N(4);new DataView(s.buffer,s.byteOffset,s.byteLength).setUint32(0,e,n),this.write(s,t)}getBigUint64(t,e){let n=this.subarray(t,t+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigUint64(0,e)}setBigUint64(t,e,n){let s=N(8);new DataView(s.buffer,s.byteOffset,s.byteLength).setBigUint64(0,e,n),this.write(s,t)}getFloat32(t,e){let n=this.subarray(t,t+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat32(0,e)}setFloat32(t,e,n){let s=N(4);new DataView(s.buffer,s.byteOffset,s.byteLength).setFloat32(0,e,n),this.write(s,t)}getFloat64(t,e){let n=this.subarray(t,t+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat64(0,e)}setFloat64(t,e,n){let s=N(8);new DataView(s.buffer,s.byteOffset,s.byteLength).setFloat64(0,e,n),this.write(s,t)}equals(t){if(t==null||!(t instanceof r)||t.bufs.length!==this.bufs.length)return!1;for(let e=0;e<this.bufs.length;e++)if(!K(this.bufs[e],t.bufs[e]))return!1;return!0}static fromUint8Arrays(t,e){let n=new r;return n.bufs=t,e==null&&(e=t.reduce((s,o)=>s+o.byteLength,0)),n.length=e,n}};var Ie=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},Lt=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},Ae=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"},Vt=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};function Le(r){return r[Symbol.asyncIterator]!=null}function Gn(r,t){if(r.byteLength>t)throw new Lt("Message length too long")}var De=r=>{let t=_(r),e=F(t);return et(r,e),De.bytes=t,e};De.bytes=0;function Pe(r,t){t=t??{};let e=t.lengthEncoder??De,n=t?.maxDataLength??4194304;function*s(o){Gn(o,n);let i=e(o.byteLength);i instanceof Uint8Array?yield i:yield*i,o instanceof Uint8Array?yield o:yield*o}return Le(r)?async function*(){for await(let o of r)yield*s(o)}():function*(){for(let o of r)yield*s(o)}()}Pe.single=(r,t)=>{t=t??{};let e=t.lengthEncoder??De,n=t?.maxDataLength??4194304;return Gn(r,n),new At(e(r.byteLength),r)};var ft;(function(r){r[r.LENGTH=0]="LENGTH",r[r.DATA=1]="DATA"})(ft||(ft={}));var _r=r=>{let t=j(r);return _r.bytes=_(t),t};_r.bytes=0;function Wt(r,t){let e=new At,n=ft.LENGTH,s=-1,o=t?.lengthDecoder??_r,i=t?.maxLengthLength??8,a=t?.maxDataLength??4194304;function*c(){for(;e.byteLength>0;){if(n===ft.LENGTH)try{if(s=o(e),s<0)throw new Ie("Invalid message length");if(s>a)throw new Lt("Message length too long");let l=o.bytes;e.consume(l),t?.onLength!=null&&t.onLength(s),n=ft.DATA}catch(l){if(l instanceof RangeError){if(e.byteLength>i)throw new Ae("Message length length too long");break}throw l}if(n===ft.DATA){if(e.byteLength<s)break;let l=e.sublist(0,s);e.consume(s),t?.onData!=null&&t.onData(l),yield l,n=ft.LENGTH}}}return Le(r)?async function*(){for await(let l of r)e.append(l),yield*c();if(e.byteLength>0)throw new Vt("Unexpected end of input")}():function*(){for(let l of r)e.append(l),yield*c();if(e.byteLength>0)throw new Vt("Unexpected end of input")}()}Wt.fromReader=(r,t)=>{let e=1,n=async function*(){for(;;)try{let{done:o,value:i}=await r.next(e);if(o===!0)return;i!=null&&(yield i)}catch(o){if(o.code==="ERR_UNDER_READ")return{done:!0,value:null};throw o}finally{e=1}}();return Wt(n,{...t??{},onLength:o=>{e=o}})};function Ro(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 Xn=Ro;function Bo(r){return r[Symbol.asyncIterator]!=null}function zo(r,t){let e=0;if(Bo(r))return async function*(){for await(let c of r)yield t(c,e++)}();let n=Xn(r),{value:s,done:o}=n.next();if(o===!0)return function*(){}();let i=t(s,e++);if(typeof i.then=="function")return async function*(){yield await i;for await(let c of n)yield t(c,e++)}();let a=t;return function*(){yield i;for(let c of n)yield a(c,e++)}()}var Qn=zo;var Sr=class{readNext;haveNext;ended;nextResult;error;constructor(){this.ended=!1,this.readNext=P(),this.haveNext=P()}[Symbol.asyncIterator](){return this}async next(){if(this.nextResult==null&&await this.haveNext.promise,this.nextResult==null)throw new Error("HaveNext promise resolved but nextResult was undefined");let t=this.nextResult;return this.nextResult=void 0,this.readNext.resolve(),this.readNext=P(),t}async throw(t){return this.ended=!0,this.error=t,t!=null&&(this.haveNext.promise.catch(()=>{}),this.haveNext.reject(t)),{done:!0,value:void 0}}async return(){let t={done:!0,value:void 0};return this.ended=!0,this.nextResult=t,this.haveNext.resolve(),t}async push(t,e){await this._push(t,e)}async end(t,e){t!=null?await this.throw(t):await this._push(void 0,e)}async _push(t,e){if(t!=null&&this.ended)throw this.error??new Error("Cannot push value onto an ended pushable");for(;this.nextResult!=null;)await this.readNext.promise;t!=null?this.nextResult={done:!1,value:t}:(this.ended=!0,this.nextResult={done:!0,value:void 0}),this.haveNext.resolve(),this.haveNext=P(),await xe(this.readNext.promise,e?.signal,e)}};function jn(){return new Sr}function Oo(r){return r[Symbol.asyncIterator]!=null}async function $o(r,t){try{await Promise.all(r.map(async e=>{for await(let n of e)await t.push(n)})),await t.end()}catch(e){await t.end(e).catch(()=>{})}}async function*qo(r){let t=jn();$o(r,t).catch(()=>{}),yield*t}function*Ho(r){for(let t of r)yield*t}function Vo(...r){let t=[];for(let e of r)Oo(e)||t.push(e);return t.length===r.length?Ho(t):qo(r)}var Kn=Vo;function Ir(r,...t){if(r==null)throw new Error("Empty pipeline");if(kr(r)){let n=r;r=()=>n.source}else if(Zn(r)||Jn(r)){let n=r;r=()=>n}let e=[r,...t];if(e.length>1&&kr(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++)kr(e[n])&&(e[n]=Go(e[n]));return Wo(...e)}var Wo=(...r)=>{let t;for(;r.length>0;)t=r.shift()(t);return t},Jn=r=>r?.[Symbol.asyncIterator]!=null,Zn=r=>r?.[Symbol.iterator]!=null,kr=r=>r==null?!1:r.sink!=null&&r.source!=null,Go=r=>t=>{let e=r.sink(t);if(e?.then!=null){let n=we({objectMode:!0});e.then(()=>{n.end()},i=>{n.end(i)});let s,o=r.source;if(Jn(o))s=async function*(){yield*o,n.end()};else if(Zn(o))s=function*(){yield*o,n.end()};else throw new Error("Unknown duplex source type - must be Iterable or AsyncIterable");return Kn(n,s())}return r.source};function Xo(r){return r[Symbol.asyncIterator]!=null}function Qo(r,t){return Xo(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 Yn=Qo;var rt=class extends Event{type;detail;constructor(t,e){super(t),this.type=t,this.detail=e}};var Gt="/ipfs/bitswap/1.2.0";var Ar=new Float32Array([-0]),ut=new Uint8Array(Ar.buffer);function ts(r,t,e){Ar[0]=r,t[e]=ut[0],t[e+1]=ut[1],t[e+2]=ut[2],t[e+3]=ut[3]}function es(r,t){return ut[0]=r[t],ut[1]=r[t+1],ut[2]=r[t+2],ut[3]=r[t+3],Ar[0]}var Lr=new Float64Array([-0]),M=new Uint8Array(Lr.buffer);function rs(r,t,e){Lr[0]=r,t[e]=M[0],t[e+1]=M[1],t[e+2]=M[2],t[e+3]=M[3],t[e+4]=M[4],t[e+5]=M[5],t[e+6]=M[6],t[e+7]=M[7]}function ns(r,t){return M[0]=r[t],M[1]=r[t+1],M[2]=r[t+2],M[3]=r[t+3],M[4]=r[t+4],M[5]=r[t+5],M[6]=r[t+6],M[7]=r[t+7],Lr[0]}var jo=BigInt(Number.MAX_SAFE_INTEGER),Ko=BigInt(Number.MIN_SAFE_INTEGER),$=class r{lo;hi;constructor(t,e){this.lo=t|0,this.hi=e|0}toNumber(t=!1){if(!t&&this.hi>>>31>0){let e=~this.lo+1>>>0,n=~this.hi>>>0;return e===0&&(n=n+1>>>0),-(e+n*4294967296)}return this.lo+this.hi*4294967296}toBigInt(t=!1){if(t)return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n);if(this.hi>>>31){let e=~this.lo+1>>>0,n=~this.hi>>>0;return e===0&&(n=n+1>>>0),-(BigInt(e)+(BigInt(n)<<32n))}return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n)}toString(t=!1){return this.toBigInt(t).toString()}zzEncode(){let t=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^t)>>>0,this.lo=(this.lo<<1^t)>>>0,this}zzDecode(){let t=-(this.lo&1);return this.lo=((this.lo>>>1|this.hi<<31)^t)>>>0,this.hi=(this.hi>>>1^t)>>>0,this}length(){let t=this.lo,e=(this.lo>>>28|this.hi<<4)>>>0,n=this.hi>>>24;return n===0?e===0?t<16384?t<128?1:2:t<2097152?3:4:e<16384?e<128?5:6:e<2097152?7:8:n<128?9:10}static fromBigInt(t){if(t===0n)return dt;if(t<jo&&t>Ko)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>ss&&(s=0n,++n>ss&&(n=0n))),new r(Number(s),Number(n))}static fromNumber(t){if(t===0)return dt;let e=t<0;e&&(t=-t);let n=t>>>0,s=(t-n)/4294967296>>>0;return e&&(s=~s>>>0,n=~n>>>0,++n>4294967295&&(n=0,++s>4294967295&&(s=0))),new r(n,s)}static from(t){return typeof t=="number"?r.fromNumber(t):typeof t=="bigint"?r.fromBigInt(t):typeof t=="string"?r.fromBigInt(BigInt(t)):t.low!=null||t.high!=null?new r(t.low>>>0,t.high>>>0):dt}},dt=new $(0,0);dt.toBigInt=function(){return 0n};dt.zzEncode=dt.zzDecode=function(){return this};dt.length=function(){return 1};var ss=4294967296n;function os(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 is(r,t,e){if(e-t<1)return"";let s,o=[],i=0,a;for(;t<e;)a=r[t++],a<128?o[i++]=a:a>191&&a<224?o[i++]=(a&31)<<6|r[t++]&63:a>239&&a<365?(a=((a&7)<<18|(r[t++]&63)<<12|(r[t++]&63)<<6|r[t++]&63)-65536,o[i++]=55296+(a>>10),o[i++]=56320+(a&1023)):o[i++]=(a&15)<<12|(r[t++]&63)<<6|r[t++]&63,i>8191&&((s??(s=[])).push(String.fromCharCode.apply(String,o)),i=0);return s!=null?(i>0&&s.push(String.fromCharCode.apply(String,o.slice(0,i))),s.join("")):String.fromCharCode.apply(String,o.slice(0,i))}function Tr(r,t,e){let n=e,s,o;for(let i=0;i<r.length;++i)s=r.charCodeAt(i),s<128?t[e++]=s:s<2048?(t[e++]=s>>6|192,t[e++]=s&63|128):(s&64512)===55296&&((o=r.charCodeAt(i+1))&64512)===56320?(s=65536+((s&1023)<<10)+(o&1023),++i,t[e++]=s>>18|240,t[e++]=s>>12&63|128,t[e++]=s>>6&63|128,t[e++]=s&63|128):(t[e++]=s>>12|224,t[e++]=s>>6&63|128,t[e++]=s&63|128);return e-n}function J(r,t){return RangeError(`index out of range: ${r.pos} + ${t??1} > ${r.len}`)}function Ne(r,t){return(r[t-4]|r[t-3]<<8|r[t-2]<<16|r[t-1]<<24)>>>0}var Dr=class{buf;pos;len;_slice=Uint8Array.prototype.subarray;constructor(t){this.buf=t,this.pos=0,this.len=t.length}uint32(){let t=4294967295;if(t=(this.buf[this.pos]&127)>>>0,this.buf[this.pos++]<128||(t=(t|(this.buf[this.pos]&127)<<7)>>>0,this.buf[this.pos++]<128)||(t=(t|(this.buf[this.pos]&127)<<14)>>>0,this.buf[this.pos++]<128)||(t=(t|(this.buf[this.pos]&127)<<21)>>>0,this.buf[this.pos++]<128)||(t=(t|(this.buf[this.pos]&15)<<28)>>>0,this.buf[this.pos++]<128))return t;if((this.pos+=5)>this.len)throw this.pos=this.len,J(this,10);return t}int32(){return this.uint32()|0}sint32(){let t=this.uint32();return t>>>1^-(t&1)|0}bool(){return this.uint32()!==0}fixed32(){if(this.pos+4>this.len)throw J(this,4);return Ne(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw J(this,4);return Ne(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw J(this,4);let t=es(this.buf,this.pos);return this.pos+=4,t}double(){if(this.pos+8>this.len)throw J(this,4);let t=ns(this.buf,this.pos);return this.pos+=8,t}bytes(){let t=this.uint32(),e=this.pos,n=this.pos+t;if(n>this.len)throw J(this,t);return this.pos+=t,e===n?new Uint8Array(0):this.buf.subarray(e,n)}string(){let t=this.bytes();return is(t,0,t.length)}skip(t){if(typeof t=="number"){if(this.pos+t>this.len)throw J(this,t);this.pos+=t}else do if(this.pos>=this.len)throw J(this);while((this.buf[this.pos++]&128)!==0);return this}skipType(t){switch(t){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;(t=this.uint32()&7)!==4;)this.skipType(t);break;case 5:this.skip(4);break;default:throw Error(`invalid wire type ${t} at offset ${this.pos}`)}return this}readLongVarint(){let t=new $(0,0),e=0;if(this.len-this.pos>4){for(;e<4;++e)if(t.lo=(t.lo|(this.buf[this.pos]&127)<<e*7)>>>0,this.buf[this.pos++]<128)return t;if(t.lo=(t.lo|(this.buf[this.pos]&127)<<28)>>>0,t.hi=(t.hi|(this.buf[this.pos]&127)>>4)>>>0,this.buf[this.pos++]<128)return t;e=0}else{for(;e<3;++e){if(this.pos>=this.len)throw J(this);if(t.lo=(t.lo|(this.buf[this.pos]&127)<<e*7)>>>0,this.buf[this.pos++]<128)return t}return t.lo=(t.lo|(this.buf[this.pos++]&127)<<e*7)>>>0,t}if(this.len-this.pos>4){for(;e<5;++e)if(t.hi=(t.hi|(this.buf[this.pos]&127)<<e*7+3)>>>0,this.buf[this.pos++]<128)return t}else for(;e<5;++e){if(this.pos>=this.len)throw J(this);if(t.hi=(t.hi|(this.buf[this.pos]&127)<<e*7+3)>>>0,this.buf[this.pos++]<128)return t}throw Error("invalid varint encoding")}readFixed64(){if(this.pos+8>this.len)throw J(this,8);let t=Ne(this.buf,this.pos+=4),e=Ne(this.buf,this.pos+=4);return new $(t,e)}int64(){return this.readLongVarint().toBigInt()}int64Number(){return this.readLongVarint().toNumber()}int64String(){return this.readLongVarint().toString()}uint64(){return this.readLongVarint().toBigInt(!0)}uint64Number(){let t=vr(this.buf,this.pos);return this.pos+=_(t),t}uint64String(){return this.readLongVarint().toString(!0)}sint64(){return this.readLongVarint().zzDecode().toBigInt()}sint64Number(){return this.readLongVarint().zzDecode().toNumber()}sint64String(){return this.readLongVarint().zzDecode().toString()}fixed64(){return this.readFixed64().toBigInt()}fixed64Number(){return this.readFixed64().toNumber()}fixed64String(){return this.readFixed64().toString()}sfixed64(){return this.readFixed64().toBigInt()}sfixed64Number(){return this.readFixed64().toNumber()}sfixed64String(){return this.readFixed64().toString()}};function Pr(r){return new Dr(r instanceof Uint8Array?r:r.subarray())}function pt(r,t,e){let n=Pr(r);return t.decode(n,void 0,e)}var Ur={};O(Ur,{base10:()=>ri});var $l=new Uint8Array(0);function cs(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 ls(r){return new TextEncoder().encode(r)}function us(r){return new TextDecoder().decode(r)}function Jo(r,t){if(r.length>=255)throw new TypeError("Alphabet too long");for(var e=new Uint8Array(256),n=0;n<e.length;n++)e[n]=255;for(var s=0;s<r.length;s++){var o=r.charAt(s),i=o.charCodeAt(0);if(e[i]!==255)throw new TypeError(o+" is ambiguous");e[i]=s}var a=r.length,c=r.charAt(0),l=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function h(d){if(d instanceof Uint8Array||(ArrayBuffer.isView(d)?d=new Uint8Array(d.buffer,d.byteOffset,d.byteLength):Array.isArray(d)&&(d=Uint8Array.from(d))),!(d instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(d.length===0)return"";for(var v=0,g=0,L=0,B=d.length;L!==B&&d[L]===0;)L++,v++;for(var T=(B-L)*u+1>>>0,z=new Uint8Array(T);L!==B;){for(var H=d[L],lt=0,G=T-1;(H!==0||lt<g)&&G!==-1;G--,lt++)H+=256*z[G]>>>0,z[G]=H%a>>>0,H=H/a>>>0;if(H!==0)throw new Error("Non-zero carry");g=lt,L++}for(var nt=T-g;nt!==T&&z[nt]===0;)nt++;for(var ue=c.repeat(v);nt<T;++nt)ue+=r.charAt(z[nt]);return ue}function f(d){if(typeof d!="string")throw new TypeError("Expected String");if(d.length===0)return new Uint8Array;var v=0;if(d[v]!==" "){for(var g=0,L=0;d[v]===c;)g++,v++;for(var B=(d.length-v)*l+1>>>0,T=new Uint8Array(B);d[v];){var z=e[d.charCodeAt(v)];if(z===255)return;for(var H=0,lt=B-1;(z!==0||H<L)&<!==-1;lt--,H++)z+=a*T[lt]>>>0,T[lt]=z%256>>>0,z=z/256>>>0;if(z!==0)throw new Error("Non-zero carry");L=H,v++}if(d[v]!==" "){for(var G=B-L;G!==B&&T[G]===0;)G++;for(var nt=new Uint8Array(g+(B-G)),ue=g;G!==B;)nt[ue++]=T[G++];return nt}}}function m(d){var v=f(d);if(v)return v;throw new Error(`Non-${t} character`)}return{encode:h,decodeUnsafe:f,decode:m}}var Zo=Jo,Yo=Zo,fs=Yo;var Nr=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")}},Fr=class{name;prefix;baseDecode;prefixCodePoint;constructor(t,e,n){this.name=t,this.prefix=e;let s=e.codePointAt(0);if(s===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=s,this.baseDecode=n}decode(t){if(typeof t=="string"){if(t.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(t)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(t.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(t){return ds(this,t)}},Cr=class{decoders;constructor(t){this.decoders=t}or(t){return ds(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 ds(r,t){return new Cr({...r.decoders??{[r.prefix]:r},...t.decoders??{[t.prefix]:t}})}var Mr=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 Nr(t,e,n),this.decoder=new Fr(t,e,s)}encode(t){return this.encoder.encode(t)}decode(t){return this.decoder.decode(t)}};function Tt({name:r,prefix:t,encode:e,decode:n}){return new Mr(r,t,e,n)}function ht({name:r,prefix:t,alphabet:e}){let{encode:n,decode:s}=fs(e,r);return Tt({prefix:t,name:r,encode:n,decode:o=>st(s(o))})}function ti(r,t,e,n){let s={};for(let u=0;u<t.length;++u)s[t[u]]=u;let o=r.length;for(;r[o-1]==="=";)--o;let i=new Uint8Array(o*e/8|0),a=0,c=0,l=0;for(let u=0;u<o;++u){let h=s[r[u]];if(h===void 0)throw new SyntaxError(`Non-${n} character`);c=c<<e|h,a+=e,a>=8&&(a-=8,i[l++]=255&c>>a)}if(a>=e||(255&c<<8-a)!==0)throw new SyntaxError("Unexpected end of data");return i}function ei(r,t,e){let n=t[t.length-1]==="=",s=(1<<e)-1,o="",i=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],i+=8;i>e;)i-=e,o+=t[s&a>>i];if(i!==0&&(o+=t[s&a<<e-i]),n)for(;(o.length*e&7)!==0;)o+="=";return o}function I({name:r,prefix:t,bitsPerChar:e,alphabet:n}){return Tt({prefix:t,name:r,encode(s){return ei(s,n,e)},decode(s){return ti(s,n,e,r)}})}var ri=ht({prefix:"9",name:"base10",alphabet:"0123456789"});var Rr={};O(Rr,{base16:()=>ni,base16upper:()=>si});var ni=I({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),si=I({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var Br={};O(Br,{base2:()=>oi});var oi=I({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var zr={};O(zr,{base256emoji:()=>ui});var ps=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}"),ii=ps.reduce((r,t,e)=>(r[e]=t,r),[]),ai=ps.reduce((r,t,e)=>{let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);return r[n]=e,r},[]);function ci(r){return r.reduce((t,e)=>(t+=ii[e],t),"")}function li(r){let t=[];for(let e of r){let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);let s=ai[n];if(s==null)throw new Error(`Non-base256emoji character: ${e}`);t.push(s)}return new Uint8Array(t)}var ui=Tt({prefix:"\u{1F680}",name:"base256emoji",encode:ci,decode:li});var Or={};O(Or,{base32:()=>ot,base32hex:()=>pi,base32hexpad:()=>gi,base32hexpadupper:()=>wi,base32hexupper:()=>mi,base32pad:()=>fi,base32padupper:()=>di,base32upper:()=>hi,base32z:()=>bi});var ot=I({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),hi=I({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),fi=I({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),di=I({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),pi=I({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),mi=I({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),gi=I({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),wi=I({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),bi=I({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var $r={};O($r,{base36:()=>Xt,base36upper:()=>yi});var Xt=ht({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),yi=ht({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var qr={};O(qr,{base58btc:()=>D,base58flickr:()=>xi});var D=ht({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),xi=ht({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var Vr={};O(Vr,{base64:()=>it,base64pad:()=>Ei,base64url:()=>Hr,base64urlpad:()=>vi});var it=I({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Ei=I({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Hr=I({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),vi=I({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var Wr={};O(Wr,{base8:()=>_i});var _i=I({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var Gr={};O(Gr,{identity:()=>Si});var Si=Tt({prefix:"\0",name:"identity",encode:r=>us(r),decode:r=>ls(r)});var nu=new TextEncoder,su=new TextDecoder;var Qr={};O(Qr,{identity:()=>Xi});var Ai=ws,ms=128,Li=127,Ti=~Li,Di=Math.pow(2,31);function ws(r,t,e){t=t||[],e=e||0;for(var n=e;r>=Di;)t[e++]=r&255|ms,r/=128;for(;r&Ti;)t[e++]=r&255|ms,r>>>=7;return t[e]=r|0,ws.bytes=e-n+1,t}var Pi=Xr,Ni=128,gs=127;function Xr(r,n){var e=0,n=n||0,s=0,o=n,i,a=r.length;do{if(o>=a)throw Xr.bytes=0,new RangeError("Could not decode varint");i=r[o++],e+=s<28?(i&gs)<<s:(i&gs)*Math.pow(2,s),s+=7}while(i>=Ni);return Xr.bytes=o-n,e}var Fi=Math.pow(2,7),Ci=Math.pow(2,14),Mi=Math.pow(2,21),Ui=Math.pow(2,28),Ri=Math.pow(2,35),Bi=Math.pow(2,42),zi=Math.pow(2,49),Oi=Math.pow(2,56),$i=Math.pow(2,63),qi=function(r){return r<Fi?1:r<Ci?2:r<Mi?3:r<Ui?4:r<Ri?5:r<Bi?6:r<zi?7:r<Oi?8:r<$i?9:10},Hi={encode:Ai,decode:Pi,encodingLength:qi},Vi=Hi,Qt=Vi;function jt(r,t=0){return[Qt.decode(r,t),Qt.decode.bytes]}function Dt(r,t,e=0){return Qt.encode(r,t,e),t}function Pt(r){return Qt.encodingLength(r)}function mt(r,t){let e=t.byteLength,n=Pt(r),s=n+Pt(e),o=new Uint8Array(s+e);return Dt(r,o,0),Dt(e,o,n),o.set(t,s),new Nt(r,e,t,o)}function Kt(r){let t=st(r),[e,n]=jt(t),[s,o]=jt(t.subarray(n)),i=t.subarray(n+o);if(i.byteLength!==s)throw new Error("Incorrect length");return new Nt(e,s,i,t)}function bs(r,t){if(r===t)return!0;{let e=t;return r.code===e.code&&r.size===e.size&&e.bytes instanceof Uint8Array&&cs(r.bytes,e.bytes)}}var Nt=class{code;size;digest;bytes;constructor(t,e,n,s){this.code=t,this.size=e,this.digest=n,this.bytes=s}};var ys=0,Wi="identity",xs=st;function Gi(r){return mt(ys,xs(r))}var Xi={code:ys,name:Wi,encode:xs,digest:Gi};var Jr={};O(Jr,{sha256:()=>Ce,sha512:()=>Qi});function Kr({name:r,code:t,encode:e}){return new jr(r,t,e)}var jr=class{name;code;encode;constructor(t,e,n){this.name=t,this.code=e,this.encode=n}digest(t){if(t instanceof Uint8Array){let e=this.encode(t);return e instanceof Uint8Array?mt(this.code,e):e.then(n=>mt(this.code,n))}else throw Error("Unknown type, must be binary type")}};function vs(r){return async t=>new Uint8Array(await crypto.subtle.digest(r,t))}var Ce=Kr({name:"sha2-256",code:18,encode:vs("SHA-256")}),Qi=Kr({name:"sha2-512",code:19,encode:vs("SHA-512")});function _s(r,t){let{bytes:e,version:n}=r;switch(n){case 0:return Ki(e,Zr(r),t??D.encoder);default:return Ji(e,Zr(r),t??ot.encoder)}}var Ss=new WeakMap;function Zr(r){let t=Ss.get(r);if(t==null){let e=new Map;return Ss.set(r,e),e}return t}var q=class r{code;version;multihash;bytes;"/";constructor(t,e,n,s){this.code=e,this.version=t,this.multihash=n,this.bytes=s,this["/"]=s}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:t,multihash:e}=this;if(t!==Jt)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(e.code!==Zi)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return r.createV0(e)}default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}toV1(){switch(this.version){case 0:{let{code:t,digest:e}=this.multihash,n=mt(t,e);return r.createV1(this.code,n)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(t){return r.equals(this,t)}static equals(t,e){let n=e;return n!=null&&t.code===n.code&&t.version===n.version&&bs(t.multihash,n.multihash)}toString(t){return _s(this,t)}toJSON(){return{"/":_s(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(t){if(t==null)return null;let e=t;if(e instanceof r)return e;if(e["/"]!=null&&e["/"]===e.bytes||e.asCID===e){let{version:n,code:s,multihash:o,bytes:i}=e;return new r(n,s,o,i??ks(n,s,o.bytes))}else if(e[Yi]===!0){let{version:n,multihash:s,code:o}=e,i=Kt(s);return r.create(n,o,i)}else return null}static create(t,e,n){if(typeof e!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(t){case 0:{if(e!==Jt)throw new Error(`Version 0 CID must use dag-pb (code: ${Jt}) block encoding`);return new r(t,e,n,n.bytes)}case 1:{let s=ks(t,e,n.bytes);return new r(t,e,n,s)}default:throw new Error("Invalid version")}}static createV0(t){return r.create(0,Jt,t)}static createV1(t,e){return r.create(1,t,e)}static decode(t){let[e,n]=r.decodeFirst(t);if(n.length!==0)throw new Error("Incorrect length");return e}static decodeFirst(t){let e=r.inspectBytes(t),n=e.size-e.multihashSize,s=st(t.subarray(n,n+e.multihashSize));if(s.byteLength!==e.multihashSize)throw new Error("Incorrect length");let o=s.subarray(e.multihashSize-e.digestSize),i=new Nt(e.multihashCode,e.digestSize,o,s);return[e.version===0?r.createV0(i):r.createV1(e.codec,i),t.subarray(e.size)]}static inspectBytes(t){let e=0,n=()=>{let[h,f]=jt(t.subarray(e));return e+=f,h},s=n(),o=Jt;if(s===18?(s=0,e=0):o=n(),s!==0&&s!==1)throw new RangeError(`Invalid CID version ${s}`);let i=e,a=n(),c=n(),l=e+c,u=l-i;return{version:s,codec:o,multihashCode:a,digestSize:c,multihashSize:u,size:l}}static parse(t,e){let[n,s]=ji(t,e),o=r.decode(s);if(o.version===0&&t[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return Zr(o).set(n,t),o}};function ji(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)]}case Xt.prefix:{let e=t??Xt;return[Xt.prefix,e.decode(r)]}default:{if(t==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[r[0],t.decode(r)]}}}function Ki(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 o=e.encode(r).slice(1);return t.set(n,o),o}else return s}function Ji(r,t,e){let{prefix:n}=e,s=t.get(n);if(s==null){let o=e.encode(r);return t.set(n,o),o}else return s}var Jt=112,Zi=18;function ks(r,t,e){let n=Pt(r),s=n+Pt(t),o=new Uint8Array(s+e.byteLength);return Dt(r,o,0),Dt(t,o,n),o.set(e,s),o}var Yi=Symbol.for("@ipld/js-cid/CID");var Zt={...Gr,...Br,...Wr,...Ur,...Rr,...Or,...$r,...qr,...Vr,...zr},Iu={...Jr,...Qr};function As(r,t,e,n){return{name:r,prefix:t,encoder:{name:r,prefix:t,encode:e},decoder:{decode:n}}}var Is=As("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),Yr=As("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=F(r.length);for(let e=0;e<r.length;e++)t[e]=r.charCodeAt(e);return t}),ta={utf8:Is,"utf-8":Is,hex:Zt.base16,latin1:Yr,ascii:Yr,binary:Yr,...Zt},Me=ta;function U(r,t="utf8"){let e=Me[t];if(e==null)throw new Error(`Unsupported encoding "${t}"`);return e.decoder.decode(`${e.prefix}${r}`)}function tn(r){let t=r??8192,e=t>>>1,n,s=t;return function(i){if(i<1||i>e)return F(i);s+i>t&&(n=F(t),s=0);let a=n.subarray(s,s+=i);return(s&7)!==0&&(s=(s|7)+1),a}}var wt=class{fn;len;next;val;constructor(t,e,n){this.fn=t,this.len=e,this.next=void 0,this.val=n}};function en(){}var nn=class{head;tail;len;next;constructor(t){this.head=t.head,this.tail=t.tail,this.len=t.len,this.next=t.states}},ea=tn();function ra(r){return globalThis.Buffer!=null?F(r):ea(r)}var te=class{len;head;tail;states;constructor(){this.len=0,this.head=new wt(en,0,0),this.tail=this.head,this.states=null}_push(t,e,n){return this.tail=this.tail.next=new wt(t,e,n),this.len+=e,this}uint32(t){return this.len+=(this.tail=this.tail.next=new sn((t=t>>>0)<128?1:t<16384?2:t<2097152?3:t<268435456?4:5,t)).len,this}int32(t){return t<0?this._push(Ue,10,$.fromNumber(t)):this.uint32(t)}sint32(t){return this.uint32((t<<1^t>>31)>>>0)}uint64(t){let e=$.fromBigInt(t);return this._push(Ue,e.length(),e)}uint64Number(t){return this._push(Er,_(t),t)}uint64String(t){return this.uint64(BigInt(t))}int64(t){return this.uint64(t)}int64Number(t){return this.uint64Number(t)}int64String(t){return this.uint64String(t)}sint64(t){let e=$.fromBigInt(t).zzEncode();return this._push(Ue,e.length(),e)}sint64Number(t){let e=$.fromNumber(t).zzEncode();return this._push(Ue,e.length(),e)}sint64String(t){return this.sint64(BigInt(t))}bool(t){return this._push(rn,1,t?1:0)}fixed32(t){return this._push(Yt,4,t>>>0)}sfixed32(t){return this.fixed32(t)}fixed64(t){let e=$.fromBigInt(t);return this._push(Yt,4,e.lo)._push(Yt,4,e.hi)}fixed64Number(t){let e=$.fromNumber(t);return this._push(Yt,4,e.lo)._push(Yt,4,e.hi)}fixed64String(t){return this.fixed64(BigInt(t))}sfixed64(t){return this.fixed64(t)}sfixed64Number(t){return this.fixed64Number(t)}sfixed64String(t){return this.fixed64String(t)}float(t){return this._push(ts,4,t)}double(t){return this._push(rs,8,t)}bytes(t){let e=t.length>>>0;return e===0?this._push(rn,1,0):this.uint32(e)._push(sa,e,t)}string(t){let e=os(t);return e!==0?this.uint32(e)._push(Tr,e,t):this._push(rn,1,0)}fork(){return this.states=new nn(this),this.head=this.tail=new wt(en,0,0),this.len=0,this}reset(){return this.states!=null?(this.head=this.states.head,this.tail=this.states.tail,this.len=this.states.len,this.states=this.states.next):(this.head=this.tail=new wt(en,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=ra(this.len),n=0;for(;t!=null;)t.fn(t.val,e,n),n+=t.len,t=t.next;return e}};function rn(r,t,e){t[e]=r&255}function na(r,t,e){for(;r>127;)t[e++]=r&127|128,r>>>=7;t[e]=r}var sn=class extends wt{next;constructor(t,e){super(na,t,e),this.next=void 0}};function Ue(r,t,e){for(;r.hi!==0;)t[e++]=r.lo&127|128,r.lo=(r.lo>>>7|r.hi<<25)>>>0,r.hi>>>=7;for(;r.lo>127;)t[e++]=r.lo&127|128,r.lo=r.lo>>>7;t[e++]=r.lo}function Yt(r,t,e){t[e]=r&255,t[e+1]=r>>>8&255,t[e+2]=r>>>16&255,t[e+3]=r>>>24}function sa(r,t,e){t.set(r,e)}globalThis.Buffer!=null&&(te.prototype.bytes=function(r){let t=r.length>>>0;return this.uint32(t),t>0&&this._push(oa,t,r),this},te.prototype.string=function(r){let t=globalThis.Buffer.byteLength(r);return this.uint32(t),t>0&&this._push(ia,t,r),this});function oa(r,t,e){t.set(r,e)}function ia(r,t,e){r.length<40?Tr(r,t,e):t.utf8Write!=null?t.utf8Write(r,e):t.set(U(r),e)}function on(){return new te}function bt(r,t){let e=on();return t.encode(r,e,{lengthDelimited:!1}),e.finish()}var Ft;(function(r){r[r.VARINT=0]="VARINT",r[r.BIT64=1]="BIT64",r[r.LENGTH_DELIMITED=2]="LENGTH_DELIMITED",r[r.START_GROUP=3]="START_GROUP",r[r.END_GROUP=4]="END_GROUP",r[r.BIT32=5]="BIT32"})(Ft||(Ft={}));function Re(r,t,e,n){return{name:r,type:t,encode:e,decode:n}}function Be(r){function t(s){if(r[s.toString()]==null)throw new Error("Invalid enum value");return r[s]}let e=function(o,i){let a=t(o);i.int32(a)},n=function(o){let i=o.int32();return t(i)};return Re("enum",Ft.VARINT,e,n)}function yt(r,t){return Re("message",Ft.LENGTH_DELIMITED,r,t)}var Ct=class extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"};var A;(function(r){r.WantBlock="WantBlock",r.WantHave="WantHave"})(A||(A={}));var an;(function(r){r[r.WantBlock=0]="WantBlock",r[r.WantHave=1]="WantHave"})(an||(an={}));(function(r){r.codec=()=>Be(an)})(A||(A={}));var Mt;(function(r){let t;r.codec=()=>(t==null&&(t=yt((e,n,s={})=>{s.lengthDelimited!==!1&&n.fork(),e.cid!=null&&e.cid.byteLength>0&&(n.uint32(10),n.bytes(e.cid)),e.priority!=null&&e.priority!==0&&(n.uint32(16),n.int32(e.priority)),e.cancel!=null&&(n.uint32(24),n.bool(e.cancel)),e.wantType!=null&&(n.uint32(32),A.codec().encode(e.wantType,n)),e.sendDontHave!=null&&(n.uint32(40),n.bool(e.sendDontHave)),s.lengthDelimited!==!1&&n.ldelim()},(e,n,s={})=>{let o={cid:N(0),priority:0},i=n==null?e.len:e.pos+n;for(;e.pos<i;){let a=e.uint32();switch(a>>>3){case 1:{o.cid=e.bytes();break}case 2:{o.priority=e.int32();break}case 3:{o.cancel=e.bool();break}case 4:{o.wantType=A.codec().decode(e);break}case 5:{o.sendDontHave=e.bool();break}default:{e.skipType(a&7);break}}}return o})),t),r.encode=e=>bt(e,r.codec()),r.decode=(e,n)=>pt(e,r.codec(),n)})(Mt||(Mt={}));var ze;(function(r){let t;r.codec=()=>(t==null&&(t=yt((e,n,s={})=>{if(s.lengthDelimited!==!1&&n.fork(),e.entries!=null)for(let o of e.entries)n.uint32(10),Mt.codec().encode(o,n);e.full!=null&&(n.uint32(16),n.bool(e.full)),s.lengthDelimited!==!1&&n.ldelim()},(e,n,s={})=>{let o={entries:[]},i=n==null?e.len:e.pos+n;for(;e.pos<i;){let a=e.uint32();switch(a>>>3){case 1:{if(s.limits?.entries!=null&&o.entries.length===s.limits.entries)throw new Ct('Decode error - map field "entries" had too many elements');o.entries.push(Mt.codec().decode(e,e.uint32(),{limits:s.limits?.entries$}));break}case 2:{o.full=e.bool();break}default:{e.skipType(a&7);break}}}return o})),t),r.encode=e=>bt(e,r.codec()),r.decode=(e,n)=>pt(e,r.codec(),n)})(ze||(ze={}));var Ut;(function(r){let t;r.codec=()=>(t==null&&(t=yt((e,n,s={})=>{s.lengthDelimited!==!1&&n.fork(),e.prefix!=null&&e.prefix.byteLength>0&&(n.uint32(10),n.bytes(e.prefix)),e.data!=null&&e.data.byteLength>0&&(n.uint32(18),n.bytes(e.data)),s.lengthDelimited!==!1&&n.ldelim()},(e,n,s={})=>{let o={prefix:N(0),data:N(0)},i=n==null?e.len:e.pos+n;for(;e.pos<i;){let a=e.uint32();switch(a>>>3){case 1:{o.prefix=e.bytes();break}case 2:{o.data=e.bytes();break}default:{e.skipType(a&7);break}}}return o})),t),r.encode=e=>bt(e,r.codec()),r.decode=(e,n)=>pt(e,r.codec(),n)})(Ut||(Ut={}));var W;(function(r){r.HaveBlock="HaveBlock",r.DoNotHaveBlock="DoNotHaveBlock"})(W||(W={}));var Oe;(function(r){r[r.HaveBlock=0]="HaveBlock",r[r.DoNotHaveBlock=1]="DoNotHaveBlock"})(Oe||(Oe={}));(function(r){r.codec=()=>Be(Oe)})(W||(W={}));var Rt;(function(r){let t;r.codec=()=>(t==null&&(t=yt((e,n,s={})=>{s.lengthDelimited!==!1&&n.fork(),e.cid!=null&&e.cid.byteLength>0&&(n.uint32(10),n.bytes(e.cid)),e.type!=null&&Oe[e.type]!==0&&(n.uint32(16),W.codec().encode(e.type,n)),s.lengthDelimited!==!1&&n.ldelim()},(e,n,s={})=>{let o={cid:N(0),type:W.HaveBlock},i=n==null?e.len:e.pos+n;for(;e.pos<i;){let a=e.uint32();switch(a>>>3){case 1:{o.cid=e.bytes();break}case 2:{o.type=W.codec().decode(e);break}default:{e.skipType(a&7);break}}}return o})),t),r.encode=e=>bt(e,r.codec()),r.decode=(e,n)=>pt(e,r.codec(),n)})(Rt||(Rt={}));var xt;(function(r){let t;r.codec=()=>(t==null&&(t=yt((e,n,s={})=>{if(s.lengthDelimited!==!1&&n.fork(),e.wantlist!=null&&(n.uint32(10),ze.codec().encode(e.wantlist,n)),e.blocks!=null)for(let o of e.blocks)n.uint32(26),Ut.codec().encode(o,n);if(e.blockPresences!=null)for(let o of e.blockPresences)n.uint32(34),Rt.codec().encode(o,n);e.pendingBytes!=null&&e.pendingBytes!==0&&(n.uint32(40),n.int32(e.pendingBytes)),s.lengthDelimited!==!1&&n.ldelim()},(e,n,s={})=>{let o={blocks:[],blockPresences:[],pendingBytes:0},i=n==null?e.len:e.pos+n;for(;e.pos<i;){let a=e.uint32();switch(a>>>3){case 1:{o.wantlist=ze.codec().decode(e,e.uint32(),{limits:s.limits?.wantlist});break}case 3:{if(s.limits?.blocks!=null&&o.blocks.length===s.limits.blocks)throw new Ct('Decode error - map field "blocks" had too many elements');o.blocks.push(Ut.codec().decode(e,e.uint32(),{limits:s.limits?.blocks$}));break}case 4:{if(s.limits?.blockPresences!=null&&o.blockPresences.length===s.limits.blockPresences)throw new Ct('Decode error - map field "blockPresences" had too many elements');o.blockPresences.push(Rt.codec().decode(e,e.uint32(),{limits:s.limits?.blockPresences$}));break}case 5:{o.pendingBytes=e.int32();break}default:{e.skipType(a&7);break}}}return o})),t),r.encode=e=>bt(e,r.codec()),r.decode=(e,n)=>pt(e,r.codec(),n)})(xt||(xt={}));function Ls(r,t){for(let[e,n]of t.wantlist.entries()){let s=r.wantlist.get(e);s!=null&&(s.priority>n.priority&&(n.priority=s.priority),n.cancel=n.cancel??s.cancel,n.wantType=n.wantType??s.wantType,n.sendDontHave=n.sendDontHave??s.sendDontHave),r.wantlist.set(e,n)}for(let[e,n]of t.blockPresences.entries())r.blockPresences.set(e,n);for(let[e,n]of t.blocks.entries())r.blocks.set(e,n);return t.full&&!r.full&&(r.full=!0),r}var $e=class extends Error{static name="BlockTooLargeError";constructor(t="Block too large"){super(t),this.name="BlockTooLargeError"}};var aa=4193648,ca=aa+16;function*Ts(r,t){let e=[...r.wantlist.values()],n=[...r.blockPresences.values()],s=[...r.blocks.values()],o=0,i=0,a=0,c=!1;for(;;){let l={wantlist:{full:r.full??!1,entries:[]},blockPresences:[],blocks:[],pendingBytes:0},u=xt.encode(l).byteLength,{added:h,hasMore:f,newSize:m}=cn(s,l.blocks,a,t,u,la);a+=h,u=m;let d=f;({added:h,hasMore:f,newSize:m}=cn(n,l.blockPresences,i,t,u,ua)),i+=h,u=m;let v=f;if({added:h,hasMore:f,newSize:m}=cn(e,l.wantlist.entries,o,t,u,ha),o+=h,u=m,c=!d&&!v&&!f,c||(l.wantlist.full=!1),yield xt.encode(l),c)break}}function cn(r,t,e,n,s,o){let i=0,a=!1;for(let c=e;c<r.length;c++){let l=r[c],u=o(l);if(u>ca)throw new $e("Cannot send block as after encoding it is over the max message size");let h=s+u;if(h>n){a=!0;break}t.push(l),i++,s=h}return{hasMore:a,added:i,newSize:s}}function la(r){return ln(3,Ut.encode(r))}function ua(r){return ln(4,Rt.encode(r))}function ha(r){return ln(1,Mt.encode(r))}function ln(r,t){let e=_(r),n=_(t.byteLength);return e+n+t.byteLength}var qe=class extends tt{log;libp2p;routing;protocols;running;maxInboundStreams;maxOutboundStreams;messageReceiveTimeout;registrarIds;metrics;sendQueue;runOnLimitedConnections;maxOutgoingMessageSize;maxIncomingMessageSize;constructor(t,e={}){super(),this.log=t.logger.forComponent("helia:bitswap:network"),this.libp2p=t.libp2p,this.routing=t.routing,this.protocols=e.protocols??[Gt],this.registrarIds=[],this.running=!1,this._onStream=this._onStream.bind(this),this.maxInboundStreams=e.maxInboundStreams??1024,this.maxOutboundStreams=e.maxOutboundStreams??1024,this.messageReceiveTimeout=e.messageReceiveTimeout??5e3,this.runOnLimitedConnections=e.runOnLimitedConnections??!1,this.maxIncomingMessageSize=e.maxIncomingMessageSize??4194304,this.maxOutgoingMessageSize=e.maxOutgoingMessageSize??e.maxIncomingMessageSize??4194304,this.metrics={blocksSent:t.metrics?.registerCounter("helia_bitswap_sent_blocks_total"),dataSent:t.metrics?.registerCounter("helia_bitswap_sent_data_bytes_total")},this.sendQueue=new _e({concurrency:e.messageSendConcurrency??50,metrics:t.metrics,metricName:"helia_bitswap_message_send_queue"}),this.sendQueue.addEventListener("error",n=>{this.log.error("error sending wantlist to peer",n.detail)})}async start(){if(this.running)return;this.running=!0,await this.libp2p.handle(this.protocols,this._onStream,{maxInboundStreams:this.maxInboundStreams,maxOutboundStreams:this.maxOutboundStreams,runOnLimitedConnection:this.runOnLimitedConnections});let t={onConnect:e=>{this.safeDispatchEvent("peer:connected",{detail:e})},onDisconnect:e=>{this.safeDispatchEvent("peer:disconnected",{detail:e})}};this.registrarIds=[];for(let e of this.protocols)this.registrarIds.push(await this.libp2p.register(e,t));this.libp2p.getConnections().forEach(e=>{this.safeDispatchEvent("peer:connected",{detail:e.remotePeer})})}async stop(){if(this.running=!1,await this.libp2p.unhandle(this.protocols),this.registrarIds!=null){for(let t of this.registrarIds)this.libp2p.unregister(t);this.registrarIds=[]}}_onStream(t){if(!this.running)return;let{stream:e,connection:n}=t;Promise.resolve().then(async()=>{this.log("incoming new bitswap %s stream from %p",e.protocol,n.remotePeer);let s=()=>{e.status==="open"?e.abort(new pe(`Incoming Bitswap stream timed out after ${this.messageReceiveTimeout}ms`)):this.log("stream aborted with status %s",e.status)},o=AbortSignal.timeout(this.messageReceiveTimeout);o.addEventListener("abort",s),await e.closeWrite(),await Ir(e,i=>Wt(i,{maxDataLength:this.maxIncomingMessageSize}),async i=>{for await(let a of i)try{let c=xt.decode(a);this.log("incoming new bitswap %s message from %p on stream",e.protocol,n.remotePeer,e.id),this.safeDispatchEvent("bitswap:message",{detail:{peer:n.remotePeer,message:c}}),o.removeEventListener("abort",s),o=AbortSignal.timeout(this.messageReceiveTimeout),o.addEventListener("abort",s)}catch(c){this.log.error("error reading incoming bitswap message from %p on stream",n.remotePeer,e.id,c),e.abort(c);break}})}).catch(s=>{this.log.error("error handling incoming stream from %p",n.remotePeer,s),e.abort(s)})}async*findProviders(t,e){e?.onProgress?.(new rt("bitswap:network:find-providers",t));for await(let n of this.routing.findProviders(t,e))await this.libp2p.isDialable(n.multiaddrs,{runOnLimitedConnection:this.runOnLimitedConnections})&&(yield n)}async findAndConnect(t,e){await gr(Qn(Yn(this.findProviders(t,e),e?.maxProviders??3),async n=>this.connectTo(n.id,e))).catch(n=>{this.log.error(n)})}async sendMessage(t,e,n){if(!this.running)throw new Error("network isn't running");let s=this.sendQueue.queue.find(o=>t.equals(o.options.peerId)&&o.status==="queued");if(s!=null){s.options.message=Ls(s.options.message,e),await s.join({signal:n?.signal});return}await this.sendQueue.add(async o=>{let i=o?.message;if(i==null)throw new fe("No message to send");this.log("sendMessage to %p",t),o?.onProgress?.(new rt("bitswap:network:send-wantlist",t));let a=await this.libp2p.dialProtocol(t,Gt,o);await a.closeRead();try{await Ir(Ts(i,this.maxOutgoingMessageSize),c=>Pe(c),a),await a.close(o)}catch(c){o?.onProgress?.(new rt("bitswap:network:send-wantlist:error",{peer:t,error:c})),this.log.error("error sending message to %p",t,c),a.abort(c)}this._updateSentStats(i.blocks)},{peerId:t,signal:n?.signal,message:e})}async connectTo(t,e){if(!this.running)throw new me("Network isn't running");e?.onProgress?.(new rt("bitswap:network:dial",t));let[n]=await Promise.all([this.libp2p.dial(t,e),Q(this.libp2p,"peer:identify",e?.signal,{filter:s=>{if(!s.detail.peerId.equals(t))return!1;if(s.detail.protocols.includes(Gt))return!0;throw new de(`${t} did not support ${Gt}`)}})]);return n}_updateSentStats(t){let e=0;for(let n of t.values())e+=n.data.byteLength;this.metrics.dataSent?.increment(e),this.metrics.blocksSent?.increment(t.size)}};function S(r,t="utf8"){let e=Me[t];if(e==null)throw new Error(`Unsupported encoding "${t}"`);return e.encoder.encode(r).substring(1)}function He(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 ee=class{map;constructor(t){if(this.map=new Map,t!=null)for(let[e,n]of t.entries())this.map.set(e.toString(),{key:e,value:n})}[Symbol.iterator](){return this.entries()}clear(){this.map.clear()}delete(t){return this.map.delete(t.toString())}entries(){return He(this.map.entries(),t=>[t[1].key,t[1].value])}forEach(t){this.map.forEach((e,n)=>{t(e.value,e.key,this)})}get(t){return this.map.get(t.toString())?.value}has(t){return this.map.has(t.toString())}set(t,e){this.map.set(t.toString(),{key:t,value:e})}keys(){return He(this.map.values(),t=>t.key)}values(){return He(this.map.values(),t=>t.value)}get size(){return this.map.size}};var un={32:16777619n,64:1099511628211n,128:309485009821345068724781371n,256:374144419156711147060143317175368453031918731002211n,512:35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759n,1024:5016456510113118655434598811035278955030765345404790744303017523831112055108147451509157692220295382716162651878526895249385292291816524375083746691371804094271873160484737966720260389217684476157468082573n},Ds={32:2166136261n,64:14695981039346656037n,128:144066263297769815596495629667062367629n,256:100029257958052580907070968620625704837092796014241193945225284501741471925557n,512:9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785n,1024:14197795064947621068722070641403218320880622795441933960878474914617582723252296732303717722150864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915n},Ps=new globalThis.TextEncoder;function xa(r,t){let e=un[t],n=Ds[t];for(let s=0;s<r.length;s++)n^=BigInt(r[s]),n=BigInt.asUintN(t,n*e);return n}function Ea(r,t,e){if(e.length===0)throw new Error("The `utf8Buffer` option must have a length greater than zero");let n=un[t],s=Ds[t],o=r;for(;o.length>0;){let i=Ps.encodeInto(o,e);o=o.slice(i.read);for(let a=0;a<i.written;a++)s^=BigInt(e[a]),s=BigInt.asUintN(t,s*n)}return s}function hn(r,{size:t=32,utf8Buffer:e}={}){if(!un[t])throw new Error("The `size` option must be one of 32, 64, 128, 256, 512, or 1024");if(typeof r=="string"){if(e)return Ea(r,t,e);r=Ps.encode(r)}return xa(r,t)}var re={hash:r=>Number(hn(r,{size:32})),hashV:(r,t)=>va(re.hash(r,t))};function va(r){let t=r.toString(16);return t.length%2===1&&(t=`0${t}`),U(t,"base16")}var fn=64,Z=class{fp;h;seed;constructor(t,e,n,s=2){if(s>fn)throw new TypeError("Invalid Fingerprint Size");let o=e.hashV(t,n),i=N(s);for(let a=0;a<i.length;a++)i[a]=o[a];i.length===0&&(i[0]=7),this.fp=i,this.h=e,this.seed=n}hash(){return this.h.hash(this.fp,this.seed)}equals(t){return t?.fp instanceof Uint8Array?K(this.fp,t.fp):!1}};function Et(r,t){return Math.floor(Math.random()*(t-r))+r}var vt=class{contents;constructor(t){this.contents=new Array(t).fill(null)}has(t){if(!(t instanceof Z))throw new TypeError("Invalid Fingerprint");return this.contents.some(e=>t.equals(e))}add(t){if(!(t instanceof Z))throw new TypeError("Invalid Fingerprint");for(let e=0;e<this.contents.length;e++)if(this.contents[e]==null)return this.contents[e]=t,!0;return!0}swap(t){if(!(t instanceof Z))throw new TypeError("Invalid Fingerprint");let e=Et(0,this.contents.length-1),n=this.contents[e];return this.contents[e]=t,n}remove(t){if(!(t instanceof Z))throw new TypeError("Invalid Fingerprint");let e=this.contents.findIndex(n=>t.equals(n));return e>-1?(this.contents[e]=null,!0):!1}};var _a=500,ne=class{bucketSize;filterSize;fingerprintSize;buckets;count;hash;seed;constructor(t){this.filterSize=t.filterSize,this.bucketSize=t.bucketSize??4,this.fingerprintSize=t.fingerprintSize??2,this.count=0,this.buckets=[],this.hash=t.hash??re,this.seed=t.seed??Et(0,Math.pow(2,10))}add(t){typeof t=="string"&&(t=U(t));let e=new Z(t,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(t,this.seed)%this.filterSize,s=(n^e.hash())%this.filterSize;if(this.buckets[n]==null&&(this.buckets[n]=new vt(this.bucketSize)),this.buckets[s]==null&&(this.buckets[s]=new vt(this.bucketSize)),this.buckets[n].add(e)||this.buckets[s].add(e))return this.count++,!0;let o=[n,s],i=o[Et(0,o.length-1)];this.buckets[i]==null&&(this.buckets[i]=new vt(this.bucketSize));for(let a=0;a<_a;a++){let c=this.buckets[i].swap(e);if(c!=null&&(i=(i^c.hash())%this.filterSize,this.buckets[i]==null&&(this.buckets[i]=new vt(this.bucketSize)),this.buckets[i].add(c)))return this.count++,!0}return!1}has(t){typeof t=="string"&&(t=U(t));let e=new Z(t,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(t,this.seed)%this.filterSize,s=this.buckets[n]?.has(e)??!1;if(s)return s;let o=(n^e.hash())%this.filterSize;return this.buckets[o]?.has(e)??!1}remove(t){typeof t=="string"&&(t=U(t));let e=new Z(t,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(t,this.seed)%this.filterSize,s=this.buckets[n]?.remove(e)??!1;if(s)return this.count--,s;let o=(n^e.hash())%this.filterSize,i=this.buckets[o]?.remove(e)??!1;return i&&this.count--,i}get reliable(){return Math.floor(100*(this.count/this.filterSize))<=90}},Sa={1:.5,2:.84,4:.95,8:.98};function ka(r=.001){return r>.002?2:r>1e-5?4:8}function Ns(r,t=.001){let e=ka(t),n=Sa[e],s=Math.round(r/n),o=Math.min(Math.ceil(Math.log2(1/t)+Math.log2(2*e)),fn);return{filterSize:s,bucketSize:e,fingerprintSize:o}}var Ve=class{filterSize;bucketSize;fingerprintSize;scale;filterSeries;hash;seed;constructor(t){this.bucketSize=t.bucketSize??4,this.filterSize=t.filterSize??(1<<18)/this.bucketSize,this.fingerprintSize=t.fingerprintSize??2,this.scale=t.scale??2,this.hash=t.hash??re,this.seed=t.seed??Et(0,Math.pow(2,10)),this.filterSeries=[new ne({filterSize:this.filterSize,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed})]}add(t){if(typeof t=="string"&&(t=U(t)),this.has(t))return!0;let e=this.filterSeries.find(n=>n.reliable);if(e==null){let n=this.filterSize*Math.pow(this.scale,this.filterSeries.length);e=new ne({filterSize:n,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed}),this.filterSeries.push(e)}return e.add(t)}has(t){typeof t=="string"&&(t=U(t));for(let e=0;e<this.filterSeries.length;e++)if(this.filterSeries[e].has(t))return!0;return!1}remove(t){typeof t=="string"&&(t=U(t));for(let e=0;e<this.filterSeries.length;e++)if(this.filterSeries[e].remove(t))return!0;return!1}get count(){return this.filterSeries.reduce((t,e)=>t+e.count,0)}};function dn(r,t=.001,e){return new Ve({...Ns(r,t),...e??{}})}var pn=class extends ee{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 se(r){let{name:t,metrics:e}=r,n;return e!=null?n=new pn({name:t,metrics:e}):n=new ee,n}var at=class{full;pendingBytes;wantlist;blocks;blockPresences;constructor(t=!1,e=0){this.full=t,this.wantlist=new Map,this.blocks=new Map,this.blockPresences=new Map,this.pendingBytes=0}addWantlistEntry(t,e){let n=it.encode(t.multihash.bytes);this.wantlist.set(n,e)}addBlockPresence(t,e){let n=it.encode(t.multihash.bytes);this.blockPresences.set(n,e)}addBlock(t,e){let n=it.encode(t.multihash.bytes);this.blocks.set(n,e)}};function Ia(r){let t=new Uint8Array(r.reduce((n,s)=>n+_(s),0)),e=0;for(let n of r)t=et(n,t,e),e+=_(n);return t}var Fs=Ia;function mn(r){return Fs([r.version,r.code,r.multihash.code,r.multihash.digest.byteLength])}var We=class{peerId;blockstore;network;wants;exchangeCount;bytesSent;bytesReceived;lastExchange;maxSizeReplaceHasWithBlock;log;constructor(t,e){this.peerId=t.peerId,this.blockstore=t.blockstore,this.network=t.network,this.wants=new Map,this.log=t.logger.forComponent(`helia:bitswap:ledger:${t.peerId}`),this.exchangeCount=0,this.bytesSent=0,this.bytesReceived=0,this.maxSizeReplaceHasWithBlock=e.maxSizeReplaceHasWithBlock??1024}sentBytes(t){this.exchangeCount++,this.lastExchange=new Date().getTime(),this.bytesSent+=t}receivedBytes(t){this.exchangeCount++,this.lastExchange=new Date().getTime(),this.bytesReceived+=t}debtRatio(){return this.bytesSent/(this.bytesReceived+1)}async sendBlocksToPeer(t){let e=new at,n=new Set;for(let[s,o]of this.wants.entries())try{let i=await this.blockstore.get(o.cid,t);o.wantType===A.WantHave?i.byteLength<this.maxSizeReplaceHasWithBlock?(this.log("sending have and block for %c",o.cid),n.add(s),e.addBlock(o.cid,{data:i,prefix:mn(o.cid)})):(this.log("sending have for %c",o.cid),e.addBlockPresence(o.cid,{cid:o.cid.bytes,type:W.HaveBlock})):(this.log("sending block for %c",o.cid),n.add(s),e.addBlock(o.cid,{data:i,prefix:mn(o.cid)}))}catch(i){if(i.name!=="NotFoundError")throw i;if(this.log("do not have block for %c",o.cid),!o.sendDontHave||o.sentDoNotHave===!0)continue;o.sentDoNotHave=!0,e.addBlockPresence(o.cid,{cid:o.cid.bytes,type:W.DoNotHaveBlock})}if(e.blocks.size>0||e.blockPresences.size>0){this.log("sending message"),await this.network.sendMessage(this.peerId,e,t),this.log("sent message"),this.sentBytes([...e.blocks.values()].reduce((s,o)=>s+o.data.byteLength,0));for(let s of n)this.wants.delete(s)}}};var Ge=class{blockstore;network;ledgerMap;maxSizeReplaceHasWithBlock;log;logger;constructor(t,e={}){this.blockstore=t.blockstore,this.network=t.network,this.maxSizeReplaceHasWithBlock=e.maxSizeReplaceHasWithBlock,this.log=t.logger.forComponent("helia:bitswap:peer-want-lists"),this.logger=t.logger,this.ledgerMap=se({name:"helia_bitswap_ledger_map",metrics:t.metrics}),this.network.addEventListener("bitswap:message",n=>{this.receiveMessage(n.detail.peer,n.detail.message).catch(s=>{this.log.error("error receiving bitswap message from %p",n.detail.peer,s)})}),this.network.addEventListener("peer:disconnected",n=>{this.peerDisconnected(n.detail)})}ledgerForPeer(t){let e=this.ledgerMap.get(t);if(e!=null)return{peer:e.peerId,value:e.debtRatio(),sent:e.bytesSent,received:e.bytesReceived,exchanged:e.exchangeCount}}wantListForPeer(t){let e=this.ledgerMap.get(t);if(e!=null)return[...e.wants.values()]}peers(){return Array.from(this.ledgerMap.values()).map(t=>t.peerId)}async receiveMessage(t,e){let n=this.ledgerMap.get(t);if(n==null&&(n=new We({peerId:t,blockstore:this.blockstore,network:this.network,logger:this.logger},{maxSizeReplaceHasWithBlock:this.maxSizeReplaceHasWithBlock}),this.ledgerMap.set(t,n)),n.receivedBytes(e.blocks?.reduce((s,o)=>s+o.data.byteLength,0)??0),e.wantlist!=null){e.wantlist.full===!0&&n.wants.clear();for(let s of e.wantlist.entries){let o=q.decode(s.cid),i=S(o.multihash.bytes,"base64");s.cancel===!0?(this.log("peer %p cancelled want of block for %c",t,o),n.wants.delete(i)):(s.wantType===A.WantHave?this.log("peer %p wanted block presence for %c",t,o):this.log("peer %p wanted block for %c",t,o),n.wants.set(i,{cid:o,priority:s.priority,wantType:s.wantType??A.WantBlock,sendDontHave:s.sendDontHave??!1}))}}this.log("send blocks to peer"),await n.sendBlocksToPeer()}async receivedBlock(t,e){let n=S(t.multihash.bytes,"base64"),s=[];for(let o of this.ledgerMap.values())o.wants.has(n)&&s.push(o);await Promise.all(s.map(async o=>o.sendBlocksToPeer(e)))}peerDisconnected(t){this.ledgerMap.delete(t)}};var Ta=qn(Ms(),1);var Bt;(function(r){r[r.A=1]="A",r[r.CNAME=5]="CNAME",r[r.TXT=16]="TXT",r[r.AAAA=28]="AAAA"})(Bt||(Bt={}));var Xe=class extends Error{static name="InsufficientProvidersError";constructor(t="Insufficient providers found"){super(t),this.name="InsufficientProvidersError"}};var _t=class extends tt{initialPeerSearchComplete;requests;name;log;logger;minProviders;maxProviders;providers;evictionFilter;constructor(t,e){super(),this.name=e.name,this.logger=t.logger,this.log=t.logger.forComponent(this.name),this.requests=new Map,this.minProviders=e.minProviders??1,this.maxProviders=e.maxProviders??5,this.providers=[],this.evictionFilter=dn(this.maxProviders)}async retrieve(t,e={}){let n=it.encode(t.multihash.bytes),s=this.requests.get(n);if(s!=null)return this.log("join existing request for %c",t),s;let o=P();if(this.requests.set(n,o.promise),this.providers.length===0){let u=!1;this.initialPeerSearchComplete==null&&(u=!0,this.log=this.logger.forComponent(`${this.name}:${t}`),this.initialPeerSearchComplete=this.findProviders(t,this.minProviders,e)),await this.initialPeerSearchComplete,u&&this.log("found initial session peers for %c",t)}let i=!1,a=new It({concurrency:this.maxProviders});a.addEventListener("error",()=>{}),a.addEventListener("failure",u=>{this.log.error("error querying provider %o, evicting from session",u.detail.job.options.provider,u.detail.error),this.evict(u.detail.job.options.provider)}),a.addEventListener("success",u=>{i=!0,o.resolve(u.detail.result)}),a.addEventListener("idle",()=>{if(i||e.signal?.aborted===!0){this.log.trace("session idle, found block");return}Promise.resolve().then(async()=>{this.log("no session peers had block for for %c, finding new providers",t);for(let u=0;u<this.minProviders&&this.providers.length!==0;u++){let h=this.providers[Math.floor(Math.random()*this.providers.length)];this.evict(h)}await this.findProviders(t,this.minProviders,e),this.log("found new providers re-retrieving %c",t),this.requests.delete(n),o.resolve(await this.retrieve(t,e))}).catch(u=>{this.log.error("could not find new providers for %c",t,u),o.reject(u)})});let c=u=>{a.add(async()=>this.queryProvider(t,u.detail,e),{provider:u.detail}).catch(h=>{e.signal?.aborted!==!0&&this.log.error("error retrieving session block for %c",t,h)})};this.addEventListener("provider",c),Promise.all([...this.providers].map(async u=>a.add(async()=>this.queryProvider(t,u,e),{provider:u}))).catch(u=>{e.signal?.aborted!==!0&&this.log.error("error retrieving session block for %c",t,u)});let l=()=>{o.reject(new X(e.signal?.reason??"Session aborted")),a.abort()};e.signal?.addEventListener("abort",l);try{return await o.promise}finally{this.removeEventListener("provider",c),e.signal?.removeEventListener("abort",l),a.clear(),this.requests.delete(n)}}evict(t){this.evictionFilter.add(this.toEvictionKey(t));let e=this.providers.findIndex(n=>this.equals(n,t));e!==-1&&this.providers.splice(e,1)}isEvicted(t){return this.evictionFilter.has(this.toEvictionKey(t))}hasProvider(t){return!!(this.providers.find(e=>this.equals(e,t))!=null||this.isEvicted(t))}async findProviders(t,e,n){let s=P(),o=0;return Promise.resolve().then(async()=>{this.log("finding %d-%d new provider(s) for %c",e,this.maxProviders,t);for await(let i of this.findNewProviders(t,n)){if(o===this.maxProviders||n.signal?.aborted===!0)break;if(!this.hasProvider(i)&&(this.log("found %d/%d new providers",o,this.maxProviders),this.providers.push(i),this.safeDispatchEvent("provider",{detail:i}),o++,o===e&&(this.log("session is ready"),s.resolve()),this.providers.length===this.maxProviders)){this.log("found max session peers",o);break}}if(this.log("found %d/%d new session peers",o,this.maxProviders),o<e)throw new Xe(`Found ${o} of ${e} ${this.name} providers for ${t}`)}).catch(i=>{this.log.error("error searching routing for potential session peers for %c",t,i.errors??i),s.reject(i)}),s.promise}};var gn=class extends _t{wantList;network;constructor(t,e){super(t,{...e,name:"helia:bitswap:session"}),this.wantList=t.wantList,this.network=t.network}async queryProvider(t,e,n){this.log("sending WANT-BLOCK for %c to %p",t,e);let s=await this.wantList.wantSessionBlock(t,e,n);if(this.log("%p %s %c",e,s.has?"has":"does not have",t),s.has&&s.block!=null)return s.block;throw new Error("Provider did not have block")}async*findNewProviders(t,e={}){for await(let n of this.network.findProviders(t,e))yield n.id}toEvictionKey(t){return t.toMultihash().bytes}equals(t,e){return t.equals(e)}};function Us(r,t){return new gn(r,t)}var Qe=class{blocksReceived;duplicateBlocksReceived;dataReceived;duplicateDataReceived;constructor(t){this.blocksReceived=t.metrics?.registerMetricGroup("helia_bitswap_received_blocks"),this.duplicateBlocksReceived=t.metrics?.registerMetricGroup("helia_bitswap_duplicate_received_blocks"),this.dataReceived=t.metrics?.registerMetricGroup("helia_bitswap_data_received_bytes"),this.duplicateDataReceived=t.metrics?.registerMetricGroup("helia_bitswap_duplicate_data_received_bytes")}updateBlocksReceived(t=1,e){let n={global:t};e!=null&&(n[e.toString()]=t),this.blocksReceived?.increment(n)}updateDuplicateBlocksReceived(t=1,e){let n={global:t};e!=null&&(n[e.toString()]=t),this.duplicateBlocksReceived?.increment(n)}updateDataReceived(t,e){let n={global:t};e!=null&&(n[e.toString()]=t),this.dataReceived?.increment(n)}updateDuplicateDataReceived(t,e){let n={global:t};e!=null&&(n[e.toString()]=t),this.duplicateDataReceived?.increment(n)}};var wn=class extends Map{metric;constructor(t){super();let{name:e,metrics:n}=t;this.metric=n.registerMetric(e),this.updateComponentMetric()}set(t,e){return super.set(t,e),this.updateComponentMetric(),this}delete(t){let e=super.delete(t);return this.updateComponentMetric(),e}clear(){super.clear(),this.updateComponentMetric()}updateComponentMetric(){this.metric.update(this.size)}};function Rs(r){let{name:t,metrics:e}=r,n;return e!=null?n=new wn({name:t,metrics:e}):n=new Map,n}function Na(r){if(!(r instanceof Uint8Array))throw new Error("arg needs to be a Uint8Array");let t=[];for(;r.length>0;){let e=j(r);t.push(e),r=r.slice(_(e))}return t}var Bs=Na;var je=class extends tt{peers;wants;network;log;sendMessagesDelay;sendMessagesTimeout;hashLoader;sendingMessages;constructor(t,e={}){super(),this.peers=se({name:"helia_bitswap_peers",metrics:t.metrics}),this.wants=Rs({name:"helia_bitswap_wantlist",metrics:t.metrics}),this.network=t.network,this.sendMessagesDelay=e.sendMessagesDelay??10,this.log=t.logger.forComponent("helia:bitswap:wantlist"),this.hashLoader=e.hashLoader,this.network.addEventListener("bitswap:message",n=>{this.receiveMessage(n.detail.peer,n.detail.message).catch(s=>{this.log.error("error receiving bitswap message from %p",n.detail.peer,s)})}),this.network.addEventListener("peer:connected",n=>{this.peerConnected(n.detail).catch(s=>{this.log.error("error processing newly connected bitswap peer %p",n.detail,s)})}),this.network.addEventListener("peer:disconnected",n=>{this.peerDisconnected(n.detail)})}async addEntry(t,e){let n=S(t.multihash.bytes,"base64"),s=this.wants.get(n);s==null&&(s={cid:t,priority:e.priority??1,wantType:e.wantType??A.WantBlock,cancel:!1,sendDontHave:!0},this.wants.set(n,s)),s.wantType===A.WantHave&&e.wantType===A.WantBlock&&(s.wantType=A.WantBlock),await this.sendMessagesDebounced();try{return e.wantType===A.WantBlock?(await Q(this,"block",e?.signal,{filter:a=>K(t.multihash.digest,a.detail.cid.multihash.digest),errorMessage:"Want was aborted"})).detail:(await Q(this,"presence",e?.signal,{filter:i=>K(t.multihash.digest,i.detail.cid.multihash.digest),errorMessage:"Want was aborted"})).detail}finally{e.signal?.aborted===!0&&(this.log("want for %c was aborted, cancelling want",t),s.cancel=!0,await this.sendMessagesDebounced())}}async sendMessagesDebounced(){await this.sendingMessages?.promise,clearTimeout(this.sendMessagesTimeout),this.sendMessagesTimeout=setTimeout(()=>{this.sendMessages().catch(t=>{this.log("error sending messages to peers",t)})},this.sendMessagesDelay)}async sendMessages(){this.sendingMessages=P(),await Promise.all([...this.peers.entries()].map(async([t,e])=>{let n=new Set,s=new at;for(let[o,i]of this.wants.entries())e.has(o)||i.cancel||(n.add(o),s.addWantlistEntry(i.cid,{cid:i.cid.bytes,priority:i.priority,wantType:i.wantType,cancel:i.cancel,sendDontHave:i.sendDontHave}));if(s.wantlist.size!==0)try{await this.network.sendMessage(t,s);for(let o of n)e.add(o)}catch(o){this.log.error("error sending full wantlist to new peer",o)}})).catch(t=>{this.log.error("error sending messages",t)});for(let[t,e]of this.wants)if(e.cancel){this.wants.delete(t);for(let n of this.peers.values())n.delete(t)}this.sendingMessages.resolve()}has(t){let e=S(t.multihash.bytes,"base64");return this.wants.has(e)}async wantSessionPresence(t,e,n={}){let s=new at;return s.addWantlistEntry(t,{cid:t.bytes,sendDontHave:!0,wantType:A.WantHave,priority:1}),await this.network.sendMessage(e,s),(await Q(this,"presence",n.signal,{filter:i=>e.equals(i.detail.sender)&&K(t.multihash.digest,i.detail.cid.multihash.digest)})).detail}async wantBlock(t,e={}){return this.addEntry(t,{...e,wantType:A.WantBlock})}async wantSessionBlock(t,e,n={}){let s=new at;return s.addWantlistEntry(t,{cid:t.bytes,sendDontHave:!0,wantType:A.WantBlock,priority:1}),await this.network.sendMessage(e,s),(await Q(this,"presence",n.signal,{filter:i=>e.equals(i.detail.sender)&&K(t.multihash.digest,i.detail.cid.multihash.digest)})).detail}async receivedBlock(t,e){let n=S(t.multihash.bytes,"base64"),s=this.wants.get(n);s!=null&&(s.cancel=!0,await this.sendMessagesDebounced())}async receiveMessage(t,e){this.log("received message from %p with %d blocks",t,e.blocks.length);let n=!1;for(let s of e.blocks){if(s.prefix==null||s.data==null)continue;let o=Bs(s.prefix),i=o[0],a=o[1],c=o[2],l=c===Ce.code?Ce:await this.hashLoader?.getHasher(c);if(l==null){this.log.error("unknown hash algorithm",c);continue}let u=l.digest(s.data);u.then!=null&&(u=await u);let h=q.create(i===0?0:1,a,u);this.log("received block from %p for %c",t,h),this.safeDispatchEvent("block",{detail:{sender:t,cid:h,block:s.data}}),this.safeDispatchEvent("presence",{detail:{sender:t,cid:h,has:!0,block:s.data}});let f=S(h.multihash.bytes,"base64"),m=this.wants.get(f);m!=null&&(m.cancel=!0,n=!0)}for(let{cid:s,type:o}of e.blockPresences){let i=q.decode(s);this.log("received %s from %p for %c",o,t,i),this.safeDispatchEvent("presence",{detail:{sender:t,cid:i,has:o===W.HaveBlock}})}n&&await this.sendMessagesDebounced()}async peerConnected(t){let e=new Set,n=new at(!0);for(let[s,o]of this.wants.entries())o.cancel||(e.add(s),n.addWantlistEntry(o.cid,{cid:o.cid.bytes,priority:1,wantType:A.WantBlock,cancel:!1,sendDontHave:!1}));if(n.wantlist.size===0){this.peers.set(t,e);return}try{await this.network.sendMessage(t,n),this.peers.set(t,e)}catch(s){this.log.error("error sending full wantlist to new peer %p",t,s)}}peerDisconnected(t){this.peers.delete(t)}start(){}stop(){this.peers.clear(),clearTimeout(this.sendMessagesTimeout)}};var Ke=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 Qe(t),this.network=new qe(t,e),this.peerWantLists=new Ge({...t,network:this.network},e),this.wantList=new je({...t,network:this.network},e)}createSession(t={}){return Us({wantList:this.wantList,network:this.network,logger:this.logger},t)}async want(t,e={}){let n=new AbortController,s=Hn([n.signal,e.signal]);n.signal,this.network.findAndConnect(t,{...e,signal:s}).catch(o=>{n.signal.aborted||this.log.error("error during finding and connect for cid %c",t,o)});try{return(await this.wantList.wantBlock(t,{...e,signal:s})).block}finally{n.abort(),s.clear()}}async notify(t,e,n={}){await Promise.all([this.peerWantLists.receivedBlock(t,n),this.wantList.receivedBlock(t,n)])}getWantlist(){return[...this.wantList.wants.values()].filter(t=>!t.cancel).map(t=>({cid:t.cid,priority:t.priority,wantType:t.wantType}))}getPeerWantlist(t){return this.peerWantLists.wantListForPeer(t)}async start(){this.wantList.start(),await this.network.start()}async stop(){this.wantList.stop(),await this.network.stop()}};var zs=(r,t={})=>new Ke(r,t);var bn=class{bitswap;started;constructor(t,e={}){let{getHasher:n}=t;this.bitswap=zs(t,{hashLoader:{getHasher:async s=>n(s)},...e}),this.started=!1}isStarted(){return this.started}async start(){await this.bitswap.start(),this.started=!0}async stop(){await this.bitswap.stop(),this.started=!1}async announce(t,e,n){await this.bitswap.notify(t,e,n)}async retrieve(t,e={}){return this.bitswap.want(t,e)}createSession(t){let e=this.bitswap.createSession(t);return{announce:async(n,s,o)=>{await this.bitswap.notify(n,s,o)},retrieve:async(n,s)=>e.retrieve(n,s)}}};function Os(r={}){return t=>new bn(t,r)}var Je=class{index=0;input="";new(t){return this.index=0,this.input=t,this}readAtomically(t){let e=this.index,n=t();return n===void 0&&(this.index=e),n}parseWith(t){let e=t();if(this.index===this.input.length)return e}peekChar(){if(!(this.index>=this.input.length))return this.input[this.index]}readChar(){if(!(this.index>=this.input.length))return this.input[this.index++]}readGivenChar(t){return this.readAtomically(()=>{let e=this.readChar();if(e===t)return e})}readSeparator(t,e,n){return this.readAtomically(()=>{if(!(e>0&&this.readGivenChar(t)===void 0))return n()})}readNumber(t,e,n,s){return this.readAtomically(()=>{let o=0,i=0,a=this.peekChar();if(a===void 0)return;let c=a==="0",l=2**(8*s)-1;for(;;){let u=this.readAtomically(()=>{let h=this.readChar();if(h===void 0)return;let f=Number.parseInt(h,t);if(!Number.isNaN(f))return f});if(u===void 0)break;if(o*=t,o+=u,o>l||(i+=1,e!==void 0&&i>e))return}if(i!==0)return!n&&c&&i>1?void 0:o})}readIPv4Addr(){return this.readAtomically(()=>{let t=new Uint8Array(4);for(let e=0;e<t.length;e++){let n=this.readSeparator(".",e,()=>this.readNumber(10,3,!1,1));if(n===void 0)return;t[e]=n}return t})}readIPv6Addr(){let t=e=>{for(let n=0;n<e.length/2;n++){let s=n*2;if(n<e.length-3){let i=this.readSeparator(":",n,()=>this.readIPv4Addr());if(i!==void 0)return e[s]=i[0],e[s+1]=i[1],e[s+2]=i[2],e[s+3]=i[3],[s+4,!0]}let o=this.readSeparator(":",n,()=>this.readNumber(16,4,!0,2));if(o===void 0)return[s,!1];e[s]=o>>8,e[s+1]=o&255}return[e.length,!1]};return this.readAtomically(()=>{let e=new Uint8Array(16),[n,s]=t(e);if(n===16)return e;if(s||this.readGivenChar(":")===void 0||this.readGivenChar(":")===void 0)return;let o=new Uint8Array(14),i=16-(n+2),[a]=t(o.subarray(0,i));return e.set(o.subarray(0,a),16-a),e})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};var $s=45,Fa=15,zt=new Je;function yn(r){if(!(r.length>Fa))return zt.new(r).parseWith(()=>zt.readIPv4Addr())}function xn(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>$s))return zt.new(r).parseWith(()=>zt.readIPv6Addr())}function Ze(r,t=!1){if(r.includes("%")&&(r=r.split("%")[0]),r.length>$s)return;let e=zt.new(r).parseWith(()=>zt.readIPAddr());if(e)return t&&e.length===4?Uint8Array.from([0,0,0,0,0,0,0,0,0,0,255,255,e[0],e[1],e[2],e[3]]):e}function Ot(r){return!!yn(r)}function $t(r){return!!xn(r)}function Ye(r){return!!Ze(r)}var Hs=qn(qs(),1),Ca=["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"],Ma=Ca.map(r=>new Hs.Netmask(r));function En(r){for(let t of Ma)if(t.contains(r))return!0;return!1}function Ua(r){return/^::ffff:([0-9a-fA-F]{1,4}):([0-9a-fA-F]{1,4})$/.test(r)}function Ra(r){let t=r.split(":");if(t.length<2)return!1;let e=t[t.length-1].padStart(4,"0"),n=t[t.length-2].padStart(4,"0"),s=`${parseInt(n.substring(0,2),16)}.${parseInt(n.substring(2),16)}.${parseInt(e.substring(0,2),16)}.${parseInt(e.substring(2),16)}`;return En(s)}function Ba(r){return/^::ffff:([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)}function za(r){let t=r.split(":"),e=t[t.length-1];return En(e)}function Oa(r){return/^::$/.test(r)||/^::1$/.test(r)||/^64:ff9b::([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)||/^100::([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^2001::([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^2001:2[0-9a-fA-F]:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^2001:db8:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^2002:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^f[c-d]([0-9a-fA-F]{2,2}):/i.test(r)||/^fe[8-9a-bA-B][0-9a-fA-F]:/i.test(r)||/^ff([0-9a-fA-F]{2,2}):/i.test(r)}function Vs(r){return Ot(r)?En(r):Ua(r)?Ra(r):Ba(r)?za(r):$t(r)?Oa(r):void 0}var $a=r=>r.toString().split("/").slice(1),qt=r=>({match:t=>t.length<1?!1:r(t[0])?t.slice(1):!1,pattern:"fn"}),w=r=>({match:t=>qt(e=>e===r).match(t),pattern:r}),St=()=>({match:r=>qt(t=>typeof t=="string").match(r),pattern:"{string}"}),ie=()=>({match:r=>qt(t=>!isNaN(parseInt(t))).match(r),pattern:"{number}"}),E=()=>({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}"}),ae=()=>({match:r=>{if(r.length<2||r[0]!=="certhash")return!1;try{Hr.decode(r[1])}catch{return!1}return r.slice(2)},pattern:"/certhash/{certhash}"}),y=r=>({match:t=>{let e=r.match(t);return e===!1?t:e},pattern:`optional(${r.pattern})`}),R=(...r)=>({match:t=>{let e;for(let n of r){let s=n.match(t);s!==!1&&(e==null||s.length<e.length)&&(e=s)}return e??!1},pattern:`or(${r.map(t=>t.pattern).join(", ")})`}),b=(...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 o=$a(s);for(let i of r){let a=i.match(o);if(a===!1)return!1;o=a}return o}function e(s){return t(s)!==!1}function n(s){let o=t(s);return o===!1?!1:o.length===0}return{matchers:r,matches:e,exactMatch:n}}var qa=E(),tp=k(qa),er=b(w("dns4"),St()),rr=b(w("dns6"),St()),nr=b(w("dnsaddr"),St()),_n=b(w("dns"),St()),ep=k(er,y(E())),rp=k(rr,y(E())),np=k(nr,y(E())),Ws=k(R(_n,nr,er,rr),y(E())),Gs=b(w("ip4"),qt(Ot)),Xs=b(w("ip6"),qt($t)),Sn=R(Gs,Xs),ct=R(Sn,_n,er,rr,nr),sp=k(R(Sn,b(R(_n,nr,er,rr),y(E())))),op=k(Gs),ip=k(Xs),ap=k(Sn),kn=b(ct,w("tcp"),ie()),ce=b(ct,w("udp"),ie()),cp=k(b(kn,y(E()))),lp=k(ce),In=b(ce,w("quic"),y(E())),sr=b(ce,w("quic-v1"),y(E())),Ha=R(In,sr),up=k(In),hp=k(sr),vn=R(ct,kn,ce,In,sr),Qs=R(b(vn,w("ws"),y(E()))),fp=k(Qs),js=R(b(vn,w("wss"),y(E())),b(vn,w("tls"),y(b(w("sni"),St())),w("ws"),y(E()))),dp=k(js),Ks=b(ce,w("webrtc-direct"),y(ae()),y(ae()),y(E())),pp=k(Ks),Js=b(sr,w("webtransport"),y(ae()),y(ae()),y(E())),mp=k(Js),tr=R(Qs,js,b(kn,y(E())),b(Ha,y(E())),b(ct,y(E())),Ks,Js,E()),gp=k(tr),Va=b(tr,w("p2p-circuit"),E()),wp=k(Va),Wa=R(b(tr,w("p2p-circuit"),w("webrtc"),y(E())),b(tr,w("webrtc"),y(E())),b(w("webrtc"),y(E()))),bp=k(Wa),Ga=R(b(ct,w("tcp"),ie(),w("http"),y(E())),b(ct,w("http"),y(E()))),Zs=k(Ga),Xa=R(b(ct,w("tcp"),R(b(w("443"),w("http")),b(ie(),w("https"))),y(E())),b(ct,w("tls"),w("http"),y(E())),b(ct,w("https"),y(E()))),Ys=k(Xa),Qa=R(b(w("memory"),St(),y(E()))),yp=k(Qa);var Ap=parseInt("0xFFFF",16),Lp=new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);var ro=Ot,Ya=$t,An=function(r){let t=0;if(r=r.toString().trim(),ro(r)){let e=new Uint8Array(t+4);return r.split(/\./g).forEach(n=>{e[t++]=parseInt(n,10)&255}),e}if(Ya(r)){let e=r.split(":",8),n;for(n=0;n<e.length;n++){let o=ro(e[n]),i;o&&(i=An(e[n]),e[n]=S(i.slice(0,2),"base16")),i!=null&&++n<8&&e.splice(n,0,S(i.slice(2,4),"base16"))}if(e[0]==="")for(;e.length<8;)e.unshift("0");else if(e[e.length-1]==="")for(;e.length<8;)e.push("0");else if(e.length<8){for(n=0;n<e.length&&e[n]!=="";n++);let o=[n,1];for(n=9-e.length;n>0;n--)o.push("0");e.splice.apply(e,o)}let s=new Uint8Array(t+16);for(n=0;n<e.length;n++){let o=parseInt(e[n],16);s[t++]=o>>8&255,s[t++]=o&255}return s}throw new Error("invalid ip address")},no=function(r,t=0,e){t=~~t,e=e??r.length-t;let n=new DataView(r.buffer);if(e===4){let s=[];for(let o=0;o<e;o++)s.push(r[t+o]);return s.join(".")}if(e===16){let s=[];for(let o=0;o<e;o+=2)s.push(n.getUint16(t+o).toString(16));return s.join(":").replace(/(^|:)0(:0)*:0(:|$)/,"$1::$3").replace(/:{3,4}/,"::")}return""};var Ht={},Ln={},ec=[[4,32,"ip4"],[6,16,"tcp"],[33,16,"dccp"],[41,128,"ip6"],[42,-1,"ip6zone"],[43,8,"ipcidr"],[53,-1,"dns",!0],[54,-1,"dns4",!0],[55,-1,"dns6",!0],[56,-1,"dnsaddr",!0],[132,16,"sctp"],[273,16,"udp"],[275,0,"p2p-webrtc-star"],[276,0,"p2p-webrtc-direct"],[277,0,"p2p-stardust"],[280,0,"webrtc-direct"],[281,0,"webrtc"],[290,0,"p2p-circuit"],[301,0,"udt"],[302,0,"utp"],[400,-1,"unix",!1,!0],[421,-1,"ipfs"],[421,-1,"p2p"],[443,0,"https"],[444,96,"onion"],[445,296,"onion3"],[446,-1,"garlic64"],[448,0,"tls"],[449,-1,"sni"],[460,0,"quic"],[461,0,"quic-v1"],[465,0,"webtransport"],[466,-1,"certhash"],[477,0,"ws"],[478,0,"wss"],[479,0,"p2p-websocket-star"],[480,0,"http"],[481,-1,"http-path"],[777,-1,"memory"]];ec.forEach(r=>{let t=rc(...r);Ln[t.code]=t,Ht[t.name]=t});function rc(r,t,e,n,s){return{code:r,size:t,name:e,resolvable:!!n,path:!!s}}function p(r){if(typeof r=="number"){if(Ln[r]!=null)return Ln[r];throw new Error(`no protocol with code: ${r}`)}else if(typeof r=="string"){if(Ht[r]!=null)return Ht[r];throw new Error(`no protocol with name: ${r}`)}throw new Error(`invalid protocol id type: ${typeof r}`)}var lm=p("ip4"),um=p("ip6"),hm=p("ipcidr");function Nn(r,t){switch(p(r).code){case 4:case 41:return sc(t);case 42:return Pn(t);case 43:return S(t,"base10");case 6:case 273:case 33:case 132:return io(t).toString();case 53:case 54:case 55:case 56:case 400:case 449:case 777:return Pn(t);case 421:return cc(t);case 444:return oo(t);case 445:return oo(t);case 466:return ac(t);case 481:return globalThis.encodeURIComponent(Pn(t));default:return S(t,"base16")}}function Fn(r,t){switch(p(r).code){case 4:return so(t);case 41:return so(t);case 42:return Dn(t);case 43:return U(t,"base10");case 6:case 273:case 33:case 132:return Cn(parseInt(t,10));case 53:case 54:case 55:case 56:case 400:case 449:case 777:return Dn(t);case 421:return oc(t);case 444:return lc(t);case 445:return uc(t);case 466:return ic(t);case 481:return Dn(globalThis.decodeURIComponent(t));default:return U(t,"base16")}}var Tn=Object.values(Zt).map(r=>r.decoder),nc=function(){let r=Tn[0].or(Tn[1]);return Tn.slice(2).forEach(t=>r=r.or(t)),r}();function so(r){if(!Ye(r))throw new Error("invalid ip address");return An(r)}function sc(r){let t=no(r,0,r.length);if(t==null)throw new Error("ipBuff is required");if(!Ye(t))throw new Error("invalid ip address");return t}function Cn(r){let t=new ArrayBuffer(2);return new DataView(t).setUint16(0,r),new Uint8Array(t)}function io(r){return new DataView(r.buffer).getUint16(r.byteOffset)}function Dn(r){let t=U(r),e=Uint8Array.from(et(t.length));return V([e,t],e.length+t.length)}function Pn(r){let t=j(r);if(r=r.slice(_(t)),r.length!==t)throw new Error("inconsistent lengths");return S(r)}function oc(r){let t;r[0]==="Q"||r[0]==="1"?t=Kt(D.decode(`z${r}`)).bytes:t=q.parse(r).multihash.bytes;let e=Uint8Array.from(et(t.length));return V([e,t],e.length+t.length)}function ic(r){let t=nc.decode(r),e=Uint8Array.from(et(t.length));return V([e,t],e.length+t.length)}function ac(r){let t=j(r),e=r.slice(_(t));if(e.length!==t)throw new Error("inconsistent lengths");return"u"+S(e,"base64url")}function cc(r){let t=j(r),e=r.slice(_(t));if(e.length!==t)throw new Error("inconsistent lengths");return S(e,"base58btc")}function lc(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=Cn(n);return V([e,s],e.length+s.length)}function uc(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=Cn(n);return V([e,s],e.length+s.length)}function oo(r){let t=r.slice(0,r.length-2),e=r.slice(r.length-2),n=S(t,"base32"),s=io(e);return`${n}:${s}`}function ao(r){r=Mn(r);let t=[],e=[],n=null,s=r.split("/").slice(1);if(s.length===1&&s[0]==="")return{bytes:new Uint8Array,string:"/",tuples:[],stringTuples:[],path:null};for(let o=0;o<s.length;o++){let i=s[o],a=p(i);if(a.size===0){t.push([a.code]),e.push([a.code]);continue}if(o++,o>=s.length)throw new or("invalid address: "+r);if(a.path===!0){n=Mn(s.slice(o).join("/")),t.push([a.code,Fn(a.code,n)]),e.push([a.code,n]);break}let c=Fn(a.code,s[o]);t.push([a.code,c]),e.push([a.code,Nn(a.code,c)])}return{string:co(e),bytes:ir(t),tuples:t,stringTuples:e,path:n}}function Un(r){let t=[],e=[],n=null,s=0;for(;s<r.length;){let o=j(r,s),i=_(o),a=p(o),c=hc(a,r.slice(s+i));if(c===0){t.push([o]),e.push([o]),s+=i;continue}let l=r.slice(s+i,s+i+c);if(s+=c+i,s>r.length)throw new or("Invalid address Uint8Array: "+S(r,"base16"));t.push([o,l]);let u=Nn(o,l);if(e.push([o,u]),a.path===!0){n=u;break}}return{bytes:Uint8Array.from(r),string:co(e),tuples:t,stringTuples:e,path:n}}function co(r){let t=[];return r.map(e=>{let n=p(e[0]);return t.push(n.name),e.length>1&&e[1]!=null&&t.push(e[1]),null}),Mn(t.join("/"))}function ir(r){return V(r.map(t=>{let e=p(t[0]),n=Uint8Array.from(et(e.code));return t.length>1&&t[1]!=null&&(n=V([n,t[1]])),n}))}function hc(r,t){if(r.size>0)return r.size/8;if(r.size===0)return 0;{let e=j(t instanceof Uint8Array?t:Uint8Array.from(t));return e+_(e)}}function Mn(r){return"/"+r.trim().split("/").filter(t=>t).join("/")}var or=class extends Error{static name="ParseError";name="ParseError";constructor(t){super(`Error parsing address: ${t}`)}};var fc=Symbol.for("nodejs.util.inspect.custom"),Bn=Symbol.for("@multiformats/js-multiaddr/multiaddr"),dc=[p("dns").code,p("dns4").code,p("dns6").code,p("dnsaddr").code],Rn=class extends Error{constructor(t="No available resolver"){super(t),this.name="NoAvailableResolverError"}},ar=class r{bytes;#t;#e;#r;#n;[Bn]=!0;constructor(t){t==null&&(t="");let e;if(t instanceof Uint8Array)e=Un(t);else if(typeof t=="string"){if(t.length>0&&t.charAt(0)!=="/")throw new Error(`multiaddr "${t}" must start with a "/"`);e=ao(t)}else if(uo(t))e=Un(t.bytes);else throw new Error("addr must be a string, Buffer, or another Multiaddr");this.bytes=e.bytes,this.#t=e.string,this.#e=e.tuples,this.#r=e.stringTuples,this.#n=e.path}toString(){return this.#t}toJSON(){return this.toString()}toOptions(){let t,e,n,s,o="",i=p("tcp"),a=p("udp"),c=p("ip4"),l=p("ip6"),u=p("dns6"),h=p("ip6zone");for(let[m,d]of this.stringTuples())m===h.code&&(o=`%${d??""}`),dc.includes(m)&&(e=i.name==="tcp"?"tcp":"udp",s=443,n=`${d??""}${o}`,t=m===u.code?6:4),(m===i.code||m===a.code)&&(e=p(m).name==="tcp"?"tcp":"udp",s=parseInt(d??"")),(m===c.code||m===l.code)&&(e=p(m).name==="tcp"?"tcp":"udp",n=`${d??""}${o}`,t=m===l.code?6:4);if(t==null||e==null||n==null||s==null)throw new Error('multiaddr must have a valid format: "/{ip4, ip6, dns4, dns6, dnsaddr}/{address}/{tcp, udp}/{port}".');return{family:t,host:n,transport:e,port:s}}protos(){return this.#e.map(([t])=>Object.assign({},p(t)))}protoCodes(){return this.#e.map(([t])=>t)}protoNames(){return this.#e.map(([t])=>p(t).name)}tuples(){return this.#e.map(([t,e])=>e==null?[t]:[t,e])}stringTuples(){return this.#r.map(([t,e])=>e==null?[t]:[t,e])}encapsulate(t){return t=new r(t),new r(this.toString()+t.toString())}decapsulate(t){let e=t.toString(),n=this.toString(),s=n.lastIndexOf(e);if(s<0)throw new Error(`Address ${this.toString()} does not contain subaddress: ${t.toString()}`);return new r(n.slice(0,s))}decapsulateCode(t){let e=this.tuples();for(let n=e.length-1;n>=0;n--)if(e[n][0]===t)return new r(ir(e.slice(0,n)));return this}getPeerId(){try{let t=[];this.stringTuples().forEach(([n,s])=>{n===Ht.p2p.code&&t.push([n,s]),n===Ht["p2p-circuit"].code&&(t=[])});let e=t.pop();if(e?.[1]!=null){let n=e[1];return n[0]==="Q"||n[0]==="1"?S(D.decode(`z${n}`),"base58btc"):S(q.parse(n).multihash.bytes,"base58btc")}return null}catch{return null}}getPath(){return this.#n}equals(t){return K(this.bytes,t.bytes)}async resolve(t){let e=this.protos().find(o=>o.resolvable);if(e==null)return[this];let n=lo.get(e.name);if(n==null)throw new Rn(`no available resolver for ${e.name}`);return(await n(this,t)).map(o=>le(o))}nodeAddress(){let t=this.toOptions();if(t.transport!=="tcp"&&t.transport!=="udp")throw new Error(`multiaddr must have a valid format - no protocol with name: "${t.transport}". Must have a valid transport protocol: "{tcp, udp}"`);return{family:t.family,address:t.host,port:t.port}}isThinWaistAddress(t){let e=(t??this).protos();return!(e.length!==2||e[0].code!==4&&e[0].code!==41||e[1].code!==6&&e[1].code!==273)}[fc](){return`Multiaddr(${this.#t})`}};var lo=new Map;function uo(r){return!!r?.[Bn]}function le(r){return new ar(r)}var pc=[p("tcp").code,p("dns").code,p("dnsaddr").code,p("dns4").code,p("dns6").code];function ho(r){return mo("sni",r)?.[1]}function fo(r){let t=mo("tcp",r)?.[1];return t==null?"":`:${t}`}function mo(r,t){let e;try{e=p(r).code}catch{return}for(let[n,s]of t)if(n===e&&s!=null)return[n,s]}function po(r){return r.some(([t,e])=>t===p("tls").code)}function Y(r,t,e){let n=go[p(r).name];if(n==null)throw new Error(`Can't interpret protocol ${p(r).name}`);let s=n(t,e);return r===p("ip6").code?`[${s}]`:s}var go={ip4:(r,t)=>r,ip6:(r,t)=>t.length===0?r:`[${r}]`,tcp:(r,t)=>{let e=t.pop();if(e==null)throw new Error("Unexpected end of multiaddr");return`tcp://${Y(e[0],e[1]??"",t)}:${r}`},udp:(r,t)=>{let e=t.pop();if(e==null)throw new Error("Unexpected end of multiaddr");return`udp://${Y(e[0],e[1]??"",t)}:${r}`},dnsaddr:(r,t)=>r,dns4:(r,t)=>r,dns6:(r,t)=>r,dns:(r,t)=>r,ipfs:(r,t)=>{let e=t.pop();if(e==null)throw new Error("Unexpected end of multiaddr");return`${Y(e[0],e[1]??"",t)}`},p2p:(r,t)=>{let e=t.pop();if(e==null)throw new Error("Unexpected end of multiaddr");return`${Y(e[0],e[1]??"",t)}`},http:(r,t)=>{let e=po(t),n=ho(t),s=fo(t);if(e&&n!=null)return`https://${n}${s}`;let o=e?"https://":"http://",i=t.pop();if(i==null)throw new Error("Unexpected end of multiaddr");let a=Y(i[0],i[1]??"",t);return a=a.replace("tcp://",""),`${o}${a}`},"http-path":(r,t)=>{let e=t.pop();if(e==null)throw new Error("Unexpected end of multiaddr");let n=Y(e[0],e[1]??"",t),s=decodeURIComponent(r);return`${n}/${s}`},tls:(r,t)=>{let e=t.pop();if(e==null)throw new Error("Unexpected end of multiaddr");return Y(e[0],e[1]??"",t)},sni:(r,t)=>{let e=t.pop();if(e==null)throw new Error("Unexpected end of multiaddr");return Y(e[0],e[1]??"",t)},https:(r,t)=>{let e=t.pop();if(e==null)throw new Error("Unexpected end of multiaddr");let n=Y(e[0],e[1]??"",t);return n=n.replace("tcp://",""),`https://${n}`},ws:(r,t)=>{let e=po(t),n=ho(t),s=fo(t);if(e&&n!=null)return`wss://${n}${s}`;let o=e?"wss://":"ws://",i=t.pop();if(i==null)throw new Error("Unexpected end of multiaddr");let a=Y(i[0],i[1]??"",t);return a=a.replace("tcp://",""),`${o}${a}`},wss:(r,t)=>{let e=t.pop();if(e==null)throw new Error("Unexpected end of multiaddr");let n=Y(e[0],e[1]??"",t);return n=n.replace("tcp://",""),`wss://${n}`}};function wo(r,t){let n=le(r).stringTuples(),s=n.pop();if(s==null)throw new Error("Unexpected end of multiaddr");let o=p(s[0]),i=go[o.name];if(i==null)throw new Error(`No interpreter found for ${o.name}`);let a=i(s[1]??"",n);return t?.assumeHttp!==!1&&pc.includes(s[0])&&(a=a.replace(/^.*:\/\//,""),s[1]==="443"?a=`https://${a}`:a=`http://${a}`),(a.startsWith("http://")||a.startsWith("https://")||a.startsWith("ws://")||a.startsWith("wss://"))&&(a=new URL(a).toString(),a.endsWith("/")&&(a=a.substring(0,a.length-1))),a}var cr=class{url;#t=0;#e=0;#r=0;#n=0;#s=new Map;log;transformRequestInit;constructor(t,{logger:e,transformRequestInit:n}){this.url=t instanceof URL?t:new URL(t),this.transformRequestInit=n,this.log=e.forComponent(`helia:trustless-gateway-block-broker:${this.url.hostname}`)}#o(t){let e=t.multihash.bytes;return it.encode(e)}async getRawBlock(t,e){let n=new URL(this.url.toString());if(n.pathname=`/ipfs/${t.toString()}`,n.search="?format=raw",e?.aborted===!0)throw new Error(`Signal to fetch raw block for CID ${t} from gateway ${this.url} was aborted prior to fetch`);let s=this.#o(t),o=new AbortController,i=()=>{o.abort()};e?.addEventListener("abort",i);try{let a=this.#s.get(s);if(a==null){this.#t++;let c={signal:o.signal,headers:{Accept:"application/vnd.ipld.raw"},cache:"force-cache"},l=this.transformRequestInit!=null?await this.transformRequestInit(c):c;a=fetch(n.toString(),l).then(async u=>{if(this.log("GET %s %d",n,u.status),!u.ok)throw this.#e++,new Error(`unable to fetch raw block for CID ${t} from gateway ${this.url}`);return this.#n++,new Uint8Array(await u.arrayBuffer())}),this.#s.set(s,a)}return await a}catch{throw e?.aborted===!0?new Error(`fetching raw block for CID ${t} from gateway ${this.url} was aborted`):(this.#e++,new Error(`unable to fetch raw block for CID ${t}`))}finally{e?.removeEventListener("abort",i),this.#s.delete(s)}}reliability(){return this.#t===0?1:this.#r>0?-1/0:this.#n/(this.#t+this.#e*3)}incrementInvalidBlocks(){this.#r++}getStats(){return{attempts:this.#t,errors:this.#e,invalidBlocks:this.#r,successes:this.#n,pendingResponses:this.#s.size}}};function mc(r,t,e){return r.filter(n=>{if(Ys.matches(n)||t&&Zs.matches(n))return e||Ws.matches(n)?!0:Vs(n.toOptions().host)===!1;if(!t&&e){let{host:s}=n.toOptions();if(s==="127.0.0.1"||s==="localhost"||s.endsWith(".localhost"))return!0}return!1})}async function*lr(r,t,e,n,s,o={}){for await(let i of t.findProviders(r,o)){let a=mc(i.multiaddrs,n,s);if(a.length===0)continue;let c=wo(a[0]);yield new cr(c,{logger:e,transformRequestInit:o.transformRequestInit})}}var zn=class extends _t{routing;allowInsecure;allowLocal;transformRequestInit;constructor(t,e){super(t,{...e,name:"helia:trustless-gateway:session"}),this.routing=t.routing,this.allowInsecure=e.allowInsecure??ur,this.allowLocal=e.allowLocal??hr,this.transformRequestInit=e.transformRequestInit}async queryProvider(t,e,n){this.log("fetching BLOCK for %c from %s",t,e.url);let s=await e.getRawBlock(t,n.signal);return this.log.trace("got block for %c from %s",t,e.url),await n.validateFn?.(s),s}async*findNewProviders(t,e={}){yield*lr(t,this.routing,this.logger,this.allowInsecure,this.allowLocal,{...e,transformRequestInit:this.transformRequestInit})}toEvictionKey(t){return t.url.toString()}equals(t,e){return t.url.toString()===e.url.toString()}};function bo(r,t){return new zn(r,t)}var fr=class{allowInsecure;allowLocal;transformRequestInit;routing;log;logger;constructor(t,e={}){this.log=t.logger.forComponent("helia:trustless-gateway-block-broker"),this.logger=t.logger,this.routing=t.routing,this.allowInsecure=e.allowInsecure??ur,this.allowLocal=e.allowLocal??hr,this.transformRequestInit=e.transformRequestInit}async retrieve(t,e={}){let n=[];for await(let s of lr(t,this.routing,this.logger,this.allowInsecure,this.allowLocal,{...e,transformRequestInit:this.transformRequestInit})){this.log("getting block for %c from %s",t,s.url);try{let o=await s.getRawBlock(t,e.signal);this.log.trace("got block for %c from %s",t,s.url);try{await e.validateFn?.(o)}catch(i){this.log.error("failed to validate block for %c from %s",t,s.url,i);continue}return o}catch(o){if(this.log.error("failed to get block for %c from %s",t,s.url,o),o instanceof Error?n.push(o):n.push(new Error(`Unable to fetch raw block for CID ${t} from gateway ${s.url}`)),e.signal?.aborted===!0){this.log.trace("request aborted while fetching raw block for CID %c from gateway %s",t,s.url);break}}}throw n.length>0?new AggregateError(n,`Unable to fetch raw block for CID ${t} from any gateway`):new Error(`Unable to fetch raw block for CID ${t} from any gateway`)}createSession(t={}){return bo({logger:this.logger,routing:this.routing},{...t,allowLocal:this.allowLocal,allowInsecure:this.allowInsecure,transformRequestInit:this.transformRequestInit})}};var ur=!1,hr=!1;function yo(r={}){return t=>new fr(t,r)}return ko(gc);})();
|
|
3
3
|
return HeliaBlockBrokers}));
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import type { TrustlessGatewayBlockBrokerInit, TrustlessGatewayBlockBrokerComponents, TrustlessGatewayGetBlockProgressEvents } from './index.js';
|
|
2
|
+
import type { TransformRequestInit } from './trustless-gateway.js';
|
|
2
3
|
import type { BlockRetrievalOptions, BlockBroker, CreateSessionOptions } from '@helia/interface';
|
|
3
4
|
import type { CID } from 'multiformats/cid';
|
|
4
5
|
export interface CreateTrustlessGatewaySessionOptions extends CreateSessionOptions<TrustlessGatewayGetBlockProgressEvents> {
|
|
@@ -16,6 +17,10 @@ export interface CreateTrustlessGatewaySessionOptions extends CreateSessionOptio
|
|
|
16
17
|
* @default false
|
|
17
18
|
*/
|
|
18
19
|
allowLocal?: boolean;
|
|
20
|
+
/**
|
|
21
|
+
* Provide a function that will be called before querying trustless-gateways. This lets you modify the fetch options to pass custom headers or other necessary things.
|
|
22
|
+
*/
|
|
23
|
+
transformRequestInit?: TransformRequestInit;
|
|
19
24
|
}
|
|
20
25
|
/**
|
|
21
26
|
* A class that accepts a list of trustless gateways that are queried
|
|
@@ -24,6 +29,7 @@ export interface CreateTrustlessGatewaySessionOptions extends CreateSessionOptio
|
|
|
24
29
|
export declare class TrustlessGatewayBlockBroker implements BlockBroker<TrustlessGatewayGetBlockProgressEvents> {
|
|
25
30
|
private readonly allowInsecure;
|
|
26
31
|
private readonly allowLocal;
|
|
32
|
+
private readonly transformRequestInit?;
|
|
27
33
|
private readonly routing;
|
|
28
34
|
private readonly log;
|
|
29
35
|
private readonly logger;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"broker.d.ts","sourceRoot":"","sources":["../../../src/trustless-gateway/broker.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,+BAA+B,EAAE,qCAAqC,EAAE,sCAAsC,EAAE,MAAM,YAAY,CAAA;AAChJ,OAAO,KAAK,EAAW,qBAAqB,EAAE,WAAW,EAAE,oBAAoB,EAAE,MAAM,kBAAkB,CAAA;AAEzG,OAAO,KAAK,EAAE,GAAG,EAAE,MAAM,kBAAkB,CAAA;AAE3C,MAAM,WAAW,oCAAqC,SAAQ,oBAAoB,CAAC,sCAAsC,CAAC;IACxH;;;;;OAKG;IACH,aAAa,CAAC,EAAE,OAAO,CAAA;IAEvB;;;;;OAKG;IACH,UAAU,CAAC,EAAE,OAAO,CAAA;
|
|
1
|
+
{"version":3,"file":"broker.d.ts","sourceRoot":"","sources":["../../../src/trustless-gateway/broker.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,+BAA+B,EAAE,qCAAqC,EAAE,sCAAsC,EAAE,MAAM,YAAY,CAAA;AAChJ,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,wBAAwB,CAAA;AAClE,OAAO,KAAK,EAAW,qBAAqB,EAAE,WAAW,EAAE,oBAAoB,EAAE,MAAM,kBAAkB,CAAA;AAEzG,OAAO,KAAK,EAAE,GAAG,EAAE,MAAM,kBAAkB,CAAA;AAE3C,MAAM,WAAW,oCAAqC,SAAQ,oBAAoB,CAAC,sCAAsC,CAAC;IACxH;;;;;OAKG;IACH,aAAa,CAAC,EAAE,OAAO,CAAA;IAEvB;;;;;OAKG;IACH,UAAU,CAAC,EAAE,OAAO,CAAA;IACpB;;OAEG;IACH,oBAAoB,CAAC,EAAE,oBAAoB,CAAA;CAC5C;AAED;;;GAGG;AACH,qBAAa,2BAA4B,YAAW,WAAW,CAAC,sCAAsC,CAAC;IACrG,OAAO,CAAC,QAAQ,CAAC,aAAa,CAAS;IACvC,OAAO,CAAC,QAAQ,CAAC,UAAU,CAAS;IACpC,OAAO,CAAC,QAAQ,CAAC,oBAAoB,CAAC,CAAsB;IAC5D,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAS;IACjC,OAAO,CAAC,QAAQ,CAAC,GAAG,CAAQ;IAC5B,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAiB;gBAE3B,UAAU,EAAE,qCAAqC,EAAE,IAAI,GAAE,+BAAoC;IASpG,QAAQ,CAAE,GAAG,EAAE,GAAG,EAAE,OAAO,GAAE,qBAAqB,CAAC,sCAAsC,CAAM,GAAG,OAAO,CAAC,UAAU,CAAC;IA2C3H,aAAa,CAAE,OAAO,GAAE,oCAAyC,GAAG,WAAW,CAAC,sCAAsC,CAAC;CAWxH"}
|
|
@@ -8,6 +8,7 @@ import { DEFAULT_ALLOW_INSECURE, DEFAULT_ALLOW_LOCAL } from './index.js';
|
|
|
8
8
|
export class TrustlessGatewayBlockBroker {
|
|
9
9
|
allowInsecure;
|
|
10
10
|
allowLocal;
|
|
11
|
+
transformRequestInit;
|
|
11
12
|
routing;
|
|
12
13
|
log;
|
|
13
14
|
logger;
|
|
@@ -17,10 +18,11 @@ export class TrustlessGatewayBlockBroker {
|
|
|
17
18
|
this.routing = components.routing;
|
|
18
19
|
this.allowInsecure = init.allowInsecure ?? DEFAULT_ALLOW_INSECURE;
|
|
19
20
|
this.allowLocal = init.allowLocal ?? DEFAULT_ALLOW_LOCAL;
|
|
21
|
+
this.transformRequestInit = init.transformRequestInit;
|
|
20
22
|
}
|
|
21
23
|
async retrieve(cid, options = {}) {
|
|
22
24
|
const aggregateErrors = [];
|
|
23
|
-
for await (const gateway of findHttpGatewayProviders(cid, this.routing, this.logger, this.allowInsecure, this.allowLocal, options)) {
|
|
25
|
+
for await (const gateway of findHttpGatewayProviders(cid, this.routing, this.logger, this.allowInsecure, this.allowLocal, { ...options, transformRequestInit: this.transformRequestInit })) {
|
|
24
26
|
this.log('getting block for %c from %s', cid, gateway.url);
|
|
25
27
|
try {
|
|
26
28
|
const block = await gateway.getRawBlock(cid, options.signal);
|
|
@@ -64,7 +66,8 @@ export class TrustlessGatewayBlockBroker {
|
|
|
64
66
|
}, {
|
|
65
67
|
...options,
|
|
66
68
|
allowLocal: this.allowLocal,
|
|
67
|
-
allowInsecure: this.allowInsecure
|
|
69
|
+
allowInsecure: this.allowInsecure,
|
|
70
|
+
transformRequestInit: this.transformRequestInit
|
|
68
71
|
});
|
|
69
72
|
}
|
|
70
73
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"broker.js","sourceRoot":"","sources":["../../../src/trustless-gateway/broker.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,6BAA6B,EAAE,MAAM,cAAc,CAAA;AAC5D,OAAO,EAAE,wBAAwB,EAAE,MAAM,YAAY,CAAA;AACrD,OAAO,EAAE,sBAAsB,EAAE,mBAAmB,EAAE,MAAM,YAAY,CAAA;
|
|
1
|
+
{"version":3,"file":"broker.js","sourceRoot":"","sources":["../../../src/trustless-gateway/broker.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,6BAA6B,EAAE,MAAM,cAAc,CAAA;AAC5D,OAAO,EAAE,wBAAwB,EAAE,MAAM,YAAY,CAAA;AACrD,OAAO,EAAE,sBAAsB,EAAE,mBAAmB,EAAE,MAAM,YAAY,CAAA;AA6BxE;;;GAGG;AACH,MAAM,OAAO,2BAA2B;IACrB,aAAa,CAAS;IACtB,UAAU,CAAS;IACnB,oBAAoB,CAAuB;IAC3C,OAAO,CAAS;IAChB,GAAG,CAAQ;IACX,MAAM,CAAiB;IAExC,YAAa,UAAiD,EAAE,OAAwC,EAAE;QACxG,IAAI,CAAC,GAAG,GAAG,UAAU,CAAC,MAAM,CAAC,YAAY,CAAC,sCAAsC,CAAC,CAAA;QACjF,IAAI,CAAC,MAAM,GAAG,UAAU,CAAC,MAAM,CAAA;QAC/B,IAAI,CAAC,OAAO,GAAG,UAAU,CAAC,OAAO,CAAA;QACjC,IAAI,CAAC,aAAa,GAAG,IAAI,CAAC,aAAa,IAAI,sBAAsB,CAAA;QACjE,IAAI,CAAC,UAAU,GAAG,IAAI,CAAC,UAAU,IAAI,mBAAmB,CAAA;QACxD,IAAI,CAAC,oBAAoB,GAAG,IAAI,CAAC,oBAAoB,CAAA;IACvD,CAAC;IAED,KAAK,CAAC,QAAQ,CAAE,GAAQ,EAAE,UAAyE,EAAE;QACnG,MAAM,eAAe,GAAY,EAAE,CAAA;QAEnC,IAAI,KAAK,EAAE,MAAM,OAAO,IAAI,wBAAwB,CAAC,GAAG,EAAE,IAAI,CAAC,OAAO,EAAE,IAAI,CAAC,MAAM,EAAE,IAAI,CAAC,aAAa,EAAE,IAAI,CAAC,UAAU,EAAE,EAAE,GAAG,OAAO,EAAE,oBAAoB,EAAE,IAAI,CAAC,oBAAoB,EAAE,CAAC,EAAE,CAAC;YAC3L,IAAI,CAAC,GAAG,CAAC,8BAA8B,EAAE,GAAG,EAAE,OAAO,CAAC,GAAG,CAAC,CAAA;YAE1D,IAAI,CAAC;gBACH,MAAM,KAAK,GAAG,MAAM,OAAO,CAAC,WAAW,CAAC,GAAG,EAAE,OAAO,CAAC,MAAM,CAAC,CAAA;gBAC5D,IAAI,CAAC,GAAG,CAAC,KAAK,CAAC,0BAA0B,EAAE,GAAG,EAAE,OAAO,CAAC,GAAG,CAAC,CAAA;gBAE5D,IAAI,CAAC;oBACH,MAAM,OAAO,CAAC,UAAU,EAAE,CAAC,KAAK,CAAC,CAAA;gBACnC,CAAC;gBAAC,OAAO,GAAG,EAAE,CAAC;oBACb,IAAI,CAAC,GAAG,CAAC,KAAK,CAAC,yCAAyC,EAAE,GAAG,EAAE,OAAO,CAAC,GAAG,EAAE,GAAG,CAAC,CAAA;oBAChF,sBAAsB;oBACtB,SAAQ;gBACV,CAAC;gBAED,OAAO,KAAK,CAAA;YACd,CAAC;YAAC,OAAO,GAAY,EAAE,CAAC;gBACtB,IAAI,CAAC,GAAG,CAAC,KAAK,CAAC,oCAAoC,EAAE,GAAG,EAAE,OAAO,CAAC,GAAG,EAAE,GAAG,CAAC,CAAA;gBAE3E,IAAI,GAAG,YAAY,KAAK,EAAE,CAAC;oBACzB,eAAe,CAAC,IAAI,CAAC,GAAG,CAAC,CAAA;gBAC3B,CAAC;qBAAM,CAAC;oBACN,eAAe,CAAC,IAAI,CAAC,IAAI,KAAK,CAAC,qCAAqC,GAAG,iBAAiB,OAAO,CAAC,GAAG,EAAE,CAAC,CAAC,CAAA;gBACzG,CAAC;gBAED,uCAAuC;gBACvC,IAAI,OAAO,CAAC,MAAM,EAAE,OAAO,KAAK,IAAI,EAAE,CAAC;oBACrC,IAAI,CAAC,GAAG,CAAC,KAAK,CAAC,qEAAqE,EAAE,GAAG,EAAE,OAAO,CAAC,GAAG,CAAC,CAAA;oBACvG,MAAK;gBACP,CAAC;YACH,CAAC;QACH,CAAC;QAED,IAAI,eAAe,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;YAC/B,MAAM,IAAI,cAAc,CAAC,eAAe,EAAE,qCAAqC,GAAG,mBAAmB,CAAC,CAAA;QACxG,CAAC;aAAM,CAAC;YACN,MAAM,IAAI,KAAK,CAAC,qCAAqC,GAAG,mBAAmB,CAAC,CAAA;QAC9E,CAAC;IACH,CAAC;IAED,aAAa,CAAE,UAAgD,EAAE;QAC/D,OAAO,6BAA6B,CAAC;YACnC,MAAM,EAAE,IAAI,CAAC,MAAM;YACnB,OAAO,EAAE,IAAI,CAAC,OAAO;SACtB,EAAE;YACD,GAAG,OAAO;YACV,UAAU,EAAE,IAAI,CAAC,UAAU;YAC3B,aAAa,EAAE,IAAI,CAAC,aAAa;YACjC,oBAAoB,EAAE,IAAI,CAAC,oBAAoB;SAChD,CAAC,CAAA;IACJ,CAAC;CACF"}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import type { TransformRequestInit } from './trustless-gateway.js';
|
|
1
2
|
import type { Routing, BlockBroker } from '@helia/interface';
|
|
2
3
|
import type { ComponentLogger } from '@libp2p/interface';
|
|
3
4
|
import type { ProgressEvent } from 'progress-events';
|
|
@@ -19,6 +20,10 @@ export interface TrustlessGatewayBlockBrokerInit {
|
|
|
19
20
|
* @default false
|
|
20
21
|
*/
|
|
21
22
|
allowLocal?: boolean;
|
|
23
|
+
/**
|
|
24
|
+
* Provide a function that will be called before querying trustless-gateways. This lets you modify the fetch options to pass custom headers or other necessary things.
|
|
25
|
+
*/
|
|
26
|
+
transformRequestInit?: TransformRequestInit;
|
|
22
27
|
}
|
|
23
28
|
export interface TrustlessGatewayBlockBrokerComponents {
|
|
24
29
|
routing: Routing;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/trustless-gateway/index.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,OAAO,EAAE,WAAW,EAAE,MAAM,kBAAkB,CAAA;AAC5D,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,mBAAmB,CAAA;AACxD,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAA;AAEpD,eAAO,MAAM,sBAAsB,QAAQ,CAAA;AAC3C,eAAO,MAAM,mBAAmB,QAAQ,CAAA;AAExC,MAAM,MAAM,sCAAsC,GAChD,aAAa,CAAC,mCAAmC,EAAE,GAAG,CAAC,CAAA;AAEzD,MAAM,WAAW,+BAA+B;IAC9C;;;;;OAKG;IACH,aAAa,CAAC,EAAE,OAAO,CAAA;IAEvB;;;;;OAKG;IACH,UAAU,CAAC,EAAE,OAAO,CAAA;
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/trustless-gateway/index.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,wBAAwB,CAAA;AAClE,OAAO,KAAK,EAAE,OAAO,EAAE,WAAW,EAAE,MAAM,kBAAkB,CAAA;AAC5D,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,mBAAmB,CAAA;AACxD,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAA;AAEpD,eAAO,MAAM,sBAAsB,QAAQ,CAAA;AAC3C,eAAO,MAAM,mBAAmB,QAAQ,CAAA;AAExC,MAAM,MAAM,sCAAsC,GAChD,aAAa,CAAC,mCAAmC,EAAE,GAAG,CAAC,CAAA;AAEzD,MAAM,WAAW,+BAA+B;IAC9C;;;;;OAKG;IACH,aAAa,CAAC,EAAE,OAAO,CAAA;IAEvB;;;;;OAKG;IACH,UAAU,CAAC,EAAE,OAAO,CAAA;IACpB;;OAEG;IACH,oBAAoB,CAAC,EAAE,oBAAoB,CAAA;CAC5C;AAED,MAAM,WAAW,qCAAqC;IACpD,OAAO,EAAE,OAAO,CAAA;IAChB,MAAM,EAAE,eAAe,CAAA;CACxB;AAED,wBAAgB,gBAAgB,CAAE,IAAI,GAAE,+BAAoC,GAAG,CAAC,UAAU,EAAE,qCAAqC,KAAK,WAAW,CAAC,sCAAsC,CAAC,CAExL"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/trustless-gateway/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,2BAA2B,EAAE,MAAM,aAAa,CAAA;
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/trustless-gateway/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,2BAA2B,EAAE,MAAM,aAAa,CAAA;AAMzD,MAAM,CAAC,MAAM,sBAAsB,GAAG,KAAK,CAAA;AAC3C,MAAM,CAAC,MAAM,mBAAmB,GAAG,KAAK,CAAA;AAgCxC,MAAM,UAAU,gBAAgB,CAAE,OAAwC,EAAE;IAC1E,OAAO,CAAC,UAAU,EAAE,EAAE,CAAC,IAAI,2BAA2B,CAAC,UAAU,EAAE,IAAI,CAAC,CAAA;AAC1E,CAAC"}
|
|
@@ -14,6 +14,7 @@ declare class TrustlessGatewaySession extends AbstractSession<TrustlessGateway,
|
|
|
14
14
|
private readonly routing;
|
|
15
15
|
private readonly allowInsecure;
|
|
16
16
|
private readonly allowLocal;
|
|
17
|
+
private readonly transformRequestInit?;
|
|
17
18
|
constructor(components: TrustlessGatewaySessionComponents, init: CreateTrustlessGatewaySessionOptions);
|
|
18
19
|
queryProvider(cid: CID, provider: TrustlessGateway, options: BlockRetrievalOptions): Promise<Uint8Array>;
|
|
19
20
|
findNewProviders(cid: CID, options?: AbortOptions): AsyncGenerator<TrustlessGateway>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"session.d.ts","sourceRoot":"","sources":["../../../src/trustless-gateway/session.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,MAAM,cAAc,CAAA;AAG9C,OAAO,KAAK,EAAE,oCAAoC,EAAE,MAAM,aAAa,CAAA;AACvE,OAAO,KAAK,EAAE,sCAAsC,EAAE,MAAM,YAAY,CAAA;AACxE,OAAO,KAAK,
|
|
1
|
+
{"version":3,"file":"session.d.ts","sourceRoot":"","sources":["../../../src/trustless-gateway/session.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,MAAM,cAAc,CAAA;AAG9C,OAAO,KAAK,EAAE,oCAAoC,EAAE,MAAM,aAAa,CAAA;AACvE,OAAO,KAAK,EAAE,sCAAsC,EAAE,MAAM,YAAY,CAAA;AACxE,OAAO,KAAK,EAAwB,gBAAgB,EAAE,MAAM,wBAAwB,CAAA;AACpF,OAAO,KAAK,EAAE,qBAAqB,EAAE,OAAO,EAAE,MAAM,kBAAkB,CAAA;AACtE,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,mBAAmB,CAAA;AACxD,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,iBAAiB,CAAA;AACnD,OAAO,KAAK,EAAE,GAAG,EAAE,MAAM,kBAAkB,CAAA;AAE3C,MAAM,WAAW,iCAAiC;IAChD,MAAM,EAAE,eAAe,CAAA;IACvB,OAAO,EAAE,OAAO,CAAA;CACjB;AAED,cAAM,uBAAwB,SAAQ,eAAe,CAAC,gBAAgB,EAAE,sCAAsC,CAAC;IAC7G,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAS;IACjC,OAAO,CAAC,QAAQ,CAAC,aAAa,CAAS;IACvC,OAAO,CAAC,QAAQ,CAAC,UAAU,CAAS;IACpC,OAAO,CAAC,QAAQ,CAAC,oBAAoB,CAAC,CAAsB;gBAE/C,UAAU,EAAE,iCAAiC,EAAE,IAAI,EAAE,oCAAoC;IAYhG,aAAa,CAAE,GAAG,EAAE,GAAG,EAAE,QAAQ,EAAE,gBAAgB,EAAE,OAAO,EAAE,qBAAqB,GAAG,OAAO,CAAC,UAAU,CAAC;IAWvG,gBAAgB,CAAE,GAAG,EAAE,GAAG,EAAE,OAAO,GAAE,YAAiB,GAAG,cAAc,CAAC,gBAAgB,CAAC;IAIjG,aAAa,CAAE,QAAQ,EAAE,gBAAgB,GAAG,UAAU,GAAG,MAAM;IAI/D,MAAM,CAAE,SAAS,EAAE,gBAAgB,EAAE,SAAS,EAAE,gBAAgB,GAAG,OAAO;CAG3E;AAED,wBAAgB,6BAA6B,CAAE,UAAU,EAAE,iCAAiC,EAAE,IAAI,EAAE,oCAAoC,GAAG,uBAAuB,CAEjK"}
|
|
@@ -5,6 +5,7 @@ class TrustlessGatewaySession extends AbstractSession {
|
|
|
5
5
|
routing;
|
|
6
6
|
allowInsecure;
|
|
7
7
|
allowLocal;
|
|
8
|
+
transformRequestInit;
|
|
8
9
|
constructor(components, init) {
|
|
9
10
|
super(components, {
|
|
10
11
|
...init,
|
|
@@ -13,6 +14,7 @@ class TrustlessGatewaySession extends AbstractSession {
|
|
|
13
14
|
this.routing = components.routing;
|
|
14
15
|
this.allowInsecure = init.allowInsecure ?? DEFAULT_ALLOW_INSECURE;
|
|
15
16
|
this.allowLocal = init.allowLocal ?? DEFAULT_ALLOW_LOCAL;
|
|
17
|
+
this.transformRequestInit = init.transformRequestInit;
|
|
16
18
|
}
|
|
17
19
|
async queryProvider(cid, provider, options) {
|
|
18
20
|
this.log('fetching BLOCK for %c from %s', cid, provider.url);
|
|
@@ -22,7 +24,7 @@ class TrustlessGatewaySession extends AbstractSession {
|
|
|
22
24
|
return block;
|
|
23
25
|
}
|
|
24
26
|
async *findNewProviders(cid, options = {}) {
|
|
25
|
-
yield* findHttpGatewayProviders(cid, this.routing, this.logger, this.allowInsecure, this.allowLocal, options);
|
|
27
|
+
yield* findHttpGatewayProviders(cid, this.routing, this.logger, this.allowInsecure, this.allowLocal, { ...options, transformRequestInit: this.transformRequestInit });
|
|
26
28
|
}
|
|
27
29
|
toEvictionKey(provider) {
|
|
28
30
|
return provider.url.toString();
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"session.js","sourceRoot":"","sources":["../../../src/trustless-gateway/session.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,MAAM,cAAc,CAAA;AAC9C,OAAO,EAAE,wBAAwB,EAAE,MAAM,YAAY,CAAA;AACrD,OAAO,EAAE,sBAAsB,EAAE,mBAAmB,EAAE,MAAM,YAAY,CAAA;AAcxE,MAAM,uBAAwB,SAAQ,eAAyE;IAC5F,OAAO,CAAS;IAChB,aAAa,CAAS;IACtB,UAAU,CAAS;
|
|
1
|
+
{"version":3,"file":"session.js","sourceRoot":"","sources":["../../../src/trustless-gateway/session.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,MAAM,cAAc,CAAA;AAC9C,OAAO,EAAE,wBAAwB,EAAE,MAAM,YAAY,CAAA;AACrD,OAAO,EAAE,sBAAsB,EAAE,mBAAmB,EAAE,MAAM,YAAY,CAAA;AAcxE,MAAM,uBAAwB,SAAQ,eAAyE;IAC5F,OAAO,CAAS;IAChB,aAAa,CAAS;IACtB,UAAU,CAAS;IACnB,oBAAoB,CAAuB;IAE5D,YAAa,UAA6C,EAAE,IAA0C;QACpG,KAAK,CAAC,UAAU,EAAE;YAChB,GAAG,IAAI;YACP,IAAI,EAAE,iCAAiC;SACxC,CAAC,CAAA;QAEF,IAAI,CAAC,OAAO,GAAG,UAAU,CAAC,OAAO,CAAA;QACjC,IAAI,CAAC,aAAa,GAAG,IAAI,CAAC,aAAa,IAAI,sBAAsB,CAAA;QACjE,IAAI,CAAC,UAAU,GAAG,IAAI,CAAC,UAAU,IAAI,mBAAmB,CAAA;QACxD,IAAI,CAAC,oBAAoB,GAAG,IAAI,CAAC,oBAAoB,CAAA;IACvD,CAAC;IAED,KAAK,CAAC,aAAa,CAAE,GAAQ,EAAE,QAA0B,EAAE,OAA8B;QACvF,IAAI,CAAC,GAAG,CAAC,+BAA+B,EAAE,GAAG,EAAE,QAAQ,CAAC,GAAG,CAAC,CAAA;QAE5D,MAAM,KAAK,GAAG,MAAM,QAAQ,CAAC,WAAW,CAAC,GAAG,EAAE,OAAO,CAAC,MAAM,CAAC,CAAA;QAC7D,IAAI,CAAC,GAAG,CAAC,KAAK,CAAC,0BAA0B,EAAE,GAAG,EAAE,QAAQ,CAAC,GAAG,CAAC,CAAA;QAE7D,MAAM,OAAO,CAAC,UAAU,EAAE,CAAC,KAAK,CAAC,CAAA;QAEjC,OAAO,KAAK,CAAA;IACd,CAAC;IAED,KAAK,CAAC,CAAE,gBAAgB,CAAE,GAAQ,EAAE,UAAwB,EAAE;QAC5D,KAAM,CAAC,CAAC,wBAAwB,CAAC,GAAG,EAAE,IAAI,CAAC,OAAO,EAAE,IAAI,CAAC,MAAM,EAAE,IAAI,CAAC,aAAa,EAAE,IAAI,CAAC,UAAU,EAAE,EAAE,GAAG,OAAO,EAAE,oBAAoB,EAAE,IAAI,CAAC,oBAAoB,EAAE,CAAC,CAAA;IACxK,CAAC;IAED,aAAa,CAAE,QAA0B;QACvC,OAAO,QAAQ,CAAC,GAAG,CAAC,QAAQ,EAAE,CAAA;IAChC,CAAC;IAED,MAAM,CAAE,SAA2B,EAAE,SAA2B;QAC9D,OAAO,SAAS,CAAC,GAAG,CAAC,QAAQ,EAAE,KAAK,SAAS,CAAC,GAAG,CAAC,QAAQ,EAAE,CAAA;IAC9D,CAAC;CACF;AAED,MAAM,UAAU,6BAA6B,CAAE,UAA6C,EAAE,IAA0C;IACtI,OAAO,IAAI,uBAAuB,CAAC,UAAU,EAAE,IAAI,CAAC,CAAA;AACtD,CAAC"}
|
|
@@ -7,6 +7,13 @@ export interface TrustlessGatewayStats {
|
|
|
7
7
|
successes: number;
|
|
8
8
|
pendingResponses?: number;
|
|
9
9
|
}
|
|
10
|
+
export interface TransformRequestInit {
|
|
11
|
+
(defaultReqInit: RequestInit): Promise<RequestInit> | RequestInit;
|
|
12
|
+
}
|
|
13
|
+
export interface TrustlessGatewayComponents {
|
|
14
|
+
logger: ComponentLogger;
|
|
15
|
+
transformRequestInit?: TransformRequestInit;
|
|
16
|
+
}
|
|
10
17
|
/**
|
|
11
18
|
* A `TrustlessGateway` keeps track of the number of attempts, errors, and
|
|
12
19
|
* successes for a given gateway url so that we can prioritize gateways that
|
|
@@ -17,7 +24,8 @@ export declare class TrustlessGateway {
|
|
|
17
24
|
#private;
|
|
18
25
|
readonly url: URL;
|
|
19
26
|
private readonly log;
|
|
20
|
-
|
|
27
|
+
private readonly transformRequestInit?;
|
|
28
|
+
constructor(url: URL | string, { logger, transformRequestInit }: TrustlessGatewayComponents);
|
|
21
29
|
/**
|
|
22
30
|
* Fetch a raw block from `this.url` following the specification defined at
|
|
23
31
|
* https://specs.ipfs.tech/http-gateways/trustless-gateway/
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"trustless-gateway.d.ts","sourceRoot":"","sources":["../../../src/trustless-gateway/trustless-gateway.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,eAAe,EAAU,MAAM,mBAAmB,CAAA;AAChE,OAAO,KAAK,EAAE,GAAG,EAAE,MAAM,kBAAkB,CAAA;AAE3C,MAAM,WAAW,qBAAqB;IACpC,QAAQ,EAAE,MAAM,CAAA;IAChB,MAAM,EAAE,MAAM,CAAA;IACd,aAAa,EAAE,MAAM,CAAA;IACrB,SAAS,EAAE,MAAM,CAAA;IACjB,gBAAgB,CAAC,EAAE,MAAM,CAAA;CAC1B;AAED;;;;;GAKG;AACH,qBAAa,gBAAgB;;IAC3B,SAAgB,GAAG,EAAE,GAAG,CAAA;IAoCxB,OAAO,CAAC,QAAQ,CAAC,GAAG,CAAQ;
|
|
1
|
+
{"version":3,"file":"trustless-gateway.d.ts","sourceRoot":"","sources":["../../../src/trustless-gateway/trustless-gateway.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,eAAe,EAAU,MAAM,mBAAmB,CAAA;AAChE,OAAO,KAAK,EAAE,GAAG,EAAE,MAAM,kBAAkB,CAAA;AAE3C,MAAM,WAAW,qBAAqB;IACpC,QAAQ,EAAE,MAAM,CAAA;IAChB,MAAM,EAAE,MAAM,CAAA;IACd,aAAa,EAAE,MAAM,CAAA;IACrB,SAAS,EAAE,MAAM,CAAA;IACjB,gBAAgB,CAAC,EAAE,MAAM,CAAA;CAC1B;AAED,MAAM,WAAW,oBAAoB;IACnC,CAAC,cAAc,EAAE,WAAW,GAAG,OAAO,CAAC,WAAW,CAAC,GAAG,WAAW,CAAA;CAClE;AAED,MAAM,WAAW,0BAA0B;IACzC,MAAM,EAAE,eAAe,CAAA;IACvB,oBAAoB,CAAC,EAAE,oBAAoB,CAAA;CAC5C;AAED;;;;;GAKG;AACH,qBAAa,gBAAgB;;IAC3B,SAAgB,GAAG,EAAE,GAAG,CAAA;IAoCxB,OAAO,CAAC,QAAQ,CAAC,GAAG,CAAQ;IAC5B,OAAO,CAAC,QAAQ,CAAC,oBAAoB,CAAC,CAAsB;gBAE/C,GAAG,EAAE,GAAG,GAAG,MAAM,EAAE,EAAE,MAAM,EAAE,oBAAoB,EAAE,EAAE,0BAA0B;IAoB5F;;;OAGG;IACG,WAAW,CAAE,GAAG,EAAE,GAAG,EAAE,MAAM,CAAC,EAAE,WAAW,GAAG,OAAO,CAAC,UAAU,CAAC;IA6DvE;;;;;;;OAOG;IACH,WAAW,IAAK,MAAM;IAyBtB;;OAEG;IACH,sBAAsB,IAAK,IAAI;IAI/B,QAAQ,IAAK,qBAAqB;CASnC"}
|
|
@@ -38,8 +38,10 @@ export class TrustlessGateway {
|
|
|
38
38
|
*/
|
|
39
39
|
#pendingResponses = new Map();
|
|
40
40
|
log;
|
|
41
|
-
|
|
41
|
+
transformRequestInit;
|
|
42
|
+
constructor(url, { logger, transformRequestInit }) {
|
|
42
43
|
this.url = url instanceof URL ? url : new URL(url);
|
|
44
|
+
this.transformRequestInit = transformRequestInit;
|
|
43
45
|
this.log = logger.forComponent(`helia:trustless-gateway-block-broker:${this.url.hostname}`);
|
|
44
46
|
}
|
|
45
47
|
/**
|
|
@@ -79,13 +81,15 @@ export class TrustlessGateway {
|
|
|
79
81
|
let pendingResponse = this.#pendingResponses.get(blockId);
|
|
80
82
|
if (pendingResponse == null) {
|
|
81
83
|
this.#attempts++;
|
|
82
|
-
|
|
84
|
+
const defaultReqInit = {
|
|
83
85
|
signal: innerController.signal,
|
|
84
86
|
headers: {
|
|
85
87
|
Accept: 'application/vnd.ipld.raw'
|
|
86
88
|
},
|
|
87
89
|
cache: 'force-cache'
|
|
88
|
-
}
|
|
90
|
+
};
|
|
91
|
+
const reqInit = this.transformRequestInit != null ? await this.transformRequestInit(defaultReqInit) : defaultReqInit;
|
|
92
|
+
pendingResponse = fetch(gwUrl.toString(), reqInit).then(async (res) => {
|
|
89
93
|
this.log('GET %s %d', gwUrl, res.status);
|
|
90
94
|
if (!res.ok) {
|
|
91
95
|
this.#errors++;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"trustless-gateway.js","sourceRoot":"","sources":["../../../src/trustless-gateway/trustless-gateway.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,2BAA2B,CAAA;
|
|
1
|
+
{"version":3,"file":"trustless-gateway.js","sourceRoot":"","sources":["../../../src/trustless-gateway/trustless-gateway.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,2BAA2B,CAAA;AAqBlD;;;;;GAKG;AACH,MAAM,OAAO,gBAAgB;IACX,GAAG,CAAK;IACxB;;;;;OAKG;IACH,SAAS,GAAG,CAAC,CAAA;IAEb;;;;;OAKG;IACH,OAAO,GAAG,CAAC,CAAA;IAEX;;;;OAIG;IACH,cAAc,GAAG,CAAC,CAAA;IAElB;;OAEG;IACH,UAAU,GAAG,CAAC,CAAA;IAEd;;;;OAIG;IACM,iBAAiB,GAAG,IAAI,GAAG,EAA+B,CAAA;IAElD,GAAG,CAAQ;IACX,oBAAoB,CAAuB;IAE5D,YAAa,GAAiB,EAAE,EAAE,MAAM,EAAE,oBAAoB,EAA8B;QAC1F,IAAI,CAAC,GAAG,GAAG,GAAG,YAAY,GAAG,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,IAAI,GAAG,CAAC,GAAG,CAAC,CAAA;QAClD,IAAI,CAAC,oBAAoB,GAAG,oBAAoB,CAAA;QAChD,IAAI,CAAC,GAAG,GAAG,MAAM,CAAC,YAAY,CAAC,wCAAwC,IAAI,CAAC,GAAG,CAAC,QAAQ,EAAE,CAAC,CAAA;IAC7F,CAAC;IAED;;;;;;;;OAQG;IACH,cAAc,CAAE,GAAQ;QACtB,MAAM,cAAc,GAAG,GAAG,CAAC,SAAS,CAAC,KAAK,CAAA;QAC1C,OAAO,MAAM,CAAC,MAAM,CAAC,cAAc,CAAC,CAAA;IACtC,CAAC;IAED;;;OAGG;IACH,KAAK,CAAC,WAAW,CAAE,GAAQ,EAAE,MAAoB;QAC/C,MAAM,KAAK,GAAG,IAAI,GAAG,CAAC,IAAI,CAAC,GAAG,CAAC,QAAQ,EAAE,CAAC,CAAA;QAC1C,KAAK,CAAC,QAAQ,GAAG,SAAS,GAAG,CAAC,QAAQ,EAAE,EAAE,CAAA;QAE1C,6EAA6E;QAC7E,0BAA0B;QAC1B,KAAK,CAAC,MAAM,GAAG,aAAa,CAAA;QAE5B,IAAI,MAAM,EAAE,OAAO,KAAK,IAAI,EAAE,CAAC;YAC7B,MAAM,IAAI,KAAK,CAAC,qCAAqC,GAAG,iBAAiB,IAAI,CAAC,GAAG,6BAA6B,CAAC,CAAA;QACjH,CAAC;QAED,MAAM,OAAO,GAAG,IAAI,CAAC,cAAc,CAAC,GAAG,CAAC,CAAA;QAExC,6DAA6D;QAC7D,MAAM,eAAe,GAAG,IAAI,eAAe,EAAE,CAAA;QAC7C,MAAM,gBAAgB,GAAG,GAAS,EAAE;YAClC,eAAe,CAAC,KAAK,EAAE,CAAA;QACzB,CAAC,CAAA;QACD,MAAM,EAAE,gBAAgB,CAAC,OAAO,EAAE,gBAAgB,CAAC,CAAA;QAEnD,IAAI,CAAC;YACH,IAAI,eAAe,GAAoC,IAAI,CAAC,iBAAiB,CAAC,GAAG,CAAC,OAAO,CAAC,CAAA;YAC1F,IAAI,eAAe,IAAI,IAAI,EAAE,CAAC;gBAC5B,IAAI,CAAC,SAAS,EAAE,CAAA;gBAChB,MAAM,cAAc,GAAgB;oBAClC,MAAM,EAAE,eAAe,CAAC,MAAM;oBAC9B,OAAO,EAAE;wBACP,MAAM,EAAE,0BAA0B;qBACnC;oBACD,KAAK,EAAE,aAAa;iBACrB,CAAA;gBAED,MAAM,OAAO,GAAgB,IAAI,CAAC,oBAAoB,IAAI,IAAI,CAAC,CAAC,CAAC,MAAM,IAAI,CAAC,oBAAoB,CAAC,cAAc,CAAC,CAAC,CAAC,CAAC,cAAc,CAAA;gBAEjI,eAAe,GAAG,KAAK,CAAC,KAAK,CAAC,QAAQ,EAAE,EAAE,OAAO,CAAC,CAAC,IAAI,CAAC,KAAK,EAAE,GAAG,EAAE,EAAE;oBACpE,IAAI,CAAC,GAAG,CAAC,WAAW,EAAE,KAAK,EAAE,GAAG,CAAC,MAAM,CAAC,CAAA;oBACxC,IAAI,CAAC,GAAG,CAAC,EAAE,EAAE,CAAC;wBACZ,IAAI,CAAC,OAAO,EAAE,CAAA;wBACd,MAAM,IAAI,KAAK,CAAC,qCAAqC,GAAG,iBAAiB,IAAI,CAAC,GAAG,EAAE,CAAC,CAAA;oBACtF,CAAC;oBACD,IAAI,CAAC,UAAU,EAAE,CAAA;oBACjB,OAAO,IAAI,UAAU,CAAC,MAAM,GAAG,CAAC,WAAW,EAAE,CAAC,CAAA;gBAChD,CAAC,CAAC,CAAA;gBACF,IAAI,CAAC,iBAAiB,CAAC,GAAG,CAAC,OAAO,EAAE,eAAe,CAAC,CAAA;YACtD,CAAC;YACD,OAAO,MAAM,eAAe,CAAA;QAC9B,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,qEAAqE;YACrE,yCAAyC;YACzC,IAAI,MAAM,EAAE,OAAO,KAAK,IAAI,EAAE,CAAC;gBAC7B,MAAM,IAAI,KAAK,CAAC,8BAA8B,GAAG,iBAAiB,IAAI,CAAC,GAAG,cAAc,CAAC,CAAA;YAC3F,CAAC;YACD,IAAI,CAAC,OAAO,EAAE,CAAA;YACd,MAAM,IAAI,KAAK,CAAC,qCAAqC,GAAG,EAAE,CAAC,CAAA;QAC7D,CAAC;gBAAS,CAAC;YACT,MAAM,EAAE,mBAAmB,CAAC,OAAO,EAAE,gBAAgB,CAAC,CAAA;YACtD,IAAI,CAAC,iBAAiB,CAAC,MAAM,CAAC,OAAO,CAAC,CAAA;QACxC,CAAC;IACH,CAAC;IAED;;;;;;;OAOG;IACH,WAAW;QACT;;;WAGG;QACH,IAAI,IAAI,CAAC,SAAS,KAAK,CAAC,EAAE,CAAC;YACzB,OAAO,CAAC,CAAA;QACV,CAAC;QAED,IAAI,IAAI,CAAC,cAAc,GAAG,CAAC,EAAE,CAAC;YAC5B,wCAAwC;YACxC,OAAO,CAAC,QAAQ,CAAA;QAClB,CAAC;QAED;;;;;;;WAOG;QACH,OAAO,IAAI,CAAC,UAAU,GAAG,CAAC,IAAI,CAAC,SAAS,GAAG,CAAC,IAAI,CAAC,OAAO,GAAG,CAAC,CAAC,CAAC,CAAA;IAChE,CAAC;IAED;;OAEG;IACH,sBAAsB;QACpB,IAAI,CAAC,cAAc,EAAE,CAAA;IACvB,CAAC;IAED,QAAQ;QACN,OAAO;YACL,QAAQ,EAAE,IAAI,CAAC,SAAS;YACxB,MAAM,EAAE,IAAI,CAAC,OAAO;YACpB,aAAa,EAAE,IAAI,CAAC,cAAc;YAClC,SAAS,EAAE,IAAI,CAAC,UAAU;YAC1B,gBAAgB,EAAE,IAAI,CAAC,iBAAiB,CAAC,IAAI;SAC9C,CAAA;IACH,CAAC;CACF"}
|
|
@@ -1,8 +1,11 @@
|
|
|
1
|
-
import { TrustlessGateway } from './trustless-gateway.js';
|
|
1
|
+
import { TrustlessGateway, type TransformRequestInit } from './trustless-gateway.js';
|
|
2
2
|
import type { Routing } from '@helia/interface';
|
|
3
3
|
import type { ComponentLogger } from '@libp2p/interface';
|
|
4
4
|
import type { AbortOptions, Multiaddr } from '@multiformats/multiaddr';
|
|
5
5
|
import type { CID } from 'multiformats/cid';
|
|
6
6
|
export declare function filterNonHTTPMultiaddrs(multiaddrs: Multiaddr[], allowInsecure: boolean, allowLocal: boolean): Multiaddr[];
|
|
7
|
-
export
|
|
7
|
+
export interface FindHttpGatewayProvidersOptions extends AbortOptions {
|
|
8
|
+
transformRequestInit?: TransformRequestInit;
|
|
9
|
+
}
|
|
10
|
+
export declare function findHttpGatewayProviders(cid: CID, routing: Routing, logger: ComponentLogger, allowInsecure: boolean, allowLocal: boolean, options?: FindHttpGatewayProvidersOptions): AsyncGenerator<TrustlessGateway>;
|
|
8
11
|
//# sourceMappingURL=utils.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"utils.d.ts","sourceRoot":"","sources":["../../../src/trustless-gateway/utils.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,gBAAgB,EAAE,MAAM,wBAAwB,CAAA;
|
|
1
|
+
{"version":3,"file":"utils.d.ts","sourceRoot":"","sources":["../../../src/trustless-gateway/utils.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,gBAAgB,EAAE,KAAK,oBAAoB,EAAE,MAAM,wBAAwB,CAAA;AACpF,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,kBAAkB,CAAA;AAC/C,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,mBAAmB,CAAA;AACxD,OAAO,KAAK,EAAE,YAAY,EAAE,SAAS,EAAE,MAAM,yBAAyB,CAAA;AACtE,OAAO,KAAK,EAAE,GAAG,EAAE,MAAM,kBAAkB,CAAA;AAE3C,wBAAgB,uBAAuB,CAAE,UAAU,EAAE,SAAS,EAAE,EAAE,aAAa,EAAE,OAAO,EAAE,UAAU,EAAE,OAAO,GAAG,SAAS,EAAE,CAwB1H;AAED,MAAM,WAAW,+BAAgC,SAAQ,YAAY;IACnE,oBAAoB,CAAC,EAAE,oBAAoB,CAAA;CAC5C;AAED,wBAAwB,wBAAwB,CAAE,GAAG,EAAE,GAAG,EAAE,OAAO,EAAE,OAAO,EAAE,MAAM,EAAE,eAAe,EAAE,aAAa,EAAE,OAAO,EAAE,UAAU,EAAE,OAAO,EAAE,OAAO,GAAE,+BAAoC,GAAG,cAAc,CAAC,gBAAgB,CAAC,CAiBnO"}
|
|
@@ -23,7 +23,7 @@ export function filterNonHTTPMultiaddrs(multiaddrs, allowInsecure, allowLocal) {
|
|
|
23
23
|
return false;
|
|
24
24
|
});
|
|
25
25
|
}
|
|
26
|
-
export async function* findHttpGatewayProviders(cid, routing, logger, allowInsecure, allowLocal, options) {
|
|
26
|
+
export async function* findHttpGatewayProviders(cid, routing, logger, allowInsecure, allowLocal, options = {}) {
|
|
27
27
|
for await (const provider of routing.findProviders(cid, options)) {
|
|
28
28
|
// require http(s) addresses
|
|
29
29
|
const httpAddresses = filterNonHTTPMultiaddrs(provider.multiaddrs, allowInsecure, allowLocal);
|
|
@@ -35,7 +35,7 @@ export async function* findHttpGatewayProviders(cid, routing, logger, allowInsec
|
|
|
35
35
|
// /ip4/x.x.x.x/tcp/31337/https
|
|
36
36
|
// etc
|
|
37
37
|
const uri = multiaddrToUri(httpAddresses[0]);
|
|
38
|
-
yield new TrustlessGateway(uri, logger);
|
|
38
|
+
yield new TrustlessGateway(uri, { logger, transformRequestInit: options.transformRequestInit });
|
|
39
39
|
}
|
|
40
40
|
}
|
|
41
41
|
//# sourceMappingURL=utils.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"utils.js","sourceRoot":"","sources":["../../../src/trustless-gateway/utils.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,0BAA0B,CAAA;AACtD,OAAO,EAAE,GAAG,EAAE,IAAI,EAAE,KAAK,EAAE,MAAM,iCAAiC,CAAA;AAClE,OAAO,EAAE,cAAc,EAAE,MAAM,gCAAgC,CAAA;AAC/D,OAAO,EAAE,gBAAgB,
|
|
1
|
+
{"version":3,"file":"utils.js","sourceRoot":"","sources":["../../../src/trustless-gateway/utils.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,0BAA0B,CAAA;AACtD,OAAO,EAAE,GAAG,EAAE,IAAI,EAAE,KAAK,EAAE,MAAM,iCAAiC,CAAA;AAClE,OAAO,EAAE,cAAc,EAAE,MAAM,gCAAgC,CAAA;AAC/D,OAAO,EAAE,gBAAgB,EAA6B,MAAM,wBAAwB,CAAA;AAMpF,MAAM,UAAU,uBAAuB,CAAE,UAAuB,EAAE,aAAsB,EAAE,UAAmB;IAC3G,OAAO,UAAU,CAAC,MAAM,CAAC,EAAE,CAAC,EAAE;QAC5B,IAAI,KAAK,CAAC,OAAO,CAAC,EAAE,CAAC,IAAI,CAAC,aAAa,IAAI,IAAI,CAAC,OAAO,CAAC,EAAE,CAAC,CAAC,EAAE,CAAC;YAC7D,IAAI,UAAU,EAAE,CAAC;gBACf,OAAO,IAAI,CAAA;YACb,CAAC;YAED,IAAI,GAAG,CAAC,OAAO,CAAC,EAAE,CAAC,EAAE,CAAC;gBACpB,OAAO,IAAI,CAAA;YACb,CAAC;YAED,OAAO,WAAW,CAAC,EAAE,CAAC,SAAS,EAAE,CAAC,IAAI,CAAC,KAAK,KAAK,CAAA;QACnD,CAAC;QAED,gJAAgJ;QAChJ,IAAI,CAAC,aAAa,IAAI,UAAU,EAAE,CAAC;YACjC,MAAM,EAAE,IAAI,EAAE,GAAG,EAAE,CAAC,SAAS,EAAE,CAAA;YAC/B,IAAI,IAAI,KAAK,WAAW,IAAI,IAAI,KAAK,WAAW,IAAI,IAAI,CAAC,QAAQ,CAAC,YAAY,CAAC,EAAE,CAAC;gBAChF,OAAO,IAAI,CAAA;YACb,CAAC;QACH,CAAC;QAED,OAAO,KAAK,CAAA;IACd,CAAC,CAAC,CAAA;AACJ,CAAC;AAMD,MAAM,CAAC,KAAK,SAAU,CAAC,CAAC,wBAAwB,CAAE,GAAQ,EAAE,OAAgB,EAAE,MAAuB,EAAE,aAAsB,EAAE,UAAmB,EAAE,UAA2C,EAAE;IAC/L,IAAI,KAAK,EAAE,MAAM,QAAQ,IAAI,OAAO,CAAC,aAAa,CAAC,GAAG,EAAE,OAAO,CAAC,EAAE,CAAC;QACjE,4BAA4B;QAC5B,MAAM,aAAa,GAAG,uBAAuB,CAAC,QAAQ,CAAC,UAAU,EAAE,aAAa,EAAE,UAAU,CAAC,CAAA;QAE7F,IAAI,aAAa,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;YAC/B,SAAQ;QACV,CAAC;QAED,sBAAsB;QACtB,8BAA8B;QAC9B,+BAA+B;QAC/B,MAAM;QACN,MAAM,GAAG,GAAG,cAAc,CAAC,aAAa,CAAC,CAAC,CAAC,CAAC,CAAA;QAE5C,MAAM,IAAI,gBAAgB,CAAC,GAAG,EAAE,EAAE,MAAM,EAAE,oBAAoB,EAAE,OAAO,CAAC,oBAAoB,EAAE,CAAC,CAAA;IACjG,CAAC;AACH,CAAC"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@helia/block-brokers",
|
|
3
|
-
"version": "4.0
|
|
3
|
+
"version": "4.1.0-313e2c1",
|
|
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",
|
|
@@ -54,9 +54,9 @@
|
|
|
54
54
|
"test:electron-main": "aegir test -t electron-main"
|
|
55
55
|
},
|
|
56
56
|
"dependencies": {
|
|
57
|
-
"@helia/bitswap": "
|
|
58
|
-
"@helia/interface": "
|
|
59
|
-
"@helia/utils": "
|
|
57
|
+
"@helia/bitswap": "2.0.5-313e2c1",
|
|
58
|
+
"@helia/interface": "5.2.1-313e2c1",
|
|
59
|
+
"@helia/utils": "1.2.2-313e2c1",
|
|
60
60
|
"@libp2p/interface": "^2.2.1",
|
|
61
61
|
"@libp2p/utils": "^6.2.1",
|
|
62
62
|
"@multiformats/multiaddr": "^12.3.3",
|
|
@@ -74,7 +74,7 @@
|
|
|
74
74
|
"@multiformats/uri-to-multiaddr": "^8.0.0",
|
|
75
75
|
"@types/polka": "^0.5.7",
|
|
76
76
|
"@types/sinon": "^17.0.3",
|
|
77
|
-
"aegir": "^45.
|
|
77
|
+
"aegir": "^45.1.1",
|
|
78
78
|
"cors": "^2.8.5",
|
|
79
79
|
"polka": "^0.5.2",
|
|
80
80
|
"sinon": "^19.0.2",
|
|
@@ -2,6 +2,7 @@ import { createTrustlessGatewaySession } from './session.js'
|
|
|
2
2
|
import { findHttpGatewayProviders } from './utils.js'
|
|
3
3
|
import { DEFAULT_ALLOW_INSECURE, DEFAULT_ALLOW_LOCAL } from './index.js'
|
|
4
4
|
import type { TrustlessGatewayBlockBrokerInit, TrustlessGatewayBlockBrokerComponents, TrustlessGatewayGetBlockProgressEvents } from './index.js'
|
|
5
|
+
import type { TransformRequestInit } from './trustless-gateway.js'
|
|
5
6
|
import type { Routing, BlockRetrievalOptions, BlockBroker, CreateSessionOptions } from '@helia/interface'
|
|
6
7
|
import type { ComponentLogger, Logger } from '@libp2p/interface'
|
|
7
8
|
import type { CID } from 'multiformats/cid'
|
|
@@ -22,6 +23,10 @@ export interface CreateTrustlessGatewaySessionOptions extends CreateSessionOptio
|
|
|
22
23
|
* @default false
|
|
23
24
|
*/
|
|
24
25
|
allowLocal?: boolean
|
|
26
|
+
/**
|
|
27
|
+
* Provide a function that will be called before querying trustless-gateways. This lets you modify the fetch options to pass custom headers or other necessary things.
|
|
28
|
+
*/
|
|
29
|
+
transformRequestInit?: TransformRequestInit
|
|
25
30
|
}
|
|
26
31
|
|
|
27
32
|
/**
|
|
@@ -31,6 +36,7 @@ export interface CreateTrustlessGatewaySessionOptions extends CreateSessionOptio
|
|
|
31
36
|
export class TrustlessGatewayBlockBroker implements BlockBroker<TrustlessGatewayGetBlockProgressEvents> {
|
|
32
37
|
private readonly allowInsecure: boolean
|
|
33
38
|
private readonly allowLocal: boolean
|
|
39
|
+
private readonly transformRequestInit?: TransformRequestInit
|
|
34
40
|
private readonly routing: Routing
|
|
35
41
|
private readonly log: Logger
|
|
36
42
|
private readonly logger: ComponentLogger
|
|
@@ -41,12 +47,13 @@ export class TrustlessGatewayBlockBroker implements BlockBroker<TrustlessGateway
|
|
|
41
47
|
this.routing = components.routing
|
|
42
48
|
this.allowInsecure = init.allowInsecure ?? DEFAULT_ALLOW_INSECURE
|
|
43
49
|
this.allowLocal = init.allowLocal ?? DEFAULT_ALLOW_LOCAL
|
|
50
|
+
this.transformRequestInit = init.transformRequestInit
|
|
44
51
|
}
|
|
45
52
|
|
|
46
53
|
async retrieve (cid: CID, options: BlockRetrievalOptions<TrustlessGatewayGetBlockProgressEvents> = {}): Promise<Uint8Array> {
|
|
47
54
|
const aggregateErrors: Error[] = []
|
|
48
55
|
|
|
49
|
-
for await (const gateway of findHttpGatewayProviders(cid, this.routing, this.logger, this.allowInsecure, this.allowLocal, options)) {
|
|
56
|
+
for await (const gateway of findHttpGatewayProviders(cid, this.routing, this.logger, this.allowInsecure, this.allowLocal, { ...options, transformRequestInit: this.transformRequestInit })) {
|
|
50
57
|
this.log('getting block for %c from %s', cid, gateway.url)
|
|
51
58
|
|
|
52
59
|
try {
|
|
@@ -93,7 +100,8 @@ export class TrustlessGatewayBlockBroker implements BlockBroker<TrustlessGateway
|
|
|
93
100
|
}, {
|
|
94
101
|
...options,
|
|
95
102
|
allowLocal: this.allowLocal,
|
|
96
|
-
allowInsecure: this.allowInsecure
|
|
103
|
+
allowInsecure: this.allowInsecure,
|
|
104
|
+
transformRequestInit: this.transformRequestInit
|
|
97
105
|
})
|
|
98
106
|
}
|
|
99
107
|
}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { TrustlessGatewayBlockBroker } from './broker.js'
|
|
2
|
+
import type { TransformRequestInit } from './trustless-gateway.js'
|
|
2
3
|
import type { Routing, BlockBroker } from '@helia/interface'
|
|
3
4
|
import type { ComponentLogger } from '@libp2p/interface'
|
|
4
5
|
import type { ProgressEvent } from 'progress-events'
|
|
@@ -25,6 +26,10 @@ export interface TrustlessGatewayBlockBrokerInit {
|
|
|
25
26
|
* @default false
|
|
26
27
|
*/
|
|
27
28
|
allowLocal?: boolean
|
|
29
|
+
/**
|
|
30
|
+
* Provide a function that will be called before querying trustless-gateways. This lets you modify the fetch options to pass custom headers or other necessary things.
|
|
31
|
+
*/
|
|
32
|
+
transformRequestInit?: TransformRequestInit
|
|
28
33
|
}
|
|
29
34
|
|
|
30
35
|
export interface TrustlessGatewayBlockBrokerComponents {
|
|
@@ -3,7 +3,7 @@ import { findHttpGatewayProviders } from './utils.js'
|
|
|
3
3
|
import { DEFAULT_ALLOW_INSECURE, DEFAULT_ALLOW_LOCAL } from './index.js'
|
|
4
4
|
import type { CreateTrustlessGatewaySessionOptions } from './broker.js'
|
|
5
5
|
import type { TrustlessGatewayGetBlockProgressEvents } from './index.js'
|
|
6
|
-
import type { TrustlessGateway } from './trustless-gateway.js'
|
|
6
|
+
import type { TransformRequestInit, TrustlessGateway } from './trustless-gateway.js'
|
|
7
7
|
import type { BlockRetrievalOptions, Routing } from '@helia/interface'
|
|
8
8
|
import type { ComponentLogger } from '@libp2p/interface'
|
|
9
9
|
import type { AbortOptions } from 'interface-store'
|
|
@@ -18,6 +18,7 @@ class TrustlessGatewaySession extends AbstractSession<TrustlessGateway, Trustles
|
|
|
18
18
|
private readonly routing: Routing
|
|
19
19
|
private readonly allowInsecure: boolean
|
|
20
20
|
private readonly allowLocal: boolean
|
|
21
|
+
private readonly transformRequestInit?: TransformRequestInit
|
|
21
22
|
|
|
22
23
|
constructor (components: TrustlessGatewaySessionComponents, init: CreateTrustlessGatewaySessionOptions) {
|
|
23
24
|
super(components, {
|
|
@@ -28,6 +29,7 @@ class TrustlessGatewaySession extends AbstractSession<TrustlessGateway, Trustles
|
|
|
28
29
|
this.routing = components.routing
|
|
29
30
|
this.allowInsecure = init.allowInsecure ?? DEFAULT_ALLOW_INSECURE
|
|
30
31
|
this.allowLocal = init.allowLocal ?? DEFAULT_ALLOW_LOCAL
|
|
32
|
+
this.transformRequestInit = init.transformRequestInit
|
|
31
33
|
}
|
|
32
34
|
|
|
33
35
|
async queryProvider (cid: CID, provider: TrustlessGateway, options: BlockRetrievalOptions): Promise<Uint8Array> {
|
|
@@ -42,7 +44,7 @@ class TrustlessGatewaySession extends AbstractSession<TrustlessGateway, Trustles
|
|
|
42
44
|
}
|
|
43
45
|
|
|
44
46
|
async * findNewProviders (cid: CID, options: AbortOptions = {}): AsyncGenerator<TrustlessGateway> {
|
|
45
|
-
yield * findHttpGatewayProviders(cid, this.routing, this.logger, this.allowInsecure, this.allowLocal, options)
|
|
47
|
+
yield * findHttpGatewayProviders(cid, this.routing, this.logger, this.allowInsecure, this.allowLocal, { ...options, transformRequestInit: this.transformRequestInit })
|
|
46
48
|
}
|
|
47
49
|
|
|
48
50
|
toEvictionKey (provider: TrustlessGateway): Uint8Array | string {
|
|
@@ -10,6 +10,15 @@ export interface TrustlessGatewayStats {
|
|
|
10
10
|
pendingResponses?: number
|
|
11
11
|
}
|
|
12
12
|
|
|
13
|
+
export interface TransformRequestInit {
|
|
14
|
+
(defaultReqInit: RequestInit): Promise<RequestInit> | RequestInit
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export interface TrustlessGatewayComponents {
|
|
18
|
+
logger: ComponentLogger
|
|
19
|
+
transformRequestInit?: TransformRequestInit
|
|
20
|
+
}
|
|
21
|
+
|
|
13
22
|
/**
|
|
14
23
|
* A `TrustlessGateway` keeps track of the number of attempts, errors, and
|
|
15
24
|
* successes for a given gateway url so that we can prioritize gateways that
|
|
@@ -54,9 +63,11 @@ export class TrustlessGateway {
|
|
|
54
63
|
readonly #pendingResponses = new Map<string, Promise<Uint8Array>>()
|
|
55
64
|
|
|
56
65
|
private readonly log: Logger
|
|
66
|
+
private readonly transformRequestInit?: TransformRequestInit
|
|
57
67
|
|
|
58
|
-
constructor (url: URL | string, logger:
|
|
68
|
+
constructor (url: URL | string, { logger, transformRequestInit }: TrustlessGatewayComponents) {
|
|
59
69
|
this.url = url instanceof URL ? url : new URL(url)
|
|
70
|
+
this.transformRequestInit = transformRequestInit
|
|
60
71
|
this.log = logger.forComponent(`helia:trustless-gateway-block-broker:${this.url.hostname}`)
|
|
61
72
|
}
|
|
62
73
|
|
|
@@ -103,13 +114,17 @@ export class TrustlessGateway {
|
|
|
103
114
|
let pendingResponse: Promise<Uint8Array> | undefined = this.#pendingResponses.get(blockId)
|
|
104
115
|
if (pendingResponse == null) {
|
|
105
116
|
this.#attempts++
|
|
106
|
-
|
|
117
|
+
const defaultReqInit: RequestInit = {
|
|
107
118
|
signal: innerController.signal,
|
|
108
119
|
headers: {
|
|
109
120
|
Accept: 'application/vnd.ipld.raw'
|
|
110
121
|
},
|
|
111
122
|
cache: 'force-cache'
|
|
112
|
-
}
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
const reqInit: RequestInit = this.transformRequestInit != null ? await this.transformRequestInit(defaultReqInit) : defaultReqInit
|
|
126
|
+
|
|
127
|
+
pendingResponse = fetch(gwUrl.toString(), reqInit).then(async (res) => {
|
|
113
128
|
this.log('GET %s %d', gwUrl, res.status)
|
|
114
129
|
if (!res.ok) {
|
|
115
130
|
this.#errors++
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { isPrivateIp } from '@libp2p/utils/private-ip'
|
|
2
2
|
import { DNS, HTTP, HTTPS } from '@multiformats/multiaddr-matcher'
|
|
3
3
|
import { multiaddrToUri } from '@multiformats/multiaddr-to-uri'
|
|
4
|
-
import { TrustlessGateway } from './trustless-gateway.js'
|
|
4
|
+
import { TrustlessGateway, type TransformRequestInit } from './trustless-gateway.js'
|
|
5
5
|
import type { Routing } from '@helia/interface'
|
|
6
6
|
import type { ComponentLogger } from '@libp2p/interface'
|
|
7
7
|
import type { AbortOptions, Multiaddr } from '@multiformats/multiaddr'
|
|
@@ -33,7 +33,11 @@ export function filterNonHTTPMultiaddrs (multiaddrs: Multiaddr[], allowInsecure:
|
|
|
33
33
|
})
|
|
34
34
|
}
|
|
35
35
|
|
|
36
|
-
export
|
|
36
|
+
export interface FindHttpGatewayProvidersOptions extends AbortOptions {
|
|
37
|
+
transformRequestInit?: TransformRequestInit
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export async function * findHttpGatewayProviders (cid: CID, routing: Routing, logger: ComponentLogger, allowInsecure: boolean, allowLocal: boolean, options: FindHttpGatewayProvidersOptions = {}): AsyncGenerator<TrustlessGateway> {
|
|
37
41
|
for await (const provider of routing.findProviders(cid, options)) {
|
|
38
42
|
// require http(s) addresses
|
|
39
43
|
const httpAddresses = filterNonHTTPMultiaddrs(provider.multiaddrs, allowInsecure, allowLocal)
|
|
@@ -48,6 +52,6 @@ export async function * findHttpGatewayProviders (cid: CID, routing: Routing, lo
|
|
|
48
52
|
// etc
|
|
49
53
|
const uri = multiaddrToUri(httpAddresses[0])
|
|
50
54
|
|
|
51
|
-
yield new TrustlessGateway(uri, logger)
|
|
55
|
+
yield new TrustlessGateway(uri, { logger, transformRequestInit: options.transformRequestInit })
|
|
52
56
|
}
|
|
53
57
|
}
|
package/dist/typedoc-urls.json
DELETED
|
@@ -1,9 +0,0 @@
|
|
|
1
|
-
{
|
|
2
|
-
"BitswapBlockBrokerComponents": "https://ipfs.github.io/helia/interfaces/_helia_block_brokers.BitswapBlockBrokerComponents.html",
|
|
3
|
-
"BitswapBlockBrokerInit": "https://ipfs.github.io/helia/interfaces/_helia_block_brokers.BitswapBlockBrokerInit.html",
|
|
4
|
-
"TrustlessGatewayBlockBrokerComponents": "https://ipfs.github.io/helia/interfaces/_helia_block_brokers.TrustlessGatewayBlockBrokerComponents.html",
|
|
5
|
-
"TrustlessGatewayBlockBrokerInit": "https://ipfs.github.io/helia/interfaces/_helia_block_brokers.TrustlessGatewayBlockBrokerInit.html",
|
|
6
|
-
"TrustlessGatewayGetBlockProgressEvents": "https://ipfs.github.io/helia/types/_helia_block_brokers.TrustlessGatewayGetBlockProgressEvents.html",
|
|
7
|
-
"bitswap": "https://ipfs.github.io/helia/functions/_helia_block_brokers.bitswap.html",
|
|
8
|
-
"trustlessGateway": "https://ipfs.github.io/helia/functions/_helia_block_brokers.trustlessGateway.html"
|
|
9
|
-
}
|