@helia/bitswap 0.0.0-e582c63 → 1.0.0
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 +6 -1
- package/dist/src/bitswap.d.ts +3 -2
- package/dist/src/bitswap.d.ts.map +1 -1
- package/dist/src/bitswap.js +7 -14
- package/dist/src/bitswap.js.map +1 -1
- package/dist/src/index.d.ts +2 -38
- package/dist/src/index.d.ts.map +1 -1
- package/dist/src/index.js.map +1 -1
- package/dist/src/network.d.ts +3 -4
- package/dist/src/network.d.ts.map +1 -1
- package/dist/src/network.js +28 -50
- package/dist/src/network.js.map +1 -1
- package/dist/src/peer-want-lists/index.d.ts +2 -2
- package/dist/src/peer-want-lists/index.d.ts.map +1 -1
- package/dist/src/peer-want-lists/index.js +2 -2
- package/dist/src/peer-want-lists/index.js.map +1 -1
- package/dist/src/session.d.ts +13 -8
- package/dist/src/session.d.ts.map +1 -1
- package/dist/src/session.js +25 -88
- package/dist/src/session.js.map +1 -1
- package/dist/src/stats.d.ts +2 -2
- package/dist/src/stats.d.ts.map +1 -1
- package/dist/src/stats.js +4 -4
- package/dist/src/stats.js.map +1 -1
- package/dist/src/want-list.d.ts +20 -23
- package/dist/src/want-list.d.ts.map +1 -1
- package/dist/src/want-list.js +130 -130
- package/dist/src/want-list.js.map +1 -1
- package/dist/typedoc-urls.json +20 -0
- package/package.json +3 -4
- package/src/bitswap.ts +9 -16
- package/src/index.ts +2 -43
- package/src/network.ts +32 -59
- package/src/peer-want-lists/index.ts +4 -4
- package/src/session.ts +31 -120
- package/src/stats.ts +6 -6
- package/src/want-list.ts +197 -209
package/dist/index.min.js
CHANGED
|
@@ -1,3 +1,8 @@
|
|
|
1
1
|
(function (root, factory) {(typeof module === 'object' && module.exports) ? module.exports = factory() : root.HeliaBitswap = factory()}(typeof self !== 'undefined' ? self : this, function () {
|
|
2
|
-
"use strict";var HeliaBitswap=(()=>{var Qs=Object.create;var ct=Object.defineProperty;var Xs=Object.getOwnPropertyDescriptor;var Js=Object.getOwnPropertyNames;var Ks=Object.getPrototypeOf,Ys=Object.prototype.hasOwnProperty;var lt=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),H=(r,e)=>{for(var t in e)ct(r,t,{get:e[t],enumerable:!0})},xn=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Js(e))!Ys.call(r,s)&&s!==t&&ct(r,s,{get:()=>e[s],enumerable:!(n=Xs(e,s))||n.enumerable});return r};var En=(r,e,t)=>(t=r!=null?Qs(Ks(r)):{},xn(e||!r||!r.__esModule?ct(t,"default",{value:r,enumerable:!0}):t,r)),Zs=r=>xn(ct({},"__esModule",{value:!0}),r);var ps=lt((ph,ds)=>{var Ue=1e3,Be=Ue*60,Oe=Be*60,me=Oe*24,Vo=me*7,Ho=me*365.25;ds.exports=function(r,e){e=e||{};var t=typeof r;if(t==="string"&&r.length>0)return Wo(r);if(t==="number"&&isFinite(r))return e.long?$o(r):qo(r);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(r))};function Wo(r){if(r=String(r),!(r.length>100)){var e=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(r);if(e){var t=parseFloat(e[1]),n=(e[2]||"ms").toLowerCase();switch(n){case"years":case"year":case"yrs":case"yr":case"y":return t*Ho;case"weeks":case"week":case"w":return t*Vo;case"days":case"day":case"d":return t*me;case"hours":case"hour":case"hrs":case"hr":case"h":return t*Oe;case"minutes":case"minute":case"mins":case"min":case"m":return t*Be;case"seconds":case"second":case"secs":case"sec":case"s":return t*Ue;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return t;default:return}}}}function qo(r){var e=Math.abs(r);return e>=me?Math.round(r/me)+"d":e>=Oe?Math.round(r/Oe)+"h":e>=Be?Math.round(r/Be)+"m":e>=Ue?Math.round(r/Ue)+"s":r+"ms"}function $o(r){var e=Math.abs(r);return e>=me?Rt(r,e,me,"day"):e>=Oe?Rt(r,e,Oe,"hour"):e>=Be?Rt(r,e,Be,"minute"):e>=Ue?Rt(r,e,Ue,"second"):r+" ms"}function Rt(r,e,t,n){var s=e>=t*1.5;return Math.round(r/t)+" "+n+(s?"s":"")}});var gs=lt((mh,ms)=>{function Go(r){t.debug=t,t.default=t,t.coerce=c,t.disable=i,t.enable=s,t.enabled=o,t.humanize=ps(),t.destroy=h,Object.keys(r).forEach(l=>{t[l]=r[l]}),t.names=[],t.skips=[],t.formatters={};function e(l){let u=0;for(let f=0;f<l.length;f++)u=(u<<5)-u+l.charCodeAt(f),u|=0;return t.colors[Math.abs(u)%t.colors.length]}t.selectColor=e;function t(l){let u,f=null,S,p;function m(...d){if(!m.enabled)return;let y=m,k=Number(new Date),C=k-(u||k);y.diff=C,y.prev=u,y.curr=k,u=k,d[0]=t.coerce(d[0]),typeof d[0]!="string"&&d.unshift("%O");let _=0;d[0]=d[0].replace(/%([a-zA-Z%])/g,(Q,V)=>{if(Q==="%%")return"%";_++;let X=t.formatters[V];if(typeof X=="function"){let Le=d[_];Q=X.call(y,Le),d.splice(_,1),_--}return Q}),t.formatArgs.call(y,d),(y.log||t.log).apply(y,d)}return m.namespace=l,m.useColors=t.useColors(),m.color=t.selectColor(l),m.extend=n,m.destroy=t.destroy,Object.defineProperty(m,"enabled",{enumerable:!0,configurable:!1,get:()=>f!==null?f:(S!==t.namespaces&&(S=t.namespaces,p=t.enabled(l)),p),set:d=>{f=d}}),typeof t.init=="function"&&t.init(m),m}function n(l,u){let f=t(this.namespace+(typeof u>"u"?":":u)+l);return f.log=this.log,f}function s(l){t.save(l),t.namespaces=l,t.names=[],t.skips=[];let u,f=(typeof l=="string"?l:"").split(/[\s,]+/),S=f.length;for(u=0;u<S;u++)f[u]&&(l=f[u].replace(/\*/g,".*?"),l[0]==="-"?t.skips.push(new RegExp("^"+l.slice(1)+"$")):t.names.push(new RegExp("^"+l+"$")))}function i(){let l=[...t.names.map(a),...t.skips.map(a).map(u=>"-"+u)].join(",");return t.enable(""),l}function o(l){if(l[l.length-1]==="*")return!0;let u,f;for(u=0,f=t.skips.length;u<f;u++)if(t.skips[u].test(l))return!1;for(u=0,f=t.names.length;u<f;u++)if(t.names[u].test(l))return!0;return!1}function a(l){return l.toString().substring(2,l.toString().length-2).replace(/\.\*\?$/,"*")}function c(l){return l instanceof Error?l.stack||l.message:l}function h(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return t.enable(t.load()),t}ms.exports=Go});var ws=lt(($,Pt)=>{$.formatArgs=Qo;$.save=Xo;$.load=Jo;$.useColors=jo;$.storage=Ko();$.destroy=(()=>{let r=!1;return()=>{r||(r=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})();$.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function jo(){return typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs)?!0:typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)?!1:typeof document<"u"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&parseInt(RegExp.$1,10)>=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function Qo(r){if(r[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+r[0]+(this.useColors?"%c ":" ")+"+"+Pt.exports.humanize(this.diff),!this.useColors)return;let e="color: "+this.color;r.splice(1,0,e,"color: inherit");let t=0,n=0;r[0].replace(/%[a-zA-Z%]/g,s=>{s!=="%%"&&(t++,s==="%c"&&(n=t))}),r.splice(n,0,e)}$.log=console.debug||console.log||(()=>{});function Xo(r){try{r?$.storage.setItem("debug",r):$.storage.removeItem("debug")}catch{}}function Jo(){let r;try{r=$.storage.getItem("debug")}catch{}return!r&&typeof process<"u"&&"env"in process&&(r=process.env.DEBUG),r}function Ko(){try{return localStorage}catch{}}Pt.exports=gs()($);var{formatters:Yo}=Pt.exports;Yo.j=function(r){try{return JSON.stringify(r)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}});var As=lt((Ih,Ss)=>{"use strict";function vs(r,e){for(let t in e)Object.defineProperty(r,t,{value:e[t],enumerable:!0,configurable:!0});return r}function ta(r,e,t){if(!r||typeof r=="string")throw new TypeError("Please pass an Error to err-code");t||(t={}),typeof e=="object"&&(t=e,e=""),e&&(t.code=e);try{return vs(r,t)}catch{t.message=r.message,t.stack=r.stack;let s=function(){};return s.prototype=Object.create(Object.getPrototypeOf(r)),vs(new s,t)}}Ss.exports=ta});var Ha={};H(Ha,{createBitswap:()=>Va});var vn=Symbol.for("@libp2p/peer-id");var ee=class r extends Error{code;type;constructor(e="The operation was aborted"){super(e),this.name="AbortError",this.code=r.code,this.type=r.type}static code="ABORT_ERR";static type="aborted"},B=class extends Error{code;props;constructor(e,t,n){super(e),this.code=t,this.name=n?.name??"CodeError",this.props=n??{}}};var te=(r,...e)=>{try{[...e]}catch{}};var Ie=class extends EventTarget{#e=new Map;constructor(){super(),te(1/0,this)}listenerCount(e){let t=this.#e.get(e);return t==null?0:t.length}addEventListener(e,t,n){super.addEventListener(e,t,n);let s=this.#e.get(e);s==null&&(s=[],this.#e.set(e,s)),s.push({callback:t,once:(n!==!0&&n!==!1&&n?.once)??!1})}removeEventListener(e,t,n){super.removeEventListener(e.toString(),t??null,n);let s=this.#e.get(e);s!=null&&(s=s.filter(({callback:i})=>i!==t),this.#e.set(e,s))}dispatchEvent(e){let t=super.dispatchEvent(e),n=this.#e.get(e.type);return n==null||(n=n.filter(({once:s})=>!s),this.#e.set(e.type,n)),t}safeDispatchEvent(e,t={}){return this.dispatchEvent(new ei(e,t))}},nr=class extends Event{detail;constructor(e,t){super(e,t),this.detail=t?.detail}},ei=globalThis.CustomEvent??nr;function ut(r){let e=new globalThis.AbortController;function t(){e.abort();for(let i of r)i?.removeEventListener!=null&&i.removeEventListener("abort",t)}for(let i of r){if(i?.aborted===!0){t();break}i?.addEventListener!=null&&i.addEventListener("abort",t)}function n(){for(let i of r)i?.removeEventListener!=null&&i.removeEventListener("abort",t)}let s=e.signal;return s.clear=n,s}function P(){let r={};return r.promise=new Promise((e,t)=>{r.resolve=e,r.reject=t}),r}var ht=class{buffer;mask;top;btm;next;constructor(e){if(!(e>0)||e-1&e)throw new Error("Max size for a FixedFIFO should be a power of two");this.buffer=new Array(e),this.mask=e-1,this.top=0,this.btm=0,this.next=null}push(e){return this.buffer[this.top]!==void 0?!1:(this.buffer[this.top]=e,this.top=this.top+1&this.mask,!0)}shift(){let e=this.buffer[this.btm];if(e!==void 0)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,e}isEmpty(){return this.buffer[this.btm]===void 0}},ke=class{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new ht(this.hwm),this.tail=this.head,this.size=0}calculateSize(e){return e?.byteLength!=null?e.byteLength:1}push(e){if(e?.value!=null&&(this.size+=this.calculateSize(e.value)),!this.head.push(e)){let t=this.head;this.head=t.next=new ht(2*this.head.buffer.length),this.head.push(e)}}shift(){let e=this.tail.shift();if(e===void 0&&this.tail.next!=null){let t=this.tail.next;this.tail.next=null,this.tail=t,e=this.tail.shift()}return e?.value!=null&&(this.size-=this.calculateSize(e.value)),e}isEmpty(){return this.head.isEmpty()}};var sr=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}};function Ce(r={}){return ti(t=>{let n=t.shift();if(n==null)return{done:!0};if(n.error!=null)throw n.error;return{done:n.done===!0,value:n.value}},r)}function ti(r,e){e=e??{};let t=e.onEnd,n=new ke,s,i,o,a=P(),c=async()=>{try{return n.isEmpty()?o?{done:!0}:await new Promise((d,y)=>{i=k=>{i=null,n.push(k);try{d(r(n))}catch(C){y(C)}return s}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=P()})}},h=d=>i!=null?i(d):(n.push(d),s),l=d=>(n=new ke,i!=null?i({error:d}):(n.push({error:d}),s)),u=d=>{if(o)return s;if(e?.objectMode!==!0&&d?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return h({done:!1,value:d})},f=d=>o?s:(o=!0,d!=null?l(d):h({done:!0})),S=()=>(n=new ke,f(),{done:!0}),p=d=>(f(d),{done:!0});if(s={[Symbol.asyncIterator](){return this},next:c,return:S,throw:p,push:u,end:f,get readableLength(){return n.size},onEmpty:async d=>{let y=d?.signal;if(y?.throwIfAborted(),n.isEmpty())return;let k,C;y!=null&&(k=new Promise((_,z)=>{C=()=>{z(new sr)},y.addEventListener("abort",C)}));try{await Promise.race([a.promise,k])}finally{C!=null&&y!=null&&y?.removeEventListener("abort",C)}}},t==null)return s;let m=s;return s={[Symbol.asyncIterator](){return this},next(){return m.next()},throw(d){return m.throw(d),t!=null&&(t(d),t=void 0),{done:!0}},return(){return m.return(),t!=null&&(t(),t=void 0),{done:!0}},push:u,end(d){return m.end(d),t!=null&&(t(d),t=void 0),s},get readableLength(){return m.readableLength},onEmpty:d=>m.onEmpty(d)},s}var ir=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.name="AbortError",this.code=t??"ABORT_ERR"}};async function De(r,e,t,n){let s=new ir(n?.errorMessage,n?.errorCode);return t?.aborted===!0?Promise.reject(s):new Promise((i,o)=>{let a=h=>{try{if(n?.filter?.(h)===!1)return}catch(l){r.removeEventListener(e,a),t?.removeEventListener("abort",c),o(l);return}r.removeEventListener(e,a),t?.removeEventListener("abort",c),i(h)},c=()=>{r.removeEventListener(e,a),t?.removeEventListener("abort",c),o(s)};r.addEventListener(e,a),t?.addEventListener("abort",c)})}var ft=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.name="AbortError",this.code=t??"ABORT_ERR"}};async function dt(r,e,t){if(e==null)return r;if(e.aborted)return Promise.reject(new ft(t?.errorMessage,t?.errorCode));let n,s=new ft(t?.errorMessage,t?.errorCode);try{return await Promise.race([r,new Promise((i,o)=>{n=()=>{o(s)},e.addEventListener("abort",n)})])}finally{n!=null&&e.removeEventListener("abort",n)}}var pt=class{deferred;signal;where;constructor(e,t){this.signal=t,this.deferred=P(),this.where=e,this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(new ee)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function ri(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var mt=class{id;fn;options;priority;recipients;status;timeline;controller;constructor(e,t,n=0){this.id=ri(),this.status="queued",this.fn=e,this.priority=n,this.options=t,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,te(1/0,this.controller.signal),this.onAbort=this.onAbort.bind(this)}abort(e){this.controller.abort(e)}onAbort(){this.recipients.reduce((t,n)=>t&&n.signal?.aborted===!0,!0)&&this.controller.abort(new ee)}async join(e={}){let t=new pt(new Error("where").stack,e.signal);return this.recipients.push(t),e.signal?.addEventListener("abort",this.onAbort),t.deferred.promise}async run(){this.status="running",this.timeline.started=Date.now();try{this.controller.signal.throwIfAborted();let e=await dt(this.fn({...this.options??{},signal:this.controller.signal}),this.controller.signal);this.recipients.forEach(t=>{t.deferred.resolve(e)}),this.status="complete"}catch(e){this.recipients.forEach(t=>{t.deferred.reject(e)}),this.status="errored"}finally{this.timeline.finished=Date.now(),this.cleanup()}}cleanup(){this.recipients.forEach(e=>{e.signal?.removeEventListener("abort",this.onAbort)})}};function ni(r,e,t){let n=0,s=r.length;for(;s>0;){let i=Math.trunc(s/2),o=n+i;t(r[o],e)<=0?(n=++o,s-=i+1):s=i}return n}var gt=class extends Ie{concurrency;queue;pending;constructor(e={}){super(),this.concurrency=e.concurrency??Number.POSITIVE_INFINITY,this.pending=0,e.metricName!=null&&e.metrics?.registerMetricGroup(e.metricName,{calculate:()=>({size:this.queue.length,running:this.pending,queued:this.queue.length-this.pending})}),this.queue=[]}tryToStartAnother(){if(this.size===0)return queueMicrotask(()=>{this.safeDispatchEvent("empty")}),this.running===0&&queueMicrotask(()=>{this.safeDispatchEvent("idle")}),!1;if(this.pending<this.concurrency){let e;for(let t of this.queue)if(t.status==="queued"){e=t;break}return e==null?!1:(this.safeDispatchEvent("active"),this.pending++,e.run().finally(()=>{for(let t=0;t<this.queue.length;t++)if(this.queue[t]===e){this.queue.splice(t,1);break}this.pending--,this.tryToStartAnother(),this.safeDispatchEvent("next")}),!0)}return!1}enqueue(e){if(this.queue[this.size-1]?.priority>=e.priority){this.queue.push(e);return}let t=ni(this.queue,e,(n,s)=>s.priority-n.priority);this.queue.splice(t,0,e)}async add(e,t){t?.signal?.throwIfAborted();let n=new mt(e,t,t?.priority),s=n.join(t).then(i=>(this.safeDispatchEvent("completed",{detail:i}),i)).catch(i=>{throw this.safeDispatchEvent("error",{detail:i}),i});return this.enqueue(n),this.safeDispatchEvent("add"),this.tryToStartAnother(),s}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(e=>{e.abort(new ee)}),this.clear()}async onEmpty(e){this.size!==0&&await De(this,"empty",e?.signal)}async onSizeLessThan(e,t){this.size<e||await De(this,"next",t?.signal,{filter:()=>this.size<e})}async onIdle(e){this.pending===0&&this.size===0||await De(this,"idle",e?.signal)}get size(){return this.queue.length}get queued(){return this.queue.length-this.pending}get running(){return this.pending}async*toGenerator(e){e?.signal?.throwIfAborted();let t=Ce({objectMode:!0}),n=c=>{c!=null?this.abort():this.clear(),t.end(c)},s=c=>{c.detail!=null&&t.push(c.detail)},i=c=>{n(c.detail)},o=()=>{n()},a=()=>{n(new B("Queue aborted","ERR_QUEUE_ABORTED"))};this.addEventListener("completed",s),this.addEventListener("error",i),this.addEventListener("idle",o),e?.signal?.addEventListener("abort",a);try{yield*t}finally{this.removeEventListener("completed",s),this.removeEventListener("error",i),this.removeEventListener("idle",o),e?.signal?.removeEventListener("abort",a),n()}}};var Te=class extends gt{has(e){return this.find(e)!=null}find(e){return this.queue.find(t=>e.equals(t.options.peerId))}};var wt=class{index=0;input="";new(e){return this.index=0,this.input=e,this}readAtomically(e){let t=this.index,n=e();return n===void 0&&(this.index=t),n}parseWith(e){let t=e();if(this.index===this.input.length)return t}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(e){return this.readAtomically(()=>{let t=this.readChar();if(t===e)return t})}readSeparator(e,t,n){return this.readAtomically(()=>{if(!(t>0&&this.readGivenChar(e)===void 0))return n()})}readNumber(e,t,n,s){return this.readAtomically(()=>{let i=0,o=0,a=this.peekChar();if(a===void 0)return;let c=a==="0",h=2**(8*s)-1;for(;;){let l=this.readAtomically(()=>{let u=this.readChar();if(u===void 0)return;let f=Number.parseInt(u,e);if(!Number.isNaN(f))return f});if(l===void 0)break;if(i*=e,i+=l,i>h||(o+=1,t!==void 0&&o>t))return}if(o!==0)return!n&&c&&o>1?void 0:i})}readIPv4Addr(){return this.readAtomically(()=>{let e=new Uint8Array(4);for(let t=0;t<e.length;t++){let n=this.readSeparator(".",t,()=>this.readNumber(10,3,!1,1));if(n===void 0)return;e[t]=n}return e})}readIPv6Addr(){let e=t=>{for(let n=0;n<t.length/2;n++){let s=n*2;if(n<t.length-3){let o=this.readSeparator(":",n,()=>this.readIPv4Addr());if(o!==void 0)return t[s]=o[0],t[s+1]=o[1],t[s+2]=o[2],t[s+3]=o[3],[s+4,!0]}let i=this.readSeparator(":",n,()=>this.readNumber(16,4,!0,2));if(i===void 0)return[s,!1];t[s]=i>>8,t[s+1]=i&255}return[t.length,!1]};return this.readAtomically(()=>{let t=new Uint8Array(16),[n,s]=e(t);if(n===16)return t;if(s||this.readGivenChar(":")===void 0||this.readGivenChar(":")===void 0)return;let i=new Uint8Array(14),o=16-(n+2),[a]=e(i.subarray(0,o));return t.set(i.subarray(0,a),16-a),t})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};var Sn=45,si=15,_e=new wt;function or(r){if(!(r.length>si))return _e.new(r).parseWith(()=>_e.readIPv4Addr())}function ar(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>Sn))return _e.new(r).parseWith(()=>_e.readIPv6Addr())}function bt(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>Sn))return _e.new(r).parseWith(()=>_e.readIPAddr())}function yt(r){return!!or(r)}function xt(r){return!!ar(r)}function Et(r){return!!bt(r)}var fr={};H(fr,{base58btc:()=>D,base58flickr:()=>ui});var kc=new Uint8Array(0);function An(r,e){if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return!1;return!0}function ne(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 Ln(r){return new TextEncoder().encode(r)}function In(r){return new TextDecoder().decode(r)}function ii(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),n=0;n<t.length;n++)t[n]=255;for(var s=0;s<r.length;s++){var i=r.charAt(s),o=i.charCodeAt(0);if(t[o]!==255)throw new TypeError(i+" is ambiguous");t[o]=s}var a=r.length,c=r.charAt(0),h=Math.log(a)/Math.log(256),l=Math.log(256)/Math.log(a);function u(p){if(p instanceof Uint8Array||(ArrayBuffer.isView(p)?p=new Uint8Array(p.buffer,p.byteOffset,p.byteLength):Array.isArray(p)&&(p=Uint8Array.from(p))),!(p instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(p.length===0)return"";for(var m=0,d=0,y=0,k=p.length;y!==k&&p[y]===0;)y++,m++;for(var C=(k-y)*l+1>>>0,_=new Uint8Array(C);y!==k;){for(var z=p[y],Q=0,V=C-1;(z!==0||Q<d)&&V!==-1;V--,Q++)z+=256*_[V]>>>0,_[V]=z%a>>>0,z=z/a>>>0;if(z!==0)throw new Error("Non-zero carry");d=Q,y++}for(var X=C-d;X!==C&&_[X]===0;)X++;for(var Le=c.repeat(m);X<C;++X)Le+=r.charAt(_[X]);return Le}function f(p){if(typeof p!="string")throw new TypeError("Expected String");if(p.length===0)return new Uint8Array;var m=0;if(p[m]!==" "){for(var d=0,y=0;p[m]===c;)d++,m++;for(var k=(p.length-m)*h+1>>>0,C=new Uint8Array(k);p[m];){var _=t[p.charCodeAt(m)];if(_===255)return;for(var z=0,Q=k-1;(_!==0||z<y)&&Q!==-1;Q--,z++)_+=a*C[Q]>>>0,C[Q]=_%256>>>0,_=_/256>>>0;if(_!==0)throw new Error("Non-zero carry");y=z,m++}if(p[m]!==" "){for(var V=k-y;V!==k&&C[V]===0;)V++;for(var X=new Uint8Array(d+(k-V)),Le=d;V!==k;)X[Le++]=C[V++];return X}}}function S(p){var m=f(p);if(m)return m;throw new Error(`Non-${e} character`)}return{encode:u,decodeUnsafe:f,decode:S}}var oi=ii,ai=oi,Cn=ai;var cr=class{name;prefix;baseEncode;constructor(e,t,n){this.name=e,this.prefix=t,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},lr=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,n){if(this.name=e,this.prefix=t,t.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=t.codePointAt(0),this.baseDecode=n}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return Dn(this,e)}},ur=class{decoders;constructor(e){this.decoders=e}or(e){return Dn(this,e)}decode(e){let t=e[0],n=this.decoders[t];if(n!=null)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function Dn(r,e){return new ur({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var hr=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,n,s){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=s,this.encoder=new cr(e,t,n),this.decoder=new lr(e,t,s)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function Re({name:r,prefix:e,encode:t,decode:n}){return new hr(r,e,t,n)}function oe({name:r,prefix:e,alphabet:t}){let{encode:n,decode:s}=Cn(t,r);return Re({prefix:e,name:r,encode:n,decode:i=>ne(s(i))})}function ci(r,e,t,n){let s={};for(let l=0;l<e.length;++l)s[e[l]]=l;let i=r.length;for(;r[i-1]==="=";)--i;let o=new Uint8Array(i*t/8|0),a=0,c=0,h=0;for(let l=0;l<i;++l){let u=s[r[l]];if(u===void 0)throw new SyntaxError(`Non-${n} character`);c=c<<t|u,a+=t,a>=8&&(a-=8,o[h++]=255&c>>a)}if(a>=t||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return o}function li(r,e,t){let n=e[e.length-1]==="=",s=(1<<t)-1,i="",o=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],o+=8;o>t;)o-=t,i+=e[s&a>>o];if(o!==0&&(i+=e[s&a<<t-o]),n)for(;i.length*t&7;)i+="=";return i}function A({name:r,prefix:e,bitsPerChar:t,alphabet:n}){return Re({prefix:e,name:r,encode(s){return li(s,n,t)},decode(s){return ci(s,n,t,r)}})}var D=oe({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),ui=oe({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var dr={};H(dr,{base32:()=>se,base32hex:()=>pi,base32hexpad:()=>gi,base32hexpadupper:()=>wi,base32hexupper:()=>mi,base32pad:()=>fi,base32padupper:()=>di,base32upper:()=>hi,base32z:()=>bi});var se=A({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),hi=A({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),fi=A({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),di=A({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),pi=A({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),mi=A({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),gi=A({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),wi=A({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),bi=A({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var yi=Rn,Tn=128,xi=127,Ei=~xi,vi=Math.pow(2,31);function Rn(r,e,t){e=e||[],t=t||0;for(var n=t;r>=vi;)e[t++]=r&255|Tn,r/=128;for(;r&Ei;)e[t++]=r&255|Tn,r>>>=7;return e[t]=r|0,Rn.bytes=t-n+1,e}var Si=pr,Ai=128,_n=127;function pr(r,n){var t=0,n=n||0,s=0,i=n,o,a=r.length;do{if(i>=a)throw pr.bytes=0,new RangeError("Could not decode varint");o=r[i++],t+=s<28?(o&_n)<<s:(o&_n)*Math.pow(2,s),s+=7}while(o>=Ai);return pr.bytes=i-n,t}var Li=Math.pow(2,7),Ii=Math.pow(2,14),ki=Math.pow(2,21),Ci=Math.pow(2,28),Di=Math.pow(2,35),Ti=Math.pow(2,42),_i=Math.pow(2,49),Ri=Math.pow(2,56),Pi=Math.pow(2,63),Ni=function(r){return r<Li?1:r<Ii?2:r<ki?3:r<Ci?4:r<Di?5:r<Ti?6:r<_i?7:r<Ri?8:r<Pi?9:10},Fi={encode:yi,decode:Si,encodingLength:Ni},Mi=Fi,We=Mi;function qe(r,e=0){return[We.decode(r,e),We.decode.bytes]}function Pe(r,e,t=0){return We.encode(r,e,t),e}function Ne(r){return We.encodingLength(r)}function ae(r,e){let t=e.byteLength,n=Ne(r),s=n+Ne(t),i=new Uint8Array(s+t);return Pe(r,i,0),Pe(t,i,n),i.set(e,s),new Fe(r,t,e,i)}function he(r){let e=ne(r),[t,n]=qe(e),[s,i]=qe(e.subarray(n)),o=e.subarray(n+i);if(o.byteLength!==s)throw new Error("Incorrect length");return new Fe(t,s,o,e)}function Pn(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&An(r.bytes,t.bytes)}}var Fe=class{code;size;digest;bytes;constructor(e,t,n,s){this.code=e,this.size=t,this.digest=n,this.bytes=s}};function Nn(r,e){let{bytes:t,version:n}=r;switch(n){case 0:return Bi(t,mr(r),e??D.encoder);default:return Oi(t,mr(r),e??se.encoder)}}var Fn=new WeakMap;function mr(r){let e=Fn.get(r);if(e==null){let t=new Map;return Fn.set(r,t),t}return e}var T=class r{code;version;multihash;bytes;"/";constructor(e,t,n,s){this.code=t,this.version=e,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:e,multihash:t}=this;if(e!==$e)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==zi)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return r.createV0(t)}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:e,digest:t}=this.multihash,n=ae(e,t);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(e){return r.equals(this,e)}static equals(e,t){let n=t;return n!=null&&e.code===n.code&&e.version===n.version&&Pn(e.multihash,n.multihash)}toString(e){return Nn(this,e)}toJSON(){return{"/":Nn(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(e){if(e==null)return null;let t=e;if(t instanceof r)return t;if(t["/"]!=null&&t["/"]===t.bytes||t.asCID===t){let{version:n,code:s,multihash:i,bytes:o}=t;return new r(n,s,i,o??Mn(n,s,i.bytes))}else if(t[Vi]===!0){let{version:n,multihash:s,code:i}=t,o=he(s);return r.create(n,i,o)}else return null}static create(e,t,n){if(typeof t!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(e){case 0:{if(t!==$e)throw new Error(`Version 0 CID must use dag-pb (code: ${$e}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let s=Mn(e,t,n.bytes);return new r(e,t,n,s)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,$e,e)}static createV1(e,t){return r.create(1,e,t)}static decode(e){let[t,n]=r.decodeFirst(e);if(n.length!==0)throw new Error("Incorrect length");return t}static decodeFirst(e){let t=r.inspectBytes(e),n=t.size-t.multihashSize,s=ne(e.subarray(n,n+t.multihashSize));if(s.byteLength!==t.multihashSize)throw new Error("Incorrect length");let i=s.subarray(t.multihashSize-t.digestSize),o=new Fe(t.multihashCode,t.digestSize,i,s);return[t.version===0?r.createV0(o):r.createV1(t.codec,o),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[u,f]=qe(e.subarray(t));return t+=f,u},s=n(),i=$e;if(s===18?(s=0,t=0):i=n(),s!==0&&s!==1)throw new RangeError(`Invalid CID version ${s}`);let o=t,a=n(),c=n(),h=t+c,l=h-o;return{version:s,codec:i,multihashCode:a,digestSize:c,multihashSize:l,size:h}}static parse(e,t){let[n,s]=Ui(e,t),i=r.decode(s);if(i.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return mr(i).set(n,e),i}};function Ui(r,e){switch(r[0]){case"Q":{let t=e??D;return[D.prefix,t.decode(`${D.prefix}${r}`)]}case D.prefix:{let t=e??D;return[D.prefix,t.decode(r)]}case se.prefix:{let t=e??se;return[se.prefix,t.decode(r)]}default:{if(e==null)throw Error("To parse non base32 or base58btc encoded CID multibase decoder must be provided");return[r[0],e.decode(r)]}}}function Bi(r,e,t){let{prefix:n}=t;if(n!==D.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let s=e.get(n);if(s==null){let i=t.encode(r).slice(1);return e.set(n,i),i}else return s}function Oi(r,e,t){let{prefix:n}=t,s=e.get(n);if(s==null){let i=t.encode(r);return e.set(n,i),i}else return s}var $e=112,zi=18;function Mn(r,e,t){let n=Ne(r),s=n+Ne(e),i=new Uint8Array(s+t.byteLength);return Pe(r,i,0),Pe(e,i,n),i.set(t,s),i}var Vi=Symbol.for("@ipld/js-cid/CID");function de(r,e){if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return!1;return!0}var gr={};H(gr,{base10:()=>Hi});var Hi=oe({prefix:"9",name:"base10",alphabet:"0123456789"});var wr={};H(wr,{base16:()=>Wi,base16upper:()=>qi});var Wi=A({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),qi=A({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var br={};H(br,{base2:()=>$i});var $i=A({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var yr={};H(yr,{base256emoji:()=>Ji});var Un=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}"),Gi=Un.reduce((r,e,t)=>(r[t]=e,r),[]),ji=Un.reduce((r,e,t)=>(r[e.codePointAt(0)]=t,r),[]);function Qi(r){return r.reduce((e,t)=>(e+=Gi[t],e),"")}function Xi(r){let e=[];for(let t of r){let n=ji[t.codePointAt(0)];if(n===void 0)throw new Error(`Non-base256emoji character: ${t}`);e.push(n)}return new Uint8Array(e)}var Ji=Re({prefix:"\u{1F680}",name:"base256emoji",encode:Qi,decode:Xi});var xr={};H(xr,{base36:()=>Ki,base36upper:()=>Yi});var Ki=oe({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Yi=oe({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var vr={};H(vr,{base64:()=>ce,base64pad:()=>Zi,base64url:()=>Er,base64urlpad:()=>eo});var ce=A({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Zi=A({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Er=A({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),eo=A({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var Sr={};H(Sr,{base8:()=>to});var to=A({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var Ar={};H(Ar,{identity:()=>ro});var ro=Re({prefix:"\0",name:"identity",encode:r=>In(r),decode:r=>Ln(r)});var Yc=new TextEncoder,Zc=new TextDecoder;var Lr={};H(Lr,{identity:()=>St});var Bn=0,io="identity",On=ne;function oo(r){return ae(Bn,On(r))}var St={code:Bn,name:io,encode:On,digest:oo};var Cr={};H(Cr,{sha256:()=>pe,sha512:()=>ao});function kr({name:r,code:e,encode:t}){return new Ir(r,e,t)}var Ir=class{name;code;encode;constructor(e,t,n){this.name=e,this.code=t,this.encode=n}digest(e){if(e instanceof Uint8Array){let t=this.encode(e);return t instanceof Uint8Array?ae(this.code,t):t.then(n=>ae(this.code,n))}else throw Error("Unknown type, must be binary type")}};function Vn(r){return async e=>new Uint8Array(await crypto.subtle.digest(r,e))}var pe=kr({name:"sha2-256",code:18,encode:Vn("SHA-256")}),ao=kr({name:"sha2-512",code:19,encode:Vn("SHA-512")});var le={...Ar,...br,...Sr,...gr,...wr,...dr,...xr,...fr,...vr,...yr},fl={...Cr,...Lr};function O(r=0){return new Uint8Array(r)}function N(r=0){return new Uint8Array(r)}function Wn(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var Hn=Wn("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),Dr=Wn("ascii","a",r=>{let e="a";for(let t=0;t<r.length;t++)e+=String.fromCharCode(r[t]);return e},r=>{r=r.substring(1);let e=N(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),co={utf8:Hn,"utf-8":Hn,hex:le.base16,latin1:Dr,ascii:Dr,binary:Dr,...le},At=co;function E(r,e="utf8"){let t=At[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.encoder.encode(r).substring(1)}var lo=Math.pow(2,7),uo=Math.pow(2,14),ho=Math.pow(2,21),Tr=Math.pow(2,28),_r=Math.pow(2,35),Rr=Math.pow(2,42),Pr=Math.pow(2,49),w=128,F=127;function v(r){if(r<lo)return 1;if(r<uo)return 2;if(r<ho)return 3;if(r<Tr)return 4;if(r<_r)return 5;if(r<Rr)return 6;if(r<Pr)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function Nr(r,e,t=0){switch(v(r)){case 8:e[t++]=r&255|w,r/=128;case 7:e[t++]=r&255|w,r/=128;case 6:e[t++]=r&255|w,r/=128;case 5:e[t++]=r&255|w,r/=128;case 4:e[t++]=r&255|w,r>>>=7;case 3:e[t++]=r&255|w,r>>>=7;case 2:e[t++]=r&255|w,r>>>=7;case 1:{e[t++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return e}function fo(r,e,t=0){switch(v(r)){case 8:e.set(t++,r&255|w),r/=128;case 7:e.set(t++,r&255|w),r/=128;case 6:e.set(t++,r&255|w),r/=128;case 5:e.set(t++,r&255|w),r/=128;case 4:e.set(t++,r&255|w),r>>>=7;case 3:e.set(t++,r&255|w),r>>>=7;case 2:e.set(t++,r&255|w),r>>>=7;case 1:{e.set(t++,r&255),r>>>=7;break}default:throw new Error("unreachable")}return e}function Fr(r,e){let t=r[e],n=0;if(n+=t&F,t<w||(t=r[e+1],n+=(t&F)<<7,t<w)||(t=r[e+2],n+=(t&F)<<14,t<w)||(t=r[e+3],n+=(t&F)<<21,t<w)||(t=r[e+4],n+=(t&F)*Tr,t<w)||(t=r[e+5],n+=(t&F)*_r,t<w)||(t=r[e+6],n+=(t&F)*Rr,t<w)||(t=r[e+7],n+=(t&F)*Pr,t<w))return n;throw new RangeError("Could not decode varint")}function po(r,e){let t=r.get(e),n=0;if(n+=t&F,t<w||(t=r.get(e+1),n+=(t&F)<<7,t<w)||(t=r.get(e+2),n+=(t&F)<<14,t<w)||(t=r.get(e+3),n+=(t&F)<<21,t<w)||(t=r.get(e+4),n+=(t&F)*Tr,t<w)||(t=r.get(e+5),n+=(t&F)*_r,t<w)||(t=r.get(e+6),n+=(t&F)*Rr,t<w)||(t=r.get(e+7),n+=(t&F)*Pr,t<w))return n;throw new RangeError("Could not decode varint")}function J(r,e,t=0){return e==null&&(e=N(v(r))),e instanceof Uint8Array?Nr(r,e,t):fo(r,e,t)}function W(r,e=0){return r instanceof Uint8Array?Fr(r,e):po(r,e)}function K(r,e){e==null&&(e=r.reduce((s,i)=>s+i.length,0));let t=N(e),n=0;for(let s of r)t.set(s,n),n+=s.length;return t}var Rl=parseInt("0xFFFF",16),Pl=new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);function je(r,e="utf8"){let t=At[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.decoder.decode(`${t.prefix}${r}`)}var Gn=yt,yo=xt,Mr=function(r){let e=0;if(r=r.toString().trim(),Gn(r)){let t=new Uint8Array(e+4);return r.split(/\./g).forEach(n=>{t[e++]=parseInt(n,10)&255}),t}if(yo(r)){let t=r.split(":",8),n;for(n=0;n<t.length;n++){let i=Gn(t[n]),o;i&&(o=Mr(t[n]),t[n]=E(o.slice(0,2),"base16")),o!=null&&++n<8&&t.splice(n,0,E(o.slice(2,4),"base16"))}if(t[0]==="")for(;t.length<8;)t.unshift("0");else if(t[t.length-1]==="")for(;t.length<8;)t.push("0");else if(t.length<8){for(n=0;n<t.length&&t[n]!=="";n++);let i=[n,1];for(n=9-t.length;n>0;n--)i.push("0");t.splice.apply(t,i)}let s=new Uint8Array(e+16);for(n=0;n<t.length;n++){let i=parseInt(t[n],16);s[e++]=i>>8&255,s[e++]=i&255}return s}throw new Error("invalid ip address")},jn=function(r,e=0,t){e=~~e,t=t??r.length-e;let n=new DataView(r.buffer);if(t===4){let s=[];for(let i=0;i<t;i++)s.push(r[e+i]);return s.join(".")}if(t===16){let s=[];for(let i=0;i<t;i+=2)s.push(n.getUint16(e+i).toString(16));return s.join(":").replace(/(^|:)0(:0)*:0(:|$)/,"$1::$3").replace(/:{3,4}/,"::")}return""};var Me={},Ur={},Eo=[[4,32,"ip4"],[6,16,"tcp"],[33,16,"dccp"],[41,128,"ip6"],[42,-1,"ip6zone"],[43,8,"ipcidr"],[53,-1,"dns",!0],[54,-1,"dns4",!0],[55,-1,"dns6",!0],[56,-1,"dnsaddr",!0],[132,16,"sctp"],[273,16,"udp"],[275,0,"p2p-webrtc-star"],[276,0,"p2p-webrtc-direct"],[277,0,"p2p-stardust"],[280,0,"webrtc-direct"],[281,0,"webrtc"],[290,0,"p2p-circuit"],[301,0,"udt"],[302,0,"utp"],[400,-1,"unix",!1,!0],[421,-1,"ipfs"],[421,-1,"p2p"],[443,0,"https"],[444,96,"onion"],[445,296,"onion3"],[446,-1,"garlic64"],[448,0,"tls"],[449,-1,"sni"],[460,0,"quic"],[461,0,"quic-v1"],[465,0,"webtransport"],[466,-1,"certhash"],[477,0,"ws"],[478,0,"wss"],[479,0,"p2p-websocket-star"],[480,0,"http"],[777,-1,"memory"]];Eo.forEach(r=>{let e=vo(...r);Ur[e.code]=e,Me[e.name]=e});function vo(r,e,t,n,s){return{code:r,size:e,name:t,resolvable:!!n,path:!!s}}function x(r){if(typeof r=="number"){if(Ur[r]!=null)return Ur[r];throw new Error(`no protocol with code: ${r}`)}else if(typeof r=="string"){if(Me[r]!=null)return Me[r];throw new Error(`no protocol with name: ${r}`)}throw new Error(`invalid protocol id type: ${typeof r}`)}var gu=x("ip4"),wu=x("ip6"),bu=x("ipcidr");function Or(r,e){switch(x(r).code){case 4:case 41:return Ao(e);case 42:return Jn(e);case 6:case 273:case 33:case 132:return Yn(e).toString();case 53:case 54:case 55:case 56:case 400:case 449:case 777:return Jn(e);case 421:return Co(e);case 444:return Kn(e);case 445:return Kn(e);case 466:return ko(e);default:return E(e,"base16")}}function zr(r,e){switch(x(r).code){case 4:return Qn(e);case 41:return Qn(e);case 42:return Xn(e);case 6:case 273:case 33:case 132:return Vr(parseInt(e,10));case 53:case 54:case 55:case 56:case 400:case 449:case 777:return Xn(e);case 421:return Lo(e);case 444:return Do(e);case 445:return To(e);case 466:return Io(e);default:return je(e,"base16")}}var Br=Object.values(le).map(r=>r.decoder),So=function(){let r=Br[0].or(Br[1]);return Br.slice(2).forEach(e=>r=r.or(e)),r}();function Qn(r){if(!Et(r))throw new Error("invalid ip address");return Mr(r)}function Ao(r){let e=jn(r,0,r.length);if(e==null)throw new Error("ipBuff is required");if(!Et(e))throw new Error("invalid ip address");return e}function Vr(r){let e=new ArrayBuffer(2);return new DataView(e).setUint16(0,r),new Uint8Array(e)}function Yn(r){return new DataView(r.buffer).getUint16(r.byteOffset)}function Xn(r){let e=je(r),t=Uint8Array.from(J(e.length));return K([t,e],t.length+e.length)}function Jn(r){let e=W(r);if(r=r.slice(v(e)),r.length!==e)throw new Error("inconsistent lengths");return E(r)}function Lo(r){let e;r[0]==="Q"||r[0]==="1"?e=he(D.decode(`z${r}`)).bytes:e=T.parse(r).multihash.bytes;let t=Uint8Array.from(J(e.length));return K([t,e],t.length+e.length)}function Io(r){let e=So.decode(r),t=Uint8Array.from(J(e.length));return K([t,e],t.length+e.length)}function ko(r){let e=W(r),t=r.slice(v(e));if(t.length!==e)throw new Error("inconsistent lengths");return"u"+E(t,"base64url")}function Co(r){let e=W(r),t=r.slice(v(e));if(t.length!==e)throw new Error("inconsistent lengths");return E(t,"base58btc")}function Do(r){let e=r.split(":");if(e.length!==2)throw new Error(`failed to parse onion addr: ["'${e.join('", "')}'"]' does not contain a port number`);if(e[0].length!==16)throw new Error(`failed to parse onion addr: ${e[0]} not a Tor onion address.`);let t=se.decode("b"+e[0]),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let s=Vr(n);return K([t,s],t.length+s.length)}function To(r){let e=r.split(":");if(e.length!==2)throw new Error(`failed to parse onion addr: ["'${e.join('", "')}'"]' does not contain a port number`);if(e[0].length!==56)throw new Error(`failed to parse onion addr: ${e[0]} not a Tor onion3 address.`);let t=se.decode(`b${e[0]}`),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let s=Vr(n);return K([t,s],t.length+s.length)}function Kn(r){let e=r.slice(0,r.length-2),t=r.slice(r.length-2),n=E(e,"base32"),s=Yn(t);return`${n}:${s}`}function Zn(r){r=Hr(r);let e=[],t=[],n=null,s=r.split("/").slice(1);if(s.length===1&&s[0]==="")return{bytes:new Uint8Array,string:"/",tuples:[],stringTuples:[],path:null};for(let i=0;i<s.length;i++){let o=s[i],a=x(o);if(a.size===0){e.push([a.code]),t.push([a.code]);continue}if(i++,i>=s.length)throw ts("invalid address: "+r);if(a.path===!0){n=Hr(s.slice(i).join("/")),e.push([a.code,zr(a.code,n)]),t.push([a.code,n]);break}let c=zr(a.code,s[i]);e.push([a.code,c]),t.push([a.code,Or(a.code,c)])}return{string:es(t),bytes:qr(e),tuples:e,stringTuples:t,path:n}}function Wr(r){let e=[],t=[],n=null,s=0;for(;s<r.length;){let i=W(r,s),o=v(i),a=x(i),c=_o(a,r.slice(s+o));if(c===0){e.push([i]),t.push([i]),s+=o;continue}let h=r.slice(s+o,s+o+c);if(s+=c+o,s>r.length)throw ts("Invalid address Uint8Array: "+E(r,"base16"));e.push([i,h]);let l=Or(i,h);if(t.push([i,l]),a.path===!0){n=l;break}}return{bytes:Uint8Array.from(r),string:es(t),tuples:e,stringTuples:t,path:n}}function es(r){let e=[];return r.map(t=>{let n=x(t[0]);return e.push(n.name),t.length>1&&t[1]!=null&&e.push(t[1]),null}),Hr(e.join("/"))}function qr(r){return K(r.map(e=>{let t=x(e[0]),n=Uint8Array.from(J(t.code));return e.length>1&&e[1]!=null&&(n=K([n,e[1]])),n}))}function _o(r,e){if(r.size>0)return r.size/8;if(r.size===0)return 0;{let t=W(e instanceof Uint8Array?e:Uint8Array.from(e));return t+v(t)}}function Hr(r){return"/"+r.trim().split("/").filter(e=>e).join("/")}function ts(r){return new Error("Error parsing address: "+r)}var Ro=Symbol.for("nodejs.util.inspect.custom"),$r=Symbol.for("@multiformats/js-multiaddr/multiaddr"),Po=[x("dns").code,x("dns4").code,x("dns6").code,x("dnsaddr").code],Lt=class r{bytes;#e;#t;#r;#n;[$r]=!0;constructor(e){e==null&&(e="");let t;if(e instanceof Uint8Array)t=Wr(e);else if(typeof e=="string"){if(e.length>0&&e.charAt(0)!=="/")throw new Error(`multiaddr "${e}" must start with a "/"`);t=Zn(e)}else if(ns(e))t=Wr(e.bytes);else throw new Error("addr must be a string, Buffer, or another Multiaddr");this.bytes=t.bytes,this.#e=t.string,this.#t=t.tuples,this.#r=t.stringTuples,this.#n=t.path}toString(){return this.#e}toJSON(){return this.toString()}toOptions(){let e,t,n,s,i="",o=x("tcp"),a=x("udp"),c=x("ip4"),h=x("ip6"),l=x("dns6"),u=x("ip6zone");for(let[S,p]of this.stringTuples())S===u.code&&(i=`%${p??""}`),Po.includes(S)&&(t=o.name,s=443,n=`${p??""}${i}`,e=S===l.code?6:4),(S===o.code||S===a.code)&&(t=x(S).name,s=parseInt(p??"")),(S===c.code||S===h.code)&&(t=x(S).name,n=`${p??""}${i}`,e=S===h.code?6:4);if(e==null||t==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:e,host:n,transport:t,port:s}}protos(){return this.#t.map(([e])=>Object.assign({},x(e)))}protoCodes(){return this.#t.map(([e])=>e)}protoNames(){return this.#t.map(([e])=>x(e).name)}tuples(){return this.#t}stringTuples(){return this.#r}encapsulate(e){return e=new r(e),new r(this.toString()+e.toString())}decapsulate(e){let t=e.toString(),n=this.toString(),s=n.lastIndexOf(t);if(s<0)throw new Error(`Address ${this.toString()} does not contain subaddress: ${e.toString()}`);return new r(n.slice(0,s))}decapsulateCode(e){let t=this.tuples();for(let n=t.length-1;n>=0;n--)if(t[n][0]===e)return new r(qr(t.slice(0,n)));return this}getPeerId(){try{let e=[];this.stringTuples().forEach(([n,s])=>{n===Me.p2p.code&&e.push([n,s]),n===Me["p2p-circuit"].code&&(e=[])});let t=e.pop();if(t?.[1]!=null){let n=t[1];return n[0]==="Q"||n[0]==="1"?E(D.decode(`z${n}`),"base58btc"):E(T.parse(n).multihash.bytes,"base58btc")}return null}catch{return null}}getPath(){return this.#n}equals(e){return de(this.bytes,e.bytes)}async resolve(e){let t=this.protos().find(i=>i.resolvable);if(t==null)return[this];let n=rs.get(t.name);if(n==null)throw new B(`no available resolver for ${t.name}`,"ERR_NO_AVAILABLE_RESOLVER");return(await n(this,e)).map(i=>Gr(i))}nodeAddress(){let e=this.toOptions();if(e.transport!=="tcp"&&e.transport!=="udp")throw new Error(`multiaddr must have a valid format - no protocol with name: "${e.transport}". Must have a valid transport protocol: "{tcp, udp}"`);return{family:e.family,address:e.host,port:e.port}}isThinWaistAddress(e){let t=(e??this).protos();return!(t.length!==2||t[0].code!==4&&t[0].code!==41||t[1].code!==6&&t[1].code!==273)}[Ro](){return`Multiaddr(${this.#e})`}};var rs=new Map;function ns(r){return!!r?.[$r]}function Gr(r){return new Lt(r)}var No=r=>r.toString().split("/").slice(1),Qe=r=>({match:e=>e.length<1?!1:r(e[0])?e.slice(1):!1,pattern:"fn"}),g=r=>({match:e=>Qe(t=>t===r).match(e),pattern:r}),Ct=()=>({match:r=>Qe(e=>typeof e=="string").match(r),pattern:"{string}"}),Dt=()=>({match:r=>Qe(e=>!isNaN(parseInt(e))).match(r),pattern:"{number}"}),R=()=>({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}"}),It=()=>({match:r=>{if(r.length<2||r[0]!=="certhash")return!1;try{Er.decode(r[1])}catch{return!1}return r.slice(2)},pattern:"/certhash/{certhash}"}),U=r=>({match:e=>{let t=r.match(e);return t===!1?e:t},pattern:`optional(${r.pattern})`}),q=(...r)=>({match:e=>{let t;for(let n of r){let s=n.match(e);s!==!1&&(t==null||s.length<t.length)&&(t=s)}return t??!1},pattern:`or(${r.map(e=>e.pattern).join(", ")})`}),b=(...r)=>({match:e=>{for(let t of r){let n=t.match(e);if(n===!1)return!1;e=n}return e},pattern:`and(${r.map(e=>e.pattern).join(", ")})`});function I(...r){function e(s){let i=No(s);for(let o of r){let a=o.match(i);if(a===!1)return!1;i=a}return i}function t(s){return e(s)!==!1}function n(s){let i=e(s);return i===!1?!1:i.length===0}return{matches:t,exactMatch:n}}var Qr=b(g("dns4"),Ct()),Xr=b(g("dns6"),Ct()),Jr=b(g("dnsaddr"),Ct()),ss=b(g("dns"),Ct()),ju=I(Qr),Qu=I(Xr),Xu=I(Jr),Ju=I(q(ss,Jr,Qr,Xr)),is=b(g("ip4"),Qe(yt)),os=b(g("ip6"),Qe(xt)),as=q(is,os),re=q(as,ss,Qr,Xr,Jr),Ku=I(re),Yu=I(is),Zu=I(os),eh=I(as),Tt=b(re,g("tcp"),Dt()),Xe=b(re,g("udp"),Dt()),Fo=q(Tt,Xe),th=I(Tt),rh=I(Xe),Kr=b(Xe,g("quic")),_t=b(Xe,g("quic-v1")),Mo=q(Kr,_t),nh=I(Kr),sh=I(_t),jr=q(re,Tt,Xe,Kr,_t),cs=q(b(jr,g("ws"),U(R()))),ih=I(cs),ls=q(b(jr,g("wss"),U(R())),b(jr,g("tls"),g("ws"),U(R()))),oh=I(ls),us=b(Fo,g("webrtc-direct"),It(),U(It()),U(R())),ah=I(us),hs=b(_t,g("webtransport"),It(),It(),U(R())),ch=I(hs),kt=q(cs,ls,b(Tt,U(R())),b(Mo,U(R())),b(re,U(R())),us,hs,R()),lh=I(kt),Uo=b(kt,g("p2p-circuit"),R()),fs=I(Uo),Bo=q(b(kt,g("p2p-circuit"),g("webrtc"),R()),b(kt,g("webrtc"),U(R())),g("webrtc")),uh=I(Bo),Oo=q(b(re,g("tcp"),Dt(),g("http"),U(R())),b(re,g("http"),U(R()))),hh=I(Oo),zo=q(b(re,g("tcp"),q(b(g("443"),g("http")),b(Dt(),g("https"))),U(R())),b(re,g("tls"),g("http"),U(R())),b(re,g("https"),U(R()))),fh=I(zo);var Os=En(ws(),1);function Zo(r){return r[Symbol.asyncIterator]!=null}function ea(r){if(Zo(r))return(async()=>{for await(let e of r);})();for(let e of r);}var bs=ea;var xs=Symbol.for("@achingbrain/uint8arraylist");function ys(r,e){if(e==null||e<0)throw new RangeError("index is out of bounds");let t=0;for(let n of r){let s=t+n.byteLength;if(e<s)return{buf:n,index:e-t};t=s}throw new RangeError("index is out of bounds")}function Nt(r){return!!r?.[xs]}var G=class r{bufs;length;[xs]=!0;constructor(...e){this.bufs=[],this.length=0,e.length>0&&this.appendAll(e)}*[Symbol.iterator](){yield*this.bufs}get byteLength(){return this.length}append(...e){this.appendAll(e)}appendAll(e){let t=0;for(let n of e)if(n instanceof Uint8Array)t+=n.byteLength,this.bufs.push(n);else if(Nt(n))t+=n.byteLength,this.bufs.push(...n.bufs);else throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");this.length+=t}prepend(...e){this.prependAll(e)}prependAll(e){let t=0;for(let n of e.reverse())if(n instanceof Uint8Array)t+=n.byteLength,this.bufs.unshift(n);else if(Nt(n))t+=n.byteLength,this.bufs.unshift(...n.bufs);else throw new Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");this.length+=t}get(e){let t=ys(this.bufs,e);return t.buf[t.index]}set(e,t){let n=ys(this.bufs,e);n.buf[n.index]=t}write(e,t=0){if(e instanceof Uint8Array)for(let n=0;n<e.length;n++)this.set(t+n,e[n]);else if(Nt(e))for(let n=0;n<e.length;n++)this.set(t+n,e.get(n));else throw new Error("Could not write value, must be an Uint8Array or a Uint8ArrayList")}consume(e){if(e=Math.trunc(e),!(Number.isNaN(e)||e<=0)){if(e===this.byteLength){this.bufs=[],this.length=0;return}for(;this.bufs.length>0;)if(e>=this.bufs[0].byteLength)e-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift();else{this.bufs[0]=this.bufs[0].subarray(e),this.length-=e;break}}}slice(e,t){let{bufs:n,length:s}=this._subList(e,t);return K(n,s)}subarray(e,t){let{bufs:n,length:s}=this._subList(e,t);return n.length===1?n[0]:K(n,s)}sublist(e,t){let{bufs:n,length:s}=this._subList(e,t),i=new r;return i.length=s,i.bufs=[...n],i}_subList(e,t){if(e=e??0,t=t??this.length,e<0&&(e=this.length+e),t<0&&(t=this.length+t),e<0||t>this.length)throw new RangeError("index is out of bounds");if(e===t)return{bufs:[],length:0};if(e===0&&t===this.length)return{bufs:this.bufs,length:this.length};let n=[],s=0;for(let i=0;i<this.bufs.length;i++){let o=this.bufs[i],a=s,c=a+o.byteLength;if(s=c,e>=c)continue;let h=e>=a&&e<c,l=t>a&&t<=c;if(h&&l){if(e===a&&t===c){n.push(o);break}let u=e-a;n.push(o.subarray(u,u+(t-e)));break}if(h){if(e===0){n.push(o);continue}n.push(o.subarray(e-a));continue}if(l){if(t===c){n.push(o);break}n.push(o.subarray(0,t-a));break}n.push(o)}return{bufs:n,length:t-e}}indexOf(e,t=0){if(!Nt(e)&&!(e instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');let n=e instanceof Uint8Array?e:e.subarray();if(t=Number(t??0),isNaN(t)&&(t=0),t<0&&(t=this.length+t),t<0&&(t=0),e.length===0)return t>this.length?this.length:t;let s=n.byteLength;if(s===0)throw new TypeError("search must be at least 1 byte long");let i=256,o=new Int32Array(i);for(let u=0;u<i;u++)o[u]=-1;for(let u=0;u<s;u++)o[n[u]]=u;let a=o,c=this.byteLength-n.byteLength,h=n.byteLength-1,l;for(let u=t;u<=c;u+=l){l=0;for(let f=h;f>=0;f--){let S=this.get(u+f);if(n[f]!==S){l=Math.max(1,f-a[S]);break}}if(l===0)return u}return-1}getInt8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getInt8(0)}setInt8(e,t){let n=N(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt8(0,t),this.write(n,e)}getInt16(e,t){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt16(0,t)}setInt16(e,t,n){let s=O(2);new DataView(s.buffer,s.byteOffset,s.byteLength).setInt16(0,t,n),this.write(s,e)}getInt32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt32(0,t)}setInt32(e,t,n){let s=O(4);new DataView(s.buffer,s.byteOffset,s.byteLength).setInt32(0,t,n),this.write(s,e)}getBigInt64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigInt64(0,t)}setBigInt64(e,t,n){let s=O(8);new DataView(s.buffer,s.byteOffset,s.byteLength).setBigInt64(0,t,n),this.write(s,e)}getUint8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getUint8(0)}setUint8(e,t){let n=N(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint8(0,t),this.write(n,e)}getUint16(e,t){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint16(0,t)}setUint16(e,t,n){let s=O(2);new DataView(s.buffer,s.byteOffset,s.byteLength).setUint16(0,t,n),this.write(s,e)}getUint32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint32(0,t)}setUint32(e,t,n){let s=O(4);new DataView(s.buffer,s.byteOffset,s.byteLength).setUint32(0,t,n),this.write(s,e)}getBigUint64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigUint64(0,t)}setBigUint64(e,t,n){let s=O(8);new DataView(s.buffer,s.byteOffset,s.byteLength).setBigUint64(0,t,n),this.write(s,e)}getFloat32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat32(0,t)}setFloat32(e,t,n){let s=O(4);new DataView(s.buffer,s.byteOffset,s.byteLength).setFloat32(0,t,n),this.write(s,e)}getFloat64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat64(0,t)}setFloat64(e,t,n){let s=O(8);new DataView(s.buffer,s.byteOffset,s.byteLength).setFloat64(0,t,n),this.write(s,e)}equals(e){if(e==null||!(e instanceof r)||e.bufs.length!==this.bufs.length)return!1;for(let t=0;t<this.bufs.length;t++)if(!de(this.bufs[t],e.bufs[t]))return!1;return!0}static fromUint8Arrays(e,t){let n=new r;return n.bufs=e,t==null&&(t=e.reduce((s,i)=>s+i.byteLength,0)),n.length=t,n}};function Ft(r){return r[Symbol.asyncIterator]!=null}var Mt=r=>{let e=v(r),t=N(e);return J(r,t),Mt.bytes=e,t};Mt.bytes=0;function Es(r,e){e=e??{};let t=e.lengthEncoder??Mt;function*n(s){let i=t(s.byteLength);i instanceof Uint8Array?yield i:yield*i,s instanceof Uint8Array?yield s:yield*s}return Ft(r)?async function*(){for await(let s of r)yield*n(s)}():function*(){for(let s of r)yield*n(s)}()}Es.single=(r,e)=>{e=e??{};let t=e.lengthEncoder??Mt;return new G(t(r.byteLength),r)};var ze=En(As(),1);var ra=8,na=1024*1024*4,ge;(function(r){r[r.LENGTH=0]="LENGTH",r[r.DATA=1]="DATA"})(ge||(ge={}));var Yr=r=>{let e=W(r);return Yr.bytes=v(e),e};Yr.bytes=0;function Je(r,e){let t=new G,n=ge.LENGTH,s=-1,i=e?.lengthDecoder??Yr,o=e?.maxLengthLength??ra,a=e?.maxDataLength??na;function*c(){for(;t.byteLength>0;){if(n===ge.LENGTH)try{if(s=i(t),s<0)throw(0,ze.default)(new Error("invalid message length"),"ERR_INVALID_MSG_LENGTH");if(s>a)throw(0,ze.default)(new Error("message length too long"),"ERR_MSG_DATA_TOO_LONG");let h=i.bytes;t.consume(h),e?.onLength!=null&&e.onLength(s),n=ge.DATA}catch(h){if(h instanceof RangeError){if(t.byteLength>o)throw(0,ze.default)(new Error("message length length too long"),"ERR_MSG_LENGTH_TOO_LONG");break}throw h}if(n===ge.DATA){if(t.byteLength<s)break;let h=t.sublist(0,s);t.consume(s),e?.onData!=null&&e.onData(h),yield h,n=ge.LENGTH}}}return Ft(r)?async function*(){for await(let h of r)t.append(h),yield*c();if(t.byteLength>0)throw(0,ze.default)(new Error("unexpected end of input"),"ERR_UNEXPECTED_EOF")}():function*(){for(let h of r)t.append(h),yield*c();if(t.byteLength>0)throw(0,ze.default)(new Error("unexpected end of input"),"ERR_UNEXPECTED_EOF")}()}Je.fromReader=(r,e)=>{let t=1,n=async function*(){for(;;)try{let{done:i,value:o}=await r.next(t);if(i===!0)return;o!=null&&(yield o)}catch(i){if(i.code==="ERR_UNDER_READ")return{done:!0,value:null};throw i}finally{t=1}}();return Je(n,{...e??{},onLength:i=>{t=i}})};var Zr=class{readNext;haveNext;ended;nextResult;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 e=this.nextResult;return this.nextResult=void 0,this.readNext.resolve(),this.readNext=P(),e}async throw(e){return this.ended=!0,e!=null&&this.haveNext.reject(e),{done:!0,value:void 0}}async return(){let e={done:!0,value:void 0};return await this._push(void 0),e}async push(e,t){await this._push(e,t)}async end(e,t){e!=null?await this.throw(e):await this._push(void 0,t)}async _push(e,t){if(e!=null&&this.ended)throw new Error("Cannot push value onto an ended pushable");if(this.nextResult!=null&&(await this.readNext.promise,this.nextResult!=null))throw new Error("NeedNext promise resolved but nextResult was not consumed");e!=null?this.nextResult={done:!1,value:e}:(this.ended=!0,this.nextResult={done:!0,value:void 0}),this.haveNext.resolve(),this.haveNext=P(),await dt(this.readNext.promise,t?.signal,t)}};function Ls(){return new Zr}var Ut=class extends Error{code;constructor(e,t){super(e),this.code=t}},en=class extends Ut{type;constructor(e){super(e,"ABORT_ERR"),this.type="aborted"}};function Is(r,e){let t=Ls();r.sink(t).catch(async o=>{await t.end(o)}),r.sink=async o=>{for await(let a of o)await t.push(a);await t.end()};let n=r.source;r.source[Symbol.iterator]!=null?n=r.source[Symbol.iterator]():r.source[Symbol.asyncIterator]!=null&&(n=r.source[Symbol.asyncIterator]());let s=new G;return{read:async(o,a)=>{a?.signal?.throwIfAborted();let c,h=new Promise((l,u)=>{c=()=>{u(new en("Read aborted"))},a?.signal?.addEventListener("abort",c)});try{if(o==null){let{done:u,value:f}=await Promise.race([n.next(),h]);return u===!0?new G:f}for(;s.byteLength<o;){let{value:u,done:f}=await Promise.race([n.next(),h]);if(f===!0)throw new Ut("unexpected end of input","ERR_UNEXPECTED_EOF");s.append(u)}let l=s.sublist(0,o);return s.consume(o),l}finally{c!=null&&a?.signal?.removeEventListener("abort",c)}},write:async(o,a)=>{a?.signal?.throwIfAborted(),o instanceof Uint8Array?await t.push(o,a):await t.push(o.subarray(),a)},unwrap:()=>{if(s.byteLength>0){let o=r.source;r.source=async function*(){e?.yieldBytes===!1?yield s:yield*s,yield*o}()}return r}}}var Bt=class extends Error{code;constructor(e,t){super(e),this.code=t}};function ks(r,e={}){let t=Is(r,e);e.maxDataLength!=null&&e.maxLengthLength==null&&(e.maxLengthLength=v(e.maxDataLength));let n=e?.lengthDecoder??W,s=e?.lengthEncoder??J;return{read:async o=>{let a=-1,c=new G;for(;;){c.append(await t.read(1,o));try{a=n(c)}catch(h){if(h instanceof RangeError)continue;throw h}if(e?.maxLengthLength!=null&&c.byteLength>e.maxLengthLength)throw new Bt("message length length too long","ERR_MSG_LENGTH_TOO_LONG");if(a>-1)break}if(e?.maxDataLength!=null&&a>e.maxDataLength)throw new Bt("message length too long","ERR_MSG_DATA_TOO_LONG");return t.read(a,o)},write:async(o,a)=>{await t.write(new G(s(o.byteLength),o),a)},writeV:async(o,a)=>{let c=new G(...o.flatMap(h=>[s(h.byteLength),h]));await t.write(c,a)},unwrap:()=>t.unwrap()}}function ia(r){let[e,t]=r[Symbol.asyncIterator]!=null?[r[Symbol.asyncIterator](),Symbol.asyncIterator]:[r[Symbol.iterator](),Symbol.iterator],n=[];return{peek:()=>e.next(),push:s=>{n.push(s)},next:()=>n.length>0?{done:!1,value:n.shift()}:e.next(),[t](){return this}}}var Ot=ia;function oa(r){return r[Symbol.asyncIterator]!=null}function aa(r,e){if(oa(r))return async function*(){for await(let a of r)yield e(a)}();let t=Ot(r),{value:n,done:s}=t.next();if(s===!0)return function*(){}();let i=e(n);if(typeof i.then=="function")return async function*(){yield await i;for await(let a of t)yield e(a)}();let o=e;return function*(){yield i;for(let a of t)yield o(a)}()}var we=aa;function ca(r){return r[Symbol.asyncIterator]!=null}function la(...r){let e=[];for(let t of r)ca(t)||e.push(t);return e.length===r.length?function*(){for(let t of e)yield*t}():async function*(){let t=Ce({objectMode:!0});Promise.resolve().then(async()=>{try{await Promise.all(r.map(async n=>{for await(let s of n)t.push(s)})),t.end()}catch(n){t.end(n)}}),yield*t}()}var zt=la;function Ke(r,...e){if(r==null)throw new Error("Empty pipeline");if(tn(r)){let n=r;r=()=>n.source}else if(Ds(r)||Cs(r)){let n=r;r=()=>n}let t=[r,...e];if(t.length>1&&tn(t[t.length-1])&&(t[t.length-1]=t[t.length-1].sink),t.length>2)for(let n=1;n<t.length-1;n++)tn(t[n])&&(t[n]=ha(t[n]));return ua(...t)}var ua=(...r)=>{let e;for(;r.length>0;)e=r.shift()(e);return e},Cs=r=>r?.[Symbol.asyncIterator]!=null,Ds=r=>r?.[Symbol.iterator]!=null,tn=r=>r==null?!1:r.sink!=null&&r.source!=null,ha=r=>e=>{let t=r.sink(e);if(t?.then!=null){let n=Ce({objectMode:!0});t.then(()=>{n.end()},o=>{n.end(o)});let s,i=r.source;if(Cs(i))s=async function*(){yield*i,n.end()};else if(Ds(i))s=function*(){yield*i,n.end()};else throw new Error("Unknown duplex source type - must be Iterable or AsyncIterable");return zt(n,s())}return r.source};function fa(r){return r[Symbol.asyncIterator]!=null}function da(r,e){return fa(r)?async function*(){let t=0;if(!(e<1)){for await(let n of r)if(yield n,t++,t===e)return}}():function*(){let t=0;if(!(e<1)){for(let n of r)if(yield n,t++,t===e)return}}()}var Ts=da;var be=class extends Event{constructor(e,t){super(e),this.detail=t}};var Ye="/ipfs/bitswap/1.2.0";var rn=new Float32Array([-0]),ue=new Uint8Array(rn.buffer);function _s(r,e,t){rn[0]=r,e[t]=ue[0],e[t+1]=ue[1],e[t+2]=ue[2],e[t+3]=ue[3]}function Rs(r,e){return ue[0]=r[e],ue[1]=r[e+1],ue[2]=r[e+2],ue[3]=r[e+3],rn[0]}var nn=new Float64Array([-0]),M=new Uint8Array(nn.buffer);function Ps(r,e,t){nn[0]=r,e[t]=M[0],e[t+1]=M[1],e[t+2]=M[2],e[t+3]=M[3],e[t+4]=M[4],e[t+5]=M[5],e[t+6]=M[6],e[t+7]=M[7]}function Ns(r,e){return M[0]=r[e],M[1]=r[e+1],M[2]=r[e+2],M[3]=r[e+3],M[4]=r[e+4],M[5]=r[e+5],M[6]=r[e+6],M[7]=r[e+7],nn[0]}var pa=BigInt(Number.MAX_SAFE_INTEGER),ma=BigInt(Number.MIN_SAFE_INTEGER),j=class r{lo;hi;constructor(e,t){this.lo=e|0,this.hi=t|0}toNumber(e=!1){if(!e&&this.hi>>>31>0){let t=~this.lo+1>>>0,n=~this.hi>>>0;return t===0&&(n=n+1>>>0),-(t+n*4294967296)}return this.lo+this.hi*4294967296}toBigInt(e=!1){if(e)return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n);if(this.hi>>>31){let t=~this.lo+1>>>0,n=~this.hi>>>0;return t===0&&(n=n+1>>>0),-(BigInt(t)+(BigInt(n)<<32n))}return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n)}toString(e=!1){return this.toBigInt(e).toString()}zzEncode(){let e=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^e)>>>0,this.lo=(this.lo<<1^e)>>>0,this}zzDecode(){let e=-(this.lo&1);return this.lo=((this.lo>>>1|this.hi<<31)^e)>>>0,this.hi=(this.hi>>>1^e)>>>0,this}length(){let e=this.lo,t=(this.lo>>>28|this.hi<<4)>>>0,n=this.hi>>>24;return n===0?t===0?e<16384?e<128?1:2:e<2097152?3:4:t<16384?t<128?5:6:t<2097152?7:8:n<128?9:10}static fromBigInt(e){if(e===0n)return ye;if(e<pa&&e>ma)return this.fromNumber(Number(e));let t=e<0n;t&&(e=-e);let n=e>>32n,s=e-(n<<32n);return t&&(n=~n|0n,s=~s|0n,++s>Fs&&(s=0n,++n>Fs&&(n=0n))),new r(Number(s),Number(n))}static fromNumber(e){if(e===0)return ye;let t=e<0;t&&(e=-e);let n=e>>>0,s=(e-n)/4294967296>>>0;return t&&(s=~s>>>0,n=~n>>>0,++n>4294967295&&(n=0,++s>4294967295&&(s=0))),new r(n,s)}static from(e){return typeof e=="number"?r.fromNumber(e):typeof e=="bigint"?r.fromBigInt(e):typeof e=="string"?r.fromBigInt(BigInt(e)):e.low!=null||e.high!=null?new r(e.low>>>0,e.high>>>0):ye}},ye=new j(0,0);ye.toBigInt=function(){return 0n};ye.zzEncode=ye.zzDecode=function(){return this};ye.length=function(){return 1};var Fs=4294967296n;function Ms(r){let e=0,t=0;for(let n=0;n<r.length;++n)t=r.charCodeAt(n),t<128?e+=1:t<2048?e+=2:(t&64512)===55296&&(r.charCodeAt(n+1)&64512)===56320?(++n,e+=4):e+=3;return e}function Us(r,e,t){if(t-e<1)return"";let s,i=[],o=0,a;for(;e<t;)a=r[e++],a<128?i[o++]=a:a>191&&a<224?i[o++]=(a&31)<<6|r[e++]&63:a>239&&a<365?(a=((a&7)<<18|(r[e++]&63)<<12|(r[e++]&63)<<6|r[e++]&63)-65536,i[o++]=55296+(a>>10),i[o++]=56320+(a&1023)):i[o++]=(a&15)<<12|(r[e++]&63)<<6|r[e++]&63,o>8191&&((s??(s=[])).push(String.fromCharCode.apply(String,i)),o=0);return s!=null?(o>0&&s.push(String.fromCharCode.apply(String,i.slice(0,o))),s.join("")):String.fromCharCode.apply(String,i.slice(0,o))}function sn(r,e,t){let n=t,s,i;for(let o=0;o<r.length;++o)s=r.charCodeAt(o),s<128?e[t++]=s:s<2048?(e[t++]=s>>6|192,e[t++]=s&63|128):(s&64512)===55296&&((i=r.charCodeAt(o+1))&64512)===56320?(s=65536+((s&1023)<<10)+(i&1023),++o,e[t++]=s>>18|240,e[t++]=s>>12&63|128,e[t++]=s>>6&63|128,e[t++]=s&63|128):(e[t++]=s>>12|224,e[t++]=s>>6&63|128,e[t++]=s&63|128);return t-n}function Z(r,e){return RangeError(`index out of range: ${r.pos} + ${e??1} > ${r.len}`)}function Vt(r,e){return(r[e-4]|r[e-3]<<8|r[e-2]<<16|r[e-1]<<24)>>>0}var on=class{buf;pos;len;_slice=Uint8Array.prototype.subarray;constructor(e){this.buf=e,this.pos=0,this.len=e.length}uint32(){let e=4294967295;if(e=(this.buf[this.pos]&127)>>>0,this.buf[this.pos++]<128||(e=(e|(this.buf[this.pos]&127)<<7)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<14)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<21)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&15)<<28)>>>0,this.buf[this.pos++]<128))return e;if((this.pos+=5)>this.len)throw this.pos=this.len,Z(this,10);return e}int32(){return this.uint32()|0}sint32(){let e=this.uint32();return e>>>1^-(e&1)|0}bool(){return this.uint32()!==0}fixed32(){if(this.pos+4>this.len)throw Z(this,4);return Vt(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw Z(this,4);return Vt(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw Z(this,4);let e=Rs(this.buf,this.pos);return this.pos+=4,e}double(){if(this.pos+8>this.len)throw Z(this,4);let e=Ns(this.buf,this.pos);return this.pos+=8,e}bytes(){let e=this.uint32(),t=this.pos,n=this.pos+e;if(n>this.len)throw Z(this,e);return this.pos+=e,t===n?new Uint8Array(0):this.buf.subarray(t,n)}string(){let e=this.bytes();return Us(e,0,e.length)}skip(e){if(typeof e=="number"){if(this.pos+e>this.len)throw Z(this,e);this.pos+=e}else do if(this.pos>=this.len)throw Z(this);while(this.buf[this.pos++]&128);return this}skipType(e){switch(e){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;(e=this.uint32()&7)!==4;)this.skipType(e);break;case 5:this.skip(4);break;default:throw Error(`invalid wire type ${e} at offset ${this.pos}`)}return this}readLongVarint(){let e=new j(0,0),t=0;if(this.len-this.pos>4){for(;t<4;++t)if(e.lo=(e.lo|(this.buf[this.pos]&127)<<t*7)>>>0,this.buf[this.pos++]<128)return e;if(e.lo=(e.lo|(this.buf[this.pos]&127)<<28)>>>0,e.hi=(e.hi|(this.buf[this.pos]&127)>>4)>>>0,this.buf[this.pos++]<128)return e;t=0}else{for(;t<3;++t){if(this.pos>=this.len)throw Z(this);if(e.lo=(e.lo|(this.buf[this.pos]&127)<<t*7)>>>0,this.buf[this.pos++]<128)return e}return e.lo=(e.lo|(this.buf[this.pos++]&127)<<t*7)>>>0,e}if(this.len-this.pos>4){for(;t<5;++t)if(e.hi=(e.hi|(this.buf[this.pos]&127)<<t*7+3)>>>0,this.buf[this.pos++]<128)return e}else for(;t<5;++t){if(this.pos>=this.len)throw Z(this);if(e.hi=(e.hi|(this.buf[this.pos]&127)<<t*7+3)>>>0,this.buf[this.pos++]<128)return e}throw Error("invalid varint encoding")}readFixed64(){if(this.pos+8>this.len)throw Z(this,8);let e=Vt(this.buf,this.pos+=4),t=Vt(this.buf,this.pos+=4);return new j(e,t)}int64(){return this.readLongVarint().toBigInt()}int64Number(){return this.readLongVarint().toNumber()}int64String(){return this.readLongVarint().toString()}uint64(){return this.readLongVarint().toBigInt(!0)}uint64Number(){let e=Fr(this.buf,this.pos);return this.pos+=v(e),e}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 an(r){return new on(r instanceof Uint8Array?r:r.subarray())}function xe(r,e,t){let n=an(r);return e.decode(n,void 0,t)}function cn(r){let e=r??8192,t=e>>>1,n,s=e;return function(o){if(o<1||o>t)return N(o);s+o>e&&(n=N(e),s=0);let a=n.subarray(s,s+=o);return s&7&&(s=(s|7)+1),a}}var Ee=class{fn;len;next;val;constructor(e,t,n){this.fn=e,this.len=t,this.next=void 0,this.val=n}};function ln(){}var hn=class{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}},ga=cn();function wa(r){return globalThis.Buffer!=null?N(r):ga(r)}var et=class{len;head;tail;states;constructor(){this.len=0,this.head=new Ee(ln,0,0),this.tail=this.head,this.states=null}_push(e,t,n){return this.tail=this.tail.next=new Ee(e,t,n),this.len+=t,this}uint32(e){return this.len+=(this.tail=this.tail.next=new fn((e=e>>>0)<128?1:e<16384?2:e<2097152?3:e<268435456?4:5,e)).len,this}int32(e){return e<0?this._push(Ht,10,j.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){let t=j.fromBigInt(e);return this._push(Ht,t.length(),t)}uint64Number(e){return this._push(Nr,v(e),e)}uint64String(e){return this.uint64(BigInt(e))}int64(e){return this.uint64(e)}int64Number(e){return this.uint64Number(e)}int64String(e){return this.uint64String(e)}sint64(e){let t=j.fromBigInt(e).zzEncode();return this._push(Ht,t.length(),t)}sint64Number(e){let t=j.fromNumber(e).zzEncode();return this._push(Ht,t.length(),t)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(un,1,e?1:0)}fixed32(e){return this._push(Ze,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){let t=j.fromBigInt(e);return this._push(Ze,4,t.lo)._push(Ze,4,t.hi)}fixed64Number(e){let t=j.fromNumber(e);return this._push(Ze,4,t.lo)._push(Ze,4,t.hi)}fixed64String(e){return this.fixed64(BigInt(e))}sfixed64(e){return this.fixed64(e)}sfixed64Number(e){return this.fixed64Number(e)}sfixed64String(e){return this.fixed64String(e)}float(e){return this._push(_s,4,e)}double(e){return this._push(Ps,8,e)}bytes(e){let t=e.length>>>0;return t===0?this._push(un,1,0):this.uint32(t)._push(ya,t,e)}string(e){let t=Ms(e);return t!==0?this.uint32(t)._push(sn,t,e):this._push(un,1,0)}fork(){return this.states=new hn(this),this.head=this.tail=new Ee(ln,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 Ee(ln,0,0),this.len=0),this}ldelim(){let e=this.head,t=this.tail,n=this.len;return this.reset().uint32(n),n!==0&&(this.tail.next=e.next,this.tail=t,this.len+=n),this}finish(){let e=this.head.next,t=wa(this.len),n=0;for(;e!=null;)e.fn(e.val,t,n),n+=e.len,e=e.next;return t}};function un(r,e,t){e[t]=r&255}function ba(r,e,t){for(;r>127;)e[t++]=r&127|128,r>>>=7;e[t]=r}var fn=class extends Ee{next;constructor(e,t){super(ba,e,t),this.next=void 0}};function Ht(r,e,t){for(;r.hi!==0;)e[t++]=r.lo&127|128,r.lo=(r.lo>>>7|r.hi<<25)>>>0,r.hi>>>=7;for(;r.lo>127;)e[t++]=r.lo&127|128,r.lo=r.lo>>>7;e[t++]=r.lo}function Ze(r,e,t){e[t]=r&255,e[t+1]=r>>>8&255,e[t+2]=r>>>16&255,e[t+3]=r>>>24}function ya(r,e,t){e.set(r,t)}globalThis.Buffer!=null&&(et.prototype.bytes=function(r){let e=r.length>>>0;return this.uint32(e),e>0&&this._push(xa,e,r),this},et.prototype.string=function(r){let e=globalThis.Buffer.byteLength(r);return this.uint32(e),e>0&&this._push(Ea,e,r),this});function xa(r,e,t){e.set(r,t)}function Ea(r,e,t){r.length<40?sn(r,e,t):e.utf8Write!=null?e.utf8Write(r,t):e.set(je(r),t)}function dn(){return new et}function ve(r,e){let t=dn();return e.encode(r,t,{lengthDelimited:!1}),t.finish()}var Ve;(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"})(Ve||(Ve={}));function Wt(r,e,t,n){return{name:r,type:e,encode:t,decode:n}}function qt(r){function e(s){if(r[s.toString()]==null)throw new Error("Invalid enum value");return r[s]}let t=function(i,o){let a=e(i);o.int32(a)},n=function(i){let o=i.int32();return e(o)};return Wt("enum",Ve.VARINT,t,n)}function Se(r,e){return Wt("message",Ve.LENGTH_DELIMITED,r,e)}var L;(function(r){r.WantBlock="WantBlock",r.WantHave="WantHave"})(L||(L={}));var pn;(function(r){r[r.WantBlock=0]="WantBlock",r[r.WantHave=1]="WantHave"})(pn||(pn={}));(function(r){r.codec=()=>qt(pn)})(L||(L={}));var $t;(function(r){let e;r.codec=()=>(e==null&&(e=Se((t,n,s={})=>{s.lengthDelimited!==!1&&n.fork(),t.cid!=null&&t.cid.byteLength>0&&(n.uint32(10),n.bytes(t.cid)),t.priority!=null&&t.priority!==0&&(n.uint32(16),n.int32(t.priority)),t.cancel!=null&&(n.uint32(24),n.bool(t.cancel)),t.wantType!=null&&(n.uint32(32),L.codec().encode(t.wantType,n)),t.sendDontHave!=null&&(n.uint32(40),n.bool(t.sendDontHave)),s.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let s={cid:O(0),priority:0},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let o=t.uint32();switch(o>>>3){case 1:{s.cid=t.bytes();break}case 2:{s.priority=t.int32();break}case 3:{s.cancel=t.bool();break}case 4:{s.wantType=L.codec().decode(t);break}case 5:{s.sendDontHave=t.bool();break}default:{t.skipType(o&7);break}}}return s})),e),r.encode=t=>ve(t,r.codec()),r.decode=t=>xe(t,r.codec())})($t||($t={}));var Gt;(function(r){let e;r.codec=()=>(e==null&&(e=Se((t,n,s={})=>{if(s.lengthDelimited!==!1&&n.fork(),t.entries!=null)for(let i of t.entries)n.uint32(10),$t.codec().encode(i,n);t.full!=null&&(n.uint32(16),n.bool(t.full)),s.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let s={entries:[]},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let o=t.uint32();switch(o>>>3){case 1:{s.entries.push($t.codec().decode(t,t.uint32()));break}case 2:{s.full=t.bool();break}default:{t.skipType(o&7);break}}}return s})),e),r.encode=t=>ve(t,r.codec()),r.decode=t=>xe(t,r.codec())})(Gt||(Gt={}));var jt;(function(r){let e;r.codec=()=>(e==null&&(e=Se((t,n,s={})=>{s.lengthDelimited!==!1&&n.fork(),t.prefix!=null&&t.prefix.byteLength>0&&(n.uint32(10),n.bytes(t.prefix)),t.data!=null&&t.data.byteLength>0&&(n.uint32(18),n.bytes(t.data)),s.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let s={prefix:O(0),data:O(0)},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let o=t.uint32();switch(o>>>3){case 1:{s.prefix=t.bytes();break}case 2:{s.data=t.bytes();break}default:{t.skipType(o&7);break}}}return s})),e),r.encode=t=>ve(t,r.codec()),r.decode=t=>xe(t,r.codec())})(jt||(jt={}));var Y;(function(r){r.HaveBlock="HaveBlock",r.DontHaveBlock="DontHaveBlock"})(Y||(Y={}));var Qt;(function(r){r[r.HaveBlock=0]="HaveBlock",r[r.DontHaveBlock=1]="DontHaveBlock"})(Qt||(Qt={}));(function(r){r.codec=()=>qt(Qt)})(Y||(Y={}));var Xt;(function(r){let e;r.codec=()=>(e==null&&(e=Se((t,n,s={})=>{s.lengthDelimited!==!1&&n.fork(),t.cid!=null&&t.cid.byteLength>0&&(n.uint32(10),n.bytes(t.cid)),t.type!=null&&Qt[t.type]!==0&&(n.uint32(16),Y.codec().encode(t.type,n)),s.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let s={cid:O(0),type:Y.HaveBlock},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let o=t.uint32();switch(o>>>3){case 1:{s.cid=t.bytes();break}case 2:{s.type=Y.codec().decode(t);break}default:{t.skipType(o&7);break}}}return s})),e),r.encode=t=>ve(t,r.codec()),r.decode=t=>xe(t,r.codec())})(Xt||(Xt={}));var tt;(function(r){let e;r.codec=()=>(e==null&&(e=Se((t,n,s={})=>{if(s.lengthDelimited!==!1&&n.fork(),t.wantlist!=null&&(n.uint32(10),Gt.codec().encode(t.wantlist,n)),t.blocks!=null)for(let i of t.blocks)n.uint32(26),jt.codec().encode(i,n);if(t.blockPresences!=null)for(let i of t.blockPresences)n.uint32(34),Xt.codec().encode(i,n);t.pendingBytes!=null&&t.pendingBytes!==0&&(n.uint32(40),n.int32(t.pendingBytes)),s.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let s={blocks:[],blockPresences:[],pendingBytes:0},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let o=t.uint32();switch(o>>>3){case 1:{s.wantlist=Gt.codec().decode(t,t.uint32());break}case 3:{s.blocks.push(jt.codec().decode(t,t.uint32()));break}case 4:{s.blockPresences.push(Xt.codec().decode(t,t.uint32()));break}case 5:{s.pendingBytes=t.int32();break}default:{t.skipType(o&7);break}}}return s})),e),r.encode=t=>ve(t,r.codec()),r.decode=t=>xe(t,r.codec())})(tt||(tt={}));Os.default.formatters.B=r=>r==null?"undefined":JSON.stringify({blocks:r.blocks?.map(e=>({data:`${E(e.data,"base64").substring(0,10)}...`,prefix:E(e.prefix,"base64")})),blockPresences:r.blockPresences?.map(e=>({...e,cid:T.decode(e.cid).toString()})),wantlist:r.wantlist==null?void 0:{full:r.wantlist.full,entries:r.wantlist.entries.map(e=>({...e,cid:T.decode(e.cid).toString()}))}},null,2);var Jt=class extends Ie{log;libp2p;routing;protocols;running;maxInboundStreams;maxOutboundStreams;messageReceiveTimeout;registrarIds;metrics;sendQueue;messageSendTimeout;runOnTransientConnections;constructor(e,t={}){super(),this.log=e.logger.forComponent("helia:bitswap:network"),this.libp2p=e.libp2p,this.routing=e.routing,this.protocols=t.protocols??[Ye],this.registrarIds=[],this.running=!1,this._onStream=this._onStream.bind(this),this.maxInboundStreams=t.maxInboundStreams??1024,this.maxOutboundStreams=t.maxOutboundStreams??1024,this.messageReceiveTimeout=t.messageReceiveTimeout??5e3,this.messageSendTimeout=t.messageSendTimeout??5e3,this.runOnTransientConnections=t.runOnTransientConnections??!1,e.metrics!=null&&(this.metrics={blocksSent:e.metrics?.registerMetricGroup("ipfs_bitswap_sent_blocks"),dataSent:e.metrics?.registerMetricGroup("ipfs_bitswap_sent_data_bytes")}),this.sendQueue=new Te({concurrency:t.messageSendConcurrency,metrics:e.metrics,metricName:"ipfs_bitswap_message_send_queue"}),this.sendQueue.addEventListener("error",n=>{this.log.error("error sending wantlist to peer",n.detail)})}async start(){if(this.running)return;this.running=!0,await this.libp2p.handle(this.protocols,this._onStream,{maxInboundStreams:this.maxInboundStreams,maxOutboundStreams:this.maxOutboundStreams,runOnTransientConnection:this.runOnTransientConnections});let e={onConnect:t=>{this.safeDispatchEvent("peer:connected",{detail:t})},onDisconnect:t=>{this.safeDispatchEvent("peer:disconnected",{detail:t})}};this.registrarIds=[];for(let t of this.protocols)this.registrarIds.push(await this.libp2p.register(t,e));this.libp2p.getConnections().forEach(t=>{this.safeDispatchEvent("peer:connected",{detail:t.remotePeer})})}async stop(){if(this.running=!1,await this.libp2p.unhandle(this.protocols),this.registrarIds!=null){for(let e of this.registrarIds)this.libp2p.unregister(e);this.registrarIds=[]}}_onStream(e){if(!this.running)return;let{stream:t,connection:n}=e;Promise.resolve().then(async()=>{this.log("incoming new bitswap %s stream from %p",t.protocol,n.remotePeer);let s=()=>{t.abort(new B("Incoming Bitswap stream timed out","ERR_TIMEOUT"))},i=AbortSignal.timeout(this.messageReceiveTimeout);te(1/0,i),i.addEventListener("abort",s),await Ke(t,o=>Je(o),async o=>{for await(let a of o)try{let c=tt.decode(a);this.log("incoming new bitswap %s message from %p %B",t.protocol,n.remotePeer,c),this.safeDispatchEvent("bitswap:message",{detail:{peer:n.remotePeer,message:c}}),i.removeEventListener("abort",s),i=AbortSignal.timeout(this.messageReceiveTimeout),te(1/0,i),i.addEventListener("abort",s)}catch(c){this.log.error("error reading incoming bitswap message from %p",n.remotePeer,c),t.abort(c);break}})}).catch(s=>{this.log.error("error handling incoming stream from %p",n.remotePeer,s),t.abort(s)})}async*findProviders(e,t){t?.onProgress?.(new be("bitswap:network:find-providers",e));for await(let n of this.routing.findProviders(e,t)){if(!this.runOnTransientConnections){let s=!1;for(let i of n.multiaddrs)if(i.getPeerId()==null&&(i=i.encapsulate(`/p2p/${n.id}`)),!fs.exactMatch(i)){s=!0;break}if(!s)continue}n.protocols?.includes("transport-bitswap")!==!1&&(yield n)}}async findAndConnect(e,t){await bs(Ts(we(this.findProviders(e,t),async n=>this.connectTo(n.id,t)),t?.maxProviders??3)).catch(n=>{this.log.error(n)})}async sendMessage(e,t,n){if(!this.running)throw new Error("network isn't running");let s={wantlist:{full:t.wantlist?.full??!1,entries:t.wantlist?.entries??[]},blocks:t.blocks??[],blockPresences:t.blockPresences??[],pendingBytes:t.pendingBytes??0},i=ut([AbortSignal.timeout(this.messageSendTimeout),n?.signal]);te(1/0,i);try{let o=this.sendQueue.find(e);if(o?.status==="queued"){o.options.message=Ca(o.options.message,s),await o.join({signal:i});return}await this.sendQueue.add(async a=>{let c=a?.message;if(c==null)throw new B("No message to send","ERR_NO_MESSAGE");this.log("sendMessage to %p %B",e,c),a?.onProgress?.(new be("bitswap:network:send-wantlist",e));let h=await this.libp2p.dialProtocol(e,Ye,a);try{let l=ks(h);await l.write(tt.encode(c),a),await l.unwrap().close(a)}catch(l){a?.onProgress?.(new be("bitswap:network:send-wantlist:error",{peer:e,error:l})),this.log.error("error sending message to %p",e,l),h.abort(l)}this._updateSentStats(e,c.blocks)},{peerId:e,signal:i,message:s})}finally{i.clear()}}async connectTo(e,t){if(!this.running)throw new B("Network isn't running","ERR_NOT_STARTED");t?.onProgress?.(new be("bitswap:network:dial",e));let[n]=await Promise.all([this.libp2p.dial(e,t),De(this.libp2p,"peer:identify",t?.signal,{filter:s=>{if(!s.detail.peerId.equals(e))return!1;if(s.detail.protocols.includes(Ye))return!0;throw new B(`${e} did not support ${Ye}`,"ERR_BITSWAP_UNSUPPORTED_BY_PEER")}})]);return n}_updateSentStats(e,t=[]){if(this.metrics!=null){let n=0;for(let s of t.values())n+=s.data.byteLength;this.metrics.dataSent.increment({global:n,[e.toString()]:n}),this.metrics.blocksSent.increment({global:t.length,[e.toString()]:t.length})}}};function Ca(r,e){let t=new Map((r.wantlist?.entries??[]).map(o=>[ce.encode(o.cid),o]));for(let o of e.wantlist?.entries??[]){let a=ce.encode(o.cid),c=t.get(a);c!=null&&(c.priority>o.priority&&(o.priority=c.priority),o.cancel=o.cancel??c.cancel,o.wantType=o.wantType??c.wantType,o.sendDontHave=o.sendDontHave??c.sendDontHave),t.set(a,o)}let n=new Map(r.blockPresences.map(o=>[ce.encode(o.cid),o]));for(let o of e.blockPresences){let a=ce.encode(o.cid);n.set(a,o)}let s=new Map(r.blocks.map(o=>[ce.encode(o.data),o]));for(let o of e.blocks){let a=ce.encode(o.data);s.set(a,o)}return{wantlist:{full:r.wantlist?.full??e.wantlist?.full??!1,entries:[...t.values()]},blockPresences:[...n.values()],blocks:[...s.values()],pendingBytes:r.pendingBytes+e.pendingBytes}}var Da=Symbol.for("nodejs.util.inspect.custom"),zs=Object.values(le).map(r=>r.decoder).reduce((r,e)=>r.or(e),le.identity.decoder),Vs=114,Hs=36,Ws=37,rt=class{type;multihash;privateKey;publicKey;string;constructor(e){this.type=e.type,this.multihash=e.multihash,this.privateKey=e.privateKey,Object.defineProperty(this,"string",{enumerable:!1,writable:!0})}get[Symbol.toStringTag](){return`PeerId(${this.toString()})`}[vn]=!0;toString(){return this.string==null&&(this.string=D.encode(this.multihash.bytes).slice(1)),this.string}toCID(){return T.createV1(Vs,this.multihash)}toBytes(){return this.multihash.bytes}toJSON(){return this.toString()}equals(e){if(e==null)return!1;if(e instanceof Uint8Array)return de(this.multihash.bytes,e);if(typeof e=="string")return ie(e).equals(this);if(e?.multihash?.bytes!=null)return de(this.multihash.bytes,e.multihash.bytes);throw new Error("not valid Id")}[Da](){return`PeerId(${this.toString()})`}},nt=class extends rt{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}},st=class extends rt{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.multihash.digest}},it=class extends rt{type="secp256k1";publicKey;constructor(e){super({...e,type:"secp256k1"}),this.publicKey=e.multihash.digest}};function ie(r,e){if(e=e??zs,r.charAt(0)==="1"||r.charAt(0)==="Q"){let t=he(D.decode(`z${r}`));return r.startsWith("12D")?new st({multihash:t}):r.startsWith("16U")?new it({multihash:t}):new nt({multihash:t})}return Ta(zs.decode(r))}function Ta(r){try{let e=he(r);if(e.code===St.code){if(e.digest.length===Hs)return new st({multihash:e});if(e.digest.length===Ws)return new it({multihash:e})}if(e.code===pe.code)return new nt({multihash:e})}catch{return _a(T.decode(r))}throw new Error("Supplied PeerID CID is invalid")}function _a(r){if(r==null||r.multihash==null||r.version==null||r.version===1&&r.code!==Vs)throw new Error("Supplied PeerID CID is invalid");let e=r.multihash;if(e.code===pe.code)return new nt({multihash:r.multihash});if(e.code===St.code){if(e.digest.length===Hs)return new st({multihash:r.multihash});if(e.digest.length===Ws)return new it({multihash:r.multihash})}throw new Error("Supplied PeerID CID is invalid")}function He(r,e){let t={[Symbol.iterator]:()=>t,next:()=>{let n=r.next(),s=n.value;return n.done===!0||s==null?{done:!0,value:void 0}:{done:!1,value:e(s)}}};return t}var ot=class{map;constructor(e){if(this.map=new Map,e!=null)for(let[t,n]of e.entries())this.map.set(t.toString(),n)}[Symbol.iterator](){return this.entries()}clear(){this.map.clear()}delete(e){return this.map.delete(e.toString())}entries(){return He(this.map.entries(),e=>[ie(e[0]),e[1]])}forEach(e){this.map.forEach((t,n)=>{e(t,ie(n),this)})}get(e){return this.map.get(e.toString())}has(e){return this.map.has(e.toString())}set(e,t){this.map.set(e.toString(),t)}keys(){return He(this.map.keys(),e=>ie(e))}values(){return this.map.values()}get size(){return this.map.size}};var Ae=class r{set;constructor(e){if(this.set=new Set,e!=null)for(let t of e)this.set.add(t.toString())}get size(){return this.set.size}[Symbol.iterator](){return this.values()}add(e){this.set.add(e.toString())}clear(){this.set.clear()}delete(e){this.set.delete(e.toString())}entries(){return He(this.set.entries(),e=>{let t=ie(e[0]);return[t,t]})}forEach(e){this.set.forEach(t=>{let n=ie(t);e(n,n,this)})}has(e){return this.set.has(e.toString())}values(){return He(this.set.values(),e=>ie(e))}intersection(e){let t=new r;for(let n of e)this.has(n)&&t.add(n);return t}difference(e){let t=new r;for(let n of this)e.has(n)||t.add(n);return t}union(e){let t=new r;for(let n of e)t.add(n);for(let n of this)t.add(n);return t}};var mn=class extends ot{metric;constructor(e){super();let{name:t,metrics:n}=e;this.metric=n.registerMetric(t),this.updateComponentMetric()}set(e,t){return super.set(e,t),this.updateComponentMetric(),this}delete(e){let t=super.delete(e);return this.updateComponentMetric(),t}clear(){super.clear(),this.updateComponentMetric()}updateComponentMetric(){this.metric.update(this.size)}};function at(r){let{name:e,metrics:t}=r,n;return t!=null?n=new mn({name:e,metrics:t}):n=new ot,n}function Ra(r){let e=new Uint8Array(r.reduce((n,s)=>n+v(s),0)),t=0;for(let n of r)e=J(n,e,t),t+=v(n);return e}var qs=Ra;function gn(r){return qs([r.version,r.code,r.multihash.code,r.multihash.digest.byteLength])}var Kt=class{peerId;blockstore;network;wants;exchangeCount;bytesSent;bytesReceived;lastExchange;maxSizeReplaceHasWithBlock;constructor(e,t){this.peerId=e.peerId,this.blockstore=e.blockstore,this.network=e.network,this.wants=new Map,this.exchangeCount=0,this.bytesSent=0,this.bytesReceived=0,this.maxSizeReplaceHasWithBlock=t.maxSizeReplaceHasWithBlock??1024}sentBytes(e){this.exchangeCount++,this.lastExchange=new Date().getTime(),this.bytesSent+=e}receivedBytes(e){this.exchangeCount++,this.lastExchange=new Date().getTime(),this.bytesReceived+=e}debtRatio(){return this.bytesSent/(this.bytesReceived+1)}async sendBlocksToPeer(e){let t={blockPresences:[],blocks:[]},n=new Set;for(let[s,i]of this.wants.entries()){if(!await this.blockstore.has(i.cid,e)){if(!i.sendDontHave||i.sentDontHave===!0)continue;i.sentDontHave=!0,t.blockPresences.push({cid:i.cid.bytes,type:Y.DontHaveBlock});continue}let a=await this.blockstore.get(i.cid,e);i.wantType===L.WantHave?a.byteLength<this.maxSizeReplaceHasWithBlock?(n.add(s),t.blocks.push({data:a,prefix:gn(i.cid)})):t.blockPresences.push({cid:i.cid.bytes,type:Y.HaveBlock}):(n.add(s),t.blocks.push({data:a,prefix:gn(i.cid)}))}if(t.blocks.length>0||t.blockPresences.length>0){await this.network.sendMessage(this.peerId,t,e),this.sentBytes(t.blocks.reduce((s,i)=>s+i.data.byteLength,0));for(let s of n)this.wants.delete(s)}}};var Yt=class{blockstore;network;ledgerMap;maxSizeReplaceHasWithBlock;log;constructor(e,t={}){this.blockstore=e.blockstore,this.network=e.network,this.maxSizeReplaceHasWithBlock=t.maxSizeReplaceHasWithBlock,this.log=e.logger.forComponent("helia:bitswap:peer-want-lists"),this.ledgerMap=at({name:"ipfs_bitswap_ledger_map",metrics:e.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(e){let t=this.ledgerMap.get(e);if(t!=null)return{peer:t.peerId,value:t.debtRatio(),sent:t.bytesSent,received:t.bytesReceived,exchanged:t.exchangeCount}}wantListForPeer(e){let t=this.ledgerMap.get(e);if(t!=null)return[...t.wants.values()]}peers(){return Array.from(this.ledgerMap.values()).map(e=>e.peerId)}async receiveMessage(e,t){let n=this.ledgerMap.get(e);if(n==null&&(n=new Kt({peerId:e,blockstore:this.blockstore,network:this.network},{maxSizeReplaceHasWithBlock:this.maxSizeReplaceHasWithBlock}),this.ledgerMap.set(e,n)),n.receivedBytes(t.blocks?.reduce((s,i)=>s+i.data.byteLength,0)??0),t.wantlist!=null){t.wantlist.full===!0&&n.wants.clear();for(let s of t.wantlist.entries){let i=T.decode(s.cid),o=E(i.multihash.bytes,"base64");s.cancel===!0?(this.log("peer %p cancelled want of block for %c",e,i),n.wants.delete(o)):(s.wantType===L.WantHave?this.log("peer %p wanted block presence for %c",e,i):this.log("peer %p wanted block for %c",e,i),n.wants.set(o,{cid:i,priority:s.priority,wantType:s.wantType??L.WantBlock,sendDontHave:s.sendDontHave??!1}))}}await n.sendBlocksToPeer()}async receivedBlock(e,t){let n=E(e.multihash.bytes,"base64"),s=[];for(let i of this.ledgerMap.values())i.wants.has(n)&&s.push(i);await Promise.all(s.map(async i=>i.sendBlocksToPeer(t)))}peerDisconnected(e){this.ledgerMap.delete(e)}};var wn=class{root;peers;log;wantList;network;queue;maxProviders;constructor(e,t){this.peers=new Ae,this.root=t.root,this.maxProviders=t.maxProviders,this.log=e.logger.forComponent(`helia:bitswap:session:${t.root}`),this.wantList=e.wantList,this.network=e.network,this.queue=new Te({concurrency:t.queryConcurrency}),this.queue.addEventListener("error",n=>{this.log.error("error querying peer for %c",this.root,n.detail)})}async want(e,t={}){if(this.peers.size===0)throw new B("Bitswap session had no peers","ERR_NO_SESSION_PEERS");this.log("sending WANT-BLOCK for %c to",e,this.peers);let n=await Promise.any([...this.peers].map(async s=>this.wantList.wantBlock(e,{peerId:s,...t})));return this.log("received block for %c from %p",e,n.sender),n.block}async findNewProviders(e,t,n={}){let s=P(),i=0;this.log("find %d-%d new provider(s) for %c",t,this.maxProviders,e);let o=zt([...this.wantList.peers.keys()],we(this.network.findProviders(e,n),a=>a.id));return Promise.resolve().then(async()=>{for await(let a of o)await this.queue.add(async()=>{try{if(this.log("asking potential session peer %p if they have %c",a,e),!(await this.wantList.wantPresence(e,{peerId:a,...n})).has){this.log("potential session peer %p did not have %c",a,e);return}this.log("potential session peer %p had %c",a,e),i++,this.peers.add(a),i===t&&(this.log("found %d session peers",i),s.resolve()),i===this.maxProviders&&(this.log("found max provider session peers",i),this.queue.clear())}catch(c){this.log.error("error querying potential session peer %p for %c",a,e,c.errors??c)}},{peerId:a});this.log("found %d session peers total",i),t>0&&s.reject(new B(`Found ${i} of ${t} providers`,"ERR_NO_PROVIDERS_FOUND"))}),s.promise}};async function $s(r,e){let t=new wn(r,e);return await t.findNewProviders(e.root,e.minProviders,{signal:e.signal}),t}var Zt=class{blocksReceived;duplicateBlocksReceived;dataReceived;duplicateDataReceived;constructor(e){this.blocksReceived=e.metrics?.registerMetricGroup("ipfs_bitswap_received_blocks"),this.duplicateBlocksReceived=e.metrics?.registerMetricGroup("ipfs_bitswap_duplicate_received_blocks"),this.dataReceived=e.metrics?.registerMetricGroup("ipfs_bitswap_data_received_bytes"),this.duplicateDataReceived=e.metrics?.registerMetricGroup("ipfs_bitswap_duplicate_data_received_bytes")}updateBlocksReceived(e=1,t){let n={global:e};t!=null&&(n[t.toString()]=e),this.blocksReceived?.increment(n)}updateDuplicateBlocksReceived(e=1,t){let n={global:e};t!=null&&(n[t.toString()]=e),this.duplicateBlocksReceived?.increment(n)}updateDataReceived(e,t){let n={global:e};t!=null&&(n[t.toString()]=e),this.dataReceived?.increment(n)}updateDuplicateDataReceived(e,t){let n={global:e};t!=null&&(n[t.toString()]=e),this.duplicateDataReceived?.increment(n)}};var bn=class extends Map{metric;constructor(e){super();let{name:t,metrics:n}=e;this.metric=n.registerMetric(t),this.updateComponentMetric()}set(e,t){return super.set(e,t),this.updateComponentMetric(),this}delete(e){let t=super.delete(e);return this.updateComponentMetric(),t}clear(){super.clear(),this.updateComponentMetric()}updateComponentMetric(){this.metric.update(this.size)}};function Gs(r){let{name:e,metrics:t}=r,n;return t!=null?n=new bn({name:e,metrics:t}):n=new Map,n}function Pa(r){return r[Symbol.asyncIterator]!=null}function Na(r){if(Pa(r))return(async()=>{let t=[];for await(let n of r)t.push(n);return t})();let e=[];for(let t of r)e.push(t);return e}var yn=Na;function Fa(r){return r[Symbol.asyncIterator]!=null}function Ma(r,e){if(Fa(r))return async function*(){for await(let a of r)await e(a)&&(yield a)}();let t=Ot(r),{value:n,done:s}=t.next();if(s===!0)return function*(){}();let i=e(n);if(typeof i.then=="function")return async function*(){await i&&(yield n);for await(let a of t)await e(a)&&(yield a)}();let o=e;return function*(){i===!0&&(yield n);for(let a of t)o(a)&&(yield a)}()}var er=Ma;function Ua(r){if(!(r instanceof Uint8Array))throw new Error("arg needs to be a Uint8Array");let e=[];for(;r.length>0;){let t=W(r);e.push(t),r=r.slice(v(t))}return e}var js=Ua;var tr=class{peers;wants;network;log;sendMessagesDelay;sendMessagesTimeout;hashLoader;constructor(e,t={}){this.peers=at({name:"ipfs_bitswap_peers",metrics:e.metrics}),this.wants=Gs({name:"ipfs_bitswap_wantlist",metrics:e.metrics}),this.network=e.network,this.sendMessagesDelay=t.sendMessagesDelay??10,this.log=e.logger.forComponent("helia:bitswap:wantlist"),this.hashLoader=t.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(e,t){let n=E(e.multihash.bytes,"base64"),s=this.wants.get(n);s==null&&(s={cid:e,session:new Ae,priority:t.priority??1,wantType:t.wantType??L.WantBlock,cancel:!1,sendDontHave:!0,blockWantListeners:[],blockPresenceListeners:[]},t.peerId!=null&&s.session.add(t.peerId),this.wants.set(n,s)),s.wantType===L.WantHave&&t.wantType===L.WantBlock&&(s.wantType=L.WantBlock),s.session.size>0&&(t.peerId!=null&&s.session.add(t.peerId),t.peerId==null&&s.session.clear());let i;if(t.wantType===L.WantBlock){let a=i=P();s.blockWantListeners.push(a)}else{let a=i=P();s.blockPresenceListeners.push(a)}let o=()=>{this.log("want for %c was aborted, cancelling want",e),s!=null&&(s.cancel=!0),i.reject(new ee("Want was aborted"))};t.signal?.addEventListener("abort",o),clearTimeout(this.sendMessagesTimeout),this.sendMessagesTimeout=setTimeout(()=>{this.sendMessages().catch(a=>{this.log("error sending messages to peers",a)})},this.sendMessagesDelay);try{return await i.promise}finally{t.signal?.removeEventListener("abort",o),t.wantType===L.WantBlock?s.blockWantListeners=s.blockWantListeners.filter(a=>a!==i):s.blockPresenceListeners=s.blockPresenceListeners.filter(a=>a!==i)}}async sendMessages(){for(let[e,t]of this.peers){let n=new Set,s={wantlist:{full:!1,entries:Ke(this.wants.entries(),i=>er(i,([o,a])=>{if(a.session.size>0&&!a.session.has(e))return!1;let c=t.has(o);return a.cancel?c:!c}),i=>we(i,([o,a])=>(n.add(o),{cid:a.cid.bytes,priority:a.priority,wantType:a.wantType,cancel:a.cancel,sendDontHave:a.sendDontHave})),i=>yn(i))}};if(s.wantlist?.entries.length===0)return;try{await this.network.sendMessage(e,s);for(let i of n)t.add(i)}catch(i){this.log.error("error sending full wantlist to new peer",i)}}for(let[e,t]of this.wants)if(t.cancel){this.wants.delete(e);for(let n of this.peers.values())n.delete(e)}}has(e){let t=E(e.multihash.bytes,"base64");return this.wants.has(t)}async wantPresence(e,t={}){if(t.peerId!=null&&this.peers.get(t.peerId)==null){let n=E(e.multihash.bytes,"base64");try{this.peers.set(t.peerId,new Set([n])),await this.network.sendMessage(t.peerId,{wantlist:{full:!1,entries:[{cid:e.bytes,sendDontHave:!0,wantType:L.WantHave,priority:1}]}})}catch(s){throw this.peers.delete(t.peerId),s}}return this.addEntry(e,{...t,wantType:L.WantHave})}async wantBlock(e,t={}){return this.addEntry(e,{...t,wantType:L.WantBlock})}async receiveMessage(e,t){this.log("received message from %p",e);let n=[],s=[];for(let i of t.blocks){if(i.prefix==null||i.data==null)continue;this.log("received block");let o=js(i.prefix),a=o[0],c=o[1],h=o[2],l=h===pe.code?pe:await this.hashLoader?.getHasher(h);if(l==null){this.log.error("unknown hash algorithm",h);continue}let u=await l.digest(i.data),f=T.create(a===0?0:1,c,u);this.log("received block from %p for %c",e,f),n.push({sender:e,cid:f,block:i.data}),s.push({sender:e,cid:f,has:!0})}for(let{cid:i,type:o}of t.blockPresences){let a=T.decode(i);this.log("received %s from %p for %c",o,e,a),s.push({sender:e,cid:a,has:o===Y.HaveBlock})}for(let i of n){let o=E(i.cid.multihash.bytes,"base64"),a=this.wants.get(o);if(a==null)return;let c=a.blockWantListeners;a.blockWantListeners=[],c.forEach(h=>{h.resolve(i)}),a.cancel=!0}for(let i of s){let o=E(i.cid.multihash.bytes,"base64"),a=this.wants.get(o);if(a==null)return;let c=a.blockPresenceListeners;a.blockPresenceListeners=[],c.forEach(h=>{h.resolve(i)})}}async peerConnected(e){let t=new Set,n={wantlist:{full:!0,entries:Ke(this.wants.entries(),s=>er(s,([i,o])=>!o.cancel&&o.session.size>0&&!o.session.has(e)),s=>er(s,([i,o])=>!o.cancel),s=>we(s,([i,o])=>(t.add(i),{cid:o.cid.bytes,priority:1,wantType:L.WantBlock,cancel:!1,sendDontHave:!1})),s=>yn(s))}};if(n.wantlist?.entries.length===0){this.peers.set(e,t);return}try{await this.network.sendMessage(e,n),this.peers.set(e,t)}catch(s){this.log.error("error sending full wantlist to new peer %p",e,s)}}peerDisconnected(e){this.peers.delete(e)}start(){}stop(){this.peers.clear()}};var rr=class{log;logger;stats;network;blockstore;peerWantLists;wantList;constructor(e,t={}){this.logger=e.logger,this.log=e.logger.forComponent("helia:bitswap"),this.blockstore=e.blockstore,this.stats=new Zt(e),this.network=new Jt(e,t),this.peerWantLists=new Yt({...e,network:this.network},t),this.wantList=new tr({...e,network:this.network},t)}async createSession(e,t){let n=t?.minProviders??1,s=t?.maxProviders??5;return $s({wantList:this.wantList,network:this.network,logger:this.logger},{root:e,queryConcurrency:t?.providerQueryConcurrency??5,minProviders:n,maxProviders:s,connectedPeers:t?.queryConnectedPeers!==!1?[...this.wantList.peers.keys()]:[],signal:t?.signal})}async want(e,t={}){let n=new AbortController;te(1/0,n.signal);let s=ut([n.signal,t.signal]);this.network.findAndConnect(e,{...t,signal:s}).catch(i=>{n.signal.aborted||this.log.error("error during finding and connect for cid %c",e,i)});try{return(await this.wantList.wantBlock(e,{...t,signal:s})).block}finally{n.abort(),s.clear()}}async notify(e,t,n={}){await this.peerWantLists.receivedBlock(e,n)}getWantlist(){return[...this.wantList.wants.values()].filter(e=>!e.cancel).map(e=>({cid:e.cid,priority:e.priority,wantType:e.wantType}))}getPeerWantlist(e){return this.peerWantLists.wantListForPeer(e)}async start(){this.wantList.start(),await this.network.start()}async stop(){this.wantList.stop(),await this.network.stop()}};var Va=(r,e={})=>new rr(r,e);return Zs(Ha);})();
|
|
2
|
+
"use strict";var HeliaBitswap=(()=>{var Yn=Object.create;var et=Object.defineProperty;var Zn=Object.getOwnPropertyDescriptor;var es=Object.getOwnPropertyNames;var ts=Object.getPrototypeOf,rs=Object.prototype.hasOwnProperty;var ne=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),P=(r,e)=>{for(var t in e)et(r,t,{get:e[t],enumerable:!0})},Vr=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of es(e))!rs.call(r,s)&&s!==t&&et(r,s,{get:()=>e[s],enumerable:!(n=Zn(e,s))||n.enumerable});return r};var tt=(r,e,t)=>(t=r!=null?Yn(ts(r)):{},Vr(e||!r||!r.__esModule?et(t,"default",{value:r,enumerable:!0}):t,r)),ns=r=>Vr(et({},"__esModule",{value:!0}),r);var Gr=ne((Zo,Wr)=>{var me=1e3,ge=me*60,we=ge*60,se=we*24,cs=se*7,ls=se*365.25;Wr.exports=function(r,e){e=e||{};var t=typeof r;if(t==="string"&&r.length>0)return us(r);if(t==="number"&&isFinite(r))return e.long?fs(r):hs(r);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(r))};function us(r){if(r=String(r),!(r.length>100)){var e=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(r);if(e){var t=parseFloat(e[1]),n=(e[2]||"ms").toLowerCase();switch(n){case"years":case"year":case"yrs":case"yr":case"y":return t*ls;case"weeks":case"week":case"w":return t*cs;case"days":case"day":case"d":return t*se;case"hours":case"hour":case"hrs":case"hr":case"h":return t*we;case"minutes":case"minute":case"mins":case"min":case"m":return t*ge;case"seconds":case"second":case"secs":case"sec":case"s":return t*me;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return t;default:return}}}}function hs(r){var e=Math.abs(r);return e>=se?Math.round(r/se)+"d":e>=we?Math.round(r/we)+"h":e>=ge?Math.round(r/ge)+"m":e>=me?Math.round(r/me)+"s":r+"ms"}function fs(r){var e=Math.abs(r);return e>=se?lt(r,e,se,"day"):e>=we?lt(r,e,we,"hour"):e>=ge?lt(r,e,ge,"minute"):e>=me?lt(r,e,me,"second"):r+" ms"}function lt(r,e,t,n){var s=e>=t*1.5;return Math.round(r/t)+" "+n+(s?"s":"")}});var Xr=ne((ea,$r)=>{function ds(r){t.debug=t,t.default=t,t.coerce=u,t.disable=i,t.enable=s,t.enabled=o,t.humanize=Gr(),t.destroy=g,Object.keys(r).forEach(p=>{t[p]=r[p]}),t.names=[],t.skips=[],t.formatters={};function e(p){let h=0;for(let v=0;v<p.length;v++)h=(h<<5)-h+p.charCodeAt(v),h|=0;return t.colors[Math.abs(h)%t.colors.length]}t.selectColor=e;function t(p){let h,v=null,a,l;function f(...x){if(!f.enabled)return;let d=f,m=Number(new Date),w=m-(h||m);d.diff=w,d.prev=h,d.curr=m,h=m,x[0]=t.coerce(x[0]),typeof x[0]!="string"&&x.unshift("%O");let b=0;x[0]=x[0].replace(/%([a-zA-Z%])/g,(S,y)=>{if(S==="%%")return"%";b++;let A=t.formatters[y];if(typeof A=="function"){let G=x[b];S=A.call(d,G),x.splice(b,1),b--}return S}),t.formatArgs.call(d,x),(d.log||t.log).apply(d,x)}return f.namespace=p,f.useColors=t.useColors(),f.color=t.selectColor(p),f.extend=n,f.destroy=t.destroy,Object.defineProperty(f,"enabled",{enumerable:!0,configurable:!1,get:()=>v!==null?v:(a!==t.namespaces&&(a=t.namespaces,l=t.enabled(p)),l),set:x=>{v=x}}),typeof t.init=="function"&&t.init(f),f}function n(p,h){let v=t(this.namespace+(typeof h>"u"?":":h)+p);return v.log=this.log,v}function s(p){t.save(p),t.namespaces=p,t.names=[],t.skips=[];let h,v=(typeof p=="string"?p:"").split(/[\s,]+/),a=v.length;for(h=0;h<a;h++)v[h]&&(p=v[h].replace(/\*/g,".*?"),p[0]==="-"?t.skips.push(new RegExp("^"+p.slice(1)+"$")):t.names.push(new RegExp("^"+p+"$")))}function i(){let p=[...t.names.map(c),...t.skips.map(c).map(h=>"-"+h)].join(",");return t.enable(""),p}function o(p){if(p[p.length-1]==="*")return!0;let h,v;for(h=0,v=t.skips.length;h<v;h++)if(t.skips[h].test(p))return!1;for(h=0,v=t.names.length;h<v;h++)if(t.names[h].test(p))return!0;return!1}function c(p){return p.toString().substring(2,p.toString().length-2).replace(/\.\*\?$/,"*")}function u(p){return p instanceof Error?p.stack||p.message:p}function g(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return t.enable(t.load()),t}$r.exports=ds});var Qr=ne((z,ut)=>{z.formatArgs=ms;z.save=gs;z.load=ws;z.useColors=ps;z.storage=bs();z.destroy=(()=>{let r=!1;return()=>{r||(r=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})();z.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function ps(){return typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs)?!0:typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)?!1:typeof document<"u"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&parseInt(RegExp.$1,10)>=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function ms(r){if(r[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+r[0]+(this.useColors?"%c ":" ")+"+"+ut.exports.humanize(this.diff),!this.useColors)return;let e="color: "+this.color;r.splice(1,0,e,"color: inherit");let t=0,n=0;r[0].replace(/%[a-zA-Z%]/g,s=>{s!=="%%"&&(t++,s==="%c"&&(n=t))}),r.splice(n,0,e)}z.log=console.debug||console.log||(()=>{});function gs(r){try{r?z.storage.setItem("debug",r):z.storage.removeItem("debug")}catch{}}function ws(){let r;try{r=z.storage.getItem("debug")}catch{}return!r&&typeof process<"u"&&"env"in process&&(r=process.env.DEBUG),r}function bs(){try{return localStorage}catch{}}ut.exports=Xr()(z);var{formatters:ys}=ut.exports;ys.j=function(r){try{return JSON.stringify(r)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}});var en=ne((ya,Zr)=>{"use strict";function Yr(r,e){for(let t in e)Object.defineProperty(r,t,{value:e[t],enumerable:!0,configurable:!0});return r}function Cs(r,e,t){if(!r||typeof r=="string")throw new TypeError("Please pass an Error to err-code");t||(t={}),typeof e=="object"&&(t=e,e=""),e&&(t.code=e);try{return Yr(r,t)}catch{t.message=r.message,t.stack=r.stack;let s=function(){};return s.prototype=Object.create(Object.getPrototypeOf(r)),Yr(new s,t)}}Zr.exports=Cs});var Wn=ne((Lu,qn)=>{qn.exports=function(r){if(!r)throw Error("hashlru must have a max value, of type number, greater than 0");var e=0,t=Object.create(null),n=Object.create(null);function s(i,o){t[i]=o,e++,e>=r&&(e=0,n=t,t=Object.create(null))}return{has:function(i){return t[i]!==void 0||n[i]!==void 0},remove:function(i){t[i]!==void 0&&(t[i]=void 0),n[i]!==void 0&&(n[i]=void 0)},get:function(i){var o=t[i];if(o!==void 0)return o;if((o=n[i])!==void 0)return s(i,o),o},set:function(i,o){t[i]!==void 0?t[i]=o:s(i,o)},clear:function(){t=Object.create(null),n=Object.create(null)}}}});var $n=ne((Je,Mt)=>{(function(r,e){"use strict";var t={version:"3.0.0",x86:{},x64:{},inputValidation:!0};function n(a){if(!Array.isArray(a)&&!ArrayBuffer.isView(a))return!1;for(var l=0;l<a.length;l++)if(!Number.isInteger(a[l])||a[l]<0||a[l]>255)return!1;return!0}function s(a,l){return(a&65535)*l+(((a>>>16)*l&65535)<<16)}function i(a,l){return a<<l|a>>>32-l}function o(a){return a^=a>>>16,a=s(a,2246822507),a^=a>>>13,a=s(a,3266489909),a^=a>>>16,a}function c(a,l){a=[a[0]>>>16,a[0]&65535,a[1]>>>16,a[1]&65535],l=[l[0]>>>16,l[0]&65535,l[1]>>>16,l[1]&65535];var f=[0,0,0,0];return f[3]+=a[3]+l[3],f[2]+=f[3]>>>16,f[3]&=65535,f[2]+=a[2]+l[2],f[1]+=f[2]>>>16,f[2]&=65535,f[1]+=a[1]+l[1],f[0]+=f[1]>>>16,f[1]&=65535,f[0]+=a[0]+l[0],f[0]&=65535,[f[0]<<16|f[1],f[2]<<16|f[3]]}function u(a,l){a=[a[0]>>>16,a[0]&65535,a[1]>>>16,a[1]&65535],l=[l[0]>>>16,l[0]&65535,l[1]>>>16,l[1]&65535];var f=[0,0,0,0];return f[3]+=a[3]*l[3],f[2]+=f[3]>>>16,f[3]&=65535,f[2]+=a[2]*l[3],f[1]+=f[2]>>>16,f[2]&=65535,f[2]+=a[3]*l[2],f[1]+=f[2]>>>16,f[2]&=65535,f[1]+=a[1]*l[3],f[0]+=f[1]>>>16,f[1]&=65535,f[1]+=a[2]*l[2],f[0]+=f[1]>>>16,f[1]&=65535,f[1]+=a[3]*l[1],f[0]+=f[1]>>>16,f[1]&=65535,f[0]+=a[0]*l[3]+a[1]*l[2]+a[2]*l[1]+a[3]*l[0],f[0]&=65535,[f[0]<<16|f[1],f[2]<<16|f[3]]}function g(a,l){return l%=64,l===32?[a[1],a[0]]:l<32?[a[0]<<l|a[1]>>>32-l,a[1]<<l|a[0]>>>32-l]:(l-=32,[a[1]<<l|a[0]>>>32-l,a[0]<<l|a[1]>>>32-l])}function p(a,l){return l%=64,l===0?a:l<32?[a[0]<<l|a[1]>>>32-l,a[1]<<l]:[a[1]<<l-32,0]}function h(a,l){return[a[0]^l[0],a[1]^l[1]]}function v(a){return a=h(a,[0,a[0]>>>1]),a=u(a,[4283543511,3981806797]),a=h(a,[0,a[0]>>>1]),a=u(a,[3301882366,444984403]),a=h(a,[0,a[0]>>>1]),a}t.x86.hash32=function(a,l){if(t.inputValidation&&!n(a))return e;l=l||0;for(var f=a.length%4,x=a.length-f,d=l,m=0,w=3432918353,b=461845907,E=0;E<x;E=E+4)m=a[E]|a[E+1]<<8|a[E+2]<<16|a[E+3]<<24,m=s(m,w),m=i(m,15),m=s(m,b),d^=m,d=i(d,13),d=s(d,5)+3864292196;switch(m=0,f){case 3:m^=a[E+2]<<16;case 2:m^=a[E+1]<<8;case 1:m^=a[E],m=s(m,w),m=i(m,15),m=s(m,b),d^=m}return d^=a.length,d=o(d),d>>>0},t.x86.hash128=function(a,l){if(t.inputValidation&&!n(a))return e;l=l||0;for(var f=a.length%16,x=a.length-f,d=l,m=l,w=l,b=l,E=0,S=0,y=0,A=0,G=597399067,je=2869860233,Ye=951274213,Ze=2716044179,L=0;L<x;L=L+16)E=a[L]|a[L+1]<<8|a[L+2]<<16|a[L+3]<<24,S=a[L+4]|a[L+5]<<8|a[L+6]<<16|a[L+7]<<24,y=a[L+8]|a[L+9]<<8|a[L+10]<<16|a[L+11]<<24,A=a[L+12]|a[L+13]<<8|a[L+14]<<16|a[L+15]<<24,E=s(E,G),E=i(E,15),E=s(E,je),d^=E,d=i(d,19),d+=m,d=s(d,5)+1444728091,S=s(S,je),S=i(S,16),S=s(S,Ye),m^=S,m=i(m,17),m+=w,m=s(m,5)+197830471,y=s(y,Ye),y=i(y,17),y=s(y,Ze),w^=y,w=i(w,15),w+=b,w=s(w,5)+2530024501,A=s(A,Ze),A=i(A,18),A=s(A,G),b^=A,b=i(b,13),b+=d,b=s(b,5)+850148119;switch(E=0,S=0,y=0,A=0,f){case 15:A^=a[L+14]<<16;case 14:A^=a[L+13]<<8;case 13:A^=a[L+12],A=s(A,Ze),A=i(A,18),A=s(A,G),b^=A;case 12:y^=a[L+11]<<24;case 11:y^=a[L+10]<<16;case 10:y^=a[L+9]<<8;case 9:y^=a[L+8],y=s(y,Ye),y=i(y,17),y=s(y,Ze),w^=y;case 8:S^=a[L+7]<<24;case 7:S^=a[L+6]<<16;case 6:S^=a[L+5]<<8;case 5:S^=a[L+4],S=s(S,je),S=i(S,16),S=s(S,Ye),m^=S;case 4:E^=a[L+3]<<24;case 3:E^=a[L+2]<<16;case 2:E^=a[L+1]<<8;case 1:E^=a[L],E=s(E,G),E=i(E,15),E=s(E,je),d^=E}return d^=a.length,m^=a.length,w^=a.length,b^=a.length,d+=m,d+=w,d+=b,m+=d,w+=d,b+=d,d=o(d),m=o(m),w=o(w),b=o(b),d+=m,d+=w,d+=b,m+=d,w+=d,b+=d,("00000000"+(d>>>0).toString(16)).slice(-8)+("00000000"+(m>>>0).toString(16)).slice(-8)+("00000000"+(w>>>0).toString(16)).slice(-8)+("00000000"+(b>>>0).toString(16)).slice(-8)},t.x64.hash128=function(a,l){if(t.inputValidation&&!n(a))return e;l=l||0;for(var f=a.length%16,x=a.length-f,d=[0,l],m=[0,l],w=[0,0],b=[0,0],E=[2277735313,289559509],S=[1291169091,658871167],y=0;y<x;y=y+16)w=[a[y+4]|a[y+5]<<8|a[y+6]<<16|a[y+7]<<24,a[y]|a[y+1]<<8|a[y+2]<<16|a[y+3]<<24],b=[a[y+12]|a[y+13]<<8|a[y+14]<<16|a[y+15]<<24,a[y+8]|a[y+9]<<8|a[y+10]<<16|a[y+11]<<24],w=u(w,E),w=g(w,31),w=u(w,S),d=h(d,w),d=g(d,27),d=c(d,m),d=c(u(d,[0,5]),[0,1390208809]),b=u(b,S),b=g(b,33),b=u(b,E),m=h(m,b),m=g(m,31),m=c(m,d),m=c(u(m,[0,5]),[0,944331445]);switch(w=[0,0],b=[0,0],f){case 15:b=h(b,p([0,a[y+14]],48));case 14:b=h(b,p([0,a[y+13]],40));case 13:b=h(b,p([0,a[y+12]],32));case 12:b=h(b,p([0,a[y+11]],24));case 11:b=h(b,p([0,a[y+10]],16));case 10:b=h(b,p([0,a[y+9]],8));case 9:b=h(b,[0,a[y+8]]),b=u(b,S),b=g(b,33),b=u(b,E),m=h(m,b);case 8:w=h(w,p([0,a[y+7]],56));case 7:w=h(w,p([0,a[y+6]],48));case 6:w=h(w,p([0,a[y+5]],40));case 5:w=h(w,p([0,a[y+4]],32));case 4:w=h(w,p([0,a[y+3]],24));case 3:w=h(w,p([0,a[y+2]],16));case 2:w=h(w,p([0,a[y+1]],8));case 1:w=h(w,[0,a[y]]),w=u(w,E),w=g(w,31),w=u(w,S),d=h(d,w)}return d=h(d,[0,a.length]),m=h(m,[0,a.length]),d=c(d,m),m=c(m,d),d=v(d),m=v(m),d=c(d,m),m=c(m,d),("00000000"+(d[0]>>>0).toString(16)).slice(-8)+("00000000"+(d[1]>>>0).toString(16)).slice(-8)+("00000000"+(m[0]>>>0).toString(16)).slice(-8)+("00000000"+(m[1]>>>0).toString(16)).slice(-8)},typeof Je<"u"?(typeof Mt<"u"&&Mt.exports&&(Je=Mt.exports=t),Je.murmurHash3=t):typeof define=="function"&&define.amd?define([],function(){return t}):(t._murmurHash3=r.murmurHash3,t.noConflict=function(){return r.murmurHash3=t._murmurHash3,t._murmurHash3=e,t.noConflict=e,t},r.murmurHash3=t)})(Je)});var Qn=ne((ju,Xn)=>{Xn.exports=$n()});var Lo={};P(Lo,{createBitswap:()=>So});var qr=Symbol.for("@libp2p/peer-id");var Z=class r extends Error{code;type;constructor(e="The operation was aborted"){super(e),this.name="AbortError",this.code=r.code,this.type=r.type}static code="ABORT_ERR";static type="aborted"},O=class extends Error{code;props;constructor(e,t,n){super(e),this.code=t,this.name=n?.name??"CodeError",this.props=n??{}}};var B=(r,...e)=>{try{[...e]}catch{}};var Q=class extends EventTarget{#e=new Map;constructor(){super(),B(1/0,this)}listenerCount(e){let t=this.#e.get(e);return t==null?0:t.length}addEventListener(e,t,n){super.addEventListener(e,t,n);let s=this.#e.get(e);s==null&&(s=[],this.#e.set(e,s)),s.push({callback:t,once:(n!==!0&&n!==!1&&n?.once)??!1})}removeEventListener(e,t,n){super.removeEventListener(e.toString(),t??null,n);let s=this.#e.get(e);s!=null&&(s=s.filter(({callback:i})=>i!==t),this.#e.set(e,s))}dispatchEvent(e){let t=super.dispatchEvent(e),n=this.#e.get(e.type);return n==null||(n=n.filter(({once:s})=>!s),this.#e.set(e.type,n)),t}safeDispatchEvent(e,t={}){return this.dispatchEvent(new ss(e,t))}},Ot=class extends Event{detail;constructor(e,t){super(e,t),this.detail=t?.detail}},ss=globalThis.CustomEvent??Ot;function rt(r){let e=new globalThis.AbortController;function t(){e.abort();for(let i of r)i?.removeEventListener!=null&&i.removeEventListener("abort",t)}for(let i of r){if(i?.aborted===!0){t();break}i?.addEventListener!=null&&i.addEventListener("abort",t)}function n(){for(let i of r)i?.removeEventListener!=null&&i.removeEventListener("abort",t)}let s=e.signal;return s.clear=n,s}function T(){let r={};return r.promise=new Promise((e,t)=>{r.resolve=e,r.reject=t}),r}var nt=class{buffer;mask;top;btm;next;constructor(e){if(!(e>0)||e-1&e)throw new Error("Max size for a FixedFIFO should be a power of two");this.buffer=new Array(e),this.mask=e-1,this.top=0,this.btm=0,this.next=null}push(e){return this.buffer[this.top]!==void 0?!1:(this.buffer[this.top]=e,this.top=this.top+1&this.mask,!0)}shift(){let e=this.buffer[this.btm];if(e!==void 0)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,e}isEmpty(){return this.buffer[this.btm]===void 0}},fe=class{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new nt(this.hwm),this.tail=this.head,this.size=0}calculateSize(e){return e?.byteLength!=null?e.byteLength:1}push(e){if(e?.value!=null&&(this.size+=this.calculateSize(e.value)),!this.head.push(e)){let t=this.head;this.head=t.next=new nt(2*this.head.buffer.length),this.head.push(e)}}shift(){let e=this.tail.shift();if(e===void 0&&this.tail.next!=null){let t=this.tail.next;this.tail.next=null,this.tail=t,e=this.tail.shift()}return e?.value!=null&&(this.size-=this.calculateSize(e.value)),e}isEmpty(){return this.head.isEmpty()}};var zt=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}};function de(r={}){return is(t=>{let n=t.shift();if(n==null)return{done:!0};if(n.error!=null)throw n.error;return{done:n.done===!0,value:n.value}},r)}function is(r,e){e=e??{};let t=e.onEnd,n=new fe,s,i,o,c=T(),u=async()=>{try{return n.isEmpty()?o?{done:!0}:await new Promise((x,d)=>{i=m=>{i=null,n.push(m);try{x(r(n))}catch(w){d(w)}return s}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{c.resolve(),c=T()})}},g=x=>i!=null?i(x):(n.push(x),s),p=x=>(n=new fe,i!=null?i({error:x}):(n.push({error:x}),s)),h=x=>{if(o)return s;if(e?.objectMode!==!0&&x?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return g({done:!1,value:x})},v=x=>o?s:(o=!0,x!=null?p(x):g({done:!0})),a=()=>(n=new fe,v(),{done:!0}),l=x=>(v(x),{done:!0});if(s={[Symbol.asyncIterator](){return this},next:u,return:a,throw:l,push:h,end:v,get readableLength(){return n.size},onEmpty:async x=>{let d=x?.signal;if(d?.throwIfAborted(),n.isEmpty())return;let m,w;d!=null&&(m=new Promise((b,E)=>{w=()=>{E(new zt)},d.addEventListener("abort",w)}));try{await Promise.race([c.promise,m])}finally{w!=null&&d!=null&&d?.removeEventListener("abort",w)}}},t==null)return s;let f=s;return s={[Symbol.asyncIterator](){return this},next(){return f.next()},throw(x){return f.throw(x),t!=null&&(t(x),t=void 0),{done:!0}},return(){return f.return(),t!=null&&(t(),t=void 0),{done:!0}},push:h,end(x){return f.end(x),t!=null&&(t(x),t=void 0),s},get readableLength(){return f.readableLength},onEmpty:x=>f.onEmpty(x)},s}var Ht=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.name="AbortError",this.code=t??"ABORT_ERR"}};async function $(r,e,t,n){let s=new Ht(n?.errorMessage,n?.errorCode);return t?.aborted===!0?Promise.reject(s):new Promise((i,o)=>{let c=g=>{try{if(n?.filter?.(g)===!1)return}catch(p){r.removeEventListener(e,c),t?.removeEventListener("abort",u),o(p);return}r.removeEventListener(e,c),t?.removeEventListener("abort",u),i(g)},u=()=>{r.removeEventListener(e,c),t?.removeEventListener("abort",u),o(s)};r.addEventListener(e,c),t?.addEventListener("abort",u)})}var st=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.name="AbortError",this.code=t??"ABORT_ERR"}};async function it(r,e,t){if(e==null)return r;if(e.aborted)return Promise.reject(new st(t?.errorMessage,t?.errorCode));let n,s=new st(t?.errorMessage,t?.errorCode);try{return await Promise.race([r,new Promise((i,o)=>{n=()=>{o(s)},e.addEventListener("abort",n)})])}finally{n!=null&&e.removeEventListener("abort",n)}}var ot=class{deferred;signal;where;constructor(e,t){this.signal=t,this.deferred=T(),this.where=e,this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(new Z)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function os(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var at=class{id;fn;options;priority;recipients;status;timeline;controller;constructor(e,t,n=0){this.id=os(),this.status="queued",this.fn=e,this.priority=n,this.options=t,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,B(1/0,this.controller.signal),this.onAbort=this.onAbort.bind(this)}abort(e){this.controller.abort(e)}onAbort(){this.recipients.reduce((t,n)=>t&&n.signal?.aborted===!0,!0)&&this.controller.abort(new Z)}async join(e={}){let t=new ot(new Error("where").stack,e.signal);return this.recipients.push(t),e.signal?.addEventListener("abort",this.onAbort),t.deferred.promise}async run(){this.status="running",this.timeline.started=Date.now();try{this.controller.signal.throwIfAborted();let e=await it(this.fn({...this.options??{},signal:this.controller.signal}),this.controller.signal);this.recipients.forEach(t=>{t.deferred.resolve(e)}),this.status="complete"}catch(e){this.recipients.forEach(t=>{t.deferred.reject(e)}),this.status="errored"}finally{this.timeline.finished=Date.now(),this.cleanup()}}cleanup(){this.recipients.forEach(e=>{e.signal?.removeEventListener("abort",this.onAbort)})}};function as(r,e,t){let n=0,s=r.length;for(;s>0;){let i=Math.trunc(s/2),o=n+i;t(r[o],e)<=0?(n=++o,s-=i+1):s=i}return n}var pe=class extends Q{concurrency;queue;pending;constructor(e={}){super(),this.concurrency=e.concurrency??Number.POSITIVE_INFINITY,this.pending=0,e.metricName!=null&&e.metrics?.registerMetricGroup(e.metricName,{calculate:()=>({size:this.queue.length,running:this.pending,queued:this.queue.length-this.pending})}),this.queue=[]}tryToStartAnother(){if(this.size===0)return queueMicrotask(()=>{this.safeDispatchEvent("empty")}),this.running===0&&queueMicrotask(()=>{this.safeDispatchEvent("idle")}),!1;if(this.pending<this.concurrency){let e;for(let t of this.queue)if(t.status==="queued"){e=t;break}return e==null?!1:(this.safeDispatchEvent("active"),this.pending++,e.run().finally(()=>{for(let t=0;t<this.queue.length;t++)if(this.queue[t]===e){this.queue.splice(t,1);break}this.pending--,this.tryToStartAnother(),this.safeDispatchEvent("next")}),!0)}return!1}enqueue(e){if(this.queue[this.size-1]?.priority>=e.priority){this.queue.push(e);return}let t=as(this.queue,e,(n,s)=>s.priority-n.priority);this.queue.splice(t,0,e)}async add(e,t){t?.signal?.throwIfAborted();let n=new at(e,t,t?.priority),s=n.join(t).then(i=>(this.safeDispatchEvent("completed",{detail:i}),this.safeDispatchEvent("success",{detail:{job:n,result:i}}),i)).catch(i=>{throw this.safeDispatchEvent("error",{detail:i}),this.safeDispatchEvent("failure",{detail:{job:n,error:i}}),i});return this.enqueue(n),this.safeDispatchEvent("add"),this.tryToStartAnother(),s}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(e=>{e.abort(new Z)}),this.clear()}async onEmpty(e){this.size!==0&&await $(this,"empty",e?.signal)}async onSizeLessThan(e,t){this.size<e||await $(this,"next",t?.signal,{filter:()=>this.size<e})}async onIdle(e){this.pending===0&&this.size===0||await $(this,"idle",e?.signal)}get size(){return this.queue.length}get queued(){return this.queue.length-this.pending}get running(){return this.pending}async*toGenerator(e){e?.signal?.throwIfAborted();let t=de({objectMode:!0}),n=u=>{u!=null?this.abort():this.clear(),t.end(u)},s=u=>{u.detail!=null&&t.push(u.detail)},i=u=>{n(u.detail)},o=()=>{n()},c=()=>{n(new O("Queue aborted","ERR_QUEUE_ABORTED"))};this.addEventListener("completed",s),this.addEventListener("error",i),this.addEventListener("idle",o),e?.signal?.addEventListener("abort",c);try{yield*t}finally{this.removeEventListener("completed",s),this.removeEventListener("error",i),this.removeEventListener("idle",o),e?.signal?.removeEventListener("abort",c),n()}}};var ct=class extends pe{has(e){return this.find(e)!=null}find(e){return this.queue.find(t=>e.equals(t.options.peerId))}};var Bn=tt(Qr(),1);function xs(r){return r[Symbol.asyncIterator]!=null}function Es(r){if(xs(r))return(async()=>{for await(let e of r);})();for(let e of r);}var Vt=Es;function R(r=0){return new Uint8Array(r)}function I(r=0){return new Uint8Array(r)}var vs=Math.pow(2,7),Ss=Math.pow(2,14),Ls=Math.pow(2,21),qt=Math.pow(2,28),Wt=Math.pow(2,35),Gt=Math.pow(2,42),$t=Math.pow(2,49),k=128,N=127;function _(r){if(r<vs)return 1;if(r<Ss)return 2;if(r<Ls)return 3;if(r<qt)return 4;if(r<Wt)return 5;if(r<Gt)return 6;if(r<$t)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function Xt(r,e,t=0){switch(_(r)){case 8:e[t++]=r&255|k,r/=128;case 7:e[t++]=r&255|k,r/=128;case 6:e[t++]=r&255|k,r/=128;case 5:e[t++]=r&255|k,r/=128;case 4:e[t++]=r&255|k,r>>>=7;case 3:e[t++]=r&255|k,r>>>=7;case 2:e[t++]=r&255|k,r>>>=7;case 1:{e[t++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return e}function As(r,e,t=0){switch(_(r)){case 8:e.set(t++,r&255|k),r/=128;case 7:e.set(t++,r&255|k),r/=128;case 6:e.set(t++,r&255|k),r/=128;case 5:e.set(t++,r&255|k),r/=128;case 4:e.set(t++,r&255|k),r>>>=7;case 3:e.set(t++,r&255|k),r>>>=7;case 2:e.set(t++,r&255|k),r>>>=7;case 1:{e.set(t++,r&255),r>>>=7;break}default:throw new Error("unreachable")}return e}function Qt(r,e){let t=r[e],n=0;if(n+=t&N,t<k||(t=r[e+1],n+=(t&N)<<7,t<k)||(t=r[e+2],n+=(t&N)<<14,t<k)||(t=r[e+3],n+=(t&N)<<21,t<k)||(t=r[e+4],n+=(t&N)*qt,t<k)||(t=r[e+5],n+=(t&N)*Wt,t<k)||(t=r[e+6],n+=(t&N)*Gt,t<k)||(t=r[e+7],n+=(t&N)*$t,t<k))return n;throw new RangeError("Could not decode varint")}function ks(r,e){let t=r.get(e),n=0;if(n+=t&N,t<k||(t=r.get(e+1),n+=(t&N)<<7,t<k)||(t=r.get(e+2),n+=(t&N)<<14,t<k)||(t=r.get(e+3),n+=(t&N)<<21,t<k)||(t=r.get(e+4),n+=(t&N)*qt,t<k)||(t=r.get(e+5),n+=(t&N)*Wt,t<k)||(t=r.get(e+6),n+=(t&N)*Gt,t<k)||(t=r.get(e+7),n+=(t&N)*$t,t<k))return n;throw new RangeError("Could not decode varint")}function be(r,e,t=0){return e==null&&(e=I(_(r))),e instanceof Uint8Array?Xt(r,e,t):As(r,e,t)}function ye(r,e=0){return r instanceof Uint8Array?Qt(r,e):ks(r,e)}function Kt(r,e){e==null&&(e=r.reduce((s,i)=>s+i.length,0));let t=I(e),n=0;for(let s of r)t.set(s,n),n+=s.length;return t}function J(r,e){if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return!1;return!0}var Kr=Symbol.for("@achingbrain/uint8arraylist");function Jr(r,e){if(e==null||e<0)throw new RangeError("index is out of bounds");let t=0;for(let n of r){let s=t+n.byteLength;if(e<s)return{buf:n,index:e-t};t=s}throw new RangeError("index is out of bounds")}function ht(r){return!!r?.[Kr]}var F=class r{bufs;length;[Kr]=!0;constructor(...e){this.bufs=[],this.length=0,e.length>0&&this.appendAll(e)}*[Symbol.iterator](){yield*this.bufs}get byteLength(){return this.length}append(...e){this.appendAll(e)}appendAll(e){let t=0;for(let n of e)if(n instanceof Uint8Array)t+=n.byteLength,this.bufs.push(n);else if(ht(n))t+=n.byteLength,this.bufs.push(...n.bufs);else throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");this.length+=t}prepend(...e){this.prependAll(e)}prependAll(e){let t=0;for(let n of e.reverse())if(n instanceof Uint8Array)t+=n.byteLength,this.bufs.unshift(n);else if(ht(n))t+=n.byteLength,this.bufs.unshift(...n.bufs);else throw new Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");this.length+=t}get(e){let t=Jr(this.bufs,e);return t.buf[t.index]}set(e,t){let n=Jr(this.bufs,e);n.buf[n.index]=t}write(e,t=0){if(e instanceof Uint8Array)for(let n=0;n<e.length;n++)this.set(t+n,e[n]);else if(ht(e))for(let n=0;n<e.length;n++)this.set(t+n,e.get(n));else throw new Error("Could not write value, must be an Uint8Array or a Uint8ArrayList")}consume(e){if(e=Math.trunc(e),!(Number.isNaN(e)||e<=0)){if(e===this.byteLength){this.bufs=[],this.length=0;return}for(;this.bufs.length>0;)if(e>=this.bufs[0].byteLength)e-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift();else{this.bufs[0]=this.bufs[0].subarray(e),this.length-=e;break}}}slice(e,t){let{bufs:n,length:s}=this._subList(e,t);return Kt(n,s)}subarray(e,t){let{bufs:n,length:s}=this._subList(e,t);return n.length===1?n[0]:Kt(n,s)}sublist(e,t){let{bufs:n,length:s}=this._subList(e,t),i=new r;return i.length=s,i.bufs=[...n],i}_subList(e,t){if(e=e??0,t=t??this.length,e<0&&(e=this.length+e),t<0&&(t=this.length+t),e<0||t>this.length)throw new RangeError("index is out of bounds");if(e===t)return{bufs:[],length:0};if(e===0&&t===this.length)return{bufs:this.bufs,length:this.length};let n=[],s=0;for(let i=0;i<this.bufs.length;i++){let o=this.bufs[i],c=s,u=c+o.byteLength;if(s=u,e>=u)continue;let g=e>=c&&e<u,p=t>c&&t<=u;if(g&&p){if(e===c&&t===u){n.push(o);break}let h=e-c;n.push(o.subarray(h,h+(t-e)));break}if(g){if(e===0){n.push(o);continue}n.push(o.subarray(e-c));continue}if(p){if(t===u){n.push(o);break}n.push(o.subarray(0,t-c));break}n.push(o)}return{bufs:n,length:t-e}}indexOf(e,t=0){if(!ht(e)&&!(e instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');let n=e instanceof Uint8Array?e:e.subarray();if(t=Number(t??0),isNaN(t)&&(t=0),t<0&&(t=this.length+t),t<0&&(t=0),e.length===0)return t>this.length?this.length:t;let s=n.byteLength;if(s===0)throw new TypeError("search must be at least 1 byte long");let i=256,o=new Int32Array(i);for(let h=0;h<i;h++)o[h]=-1;for(let h=0;h<s;h++)o[n[h]]=h;let c=o,u=this.byteLength-n.byteLength,g=n.byteLength-1,p;for(let h=t;h<=u;h+=p){p=0;for(let v=g;v>=0;v--){let a=this.get(h+v);if(n[v]!==a){p=Math.max(1,v-c[a]);break}}if(p===0)return h}return-1}getInt8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getInt8(0)}setInt8(e,t){let n=I(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt8(0,t),this.write(n,e)}getInt16(e,t){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt16(0,t)}setInt16(e,t,n){let s=R(2);new DataView(s.buffer,s.byteOffset,s.byteLength).setInt16(0,t,n),this.write(s,e)}getInt32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt32(0,t)}setInt32(e,t,n){let s=R(4);new DataView(s.buffer,s.byteOffset,s.byteLength).setInt32(0,t,n),this.write(s,e)}getBigInt64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigInt64(0,t)}setBigInt64(e,t,n){let s=R(8);new DataView(s.buffer,s.byteOffset,s.byteLength).setBigInt64(0,t,n),this.write(s,e)}getUint8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getUint8(0)}setUint8(e,t){let n=I(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint8(0,t),this.write(n,e)}getUint16(e,t){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint16(0,t)}setUint16(e,t,n){let s=R(2);new DataView(s.buffer,s.byteOffset,s.byteLength).setUint16(0,t,n),this.write(s,e)}getUint32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint32(0,t)}setUint32(e,t,n){let s=R(4);new DataView(s.buffer,s.byteOffset,s.byteLength).setUint32(0,t,n),this.write(s,e)}getBigUint64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigUint64(0,t)}setBigUint64(e,t,n){let s=R(8);new DataView(s.buffer,s.byteOffset,s.byteLength).setBigUint64(0,t,n),this.write(s,e)}getFloat32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat32(0,t)}setFloat32(e,t,n){let s=R(4);new DataView(s.buffer,s.byteOffset,s.byteLength).setFloat32(0,t,n),this.write(s,e)}getFloat64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat64(0,t)}setFloat64(e,t,n){let s=R(8);new DataView(s.buffer,s.byteOffset,s.byteLength).setFloat64(0,t,n),this.write(s,e)}equals(e){if(e==null||!(e instanceof r)||e.bufs.length!==this.bufs.length)return!1;for(let t=0;t<this.bufs.length;t++)if(!J(this.bufs[t],e.bufs[t]))return!1;return!0}static fromUint8Arrays(e,t){let n=new r;return n.bufs=e,t==null&&(t=e.reduce((s,i)=>s+i.byteLength,0)),n.length=t,n}};function ft(r){return r[Symbol.asyncIterator]!=null}var dt=r=>{let e=_(r),t=I(e);return be(r,t),dt.bytes=e,t};dt.bytes=0;function jr(r,e){e=e??{};let t=e.lengthEncoder??dt;function*n(s){let i=t(s.byteLength);i instanceof Uint8Array?yield i:yield*i,s instanceof Uint8Array?yield s:yield*s}return ft(r)?async function*(){for await(let s of r)yield*n(s)}():function*(){for(let s of r)yield*n(s)}()}jr.single=(r,e)=>{e=e??{};let t=e.lengthEncoder??dt;return new F(t(r.byteLength),r)};var xe=tt(en(),1);var Ds=8,_s=1024*1024*4,ie;(function(r){r[r.LENGTH=0]="LENGTH",r[r.DATA=1]="DATA"})(ie||(ie={}));var jt=r=>{let e=ye(r);return jt.bytes=_(e),e};jt.bytes=0;function Te(r,e){let t=new F,n=ie.LENGTH,s=-1,i=e?.lengthDecoder??jt,o=e?.maxLengthLength??Ds,c=e?.maxDataLength??_s;function*u(){for(;t.byteLength>0;){if(n===ie.LENGTH)try{if(s=i(t),s<0)throw(0,xe.default)(new Error("invalid message length"),"ERR_INVALID_MSG_LENGTH");if(s>c)throw(0,xe.default)(new Error("message length too long"),"ERR_MSG_DATA_TOO_LONG");let g=i.bytes;t.consume(g),e?.onLength!=null&&e.onLength(s),n=ie.DATA}catch(g){if(g instanceof RangeError){if(t.byteLength>o)throw(0,xe.default)(new Error("message length length too long"),"ERR_MSG_LENGTH_TOO_LONG");break}throw g}if(n===ie.DATA){if(t.byteLength<s)break;let g=t.sublist(0,s);t.consume(s),e?.onData!=null&&e.onData(g),yield g,n=ie.LENGTH}}}return ft(r)?async function*(){for await(let g of r)t.append(g),yield*u();if(t.byteLength>0)throw(0,xe.default)(new Error("unexpected end of input"),"ERR_UNEXPECTED_EOF")}():function*(){for(let g of r)t.append(g),yield*u();if(t.byteLength>0)throw(0,xe.default)(new Error("unexpected end of input"),"ERR_UNEXPECTED_EOF")}()}Te.fromReader=(r,e)=>{let t=1,n=async function*(){for(;;)try{let{done:i,value:o}=await r.next(t);if(i===!0)return;o!=null&&(yield o)}catch(i){if(i.code==="ERR_UNDER_READ")return{done:!0,value:null};throw i}finally{t=1}}();return Te(n,{...e??{},onLength:i=>{t=i}})};var Yt=class{readNext;haveNext;ended;nextResult;constructor(){this.ended=!1,this.readNext=T(),this.haveNext=T()}[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 e=this.nextResult;return this.nextResult=void 0,this.readNext.resolve(),this.readNext=T(),e}async throw(e){return this.ended=!0,e!=null&&this.haveNext.reject(e),{done:!0,value:void 0}}async return(){let e={done:!0,value:void 0};return await this._push(void 0),e}async push(e,t){await this._push(e,t)}async end(e,t){e!=null?await this.throw(e):await this._push(void 0,t)}async _push(e,t){if(e!=null&&this.ended)throw new Error("Cannot push value onto an ended pushable");if(this.nextResult!=null&&(await this.readNext.promise,this.nextResult!=null))throw new Error("NeedNext promise resolved but nextResult was not consumed");e!=null?this.nextResult={done:!1,value:e}:(this.ended=!0,this.nextResult={done:!0,value:void 0}),this.haveNext.resolve(),this.haveNext=T(),await it(this.readNext.promise,t?.signal,t)}};function tn(){return new Yt}var pt=class extends Error{code;constructor(e,t){super(e),this.code=t}},Zt=class extends pt{type;constructor(e){super(e,"ABORT_ERR"),this.type="aborted"}};function rn(r,e){let t=tn();r.sink(t).catch(async o=>{await t.end(o)}),r.sink=async o=>{for await(let c of o)await t.push(c);await t.end()};let n=r.source;r.source[Symbol.iterator]!=null?n=r.source[Symbol.iterator]():r.source[Symbol.asyncIterator]!=null&&(n=r.source[Symbol.asyncIterator]());let s=new F;return{read:async(o,c)=>{c?.signal?.throwIfAborted();let u,g=new Promise((p,h)=>{u=()=>{h(new Zt("Read aborted"))},c?.signal?.addEventListener("abort",u)});try{if(o==null){let{done:h,value:v}=await Promise.race([n.next(),g]);return h===!0?new F:v}for(;s.byteLength<o;){let{value:h,done:v}=await Promise.race([n.next(),g]);if(v===!0)throw new pt("unexpected end of input","ERR_UNEXPECTED_EOF");s.append(h)}let p=s.sublist(0,o);return s.consume(o),p}finally{u!=null&&c?.signal?.removeEventListener("abort",u)}},write:async(o,c)=>{c?.signal?.throwIfAborted(),o instanceof Uint8Array?await t.push(o,c):await t.push(o.subarray(),c)},unwrap:()=>{if(s.byteLength>0){let o=r.source;r.source=async function*(){e?.yieldBytes===!1?yield s:yield*s,yield*o}()}return r}}}var mt=class extends Error{code;constructor(e,t){super(e),this.code=t}};function nn(r,e={}){let t=rn(r,e);e.maxDataLength!=null&&e.maxLengthLength==null&&(e.maxLengthLength=_(e.maxDataLength));let n=e?.lengthDecoder??ye,s=e?.lengthEncoder??be;return{read:async o=>{let c=-1,u=new F;for(;;){u.append(await t.read(1,o));try{c=n(u)}catch(g){if(g instanceof RangeError)continue;throw g}if(e?.maxLengthLength!=null&&u.byteLength>e.maxLengthLength)throw new mt("message length length too long","ERR_MSG_LENGTH_TOO_LONG");if(c>-1)break}if(e?.maxDataLength!=null&&c>e.maxDataLength)throw new mt("message length too long","ERR_MSG_DATA_TOO_LONG");return t.read(c,o)},write:async(o,c)=>{await t.write(new F(s(o.byteLength),o),c)},writeV:async(o,c)=>{let u=new F(...o.flatMap(g=>[s(g.byteLength),g]));await t.write(u,c)},unwrap:()=>t.unwrap()}}function Rs(r){let[e,t]=r[Symbol.asyncIterator]!=null?[r[Symbol.asyncIterator](),Symbol.asyncIterator]:[r[Symbol.iterator](),Symbol.iterator],n=[];return{peek:()=>e.next(),push:s=>{n.push(s)},next:()=>n.length>0?{done:!1,value:n.shift()}:e.next(),[t](){return this}}}var gt=Rs;function Is(r){return r[Symbol.asyncIterator]!=null}function Ns(r,e){if(Is(r))return async function*(){for await(let c of r)yield e(c)}();let t=gt(r),{value:n,done:s}=t.next();if(s===!0)return function*(){}();let i=e(n);if(typeof i.then=="function")return async function*(){yield await i;for await(let c of t)yield e(c)}();let o=e;return function*(){yield i;for(let c of t)yield o(c)}()}var Re=Ns;function Ms(r){return r[Symbol.asyncIterator]!=null}function Fs(...r){let e=[];for(let t of r)Ms(t)||e.push(t);return e.length===r.length?function*(){for(let t of e)yield*t}():async function*(){let t=de({objectMode:!0});Promise.resolve().then(async()=>{try{await Promise.all(r.map(async n=>{for await(let s of n)t.push(s)})),t.end()}catch(n){t.end(n)}}),yield*t}()}var sn=Fs;function Ie(r,...e){if(r==null)throw new Error("Empty pipeline");if(er(r)){let n=r;r=()=>n.source}else if(an(r)||on(r)){let n=r;r=()=>n}let t=[r,...e];if(t.length>1&&er(t[t.length-1])&&(t[t.length-1]=t[t.length-1].sink),t.length>2)for(let n=1;n<t.length-1;n++)er(t[n])&&(t[n]=Bs(t[n]));return Us(...t)}var Us=(...r)=>{let e;for(;r.length>0;)e=r.shift()(e);return e},on=r=>r?.[Symbol.asyncIterator]!=null,an=r=>r?.[Symbol.iterator]!=null,er=r=>r==null?!1:r.sink!=null&&r.source!=null,Bs=r=>e=>{let t=r.sink(e);if(t?.then!=null){let n=de({objectMode:!0});t.then(()=>{n.end()},o=>{n.end(o)});let s,i=r.source;if(on(i))s=async function*(){yield*i,n.end()};else if(an(i))s=function*(){yield*i,n.end()};else throw new Error("Unknown duplex source type - must be Iterable or AsyncIterable");return sn(n,s())}return r.source};function Ps(r){return r[Symbol.asyncIterator]!=null}function Os(r,e){return Ps(r)?async function*(){let t=0;if(!(e<1)){for await(let n of r)if(yield n,t++,t===e)return}}():function*(){let t=0;if(!(e<1)){for(let n of r)if(yield n,t++,t===e)return}}()}var cn=Os;var ir={};P(ir,{base64:()=>K,base64pad:()=>Gs,base64url:()=>$s,base64urlpad:()=>Xs});var Wa=new Uint8Array(0);function ln(r,e){if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return!1;return!0}function Y(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 un(r){return new TextEncoder().encode(r)}function hn(r){return new TextDecoder().decode(r)}function zs(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),n=0;n<t.length;n++)t[n]=255;for(var s=0;s<r.length;s++){var i=r.charAt(s),o=i.charCodeAt(0);if(t[o]!==255)throw new TypeError(i+" is ambiguous");t[o]=s}var c=r.length,u=r.charAt(0),g=Math.log(c)/Math.log(256),p=Math.log(256)/Math.log(c);function h(l){if(l instanceof Uint8Array||(ArrayBuffer.isView(l)?l=new Uint8Array(l.buffer,l.byteOffset,l.byteLength):Array.isArray(l)&&(l=Uint8Array.from(l))),!(l instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(l.length===0)return"";for(var f=0,x=0,d=0,m=l.length;d!==m&&l[d]===0;)d++,f++;for(var w=(m-d)*p+1>>>0,b=new Uint8Array(w);d!==m;){for(var E=l[d],S=0,y=w-1;(E!==0||S<x)&&y!==-1;y--,S++)E+=256*b[y]>>>0,b[y]=E%c>>>0,E=E/c>>>0;if(E!==0)throw new Error("Non-zero carry");x=S,d++}for(var A=w-x;A!==w&&b[A]===0;)A++;for(var G=u.repeat(f);A<w;++A)G+=r.charAt(b[A]);return G}function v(l){if(typeof l!="string")throw new TypeError("Expected String");if(l.length===0)return new Uint8Array;var f=0;if(l[f]!==" "){for(var x=0,d=0;l[f]===u;)x++,f++;for(var m=(l.length-f)*g+1>>>0,w=new Uint8Array(m);l[f];){var b=t[l.charCodeAt(f)];if(b===255)return;for(var E=0,S=m-1;(b!==0||E<d)&&S!==-1;S--,E++)b+=c*w[S]>>>0,w[S]=b%256>>>0,b=b/256>>>0;if(b!==0)throw new Error("Non-zero carry");d=E,f++}if(l[f]!==" "){for(var y=m-d;y!==m&&w[y]===0;)y++;for(var A=new Uint8Array(x+(m-y)),G=x;y!==m;)A[G++]=w[y++];return A}}}function a(l){var f=v(l);if(f)return f;throw new Error(`Non-${e} character`)}return{encode:h,decodeUnsafe:v,decode:a}}var Hs=zs,Vs=Hs,dn=Vs;var tr=class{name;prefix;baseEncode;constructor(e,t,n){this.name=e,this.prefix=t,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},rr=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,n){if(this.name=e,this.prefix=t,t.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=t.codePointAt(0),this.baseDecode=n}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return pn(this,e)}},nr=class{decoders;constructor(e){this.decoders=e}or(e){return pn(this,e)}decode(e){let t=e[0],n=this.decoders[t];if(n!=null)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function pn(r,e){return new nr({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var sr=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,n,s){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=s,this.encoder=new tr(e,t,n),this.decoder=new rr(e,t,s)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function Ee({name:r,prefix:e,encode:t,decode:n}){return new sr(r,e,t,n)}function ee({name:r,prefix:e,alphabet:t}){let{encode:n,decode:s}=dn(t,r);return Ee({prefix:e,name:r,encode:n,decode:i=>Y(s(i))})}function qs(r,e,t,n){let s={};for(let p=0;p<e.length;++p)s[e[p]]=p;let i=r.length;for(;r[i-1]==="=";)--i;let o=new Uint8Array(i*t/8|0),c=0,u=0,g=0;for(let p=0;p<i;++p){let h=s[r[p]];if(h===void 0)throw new SyntaxError(`Non-${n} character`);u=u<<t|h,c+=t,c>=8&&(c-=8,o[g++]=255&u>>c)}if(c>=t||255&u<<8-c)throw new SyntaxError("Unexpected end of data");return o}function Ws(r,e,t){let n=e[e.length-1]==="=",s=(1<<t)-1,i="",o=0,c=0;for(let u=0;u<r.length;++u)for(c=c<<8|r[u],o+=8;o>t;)o-=t,i+=e[s&c>>o];if(o!==0&&(i+=e[s&c<<t-o]),n)for(;i.length*t&7;)i+="=";return i}function C({name:r,prefix:e,bitsPerChar:t,alphabet:n}){return Ee({prefix:e,name:r,encode(s){return Ws(s,n,t)},decode(s){return qs(s,n,t,r)}})}var K=C({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Gs=C({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),$s=C({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Xs=C({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var or={};P(or,{base32:()=>ve,base32hex:()=>js,base32hexpad:()=>Zs,base32hexpadupper:()=>ei,base32hexupper:()=>Ys,base32pad:()=>Js,base32padupper:()=>Ks,base32upper:()=>Qs,base32z:()=>ti});var ve=C({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Qs=C({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Js=C({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Ks=C({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),js=C({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Ys=C({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Zs=C({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),ei=C({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),ti=C({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var ar={};P(ar,{base58btc:()=>H,base58flickr:()=>ri});var H=ee({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),ri=ee({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var ni=wn,mn=128,si=127,ii=~si,oi=Math.pow(2,31);function wn(r,e,t){e=e||[],t=t||0;for(var n=t;r>=oi;)e[t++]=r&255|mn,r/=128;for(;rⅈ)e[t++]=r&255|mn,r>>>=7;return e[t]=r|0,wn.bytes=t-n+1,e}var ai=cr,ci=128,gn=127;function cr(r,n){var t=0,n=n||0,s=0,i=n,o,c=r.length;do{if(i>=c)throw cr.bytes=0,new RangeError("Could not decode varint");o=r[i++],t+=s<28?(o&gn)<<s:(o&gn)*Math.pow(2,s),s+=7}while(o>=ci);return cr.bytes=i-n,t}var li=Math.pow(2,7),ui=Math.pow(2,14),hi=Math.pow(2,21),fi=Math.pow(2,28),di=Math.pow(2,35),pi=Math.pow(2,42),mi=Math.pow(2,49),gi=Math.pow(2,56),wi=Math.pow(2,63),bi=function(r){return r<li?1:r<ui?2:r<hi?3:r<fi?4:r<di?5:r<pi?6:r<mi?7:r<gi?8:r<wi?9:10},yi={encode:ni,decode:ai,encodingLength:bi},xi=yi,Ne=xi;function Me(r,e=0){return[Ne.decode(r,e),Ne.decode.bytes]}function Se(r,e,t=0){return Ne.encode(r,e,t),e}function Le(r){return Ne.encodingLength(r)}function te(r,e){let t=e.byteLength,n=Le(r),s=n+Le(t),i=new Uint8Array(s+t);return Se(r,i,0),Se(t,i,n),i.set(e,s),new Ae(r,t,e,i)}function Fe(r){let e=Y(r),[t,n]=Me(e),[s,i]=Me(e.subarray(n)),o=e.subarray(n+i);if(o.byteLength!==s)throw new Error("Incorrect length");return new Ae(t,s,o,e)}function bn(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&ln(r.bytes,t.bytes)}}var Ae=class{code;size;digest;bytes;constructor(e,t,n,s){this.code=e,this.size=t,this.digest=n,this.bytes=s}};function yn(r,e){let{bytes:t,version:n}=r;switch(n){case 0:return vi(t,lr(r),e??H.encoder);default:return Si(t,lr(r),e??ve.encoder)}}var xn=new WeakMap;function lr(r){let e=xn.get(r);if(e==null){let t=new Map;return xn.set(r,t),t}return e}var U=class r{code;version;multihash;bytes;"/";constructor(e,t,n,s){this.code=t,this.version=e,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:e,multihash:t}=this;if(e!==Ue)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==Li)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return r.createV0(t)}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:e,digest:t}=this.multihash,n=te(e,t);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(e){return r.equals(this,e)}static equals(e,t){let n=t;return n!=null&&e.code===n.code&&e.version===n.version&&bn(e.multihash,n.multihash)}toString(e){return yn(this,e)}toJSON(){return{"/":yn(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(e){if(e==null)return null;let t=e;if(t instanceof r)return t;if(t["/"]!=null&&t["/"]===t.bytes||t.asCID===t){let{version:n,code:s,multihash:i,bytes:o}=t;return new r(n,s,i,o??En(n,s,i.bytes))}else if(t[Ai]===!0){let{version:n,multihash:s,code:i}=t,o=Fe(s);return r.create(n,i,o)}else return null}static create(e,t,n){if(typeof t!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(e){case 0:{if(t!==Ue)throw new Error(`Version 0 CID must use dag-pb (code: ${Ue}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let s=En(e,t,n.bytes);return new r(e,t,n,s)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,Ue,e)}static createV1(e,t){return r.create(1,e,t)}static decode(e){let[t,n]=r.decodeFirst(e);if(n.length!==0)throw new Error("Incorrect length");return t}static decodeFirst(e){let t=r.inspectBytes(e),n=t.size-t.multihashSize,s=Y(e.subarray(n,n+t.multihashSize));if(s.byteLength!==t.multihashSize)throw new Error("Incorrect length");let i=s.subarray(t.multihashSize-t.digestSize),o=new Ae(t.multihashCode,t.digestSize,i,s);return[t.version===0?r.createV0(o):r.createV1(t.codec,o),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[h,v]=Me(e.subarray(t));return t+=v,h},s=n(),i=Ue;if(s===18?(s=0,t=0):i=n(),s!==0&&s!==1)throw new RangeError(`Invalid CID version ${s}`);let o=t,c=n(),u=n(),g=t+u,p=g-o;return{version:s,codec:i,multihashCode:c,digestSize:u,multihashSize:p,size:g}}static parse(e,t){let[n,s]=Ei(e,t),i=r.decode(s);if(i.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return lr(i).set(n,e),i}};function Ei(r,e){switch(r[0]){case"Q":{let t=e??H;return[H.prefix,t.decode(`${H.prefix}${r}`)]}case H.prefix:{let t=e??H;return[H.prefix,t.decode(r)]}case ve.prefix:{let t=e??ve;return[ve.prefix,t.decode(r)]}default:{if(e==null)throw Error("To parse non base32 or base58btc encoded CID multibase decoder must be provided");return[r[0],e.decode(r)]}}}function vi(r,e,t){let{prefix:n}=t;if(n!==H.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let s=e.get(n);if(s==null){let i=t.encode(r).slice(1);return e.set(n,i),i}else return s}function Si(r,e,t){let{prefix:n}=t,s=e.get(n);if(s==null){let i=t.encode(r);return e.set(n,i),i}else return s}var Ue=112,Li=18;function En(r,e,t){let n=Le(r),s=n+Le(e),i=new Uint8Array(s+t.byteLength);return Se(r,i,0),Se(e,i,n),i.set(t,s),i}var Ai=Symbol.for("@ipld/js-cid/CID");var j=class extends Event{constructor(e,t){super(e),this.detail=t}};var ur={};P(ur,{base10:()=>ki});var ki=ee({prefix:"9",name:"base10",alphabet:"0123456789"});var hr={};P(hr,{base16:()=>Ci,base16upper:()=>Di});var Ci=C({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),Di=C({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var fr={};P(fr,{base2:()=>_i});var _i=C({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var dr={};P(dr,{base256emoji:()=>Mi});var vn=Array.from("\u{1F680}\u{1FA90}\u2604\u{1F6F0}\u{1F30C}\u{1F311}\u{1F312}\u{1F313}\u{1F314}\u{1F315}\u{1F316}\u{1F317}\u{1F318}\u{1F30D}\u{1F30F}\u{1F30E}\u{1F409}\u2600\u{1F4BB}\u{1F5A5}\u{1F4BE}\u{1F4BF}\u{1F602}\u2764\u{1F60D}\u{1F923}\u{1F60A}\u{1F64F}\u{1F495}\u{1F62D}\u{1F618}\u{1F44D}\u{1F605}\u{1F44F}\u{1F601}\u{1F525}\u{1F970}\u{1F494}\u{1F496}\u{1F499}\u{1F622}\u{1F914}\u{1F606}\u{1F644}\u{1F4AA}\u{1F609}\u263A\u{1F44C}\u{1F917}\u{1F49C}\u{1F614}\u{1F60E}\u{1F607}\u{1F339}\u{1F926}\u{1F389}\u{1F49E}\u270C\u2728\u{1F937}\u{1F631}\u{1F60C}\u{1F338}\u{1F64C}\u{1F60B}\u{1F497}\u{1F49A}\u{1F60F}\u{1F49B}\u{1F642}\u{1F493}\u{1F929}\u{1F604}\u{1F600}\u{1F5A4}\u{1F603}\u{1F4AF}\u{1F648}\u{1F447}\u{1F3B6}\u{1F612}\u{1F92D}\u2763\u{1F61C}\u{1F48B}\u{1F440}\u{1F62A}\u{1F611}\u{1F4A5}\u{1F64B}\u{1F61E}\u{1F629}\u{1F621}\u{1F92A}\u{1F44A}\u{1F973}\u{1F625}\u{1F924}\u{1F449}\u{1F483}\u{1F633}\u270B\u{1F61A}\u{1F61D}\u{1F634}\u{1F31F}\u{1F62C}\u{1F643}\u{1F340}\u{1F337}\u{1F63B}\u{1F613}\u2B50\u2705\u{1F97A}\u{1F308}\u{1F608}\u{1F918}\u{1F4A6}\u2714\u{1F623}\u{1F3C3}\u{1F490}\u2639\u{1F38A}\u{1F498}\u{1F620}\u261D\u{1F615}\u{1F33A}\u{1F382}\u{1F33B}\u{1F610}\u{1F595}\u{1F49D}\u{1F64A}\u{1F639}\u{1F5E3}\u{1F4AB}\u{1F480}\u{1F451}\u{1F3B5}\u{1F91E}\u{1F61B}\u{1F534}\u{1F624}\u{1F33C}\u{1F62B}\u26BD\u{1F919}\u2615\u{1F3C6}\u{1F92B}\u{1F448}\u{1F62E}\u{1F646}\u{1F37B}\u{1F343}\u{1F436}\u{1F481}\u{1F632}\u{1F33F}\u{1F9E1}\u{1F381}\u26A1\u{1F31E}\u{1F388}\u274C\u270A\u{1F44B}\u{1F630}\u{1F928}\u{1F636}\u{1F91D}\u{1F6B6}\u{1F4B0}\u{1F353}\u{1F4A2}\u{1F91F}\u{1F641}\u{1F6A8}\u{1F4A8}\u{1F92C}\u2708\u{1F380}\u{1F37A}\u{1F913}\u{1F619}\u{1F49F}\u{1F331}\u{1F616}\u{1F476}\u{1F974}\u25B6\u27A1\u2753\u{1F48E}\u{1F4B8}\u2B07\u{1F628}\u{1F31A}\u{1F98B}\u{1F637}\u{1F57A}\u26A0\u{1F645}\u{1F61F}\u{1F635}\u{1F44E}\u{1F932}\u{1F920}\u{1F927}\u{1F4CC}\u{1F535}\u{1F485}\u{1F9D0}\u{1F43E}\u{1F352}\u{1F617}\u{1F911}\u{1F30A}\u{1F92F}\u{1F437}\u260E\u{1F4A7}\u{1F62F}\u{1F486}\u{1F446}\u{1F3A4}\u{1F647}\u{1F351}\u2744\u{1F334}\u{1F4A3}\u{1F438}\u{1F48C}\u{1F4CD}\u{1F940}\u{1F922}\u{1F445}\u{1F4A1}\u{1F4A9}\u{1F450}\u{1F4F8}\u{1F47B}\u{1F910}\u{1F92E}\u{1F3BC}\u{1F975}\u{1F6A9}\u{1F34E}\u{1F34A}\u{1F47C}\u{1F48D}\u{1F4E3}\u{1F942}"),Ti=vn.reduce((r,e,t)=>(r[t]=e,r),[]),Ri=vn.reduce((r,e,t)=>(r[e.codePointAt(0)]=t,r),[]);function Ii(r){return r.reduce((e,t)=>(e+=Ti[t],e),"")}function Ni(r){let e=[];for(let t of r){let n=Ri[t.codePointAt(0)];if(n===void 0)throw new Error(`Non-base256emoji character: ${t}`);e.push(n)}return new Uint8Array(e)}var Mi=Ee({prefix:"\u{1F680}",name:"base256emoji",encode:Ii,decode:Ni});var pr={};P(pr,{base36:()=>Fi,base36upper:()=>Ui});var Fi=ee({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Ui=ee({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var mr={};P(mr,{base8:()=>Bi});var Bi=C({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var gr={};P(gr,{identity:()=>Pi});var Pi=Ee({prefix:"\0",name:"identity",encode:r=>hn(r),decode:r=>un(r)});var mc=new TextEncoder,gc=new TextDecoder;var wr={};P(wr,{identity:()=>bt});var Sn=0,Hi="identity",Ln=Y;function Vi(r){return te(Sn,Ln(r))}var bt={code:Sn,name:Hi,encode:Ln,digest:Vi};var xr={};P(xr,{sha256:()=>oe,sha512:()=>qi});function yr({name:r,code:e,encode:t}){return new br(r,e,t)}var br=class{name;code;encode;constructor(e,t,n){this.name=e,this.code=t,this.encode=n}digest(e){if(e instanceof Uint8Array){let t=this.encode(e);return t instanceof Uint8Array?te(this.code,t):t.then(n=>te(this.code,n))}else throw Error("Unknown type, must be binary type")}};function kn(r){return async e=>new Uint8Array(await crypto.subtle.digest(r,e))}var oe=yr({name:"sha2-256",code:18,encode:kn("SHA-256")}),qi=yr({name:"sha2-512",code:19,encode:kn("SHA-512")});var Ce={...gr,...fr,...mr,...ur,...hr,...or,...pr,...ar,...ir,...dr},_c={...xr,...wr};function Dn(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var Cn=Dn("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),Er=Dn("ascii","a",r=>{let e="a";for(let t=0;t<r.length;t++)e+=String.fromCharCode(r[t]);return e},r=>{r=r.substring(1);let e=I(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),Wi={utf8:Cn,"utf-8":Cn,hex:Ce.base16,latin1:Er,ascii:Er,binary:Er,...Ce},yt=Wi;function q(r,e="utf8"){let t=yt[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.encoder.encode(r).substring(1)}var Be="/ipfs/bitswap/1.2.0";var vr=new Float32Array([-0]),re=new Uint8Array(vr.buffer);function _n(r,e,t){vr[0]=r,e[t]=re[0],e[t+1]=re[1],e[t+2]=re[2],e[t+3]=re[3]}function Tn(r,e){return re[0]=r[e],re[1]=r[e+1],re[2]=r[e+2],re[3]=r[e+3],vr[0]}var Sr=new Float64Array([-0]),M=new Uint8Array(Sr.buffer);function Rn(r,e,t){Sr[0]=r,e[t]=M[0],e[t+1]=M[1],e[t+2]=M[2],e[t+3]=M[3],e[t+4]=M[4],e[t+5]=M[5],e[t+6]=M[6],e[t+7]=M[7]}function In(r,e){return M[0]=r[e],M[1]=r[e+1],M[2]=r[e+2],M[3]=r[e+3],M[4]=r[e+4],M[5]=r[e+5],M[6]=r[e+6],M[7]=r[e+7],Sr[0]}var Gi=BigInt(Number.MAX_SAFE_INTEGER),$i=BigInt(Number.MIN_SAFE_INTEGER),V=class r{lo;hi;constructor(e,t){this.lo=e|0,this.hi=t|0}toNumber(e=!1){if(!e&&this.hi>>>31>0){let t=~this.lo+1>>>0,n=~this.hi>>>0;return t===0&&(n=n+1>>>0),-(t+n*4294967296)}return this.lo+this.hi*4294967296}toBigInt(e=!1){if(e)return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n);if(this.hi>>>31){let t=~this.lo+1>>>0,n=~this.hi>>>0;return t===0&&(n=n+1>>>0),-(BigInt(t)+(BigInt(n)<<32n))}return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n)}toString(e=!1){return this.toBigInt(e).toString()}zzEncode(){let e=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^e)>>>0,this.lo=(this.lo<<1^e)>>>0,this}zzDecode(){let e=-(this.lo&1);return this.lo=((this.lo>>>1|this.hi<<31)^e)>>>0,this.hi=(this.hi>>>1^e)>>>0,this}length(){let e=this.lo,t=(this.lo>>>28|this.hi<<4)>>>0,n=this.hi>>>24;return n===0?t===0?e<16384?e<128?1:2:e<2097152?3:4:t<16384?t<128?5:6:t<2097152?7:8:n<128?9:10}static fromBigInt(e){if(e===0n)return ae;if(e<Gi&&e>$i)return this.fromNumber(Number(e));let t=e<0n;t&&(e=-e);let n=e>>32n,s=e-(n<<32n);return t&&(n=~n|0n,s=~s|0n,++s>Nn&&(s=0n,++n>Nn&&(n=0n))),new r(Number(s),Number(n))}static fromNumber(e){if(e===0)return ae;let t=e<0;t&&(e=-e);let n=e>>>0,s=(e-n)/4294967296>>>0;return t&&(s=~s>>>0,n=~n>>>0,++n>4294967295&&(n=0,++s>4294967295&&(s=0))),new r(n,s)}static from(e){return typeof e=="number"?r.fromNumber(e):typeof e=="bigint"?r.fromBigInt(e):typeof e=="string"?r.fromBigInt(BigInt(e)):e.low!=null||e.high!=null?new r(e.low>>>0,e.high>>>0):ae}},ae=new V(0,0);ae.toBigInt=function(){return 0n};ae.zzEncode=ae.zzDecode=function(){return this};ae.length=function(){return 1};var Nn=4294967296n;function Mn(r){let e=0,t=0;for(let n=0;n<r.length;++n)t=r.charCodeAt(n),t<128?e+=1:t<2048?e+=2:(t&64512)===55296&&(r.charCodeAt(n+1)&64512)===56320?(++n,e+=4):e+=3;return e}function Fn(r,e,t){if(t-e<1)return"";let s,i=[],o=0,c;for(;e<t;)c=r[e++],c<128?i[o++]=c:c>191&&c<224?i[o++]=(c&31)<<6|r[e++]&63:c>239&&c<365?(c=((c&7)<<18|(r[e++]&63)<<12|(r[e++]&63)<<6|r[e++]&63)-65536,i[o++]=55296+(c>>10),i[o++]=56320+(c&1023)):i[o++]=(c&15)<<12|(r[e++]&63)<<6|r[e++]&63,o>8191&&((s??(s=[])).push(String.fromCharCode.apply(String,i)),o=0);return s!=null?(o>0&&s.push(String.fromCharCode.apply(String,i.slice(0,o))),s.join("")):String.fromCharCode.apply(String,i.slice(0,o))}function Lr(r,e,t){let n=t,s,i;for(let o=0;o<r.length;++o)s=r.charCodeAt(o),s<128?e[t++]=s:s<2048?(e[t++]=s>>6|192,e[t++]=s&63|128):(s&64512)===55296&&((i=r.charCodeAt(o+1))&64512)===56320?(s=65536+((s&1023)<<10)+(i&1023),++o,e[t++]=s>>18|240,e[t++]=s>>12&63|128,e[t++]=s>>6&63|128,e[t++]=s&63|128):(e[t++]=s>>12|224,e[t++]=s>>6&63|128,e[t++]=s&63|128);return t-n}function X(r,e){return RangeError(`index out of range: ${r.pos} + ${e??1} > ${r.len}`)}function xt(r,e){return(r[e-4]|r[e-3]<<8|r[e-2]<<16|r[e-1]<<24)>>>0}var Ar=class{buf;pos;len;_slice=Uint8Array.prototype.subarray;constructor(e){this.buf=e,this.pos=0,this.len=e.length}uint32(){let e=4294967295;if(e=(this.buf[this.pos]&127)>>>0,this.buf[this.pos++]<128||(e=(e|(this.buf[this.pos]&127)<<7)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<14)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<21)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&15)<<28)>>>0,this.buf[this.pos++]<128))return e;if((this.pos+=5)>this.len)throw this.pos=this.len,X(this,10);return e}int32(){return this.uint32()|0}sint32(){let e=this.uint32();return e>>>1^-(e&1)|0}bool(){return this.uint32()!==0}fixed32(){if(this.pos+4>this.len)throw X(this,4);return xt(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw X(this,4);return xt(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw X(this,4);let e=Tn(this.buf,this.pos);return this.pos+=4,e}double(){if(this.pos+8>this.len)throw X(this,4);let e=In(this.buf,this.pos);return this.pos+=8,e}bytes(){let e=this.uint32(),t=this.pos,n=this.pos+e;if(n>this.len)throw X(this,e);return this.pos+=e,t===n?new Uint8Array(0):this.buf.subarray(t,n)}string(){let e=this.bytes();return Fn(e,0,e.length)}skip(e){if(typeof e=="number"){if(this.pos+e>this.len)throw X(this,e);this.pos+=e}else do if(this.pos>=this.len)throw X(this);while(this.buf[this.pos++]&128);return this}skipType(e){switch(e){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;(e=this.uint32()&7)!==4;)this.skipType(e);break;case 5:this.skip(4);break;default:throw Error(`invalid wire type ${e} at offset ${this.pos}`)}return this}readLongVarint(){let e=new V(0,0),t=0;if(this.len-this.pos>4){for(;t<4;++t)if(e.lo=(e.lo|(this.buf[this.pos]&127)<<t*7)>>>0,this.buf[this.pos++]<128)return e;if(e.lo=(e.lo|(this.buf[this.pos]&127)<<28)>>>0,e.hi=(e.hi|(this.buf[this.pos]&127)>>4)>>>0,this.buf[this.pos++]<128)return e;t=0}else{for(;t<3;++t){if(this.pos>=this.len)throw X(this);if(e.lo=(e.lo|(this.buf[this.pos]&127)<<t*7)>>>0,this.buf[this.pos++]<128)return e}return e.lo=(e.lo|(this.buf[this.pos++]&127)<<t*7)>>>0,e}if(this.len-this.pos>4){for(;t<5;++t)if(e.hi=(e.hi|(this.buf[this.pos]&127)<<t*7+3)>>>0,this.buf[this.pos++]<128)return e}else for(;t<5;++t){if(this.pos>=this.len)throw X(this);if(e.hi=(e.hi|(this.buf[this.pos]&127)<<t*7+3)>>>0,this.buf[this.pos++]<128)return e}throw Error("invalid varint encoding")}readFixed64(){if(this.pos+8>this.len)throw X(this,8);let e=xt(this.buf,this.pos+=4),t=xt(this.buf,this.pos+=4);return new V(e,t)}int64(){return this.readLongVarint().toBigInt()}int64Number(){return this.readLongVarint().toNumber()}int64String(){return this.readLongVarint().toString()}uint64(){return this.readLongVarint().toBigInt(!0)}uint64Number(){let e=Qt(this.buf,this.pos);return this.pos+=_(e),e}uint64String(){return this.readLongVarint().toString(!0)}sint64(){return this.readLongVarint().zzDecode().toBigInt()}sint64Number(){return this.readLongVarint().zzDecode().toNumber()}sint64String(){return this.readLongVarint().zzDecode().toString()}fixed64(){return this.readFixed64().toBigInt()}fixed64Number(){return this.readFixed64().toNumber()}fixed64String(){return this.readFixed64().toString()}sfixed64(){return this.readFixed64().toBigInt()}sfixed64Number(){return this.readFixed64().toNumber()}sfixed64String(){return this.readFixed64().toString()}};function kr(r){return new Ar(r instanceof Uint8Array?r:r.subarray())}function ce(r,e,t){let n=kr(r);return e.decode(n,void 0,t)}function Pe(r,e="utf8"){let t=yt[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.decoder.decode(`${t.prefix}${r}`)}function Cr(r){let e=r??8192,t=e>>>1,n,s=e;return function(o){if(o<1||o>t)return I(o);s+o>e&&(n=I(e),s=0);let c=n.subarray(s,s+=o);return s&7&&(s=(s|7)+1),c}}var le=class{fn;len;next;val;constructor(e,t,n){this.fn=e,this.len=t,this.next=void 0,this.val=n}};function Dr(){}var Tr=class{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}},Xi=Cr();function Qi(r){return globalThis.Buffer!=null?I(r):Xi(r)}var ze=class{len;head;tail;states;constructor(){this.len=0,this.head=new le(Dr,0,0),this.tail=this.head,this.states=null}_push(e,t,n){return this.tail=this.tail.next=new le(e,t,n),this.len+=t,this}uint32(e){return this.len+=(this.tail=this.tail.next=new Rr((e=e>>>0)<128?1:e<16384?2:e<2097152?3:e<268435456?4:5,e)).len,this}int32(e){return e<0?this._push(Et,10,V.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){let t=V.fromBigInt(e);return this._push(Et,t.length(),t)}uint64Number(e){return this._push(Xt,_(e),e)}uint64String(e){return this.uint64(BigInt(e))}int64(e){return this.uint64(e)}int64Number(e){return this.uint64Number(e)}int64String(e){return this.uint64String(e)}sint64(e){let t=V.fromBigInt(e).zzEncode();return this._push(Et,t.length(),t)}sint64Number(e){let t=V.fromNumber(e).zzEncode();return this._push(Et,t.length(),t)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(_r,1,e?1:0)}fixed32(e){return this._push(Oe,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){let t=V.fromBigInt(e);return this._push(Oe,4,t.lo)._push(Oe,4,t.hi)}fixed64Number(e){let t=V.fromNumber(e);return this._push(Oe,4,t.lo)._push(Oe,4,t.hi)}fixed64String(e){return this.fixed64(BigInt(e))}sfixed64(e){return this.fixed64(e)}sfixed64Number(e){return this.fixed64Number(e)}sfixed64String(e){return this.fixed64String(e)}float(e){return this._push(_n,4,e)}double(e){return this._push(Rn,8,e)}bytes(e){let t=e.length>>>0;return t===0?this._push(_r,1,0):this.uint32(t)._push(Ki,t,e)}string(e){let t=Mn(e);return t!==0?this.uint32(t)._push(Lr,t,e):this._push(_r,1,0)}fork(){return this.states=new Tr(this),this.head=this.tail=new le(Dr,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 le(Dr,0,0),this.len=0),this}ldelim(){let e=this.head,t=this.tail,n=this.len;return this.reset().uint32(n),n!==0&&(this.tail.next=e.next,this.tail=t,this.len+=n),this}finish(){let e=this.head.next,t=Qi(this.len),n=0;for(;e!=null;)e.fn(e.val,t,n),n+=e.len,e=e.next;return t}};function _r(r,e,t){e[t]=r&255}function Ji(r,e,t){for(;r>127;)e[t++]=r&127|128,r>>>=7;e[t]=r}var Rr=class extends le{next;constructor(e,t){super(Ji,e,t),this.next=void 0}};function Et(r,e,t){for(;r.hi!==0;)e[t++]=r.lo&127|128,r.lo=(r.lo>>>7|r.hi<<25)>>>0,r.hi>>>=7;for(;r.lo>127;)e[t++]=r.lo&127|128,r.lo=r.lo>>>7;e[t++]=r.lo}function Oe(r,e,t){e[t]=r&255,e[t+1]=r>>>8&255,e[t+2]=r>>>16&255,e[t+3]=r>>>24}function Ki(r,e,t){e.set(r,t)}globalThis.Buffer!=null&&(ze.prototype.bytes=function(r){let e=r.length>>>0;return this.uint32(e),e>0&&this._push(ji,e,r),this},ze.prototype.string=function(r){let e=globalThis.Buffer.byteLength(r);return this.uint32(e),e>0&&this._push(Yi,e,r),this});function ji(r,e,t){e.set(r,t)}function Yi(r,e,t){r.length<40?Lr(r,e,t):e.utf8Write!=null?e.utf8Write(r,t):e.set(Pe(r),t)}function Ir(){return new ze}function ue(r,e){let t=Ir();return e.encode(r,t,{lengthDelimited:!1}),t.finish()}var De;(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"})(De||(De={}));function vt(r,e,t,n){return{name:r,type:e,encode:t,decode:n}}function St(r){function e(s){if(r[s.toString()]==null)throw new Error("Invalid enum value");return r[s]}let t=function(i,o){let c=e(i);o.int32(c)},n=function(i){let o=i.int32();return e(o)};return vt("enum",De.VARINT,t,n)}function he(r,e){return vt("message",De.LENGTH_DELIMITED,r,e)}var D;(function(r){r.WantBlock="WantBlock",r.WantHave="WantHave"})(D||(D={}));var Nr;(function(r){r[r.WantBlock=0]="WantBlock",r[r.WantHave=1]="WantHave"})(Nr||(Nr={}));(function(r){r.codec=()=>St(Nr)})(D||(D={}));var Lt;(function(r){let e;r.codec=()=>(e==null&&(e=he((t,n,s={})=>{s.lengthDelimited!==!1&&n.fork(),t.cid!=null&&t.cid.byteLength>0&&(n.uint32(10),n.bytes(t.cid)),t.priority!=null&&t.priority!==0&&(n.uint32(16),n.int32(t.priority)),t.cancel!=null&&(n.uint32(24),n.bool(t.cancel)),t.wantType!=null&&(n.uint32(32),D.codec().encode(t.wantType,n)),t.sendDontHave!=null&&(n.uint32(40),n.bool(t.sendDontHave)),s.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let s={cid:R(0),priority:0},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let o=t.uint32();switch(o>>>3){case 1:{s.cid=t.bytes();break}case 2:{s.priority=t.int32();break}case 3:{s.cancel=t.bool();break}case 4:{s.wantType=D.codec().decode(t);break}case 5:{s.sendDontHave=t.bool();break}default:{t.skipType(o&7);break}}}return s})),e),r.encode=t=>ue(t,r.codec()),r.decode=t=>ce(t,r.codec())})(Lt||(Lt={}));var At;(function(r){let e;r.codec=()=>(e==null&&(e=he((t,n,s={})=>{if(s.lengthDelimited!==!1&&n.fork(),t.entries!=null)for(let i of t.entries)n.uint32(10),Lt.codec().encode(i,n);t.full!=null&&(n.uint32(16),n.bool(t.full)),s.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let s={entries:[]},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let o=t.uint32();switch(o>>>3){case 1:{s.entries.push(Lt.codec().decode(t,t.uint32()));break}case 2:{s.full=t.bool();break}default:{t.skipType(o&7);break}}}return s})),e),r.encode=t=>ue(t,r.codec()),r.decode=t=>ce(t,r.codec())})(At||(At={}));var kt;(function(r){let e;r.codec=()=>(e==null&&(e=he((t,n,s={})=>{s.lengthDelimited!==!1&&n.fork(),t.prefix!=null&&t.prefix.byteLength>0&&(n.uint32(10),n.bytes(t.prefix)),t.data!=null&&t.data.byteLength>0&&(n.uint32(18),n.bytes(t.data)),s.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let s={prefix:R(0),data:R(0)},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let o=t.uint32();switch(o>>>3){case 1:{s.prefix=t.bytes();break}case 2:{s.data=t.bytes();break}default:{t.skipType(o&7);break}}}return s})),e),r.encode=t=>ue(t,r.codec()),r.decode=t=>ce(t,r.codec())})(kt||(kt={}));var W;(function(r){r.HaveBlock="HaveBlock",r.DontHaveBlock="DontHaveBlock"})(W||(W={}));var Ct;(function(r){r[r.HaveBlock=0]="HaveBlock",r[r.DontHaveBlock=1]="DontHaveBlock"})(Ct||(Ct={}));(function(r){r.codec=()=>St(Ct)})(W||(W={}));var Dt;(function(r){let e;r.codec=()=>(e==null&&(e=he((t,n,s={})=>{s.lengthDelimited!==!1&&n.fork(),t.cid!=null&&t.cid.byteLength>0&&(n.uint32(10),n.bytes(t.cid)),t.type!=null&&Ct[t.type]!==0&&(n.uint32(16),W.codec().encode(t.type,n)),s.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let s={cid:R(0),type:W.HaveBlock},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let o=t.uint32();switch(o>>>3){case 1:{s.cid=t.bytes();break}case 2:{s.type=W.codec().decode(t);break}default:{t.skipType(o&7);break}}}return s})),e),r.encode=t=>ue(t,r.codec()),r.decode=t=>ce(t,r.codec())})(Dt||(Dt={}));var He;(function(r){let e;r.codec=()=>(e==null&&(e=he((t,n,s={})=>{if(s.lengthDelimited!==!1&&n.fork(),t.wantlist!=null&&(n.uint32(10),At.codec().encode(t.wantlist,n)),t.blocks!=null)for(let i of t.blocks)n.uint32(26),kt.codec().encode(i,n);if(t.blockPresences!=null)for(let i of t.blockPresences)n.uint32(34),Dt.codec().encode(i,n);t.pendingBytes!=null&&t.pendingBytes!==0&&(n.uint32(40),n.int32(t.pendingBytes)),s.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let s={blocks:[],blockPresences:[],pendingBytes:0},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let o=t.uint32();switch(o>>>3){case 1:{s.wantlist=At.codec().decode(t,t.uint32());break}case 3:{s.blocks.push(kt.codec().decode(t,t.uint32()));break}case 4:{s.blockPresences.push(Dt.codec().decode(t,t.uint32()));break}case 5:{s.pendingBytes=t.int32();break}default:{t.skipType(o&7);break}}}return s})),e),r.encode=t=>ue(t,r.codec()),r.decode=t=>ce(t,r.codec())})(He||(He={}));Bn.default.formatters.B=r=>r==null?"undefined":JSON.stringify({blocks:r.blocks?.map(e=>({data:`${q(e.data,"base64").substring(0,10)}...`,prefix:q(e.prefix,"base64")})),blockPresences:r.blockPresences?.map(e=>({...e,cid:U.decode(e.cid).toString()})),wantlist:r.wantlist==null?void 0:{full:r.wantlist.full,entries:r.wantlist.entries.map(e=>({...e,cid:U.decode(e.cid).toString()}))}},null,2);var _t=class extends Q{log;libp2p;routing;protocols;running;maxInboundStreams;maxOutboundStreams;messageReceiveTimeout;registrarIds;metrics;sendQueue;messageSendTimeout;runOnTransientConnections;constructor(e,t={}){super(),this.log=e.logger.forComponent("helia:bitswap:network"),this.libp2p=e.libp2p,this.routing=e.routing,this.protocols=t.protocols??[Be],this.registrarIds=[],this.running=!1,this._onStream=this._onStream.bind(this),this.maxInboundStreams=t.maxInboundStreams??1024,this.maxOutboundStreams=t.maxOutboundStreams??1024,this.messageReceiveTimeout=t.messageReceiveTimeout??5e3,this.messageSendTimeout=t.messageSendTimeout??5e3,this.runOnTransientConnections=t.runOnTransientConnections??!1,this.metrics={blocksSent:e.libp2p.metrics?.registerCounter("helia_bitswap_sent_blocks_total"),dataSent:e.libp2p.metrics?.registerCounter("helia_bitswap_sent_data_bytes_total")},this.sendQueue=new ct({concurrency:t.messageSendConcurrency??50,metrics:e.libp2p.metrics,metricName:"helia_bitswap_message_send_queue"}),this.sendQueue.addEventListener("error",n=>{this.log.error("error sending wantlist to peer",n.detail)})}async start(){if(this.running)return;this.running=!0,await this.libp2p.handle(this.protocols,this._onStream,{maxInboundStreams:this.maxInboundStreams,maxOutboundStreams:this.maxOutboundStreams,runOnTransientConnection:this.runOnTransientConnections});let e={onConnect:t=>{this.safeDispatchEvent("peer:connected",{detail:t})},onDisconnect:t=>{this.safeDispatchEvent("peer:disconnected",{detail:t})}};this.registrarIds=[];for(let t of this.protocols)this.registrarIds.push(await this.libp2p.register(t,e));this.libp2p.getConnections().forEach(t=>{this.safeDispatchEvent("peer:connected",{detail:t.remotePeer})})}async stop(){if(this.running=!1,await this.libp2p.unhandle(this.protocols),this.registrarIds!=null){for(let e of this.registrarIds)this.libp2p.unregister(e);this.registrarIds=[]}}_onStream(e){if(!this.running)return;let{stream:t,connection:n}=e;Promise.resolve().then(async()=>{this.log("incoming new bitswap %s stream from %p",t.protocol,n.remotePeer);let s=()=>{t.abort(new O("Incoming Bitswap stream timed out","ERR_TIMEOUT"))},i=AbortSignal.timeout(this.messageReceiveTimeout);B(1/0,i),i.addEventListener("abort",s),await Ie(t,o=>Te(o),async o=>{for await(let c of o)try{let u=He.decode(c);this.log("incoming new bitswap %s message from %p %B",t.protocol,n.remotePeer,u),this.safeDispatchEvent("bitswap:message",{detail:{peer:n.remotePeer,message:u}}),i.removeEventListener("abort",s),i=AbortSignal.timeout(this.messageReceiveTimeout),B(1/0,i),i.addEventListener("abort",s)}catch(u){this.log.error("error reading incoming bitswap message from %p",n.remotePeer,u),t.abort(u);break}})}).catch(s=>{this.log.error("error handling incoming stream from %p",n.remotePeer,s),t.abort(s)})}async*findProviders(e,t){t?.onProgress?.(new j("bitswap:network:find-providers",e));for await(let n of this.routing.findProviders(e,t))await this.libp2p.isDialable(n.multiaddrs,{runOnTransientConnection:this.runOnTransientConnections})&&(yield n)}async findAndConnect(e,t){await Vt(Re(cn(this.findProviders(e,t),t?.maxProviders??3),async n=>this.connectTo(n.id,t))).catch(n=>{this.log.error(n)})}async sendMessage(e,t,n){if(!this.running)throw new Error("network isn't running");let s={wantlist:{full:t.wantlist?.full??!1,entries:t.wantlist?.entries??[]},blocks:t.blocks??[],blockPresences:t.blockPresences??[],pendingBytes:t.pendingBytes??0},i=AbortSignal.timeout(this.messageSendTimeout),o=rt([i,n?.signal]);B(1/0,i,o);try{let c=this.sendQueue.queue.find(u=>e.equals(u.options.peerId)&&u.status==="queued");if(c!=null){c.options.message=oo(c.options.message,s),await c.join({signal:o});return}await this.sendQueue.add(async u=>{let g=u?.message;if(g==null)throw new O("No message to send","ERR_NO_MESSAGE");this.log("sendMessage to %p %B",e,g),u?.onProgress?.(new j("bitswap:network:send-wantlist",e));let p=await this.libp2p.dialProtocol(e,Be,u);try{let h=nn(p);await h.write(He.encode(g),u),await h.unwrap().close(u)}catch(h){u?.onProgress?.(new j("bitswap:network:send-wantlist:error",{peer:e,error:h})),this.log.error("error sending message to %p",e,h),p.abort(h)}this._updateSentStats(g.blocks)},{peerId:e,signal:o,message:s})}finally{o.clear()}}async connectTo(e,t){if(!this.running)throw new O("Network isn't running","ERR_NOT_STARTED");t?.onProgress?.(new j("bitswap:network:dial",e));let[n]=await Promise.all([this.libp2p.dial(e,t),$(this.libp2p,"peer:identify",t?.signal,{filter:s=>{if(!s.detail.peerId.equals(e))return!1;if(s.detail.protocols.includes(Be))return!0;throw new O(`${e} did not support ${Be}`,"ERR_BITSWAP_UNSUPPORTED_BY_PEER")}})]);return n}_updateSentStats(e=[]){let t=0;for(let n of e.values())t+=n.data.byteLength;this.metrics.dataSent?.increment(t),this.metrics.blocksSent?.increment(e.length)}};function oo(r,e){let t=new Map((r.wantlist?.entries??[]).map(o=>[K.encode(o.cid),o]));for(let o of e.wantlist?.entries??[]){let c=K.encode(o.cid),u=t.get(c);u!=null&&(u.priority>o.priority&&(o.priority=u.priority),o.cancel=o.cancel??u.cancel,o.wantType=o.wantType??u.wantType,o.sendDontHave=o.sendDontHave??u.sendDontHave),t.set(c,o)}let n=new Map(r.blockPresences.map(o=>[K.encode(o.cid),o]));for(let o of e.blockPresences){let c=K.encode(o.cid);n.set(c,o)}let s=new Map(r.blocks.map(o=>[K.encode(o.data),o]));for(let o of e.blocks){let c=K.encode(o.data);s.set(c,o)}return{wantlist:{full:r.wantlist?.full??e.wantlist?.full??!1,entries:[...t.values()]},blockPresences:[...n.values()],blocks:[...s.values()],pendingBytes:r.pendingBytes+e.pendingBytes}}var ao=Symbol.for("nodejs.util.inspect.custom"),Pn=Object.values(Ce).map(r=>r.decoder).reduce((r,e)=>r.or(e),Ce.identity.decoder),On=114,zn=36,Hn=37,Ve=class{type;multihash;privateKey;publicKey;string;constructor(e){this.type=e.type,this.multihash=e.multihash,this.privateKey=e.privateKey,Object.defineProperty(this,"string",{enumerable:!1,writable:!0})}get[Symbol.toStringTag](){return`PeerId(${this.toString()})`}[qr]=!0;toString(){return this.string==null&&(this.string=H.encode(this.multihash.bytes).slice(1)),this.string}toCID(){return U.createV1(On,this.multihash)}toBytes(){return this.multihash.bytes}toJSON(){return this.toString()}equals(e){if(e==null)return!1;if(e instanceof Uint8Array)return J(this.multihash.bytes,e);if(typeof e=="string")return $e(e).equals(this);if(e?.multihash?.bytes!=null)return J(this.multihash.bytes,e.multihash.bytes);throw new Error("not valid Id")}[ao](){return`PeerId(${this.toString()})`}},qe=class extends Ve{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}},We=class extends Ve{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.multihash.digest}},Ge=class extends Ve{type="secp256k1";publicKey;constructor(e){super({...e,type:"secp256k1"}),this.publicKey=e.multihash.digest}};function $e(r,e){if(e=e??Pn,r.charAt(0)==="1"||r.charAt(0)==="Q"){let t=Fe(H.decode(`z${r}`));return r.startsWith("12D")?new We({multihash:t}):r.startsWith("16U")?new Ge({multihash:t}):new qe({multihash:t})}return co(Pn.decode(r))}function co(r){try{let e=Fe(r);if(e.code===bt.code){if(e.digest.length===zn)return new We({multihash:e});if(e.digest.length===Hn)return new Ge({multihash:e})}if(e.code===oe.code)return new qe({multihash:e})}catch{return lo(U.decode(r))}throw new Error("Supplied PeerID CID is invalid")}function lo(r){if(r==null||r.multihash==null||r.version==null||r.version===1&&r.code!==On)throw new Error("Supplied PeerID CID is invalid");let e=r.multihash;if(e.code===oe.code)return new qe({multihash:r.multihash});if(e.code===bt.code){if(e.digest.length===zn)return new We({multihash:r.multihash});if(e.digest.length===Hn)return new Ge({multihash:r.multihash})}throw new Error("Supplied PeerID CID is invalid")}function Mr(r,e){let t={[Symbol.iterator]:()=>t,next:()=>{let n=r.next(),s=n.value;return n.done===!0||s==null?{done:!0,value:void 0}:{done:!1,value:e(s)}}};return t}var Xe=class{map;constructor(e){if(this.map=new Map,e!=null)for(let[t,n]of e.entries())this.map.set(t.toString(),n)}[Symbol.iterator](){return this.entries()}clear(){this.map.clear()}delete(e){return this.map.delete(e.toString())}entries(){return Mr(this.map.entries(),e=>[$e(e[0]),e[1]])}forEach(e){this.map.forEach((t,n)=>{e(t,$e(n),this)})}get(e){return this.map.get(e.toString())}has(e){return this.map.has(e.toString())}set(e,t){this.map.set(e.toString(),t)}keys(){return Mr(this.map.keys(),e=>$e(e))}values(){return this.map.values()}get size(){return this.map.size}};var Fr=class extends Xe{metric;constructor(e){super();let{name:t,metrics:n}=e;this.metric=n.registerMetric(t),this.updateComponentMetric()}set(e,t){return super.set(e,t),this.updateComponentMetric(),this}delete(e){let t=super.delete(e);return this.updateComponentMetric(),t}clear(){super.clear(),this.updateComponentMetric()}updateComponentMetric(){this.metric.update(this.size)}};function Qe(r){let{name:e,metrics:t}=r,n;return t!=null?n=new Fr({name:e,metrics:t}):n=new Xe,n}function uo(r){let e=new Uint8Array(r.reduce((n,s)=>n+_(s),0)),t=0;for(let n of r)e=be(n,e,t),t+=_(n);return e}var Vn=uo;function Ur(r){return Vn([r.version,r.code,r.multihash.code,r.multihash.digest.byteLength])}var Tt=class{peerId;blockstore;network;wants;exchangeCount;bytesSent;bytesReceived;lastExchange;maxSizeReplaceHasWithBlock;constructor(e,t){this.peerId=e.peerId,this.blockstore=e.blockstore,this.network=e.network,this.wants=new Map,this.exchangeCount=0,this.bytesSent=0,this.bytesReceived=0,this.maxSizeReplaceHasWithBlock=t.maxSizeReplaceHasWithBlock??1024}sentBytes(e){this.exchangeCount++,this.lastExchange=new Date().getTime(),this.bytesSent+=e}receivedBytes(e){this.exchangeCount++,this.lastExchange=new Date().getTime(),this.bytesReceived+=e}debtRatio(){return this.bytesSent/(this.bytesReceived+1)}async sendBlocksToPeer(e){let t={blockPresences:[],blocks:[]},n=new Set;for(let[s,i]of this.wants.entries()){if(!await this.blockstore.has(i.cid,e)){if(!i.sendDontHave||i.sentDontHave===!0)continue;i.sentDontHave=!0,t.blockPresences.push({cid:i.cid.bytes,type:W.DontHaveBlock});continue}let c=await this.blockstore.get(i.cid,e);i.wantType===D.WantHave?c.byteLength<this.maxSizeReplaceHasWithBlock?(n.add(s),t.blocks.push({data:c,prefix:Ur(i.cid)})):t.blockPresences.push({cid:i.cid.bytes,type:W.HaveBlock}):(n.add(s),t.blocks.push({data:c,prefix:Ur(i.cid)}))}if(t.blocks.length>0||t.blockPresences.length>0){await this.network.sendMessage(this.peerId,t,e),this.sentBytes(t.blocks.reduce((s,i)=>s+i.data.byteLength,0));for(let s of n)this.wants.delete(s)}}};var Rt=class{blockstore;network;ledgerMap;maxSizeReplaceHasWithBlock;log;constructor(e,t={}){this.blockstore=e.blockstore,this.network=e.network,this.maxSizeReplaceHasWithBlock=t.maxSizeReplaceHasWithBlock,this.log=e.logger.forComponent("helia:bitswap:peer-want-lists"),this.ledgerMap=Qe({name:"helia_bitswap_ledger_map",metrics:e.libp2p.metrics}),this.network.addEventListener("bitswap:message",n=>{this.receiveMessage(n.detail.peer,n.detail.message).catch(s=>{this.log.error("error receiving bitswap message from %p",n.detail.peer,s)})}),this.network.addEventListener("peer:disconnected",n=>{this.peerDisconnected(n.detail)})}ledgerForPeer(e){let t=this.ledgerMap.get(e);if(t!=null)return{peer:t.peerId,value:t.debtRatio(),sent:t.bytesSent,received:t.bytesReceived,exchanged:t.exchangeCount}}wantListForPeer(e){let t=this.ledgerMap.get(e);if(t!=null)return[...t.wants.values()]}peers(){return Array.from(this.ledgerMap.values()).map(e=>e.peerId)}async receiveMessage(e,t){let n=this.ledgerMap.get(e);if(n==null&&(n=new Tt({peerId:e,blockstore:this.blockstore,network:this.network},{maxSizeReplaceHasWithBlock:this.maxSizeReplaceHasWithBlock}),this.ledgerMap.set(e,n)),n.receivedBytes(t.blocks?.reduce((s,i)=>s+i.data.byteLength,0)??0),t.wantlist!=null){t.wantlist.full===!0&&n.wants.clear();for(let s of t.wantlist.entries){let i=U.decode(s.cid),o=q(i.multihash.bytes,"base64");s.cancel===!0?(this.log("peer %p cancelled want of block for %c",e,i),n.wants.delete(o)):(s.wantType===D.WantHave?this.log("peer %p wanted block presence for %c",e,i):this.log("peer %p wanted block for %c",e,i),n.wants.set(o,{cid:i,priority:s.priority,wantType:s.wantType??D.WantBlock,sendDontHave:s.sendDontHave??!1}))}}await n.sendBlocksToPeer()}async receivedBlock(e,t){let n=q(e.multihash.bytes,"base64"),s=[];for(let i of this.ledgerMap.values())i.wants.has(n)&&s.push(i);await Promise.all(s.map(async i=>i.sendBlocksToPeer(t)))}peerDisconnected(e){this.ledgerMap.delete(e)}};var po=tt(Wn(),1);var _e;(function(r){r[r.A=1]="A",r[r.CNAME=5]="CNAME",r[r.TXT=16]="TXT",r[r.AAAA=28]="AAAA"})(_e||(_e={}));function mo(r){return r[Symbol.asyncIterator]!=null}function go(r,e){if(mo(r))return async function*(){for await(let c of r)await e(c)&&(yield c)}();let t=gt(r),{value:n,done:s}=t.next();if(s===!0)return function*(){}();let i=e(n);if(typeof i.then=="function")return async function*(){await i&&(yield n);for await(let c of t)await e(c)&&(yield c)}();let o=e;return function*(){i===!0&&(yield n);for(let c of t)o(c)&&(yield c)}()}var Br=go;var It=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;var qu=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;var Wu={}.toString;function Gn(r=32){if(It&&typeof It.getRandomValues=="function")return It.getRandomValues(new Uint8Array(r));throw new Error("crypto.getRandomValues must be defined")}function Nt(r){if(isNaN(r)||r<=0)throw new O("random bytes length must be a Number bigger than 0","ERR_INVALID_LENGTH");return Gn(r)}var Pr=tt(Qn(),1);var wo=Math.LN2*Math.LN2,Ft=class r{static create(e,t=.005){let n=bo(e,t);return new r(n)}seeds;bits;buffer;constructor(e={}){e.seeds!=null?this.seeds=e.seeds:this.seeds=yo(e.hashes??8),this.bits=e.bits??1024,this.buffer=R(Math.ceil(this.bits/8))}add(e){typeof e=="string"&&(e=Pe(e));for(let t=0;t<this.seeds.length;t++){let s=Pr.default.x86.hash32(e,this.seeds[t])%this.bits;this.setbit(s)}}has(e){typeof e=="string"&&(e=Pe(e));for(let t=0;t<this.seeds.length;t++){let s=Pr.default.x86.hash32(e,this.seeds[t])%this.bits;if(!this.getbit(s))return!1}return!0}clear(){this.buffer.fill(0)}setbit(e){let t=0,n=e;for(;n>7;)t++,n-=8;let s=this.buffer[t];s|=1<<n,this.buffer[t]=s}getbit(e){let t=0,n=e;for(;n>7;)t++,n-=8;return(this.buffer[t]&1<<n)!==0}};function bo(r,e=.005){let t=Math.round(-1*r*Math.log(e)/wo),n=Math.round(t/r*Math.LN2);return{bits:t,hashes:n}}function yo(r){let e,t,n=[];for(let s=0;s<r;s++)for(e=new F(Nt(4)),n[s]=e.getUint32(0,!0),t=0;t<s;t++)if(n[s]===n[t]){s--;break}return n}var Ke=class extends Q{intialPeerSearchComplete;requests;name;log;logger;minProviders;maxProviders;providers;evictionFilter;constructor(e,t){super(),B(1/0,this),this.name=t.name,this.logger=e.logger,this.log=e.logger.forComponent(this.name),this.requests=new Map,this.minProviders=t.minProviders??1,this.maxProviders=t.maxProviders??5,this.providers=[],this.evictionFilter=Ft.create(this.maxProviders)}async retrieve(e,t={}){let n=K.encode(e.multihash.bytes),s=this.requests.get(n);if(s!=null)return this.log("join existing request for %c",e),s;let i=T();if(this.requests.set(n,i.promise),this.providers.length===0){let g=!1;this.intialPeerSearchComplete==null&&(g=!0,this.log=this.logger.forComponent(`${this.name}:${e}`),this.intialPeerSearchComplete=this.findProviders(e,this.minProviders,t)),await this.intialPeerSearchComplete,g&&this.log("found initial session peers for %c",e)}let o=!1,c=new pe({concurrency:this.maxProviders});c.addEventListener("error",()=>{}),c.addEventListener("failure",g=>{this.log.error("error querying provider %o, evicting from session",g.detail.job.options.provider,g.detail.error),this.evict(g.detail.job.options.provider)}),c.addEventListener("success",g=>{o=!0,i.resolve(g.detail.result)}),c.addEventListener("idle",()=>{o||t.signal?.aborted===!0||Promise.resolve().then(async()=>{this.log("no session peers had block for for %c, finding new providers",e);for(let g=0;g<this.minProviders&&this.providers.length!==0;g++){let p=this.providers[Math.floor(Math.random()*this.providers.length)];this.evict(p)}await this.findProviders(e,this.minProviders,t),this.log("found new providers re-retrieving %c",e),this.requests.delete(n),i.resolve(await this.retrieve(e,t))}).catch(g=>{this.log.error("could not find new providers for %c",e,g),i.reject(g)})});let u=g=>{c.add(async()=>this.queryProvider(e,g.detail,t),{provider:g.detail}).catch(p=>{t.signal?.aborted!==!0&&this.log.error("error retrieving session block for %c",e,p)})};this.addEventListener("provider",u),Promise.all([...this.providers].map(async g=>c.add(async()=>this.queryProvider(e,g,t),{provider:g}))).catch(g=>{t.signal?.aborted!==!0&&this.log.error("error retrieving session block for %c",e,g)});try{return await i.promise}finally{this.removeEventListener("provider",u),c.clear(),this.requests.delete(n)}}evict(e){this.evictionFilter.add(this.toEvictionKey(e));let t=this.providers.findIndex(n=>this.equals(n,e));t!==-1&&this.providers.splice(t,1)}isEvicted(e){return this.providers.some(t=>this.equals(t,e))}hasProvider(e){return!!(this.providers.find(t=>this.equals(t,e))!=null||this.isEvicted(e))}async findProviders(e,t,n){let s=T(),i=0;return Promise.resolve().then(async()=>{this.log("finding %d-%d new provider(s) for %c",t,this.maxProviders,e);for await(let o of this.findNewProviders(e,n)){if(i===this.maxProviders||n.signal?.aborted===!0)break;if(!this.hasProvider(o)&&(this.log("found %d/%d new providers",i,this.maxProviders),this.providers.push(o),this.safeDispatchEvent("provider",{detail:o}),i++,i===t&&(this.log("session is ready"),s.resolve()),this.providers.length===this.maxProviders)){this.log("found max session peers",i);break}}if(this.log("found %d/%d new session peers",i,this.maxProviders),i<t)throw new O(`Found ${i} of ${t} ${this.name} providers for ${e}`,"ERR_INSUFFICIENT_PROVIDERS_FOUND")}).catch(o=>{this.log.error("error searching routing for potential session peers for %c",e,o.errors??o),s.reject(o)}),s.promise}};var Or=class extends Ke{wantList;network;constructor(e,t){super(e,{...t,name:"helia:bitswap:session"}),this.wantList=e.wantList,this.network=e.network}async queryProvider(e,t,n){this.log("sending WANT-BLOCK for %c to %p",e,t);let s=await this.wantList.wantSessionBlock(e,t,n);if(this.log("%p %s %c",t,s.has?"has":"does not have",e),s.has&&s.block!=null)return s.block;throw new Error("Provider did not have block")}async*findNewProviders(e,t={}){for await(let n of this.network.findProviders(e,t))yield n.id}toEvictionKey(e){return e.toBytes()}equals(e,t){return e.equals(t)}};function Jn(r,e){return new Or(r,e)}var Ut=class{blocksReceived;duplicateBlocksReceived;dataReceived;duplicateDataReceived;constructor(e){this.blocksReceived=e.libp2p.metrics?.registerMetricGroup("helia_bitswap_received_blocks"),this.duplicateBlocksReceived=e.libp2p.metrics?.registerMetricGroup("helia_bitswap_duplicate_received_blocks"),this.dataReceived=e.libp2p.metrics?.registerMetricGroup("helia_bitswap_data_received_bytes"),this.duplicateDataReceived=e.libp2p.metrics?.registerMetricGroup("helia_bitswap_duplicate_data_received_bytes")}updateBlocksReceived(e=1,t){let n={global:e};t!=null&&(n[t.toString()]=e),this.blocksReceived?.increment(n)}updateDuplicateBlocksReceived(e=1,t){let n={global:e};t!=null&&(n[t.toString()]=e),this.duplicateBlocksReceived?.increment(n)}updateDataReceived(e,t){let n={global:e};t!=null&&(n[t.toString()]=e),this.dataReceived?.increment(n)}updateDuplicateDataReceived(e,t){let n={global:e};t!=null&&(n[t.toString()]=e),this.duplicateDataReceived?.increment(n)}};var zr=class extends Map{metric;constructor(e){super();let{name:t,metrics:n}=e;this.metric=n.registerMetric(t),this.updateComponentMetric()}set(e,t){return super.set(e,t),this.updateComponentMetric(),this}delete(e){let t=super.delete(e);return this.updateComponentMetric(),t}clear(){super.clear(),this.updateComponentMetric()}updateComponentMetric(){this.metric.update(this.size)}};function Kn(r){let{name:e,metrics:t}=r,n;return t!=null?n=new zr({name:e,metrics:t}):n=new Map,n}function xo(r){return r[Symbol.asyncIterator]!=null}function Eo(r){if(xo(r))return(async()=>{let t=[];for await(let n of r)t.push(n);return t})();let e=[];for(let t of r)e.push(t);return e}var Hr=Eo;function vo(r){if(!(r instanceof Uint8Array))throw new Error("arg needs to be a Uint8Array");let e=[];for(;r.length>0;){let t=ye(r);e.push(t),r=r.slice(_(t))}return e}var jn=vo;var Bt=class extends Q{peers;wants;network;log;sendMessagesDelay;sendMessagesTimeout;hashLoader;sendingMessages;constructor(e,t={}){super(),B(1/0,this),this.peers=Qe({name:"helia_bitswap_peers",metrics:e.libp2p.metrics}),this.wants=Kn({name:"helia_bitswap_wantlist",metrics:e.libp2p.metrics}),this.network=e.network,this.sendMessagesDelay=t.sendMessagesDelay??10,this.log=e.logger.forComponent("helia:bitswap:wantlist"),this.hashLoader=t.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(e,t){let n=q(e.multihash.bytes,"base64"),s=this.wants.get(n);s==null&&(s={cid:e,priority:t.priority??1,wantType:t.wantType??D.WantBlock,cancel:!1,sendDontHave:!0},this.wants.set(n,s)),s.wantType===D.WantHave&&t.wantType===D.WantBlock&&(s.wantType=D.WantBlock),await this.sendMessagesDebounced();try{return t.wantType===D.WantBlock?(await $(this,"block",t?.signal,{filter:c=>J(e.multihash.digest,c.detail.cid.multihash.digest),errorMessage:"Want was aborted"})).detail:(await $(this,"presence",t?.signal,{filter:o=>J(e.multihash.digest,o.detail.cid.multihash.digest),errorMessage:"Want was aborted"})).detail}finally{t.signal?.aborted===!0&&(this.log("want for %c was aborted, cancelling want",e),s.cancel=!0,await this.sendMessagesDebounced())}}async sendMessagesDebounced(){await this.sendingMessages?.promise,clearTimeout(this.sendMessagesTimeout),this.sendMessagesTimeout=setTimeout(()=>{this.sendMessages().catch(e=>{this.log("error sending messages to peers",e)})},this.sendMessagesDelay)}async sendMessages(){this.sendingMessages=T(),await Promise.all([...this.peers.entries()].map(async([e,t])=>{let n=new Set,s={wantlist:{full:!1,entries:Ie(this.wants.entries(),i=>Br(i,([o,c])=>{let u=t.has(o);return c.cancel?u:!u}),i=>Re(i,([o,c])=>(n.add(o),{cid:c.cid.bytes,priority:c.priority,wantType:c.wantType,cancel:c.cancel,sendDontHave:c.sendDontHave})),i=>Hr(i))}};if(s.wantlist?.entries.length!==0)try{await this.network.sendMessage(e,s);for(let i of n)t.add(i)}catch(i){this.log.error("error sending full wantlist to new peer",i)}})).catch(e=>{this.log.error("error sending messages",e)});for(let[e,t]of this.wants)if(t.cancel){this.wants.delete(e);for(let n of this.peers.values())n.delete(e)}this.sendingMessages.resolve()}has(e){let t=q(e.multihash.bytes,"base64");return this.wants.has(t)}async wantSessionPresence(e,t,n={}){return await this.network.sendMessage(t,{wantlist:{full:!1,entries:[{cid:e.bytes,sendDontHave:!0,wantType:D.WantHave,priority:1}]}}),(await $(this,"presence",n.signal,{filter:i=>t.equals(i.detail.sender)&&J(e.multihash.digest,i.detail.cid.multihash.digest)})).detail}async wantBlock(e,t={}){return this.addEntry(e,{...t,wantType:D.WantBlock})}async wantSessionBlock(e,t,n={}){return await this.network.sendMessage(t,{wantlist:{full:!1,entries:[{cid:e.bytes,sendDontHave:!0,wantType:D.WantBlock,priority:1}]}}),(await $(this,"presence",n.signal,{filter:i=>t.equals(i.detail.sender)&&J(e.multihash.digest,i.detail.cid.multihash.digest)})).detail}async receivedBlock(e,t){let n=q(e.multihash.bytes,"base64"),s=this.wants.get(n);s!=null&&(s.cancel=!0,await this.sendMessagesDebounced())}async receiveMessage(e,t){this.log("received message from %p",e);let n=!1;for(let s of t.blocks){if(s.prefix==null||s.data==null)continue;let i=jn(s.prefix),o=i[0],c=i[1],u=i[2],g=u===oe.code?oe:await this.hashLoader?.getHasher(u);if(g==null){this.log.error("unknown hash algorithm",u);continue}let p=await g.digest(s.data),h=U.create(o===0?0:1,c,p);this.log("received block from %p for %c",e,h),this.safeDispatchEvent("block",{detail:{sender:e,cid:h,block:s.data}}),this.safeDispatchEvent("presence",{detail:{sender:e,cid:h,has:!0,block:s.data}});let v=q(h.multihash.bytes,"base64"),a=this.wants.get(v);if(a==null)return;a.cancel=!0,n=!0}for(let{cid:s,type:i}of t.blockPresences){let o=U.decode(s);this.log("received %s from %p for %c",i,e,o),this.safeDispatchEvent("presence",{detail:{sender:e,cid:o,has:i===W.HaveBlock}})}n&&await this.sendMessagesDebounced()}async peerConnected(e){let t=new Set,n={wantlist:{full:!0,entries:Ie(this.wants.entries(),s=>Br(s,([i,o])=>!o.cancel),s=>Re(s,([i,o])=>(t.add(i),{cid:o.cid.bytes,priority:1,wantType:D.WantBlock,cancel:!1,sendDontHave:!1})),s=>Hr(s))}};if(n.wantlist?.entries.length===0){this.peers.set(e,t);return}try{await this.network.sendMessage(e,n),this.peers.set(e,t)}catch(s){this.log.error("error sending full wantlist to new peer %p",e,s)}}peerDisconnected(e){this.peers.delete(e)}start(){}stop(){this.peers.clear(),clearTimeout(this.sendMessagesTimeout)}};var Pt=class{log;logger;stats;network;blockstore;peerWantLists;wantList;constructor(e,t={}){this.logger=e.logger,this.log=e.logger.forComponent("helia:bitswap"),this.blockstore=e.blockstore,this.stats=new Ut(e),this.network=new _t(e,t),this.peerWantLists=new Rt({...e,network:this.network},t),this.wantList=new Bt({...e,network:this.network},t)}createSession(e={}){return Jn({wantList:this.wantList,network:this.network,logger:this.logger},e)}async want(e,t={}){let n=new AbortController,s=rt([n.signal,t.signal]);B(1/0,n.signal,s),this.network.findAndConnect(e,{...t,signal:s}).catch(i=>{n.signal.aborted||this.log.error("error during finding and connect for cid %c",e,i)});try{return(await this.wantList.wantBlock(e,{...t,signal:s})).block}finally{n.abort(),s.clear()}}async notify(e,t,n={}){await Promise.all([this.peerWantLists.receivedBlock(e,n),this.wantList.receivedBlock(e,n)])}getWantlist(){return[...this.wantList.wants.values()].filter(e=>!e.cancel).map(e=>({cid:e.cid,priority:e.priority,wantType:e.wantType}))}getPeerWantlist(e){return this.peerWantLists.wantListForPeer(e)}async start(){this.wantList.start(),await this.network.start()}async stop(){this.wantList.stop(),await this.network.stop()}};var So=(r,e={})=>new Pt(r,e);return ns(Lo);})();
|
|
3
|
+
/*! Bundled license information:
|
|
4
|
+
|
|
5
|
+
@noble/hashes/esm/utils.js:
|
|
6
|
+
(*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
|
|
7
|
+
*/
|
|
3
8
|
return HeliaBitswap}));
|
package/dist/src/bitswap.d.ts
CHANGED
|
@@ -2,7 +2,8 @@ import { Network } from './network.js';
|
|
|
2
2
|
import { PeerWantLists } from './peer-want-lists/index.js';
|
|
3
3
|
import { Stats } from './stats.js';
|
|
4
4
|
import { WantList } from './want-list.js';
|
|
5
|
-
import type { BitswapOptions, Bitswap as BitswapInterface, BitswapWantProgressEvents, BitswapNotifyProgressEvents,
|
|
5
|
+
import type { BitswapOptions, Bitswap as BitswapInterface, BitswapWantProgressEvents, BitswapNotifyProgressEvents, WantListEntry, BitswapComponents } from './index.js';
|
|
6
|
+
import type { BlockBroker, CreateSessionOptions } from '@helia/interface';
|
|
6
7
|
import type { PeerId } from '@libp2p/interface';
|
|
7
8
|
import type { AbortOptions } from '@multiformats/multiaddr';
|
|
8
9
|
import type { Blockstore } from 'interface-blockstore';
|
|
@@ -30,7 +31,7 @@ export declare class Bitswap implements BitswapInterface {
|
|
|
30
31
|
peerWantLists: PeerWantLists;
|
|
31
32
|
wantList: WantList;
|
|
32
33
|
constructor(components: BitswapComponents, init?: BitswapOptions);
|
|
33
|
-
createSession(
|
|
34
|
+
createSession(options?: CreateSessionOptions): Required<Pick<BlockBroker<BitswapWantProgressEvents>, 'retrieve'>>;
|
|
34
35
|
want(cid: CID, options?: WantOptions): Promise<Uint8Array>;
|
|
35
36
|
/**
|
|
36
37
|
* Sends notifications about the arrival of a block
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"bitswap.d.ts","sourceRoot":"","sources":["../../src/bitswap.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"bitswap.d.ts","sourceRoot":"","sources":["../../src/bitswap.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,OAAO,EAAE,MAAM,cAAc,CAAA;AACtC,OAAO,EAAE,aAAa,EAAE,MAAM,4BAA4B,CAAA;AAE1D,OAAO,EAAE,KAAK,EAAE,MAAM,YAAY,CAAA;AAClC,OAAO,EAAE,QAAQ,EAAE,MAAM,gBAAgB,CAAA;AACzC,OAAO,KAAK,EAAE,cAAc,EAAE,OAAO,IAAI,gBAAgB,EAAE,yBAAyB,EAAE,2BAA2B,EAAE,aAAa,EAAE,iBAAiB,EAAE,MAAM,YAAY,CAAA;AACvK,OAAO,KAAK,EAAE,WAAW,EAAE,oBAAoB,EAAE,MAAM,kBAAkB,CAAA;AACzE,OAAO,KAAK,EAAmB,MAAM,EAAE,MAAM,mBAAmB,CAAA;AAEhE,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,yBAAyB,CAAA;AAC3D,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,sBAAsB,CAAA;AACtD,OAAO,KAAK,EAAE,GAAG,EAAE,MAAM,kBAAkB,CAAA;AAC3C,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,iBAAiB,CAAA;AAEtD,MAAM,WAAW,WAAY,SAAQ,YAAY,EAAE,eAAe,CAAC,yBAAyB,CAAC;IAC3F;;;;;OAKG;IACH,YAAY,CAAC,EAAE,MAAM,CAAA;CACtB;AAED;;;GAGG;AACH,qBAAa,OAAQ,YAAW,gBAAgB;IAC9C,OAAO,CAAC,QAAQ,CAAC,GAAG,CAAQ;IAC5B,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAiB;IACxC,SAAgB,KAAK,EAAE,KAAK,CAAA;IACrB,OAAO,EAAE,OAAO,CAAA;IAChB,UAAU,EAAE,UAAU,CAAA;IACtB,aAAa,EAAE,aAAa,CAAA;IAC5B,QAAQ,EAAE,QAAQ,CAAA;gBAEZ,UAAU,EAAE,iBAAiB,EAAE,IAAI,GAAE,cAAmB;IAwBrE,aAAa,CAAE,OAAO,GAAE,oBAAyB,GAAG,QAAQ,CAAC,IAAI,CAAC,WAAW,CAAC,yBAAyB,CAAC,EAAE,UAAU,CAAC,CAAC;IAQhH,IAAI,CAAE,GAAG,EAAE,GAAG,EAAE,OAAO,GAAE,WAAgB,GAAG,OAAO,CAAC,UAAU,CAAC;IAiCrE;;OAEG;IACG,MAAM,CAAE,GAAG,EAAE,GAAG,EAAE,KAAK,EAAE,UAAU,EAAE,OAAO,GAAE,eAAe,CAAC,2BAA2B,CAAC,GAAG,YAAiB,GAAG,OAAO,CAAC,IAAI,CAAC;IAOpI,WAAW,IAAK,aAAa,EAAE;IAU/B,eAAe,CAAE,IAAI,EAAE,MAAM,GAAG,aAAa,EAAE,GAAG,SAAS;IAI3D;;OAEG;IACG,KAAK,IAAK,OAAO,CAAC,IAAI,CAAC;IAK7B;;OAEG;IACG,IAAI,IAAK,OAAO,CAAC,IAAI,CAAC;CAI7B"}
|
package/dist/src/bitswap.js
CHANGED
|
@@ -1,5 +1,4 @@
|
|
|
1
1
|
/* eslint-disable no-loop-func */
|
|
2
|
-
import { DEFAULT_SESSION_MAX_PROVIDERS, DEFAULT_SESSION_MIN_PROVIDERS, DEFAULT_SESSION_PROVIDER_QUERY_CONCURRENCY } from '@helia/interface';
|
|
3
2
|
import { setMaxListeners } from '@libp2p/interface';
|
|
4
3
|
import { anySignal } from 'any-signal';
|
|
5
4
|
import { Network } from './network.js';
|
|
@@ -38,26 +37,17 @@ export class Bitswap {
|
|
|
38
37
|
network: this.network
|
|
39
38
|
}, init);
|
|
40
39
|
}
|
|
41
|
-
|
|
42
|
-
const minProviders = options?.minProviders ?? DEFAULT_SESSION_MIN_PROVIDERS;
|
|
43
|
-
const maxProviders = options?.maxProviders ?? DEFAULT_SESSION_MAX_PROVIDERS;
|
|
40
|
+
createSession(options = {}) {
|
|
44
41
|
return createBitswapSession({
|
|
45
42
|
wantList: this.wantList,
|
|
46
43
|
network: this.network,
|
|
47
44
|
logger: this.logger
|
|
48
|
-
},
|
|
49
|
-
root,
|
|
50
|
-
queryConcurrency: options?.providerQueryConcurrency ?? DEFAULT_SESSION_PROVIDER_QUERY_CONCURRENCY,
|
|
51
|
-
minProviders,
|
|
52
|
-
maxProviders,
|
|
53
|
-
connectedPeers: options?.queryConnectedPeers !== false ? [...this.wantList.peers.keys()] : [],
|
|
54
|
-
signal: options?.signal
|
|
55
|
-
});
|
|
45
|
+
}, options);
|
|
56
46
|
}
|
|
57
47
|
async want(cid, options = {}) {
|
|
58
48
|
const controller = new AbortController();
|
|
59
|
-
setMaxListeners(Infinity, controller.signal);
|
|
60
49
|
const signal = anySignal([controller.signal, options.signal]);
|
|
50
|
+
setMaxListeners(Infinity, controller.signal, signal);
|
|
61
51
|
// find providers and connect to them
|
|
62
52
|
this.network.findAndConnect(cid, {
|
|
63
53
|
...options,
|
|
@@ -88,7 +78,10 @@ export class Bitswap {
|
|
|
88
78
|
* Sends notifications about the arrival of a block
|
|
89
79
|
*/
|
|
90
80
|
async notify(cid, block, options = {}) {
|
|
91
|
-
await
|
|
81
|
+
await Promise.all([
|
|
82
|
+
this.peerWantLists.receivedBlock(cid, options),
|
|
83
|
+
this.wantList.receivedBlock(cid, options)
|
|
84
|
+
]);
|
|
92
85
|
}
|
|
93
86
|
getWantlist() {
|
|
94
87
|
return [...this.wantList.wants.values()]
|