@helia/block-brokers 0.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.
Files changed (39) hide show
  1. package/LICENSE +4 -0
  2. package/README.md +45 -0
  3. package/dist/index.min.js +3 -0
  4. package/dist/src/bitswap.d.ts +19 -0
  5. package/dist/src/bitswap.d.ts.map +1 -0
  6. package/dist/src/bitswap.js +48 -0
  7. package/dist/src/bitswap.js.map +1 -0
  8. package/dist/src/index.d.ts +4 -0
  9. package/dist/src/index.d.ts.map +1 -0
  10. package/dist/src/index.js +4 -0
  11. package/dist/src/index.js.map +1 -0
  12. package/dist/src/trustless-gateway/broker.d.ts +15 -0
  13. package/dist/src/trustless-gateway/broker.d.ts.map +1 -0
  14. package/dist/src/trustless-gateway/broker.js +55 -0
  15. package/dist/src/trustless-gateway/broker.js.map +1 -0
  16. package/dist/src/trustless-gateway/index.d.ts +13 -0
  17. package/dist/src/trustless-gateway/index.d.ts.map +1 -0
  18. package/dist/src/trustless-gateway/index.js +15 -0
  19. package/dist/src/trustless-gateway/index.js.map +1 -0
  20. package/dist/src/trustless-gateway/trustless-gateway.d.ts +31 -0
  21. package/dist/src/trustless-gateway/trustless-gateway.d.ts.map +1 -0
  22. package/dist/src/trustless-gateway/trustless-gateway.js +114 -0
  23. package/dist/src/trustless-gateway/trustless-gateway.js.map +1 -0
  24. package/dist/src/utils/default-hashers.d.ts +3 -0
  25. package/dist/src/utils/default-hashers.d.ts.map +1 -0
  26. package/dist/src/utils/default-hashers.js +11 -0
  27. package/dist/src/utils/default-hashers.js.map +1 -0
  28. package/dist/src/utils/networked-storage.d.ts +69 -0
  29. package/dist/src/utils/networked-storage.d.ts.map +1 -0
  30. package/dist/src/utils/networked-storage.js +207 -0
  31. package/dist/src/utils/networked-storage.js.map +1 -0
  32. package/package.json +91 -0
  33. package/src/bitswap.ts +77 -0
  34. package/src/index.ts +3 -0
  35. package/src/trustless-gateway/broker.ts +65 -0
  36. package/src/trustless-gateway/index.ts +33 -0
  37. package/src/trustless-gateway/trustless-gateway.ts +126 -0
  38. package/src/utils/default-hashers.ts +12 -0
  39. package/src/utils/networked-storage.ts +266 -0
package/LICENSE ADDED
@@ -0,0 +1,4 @@
1
+ This project is dual licensed under MIT and Apache-2.0.
2
+
3
+ MIT: https://www.opensource.org/licenses/mit
4
+ Apache-2.0: https://www.apache.org/licenses/license-2.0
package/README.md ADDED
@@ -0,0 +1,45 @@
1
+ <p align="center">
2
+ <a href="https://github.com/ipfs/helia" title="Helia">
3
+ <img src="https://raw.githubusercontent.com/ipfs/helia/main/assets/helia.png" alt="Helia logo" width="300" />
4
+ </a>
5
+ </p>
6
+
7
+ [![ipfs.tech](https://img.shields.io/badge/project-IPFS-blue.svg?style=flat-square)](https://ipfs.tech)
8
+ [![Discuss](https://img.shields.io/discourse/https/discuss.ipfs.tech/posts.svg?style=flat-square)](https://discuss.ipfs.tech)
9
+ [![codecov](https://img.shields.io/codecov/c/github/ipfs/helia.svg?style=flat-square)](https://codecov.io/gh/ipfs/helia)
10
+ [![CI](https://img.shields.io/github/actions/workflow/status/ipfs/helia/main.yml?branch=main\&style=flat-square)](https://github.com/ipfs/helia/actions/workflows/main.yml?query=branch%3Amain)
11
+
12
+ > Block brokers for Helia
13
+
14
+ ## Install
15
+
16
+ ```console
17
+ $ npm i @helia/block-brokers
18
+ ```
19
+
20
+ <!-- ### Browser `<script>` tag
21
+
22
+ Loading this module through a script tag will make it's exports available as `bitswap` and `trustlessGateway` and `NetworkedStorage` in the global namespace.
23
+
24
+ ```html
25
+ <script src="https://unpkg.com/@helia/block-brokers/dist/index.min.js"></script>
26
+ ``` -->
27
+
28
+ ## License
29
+
30
+ Licensed under either of
31
+
32
+ - Apache 2.0, ([LICENSE-APACHE](LICENSE-APACHE) / <http://www.apache.org/licenses/LICENSE-2.0>)
33
+ - MIT ([LICENSE-MIT](LICENSE-MIT) / <http://opensource.org/licenses/MIT>)
34
+
35
+ ## Contribute
36
+
37
+ Contributions welcome! Please check out [the issues](https://github.com/ipfs/helia/issues).
38
+
39
+ Also see our [contributing document](https://github.com/ipfs/community/blob/master/CONTRIBUTING_JS.md) for more information on how we work, and about contributing in general.
40
+
41
+ Please be aware that all interactions related to this repo are subject to the IPFS [Code of Conduct](https://github.com/ipfs/community/blob/master/code-of-conduct.md).
42
+
43
+ Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.
44
+
45
+ [![](https://cdn.rawgit.com/jbenet/contribute-ipfs-gif/master/img/contribute.gif)](https://github.com/ipfs/community/blob/master/CONTRIBUTING.md)
@@ -0,0 +1,3 @@
1
+ (function (root, factory) {(typeof module === 'object' && module.exports) ? module.exports = factory() : root.HeliaBlockBrokers = factory()}(typeof self !== 'undefined' ? self : this, function () {
2
+ "use strict";var HeliaBlockBrokers=(()=>{var Qo=Object.create;var Kt=Object.defineProperty;var Jo=Object.getOwnPropertyDescriptor;var Ko=Object.getOwnPropertyNames;var Zo=Object.getPrototypeOf,Yo=Object.prototype.hasOwnProperty;var I=(r,t)=>()=>(t||r((t={exports:{}}).exports,t),t.exports),A=(r,t)=>{for(var e in t)Kt(r,e,{get:t[e],enumerable:!0})},an=(r,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of Ko(t))!Yo.call(r,s)&&s!==e&&Kt(r,s,{get:()=>t[s],enumerable:!(n=Jo(t,s))||n.enumerable});return r};var G=(r,t,e)=>(e=r!=null?Qo(Zo(r)):{},an(t||!r||!r.__esModule?Kt(e,"default",{value:r,enumerable:!0}):e,r)),ti=r=>an(Kt({},"__esModule",{value:!0}),r);var Fn=I((vu,In)=>{In.exports=Dn;var Bn=128,Hi=127,Vi=~Hi,Wi=Math.pow(2,31);function Dn(r,t,e){t=t||[],e=e||0;for(var n=e;r>=Wi;)t[e++]=r&255|Bn,r/=128;for(;r&Vi;)t[e++]=r&255|Bn,r>>>=7;return t[e]=r|0,Dn.bytes=e-n+1,t}});var Pn=I((_u,Mn)=>{Mn.exports=Ge;var $i=128,Nn=127;function Ge(r,n){var e=0,n=n||0,s=0,o=n,i,a=r.length;do{if(o>=a)throw Ge.bytes=0,new RangeError("Could not decode varint");i=r[o++],e+=s<28?(i&Nn)<<s:(i&Nn)*Math.pow(2,s),s+=7}while(i>=$i);return Ge.bytes=o-n,e}});var Rn=I((ku,Un)=>{var Gi=Math.pow(2,7),ji=Math.pow(2,14),Xi=Math.pow(2,21),Qi=Math.pow(2,28),Ji=Math.pow(2,35),Ki=Math.pow(2,42),Zi=Math.pow(2,49),Yi=Math.pow(2,56),ta=Math.pow(2,63);Un.exports=function(r){return r<Gi?1:r<ji?2:r<Xi?3:r<Qi?4:r<Ji?5:r<Ki?6:r<Zi?7:r<Yi?8:r<ta?9:10}});var zn=I((Su,On)=>{On.exports={encode:Fn(),decode:Pn(),encodingLength:Rn()}});var Vn=I((Eu,Hn)=>{"use strict";var qn=zn();Hn.exports=r=>{if(!(r instanceof Uint8Array))throw new Error("arg needs to be a Uint8Array");let t=[];for(;r.length>0;){let e=qn.decode(r);t.push(e),r=r.slice(qn.decode.bytes)}return t}});var $n=I((Au,Wn)=>{var _t=1e3,kt=_t*60,St=kt*60,it=St*24,ea=it*7,ra=it*365.25;Wn.exports=function(r,t){t=t||{};var e=typeof r;if(e==="string"&&r.length>0)return na(r);if(e==="number"&&isFinite(r))return t.long?oa(r):sa(r);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(r))};function na(r){if(r=String(r),!(r.length>100)){var t=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(r);if(t){var e=parseFloat(t[1]),n=(t[2]||"ms").toLowerCase();switch(n){case"years":case"year":case"yrs":case"yr":case"y":return e*ra;case"weeks":case"week":case"w":return e*ea;case"days":case"day":case"d":return e*it;case"hours":case"hour":case"hrs":case"hr":case"h":return e*St;case"minutes":case"minute":case"mins":case"min":case"m":return e*kt;case"seconds":case"second":case"secs":case"sec":case"s":return e*_t;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return e;default:return}}}}function sa(r){var t=Math.abs(r);return t>=it?Math.round(r/it)+"d":t>=St?Math.round(r/St)+"h":t>=kt?Math.round(r/kt)+"m":t>=_t?Math.round(r/_t)+"s":r+"ms"}function oa(r){var t=Math.abs(r);return t>=it?te(r,t,it,"day"):t>=St?te(r,t,St,"hour"):t>=kt?te(r,t,kt,"minute"):t>=_t?te(r,t,_t,"second"):r+" ms"}function te(r,t,e,n){var s=t>=e*1.5;return Math.round(r/e)+" "+n+(s?"s":"")}});var jn=I((Cu,Gn)=>{function ia(r){e.debug=e,e.default=e,e.coerce=c,e.disable=o,e.enable=s,e.enabled=i,e.humanize=$n(),e.destroy=l,Object.keys(r).forEach(h=>{e[h]=r[h]}),e.names=[],e.skips=[],e.formatters={};function t(h){let u=0;for(let d=0;d<h.length;d++)u=(u<<5)-u+h.charCodeAt(d),u|=0;return e.colors[Math.abs(u)%e.colors.length]}e.selectColor=t;function e(h){let u,d=null,b,f;function p(...m){if(!p.enabled)return;let g=p,y=Number(new Date),v=y-(u||y);g.diff=v,g.prev=u,g.curr=y,u=y,m[0]=e.coerce(m[0]),typeof m[0]!="string"&&m.unshift("%O");let x=0;m[0]=m[0].replace(/%([a-zA-Z%])/g,(D,E)=>{if(D==="%%")return"%";x++;let T=e.formatters[E];if(typeof T=="function"){let W=m[x];D=T.call(g,W),m.splice(x,1),x--}return D}),e.formatArgs.call(g,m),(g.log||e.log).apply(g,m)}return p.namespace=h,p.useColors=e.useColors(),p.color=e.selectColor(h),p.extend=n,p.destroy=e.destroy,Object.defineProperty(p,"enabled",{enumerable:!0,configurable:!1,get:()=>d!==null?d:(b!==e.namespaces&&(b=e.namespaces,f=e.enabled(h)),f),set:m=>{d=m}}),typeof e.init=="function"&&e.init(p),p}function n(h,u){let d=e(this.namespace+(typeof u>"u"?":":u)+h);return d.log=this.log,d}function s(h){e.save(h),e.namespaces=h,e.names=[],e.skips=[];let u,d=(typeof h=="string"?h:"").split(/[\s,]+/),b=d.length;for(u=0;u<b;u++)d[u]&&(h=d[u].replace(/\*/g,".*?"),h[0]==="-"?e.skips.push(new RegExp("^"+h.slice(1)+"$")):e.names.push(new RegExp("^"+h+"$")))}function o(){let h=[...e.names.map(a),...e.skips.map(a).map(u=>"-"+u)].join(",");return e.enable(""),h}function i(h){if(h[h.length-1]==="*")return!0;let u,d;for(u=0,d=e.skips.length;u<d;u++)if(e.skips[u].test(h))return!1;for(u=0,d=e.names.length;u<d;u++)if(e.names[u].test(h))return!0;return!1}function a(h){return h.toString().substring(2,h.toString().length-2).replace(/\.\*\?$/,"*")}function c(h){return h instanceof Error?h.stack||h.message:h}function l(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return e.enable(e.load()),e}Gn.exports=ia});var Xn=I((z,ee)=>{z.formatArgs=ca;z.save=la;z.load=ha;z.useColors=aa;z.storage=ua();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 aa(){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 ca(r){if(r[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+r[0]+(this.useColors?"%c ":" ")+"+"+ee.exports.humanize(this.diff),!this.useColors)return;let t="color: "+this.color;r.splice(1,0,t,"color: inherit");let e=0,n=0;r[0].replace(/%[a-zA-Z%]/g,s=>{s!=="%%"&&(e++,s==="%c"&&(n=e))}),r.splice(n,0,t)}z.log=console.debug||console.log||(()=>{});function la(r){try{r?z.storage.setItem("debug",r):z.storage.removeItem("debug")}catch{}}function ha(){let r;try{r=z.storage.getItem("debug")}catch{}return!r&&typeof process<"u"&&"env"in process&&(r=process.env.DEBUG),r}function ua(){try{return localStorage}catch{}}ee.exports=jn()(z);var{formatters:fa}=ee.exports;fa.j=function(r){try{return JSON.stringify(r)}catch(t){return"[UnexpectedJSONParseError]: "+t.message}}});var os=I((Yu,ss)=>{ss.exports=er;var ns=128,Da=127,Ia=~Da,Fa=Math.pow(2,31);function er(r,t,e){if(Number.MAX_SAFE_INTEGER&&r>Number.MAX_SAFE_INTEGER)throw er.bytes=0,new RangeError("Could not encode varint");t=t||[],e=e||0;for(var n=e;r>=Fa;)t[e++]=r&255|ns,r/=128;for(;r&Ia;)t[e++]=r&255|ns,r>>>=7;return t[e]=r|0,er.bytes=e-n+1,t}});var cs=I((tf,as)=>{as.exports=rr;var Na=128,is=127;function rr(r,n){var e=0,n=n||0,s=0,o=n,i,a=r.length;do{if(o>=a||s>49)throw rr.bytes=0,new RangeError("Could not decode varint");i=r[o++],e+=s<28?(i&is)<<s:(i&is)*Math.pow(2,s),s+=7}while(i>=Na);return rr.bytes=o-n,e}});var hs=I((ef,ls)=>{var Ma=Math.pow(2,7),Pa=Math.pow(2,14),Ua=Math.pow(2,21),Ra=Math.pow(2,28),Oa=Math.pow(2,35),za=Math.pow(2,42),qa=Math.pow(2,49),Ha=Math.pow(2,56),Va=Math.pow(2,63);ls.exports=function(r){return r<Ma?1:r<Pa?2:r<Ua?3:r<Ra?4:r<Oa?5:r<za?6:r<qa?7:r<Ha?8:r<Va?9:10}});var fs=I((rf,us)=>{us.exports={encode:os(),decode:cs(),encodingLength:hs()}});var Ks=I((pp,Js)=>{"use strict";function Qs(r,t){for(let e in t)Object.defineProperty(r,e,{value:t[e],enumerable:!0,configurable:!0});return r}function rl(r,t,e){if(!r||typeof r=="string")throw new TypeError("Please pass an Error to err-code");e||(e={}),typeof t=="object"&&(e=t,t=""),t&&(e.code=t);try{return Qs(r,e)}catch{e.message=r.message,e.stack=r.stack;let s=function(){};return s.prototype=Object.create(Object.getPrototypeOf(r)),Qs(new s,e)}}Js.exports=rl});var so=I((Np,no)=>{"use strict";no.exports=function(){return Date.now()}});var io=I((Mp,oo)=>{"use strict";var xe=so(),Or=class{constructor(t,e,n){let s=this;this._started=xe(),this._rescheduled=0,this._scheduled=e,this._args=n,this._triggered=!1,this._timerWrapper=()=>{s._rescheduled>0?(s._scheduled=s._rescheduled-(xe()-s._started),s._schedule(s._scheduled)):(s._triggered=!0,t.apply(null,s._args))},this._timer=setTimeout(this._timerWrapper,e)}reschedule(t){t||(t=this._scheduled);let e=xe();e+t-(this._started+this._scheduled)<0?(clearTimeout(this._timer),this._schedule(t)):this._triggered?this._schedule(t):(this._started=e,this._rescheduled=t)}_schedule(t){this._triggered=!1,this._started=xe(),this._rescheduled=0,this._scheduled=t,this._timer=setTimeout(this._timerWrapper,t)}clear(){clearTimeout(this._timer)}};function ml(){if(typeof arguments[0]!="function")throw new Error("callback needed");if(typeof arguments[1]!="number")throw new Error("timeout needed");let r;if(arguments.length>0){r=new Array(arguments.length-2);for(var t=0;t<r.length;t++)r[t]=arguments[t+2]}return new Or(arguments[0],arguments[1],r)}oo.exports=ml});var lo=I((Pp,co)=>{"use strict";var{AbortController:gl}=globalThis,ao=io(),zr=class r extends gl{constructor(t){super(),this._ms=t,this._timer=ao(()=>this.abort(),t),Object.setPrototypeOf(this,r.prototype)}abort(){return this._timer.clear(),super.abort()}clear(){this._timer.clear()}reset(){this._timer.clear(),this._timer=ao(()=>this.abort(),this._ms)}};co.exports={TimeoutController:zr}});var Se=I((Gp,$r)=>{"use strict";var Ft=typeof Reflect=="object"?Reflect:null,mo=Ft&&typeof Ft.apply=="function"?Ft.apply:function(t,e,n){return Function.prototype.apply.call(t,e,n)},_e;Ft&&typeof Ft.ownKeys=="function"?_e=Ft.ownKeys:Object.getOwnPropertySymbols?_e=function(t){return Object.getOwnPropertyNames(t).concat(Object.getOwnPropertySymbols(t))}:_e=function(t){return Object.getOwnPropertyNames(t)};function vl(r){console&&console.warn&&console.warn(r)}var bo=Number.isNaN||function(t){return t!==t};function S(){S.init.call(this)}$r.exports=S;$r.exports.once=El;S.EventEmitter=S;S.prototype._events=void 0;S.prototype._eventsCount=0;S.prototype._maxListeners=void 0;var go=10;function ke(r){if(typeof r!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof r)}Object.defineProperty(S,"defaultMaxListeners",{enumerable:!0,get:function(){return go},set:function(r){if(typeof r!="number"||r<0||bo(r))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+r+".");go=r}});S.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0};S.prototype.setMaxListeners=function(t){if(typeof t!="number"||t<0||bo(t))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+t+".");return this._maxListeners=t,this};function yo(r){return r._maxListeners===void 0?S.defaultMaxListeners:r._maxListeners}S.prototype.getMaxListeners=function(){return yo(this)};S.prototype.emit=function(t){for(var e=[],n=1;n<arguments.length;n++)e.push(arguments[n]);var s=t==="error",o=this._events;if(o!==void 0)s=s&&o.error===void 0;else if(!s)return!1;if(s){var i;if(e.length>0&&(i=e[0]),i instanceof Error)throw i;var a=new Error("Unhandled error."+(i?" ("+i.message+")":""));throw a.context=i,a}var c=o[t];if(c===void 0)return!1;if(typeof c=="function")mo(c,this,e);else for(var l=c.length,h=ko(c,l),n=0;n<l;++n)mo(h[n],this,e);return!0};function wo(r,t,e,n){var s,o,i;if(ke(e),o=r._events,o===void 0?(o=r._events=Object.create(null),r._eventsCount=0):(o.newListener!==void 0&&(r.emit("newListener",t,e.listener?e.listener:e),o=r._events),i=o[t]),i===void 0)i=o[t]=e,++r._eventsCount;else if(typeof i=="function"?i=o[t]=n?[e,i]:[i,e]:n?i.unshift(e):i.push(e),s=yo(r),s>0&&i.length>s&&!i.warned){i.warned=!0;var a=new Error("Possible EventEmitter memory leak detected. "+i.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");a.name="MaxListenersExceededWarning",a.emitter=r,a.type=t,a.count=i.length,vl(a)}return r}S.prototype.addListener=function(t,e){return wo(this,t,e,!1)};S.prototype.on=S.prototype.addListener;S.prototype.prependListener=function(t,e){return wo(this,t,e,!0)};function _l(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function xo(r,t,e){var n={fired:!1,wrapFn:void 0,target:r,type:t,listener:e},s=_l.bind(n);return s.listener=e,n.wrapFn=s,s}S.prototype.once=function(t,e){return ke(e),this.on(t,xo(this,t,e)),this};S.prototype.prependOnceListener=function(t,e){return ke(e),this.prependListener(t,xo(this,t,e)),this};S.prototype.removeListener=function(t,e){var n,s,o,i,a;if(ke(e),s=this._events,s===void 0)return this;if(n=s[t],n===void 0)return this;if(n===e||n.listener===e)--this._eventsCount===0?this._events=Object.create(null):(delete s[t],s.removeListener&&this.emit("removeListener",t,n.listener||e));else if(typeof n!="function"){for(o=-1,i=n.length-1;i>=0;i--)if(n[i]===e||n[i].listener===e){a=n[i].listener,o=i;break}if(o<0)return this;o===0?n.shift():kl(n,o),n.length===1&&(s[t]=n[0]),s.removeListener!==void 0&&this.emit("removeListener",t,a||e)}return this};S.prototype.off=S.prototype.removeListener;S.prototype.removeAllListeners=function(t){var e,n,s;if(n=this._events,n===void 0)return this;if(n.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):n[t]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete n[t]),this;if(arguments.length===0){var o=Object.keys(n),i;for(s=0;s<o.length;++s)i=o[s],i!=="removeListener"&&this.removeAllListeners(i);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(e=n[t],typeof e=="function")this.removeListener(t,e);else if(e!==void 0)for(s=e.length-1;s>=0;s--)this.removeListener(t,e[s]);return this};function vo(r,t,e){var n=r._events;if(n===void 0)return[];var s=n[t];return s===void 0?[]:typeof s=="function"?e?[s.listener||s]:[s]:e?Sl(s):ko(s,s.length)}S.prototype.listeners=function(t){return vo(this,t,!0)};S.prototype.rawListeners=function(t){return vo(this,t,!1)};S.listenerCount=function(r,t){return typeof r.listenerCount=="function"?r.listenerCount(t):_o.call(r,t)};S.prototype.listenerCount=_o;function _o(r){var t=this._events;if(t!==void 0){var e=t[r];if(typeof e=="function")return 1;if(e!==void 0)return e.length}return 0}S.prototype.eventNames=function(){return this._eventsCount>0?_e(this._events):[]};function ko(r,t){for(var e=new Array(t),n=0;n<t;++n)e[n]=r[n];return e}function kl(r,t){for(;t+1<r.length;t++)r[t]=r[t+1];r.pop()}function Sl(r){for(var t=new Array(r.length),e=0;e<t.length;++e)t[e]=r[e].listener||r[e];return t}function El(r,t){return new Promise(function(e,n){function s(i){r.removeListener(t,o),n(i)}function o(){typeof r.removeListener=="function"&&r.removeListener("error",s),e([].slice.call(arguments))}So(r,t,o,{once:!0}),t!=="error"&&Al(r,s,{once:!0})})}function Al(r,t,e){typeof r.on=="function"&&So(r,"error",t,e)}function So(r,t,e,n){if(typeof r.on=="function")n.once?r.once(t,e):r.on(t,e);else if(typeof r.addEventListener=="function")r.addEventListener(t,function s(o){n.once&&r.removeEventListener(t,s),e(o)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof r)}});var Ro=I((Po,Uo)=>{"use strict";var Jl=Math.exp;Po=Uo.exports=function(t){if(typeof t!="number")throw new Error("must provide a timespan to the moving average constructor");if(t<=0)throw new Error("must provide a timespan > 0 to the moving average constructor");let e,n=0,s=0,o=0,i,a={};function c(l,h){return 1-Jl(-(l-h)/t)}return a.push=function(h,u){if(i){let d=c(h,i),b=u-e,f=d*b;e=d*u+(1-d)*e,n=(1-d)*(n+b*f),s=Math.sqrt(n),o=e+d*b}else e=u;i=h},a.movingAverage=function(){return e},a.variance=function(){return n},a.deviation=function(){return s},a.forecast=function(){return o},a}});var ih={};A(ih,{NetworkedStorage:()=>Ie,bitswap:()=>Wo,trustlessGateway:()=>Go});function Zt(r){let t=new globalThis.AbortController;function e(){t.abort();for(let o of r)o?.removeEventListener!=null&&o.removeEventListener("abort",e)}for(let o of r){if(o?.aborted===!0){e();break}o?.addEventListener!=null&&o.addEventListener("abort",e)}function n(){for(let o of r)o?.removeEventListener!=null&&o.removeEventListener("abort",e)}let s=t.signal;return s.clear=n,s}function ei(r){let[t,e]=r[Symbol.asyncIterator]!=null?[r[Symbol.asyncIterator](),Symbol.asyncIterator]:[r[Symbol.iterator](),Symbol.iterator],n=[];return{peek:()=>t.next(),push:s=>{n.push(s)},next:()=>n.length>0?{done:!1,value:n.shift()}:t.next(),[e](){return this}}}var gt=ei;function ri(r){return r[Symbol.asyncIterator]!=null}function cn(r){return r?.then!=null}function ni(r,t){if(ri(r))return async function*(){for await(let a of r){let c=t(a);cn(c)&&await c,yield a}}();let e=gt(r),{value:n,done:s}=e.next();if(s===!0)return function*(){}();if(typeof t(n)?.then=="function")return async function*(){yield n;for await(let a of e){let c=t(a);cn(c)&&await c,yield a}}();let i=t;return function*(){yield n;for(let a of e)i(a),yield a}()}var Nt=ni;var Ue={};A(Ue,{base32:()=>yt,base32hex:()=>fi,base32hexpad:()=>pi,base32hexpadupper:()=>mi,base32hexupper:()=>di,base32pad:()=>hi,base32padupper:()=>ui,base32upper:()=>li,base32z:()=>gi});function si(r,t){if(r.length>=255)throw new TypeError("Alphabet too long");for(var e=new Uint8Array(256),n=0;n<e.length;n++)e[n]=255;for(var s=0;s<r.length;s++){var o=r.charAt(s),i=o.charCodeAt(0);if(e[i]!==255)throw new TypeError(o+" is ambiguous");e[i]=s}var a=r.length,c=r.charAt(0),l=Math.log(a)/Math.log(256),h=Math.log(256)/Math.log(a);function u(f){if(f instanceof Uint8Array||(ArrayBuffer.isView(f)?f=new Uint8Array(f.buffer,f.byteOffset,f.byteLength):Array.isArray(f)&&(f=Uint8Array.from(f))),!(f instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(f.length===0)return"";for(var p=0,m=0,g=0,y=f.length;g!==y&&f[g]===0;)g++,p++;for(var v=(y-g)*h+1>>>0,x=new Uint8Array(v);g!==y;){for(var C=f[g],D=0,E=v-1;(C!==0||D<m)&&E!==-1;E--,D++)C+=256*x[E]>>>0,x[E]=C%a>>>0,C=C/a>>>0;if(C!==0)throw new Error("Non-zero carry");m=D,g++}for(var T=v-m;T!==v&&x[T]===0;)T++;for(var W=c.repeat(p);T<v;++T)W+=r.charAt(x[T]);return W}function d(f){if(typeof f!="string")throw new TypeError("Expected String");if(f.length===0)return new Uint8Array;var p=0;if(f[p]!==" "){for(var m=0,g=0;f[p]===c;)m++,p++;for(var y=(f.length-p)*l+1>>>0,v=new Uint8Array(y);f[p];){var x=e[f.charCodeAt(p)];if(x===255)return;for(var C=0,D=y-1;(x!==0||C<g)&&D!==-1;D--,C++)x+=a*v[D]>>>0,v[D]=x%256>>>0,x=x/256>>>0;if(x!==0)throw new Error("Non-zero carry");g=C,p++}if(f[p]!==" "){for(var E=y-g;E!==y&&v[E]===0;)E++;for(var T=new Uint8Array(m+(y-E)),W=m;E!==y;)T[W++]=v[E++];return T}}}function b(f){var p=d(f);if(p)return p;throw new Error(`Non-${t} character`)}return{encode:u,decodeUnsafe:d,decode:b}}var oi=si,ii=oi,ln=ii;var dh=new Uint8Array(0);var hn=(r,t)=>{if(r===t)return!0;if(r.byteLength!==t.byteLength)return!1;for(let e=0;e<r.byteLength;e++)if(r[e]!==t[e])return!1;return!0},j=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")};var un=r=>new TextEncoder().encode(r),fn=r=>new TextDecoder().decode(r);var Fe=class{constructor(t,e,n){this.name=t,this.prefix=e,this.baseEncode=n}encode(t){if(t instanceof Uint8Array)return`${this.prefix}${this.baseEncode(t)}`;throw Error("Unknown type, must be binary type")}},Ne=class{constructor(t,e,n){if(this.name=t,this.prefix=e,e.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=e.codePointAt(0),this.baseDecode=n}decode(t){if(typeof t=="string"){if(t.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(t)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(t.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(t){return pn(this,t)}},Me=class{constructor(t){this.decoders=t}or(t){return pn(this,t)}decode(t){let e=t[0],n=this.decoders[e];if(n)return n.decode(t);throw RangeError(`Unable to decode multibase string ${JSON.stringify(t)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}},pn=(r,t)=>new Me({...r.decoders||{[r.prefix]:r},...t.decoders||{[t.prefix]:t}}),Pe=class{constructor(t,e,n,s){this.name=t,this.prefix=e,this.baseEncode=n,this.baseDecode=s,this.encoder=new Fe(t,e,n),this.decoder=new Ne(t,e,s)}encode(t){return this.encoder.encode(t)}decode(t){return this.decoder.decode(t)}},bt=({name:r,prefix:t,encode:e,decode:n})=>new Pe(r,t,e,n),K=({prefix:r,name:t,alphabet:e})=>{let{encode:n,decode:s}=ln(e,t);return bt({prefix:r,name:t,encode:n,decode:o=>j(s(o))})},ai=(r,t,e,n)=>{let s={};for(let h=0;h<t.length;++h)s[t[h]]=h;let o=r.length;for(;r[o-1]==="=";)--o;let i=new Uint8Array(o*e/8|0),a=0,c=0,l=0;for(let h=0;h<o;++h){let u=s[r[h]];if(u===void 0)throw new SyntaxError(`Non-${n} character`);c=c<<e|u,a+=e,a>=8&&(a-=8,i[l++]=255&c>>a)}if(a>=e||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return i},ci=(r,t,e)=>{let n=t[t.length-1]==="=",s=(1<<e)-1,o="",i=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],i+=8;i>e;)i-=e,o+=t[s&a>>i];if(i&&(o+=t[s&a<<e-i]),n)for(;o.length*e&7;)o+="=";return o},L=({name:r,prefix:t,bitsPerChar:e,alphabet:n})=>bt({prefix:t,name:r,encode(s){return ci(s,n,e)},decode(s){return ai(s,n,e,r)}});var yt=L({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),li=L({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),hi=L({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),ui=L({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),fi=L({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),di=L({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),pi=L({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),mi=L({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),gi=L({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Re={};A(Re,{base58btc:()=>w,base58flickr:()=>bi});var w=K({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),bi=K({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var yi=bn,mn=128,wi=127,xi=~wi,vi=Math.pow(2,31);function bn(r,t,e){t=t||[],e=e||0;for(var n=e;r>=vi;)t[e++]=r&255|mn,r/=128;for(;r&xi;)t[e++]=r&255|mn,r>>>=7;return t[e]=r|0,bn.bytes=e-n+1,t}var _i=Oe,ki=128,gn=127;function Oe(r,n){var e=0,n=n||0,s=0,o=n,i,a=r.length;do{if(o>=a)throw Oe.bytes=0,new RangeError("Could not decode varint");i=r[o++],e+=s<28?(i&gn)<<s:(i&gn)*Math.pow(2,s),s+=7}while(i>=ki);return Oe.bytes=o-n,e}var Si=Math.pow(2,7),Ei=Math.pow(2,14),Ai=Math.pow(2,21),Ci=Math.pow(2,28),Ti=Math.pow(2,35),Li=Math.pow(2,42),Bi=Math.pow(2,49),Di=Math.pow(2,56),Ii=Math.pow(2,63),Fi=function(r){return r<Si?1:r<Ei?2:r<Ai?3:r<Ci?4:r<Ti?5:r<Li?6:r<Bi?7:r<Di?8:r<Ii?9:10},Ni={encode:yi,decode:_i,encodingLength:Fi},Mi=Ni,Mt=Mi;var Pt=(r,t=0)=>[Mt.decode(r,t),Mt.decode.bytes],wt=(r,t,e=0)=>(Mt.encode(r,t,e),t),xt=r=>Mt.encodingLength(r);var ot=(r,t)=>{let e=t.byteLength,n=xt(r),s=n+xt(e),o=new Uint8Array(s+e);return wt(r,o,0),wt(e,o,n),o.set(t,s),new vt(r,e,t,o)},yn=r=>{let t=j(r),[e,n]=Pt(t),[s,o]=Pt(t.subarray(n)),i=t.subarray(n+o);if(i.byteLength!==s)throw new Error("Incorrect length");return new vt(e,s,i,t)},wn=(r,t)=>{if(r===t)return!0;{let e=t;return r.code===e.code&&r.size===e.size&&e.bytes instanceof Uint8Array&&hn(r.bytes,e.bytes)}},vt=class{constructor(t,e,n,s){this.code=t,this.size=e,this.digest=n,this.bytes=s}};var xn=(r,t)=>{let{bytes:e,version:n}=r;switch(n){case 0:return Ui(e,ze(r),t||w.encoder);default:return Ri(e,ze(r),t||yt.encoder)}};var vn=new WeakMap,ze=r=>{let t=vn.get(r);if(t==null){let e=new Map;return vn.set(r,e),e}return t},F=class r{constructor(t,e,n,s){this.code=e,this.version=t,this.multihash=n,this.bytes=s,this["/"]=s}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:t,multihash:e}=this;if(t!==Rt)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(e.code!==Oi)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return r.createV0(e)}default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}toV1(){switch(this.version){case 0:{let{code:t,digest:e}=this.multihash,n=ot(t,e);return r.createV1(this.code,n)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(t){return r.equals(this,t)}static equals(t,e){let n=e;return n&&t.code===n.code&&t.version===n.version&&wn(t.multihash,n.multihash)}toString(t){return xn(this,t)}toJSON(){return{"/":xn(this)}}link(){return this}get[Symbol.toStringTag](){return"CID"}[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(t){if(t==null)return null;let e=t;if(e instanceof r)return e;if(e["/"]!=null&&e["/"]===e.bytes||e.asCID===e){let{version:n,code:s,multihash:o,bytes:i}=e;return new r(n,s,o,i||_n(n,s,o.bytes))}else if(e[zi]===!0){let{version:n,multihash:s,code:o}=e,i=yn(s);return r.create(n,o,i)}else return null}static create(t,e,n){if(typeof e!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(t){case 0:{if(e!==Rt)throw new Error(`Version 0 CID must use dag-pb (code: ${Rt}) block encoding`);return new r(t,e,n,n.bytes)}case 1:{let s=_n(t,e,n.bytes);return new r(t,e,n,s)}default:throw new Error("Invalid version")}}static createV0(t){return r.create(0,Rt,t)}static createV1(t,e){return r.create(1,t,e)}static decode(t){let[e,n]=r.decodeFirst(t);if(n.length)throw new Error("Incorrect length");return e}static decodeFirst(t){let e=r.inspectBytes(t),n=e.size-e.multihashSize,s=j(t.subarray(n,n+e.multihashSize));if(s.byteLength!==e.multihashSize)throw new Error("Incorrect length");let o=s.subarray(e.multihashSize-e.digestSize),i=new vt(e.multihashCode,e.digestSize,o,s);return[e.version===0?r.createV0(i):r.createV1(e.codec,i),t.subarray(e.size)]}static inspectBytes(t){let e=0,n=()=>{let[u,d]=Pt(t.subarray(e));return e+=d,u},s=n(),o=Rt;if(s===18?(s=0,e=0):o=n(),s!==0&&s!==1)throw new RangeError(`Invalid CID version ${s}`);let i=e,a=n(),c=n(),l=e+c,h=l-i;return{version:s,codec:o,multihashCode:a,digestSize:c,multihashSize:h,size:l}}static parse(t,e){let[n,s]=Pi(t,e),o=r.decode(s);if(o.version===0&&t[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return ze(o).set(n,t),o}},Pi=(r,t)=>{switch(r[0]){case"Q":{let e=t||w;return[w.prefix,e.decode(`${w.prefix}${r}`)]}case w.prefix:{let e=t||w;return[w.prefix,e.decode(r)]}case yt.prefix:{let e=t||yt;return[yt.prefix,e.decode(r)]}default:{if(t==null)throw Error("To parse non base32 or base58btc encoded CID multibase decoder must be provided");return[r[0],t.decode(r)]}}},Ui=(r,t,e)=>{let{prefix:n}=e;if(n!==w.prefix)throw Error(`Cannot string encode V0 in ${e.name} encoding`);let s=t.get(n);if(s==null){let o=e.encode(r).slice(1);return t.set(n,o),o}else return s},Ri=(r,t,e)=>{let{prefix:n}=e,s=t.get(n);if(s==null){let o=e.encode(r);return t.set(n,o),o}else return s},Rt=112,Oi=18,_n=(r,t,e)=>{let n=xt(r),s=n+xt(t),o=new Uint8Array(s+e.byteLength);return wt(r,o,0),wt(t,o,n),o.set(e,s),o},zi=Symbol.for("@ipld/js-cid/CID");var qe=class extends Map{metric;constructor(t){super();let{name:e,metrics:n}=t;this.metric=n.registerMetric(e),this.updateComponentMetric()}set(t,e){return super.set(t,e),this.updateComponentMetric(),this}delete(t){let e=super.delete(t);return this.updateComponentMetric(),e}clear(){super.clear(),this.updateComponentMetric()}updateComponentMetric(){this.metric.update(this.size)}};function Z(r){let{name:t,metrics:e}=r,n;return e!=null?n=new qe({name:t,metrics:e}):n=new Map,n}var Th=Symbol.for("@libp2p/connection");var Bh=Symbol.for("@libp2p/content-routing");var Fh=Symbol.for("@libp2p/peer-discovery");var Mh=Symbol.for("@libp2p/peer-id");var Uh=Symbol.for("@libp2p/peer-routing");var kn;(function(r){r.Accept="accept",r.Ignore="ignore",r.Reject="reject"})(kn||(kn={}));var qh=Symbol.for("@libp2p/transport");var Sn;(function(r){r[r.FATAL_ALL=0]="FATAL_ALL",r[r.NO_FATAL=1]="NO_FATAL"})(Sn||(Sn={}));var X=class extends Error{code;props;constructor(t,e,n){super(t),this.code=e,this.name=n?.name??"CodeError",this.props=n??{}}};var He=class extends Event{detail;constructor(t,e){super(t,e),this.detail=e?.detail}},Wh=globalThis.CustomEvent??He;function En(r){return r!=null&&typeof r.start=="function"&&typeof r.stop=="function"}async function An(...r){let t=[];for(let e of r)En(e)&&t.push(e);await Promise.all(t.map(async e=>{e.beforeStart!=null&&await e.beforeStart()})),await Promise.all(t.map(async e=>{await e.start()})),await Promise.all(t.map(async e=>{e.afterStart!=null&&await e.afterStart()}))}async function Cn(...r){let t=[];for(let e of r)En(e)&&t.push(e);await Promise.all(t.map(async e=>{e.beforeStop!=null&&await e.beforeStop()})),await Promise.all(t.map(async e=>{await e.stop()})),await Promise.all(t.map(async e=>{e.afterStop!=null&&await e.afterStop()}))}var $e={};A($e,{sha256:()=>Ot,sha512:()=>qi});var We=({name:r,code:t,encode:e})=>new Ve(r,t,e),Ve=class{constructor(t,e,n){this.name=t,this.code=e,this.encode=n}digest(t){if(t instanceof Uint8Array){let e=this.encode(t);return e instanceof Uint8Array?ot(this.code,e):e.then(n=>ot(this.code,n))}else throw Error("Unknown type, must be binary type")}};var Ln=r=>async t=>new Uint8Array(await crypto.subtle.digest(r,t)),Ot=We({name:"sha2-256",code:18,encode:Ln("SHA-256")}),qi=We({name:"sha2-512",code:19,encode:Ln("SHA-512")});var Os=G(Vn(),1);var q=G(Xn(),1);var Ke={};A(Ke,{base32:()=>tt,base32hex:()=>va,base32hexpad:()=>ka,base32hexpadupper:()=>Sa,base32hexupper:()=>_a,base32pad:()=>wa,base32padupper:()=>xa,base32upper:()=>ya,base32z:()=>Ea});var Tu=new Uint8Array(0);function Qn(r,t){if(r===t)return!0;if(r.byteLength!==t.byteLength)return!1;for(let e=0;e<r.byteLength;e++)if(r[e]!==t[e])return!1;return!0}function Q(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 Jn(r){return new TextEncoder().encode(r)}function Kn(r){return new TextDecoder().decode(r)}function da(r,t){if(r.length>=255)throw new TypeError("Alphabet too long");for(var e=new Uint8Array(256),n=0;n<e.length;n++)e[n]=255;for(var s=0;s<r.length;s++){var o=r.charAt(s),i=o.charCodeAt(0);if(e[i]!==255)throw new TypeError(o+" is ambiguous");e[i]=s}var a=r.length,c=r.charAt(0),l=Math.log(a)/Math.log(256),h=Math.log(256)/Math.log(a);function u(f){if(f instanceof Uint8Array||(ArrayBuffer.isView(f)?f=new Uint8Array(f.buffer,f.byteOffset,f.byteLength):Array.isArray(f)&&(f=Uint8Array.from(f))),!(f instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(f.length===0)return"";for(var p=0,m=0,g=0,y=f.length;g!==y&&f[g]===0;)g++,p++;for(var v=(y-g)*h+1>>>0,x=new Uint8Array(v);g!==y;){for(var C=f[g],D=0,E=v-1;(C!==0||D<m)&&E!==-1;E--,D++)C+=256*x[E]>>>0,x[E]=C%a>>>0,C=C/a>>>0;if(C!==0)throw new Error("Non-zero carry");m=D,g++}for(var T=v-m;T!==v&&x[T]===0;)T++;for(var W=c.repeat(p);T<v;++T)W+=r.charAt(x[T]);return W}function d(f){if(typeof f!="string")throw new TypeError("Expected String");if(f.length===0)return new Uint8Array;var p=0;if(f[p]!==" "){for(var m=0,g=0;f[p]===c;)m++,p++;for(var y=(f.length-p)*l+1>>>0,v=new Uint8Array(y);f[p];){var x=e[f.charCodeAt(p)];if(x===255)return;for(var C=0,D=y-1;(x!==0||C<g)&&D!==-1;D--,C++)x+=a*v[D]>>>0,v[D]=x%256>>>0,x=x/256>>>0;if(x!==0)throw new Error("Non-zero carry");g=C,p++}if(f[p]!==" "){for(var E=y-g;E!==y&&v[E]===0;)E++;for(var T=new Uint8Array(m+(y-E)),W=m;E!==y;)T[W++]=v[E++];return T}}}function b(f){var p=d(f);if(p)return p;throw new Error(`Non-${t} character`)}return{encode:u,decodeUnsafe:d,decode:b}}var pa=da,ma=pa,Yn=ma;var je=class{name;prefix;baseEncode;constructor(t,e,n){this.name=t,this.prefix=e,this.baseEncode=n}encode(t){if(t instanceof Uint8Array)return`${this.prefix}${this.baseEncode(t)}`;throw Error("Unknown type, must be binary type")}},Xe=class{name;prefix;baseDecode;prefixCodePoint;constructor(t,e,n){if(this.name=t,this.prefix=e,e.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=e.codePointAt(0),this.baseDecode=n}decode(t){if(typeof t=="string"){if(t.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(t)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(t.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(t){return ts(this,t)}},Qe=class{decoders;constructor(t){this.decoders=t}or(t){return ts(this,t)}decode(t){let e=t[0],n=this.decoders[e];if(n!=null)return n.decode(t);throw RangeError(`Unable to decode multibase string ${JSON.stringify(t)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function ts(r,t){return new Qe({...r.decoders??{[r.prefix]:r},...t.decoders??{[t.prefix]:t}})}var Je=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(t,e,n,s){this.name=t,this.prefix=e,this.baseEncode=n,this.baseDecode=s,this.encoder=new je(t,e,n),this.decoder=new Xe(t,e,s)}encode(t){return this.encoder.encode(t)}decode(t){return this.decoder.decode(t)}};function Et({name:r,prefix:t,encode:e,decode:n}){return new Je(r,t,e,n)}function Y({name:r,prefix:t,alphabet:e}){let{encode:n,decode:s}=Yn(e,r);return Et({prefix:t,name:r,encode:n,decode:o=>Q(s(o))})}function ga(r,t,e,n){let s={};for(let h=0;h<t.length;++h)s[t[h]]=h;let o=r.length;for(;r[o-1]==="=";)--o;let i=new Uint8Array(o*e/8|0),a=0,c=0,l=0;for(let h=0;h<o;++h){let u=s[r[h]];if(u===void 0)throw new SyntaxError(`Non-${n} character`);c=c<<e|u,a+=e,a>=8&&(a-=8,i[l++]=255&c>>a)}if(a>=e||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return i}function ba(r,t,e){let n=t[t.length-1]==="=",s=(1<<e)-1,o="",i=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],i+=8;i>e;)i-=e,o+=t[s&a>>i];if(i!==0&&(o+=t[s&a<<e-i]),n)for(;o.length*e&7;)o+="=";return o}function B({name:r,prefix:t,bitsPerChar:e,alphabet:n}){return Et({prefix:t,name:r,encode(s){return ba(s,n,e)},decode(s){return ga(s,n,e,r)}})}var tt=B({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),ya=B({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),wa=B({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),xa=B({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),va=B({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),_a=B({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),ka=B({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Sa=B({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Ea=B({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Ze={};A(Ze,{base58btc:()=>H,base58flickr:()=>Aa});var H=Y({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Aa=Y({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var tr={};A(tr,{base64:()=>Ye,base64pad:()=>Ca,base64url:()=>Ta,base64urlpad:()=>La});var Ye=B({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Ca=B({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Ta=B({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),La=B({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});q.default.formatters.b=r=>r==null?"undefined":H.baseEncode(r);q.default.formatters.t=r=>r==null?"undefined":tt.baseEncode(r);q.default.formatters.m=r=>r==null?"undefined":Ye.baseEncode(r);q.default.formatters.p=r=>r==null?"undefined":r.toString();q.default.formatters.c=r=>r==null?"undefined":r.toString();q.default.formatters.k=r=>r==null?"undefined":r.toString();q.default.formatters.a=r=>r==null?"undefined":r.toString();function Ba(r){let t=()=>{};return t.enabled=!1,t.color="",t.diff=0,t.log=()=>{},t.namespace=r,t.destroy=()=>!0,t.extend=()=>t,t}function es(r){let t=Ba(`${r}:trace`);return q.default.enabled(`${r}:trace`)&&q.default.names.map(e=>e.toString()).find(e=>e.includes(":trace"))!=null&&(t=(0,q.default)(`${r}:trace`)),Object.assign((0,q.default)(r),{error:(0,q.default)(`${r}:error`),trace:t})}function rs(r,t){if(r===t)return!0;if(r.byteLength!==t.byteLength)return!1;for(let e=0;e<r.byteLength;e++)if(r[e]!==t[e])return!1;return!0}var at=class{_refCounter;cid;priority;wantType;constructor(t,e,n){this._refCounter=1,this.cid=t,this.priority=e??1,this.wantType=n}inc(){this._refCounter+=1}dec(){this._refCounter=Math.max(0,this._refCounter-1)}hasRefs(){return this._refCounter>0}get[Symbol.toStringTag](){return`WantlistEntry <key: ${this.cid.toString(w)}, priority: ${this.priority}, refs: ${this._refCounter}>`}equals(t){return this._refCounter===t._refCounter&&this.cid.equals(t.cid)&&this.priority===t.priority&&this.wantType===t.wantType}};var et=class{entry;cancel;sendDontHave;constructor(t,e,n,s,o){this.entry=new at(t,e,n),this.cancel=!!s,this.sendDontHave=!!o}get cid(){return this.entry.cid}set cid(t){this.entry.cid=t}get priority(){return this.entry.priority}set priority(t){this.entry.priority=t}get wantType(){return this.entry.wantType}set wantType(t){this.entry.wantType=t}get[Symbol.toStringTag](){return`BitswapMessageEntry ${this.cid.toString(w)} <cancel: ${this.cancel}, priority: ${this.priority}>`}equals(t){return this.cancel===t.cancel&&this.sendDontHave===t.sendDontHave&&this.wantType===t.wantType&&this.entry.equals(t.entry)}};var V=(r,t)=>{let e=["bitswap"];return t!=null&&e.push(t),r!=null&&e.push(`${r.toString().slice(0,8)}`),es(e.join(":"))};var re=(r,t)=>{if(r.size!==t.size)return!1;for(let[e,n]of r){let s=t.get(e);if(s===void 0||n instanceof Uint8Array&&s instanceof Uint8Array&&!rs(n,s)||n instanceof et&&s instanceof et&&!n.equals(s))return!1}return!0};var zt=G(fs(),1);function Wa(r){let t=new Uint8Array(r.reduce((n,s)=>n+zt.default.encodingLength(s),0)),e=0;for(let n of r)t=zt.encode(n,t,e),e+=zt.default.encodingLength(n);return t}var ds=Wa;var nr=new Float32Array([-0]),rt=new Uint8Array(nr.buffer);function ps(r,t,e){nr[0]=r,t[e]=rt[0],t[e+1]=rt[1],t[e+2]=rt[2],t[e+3]=rt[3]}function ms(r,t){return rt[0]=r[t],rt[1]=r[t+1],rt[2]=r[t+2],rt[3]=r[t+3],nr[0]}var sr=new Float64Array([-0]),N=new Uint8Array(sr.buffer);function gs(r,t,e){sr[0]=r,t[e]=N[0],t[e+1]=N[1],t[e+2]=N[2],t[e+3]=N[3],t[e+4]=N[4],t[e+5]=N[5],t[e+6]=N[6],t[e+7]=N[7]}function bs(r,t){return N[0]=r[t],N[1]=r[t+1],N[2]=r[t+2],N[3]=r[t+3],N[4]=r[t+4],N[5]=r[t+5],N[6]=r[t+6],N[7]=r[t+7],sr[0]}var $a=BigInt(Number.MAX_SAFE_INTEGER),Ga=BigInt(Number.MIN_SAFE_INTEGER),R=class r{lo;hi;constructor(t,e){this.lo=t|0,this.hi=e|0}toNumber(t=!1){if(!t&&this.hi>>>31>0){let e=~this.lo+1>>>0,n=~this.hi>>>0;return e===0&&(n=n+1>>>0),-(e+n*4294967296)}return this.lo+this.hi*4294967296}toBigInt(t=!1){if(t)return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n);if(this.hi>>>31){let e=~this.lo+1>>>0,n=~this.hi>>>0;return e===0&&(n=n+1>>>0),-(BigInt(e)+(BigInt(n)<<32n))}return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n)}toString(t=!1){return this.toBigInt(t).toString()}zzEncode(){let t=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^t)>>>0,this.lo=(this.lo<<1^t)>>>0,this}zzDecode(){let t=-(this.lo&1);return this.lo=((this.lo>>>1|this.hi<<31)^t)>>>0,this.hi=(this.hi>>>1^t)>>>0,this}length(){let t=this.lo,e=(this.lo>>>28|this.hi<<4)>>>0,n=this.hi>>>24;return n===0?e===0?t<16384?t<128?1:2:t<2097152?3:4:e<16384?e<128?5:6:e<2097152?7:8:n<128?9:10}static fromBigInt(t){if(t===0n)return ct;if(t<$a&&t>Ga)return this.fromNumber(Number(t));let e=t<0n;e&&(t=-t);let n=t>>32n,s=t-(n<<32n);return e&&(n=~n|0n,s=~s|0n,++s>ys&&(s=0n,++n>ys&&(n=0n))),new r(Number(s),Number(n))}static fromNumber(t){if(t===0)return ct;let e=t<0;e&&(t=-t);let n=t>>>0,s=(t-n)/4294967296>>>0;return e&&(s=~s>>>0,n=~n>>>0,++n>4294967295&&(n=0,++s>4294967295&&(s=0))),new r(n,s)}static from(t){return typeof t=="number"?r.fromNumber(t):typeof t=="bigint"?r.fromBigInt(t):typeof t=="string"?r.fromBigInt(BigInt(t)):t.low!=null||t.high!=null?new r(t.low>>>0,t.high>>>0):ct}},ct=new R(0,0);ct.toBigInt=function(){return 0n};ct.zzEncode=ct.zzDecode=function(){return this};ct.length=function(){return 1};var ys=4294967296n;function ws(r){let t=0,e=0;for(let n=0;n<r.length;++n)e=r.charCodeAt(n),e<128?t+=1:e<2048?t+=2:(e&64512)===55296&&(r.charCodeAt(n+1)&64512)===56320?(++n,t+=4):t+=3;return t}function xs(r,t,e){if(e-t<1)return"";let s,o=[],i=0,a;for(;t<e;)a=r[t++],a<128?o[i++]=a:a>191&&a<224?o[i++]=(a&31)<<6|r[t++]&63:a>239&&a<365?(a=((a&7)<<18|(r[t++]&63)<<12|(r[t++]&63)<<6|r[t++]&63)-65536,o[i++]=55296+(a>>10),o[i++]=56320+(a&1023)):o[i++]=(a&15)<<12|(r[t++]&63)<<6|r[t++]&63,i>8191&&((s??(s=[])).push(String.fromCharCode.apply(String,o)),i=0);return s!=null?(i>0&&s.push(String.fromCharCode.apply(String,o.slice(0,i))),s.join("")):String.fromCharCode.apply(String,o.slice(0,i))}function or(r,t,e){let n=e,s,o;for(let i=0;i<r.length;++i)s=r.charCodeAt(i),s<128?t[e++]=s:s<2048?(t[e++]=s>>6|192,t[e++]=s&63|128):(s&64512)===55296&&((o=r.charCodeAt(i+1))&64512)===56320?(s=65536+((s&1023)<<10)+(o&1023),++i,t[e++]=s>>18|240,t[e++]=s>>12&63|128,t[e++]=s>>6&63|128,t[e++]=s&63|128):(t[e++]=s>>12|224,t[e++]=s>>6&63|128,t[e++]=s&63|128);return e-n}function $(r,t){return RangeError(`index out of range: ${r.pos} + ${t??1} > ${r.len}`)}function ne(r,t){return(r[t-4]|r[t-3]<<8|r[t-2]<<16|r[t-1]<<24)>>>0}var ir=class{buf;pos;len;_slice=Uint8Array.prototype.subarray;constructor(t){this.buf=t,this.pos=0,this.len=t.length}uint32(){let t=4294967295;if(t=(this.buf[this.pos]&127)>>>0,this.buf[this.pos++]<128||(t=(t|(this.buf[this.pos]&127)<<7)>>>0,this.buf[this.pos++]<128)||(t=(t|(this.buf[this.pos]&127)<<14)>>>0,this.buf[this.pos++]<128)||(t=(t|(this.buf[this.pos]&127)<<21)>>>0,this.buf[this.pos++]<128)||(t=(t|(this.buf[this.pos]&15)<<28)>>>0,this.buf[this.pos++]<128))return t;if((this.pos+=5)>this.len)throw this.pos=this.len,$(this,10);return t}int32(){return this.uint32()|0}sint32(){let t=this.uint32();return t>>>1^-(t&1)|0}bool(){return this.uint32()!==0}fixed32(){if(this.pos+4>this.len)throw $(this,4);return ne(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw $(this,4);return ne(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw $(this,4);let t=ms(this.buf,this.pos);return this.pos+=4,t}double(){if(this.pos+8>this.len)throw $(this,4);let t=bs(this.buf,this.pos);return this.pos+=8,t}bytes(){let t=this.uint32(),e=this.pos,n=this.pos+t;if(n>this.len)throw $(this,t);return this.pos+=t,e===n?new Uint8Array(0):this.buf.subarray(e,n)}string(){let t=this.bytes();return xs(t,0,t.length)}skip(t){if(typeof t=="number"){if(this.pos+t>this.len)throw $(this,t);this.pos+=t}else do if(this.pos>=this.len)throw $(this);while(this.buf[this.pos++]&128);return this}skipType(t){switch(t){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;(t=this.uint32()&7)!==4;)this.skipType(t);break;case 5:this.skip(4);break;default:throw Error(`invalid wire type ${t} at offset ${this.pos}`)}return this}readLongVarint(){let t=new R(0,0),e=0;if(this.len-this.pos>4){for(;e<4;++e)if(t.lo=(t.lo|(this.buf[this.pos]&127)<<e*7)>>>0,this.buf[this.pos++]<128)return t;if(t.lo=(t.lo|(this.buf[this.pos]&127)<<28)>>>0,t.hi=(t.hi|(this.buf[this.pos]&127)>>4)>>>0,this.buf[this.pos++]<128)return t;e=0}else{for(;e<3;++e){if(this.pos>=this.len)throw $(this);if(t.lo=(t.lo|(this.buf[this.pos]&127)<<e*7)>>>0,this.buf[this.pos++]<128)return t}return t.lo=(t.lo|(this.buf[this.pos++]&127)<<e*7)>>>0,t}if(this.len-this.pos>4){for(;e<5;++e)if(t.hi=(t.hi|(this.buf[this.pos]&127)<<e*7+3)>>>0,this.buf[this.pos++]<128)return t}else for(;e<5;++e){if(this.pos>=this.len)throw $(this);if(t.hi=(t.hi|(this.buf[this.pos]&127)<<e*7+3)>>>0,this.buf[this.pos++]<128)return t}throw Error("invalid varint encoding")}readFixed64(){if(this.pos+8>this.len)throw $(this,8);let t=ne(this.buf,this.pos+=4),e=ne(this.buf,this.pos+=4);return new R(t,e)}int64(){return this.readLongVarint().toBigInt()}int64Number(){return this.readLongVarint().toNumber()}int64String(){return this.readLongVarint().toString()}uint64(){return this.readLongVarint().toBigInt(!0)}uint64Number(){return this.readLongVarint().toNumber(!0)}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 ar(r){return new ir(r instanceof Uint8Array?r:r.subarray())}function lt(r,t){let e=ar(r);return t.decode(e)}function nt(r){return globalThis.Buffer!=null?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):r}function J(r=0){return globalThis.Buffer?.alloc!=null?nt(globalThis.Buffer.alloc(r)):new Uint8Array(r)}function M(r=0){return globalThis.Buffer?.allocUnsafe!=null?nt(globalThis.Buffer.allocUnsafe(r)):new Uint8Array(r)}var cr={};A(cr,{base10:()=>ja});var ja=Y({prefix:"9",name:"base10",alphabet:"0123456789"});var lr={};A(lr,{base16:()=>Xa,base16upper:()=>Qa});var Xa=B({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),Qa=B({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var hr={};A(hr,{base2:()=>Ja});var Ja=B({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var ur={};A(ur,{base256emoji:()=>ec});var _s=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}"),Ka=_s.reduce((r,t,e)=>(r[e]=t,r),[]),Za=_s.reduce((r,t,e)=>(r[t.codePointAt(0)]=e,r),[]);function Ya(r){return r.reduce((t,e)=>(t+=Ka[e],t),"")}function tc(r){let t=[];for(let e of r){let n=Za[e.codePointAt(0)];if(n===void 0)throw new Error(`Non-base256emoji character: ${e}`);t.push(n)}return new Uint8Array(t)}var ec=Et({prefix:"\u{1F680}",name:"base256emoji",encode:Ya,decode:tc});var fr={};A(fr,{base36:()=>rc,base36upper:()=>nc});var rc=Y({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),nc=Y({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var dr={};A(dr,{base8:()=>sc});var sc=B({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var pr={};A(pr,{identity:()=>oc});var oc=Et({prefix:"\0",name:"identity",encode:r=>Kn(r),decode:r=>Jn(r)});var kf=new TextEncoder,Sf=new TextDecoder;var gr={};A(gr,{identity:()=>Tc});var cc=Es,ks=128,lc=127,hc=~lc,uc=Math.pow(2,31);function Es(r,t,e){t=t||[],e=e||0;for(var n=e;r>=uc;)t[e++]=r&255|ks,r/=128;for(;r&hc;)t[e++]=r&255|ks,r>>>=7;return t[e]=r|0,Es.bytes=e-n+1,t}var fc=mr,dc=128,Ss=127;function mr(r,n){var e=0,n=n||0,s=0,o=n,i,a=r.length;do{if(o>=a)throw mr.bytes=0,new RangeError("Could not decode varint");i=r[o++],e+=s<28?(i&Ss)<<s:(i&Ss)*Math.pow(2,s),s+=7}while(i>=dc);return mr.bytes=o-n,e}var pc=Math.pow(2,7),mc=Math.pow(2,14),gc=Math.pow(2,21),bc=Math.pow(2,28),yc=Math.pow(2,35),wc=Math.pow(2,42),xc=Math.pow(2,49),vc=Math.pow(2,56),_c=Math.pow(2,63),kc=function(r){return r<pc?1:r<mc?2:r<gc?3:r<bc?4:r<yc?5:r<wc?6:r<xc?7:r<vc?8:r<_c?9:10},Sc={encode:cc,decode:fc,encodingLength:kc},Ec=Sc,qt=Ec;function Ht(r,t=0){return[qt.decode(r,t),qt.decode.bytes]}function At(r,t,e=0){return qt.encode(r,t,e),t}function Ct(r){return qt.encodingLength(r)}function ht(r,t){let e=t.byteLength,n=Ct(r),s=n+Ct(e),o=new Uint8Array(s+e);return At(r,o,0),At(e,o,n),o.set(t,s),new Tt(r,e,t,o)}function As(r){let t=Q(r),[e,n]=Ht(t),[s,o]=Ht(t.subarray(n)),i=t.subarray(n+o);if(i.byteLength!==s)throw new Error("Incorrect length");return new Tt(e,s,i,t)}function Cs(r,t){if(r===t)return!0;{let e=t;return r.code===e.code&&r.size===e.size&&e.bytes instanceof Uint8Array&&Qn(r.bytes,e.bytes)}}var Tt=class{code;size;digest;bytes;constructor(t,e,n,s){this.code=t,this.size=e,this.digest=n,this.bytes=s}};var Ts=0,Ac="identity",Ls=Q;function Cc(r){return ht(Ts,Ls(r))}var Tc={code:Ts,name:Ac,encode:Ls,digest:Cc};var wr={};A(wr,{sha256:()=>Lc,sha512:()=>Bc});function yr({name:r,code:t,encode:e}){return new br(r,t,e)}var br=class{name;code;encode;constructor(t,e,n){this.name=t,this.code=e,this.encode=n}digest(t){if(t instanceof Uint8Array){let e=this.encode(t);return e instanceof Uint8Array?ht(this.code,e):e.then(n=>ht(this.code,n))}else throw Error("Unknown type, must be binary type")}};function Ds(r){return async t=>new Uint8Array(await crypto.subtle.digest(r,t))}var Lc=yr({name:"sha2-256",code:18,encode:Ds("SHA-256")}),Bc=yr({name:"sha2-512",code:19,encode:Ds("SHA-512")});function Is(r,t){let{bytes:e,version:n}=r;switch(n){case 0:return Ic(e,xr(r),t??H.encoder);default:return Fc(e,xr(r),t??tt.encoder)}}var Fs=new WeakMap;function xr(r){let t=Fs.get(r);if(t==null){let e=new Map;return Fs.set(r,e),e}return t}var oe=class r{code;version;multihash;bytes;"/";constructor(t,e,n,s){this.code=e,this.version=t,this.multihash=n,this.bytes=s,this["/"]=s}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:t,multihash:e}=this;if(t!==Wt)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(e.code!==Nc)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return r.createV0(e)}default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}toV1(){switch(this.version){case 0:{let{code:t,digest:e}=this.multihash,n=ht(t,e);return r.createV1(this.code,n)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(t){return r.equals(this,t)}static equals(t,e){let n=e;return n!=null&&t.code===n.code&&t.version===n.version&&Cs(t.multihash,n.multihash)}toString(t){return Is(this,t)}toJSON(){return{"/":Is(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(t){if(t==null)return null;let e=t;if(e instanceof r)return e;if(e["/"]!=null&&e["/"]===e.bytes||e.asCID===e){let{version:n,code:s,multihash:o,bytes:i}=e;return new r(n,s,o,i??Ns(n,s,o.bytes))}else if(e[Mc]===!0){let{version:n,multihash:s,code:o}=e,i=As(s);return r.create(n,o,i)}else return null}static create(t,e,n){if(typeof e!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(t){case 0:{if(e!==Wt)throw new Error(`Version 0 CID must use dag-pb (code: ${Wt}) block encoding`);return new r(t,e,n,n.bytes)}case 1:{let s=Ns(t,e,n.bytes);return new r(t,e,n,s)}default:throw new Error("Invalid version")}}static createV0(t){return r.create(0,Wt,t)}static createV1(t,e){return r.create(1,t,e)}static decode(t){let[e,n]=r.decodeFirst(t);if(n.length!==0)throw new Error("Incorrect length");return e}static decodeFirst(t){let e=r.inspectBytes(t),n=e.size-e.multihashSize,s=Q(t.subarray(n,n+e.multihashSize));if(s.byteLength!==e.multihashSize)throw new Error("Incorrect length");let o=s.subarray(e.multihashSize-e.digestSize),i=new Tt(e.multihashCode,e.digestSize,o,s);return[e.version===0?r.createV0(i):r.createV1(e.codec,i),t.subarray(e.size)]}static inspectBytes(t){let e=0,n=()=>{let[u,d]=Ht(t.subarray(e));return e+=d,u},s=n(),o=Wt;if(s===18?(s=0,e=0):o=n(),s!==0&&s!==1)throw new RangeError(`Invalid CID version ${s}`);let i=e,a=n(),c=n(),l=e+c,h=l-i;return{version:s,codec:o,multihashCode:a,digestSize:c,multihashSize:h,size:l}}static parse(t,e){let[n,s]=Dc(t,e),o=r.decode(s);if(o.version===0&&t[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return xr(o).set(n,t),o}};function Dc(r,t){switch(r[0]){case"Q":{let e=t??H;return[H.prefix,e.decode(`${H.prefix}${r}`)]}case H.prefix:{let e=t??H;return[H.prefix,e.decode(r)]}case tt.prefix:{let e=t??tt;return[tt.prefix,e.decode(r)]}default:{if(t==null)throw Error("To parse non base32 or base58btc encoded CID multibase decoder must be provided");return[r[0],t.decode(r)]}}}function Ic(r,t,e){let{prefix:n}=e;if(n!==H.prefix)throw Error(`Cannot string encode V0 in ${e.name} encoding`);let s=t.get(n);if(s==null){let o=e.encode(r).slice(1);return t.set(n,o),o}else return s}function Fc(r,t,e){let{prefix:n}=e,s=t.get(n);if(s==null){let o=e.encode(r);return t.set(n,o),o}else return s}var Wt=112,Nc=18;function Ns(r,t,e){let n=Ct(r),s=n+Ct(t),o=new Uint8Array(s+e.byteLength);return At(r,o,0),At(t,o,n),o.set(e,s),o}var Mc=Symbol.for("@ipld/js-cid/CID");var vr={...pr,...hr,...dr,...cr,...lr,...Ke,...fr,...Ze,...tr,...ur},$f={...wr,...gr};function Ps(r,t,e,n){return{name:r,prefix:t,encoder:{name:r,prefix:t,encode:e},decoder:{decode:n}}}var Ms=Ps("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),_r=Ps("ascii","a",r=>{let t="a";for(let e=0;e<r.length;e++)t+=String.fromCharCode(r[e]);return t},r=>{r=r.substring(1);let t=M(r.length);for(let e=0;e<r.length;e++)t[e]=r.charCodeAt(e);return t}),Pc={utf8:Ms,"utf-8":Ms,hex:vr.base16,latin1:_r,ascii:_r,binary:_r,...vr},Us=Pc;function Rs(r,t="utf8"){let e=Us[t];if(e==null)throw new Error(`Unsupported encoding "${t}"`);return(t==="utf8"||t==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?nt(globalThis.Buffer.from(r,"utf-8")):e.decoder.decode(`${e.prefix}${r}`)}function kr(r){let t=r??8192,e=t>>>1,n,s=t;return function(i){if(i<1||i>e)return M(i);s+i>t&&(n=M(t),s=0);let a=n.subarray(s,s+=i);return s&7&&(s=(s|7)+1),a}}var ut=class{fn;len;next;val;constructor(t,e,n){this.fn=t,this.len=e,this.next=void 0,this.val=n}};function Sr(){}var Ar=class{head;tail;len;next;constructor(t){this.head=t.head,this.tail=t.tail,this.len=t.len,this.next=t.states}},Uc=kr();function Rc(r){return globalThis.Buffer!=null?M(r):Uc(r)}var jt=class{len;head;tail;states;constructor(){this.len=0,this.head=new ut(Sr,0,0),this.tail=this.head,this.states=null}_push(t,e,n){return this.tail=this.tail.next=new ut(t,e,n),this.len+=e,this}uint32(t){return this.len+=(this.tail=this.tail.next=new Cr((t=t>>>0)<128?1:t<16384?2:t<2097152?3:t<268435456?4:5,t)).len,this}int32(t){return t<0?this._push($t,10,R.fromNumber(t)):this.uint32(t)}sint32(t){return this.uint32((t<<1^t>>31)>>>0)}uint64(t){let e=R.fromBigInt(t);return this._push($t,e.length(),e)}uint64Number(t){let e=R.fromNumber(t);return this._push($t,e.length(),e)}uint64String(t){return this.uint64(BigInt(t))}int64(t){return this.uint64(t)}int64Number(t){return this.uint64Number(t)}int64String(t){return this.uint64String(t)}sint64(t){let e=R.fromBigInt(t).zzEncode();return this._push($t,e.length(),e)}sint64Number(t){let e=R.fromNumber(t).zzEncode();return this._push($t,e.length(),e)}sint64String(t){return this.sint64(BigInt(t))}bool(t){return this._push(Er,1,t?1:0)}fixed32(t){return this._push(Gt,4,t>>>0)}sfixed32(t){return this.fixed32(t)}fixed64(t){let e=R.fromBigInt(t);return this._push(Gt,4,e.lo)._push(Gt,4,e.hi)}fixed64Number(t){let e=R.fromNumber(t);return this._push(Gt,4,e.lo)._push(Gt,4,e.hi)}fixed64String(t){return this.fixed64(BigInt(t))}sfixed64(t){return this.fixed64(t)}sfixed64Number(t){return this.fixed64Number(t)}sfixed64String(t){return this.fixed64String(t)}float(t){return this._push(ps,4,t)}double(t){return this._push(gs,8,t)}bytes(t){let e=t.length>>>0;return e===0?this._push(Er,1,0):this.uint32(e)._push(zc,e,t)}string(t){let e=ws(t);return e!==0?this.uint32(e)._push(or,e,t):this._push(Er,1,0)}fork(){return this.states=new Ar(this),this.head=this.tail=new ut(Sr,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 ut(Sr,0,0),this.len=0),this}ldelim(){let t=this.head,e=this.tail,n=this.len;return this.reset().uint32(n),n!==0&&(this.tail.next=t.next,this.tail=e,this.len+=n),this}finish(){let t=this.head.next,e=Rc(this.len),n=0;for(;t!=null;)t.fn(t.val,e,n),n+=t.len,t=t.next;return e}};function Er(r,t,e){t[e]=r&255}function Oc(r,t,e){for(;r>127;)t[e++]=r&127|128,r>>>=7;t[e]=r}var Cr=class extends ut{next;constructor(t,e){super(Oc,t,e),this.next=void 0}};function $t(r,t,e){for(;r.hi!==0;)t[e++]=r.lo&127|128,r.lo=(r.lo>>>7|r.hi<<25)>>>0,r.hi>>>=7;for(;r.lo>127;)t[e++]=r.lo&127|128,r.lo=r.lo>>>7;t[e++]=r.lo}function Gt(r,t,e){t[e]=r&255,t[e+1]=r>>>8&255,t[e+2]=r>>>16&255,t[e+3]=r>>>24}function zc(r,t,e){t.set(r,e)}globalThis.Buffer!=null&&(jt.prototype.bytes=function(r){let t=r.length>>>0;return this.uint32(t),t>0&&this._push(qc,t,r),this},jt.prototype.string=function(r){let t=globalThis.Buffer.byteLength(r);return this.uint32(t),t>0&&this._push(Hc,t,r),this});function qc(r,t,e){t.set(r,e)}function Hc(r,t,e){r.length<40?or(r,t,e):t.utf8Write!=null?t.utf8Write(r,e):t.set(Rs(r),e)}function Tr(){return new jt}function ft(r,t){let e=Tr();return t.encode(r,e,{lengthDelimited:!1}),e.finish()}var Lt;(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"})(Lt||(Lt={}));function ie(r,t,e,n){return{name:r,type:t,encode:e,decode:n}}function ae(r){function t(s){if(r[s.toString()]==null)throw new Error("Invalid enum value");return r[s]}let e=function(o,i){let a=t(o);i.int32(a)},n=function(o){let i=o.int32();return t(i)};return ie("enum",Lt.VARINT,e,n)}function dt(r,t){return ie("message",Lt.LENGTH_DELIMITED,r,t)}var O;(function(r){let t;(function(a){let c;(function(d){d.Block="Block",d.Have="Have"})(c=a.WantType||(a.WantType={}));let l;(function(d){d[d.Block=0]="Block",d[d.Have=1]="Have"})(l||(l={})),function(d){d.codec=()=>ae(l)}(c=a.WantType||(a.WantType={}));let h;(function(d){let b;d.codec=()=>(b==null&&(b=dt((f,p,m={})=>{m.lengthDelimited!==!1&&p.fork(),f.block!=null&&f.block.byteLength>0&&(p.uint32(10),p.bytes(f.block)),f.priority!=null&&f.priority!==0&&(p.uint32(16),p.int32(f.priority)),f.cancel!=null&&f.cancel!==!1&&(p.uint32(24),p.bool(f.cancel)),f.wantType!=null&&l[f.wantType]!==0&&(p.uint32(32),r.Wantlist.WantType.codec().encode(f.wantType,p)),f.sendDontHave!=null&&f.sendDontHave!==!1&&(p.uint32(40),p.bool(f.sendDontHave)),m.lengthDelimited!==!1&&p.ldelim()},(f,p)=>{let m={block:new Uint8Array(0),priority:0,cancel:!1,wantType:c.Block,sendDontHave:!1},g=p==null?f.len:f.pos+p;for(;f.pos<g;){let y=f.uint32();switch(y>>>3){case 1:m.block=f.bytes();break;case 2:m.priority=f.int32();break;case 3:m.cancel=f.bool();break;case 4:m.wantType=r.Wantlist.WantType.codec().decode(f);break;case 5:m.sendDontHave=f.bool();break;default:f.skipType(y&7);break}}return m})),b),d.encode=f=>ft(f,d.codec()),d.decode=f=>lt(f,d.codec())})(h=a.Entry||(a.Entry={}));let u;a.codec=()=>(u==null&&(u=dt((d,b,f={})=>{if(f.lengthDelimited!==!1&&b.fork(),d.entries!=null)for(let p of d.entries)b.uint32(10),r.Wantlist.Entry.codec().encode(p,b);d.full!=null&&d.full!==!1&&(b.uint32(16),b.bool(d.full)),f.lengthDelimited!==!1&&b.ldelim()},(d,b)=>{let f={entries:[],full:!1},p=b==null?d.len:d.pos+b;for(;d.pos<p;){let m=d.uint32();switch(m>>>3){case 1:f.entries.push(r.Wantlist.Entry.codec().decode(d,d.uint32()));break;case 2:f.full=d.bool();break;default:d.skipType(m&7);break}}return f})),u),a.encode=d=>ft(d,a.codec()),a.decode=d=>lt(d,a.codec())})(t=r.Wantlist||(r.Wantlist={}));let e;(function(a){let c;a.codec=()=>(c==null&&(c=dt((l,h,u={})=>{u.lengthDelimited!==!1&&h.fork(),l.prefix!=null&&l.prefix.byteLength>0&&(h.uint32(10),h.bytes(l.prefix)),l.data!=null&&l.data.byteLength>0&&(h.uint32(18),h.bytes(l.data)),u.lengthDelimited!==!1&&h.ldelim()},(l,h)=>{let u={prefix:new Uint8Array(0),data:new Uint8Array(0)},d=h==null?l.len:l.pos+h;for(;l.pos<d;){let b=l.uint32();switch(b>>>3){case 1:u.prefix=l.bytes();break;case 2:u.data=l.bytes();break;default:l.skipType(b&7);break}}return u})),c),a.encode=l=>ft(l,a.codec()),a.decode=l=>lt(l,a.codec())})(e=r.Block||(r.Block={}));let n;(function(a){a.Have="Have",a.DontHave="DontHave"})(n=r.BlockPresenceType||(r.BlockPresenceType={}));let s;(function(a){a[a.Have=0]="Have",a[a.DontHave=1]="DontHave"})(s||(s={})),function(a){a.codec=()=>ae(s)}(n=r.BlockPresenceType||(r.BlockPresenceType={}));let o;(function(a){let c;a.codec=()=>(c==null&&(c=dt((l,h,u={})=>{u.lengthDelimited!==!1&&h.fork(),l.cid!=null&&l.cid.byteLength>0&&(h.uint32(10),h.bytes(l.cid)),l.type!=null&&s[l.type]!==0&&(h.uint32(16),r.BlockPresenceType.codec().encode(l.type,h)),u.lengthDelimited!==!1&&h.ldelim()},(l,h)=>{let u={cid:new Uint8Array(0),type:n.Have},d=h==null?l.len:l.pos+h;for(;l.pos<d;){let b=l.uint32();switch(b>>>3){case 1:u.cid=l.bytes();break;case 2:u.type=r.BlockPresenceType.codec().decode(l);break;default:l.skipType(b&7);break}}return u})),c),a.encode=l=>ft(l,a.codec()),a.decode=l=>lt(l,a.codec())})(o=r.BlockPresence||(r.BlockPresence={}));let i;r.codec=()=>(i==null&&(i=dt((a,c,l={})=>{if(l.lengthDelimited!==!1&&c.fork(),a.wantlist!=null&&(c.uint32(10),r.Wantlist.codec().encode(a.wantlist,c)),a.blocks!=null)for(let h of a.blocks)c.uint32(18),c.bytes(h);if(a.payload!=null)for(let h of a.payload)c.uint32(26),r.Block.codec().encode(h,c);if(a.blockPresences!=null)for(let h of a.blockPresences)c.uint32(34),r.BlockPresence.codec().encode(h,c);a.pendingBytes!=null&&a.pendingBytes!==0&&(c.uint32(40),c.int32(a.pendingBytes)),l.lengthDelimited!==!1&&c.ldelim()},(a,c)=>{let l={blocks:[],payload:[],blockPresences:[],pendingBytes:0},h=c==null?a.len:a.pos+c;for(;a.pos<h;){let u=a.uint32();switch(u>>>3){case 1:l.wantlist=r.Wantlist.codec().decode(a,a.uint32());break;case 2:l.blocks.push(a.bytes());break;case 3:l.payload.push(r.Block.codec().decode(a,a.uint32()));break;case 4:l.blockPresences.push(r.BlockPresence.codec().decode(a,a.uint32()));break;case 5:l.pendingBytes=a.int32();break;default:a.skipType(u&7);break}}return l})),i),r.encode=a=>ft(a,r.codec()),r.decode=a=>lt(a,r.codec())})(O||(O={}));var P=class r{static Entry=et;static WantType={Block:O.Wantlist.WantType.Block,Have:O.Wantlist.WantType.Have};static BlockPresenceType={Have:O.BlockPresenceType.Have,DontHave:O.BlockPresenceType.DontHave};static deserialize=async(t,e)=>{let n=O.decode(t),s=n.wantlist?.full===!0,o=new r(s);return n.wantlist?.entries.forEach(i=>{if(i.block==null)return;let a=F.decode(i.block);o.addEntry(a,i.priority??0,i.wantType,!!i.cancel,!!i.sendDontHave)}),n.blockPresences.forEach(i=>{if(i.cid==null)return;let a=F.decode(i.cid);i.type===r.BlockPresenceType.Have?o.addHave(a):o.addDontHave(a)}),n.blocks.length>0?(await Promise.all(n.blocks.map(async i=>{let a=await Ot.digest(i),c=F.createV0(a);o.addBlock(c,i)})),o):(n.payload.length>0&&(await Promise.all(n.payload.map(async i=>{if(i.prefix==null||i.data==null)return;let a=(0,Os.default)(i.prefix),c=a[0],l=a[1],h=a[2],u=h===Ot.code?Ot:await e?.getHasher(h);if(u==null)throw new X("Unknown hash algorithm","ERR_UNKNOWN_HASH_ALG");let d=await u.digest(i.data),b=F.create(c,l,d);o.addBlock(b,i.data)})),o.setPendingBytes(n.pendingBytes)),o)};static blockPresenceSize=t=>t.bytes.length+1;full;wantlist;blocks;blockPresences;pendingBytes;constructor(t){this.full=t,this.wantlist=new Map,this.blocks=new Map,this.blockPresences=new Map,this.pendingBytes=0}get empty(){return this.blocks.size===0&&this.wantlist.size===0&&this.blockPresences.size===0}addEntry(t,e,n,s,o){n==null&&(n=r.WantType.Block);let i=t.toString(w),a=this.wantlist.get(i);a!=null?(a.wantType===n&&(a.priority=e),s===!0&&(a.cancel=!!s),o===!0&&(a.sendDontHave=!!o),n===r.WantType.Block&&a.wantType===r.WantType.Have&&(a.wantType=n)):this.wantlist.set(i,new et(t,e,n,s,o))}addBlock(t,e){let n=t.toString(w);this.blocks.set(n,e)}addHave(t){let e=t.toString(w);this.blockPresences.has(e)||this.blockPresences.set(e,r.BlockPresenceType.Have)}addDontHave(t){let e=t.toString(w);this.blockPresences.has(e)||this.blockPresences.set(e,r.BlockPresenceType.DontHave)}cancel(t){let e=t.toString(w);this.wantlist.delete(e),this.addEntry(t,0,r.WantType.Block,!0,!1)}setPendingBytes(t){this.pendingBytes=t}serializeToBitswap100(){return O.encode({wantlist:{entries:Array.from(this.wantlist.values()).map(t=>({block:t.cid.bytes,priority:Number(t.priority),cancel:!!t.cancel,wantType:O.Wantlist.WantType.Block,sendDontHave:!1})),full:!!this.full},blocks:Array.from(this.blocks.values())})}serializeToBitswap110(){let t={wantlist:{entries:Array.from(this.wantlist.values()).map(e=>({block:e.cid.bytes,priority:Number(e.priority),wantType:e.wantType,cancel:!!e.cancel,sendDontHave:!!e.sendDontHave})),full:!!this.full},blockPresences:[],payload:[],pendingBytes:this.pendingBytes,blocks:[]};for(let[e,n]of this.blocks.entries()){let s=F.parse(e),o=s.version,i=s.code,a=s.multihash.code,c=s.multihash.digest.length,l=ds([o,i,a,c]);t.payload.push({prefix:l,data:n})}for(let[e,n]of this.blockPresences)t.blockPresences.push({cid:F.parse(e).bytes,type:n});return this.pendingBytes>0&&(t.pendingBytes=this.pendingBytes),O.encode(t)}equals(t){return!(this.full!==t.full||this.pendingBytes!==t.pendingBytes||!re(this.wantlist,t.wantlist)||!re(this.blocks,t.blocks)||!re(this.blockPresences,t.blockPresences))}get[Symbol.toStringTag](){let t=Array.from(this.wantlist.keys()),e=Array.from(this.blocks.keys());return`BitswapMessage <full: ${this.full}, list: ${t}, blocks: ${e}>`}};var zs={Block:O.Wantlist.WantType.Block,Have:O.Wantlist.WantType.Have},Vc=(r,t)=>Array.prototype.slice.call(t,0).sort((e,n)=>{let s=r(e),o=r(n);return s<o?-1:s>o?1:0}),st=class{static Entry=at;set;_stats;constructor(t,e){this.set=e!=null?Z({name:"ipfs_bitswap_wantlist",metrics:e.metrics}):new Map,this._stats=t}get length(){return this.set.size}add(t,e,n){let s=t.toString(w),o=this.set.get(s);o!=null?(o.inc(),o.priority=e,o.wantType===zs.Have&&n===zs.Block&&(o.wantType=n)):(this.set.set(s,new at(t,e,n)),this._stats!=null&&this._stats.push(void 0,"wantListSize",1))}remove(t){let e=t.toString(w),n=this.set.get(e);n!=null&&(n.dec(),!n.hasRefs()&&(this.set.delete(e),this._stats!=null&&this._stats.push(void 0,"wantListSize",-1)))}removeForce(t){this.set.has(t)&&this.set.delete(t)}forEach(t){this.set.forEach(t)}entries(){return this.set.entries()}sortedEntries(){return new Map(Vc(t=>t[1].key,Array.from(this.set.entries())))}contains(t){let e=t.toString(w);return this.set.has(e)}get(t){let e=t.toString(w);return this.set.get(e)}};var ce=class{partner;wantlist;exchangeCount;accounting;lastExchange;constructor(t){this.partner=t,this.wantlist=new st,this.exchangeCount=0,this.accounting={bytesSent:0,bytesRecv:0}}sentBytes(t){this.exchangeCount++,this.lastExchange=new Date().getTime(),this.accounting.bytesSent+=t}receivedBytes(t){this.exchangeCount++,this.lastExchange=new Date().getTime(),this.accounting.bytesRecv+=t}wants(t,e,n){this.wantlist.add(t,e,n)}cancelWant(t){this.wantlist.remove(t)}wantlistContains(t){return this.wantlist.get(t)}debtRatio(){return this.accounting.bytesSent/(this.accounting.bytesRecv+1)}};var Xt=class extends Map{_cmp;_keys;constructor(t,e){super(),this._cmp=e??this._defaultSort,this._keys=[];for(let[n,s]of t??[])this.set(n,s)}update(t){if(t<0||t>=this._keys.length)return;let e=this._keys[t];this._keys.splice(t,1);let n=this._find(e);this._keys.splice(n,0,e)}set(t,e){if(this.has(t)){let s=this.indexOf(t);this._keys.splice(s,1)}super.set(t,e);let n=this._find(t);return this._keys.splice(n,0,t),this}clear(){super.clear(),this._keys=[]}delete(t){if(!this.has(t))return!1;let e=this.indexOf(t);return this._keys.splice(e,1),super.delete(t)}indexOf(t){if(!this.has(t))return-1;let e=this._find(t);if(this._keys[e]===t)return e;for(let n=1;n<this._keys.length;n++){if(this._keys[e+n]===t)return e+n;if(this._keys[e-n]===t)return e-n}return-1}_find(t){let e=0,n=this._keys.length;for(;e<n;){let s=e+n>>>1,o=this._kCmp(this._keys[s],t);if(o<0)e=s+1;else if(o>0)n=s;else return s}return e}*keys(){for(let t of this._keys)yield t}*values(){for(let t of this._keys)yield this.get(t)}*entries(){for(let t of this._keys)yield[t,this.get(t)]}*[Symbol.iterator](){yield*this.entries()}forEach(t,e=this){if(t!=null)for(let n of this._keys){let s=this.get(n);if(s==null)throw new Error("Value cannot be undefined");t.apply(e,[[n,s]])}}_defaultSort(t,e){return t[0]<e[0]?-1:e[0]<t[0]?1:0}_kCmp(t,e){return this._cmp([t,this.get(t)],[e,this.get(e)])}};var Wc={hasNewInfo(){return!1},merge(){}},le=class{_taskMerger;_byPeer;constructor(t=Wc){this._taskMerger=t,this._byPeer=new Xt([],he.compare)}pushTasks(t,e){let n=this._byPeer.get(t.toString());n==null&&(n=new he(t,this._taskMerger)),n.pushTasks(e),this._byPeer.set(t.toString(),n)}popTasks(t){let e=this._head();if(e===void 0)return{tasks:[],pendingSize:0};let{tasks:n,pendingSize:s}=e.popTasks(t);if(n.length===0)return{tasks:n,pendingSize:s};let o=e.peerId;return e.isIdle()?this._byPeer.delete(o.toString()):this._byPeer.update(0),{peerId:o,tasks:n,pendingSize:s}}_head(){if(this._byPeer.size!==0)for(let[,t]of this._byPeer)return t}remove(t,e){this._byPeer.get(e.toString())?.remove(t)}tasksDone(t,e){let n=this._byPeer.get(t.toString());if(n==null)return;let s=this._byPeer.indexOf(t.toString());for(let o of e)n.taskDone(o);this._byPeer.update(s)}},he=class{peerId;_taskMerger;_activeTotalSize;_pending;_active;constructor(t,e){this.peerId=t,this._taskMerger=e,this._activeTotalSize=0,this._pending=new Lr,this._active=new Set}pushTasks(t){for(let e of t)this._pushTask(e)}_pushTask(t){if(!this._taskHasMoreInfoThanActiveTasks(t))return;let e=this._pending.get(t.topic);if(e!=null){t.priority>e.priority&&this._pending.updatePriority(t.topic,t.priority),this._taskMerger.merge(t,e);return}this._pending.add(t)}_taskHasMoreInfoThanActiveTasks(t){let e=[];for(let n of this._active)n.topic===t.topic&&e.push(n);return e.length===0?!0:this._taskMerger.hasNewInfo(t,e)}popTasks(t){let e=0,n=[],s=this._pending.tasks();for(let o=0;o<s.length&&e<t;o++){let i=s[o];n.push(i),e+=i.size,this._pending.delete(i.topic),this._activeTotalSize+=i.size,this._active.add(i)}return{tasks:n,pendingSize:this._pending.totalSize}}taskDone(t){this._active.has(t)&&(this._activeTotalSize-=t.size,this._active.delete(t))}remove(t){this._pending.delete(t)}isIdle(){return this._pending.length===0&&this._active.size===0}static compare(t,e){return t[1]._pending.length===0?1:e[1]._pending.length===0?-1:t[1]._activeTotalSize===e[1]._activeTotalSize?e[1]._pending.length-t[1]._pending.length:t[1]._activeTotalSize-e[1]._activeTotalSize}},Lr=class{_tasks;constructor(){this._tasks=new Xt([],this._compare)}get length(){return this._tasks.size}get totalSize(){return[...this._tasks.values()].reduce((t,e)=>t+e.task.size,0)}get(t){return this._tasks?.get(t)?.task}add(t){this._tasks.set(t.topic,{created:Date.now(),task:t})}delete(t){this._tasks.delete(t)}tasks(){return[...this._tasks.values()].map(t=>t.task)}updatePriority(t,e){let n=this._tasks.get(t);if(n==null)return;let s=this._tasks.indexOf(t);n.task.priority=e,this._tasks.update(s)}_compare(t,e){return t[1].task.priority===e[1].task.priority?t[1].created-e[1].created:e[1].task.priority-t[1].task.priority}};var qs={hasNewInfo(r,t){let e=!1,n=!1;for(let s of t)s.data.haveBlock&&(e=!0),s.data.isWantBlock&&(n=!0);return!!(!n&&r.data.isWantBlock||!e&&r.data.haveBlock)},merge(r,t){let e=r.data,n=t.data;!n.haveBlock&&e.haveBlock&&(n.haveBlock=e.haveBlock,n.blockSize=e.blockSize),!n.isWantBlock&&e.isWantBlock&&(n.isWantBlock=!0,(!n.haveBlock||e.haveBlock)&&(n.haveBlock=e.haveBlock,t.size=r.size)),n.isWantBlock&&n.haveBlock&&(t.size=n.blockSize)}};var Hs=P.WantType,$c=16*1024,Gc=1024,ue=class{_log;blockstore;network;_stats;_opts;ledgerMap;_running;_requestQueue;constructor(t,e,n,s,o,i={}){this._log=V(t,"engine"),this.blockstore=e,this.network=n,this._stats=s,this._opts=this._processOpts(i),this.ledgerMap=Z({name:"ipfs_bitswap_ledger_map",metrics:o.metrics}),this._running=!1,this._requestQueue=new le(qs)}_processOpts(t){return{maxSizeReplaceHasWithBlock:Gc,targetMessageSize:$c,...t}}_scheduleProcessTasks(){setTimeout(()=>{this._processTasks().catch(t=>{this._log.error("error processing stats",t)})})}async _processTasks(){if(!this._running)return;let{peerId:t,tasks:e,pendingSize:n}=this._requestQueue.popTasks(this._opts.targetMessageSize);if(e.length===0)return;let s=new P(!1);s.setPendingBytes(n);let o=[],i=new Map;for(let c of e){let l=F.parse(c.topic);c.data.haveBlock?c.data.isWantBlock?(o.push(l),i.set(c.topic,c.data)):s.addHave(l):s.addDontHave(l)}let a=await this._getBlocks(o);for(let[c,l]of i){let h=F.parse(c),u=a.get(c);u!=null?s.addBlock(h,u):l.sendDontHave&&s.addDontHave(h)}if(s.empty){t!=null&&this._requestQueue.tasksDone(t,e),this._scheduleProcessTasks();return}try{t!=null&&await this.network.sendMessage(t,s);for(let[c,l]of a.entries())t!=null&&this.messageSent(t,F.parse(c),l)}catch(c){this._log.error(c)}t!=null&&this._requestQueue.tasksDone(t,e),this._scheduleProcessTasks()}wantlistForPeer(t){let e=t.toString(),n=this.ledgerMap.get(e);return n!=null?n.wantlist.sortedEntries():new Map}ledgerForPeer(t){let e=t.toString(),n=this.ledgerMap.get(e);if(n!=null)return{peer:n.partner,value:n.debtRatio(),sent:n.accounting.bytesSent,recv:n.accounting.bytesRecv,exchanged:n.exchangeCount}}peers(){return Array.from(this.ledgerMap.values()).map(t=>t.partner)}receivedBlocks(t){if(t.length!==0){for(let e of this.ledgerMap.values())for(let{cid:n,block:s}of t){let o=e.wantlistContains(n);if(o==null)continue;let i=s.length,a=this._sendAsBlock(o.wantType,i),c=i;a||(c=P.blockPresenceSize(o.cid)),this._requestQueue.pushTasks(e.partner,[{topic:o.cid.toString(w),priority:o.priority,size:c,data:{blockSize:i,isWantBlock:a,haveBlock:!0,sendDontHave:!1}}])}this._scheduleProcessTasks()}}async messageReceived(t,e){let n=this._findOrCreate(t);if(e.empty)return;if(e.full&&(n.wantlist=new st),this._updateBlockAccounting(e.blocks,n),e.wantlist.size===0){this._scheduleProcessTasks();return}let s=[],o=[];e.wantlist.forEach(i=>{i.cancel?(n.cancelWant(i.cid),s.push(i.cid)):(n.wants(i.cid,i.priority,i.wantType),o.push(i))}),this._cancelWants(t,s),await this._addWants(t,o),this._scheduleProcessTasks()}_cancelWants(t,e){for(let n of e)this._requestQueue.remove(n.toString(w),t)}async _addWants(t,e){let n=await this._getBlockSizes(e.map(o=>o.cid)),s=[];for(let o of e){let i=o.cid.toString(w),a=n.get(i);if(a==null)o.sendDontHave&&s.push({topic:i,priority:o.priority,size:P.blockPresenceSize(o.cid),data:{isWantBlock:o.wantType===Hs.Block,blockSize:0,haveBlock:!1,sendDontHave:o.sendDontHave}});else{let c=this._sendAsBlock(o.wantType,a),l=a;c||(l=P.blockPresenceSize(o.cid)),s.push({topic:i,priority:o.priority,size:l,data:{isWantBlock:c,blockSize:a,haveBlock:!0,sendDontHave:o.sendDontHave}})}this._requestQueue.pushTasks(t,s)}}_sendAsBlock(t,e){return t===Hs.Block||e<=this._opts.maxSizeReplaceHasWithBlock}async _getBlockSizes(t){let e=await this._getBlocks(t);return new Map([...e].map(([n,s])=>[n,s.length]))}async _getBlocks(t){let e=new Map;return await Promise.all(t.map(async n=>{try{let s=await this.blockstore.get(n);e.set(n.toString(w),s)}catch(s){s.code!=="ERR_NOT_FOUND"&&this._log.error("failed to query blockstore for %s: %s",n,s)}})),e}_updateBlockAccounting(t,e){for(let n of t.values())this._log("got block (%s bytes)",n.length),e.receivedBytes(n.length)}messageSent(t,e,n){let s=this._findOrCreate(t);s.sentBytes(n.length),s.wantlist.remove(e)}numBytesSentTo(t){return this._findOrCreate(t).accounting.bytesSent}numBytesReceivedFrom(t){return this._findOrCreate(t).accounting.bytesRecv}peerDisconnected(t){this.ledgerMap.delete(t.toString())}_findOrCreate(t){let e=t.toString(),n=this.ledgerMap.get(e);if(n!=null)return n;let s=new ce(t);return this.ledgerMap.set(e,s),this._stats!=null&&this._stats.push(e,"peerCount",1),s}start(){this._running=!0}stop(){this._running=!1}};function jc(r){return r[Symbol.asyncIterator]!=null}function Xc(r){if(jc(r))return(async()=>{for await(let t of r);})();for(let t of r);}var Vs=Xc;var Qc=Math.pow(2,7),Jc=Math.pow(2,14),Kc=Math.pow(2,21),Br=Math.pow(2,28),Dr=Math.pow(2,35),Ir=Math.pow(2,42),Fr=Math.pow(2,49),_=128,U=127;function pt(r){if(r<Qc)return 1;if(r<Jc)return 2;if(r<Kc)return 3;if(r<Br)return 4;if(r<Dr)return 5;if(r<Ir)return 6;if(r<Fr)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function Zc(r,t,e=0){switch(pt(r)){case 8:t[e++]=r&255|_,r/=128;case 7:t[e++]=r&255|_,r/=128;case 6:t[e++]=r&255|_,r/=128;case 5:t[e++]=r&255|_,r/=128;case 4:t[e++]=r&255|_,r>>>=7;case 3:t[e++]=r&255|_,r>>>=7;case 2:t[e++]=r&255|_,r>>>=7;case 1:{t[e++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return t}function Yc(r,t,e=0){switch(pt(r)){case 8:t.set(e++,r&255|_),r/=128;case 7:t.set(e++,r&255|_),r/=128;case 6:t.set(e++,r&255|_),r/=128;case 5:t.set(e++,r&255|_),r/=128;case 4:t.set(e++,r&255|_),r>>>=7;case 3:t.set(e++,r&255|_),r>>>=7;case 2:t.set(e++,r&255|_),r>>>=7;case 1:{t.set(e++,r&255),r>>>=7;break}default:throw new Error("unreachable")}return t}function tl(r,t){let e=r[t],n=0;if(n+=e&U,e<_||(e=r[t+1],n+=(e&U)<<7,e<_)||(e=r[t+2],n+=(e&U)<<14,e<_)||(e=r[t+3],n+=(e&U)<<21,e<_)||(e=r[t+4],n+=(e&U)*Br,e<_)||(e=r[t+5],n+=(e&U)*Dr,e<_)||(e=r[t+6],n+=(e&U)*Ir,e<_)||(e=r[t+7],n+=(e&U)*Fr,e<_))return n;throw new RangeError("Could not decode varint")}function el(r,t){let e=r.get(t),n=0;if(n+=e&U,e<_||(e=r.get(t+1),n+=(e&U)<<7,e<_)||(e=r.get(t+2),n+=(e&U)<<14,e<_)||(e=r.get(t+3),n+=(e&U)<<21,e<_)||(e=r.get(t+4),n+=(e&U)*Br,e<_)||(e=r.get(t+5),n+=(e&U)*Dr,e<_)||(e=r.get(t+6),n+=(e&U)*Ir,e<_)||(e=r.get(t+7),n+=(e&U)*Fr,e<_))return n;throw new RangeError("Could not decode varint")}function Ws(r,t,e=0){return t==null&&(t=M(pt(r))),t instanceof Uint8Array?Zc(r,t,e):Yc(r,t,e)}function $s(r,t=0){return r instanceof Uint8Array?tl(r,t):el(r,t)}function Nr(r,t){if(globalThis.Buffer!=null)return nt(globalThis.Buffer.concat(r,t));t==null&&(t=r.reduce((s,o)=>s+o.length,0));let e=M(t),n=0;for(let s of r)e.set(s,n),n+=s.length;return nt(e)}function fe(r,t){if(r===t)return!0;if(r.byteLength!==t.byteLength)return!1;for(let e=0;e<r.byteLength;e++)if(r[e]!==t[e])return!1;return!0}var Xs=Symbol.for("@achingbrain/uint8arraylist");function js(r,t){if(t==null||t<0)throw new RangeError("index is out of bounds");let e=0;for(let n of r){let s=e+n.byteLength;if(t<s)return{buf:n,index:t-e};e=s}throw new RangeError("index is out of bounds")}function de(r){return!!r?.[Xs]}var Bt=class r{bufs;length;[Xs]=!0;constructor(...t){this.bufs=[],this.length=0,t.length>0&&this.appendAll(t)}*[Symbol.iterator](){yield*this.bufs}get byteLength(){return this.length}append(...t){this.appendAll(t)}appendAll(t){let e=0;for(let n of t)if(n instanceof Uint8Array)e+=n.byteLength,this.bufs.push(n);else if(de(n))e+=n.byteLength,this.bufs.push(...n.bufs);else throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");this.length+=e}prepend(...t){this.prependAll(t)}prependAll(t){let e=0;for(let n of t.reverse())if(n instanceof Uint8Array)e+=n.byteLength,this.bufs.unshift(n);else if(de(n))e+=n.byteLength,this.bufs.unshift(...n.bufs);else throw new Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");this.length+=e}get(t){let e=js(this.bufs,t);return e.buf[e.index]}set(t,e){let n=js(this.bufs,t);n.buf[n.index]=e}write(t,e=0){if(t instanceof Uint8Array)for(let n=0;n<t.length;n++)this.set(e+n,t[n]);else if(de(t))for(let n=0;n<t.length;n++)this.set(e+n,t.get(n));else throw new Error("Could not write value, must be an Uint8Array or a Uint8ArrayList")}consume(t){if(t=Math.trunc(t),!(Number.isNaN(t)||t<=0)){if(t===this.byteLength){this.bufs=[],this.length=0;return}for(;this.bufs.length>0;)if(t>=this.bufs[0].byteLength)t-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift();else{this.bufs[0]=this.bufs[0].subarray(t),this.length-=t;break}}}slice(t,e){let{bufs:n,length:s}=this._subList(t,e);return Nr(n,s)}subarray(t,e){let{bufs:n,length:s}=this._subList(t,e);return n.length===1?n[0]:Nr(n,s)}sublist(t,e){let{bufs:n,length:s}=this._subList(t,e),o=new r;return o.length=s,o.bufs=[...n],o}_subList(t,e){if(t=t??0,e=e??this.length,t<0&&(t=this.length+t),e<0&&(e=this.length+e),t<0||e>this.length)throw new RangeError("index is out of bounds");if(t===e)return{bufs:[],length:0};if(t===0&&e===this.length)return{bufs:this.bufs,length:this.length};let n=[],s=0;for(let o=0;o<this.bufs.length;o++){let i=this.bufs[o],a=s,c=a+i.byteLength;if(s=c,t>=c)continue;let l=t>=a&&t<c,h=e>a&&e<=c;if(l&&h){if(t===a&&e===c){n.push(i);break}let u=t-a;n.push(i.subarray(u,u+(e-t)));break}if(l){if(t===0){n.push(i);continue}n.push(i.subarray(t-a));continue}if(h){if(e===c){n.push(i);break}n.push(i.subarray(0,e-a));break}n.push(i)}return{bufs:n,length:e-t}}indexOf(t,e=0){if(!de(t)&&!(t instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');let n=t instanceof Uint8Array?t:t.subarray();if(e=Number(e??0),isNaN(e)&&(e=0),e<0&&(e=this.length+e),e<0&&(e=0),t.length===0)return e>this.length?this.length:e;let s=n.byteLength;if(s===0)throw new TypeError("search must be at least 1 byte long");let o=256,i=new Int32Array(o);for(let u=0;u<o;u++)i[u]=-1;for(let u=0;u<s;u++)i[n[u]]=u;let a=i,c=this.byteLength-n.byteLength,l=n.byteLength-1,h;for(let u=e;u<=c;u+=h){h=0;for(let d=l;d>=0;d--){let b=this.get(u+d);if(n[d]!==b){h=Math.max(1,d-a[b]);break}}if(h===0)return u}return-1}getInt8(t){let e=this.subarray(t,t+1);return new DataView(e.buffer,e.byteOffset,e.byteLength).getInt8(0)}setInt8(t,e){let n=M(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt8(0,e),this.write(n,t)}getInt16(t,e){let n=this.subarray(t,t+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt16(0,e)}setInt16(t,e,n){let s=J(2);new DataView(s.buffer,s.byteOffset,s.byteLength).setInt16(0,e,n),this.write(s,t)}getInt32(t,e){let n=this.subarray(t,t+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt32(0,e)}setInt32(t,e,n){let s=J(4);new DataView(s.buffer,s.byteOffset,s.byteLength).setInt32(0,e,n),this.write(s,t)}getBigInt64(t,e){let n=this.subarray(t,t+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigInt64(0,e)}setBigInt64(t,e,n){let s=J(8);new DataView(s.buffer,s.byteOffset,s.byteLength).setBigInt64(0,e,n),this.write(s,t)}getUint8(t){let e=this.subarray(t,t+1);return new DataView(e.buffer,e.byteOffset,e.byteLength).getUint8(0)}setUint8(t,e){let n=M(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint8(0,e),this.write(n,t)}getUint16(t,e){let n=this.subarray(t,t+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint16(0,e)}setUint16(t,e,n){let s=J(2);new DataView(s.buffer,s.byteOffset,s.byteLength).setUint16(0,e,n),this.write(s,t)}getUint32(t,e){let n=this.subarray(t,t+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint32(0,e)}setUint32(t,e,n){let s=J(4);new DataView(s.buffer,s.byteOffset,s.byteLength).setUint32(0,e,n),this.write(s,t)}getBigUint64(t,e){let n=this.subarray(t,t+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigUint64(0,e)}setBigUint64(t,e,n){let s=J(8);new DataView(s.buffer,s.byteOffset,s.byteLength).setBigUint64(0,e,n),this.write(s,t)}getFloat32(t,e){let n=this.subarray(t,t+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat32(0,e)}setFloat32(t,e,n){let s=J(4);new DataView(s.buffer,s.byteOffset,s.byteLength).setFloat32(0,e,n),this.write(s,t)}getFloat64(t,e){let n=this.subarray(t,t+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat64(0,e)}setFloat64(t,e,n){let s=J(8);new DataView(s.buffer,s.byteOffset,s.byteLength).setFloat64(0,e,n),this.write(s,t)}equals(t){if(t==null||!(t instanceof r)||t.bufs.length!==this.bufs.length)return!1;for(let e=0;e<this.bufs.length;e++)if(!fe(this.bufs[e],t.bufs[e]))return!1;return!0}static fromUint8Arrays(t,e){let n=new r;return n.bufs=t,e==null&&(e=t.reduce((s,o)=>s+o.byteLength,0)),n.length=e,n}};function pe(r){return r[Symbol.asyncIterator]!=null}var me=r=>{let t=pt(r),e=M(t);return Ws(r,e),me.bytes=t,e};me.bytes=0;function ge(r,t){t=t??{};let e=t.lengthEncoder??me;function*n(s){let o=e(s.byteLength);o instanceof Uint8Array?yield o:yield*o,s instanceof Uint8Array?yield s:yield*s}return pe(r)?async function*(){for await(let s of r)yield*n(s)}():function*(){for(let s of r)yield*n(s)}()}ge.single=(r,t)=>{t=t??{};let e=t.lengthEncoder??me;return new Bt(e(r.byteLength),r)};var Dt=G(Ks(),1);var nl=8,sl=1024*1024*4,mt;(function(r){r[r.LENGTH=0]="LENGTH",r[r.DATA=1]="DATA"})(mt||(mt={}));var Mr=r=>{let t=$s(r);return Mr.bytes=pt(t),t};Mr.bytes=0;function Qt(r,t){let e=new Bt,n=mt.LENGTH,s=-1,o=t?.lengthDecoder??Mr,i=t?.maxLengthLength??nl,a=t?.maxDataLength??sl;function*c(){for(;e.byteLength>0;){if(n===mt.LENGTH)try{if(s=o(e),s<0)throw(0,Dt.default)(new Error("invalid message length"),"ERR_INVALID_MSG_LENGTH");if(s>a)throw(0,Dt.default)(new Error("message length too long"),"ERR_MSG_DATA_TOO_LONG");let l=o.bytes;e.consume(l),t?.onLength!=null&&t.onLength(s),n=mt.DATA}catch(l){if(l instanceof RangeError){if(e.byteLength>i)throw(0,Dt.default)(new Error("message length length too long"),"ERR_MSG_LENGTH_TOO_LONG");break}throw l}if(n===mt.DATA){if(e.byteLength<s)break;let l=e.sublist(0,s);e.consume(s),t?.onData!=null&&t.onData(l),yield l,n=mt.LENGTH}}}return pe(r)?async function*(){for await(let l of r)e.append(l),yield*c();if(e.byteLength>0)throw(0,Dt.default)(new Error("unexpected end of input"),"ERR_UNEXPECTED_EOF")}():function*(){for(let l of r)e.append(l),yield*c();if(e.byteLength>0)throw(0,Dt.default)(new Error("unexpected end of input"),"ERR_UNEXPECTED_EOF")}()}Qt.fromReader=(r,t)=>{let e=1,n=async function*(){for(;;)try{let{done:o,value:i}=await r.next(e);if(o===!0)return;i!=null&&(yield i)}catch(o){if(o.code==="ERR_UNDER_READ")return{done:!0,value:null};throw o}finally{e=1}}();return Qt(n,{...t??{},onLength:o=>{e=o}})};function il(r){return r[Symbol.asyncIterator]!=null}function al(r,t){if(il(r))return async function*(){for await(let a of r)yield t(a)}();let e=gt(r),{value:n,done:s}=e.next();if(s===!0)return function*(){}();let o=t(n);if(typeof o.then=="function")return async function*(){yield await o;for await(let a of e)yield t(a)}();let i=t;return function*(){yield o;for(let a of e)yield i(a)}()}var Zs=al;function be(){let r={};return r.promise=new Promise((t,e)=>{r.resolve=t,r.reject=e}),r}var ye=class{buffer;mask;top;btm;next;constructor(t){if(!(t>0)||t-1&t)throw new Error("Max size for a FixedFIFO should be a power of two");this.buffer=new Array(t),this.mask=t-1,this.top=0,this.btm=0,this.next=null}push(t){return this.buffer[this.top]!==void 0?!1:(this.buffer[this.top]=t,this.top=this.top+1&this.mask,!0)}shift(){let t=this.buffer[this.btm];if(t!==void 0)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,t}isEmpty(){return this.buffer[this.btm]===void 0}},It=class{size;hwm;head;tail;constructor(t={}){this.hwm=t.splitLimit??16,this.head=new ye(this.hwm),this.tail=this.head,this.size=0}calculateSize(t){return t?.byteLength!=null?t.byteLength:1}push(t){if(t?.value!=null&&(this.size+=this.calculateSize(t.value)),!this.head.push(t)){let e=this.head;this.head=e.next=new ye(2*this.head.buffer.length),this.head.push(t)}}shift(){let t=this.tail.shift();if(t===void 0&&this.tail.next!=null){let e=this.tail.next;this.tail.next=null,this.tail=e,t=this.tail.shift()}return t?.value!=null&&(this.size-=this.calculateSize(t.value)),t}isEmpty(){return this.head.isEmpty()}};var Pr=class extends Error{type;code;constructor(t,e){super(t??"The operation was aborted"),this.type="aborted",this.code=e??"ABORT_ERR"}};function we(r={}){return cl(e=>{let n=e.shift();if(n==null)return{done:!0};if(n.error!=null)throw n.error;return{done:n.done===!0,value:n.value}},r)}function cl(r,t){t=t??{};let e=t.onEnd,n=new It,s,o,i,a=be(),c=async()=>{try{return n.isEmpty()?i?{done:!0}:await new Promise((m,g)=>{o=y=>{o=null,n.push(y);try{m(r(n))}catch(v){g(v)}return s}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=be()})}},l=m=>o!=null?o(m):(n.push(m),s),h=m=>(n=new It,o!=null?o({error:m}):(n.push({error:m}),s)),u=m=>{if(i)return s;if(t?.objectMode!==!0&&m?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return l({done:!1,value:m})},d=m=>i?s:(i=!0,m!=null?h(m):l({done:!0})),b=()=>(n=new It,d(),{done:!0}),f=m=>(d(m),{done:!0});if(s={[Symbol.asyncIterator](){return this},next:c,return:b,throw:f,push:u,end:d,get readableLength(){return n.size},onEmpty:async m=>{let g=m?.signal;if(g?.throwIfAborted(),n.isEmpty())return;let y,v;g!=null&&(y=new Promise((x,C)=>{v=()=>{C(new Pr)},g.addEventListener("abort",v)}));try{await Promise.race([a.promise,y])}finally{v!=null&&g!=null&&g?.removeEventListener("abort",v)}}},e==null)return s;let p=s;return s={[Symbol.asyncIterator](){return this},next(){return p.next()},throw(m){return p.throw(m),e!=null&&(e(m),e=void 0),{done:!0}},return(){return p.return(),e!=null&&(e(),e=void 0),{done:!0}},push:u,end(m){return p.end(m),e!=null&&(e(m),e=void 0),s},get readableLength(){return p.readableLength},onEmpty:m=>p.onEmpty(m)},s}function ll(r){return r[Symbol.asyncIterator]!=null}function hl(...r){let t=[];for(let e of r)ll(e)||t.push(e);return t.length===r.length?function*(){for(let e of t)yield*e}():async function*(){let e=we({objectMode:!0});Promise.resolve().then(async()=>{try{await Promise.all(r.map(async n=>{for await(let s of n)e.push(s)})),e.end()}catch(n){e.end(n)}}),yield*e}()}var Ys=hl;function Rr(r,...t){if(r==null)throw new Error("Empty pipeline");if(Ur(r)){let n=r;r=()=>n.source}else if(eo(r)||to(r)){let n=r;r=()=>n}let e=[r,...t];if(e.length>1&&Ur(e[e.length-1])&&(e[e.length-1]=e[e.length-1].sink),e.length>2)for(let n=1;n<e.length-1;n++)Ur(e[n])&&(e[n]=fl(e[n]));return ul(...e)}var ul=(...r)=>{let t;for(;r.length>0;)t=r.shift()(t);return t},to=r=>r?.[Symbol.asyncIterator]!=null,eo=r=>r?.[Symbol.iterator]!=null,Ur=r=>r==null?!1:r.sink!=null&&r.source!=null,fl=r=>t=>{let e=r.sink(t);if(e?.then!=null){let n=we({objectMode:!0});e.then(()=>{n.end()},i=>{n.end(i)});let s,o=r.source;if(to(o))s=async function*(){yield*o,n.end()};else if(eo(o))s=function*(){yield*o,n.end()};else throw new Error("Unknown duplex source type - must be Iterable or AsyncIterable");return Ys(n,s())}return r.source};function dl(r){return r[Symbol.asyncIterator]!=null}function pl(r,t){return dl(r)?async function*(){let e=0;if(!(t<1)){for await(let n of r)if(yield n,e++,e===t)return}}():function*(){let e=0;if(!(t<1)){for(let n of r)if(yield n,e++,e===t)return}}()}var ro=pl;var k=class extends Event{constructor(t,e){super(t),this.detail=e}};var po=G(lo(),1);var ho=Math.pow(2,31)-1,uo=1e3,fo=1;var Hr="/ipfs/bitswap/1.0.0",Vr="/ipfs/bitswap/1.1.0",Wr="/ipfs/bitswap/1.2.0",yl=1024,wl=1024,xl=3e4,ve=class{_log;_libp2p;_bitswap;_protocols;_stats;_running;_hashLoader;_maxInboundStreams;_maxOutboundStreams;_incomingStreamTimeout;_registrarIds;constructor(t,e,n,s={}){this._log=V(t.peerId,"network"),this._libp2p=t,this._bitswap=e,this._protocols=[Hr],s.b100Only!==!0&&(this._protocols.unshift(Vr),this._protocols.unshift(Wr)),this._stats=n,this._running=!1,this._onPeerConnect=this._onPeerConnect.bind(this),this._onPeerDisconnect=this._onPeerDisconnect.bind(this),this._onConnection=this._onConnection.bind(this),this._hashLoader=s.hashLoader??{async getHasher(){throw new Error("Not implemented")}},this._maxInboundStreams=s.maxInboundStreams??yl,this._maxOutboundStreams=s.maxOutboundStreams??wl,this._incomingStreamTimeout=s.incomingStreamTimeout??xl}async start(){this._running=!0,await this._libp2p.handle(this._protocols,this._onConnection,{maxInboundStreams:this._maxInboundStreams,maxOutboundStreams:this._maxOutboundStreams});let t={onConnect:this._onPeerConnect,onDisconnect:this._onPeerDisconnect};this._registrarIds=[];for(let e of this._protocols)this._registrarIds.push(await this._libp2p.register(e,t));this._libp2p.getConnections().forEach(e=>{this._onPeerConnect(e.remotePeer)})}async stop(){if(this._running=!1,await this._libp2p.unhandle(this._protocols),this._registrarIds!=null){for(let t of this._registrarIds)this._libp2p.unregister(t);this._registrarIds=[]}}_onConnection(t){if(!this._running)return;let{stream:e,connection:n}=t,s=new po.TimeoutController(this._incomingStreamTimeout);Promise.resolve().then(async()=>{this._log("incoming new bitswap %s connection from %p",e.protocol,n.remotePeer);let o=()=>{e.abort(new X("Incoming Bitswap stream timed out","ERR_TIMEOUT"))},i=AbortSignal.timeout(this._incomingStreamTimeout);i.addEventListener("abort",o),await Rr(e,a=>Qt(a),async a=>{for await(let c of a){try{let l=await P.deserialize(c.subarray(),this._hashLoader);await this._bitswap._receiveMessage(n.remotePeer,l)}catch(l){this._bitswap._receiveError(l);break}i.removeEventListener("abort",o),i=AbortSignal.timeout(this._incomingStreamTimeout),i.addEventListener("abort",o)}}),await e.close({signal:i})}).catch(o=>{this._log(o),e.abort(o)}).finally(()=>{s.clear()})}_onPeerConnect(t){this._bitswap._onPeerConnected(t)}_onPeerDisconnect(t){this._bitswap._onPeerDisconnected(t)}findProviders(t,e={}){return e.onProgress?.(new k("bitswap:network:find-providers",t)),this._libp2p.contentRouting.findProviders(t,e)}async findAndConnect(t,e){await Vs(ro(Zs(this.findProviders(t,e),async n=>this.connectTo(n.id,e).catch(s=>{this._log.error(s)})),3)).catch(n=>{this._log.error(n)})}async provide(t,e={}){e.onProgress?.(new k("bitswap:network:provide",t)),await this._libp2p.contentRouting.provide(t,e)}async sendMessage(t,e,n={}){if(!this._running)throw new Error("network isn't running");let s=t.toString();this._log("sendMessage to %s",s,e),n.onProgress?.(new k("bitswap:network:send-wantlist",t)),await this._writeMessage(t,e,n),this._updateSentStats(t,e.blocks)}async connectTo(t,e={}){if(!this._running)throw new Error("network isn't running");return e.onProgress?.(new k("bitswap:network:dial",t)),this._libp2p.dial(t,e)}_updateSentStats(t,e){let n=t.toString();if(this._stats!=null){for(let s of e.values())this._stats.push(n,"dataSent",s.length);this._stats.push(n,"blocksSent",e.size)}}async _writeMessage(t,e,n={}){let s=await this._libp2p.dialProtocol(t,[Wr,Vr,Hr]);try{let o;switch(s.protocol){case Hr:o=e.serializeToBitswap100();break;case Vr:case Wr:o=e.serializeToBitswap110();break;default:throw new Error(`Unknown protocol: ${s.protocol}`)}await Rr([o],i=>ge(i),s),await s.close()}catch(o){n.onProgress?.(new k("bitswap:network:send-wantlist:error",{peer:t,error:o})),this._log(o),s.abort(o)}}};var Mo=G(Se(),1);var Gr={};A(Gr,{base10:()=>Cl});var Cl=K({prefix:"9",name:"base10",alphabet:"0123456789"});var jr={};A(jr,{base16:()=>Tl,base16upper:()=>Ll});var Tl=L({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),Ll=L({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var Xr={};A(Xr,{base2:()=>Bl});var Bl=L({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var Qr={};A(Qr,{base256emoji:()=>Ml});var Eo=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}"),Dl=Eo.reduce((r,t,e)=>(r[e]=t,r),[]),Il=Eo.reduce((r,t,e)=>(r[t.codePointAt(0)]=e,r),[]);function Fl(r){return r.reduce((t,e)=>(t+=Dl[e],t),"")}function Nl(r){let t=[];for(let e of r){let n=Il[e.codePointAt(0)];if(n===void 0)throw new Error(`Non-base256emoji character: ${e}`);t.push(n)}return new Uint8Array(t)}var Ml=bt({prefix:"\u{1F680}",name:"base256emoji",encode:Fl,decode:Nl});var Jr={};A(Jr,{base36:()=>Pl,base36upper:()=>Ul});var Pl=K({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Ul=K({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var Kr={};A(Kr,{base64:()=>Rl,base64pad:()=>Ol,base64url:()=>zl,base64urlpad:()=>ql});var Rl=L({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Ol=L({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),zl=L({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),ql=L({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var Zr={};A(Zr,{base8:()=>Hl});var Hl=L({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var Yr={};A(Yr,{identity:()=>Vl});var Vl=bt({prefix:"\0",name:"identity",encode:r=>fn(r),decode:r=>un(r)});var rm=new TextEncoder,nm=new TextDecoder;var tn={};A(tn,{identity:()=>Xl});var Ao=0,Gl="identity",Co=j,jl=r=>ot(Ao,Co(r)),Xl={code:Ao,name:Gl,encode:Co,digest:jl};var en={...Yr,...Xr,...Zr,...Gr,...jr,...Ue,...Jr,...Re,...Kr,...Qr},hm={...$e,...tn};function To(r){return globalThis.Buffer!=null?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):r}function Lo(r=0){return globalThis.Buffer?.allocUnsafe!=null?To(globalThis.Buffer.allocUnsafe(r)):new Uint8Array(r)}function Do(r,t,e,n){return{name:r,prefix:t,encoder:{name:r,prefix:t,encode:e},decoder:{decode:n}}}var Bo=Do("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),rn=Do("ascii","a",r=>{let t="a";for(let e=0;e<r.length;e++)t+=String.fromCharCode(r[e]);return t},r=>{r=r.substring(1);let t=Lo(r.length);for(let e=0;e<r.length;e++)t[e]=r.charCodeAt(e);return t}),Ql={utf8:Bo,"utf-8":Bo,hex:en.base16,latin1:rn,ascii:rn,binary:rn,...en},Io=Ql;function nn(r,t="utf8"){let e=Io[t];if(e==null)throw new Error(`Unsupported encoding "${t}"`);return(t==="utf8"||t==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?globalThis.Buffer.from(r.buffer,r.byteOffset,r.byteLength).toString("utf8"):e.encoder.encode(r).substring(1)}var Fo=r=>`unwant:${nn(r.multihash.bytes,"base64")}`,No=r=>`block:${nn(r.multihash.bytes,"base64")}`,Ee=class extends Mo.EventEmitter{_log;constructor(t){super(),this.setMaxListeners(uo),this._log=V(t,"notif")}hasBlock(t,e){let n=No(t);this._log(n),this.emit(n,e)}async wantBlock(t,e={}){if(t==null)throw new Error("Not a valid cid");let n=No(t),s=Fo(t);return this._log(`wantBlock:${t}`),new Promise((o,i)=>{let a=()=>{this.removeListener(n,c),e.onProgress?.(new k("bitswap:want-block:unwant",t)),i(new Error(`Block for ${t} unwanted`))},c=l=>{this.removeListener(s,a),e.onProgress?.(new k("bitswap:want-block:block",t)),o(l)};this.once(s,a),this.once(n,c),e.signal?.addEventListener("abort",()=>{this.removeListener(n,c),this.removeListener(s,a),i(new Error(`Want for ${t} aborted`))})})}unwantBlock(t){let e=Fo(t);this._log(e),this.emit(e)}};var qo=G(Se(),1);var Oo=G(Se(),1),sn=G(Ro(),1),Jt=class extends Oo.EventEmitter{_options;_queue;_stats;_frequencyLastTime;_frequencyAccumulators;_movingAverages;_enabled;_timeout;constructor(t,e){super(),this._options=e,this._queue=[],this._stats={},this._frequencyLastTime=Date.now(),this._frequencyAccumulators={},this._movingAverages={},this._update=this._update.bind(this),t.forEach(n=>{this._stats[n]=BigInt(0),this._movingAverages[n]={},this._options.movingAverageIntervals.forEach(s=>{(this._movingAverages[n][s]=(0,sn.default)(s)).push(this._frequencyLastTime,0)})}),this._enabled=this._options.enabled}enable(){this._enabled=!0}disable(){this._enabled=!1}stop(){this._timeout!=null&&clearTimeout(this._timeout)}get snapshot(){return Object.assign({},this._stats)}get movingAverages(){return Object.assign({},this._movingAverages)}push(t,e){this._enabled&&(this._queue.push([t,e,Date.now()]),this._resetComputeTimeout())}_resetComputeTimeout(){this._timeout!=null&&clearTimeout(this._timeout),this._timeout=setTimeout(this._update,this._nextTimeout())}_nextTimeout(){let t=this._queue.length/this._options.computeThrottleMaxQueueSize;return Math.max(this._options.computeThrottleTimeout*(1-t),0)}_update(){if(this._timeout=void 0,this._queue.length>0){let t;for(;this._queue.length>0;){let e=t=this._queue.shift();e!=null&&this._applyOp(e)}t!=null&&this._updateFrequency(t[2]),this.emit("update",this._stats)}}_updateFrequency(t){let e=t-this._frequencyLastTime;e>0&&Object.keys(this._stats).forEach(n=>{this._updateFrequencyFor(n,e,t)}),this._frequencyLastTime=t}_updateFrequencyFor(t,e,n){let s=this._frequencyAccumulators[t]??0;this._frequencyAccumulators[t]=0;let o=s/e*1e3,i=this._movingAverages[t];i==null&&(i=this._movingAverages[t]={}),this._options.movingAverageIntervals.forEach(a=>{let c=i[a];c==null&&(c=i[a]=(0,sn.default)(a)),c.push(n,o)})}_applyOp(t){let e=t[0],n=t[1];if(typeof n!="number")throw new Error(`invalid increment number: ${n}`);Object.prototype.hasOwnProperty.call(this._stats,e)||(this._stats[e]=BigInt(0)),this._stats[e]=BigInt(this._stats[e])+BigInt(n),this._frequencyAccumulators[e]==null&&(this._frequencyAccumulators[e]=0),this._frequencyAccumulators[e]+=n}};var zo={enabled:!1,computeThrottleTimeout:1e3,computeThrottleMaxQueueSize:1e3,movingAverageIntervals:[60*1e3,5*60*1e3,15*60*1e3]},Ae=class extends qo.EventEmitter{_initialCounters;_options;_enabled;_global;_peers;constructor(t,e=[],n=zo){super();let s=Object.assign({},zo,n);if(typeof s.computeThrottleTimeout!="number")throw new Error("need computeThrottleTimeout");if(typeof s.computeThrottleMaxQueueSize!="number")throw new Error("need computeThrottleMaxQueueSize");this._initialCounters=e,this._options=s,this._enabled=this._options.enabled,this._global=new Jt(e,s),this._global.on("update",o=>this.emit("update",o)),this._peers=Z({name:"ipfs_bitswap_stats_peers",metrics:t.metrics})}enable(){this._enabled=!0,this._options.enabled=!0,this._global.enable()}disable(){this._enabled=!1,this._options.enabled=!1,this._global.disable()}stop(){this._enabled=!1,this._global.stop();for(let t of this._peers)t[1].stop()}get snapshot(){return this._global.snapshot}get movingAverages(){return this._global.movingAverages}forPeer(t){let e=t.toString();return this._peers.get(e)}push(t,e,n){if(this._enabled&&(this._global.push(e,n),t!=null)){let s=this._peers.get(t);s==null&&(s=new Jt(this._initialCounters,this._options),this._peers.set(t,s)),s.push(e,n)}}disconnected(t){let e=t.toString(),n=this._peers.get(e);n!=null&&(n.stop(),this._peers.delete(e))}};var Ho=Kl;function Kl(r,t,e){var n=null,s=null,o=function(){n&&(clearTimeout(n),s=null,n=null)},i=function(){var c=s;o(),c&&c()},a=function(){if(!t)return r.apply(this,arguments);var c=this,l=arguments,h=e&&!n;if(o(),s=function(){r.apply(c,l)},n=setTimeout(function(){if(n=null,!h){var u=s;return s=null,u()}},t),h)return s()};return a.cancel=o,a.flush=i,a}var Ce=class{peerId;refcnt;network;_entries;_log;constructor(t,e,n){this.peerId=e,this.network=n,this.refcnt=1,this._entries=[],this._log=V(t,"msgqueue"),this.sendEntries=Ho(this.sendEntries.bind(this),fo)}addMessage(t,e={}){t.empty||this.send(t,e)}addEntries(t,e={}){this._entries=this._entries.concat(t),this.sendEntries(e)}sendEntries(t={}){if(this._entries.length===0)return;let e=new P(!1);this._entries.forEach(n=>{n.cancel===!0?e.cancel(n.cid):e.addEntry(n.cid,n.priority)}),this._entries=[],this.addMessage(e,t)}async send(t,e={}){try{await this.network.connectTo(this.peerId,e)}catch(n){this._log.error("cant connect to peer %p: %s",this.peerId,n.message);return}this._log("sending message to peer %p",this.peerId),this.network.sendMessage(this.peerId,t,e).catch(n=>{this._log.error("send error",n)})}};var Te=class{peers;wantlist;network;_peerId;_log;constructor(t,e,n,s){this.peers=Z({name:"ipfs_bitswap_want_manager_peers",metrics:s.metrics}),this.wantlist=new st(n,s),this.network=e,this._peerId=t,this._log=V(t,"want")}_addEntries(t,e,n,s={}){let o=t.map((i,a)=>new P.Entry(i,ho-a,P.WantType.Block,e));o.forEach(i=>{i.cancel?n===!0?this.wantlist.removeForce(i.cid.toString(w)):this.wantlist.remove(i.cid):(this._log("adding to wantlist"),this.wantlist.add(i.cid,i.priority))});for(let i of this.peers.values())i.addEntries(o,s)}_startPeerHandler(t){let e=this.peers.get(t.toString());if(e!=null){e.refcnt++;return}e=new Ce(this._peerId,t,this.network);let n=new P(!0);for(let s of this.wantlist.entries())n.addEntry(s[1].cid,s[1].priority);return e.addMessage(n),this.peers.set(t.toString(),e),e}_stopPeerHandler(t){let e=this.peers.get(t.toString());e!=null&&(e.refcnt--,!(e.refcnt>0)&&this.peers.delete(t.toString()))}wantBlocks(t,e={}){this._addEntries(t,!1,!1,e),e.signal?.addEventListener("abort",()=>{this.cancelWants(t)})}unwantBlocks(t){this._log("unwant blocks: %s",t.length),this._addEntries(t,!0,!0)}cancelWants(t){this._log("cancel wants: %s",t.length),this._addEntries(t,!0)}connectedPeers(){return Array.from(this.peers.keys())}connected(t){this._startPeerHandler(t)}disconnected(t){this._stopPeerHandler(t)}start(){}stop(){this.peers.forEach(t=>{this.disconnected(t.peerId)})}};var Zl={async getHasher(){throw new Error("Not implemented")}},Yl={maxInboundStreams:1024,maxOutboundStreams:1024,incomingStreamTimeout:3e4,hashLoader:Zl,statsEnabled:!1,statsComputeThrottleTimeout:1e3,statsComputeThrottleMaxQueueSize:1e3},th=["blocksReceived","dataReceived","dupBlksReceived","dupDataReceived","blocksSent","dataSent","providesBufferLength","wantListLength","peerCount"],Le=class{_libp2p;_log;stats;network;blockstore;engine;wm;notifications;started;constructor(t,e,n={}){this._libp2p=t,this._log=V(this.peerId),n=Object.assign({},Yl,n),this.stats=new Ae(t,th,{enabled:n.statsEnabled,computeThrottleTimeout:n.statsComputeThrottleTimeout,computeThrottleMaxQueueSize:n.statsComputeThrottleMaxQueueSize}),this.network=new ve(t,this,this.stats,{hashLoader:n.hashLoader,maxInboundStreams:n.maxInboundStreams,maxOutboundStreams:n.maxOutboundStreams,incomingStreamTimeout:n.incomingStreamTimeout}),this.blockstore=e,this.engine=new ue(this.peerId,e,this.network,this.stats,t),this.wm=new Te(this.peerId,this.network,this.stats,t),this.notifications=new Ee(this.peerId),this.started=!1}isStarted(){return this.started}get peerId(){return this._libp2p.peerId}async _receiveMessage(t,e){try{await this.engine.messageReceived(t,e)}catch{this._log("failed to receive message",e)}if(e.blocks.size===0)return;let n=[];for(let[s,o]of e.blocks.entries()){let i=F.parse(s);n.push({wasWanted:this.wm.wantlist.contains(i),cid:i,data:o})}this.wm.cancelWants(n.filter(({wasWanted:s})=>s).map(({cid:s})=>s)),await Promise.all(n.map(async({cid:s,wasWanted:o,data:i})=>{await this._handleReceivedBlock(t,s,i,o)}))}async _handleReceivedBlock(t,e,n,s){this._log("received block");let o=await this.blockstore.has(e);this._updateReceiveCounters(t.toString(),e,n,o),s&&await this.put(e,n)}_updateReceiveCounters(t,e,n,s){this.stats.push(t,"blocksReceived",1),this.stats.push(t,"dataReceived",n.length),s&&(this.stats.push(t,"dupBlksReceived",1),this.stats.push(t,"dupDataReceived",n.length))}_receiveError(t){this._log.error("ReceiveError",t)}_onPeerConnected(t){this.wm.connected(t)}_onPeerDisconnected(t){this.wm.disconnected(t),this.engine.peerDisconnected(t),this.stats.disconnected(t)}enableStats(){this.stats.enable()}disableStats(){this.stats.disable()}wantlistForPeer(t,e){return this.engine.wantlistForPeer(t)}ledgerForPeer(t){return this.engine.ledgerForPeer(t)}async want(t,e={}){let n=async(c,l)=>(this.wm.wantBlocks([c],l),this.notifications.wantBlock(c,l)),s=!1,o=async(c,l)=>{try{return await this.blockstore.get(c,l)}catch(h){if(h.code!=="ERR_NOT_FOUND")throw h;return s||(s=!0,this.network.findAndConnect(c,l).catch(u=>{this._log.error(u)})),await n(c,l)}},i=new AbortController,a=Zt([i.signal,e.signal]);try{return await Promise.race([this.notifications.wantBlock(t,{...e,signal:a}),o(t,{...e,signal:a})])}finally{i.abort(),a.clear()}}unwant(t){let e=Array.isArray(t)?t:[t];this.wm.unwantBlocks(e),e.forEach(n=>{this.notifications.unwantBlock(n)})}cancelWants(t){this.wm.cancelWants(Array.isArray(t)?t:[t])}async put(t,e,n){await this.blockstore.put(t,e),this.notify(t,e)}async*putMany(t,e){yield*this.blockstore.putMany(Nt(t,({cid:n,block:s})=>{this.notify(n,s)}),e)}notify(t,e,n={}){this.notifications.hasBlock(t,e),this.engine.receivedBlocks([{cid:t,block:e}]),this.network.provide(t,n).catch(s=>{this._log.error("Failed to provide: %s",s.message)})}getWantlist(){return this.wm.wantlist.entries()}get peers(){return this.engine.peers()}async start(){this.wm.start(),await this.network.start(),this.engine.start(),this.started=!0}async stop(){this.stats.stop(),this.wm.stop(),await this.network.stop(),this.engine.stop(),this.started=!1}};var Vo=(r,t,e={})=>new Le(r,t,e);var on=class{bitswap;started;constructor(t,e={}){let{libp2p:n,blockstore:s,hashers:o}=t;this.bitswap=Vo(n,s,{hashLoader:{getHasher:async i=>{let a=o.find(c=>c.code===i||c.name===i);if(a!=null)return a;throw new Error(`Could not load hasher for code/name "${i}"`)}},...e}),this.started=!1}isStarted(){return this.started}async start(){await this.bitswap.start(),this.started=!0}async stop(){await this.bitswap.stop(),this.started=!1}announce(t,e,n){this.bitswap.notify(t,e,n)}async retrieve(t,{validateFn:e,...n}={}){return this.bitswap.want(t,n)}};function Wo(r={}){return t=>new on(t,r)}var Be=class{url;#t=0;#e=0;#r=0;#n=0;constructor(t){this.url=t instanceof URL?t:new URL(t)}async getRawBlock(t,e){let n=this.url;if(n.pathname=`/ipfs/${t.toString()}`,n.search="?format=raw",e?.aborted===!0)throw new Error(`Signal to fetch raw block for CID ${t} from gateway ${this.url} was aborted prior to fetch`);try{this.#t++;let s=await fetch(n.toString(),{signal:e,headers:{Accept:"application/vnd.ipld.raw"},cache:"force-cache"});if(!s.ok)throw this.#e++,new Error(`unable to fetch raw block for CID ${t} from gateway ${this.url}`);return this.#n++,new Uint8Array(await s.arrayBuffer())}catch{throw e?.aborted===!0?new Error(`fetching raw block for CID ${t} from gateway ${this.url} was aborted`):(this.#e++,new Error(`unable to fetch raw block for CID ${t}`))}}reliability(){return this.#t===0?1:this.#r>0?-1/0:this.#n/(this.#t+this.#e*3)}incrementInvalidBlocks(){this.#r++}};var De=class{gateways;log;constructor(t,e={}){this.log=t.logger.forComponent("helia:trustless-gateway-block-broker"),this.gateways=(e.gateways??$o).map(n=>new Be(n))}async retrieve(t,e={}){let n=this.gateways.sort((o,i)=>i.reliability()-o.reliability()),s=[];for(let o of n){this.log("getting block for %c from %s",t,o.url);try{let i=await o.getRawBlock(t,e.signal);this.log.trace("got block for %c from %s",t,o.url);try{await e.validateFn?.(i)}catch(a){throw this.log.error("failed to validate block for %c from %s",t,o.url,a),o.incrementInvalidBlocks(),new Error(`unable to validate block for CID ${t} from gateway ${o.url}`)}return i}catch(i){if(this.log.error("failed to get block for %c from %s",t,o.url,i),i instanceof Error?s.push(i):s.push(new Error(`unable to fetch raw block for CID ${t} from gateway ${o.url}`)),e.signal?.aborted===!0){this.log.trace("request aborted while fetching raw block for CID %c from gateway %s",t,o.url);break}}}throw new AggregateError(s,`unable to fetch raw block for CID ${t} from any gateway`)}};var $o=["https://dweb.link","https://cf-ipfs.com","https://4everland.io","https://w3s.link"];function Go(r={}){return t=>new De(t,r)}function eh(r){return r[Symbol.asyncIterator]!=null}function rh(r,t){if(eh(r))return async function*(){for await(let a of r)await t(a)&&(yield a)}();let e=gt(r),{value:n,done:s}=e.next();if(s===!0)return function*(){}();let o=t(n);if(typeof o.then=="function")return async function*(){await o&&(yield n);for await(let a of e)await t(a)&&(yield a)}();let i=t;return function*(){o===!0&&(yield n);for(let a of e)i(a)&&(yield a)}()}var jo=rh;function nh(r){return typeof r.retrieve=="function"}function sh(r){return typeof r.announce=="function"}var Ie=class{child;blockRetrievers;blockAnnouncers;hashers;started;log;constructor(t,e){this.log=t.logger.forComponent("helia:networked-storage"),this.child=t.blockstore,this.blockRetrievers=(e.blockBrokers??[]).filter(nh),this.blockAnnouncers=(e.blockBrokers??[]).filter(sh),this.hashers=e.hashers??[],this.started=!1}isStarted(){return this.started}async start(){await An(this.child,...new Set([...this.blockRetrievers,...this.blockAnnouncers])),this.started=!0}async stop(){await Cn(this.child,...new Set([...this.blockRetrievers,...this.blockAnnouncers])),this.started=!1}unwrap(){return this.child}async put(t,e,n={}){return await this.child.has(t)?(n.onProgress?.(new k("blocks:put:duplicate",t)),t):(n.onProgress?.(new k("blocks:put:providers:notify",t)),this.blockAnnouncers.forEach(s=>{s.announce(t,e,n)}),n.onProgress?.(new k("blocks:put:blockstore:put",t)),this.child.put(t,e,n))}async*putMany(t,e={}){let n=jo(t,async({cid:o})=>{let i=await this.child.has(o);return i&&e.onProgress?.(new k("blocks:put-many:duplicate",o)),!i}),s=Nt(n,({cid:o,block:i})=>{e.onProgress?.(new k("blocks:put-many:providers:notify",o)),this.blockAnnouncers.forEach(a=>{a.announce(o,i,e)})});e.onProgress?.(new k("blocks:put-many:blockstore:put-many")),yield*this.child.putMany(s,e)}async get(t,e={}){if(e.offline!==!0&&!await this.child.has(t)){e.onProgress?.(new k("blocks:get:providers:get",t));let n=await Xo(t,this.blockRetrievers,this.hashers,{...e,log:this.log});return e.onProgress?.(new k("blocks:get:blockstore:put",t)),await this.child.put(t,n,e),e.onProgress?.(new k("blocks:get:providers:notify",t)),this.blockAnnouncers.forEach(s=>{s.announce(t,n,e)}),n}return e.onProgress?.(new k("blocks:get:blockstore:get",t)),this.child.get(t,e)}async*getMany(t,e={}){e.onProgress?.(new k("blocks:get-many:blockstore:get-many")),yield*this.child.getMany(Nt(t,async n=>{if(e.offline!==!0&&!await this.child.has(n)){e.onProgress?.(new k("blocks:get-many:providers:get",n));let s=await Xo(n,this.blockRetrievers,this.hashers,{...e,log:this.log});e.onProgress?.(new k("blocks:get-many:blockstore:put",n)),await this.child.put(n,s,e),e.onProgress?.(new k("blocks:get-many:providers:notify",n)),this.blockAnnouncers.forEach(o=>{o.announce(n,s,e)})}}))}async delete(t,e={}){e.onProgress?.(new k("blocks:delete:blockstore:delete",t)),await this.child.delete(t,e)}async*deleteMany(t,e={}){e.onProgress?.(new k("blocks:delete-many:blockstore:delete-many")),yield*this.child.deleteMany(async function*(){for await(let n of t)yield n}(),e)}async has(t,e={}){return this.child.has(t,e)}async*getAll(t={}){t.onProgress?.(new k("blocks:get-all:blockstore:get-many")),yield*this.child.getAll(t)}},oh=(r,t)=>{let e=t.find(n=>n.code===r.multihash.code);if(e==null)throw new X(`No hasher configured for multihash code 0x${r.multihash.code.toString(16)}, please configure one. You can look up which hash this is at https://github.com/multiformats/multicodec/blob/master/table.csv`,"ERR_UNKNOWN_HASH_ALG");return async n=>{let s=await e.digest(n);if(!fe(s.digest,r.multihash.digest))throw new X("Hash of downloaded block did not match multihash from passed CID","ERR_HASH_MISMATCH")}};async function Xo(r,t,e,n){let s=oh(r,e),o=new AbortController,i=Zt([o.signal,n.signal]);try{return await Promise.any(t.map(async a=>{try{let c=!1,l=await a.retrieve(r,{...n,signal:i,validateFn:async h=>{await s(h),c=!0}});return c||await s(l),l}catch(c){throw n.log.error("could not retrieve verified block for %c",r,c),c}}))}finally{i.clear()}}return ti(ih);})();
3
+ return HeliaBlockBrokers}));
@@ -0,0 +1,19 @@
1
+ import type { BlockBroker } from '@helia/interface/blocks';
2
+ import type { Libp2p } from '@libp2p/interface';
3
+ import type { Blockstore } from 'interface-blockstore';
4
+ import type { BitswapOptions } from 'ipfs-bitswap';
5
+ import type { MultihashHasher } from 'multiformats/hashes/interface';
6
+ interface BitswapComponents {
7
+ libp2p: Libp2p;
8
+ blockstore: Blockstore;
9
+ hashers: MultihashHasher[];
10
+ }
11
+ export interface BitswapInit extends BitswapOptions {
12
+ }
13
+ /**
14
+ * A helper factory for users who want to override Helia `blockBrokers` but
15
+ * still want to use the default `BitswapBlockBroker`.
16
+ */
17
+ export declare function bitswap(init?: BitswapInit): (components: BitswapComponents) => BlockBroker;
18
+ export {};
19
+ //# sourceMappingURL=bitswap.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"bitswap.d.ts","sourceRoot":"","sources":["../../src/bitswap.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAkB,WAAW,EAAyC,MAAM,yBAAyB,CAAA;AACjH,OAAO,KAAK,EAAE,MAAM,EAAa,MAAM,mBAAmB,CAAA;AAC1D,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,sBAAsB,CAAA;AACtD,OAAO,KAAK,EAAwC,cAAc,EAAkC,MAAM,cAAc,CAAA;AAExH,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,+BAA+B,CAAA;AAGpE,UAAU,iBAAiB;IACzB,MAAM,EAAE,MAAM,CAAA;IACd,UAAU,EAAE,UAAU,CAAA;IACtB,OAAO,EAAE,eAAe,EAAE,CAAA;CAC3B;AAED,MAAM,WAAW,WAAY,SAAQ,cAAc;CAElD;AAqDD;;;GAGG;AACH,wBAAgB,OAAO,CAAE,IAAI,GAAE,WAAgB,GAAG,CAAC,UAAU,EAAE,iBAAiB,KAAK,WAAW,CAE/F"}
@@ -0,0 +1,48 @@
1
+ import { createBitswap } from 'ipfs-bitswap';
2
+ class BitswapBlockBroker {
3
+ bitswap;
4
+ started;
5
+ constructor(components, init = {}) {
6
+ const { libp2p, blockstore, hashers } = components;
7
+ this.bitswap = createBitswap(libp2p, blockstore, {
8
+ hashLoader: {
9
+ getHasher: async (codecOrName) => {
10
+ const hasher = hashers.find(hasher => {
11
+ return hasher.code === codecOrName || hasher.name === codecOrName;
12
+ });
13
+ if (hasher != null) {
14
+ return hasher;
15
+ }
16
+ throw new Error(`Could not load hasher for code/name "${codecOrName}"`);
17
+ }
18
+ },
19
+ ...init
20
+ });
21
+ this.started = false;
22
+ }
23
+ isStarted() {
24
+ return this.started;
25
+ }
26
+ async start() {
27
+ await this.bitswap.start();
28
+ this.started = true;
29
+ }
30
+ async stop() {
31
+ await this.bitswap.stop();
32
+ this.started = false;
33
+ }
34
+ announce(cid, block, options) {
35
+ this.bitswap.notify(cid, block, options);
36
+ }
37
+ async retrieve(cid, { validateFn, ...options } = {}) {
38
+ return this.bitswap.want(cid, options);
39
+ }
40
+ }
41
+ /**
42
+ * A helper factory for users who want to override Helia `blockBrokers` but
43
+ * still want to use the default `BitswapBlockBroker`.
44
+ */
45
+ export function bitswap(init = {}) {
46
+ return (components) => new BitswapBlockBroker(components, init);
47
+ }
48
+ //# sourceMappingURL=bitswap.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"bitswap.js","sourceRoot":"","sources":["../../src/bitswap.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,cAAc,CAAA;AAmB5C,MAAM,kBAAkB;IAGL,OAAO,CAAS;IACzB,OAAO,CAAS;IAExB,YAAa,UAA6B,EAAE,OAAoB,EAAE;QAChE,MAAM,EAAE,MAAM,EAAE,UAAU,EAAE,OAAO,EAAE,GAAG,UAAU,CAAA;QAElD,IAAI,CAAC,OAAO,GAAG,aAAa,CAAC,MAAM,EAAE,UAAU,EAAE;YAC/C,UAAU,EAAE;gBACV,SAAS,EAAE,KAAK,EAAE,WAA4B,EAAoC,EAAE;oBAClF,MAAM,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,MAAM,CAAC,EAAE;wBACnC,OAAO,MAAM,CAAC,IAAI,KAAK,WAAW,IAAI,MAAM,CAAC,IAAI,KAAK,WAAW,CAAA;oBACnE,CAAC,CAAC,CAAA;oBAEF,IAAI,MAAM,IAAI,IAAI,EAAE,CAAC;wBACnB,OAAO,MAAM,CAAA;oBACf,CAAC;oBAED,MAAM,IAAI,KAAK,CAAC,wCAAwC,WAAW,GAAG,CAAC,CAAA;gBACzE,CAAC;aACF;YACD,GAAG,IAAI;SACR,CAAC,CAAA;QACF,IAAI,CAAC,OAAO,GAAG,KAAK,CAAA;IACtB,CAAC;IAED,SAAS;QACP,OAAO,IAAI,CAAC,OAAO,CAAA;IACrB,CAAC;IAED,KAAK,CAAC,KAAK;QACT,MAAM,IAAI,CAAC,OAAO,CAAC,KAAK,EAAE,CAAA;QAC1B,IAAI,CAAC,OAAO,GAAG,IAAI,CAAA;IACrB,CAAC;IAED,KAAK,CAAC,IAAI;QACR,MAAM,IAAI,CAAC,OAAO,CAAC,IAAI,EAAE,CAAA;QACzB,IAAI,CAAC,OAAO,GAAG,KAAK,CAAA;IACtB,CAAC;IAED,QAAQ,CAAE,GAAQ,EAAE,KAAiB,EAAE,OAAsD;QAC3F,IAAI,CAAC,OAAO,CAAC,MAAM,CAAC,GAAG,EAAE,KAAK,EAAE,OAAO,CAAC,CAAA;IAC1C,CAAC;IAED,KAAK,CAAC,QAAQ,CAAE,GAAQ,EAAE,EAAE,UAAU,EAAE,GAAG,OAAO,KAA6E,EAAE;QAC/H,OAAO,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,GAAG,EAAE,OAAO,CAAC,CAAA;IACxC,CAAC;CACF;AAED;;;GAGG;AACH,MAAM,UAAU,OAAO,CAAE,OAAoB,EAAE;IAC7C,OAAO,CAAC,UAAU,EAAE,EAAE,CAAC,IAAI,kBAAkB,CAAC,UAAU,EAAE,IAAI,CAAC,CAAA;AACjE,CAAC"}
@@ -0,0 +1,4 @@
1
+ export { bitswap } from './bitswap.js';
2
+ export { trustlessGateway } from './trustless-gateway/index.js';
3
+ export { NetworkedStorage } from './utils/networked-storage.js';
4
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,cAAc,CAAA;AACtC,OAAO,EAAE,gBAAgB,EAAE,MAAM,8BAA8B,CAAA;AAC/D,OAAO,EAAE,gBAAgB,EAAE,MAAM,8BAA8B,CAAA"}
@@ -0,0 +1,4 @@
1
+ export { bitswap } from './bitswap.js';
2
+ export { trustlessGateway } from './trustless-gateway/index.js';
3
+ export { NetworkedStorage } from './utils/networked-storage.js';
4
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,cAAc,CAAA;AACtC,OAAO,EAAE,gBAAgB,EAAE,MAAM,8BAA8B,CAAA;AAC/D,OAAO,EAAE,gBAAgB,EAAE,MAAM,8BAA8B,CAAA"}
@@ -0,0 +1,15 @@
1
+ import type { TrustlessGatewayBlockBrokerInit, TrustlessGatewayComponents, TrustlessGatewayGetBlockProgressEvents } from './index.js';
2
+ import type { BlockRetrievalOptions, BlockRetriever } from '@helia/interface/blocks';
3
+ import type { CID } from 'multiformats/cid';
4
+ import type { ProgressOptions } from 'progress-events';
5
+ /**
6
+ * A class that accepts a list of trustless gateways that are queried
7
+ * for blocks.
8
+ */
9
+ export declare class TrustlessGatewayBlockBroker implements BlockRetriever<ProgressOptions<TrustlessGatewayGetBlockProgressEvents>> {
10
+ private readonly gateways;
11
+ private readonly log;
12
+ constructor(components: TrustlessGatewayComponents, init?: TrustlessGatewayBlockBrokerInit);
13
+ retrieve(cid: CID, options?: BlockRetrievalOptions<ProgressOptions<TrustlessGatewayGetBlockProgressEvents>>): Promise<Uint8Array>;
14
+ }
15
+ //# sourceMappingURL=broker.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"broker.d.ts","sourceRoot":"","sources":["../../../src/trustless-gateway/broker.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,+BAA+B,EAAE,0BAA0B,EAAE,sCAAsC,EAAE,MAAM,YAAY,CAAA;AACrI,OAAO,KAAK,EAAE,qBAAqB,EAAE,cAAc,EAAE,MAAM,yBAAyB,CAAA;AAEpF,OAAO,KAAK,EAAE,GAAG,EAAE,MAAM,kBAAkB,CAAA;AAC3C,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,iBAAiB,CAAA;AAEtD;;;GAGG;AACH,qBAAa,2BAA4B,YAAW,cAAc,CAClE,eAAe,CAAC,sCAAsC,CAAC,CACtD;IACC,OAAO,CAAC,QAAQ,CAAC,QAAQ,CAAoB;IAC7C,OAAO,CAAC,QAAQ,CAAC,GAAG,CAAQ;gBAEf,UAAU,EAAE,0BAA0B,EAAE,IAAI,GAAE,+BAAoC;IAQzF,QAAQ,CAAE,GAAG,EAAE,GAAG,EAAE,OAAO,GAAE,qBAAqB,CAAC,eAAe,CAAC,sCAAsC,CAAC,CAAM,GAAG,OAAO,CAAC,UAAU,CAAC;CAsC7I"}
@@ -0,0 +1,55 @@
1
+ import { TrustlessGateway } from './trustless-gateway.js';
2
+ import { DEFAULT_TRUSTLESS_GATEWAYS } from './index.js';
3
+ /**
4
+ * A class that accepts a list of trustless gateways that are queried
5
+ * for blocks.
6
+ */
7
+ export class TrustlessGatewayBlockBroker {
8
+ gateways;
9
+ log;
10
+ constructor(components, init = {}) {
11
+ this.log = components.logger.forComponent('helia:trustless-gateway-block-broker');
12
+ this.gateways = (init.gateways ?? DEFAULT_TRUSTLESS_GATEWAYS)
13
+ .map((gatewayOrUrl) => {
14
+ return new TrustlessGateway(gatewayOrUrl);
15
+ });
16
+ }
17
+ async retrieve(cid, options = {}) {
18
+ // Loop through the gateways until we get a block or run out of gateways
19
+ // TODO: switch to toSorted when support is better
20
+ const sortedGateways = this.gateways.sort((a, b) => b.reliability() - a.reliability());
21
+ const aggregateErrors = [];
22
+ for (const gateway of sortedGateways) {
23
+ this.log('getting block for %c from %s', cid, gateway.url);
24
+ try {
25
+ const block = await gateway.getRawBlock(cid, options.signal);
26
+ this.log.trace('got block for %c from %s', cid, gateway.url);
27
+ try {
28
+ await options.validateFn?.(block);
29
+ }
30
+ catch (err) {
31
+ this.log.error('failed to validate block for %c from %s', cid, gateway.url, err);
32
+ gateway.incrementInvalidBlocks();
33
+ throw new Error(`unable to validate block for CID ${cid} from gateway ${gateway.url}`);
34
+ }
35
+ return block;
36
+ }
37
+ catch (err) {
38
+ this.log.error('failed to get block for %c from %s', cid, gateway.url, err);
39
+ if (err instanceof Error) {
40
+ aggregateErrors.push(err);
41
+ }
42
+ else {
43
+ aggregateErrors.push(new Error(`unable to fetch raw block for CID ${cid} from gateway ${gateway.url}`));
44
+ }
45
+ // if signal was aborted, exit the loop
46
+ if (options.signal?.aborted === true) {
47
+ this.log.trace('request aborted while fetching raw block for CID %c from gateway %s', cid, gateway.url);
48
+ break;
49
+ }
50
+ }
51
+ }
52
+ throw new AggregateError(aggregateErrors, `unable to fetch raw block for CID ${cid} from any gateway`);
53
+ }
54
+ }
55
+ //# sourceMappingURL=broker.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"broker.js","sourceRoot":"","sources":["../../../src/trustless-gateway/broker.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,gBAAgB,EAAE,MAAM,wBAAwB,CAAA;AACzD,OAAO,EAAE,0BAA0B,EAAE,MAAM,YAAY,CAAA;AAOvD;;;GAGG;AACH,MAAM,OAAO,2BAA2B;IAGrB,QAAQ,CAAoB;IAC5B,GAAG,CAAQ;IAE5B,YAAa,UAAsC,EAAE,OAAwC,EAAE;QAC7F,IAAI,CAAC,GAAG,GAAG,UAAU,CAAC,MAAM,CAAC,YAAY,CAAC,sCAAsC,CAAC,CAAA;QACjF,IAAI,CAAC,QAAQ,GAAG,CAAC,IAAI,CAAC,QAAQ,IAAI,0BAA0B,CAAC;aAC1D,GAAG,CAAC,CAAC,YAAY,EAAE,EAAE;YACpB,OAAO,IAAI,gBAAgB,CAAC,YAAY,CAAC,CAAA;QAC3C,CAAC,CAAC,CAAA;IACN,CAAC;IAED,KAAK,CAAC,QAAQ,CAAE,GAAQ,EAAE,UAA0F,EAAE;QACpH,wEAAwE;QACxE,kDAAkD;QAClD,MAAM,cAAc,GAAG,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,WAAW,EAAE,GAAG,CAAC,CAAC,WAAW,EAAE,CAAC,CAAA;QACtF,MAAM,eAAe,GAAY,EAAE,CAAA;QAEnC,KAAK,MAAM,OAAO,IAAI,cAAc,EAAE,CAAC;YACrC,IAAI,CAAC,GAAG,CAAC,8BAA8B,EAAE,GAAG,EAAE,OAAO,CAAC,GAAG,CAAC,CAAA;YAC1D,IAAI,CAAC;gBACH,MAAM,KAAK,GAAG,MAAM,OAAO,CAAC,WAAW,CAAC,GAAG,EAAE,OAAO,CAAC,MAAM,CAAC,CAAA;gBAC5D,IAAI,CAAC,GAAG,CAAC,KAAK,CAAC,0BAA0B,EAAE,GAAG,EAAE,OAAO,CAAC,GAAG,CAAC,CAAA;gBAC5D,IAAI,CAAC;oBACH,MAAM,OAAO,CAAC,UAAU,EAAE,CAAC,KAAK,CAAC,CAAA;gBACnC,CAAC;gBAAC,OAAO,GAAG,EAAE,CAAC;oBACb,IAAI,CAAC,GAAG,CAAC,KAAK,CAAC,yCAAyC,EAAE,GAAG,EAAE,OAAO,CAAC,GAAG,EAAE,GAAG,CAAC,CAAA;oBAChF,OAAO,CAAC,sBAAsB,EAAE,CAAA;oBAEhC,MAAM,IAAI,KAAK,CAAC,oCAAoC,GAAG,iBAAiB,OAAO,CAAC,GAAG,EAAE,CAAC,CAAA;gBACxF,CAAC;gBAED,OAAO,KAAK,CAAA;YACd,CAAC;YAAC,OAAO,GAAY,EAAE,CAAC;gBACtB,IAAI,CAAC,GAAG,CAAC,KAAK,CAAC,oCAAoC,EAAE,GAAG,EAAE,OAAO,CAAC,GAAG,EAAE,GAAG,CAAC,CAAA;gBAC3E,IAAI,GAAG,YAAY,KAAK,EAAE,CAAC;oBACzB,eAAe,CAAC,IAAI,CAAC,GAAG,CAAC,CAAA;gBAC3B,CAAC;qBAAM,CAAC;oBACN,eAAe,CAAC,IAAI,CAAC,IAAI,KAAK,CAAC,qCAAqC,GAAG,iBAAiB,OAAO,CAAC,GAAG,EAAE,CAAC,CAAC,CAAA;gBACzG,CAAC;gBACD,uCAAuC;gBACvC,IAAI,OAAO,CAAC,MAAM,EAAE,OAAO,KAAK,IAAI,EAAE,CAAC;oBACrC,IAAI,CAAC,GAAG,CAAC,KAAK,CAAC,qEAAqE,EAAE,GAAG,EAAE,OAAO,CAAC,GAAG,CAAC,CAAA;oBACvG,MAAK;gBACP,CAAC;YACH,CAAC;QACH,CAAC;QAED,MAAM,IAAI,cAAc,CAAC,eAAe,EAAE,qCAAqC,GAAG,mBAAmB,CAAC,CAAA;IACxG,CAAC;CACF"}
@@ -0,0 +1,13 @@
1
+ import type { BlockRetriever } from '@helia/interface/src/blocks.js';
2
+ import type { ComponentLogger } from '@libp2p/interface';
3
+ import type { ProgressEvent } from 'progress-events';
4
+ export declare const DEFAULT_TRUSTLESS_GATEWAYS: string[];
5
+ export type TrustlessGatewayGetBlockProgressEvents = ProgressEvent<'trustless-gateway:get-block:fetch', URL>;
6
+ export interface TrustlessGatewayBlockBrokerInit {
7
+ gateways?: Array<string | URL>;
8
+ }
9
+ export interface TrustlessGatewayComponents {
10
+ logger: ComponentLogger;
11
+ }
12
+ export declare function trustlessGateway(init?: TrustlessGatewayBlockBrokerInit): (components: TrustlessGatewayComponents) => BlockRetriever;
13
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/trustless-gateway/index.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,gCAAgC,CAAA;AACpE,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,mBAAmB,CAAA;AACxD,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAA;AAEpD,eAAO,MAAM,0BAA0B,UAYtC,CAAA;AAED,MAAM,MAAM,sCAAsC,GAChD,aAAa,CAAC,mCAAmC,EAAE,GAAG,CAAC,CAAA;AAEzD,MAAM,WAAW,+BAA+B;IAC9C,QAAQ,CAAC,EAAE,KAAK,CAAC,MAAM,GAAG,GAAG,CAAC,CAAA;CAC/B;AAED,MAAM,WAAW,0BAA0B;IACzC,MAAM,EAAE,eAAe,CAAA;CACxB;AAED,wBAAgB,gBAAgB,CAAE,IAAI,GAAE,+BAAoC,GAAG,CAAC,UAAU,EAAE,0BAA0B,KAAK,cAAc,CAExI"}
@@ -0,0 +1,15 @@
1
+ import { TrustlessGatewayBlockBroker } from './broker.js';
2
+ export const DEFAULT_TRUSTLESS_GATEWAYS = [
3
+ // 2023-10-03: IPNS, Origin, and Block/CAR support from https://ipfs-public-gateway-checker.on.fleek.co/
4
+ 'https://dweb.link',
5
+ // 2023-10-03: IPNS, Origin, and Block/CAR support from https://ipfs-public-gateway-checker.on.fleek.co/
6
+ 'https://cf-ipfs.com',
7
+ // 2023-10-03: IPNS, Origin, and Block/CAR support from https://ipfs-public-gateway-checker.on.fleek.co/
8
+ 'https://4everland.io',
9
+ // 2023-10-03: IPNS, Origin, and Block/CAR support from https://ipfs-public-gateway-checker.on.fleek.co/
10
+ 'https://w3s.link'
11
+ ];
12
+ export function trustlessGateway(init = {}) {
13
+ return (components) => new TrustlessGatewayBlockBroker(components, init);
14
+ }
15
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/trustless-gateway/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,2BAA2B,EAAE,MAAM,aAAa,CAAA;AAKzD,MAAM,CAAC,MAAM,0BAA0B,GAAG;IACxC,wGAAwG;IACxG,mBAAmB;IAEnB,wGAAwG;IACxG,qBAAqB;IAErB,wGAAwG;IACxG,sBAAsB;IAEtB,wGAAwG;IACxG,kBAAkB;CACnB,CAAA;AAaD,MAAM,UAAU,gBAAgB,CAAE,OAAwC,EAAE;IAC1E,OAAO,CAAC,UAAU,EAAE,EAAE,CAAC,IAAI,2BAA2B,CAAC,UAAU,EAAE,IAAI,CAAC,CAAA;AAC1E,CAAC"}