@helia/bitswap 0.0.0-329652a

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