@libp2p/tcp
Version:
A TCP transport for libp2p
2 lines • 52 kB
JavaScript
(function (root, factory) {(typeof module === 'object' && module.exports) ? module.exports = factory() : root.Libp2PTcp = factory()}(typeof self !== 'undefined' ? self : this, function () {
"use strict";var Libp2PTcp=(()=>{var Jr=Object.create;var ye=Object.defineProperty;var Xr=Object.getOwnPropertyDescriptor;var Kr=Object.getOwnPropertyNames;var Yr=Object.getPrototypeOf,Zr=Object.prototype.hasOwnProperty;var F=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,r)=>(typeof require<"u"?require:e)[r]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var k=(t,e)=>{for(var r in e)ye(t,r,{get:e[r],enumerable:!0})},jt=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Kr(e))!Zr.call(t,o)&&o!==r&&ye(t,o,{get:()=>e[o],enumerable:!(n=Xr(e,o))||n.enumerable});return t};var Z=(t,e,r)=>(r=t!=null?Jr(Yr(t)):{},jt(e||!t||!t.__esModule?ye(r,"default",{value:t,enumerable:!0}):r,t)),en=t=>jt(ye({},"__esModule",{value:!0}),t);var Zo={};k(Zo,{tcp:()=>Yo});var Qr=Z(F("net"),1);var qt=Symbol.for("@libp2p/transport");var Wt;(function(t){t[t.FATAL_ALL=0]="FATAL_ALL",t[t.NO_FATAL=1]="NO_FATAL"})(Wt||(Wt={}));var ve=class extends Error{static name="AbortError";constructor(e="The operation was aborted"){super(e),this.name="AbortError"}};var B=class extends Error{static name="InvalidParametersError";constructor(e="Invalid parameters"){super(e),this.name="InvalidParametersError"}};var ee=class extends Error{static name="TimeoutError";constructor(e="Timed out"){super(e),this.name="TimeoutError"}},Ee=class extends Error{static name="NotStartedError";constructor(e="Not started"){super(e),this.name="NotStartedError"}},Ie=class extends Error{static name="AlreadyStartedError";constructor(e="Already started"){super(e),this.name="AlreadyStartedError"}};var Gt=F("node:events"),Ae=(t,...e)=>{try{(0,Gt.setMaxListeners)(t,...e)}catch{}};var Te=class extends EventTarget{#e=new Map;constructor(){super(),Ae(1/0,this)}listenerCount(e){let r=this.#e.get(e);return r==null?0:r.length}addEventListener(e,r,n){super.addEventListener(e,r,n);let o=this.#e.get(e);o==null&&(o=[],this.#e.set(e,o)),o.push({callback:r,once:(n!==!0&&n!==!1&&n?.once)??!1})}removeEventListener(e,r,n){super.removeEventListener(e.toString(),r??null,n);let o=this.#e.get(e);o!=null&&(o=o.filter(({callback:s})=>s!==r),this.#e.set(e,o))}dispatchEvent(e){let r=super.dispatchEvent(e),n=this.#e.get(e.type);return n==null||(n=n.filter(({once:o})=>!o),this.#e.set(e.type,n)),r}safeDispatchEvent(e,r={}){return this.dispatchEvent(new CustomEvent(e,r))}};var Ht=Symbol.for("@libp2p/service-capabilities"),is=Symbol.for("@libp2p/service-dependencies");var S=F("node:net");function Ce(t){return!!(0,S.isIP)(t)}var Je={};k(Je,{base58btc:()=>P,base58flickr:()=>cn});var Ds=new Uint8Array(0);function Qt(t,e){if(t===e)return!0;if(t.byteLength!==e.byteLength)return!1;for(let r=0;r<t.byteLength;r++)if(t[r]!==e[r])return!1;return!0}function O(t){if(t instanceof Uint8Array&&t.constructor.name==="Uint8Array")return t;if(t instanceof ArrayBuffer)return new Uint8Array(t);if(ArrayBuffer.isView(t))return new Uint8Array(t.buffer,t.byteOffset,t.byteLength);throw new Error("Unknown type, must be binary type")}function Jt(t){return new TextEncoder().encode(t)}function Xt(t){return new TextDecoder().decode(t)}function tn(t,e){if(t.length>=255)throw new TypeError("Alphabet too long");for(var r=new Uint8Array(256),n=0;n<r.length;n++)r[n]=255;for(var o=0;o<t.length;o++){var s=t.charAt(o),i=s.charCodeAt(0);if(r[i]!==255)throw new TypeError(s+" is ambiguous");r[i]=o}var c=t.length,l=t.charAt(0),f=Math.log(c)/Math.log(256),u=Math.log(256)/Math.log(c);function p(d){if(d instanceof Uint8Array||(ArrayBuffer.isView(d)?d=new Uint8Array(d.buffer,d.byteOffset,d.byteLength):Array.isArray(d)&&(d=Uint8Array.from(d))),!(d instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(d.length===0)return"";for(var T=0,N=0,x=0,b=d.length;x!==b&&d[x]===0;)x++,T++;for(var M=(b-x)*u+1>>>0,$=new Uint8Array(M);x!==b;){for(var z=d[x],H=0,V=M-1;(z!==0||H<N)&&V!==-1;V--,H++)z+=256*$[V]>>>0,$[V]=z%c>>>0,z=z/c>>>0;if(z!==0)throw new Error("Non-zero carry");N=H,x++}for(var j=M-N;j!==M&&$[j]===0;)j++;for(var be=l.repeat(T);j<M;++j)be+=t.charAt($[j]);return be}function y(d){if(typeof d!="string")throw new TypeError("Expected String");if(d.length===0)return new Uint8Array;var T=0;if(d[T]!==" "){for(var N=0,x=0;d[T]===l;)N++,T++;for(var b=(d.length-T)*f+1>>>0,M=new Uint8Array(b);d[T];){var $=r[d.charCodeAt(T)];if($===255)return;for(var z=0,H=b-1;($!==0||z<x)&&H!==-1;H--,z++)$+=c*M[H]>>>0,M[H]=$%256>>>0,$=$/256>>>0;if($!==0)throw new Error("Non-zero carry");x=z,T++}if(d[T]!==" "){for(var V=b-x;V!==b&&M[V]===0;)V++;for(var j=new Uint8Array(N+(b-V)),be=N;V!==b;)j[be++]=M[V++];return j}}}function a(d){var T=y(d);if(T)return T;throw new Error(`Non-${e} character`)}return{encode:p,decodeUnsafe:y,decode:a}}var rn=tn,nn=rn,Yt=nn;var qe=class{name;prefix;baseEncode;constructor(e,r,n){this.name=e,this.prefix=r,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},Ge=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,r,n){this.name=e,this.prefix=r;let o=r.codePointAt(0);if(o===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=o,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 Zt(this,e)}},He=class{decoders;constructor(e){this.decoders=e}or(e){return Zt(this,e)}decode(e){let r=e[0],n=this.decoders[r];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 Zt(t,e){return new He({...t.decoders??{[t.prefix]:t},...e.decoders??{[e.prefix]:e}})}var Qe=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,r,n,o){this.name=e,this.prefix=r,this.baseEncode=n,this.baseDecode=o,this.encoder=new qe(e,r,n),this.decoder=new Ge(e,r,o)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function te({name:t,prefix:e,encode:r,decode:n}){return new Qe(t,e,r,n)}function Q({name:t,prefix:e,alphabet:r}){let{encode:n,decode:o}=Yt(r,t);return te({prefix:e,name:t,encode:n,decode:s=>O(o(s))})}function on(t,e,r,n){let o={};for(let u=0;u<e.length;++u)o[e[u]]=u;let s=t.length;for(;t[s-1]==="=";)--s;let i=new Uint8Array(s*r/8|0),c=0,l=0,f=0;for(let u=0;u<s;++u){let p=o[t[u]];if(p===void 0)throw new SyntaxError(`Non-${n} character`);l=l<<r|p,c+=r,c>=8&&(c-=8,i[f++]=255&l>>c)}if(c>=r||(255&l<<8-c)!==0)throw new SyntaxError("Unexpected end of data");return i}function sn(t,e,r){let n=e[e.length-1]==="=",o=(1<<r)-1,s="",i=0,c=0;for(let l=0;l<t.length;++l)for(c=c<<8|t[l],i+=8;i>r;)i-=r,s+=e[o&c>>i];if(i!==0&&(s+=e[o&c<<r-i]),n)for(;(s.length*r&7)!==0;)s+="=";return s}function A({name:t,prefix:e,bitsPerChar:r,alphabet:n}){return te({prefix:e,name:t,encode(o){return sn(o,n,r)},decode(o){return on(o,n,r,t)}})}var P=Q({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),cn=Q({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var Ke={};k(Ke,{base64:()=>an,base64pad:()=>ln,base64url:()=>Xe,base64urlpad:()=>un});var an=A({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),ln=A({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Xe=A({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),un=A({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var dn=t=>t.toString().split("/").slice(1),re=t=>({match:e=>e.length<1?!1:t(e[0])?e.slice(1):!1,pattern:"fn"}),h=t=>({match:e=>re(r=>r===t).match(e),pattern:t}),X=()=>({match:t=>re(e=>typeof e=="string").match(t),pattern:"{string}"}),de=()=>({match:t=>re(e=>!isNaN(parseInt(e))).match(t),pattern:"{number}"}),v=()=>({match:t=>{if(t.length<2||t[0]!=="p2p"&&t[0]!=="ipfs")return!1;if(t[1].startsWith("Q")||t[1].startsWith("1"))try{P.decode(`z${t[1]}`)}catch{return!1}else return!1;return t.slice(2)},pattern:"/p2p/{peerid}"}),pe=()=>({match:t=>{if(t.length<2||t[0]!=="certhash")return!1;try{Xe.decode(t[1])}catch{return!1}return t.slice(2)},pattern:"/certhash/{certhash}"}),g=t=>({match:e=>{let r=t.match(e);return r===!1?e:r},pattern:`optional(${t.pattern})`}),L=(...t)=>({match:e=>{let r;for(let n of t){let o=n.match(e);o!==!1&&(r==null||o.length<r.length)&&(r=o)}return r??!1},pattern:`or(${t.map(e=>e.pattern).join(", ")})`}),m=(...t)=>({match:e=>{for(let r of t){let n=r.match(e);if(n===!1)return!1;e=n}return e},pattern:`and(${t.map(e=>e.pattern).join(", ")})`});function I(...t){function e(o){let s=dn(o);for(let i of t){let c=i.match(s);if(c===!1)return!1;s=c}return s}function r(o){return e(o)!==!1}function n(o){let s=e(o);return s===!1?!1:s.length===0}return{matchers:t,matches:r,exactMatch:n}}var Pe=m(h("dns4"),X()),Le=m(h("dns6"),X()),De=m(h("dnsaddr"),X()),Ze=m(h("dns"),X()),Rs=I(Pe,g(v())),js=I(Le,g(v())),Ws=I(De,g(v())),qs=I(L(Ze,De,Pe,Le),g(v())),er=m(h("ip4"),re(S.isIPv4)),tr=m(h("ip6"),re(S.isIPv6)),et=L(er,tr),W=L(et,Ze,Pe,Le,De),Gs=I(L(et,m(L(Ze,De,Pe,Le),g(v())))),Hs=I(er),Qs=I(tr),Js=I(et),tt=m(W,h("tcp"),de()),fe=m(W,h("udp"),de()),rr=I(m(tt,g(v()))),Xs=I(fe),rt=m(fe,h("quic"),g(v())),Ne=m(fe,h("quic-v1"),g(v())),pn=L(rt,Ne),Ks=I(rt),Ys=I(Ne),Ye=L(W,tt,fe,rt,Ne),nr=L(m(Ye,h("ws"),g(v()))),Zs=I(nr),or=L(m(Ye,h("wss"),g(v())),m(Ye,h("tls"),g(m(h("sni"),X())),h("ws"),g(v()))),ei=I(or),sr=m(fe,h("webrtc-direct"),g(pe()),g(pe()),g(v())),ti=I(sr),ir=m(Ne,h("webtransport"),g(pe()),g(pe()),g(v())),ri=I(ir),Se=L(nr,or,m(tt,g(v())),m(pn,g(v())),m(W,g(v())),sr,ir,v()),ni=I(Se),fn=m(Se,h("p2p-circuit"),v()),oi=I(fn),hn=L(m(Se,h("p2p-circuit"),h("webrtc"),g(v())),m(Se,h("webrtc"),g(v())),m(h("webrtc"),g(v()))),si=I(hn),mn=L(m(W,h("tcp"),de(),h("http"),g(v())),m(W,h("http"),g(v()))),ii=I(mn),xn=L(m(W,h("tcp"),L(m(h("443"),h("http")),m(de(),h("https"))),g(v())),m(W,h("tls"),h("http"),g(v())),m(W,h("https"),g(v()))),ci=I(xn),gn=L(m(h("memory"),X(),g(v()))),ai=I(gn);var Ue=class extends Event{type;detail;constructor(e,r){super(e),this.type=e,this.detail=r}};var Hr=Z(F("net"),1);var Vr=Z(F("node:os"),1);var cr=F("node:buffer");function ne(t){return new Uint8Array(t.buffer,t.byteOffset,t.byteLength)}function Me(t=0){return ne(cr.Buffer.allocUnsafe(t))}var wn=Math.pow(2,7),bn=Math.pow(2,14),yn=Math.pow(2,21),nt=Math.pow(2,28),ot=Math.pow(2,35),st=Math.pow(2,42),it=Math.pow(2,49),w=128,D=127;function R(t){if(t<wn)return 1;if(t<bn)return 2;if(t<yn)return 3;if(t<nt)return 4;if(t<ot)return 5;if(t<st)return 6;if(t<it)return 7;if(Number.MAX_SAFE_INTEGER!=null&&t>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function vn(t,e,r=0){switch(R(t)){case 8:e[r++]=t&255|w,t/=128;case 7:e[r++]=t&255|w,t/=128;case 6:e[r++]=t&255|w,t/=128;case 5:e[r++]=t&255|w,t/=128;case 4:e[r++]=t&255|w,t>>>=7;case 3:e[r++]=t&255|w,t>>>=7;case 2:e[r++]=t&255|w,t>>>=7;case 1:{e[r++]=t&255,t>>>=7;break}default:throw new Error("unreachable")}return e}function En(t,e,r=0){switch(R(t)){case 8:e.set(r++,t&255|w),t/=128;case 7:e.set(r++,t&255|w),t/=128;case 6:e.set(r++,t&255|w),t/=128;case 5:e.set(r++,t&255|w),t/=128;case 4:e.set(r++,t&255|w),t>>>=7;case 3:e.set(r++,t&255|w),t>>>=7;case 2:e.set(r++,t&255|w),t>>>=7;case 1:{e.set(r++,t&255),t>>>=7;break}default:throw new Error("unreachable")}return e}function In(t,e){let r=t[e],n=0;if(n+=r&D,r<w||(r=t[e+1],n+=(r&D)<<7,r<w)||(r=t[e+2],n+=(r&D)<<14,r<w)||(r=t[e+3],n+=(r&D)<<21,r<w)||(r=t[e+4],n+=(r&D)*nt,r<w)||(r=t[e+5],n+=(r&D)*ot,r<w)||(r=t[e+6],n+=(r&D)*st,r<w)||(r=t[e+7],n+=(r&D)*it,r<w))return n;throw new RangeError("Could not decode varint")}function An(t,e){let r=t.get(e),n=0;if(n+=r&D,r<w||(r=t.get(e+1),n+=(r&D)<<7,r<w)||(r=t.get(e+2),n+=(r&D)<<14,r<w)||(r=t.get(e+3),n+=(r&D)<<21,r<w)||(r=t.get(e+4),n+=(r&D)*nt,r<w)||(r=t.get(e+5),n+=(r&D)*ot,r<w)||(r=t.get(e+6),n+=(r&D)*st,r<w)||(r=t.get(e+7),n+=(r&D)*it,r<w))return n;throw new RangeError("Could not decode varint")}function oe(t,e,r=0){return e==null&&(e=Me(R(t))),e instanceof Uint8Array?vn(t,e,r):En(t,e,r)}function K(t,e=0){return t instanceof Uint8Array?In(t,e):An(t,e)}var lr=F("node:buffer");function q(t,e){return ne(lr.Buffer.concat(t,e))}var Ir=F("node:buffer");var ct={};k(ct,{base10:()=>Tn});var Tn=Q({prefix:"9",name:"base10",alphabet:"0123456789"});var at={};k(at,{base16:()=>Cn,base16upper:()=>Sn});var Cn=A({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),Sn=A({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var lt={};k(lt,{base2:()=>Pn});var Pn=A({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var ut={};k(ut,{base256emoji:()=>Mn});var ur=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}"),Ln=ur.reduce((t,e,r)=>(t[r]=e,t),[]),Dn=ur.reduce((t,e,r)=>{let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);return t[n]=r,t},[]);function Nn(t){return t.reduce((e,r)=>(e+=Ln[r],e),"")}function Un(t){let e=[];for(let r of t){let n=r.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${r}`);let o=Dn[n];if(o==null)throw new Error(`Non-base256emoji character: ${r}`);e.push(o)}return new Uint8Array(e)}var Mn=te({prefix:"\u{1F680}",name:"base256emoji",encode:Nn,decode:Un});var dt={};k(dt,{base32:()=>G,base32hex:()=>On,base32hexpad:()=>_n,base32hexpadupper:()=>zn,base32hexupper:()=>Vn,base32pad:()=>$n,base32padupper:()=>Fn,base32upper:()=>kn,base32z:()=>Bn});var G=A({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),kn=A({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),$n=A({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Fn=A({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),On=A({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Vn=A({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),_n=A({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),zn=A({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Bn=A({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var pt={};k(pt,{base36:()=>he,base36upper:()=>Rn});var he=Q({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Rn=Q({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var ft={};k(ft,{base8:()=>jn});var jn=A({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var ht={};k(ht,{identity:()=>Wn});var Wn=te({prefix:"\0",name:"identity",encode:t=>Xt(t),decode:t=>Jt(t)});var Ci=new TextEncoder,Si=new TextDecoder;var xt={};k(xt,{identity:()=>ho});var Hn=fr,dr=128,Qn=127,Jn=~Qn,Xn=Math.pow(2,31);function fr(t,e,r){e=e||[],r=r||0;for(var n=r;t>=Xn;)e[r++]=t&255|dr,t/=128;for(;t&Jn;)e[r++]=t&255|dr,t>>>=7;return e[r]=t|0,fr.bytes=r-n+1,e}var Kn=mt,Yn=128,pr=127;function mt(t,n){var r=0,n=n||0,o=0,s=n,i,c=t.length;do{if(s>=c)throw mt.bytes=0,new RangeError("Could not decode varint");i=t[s++],r+=o<28?(i&pr)<<o:(i&pr)*Math.pow(2,o),o+=7}while(i>=Yn);return mt.bytes=s-n,r}var Zn=Math.pow(2,7),eo=Math.pow(2,14),to=Math.pow(2,21),ro=Math.pow(2,28),no=Math.pow(2,35),oo=Math.pow(2,42),so=Math.pow(2,49),io=Math.pow(2,56),co=Math.pow(2,63),ao=function(t){return t<Zn?1:t<eo?2:t<to?3:t<ro?4:t<no?5:t<oo?6:t<so?7:t<io?8:t<co?9:10},lo={encode:Hn,decode:Kn,encodingLength:ao},uo=lo,me=uo;function xe(t,e=0){return[me.decode(t,e),me.decode.bytes]}function se(t,e,r=0){return me.encode(t,e,r),e}function ie(t){return me.encodingLength(t)}function Y(t,e){let r=e.byteLength,n=ie(t),o=n+ie(r),s=new Uint8Array(o+r);return se(t,s,0),se(r,s,n),s.set(e,o),new ce(t,r,e,s)}function $e(t){let e=O(t),[r,n]=xe(e),[o,s]=xe(e.subarray(n)),i=e.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new ce(r,o,i,e)}function hr(t,e){if(t===e)return!0;{let r=e;return t.code===r.code&&t.size===r.size&&r.bytes instanceof Uint8Array&&Qt(t.bytes,r.bytes)}}var ce=class{code;size;digest;bytes;constructor(e,r,n,o){this.code=e,this.size=r,this.digest=n,this.bytes=o}};var mr=0,po="identity",xr=O;function fo(t){return Y(mr,xr(t))}var ho={code:mr,name:po,encode:xr,digest:fo};var yt={};k(yt,{sha256:()=>mo,sha512:()=>xo});var bt=Z(F("crypto"),1);function wt({name:t,code:e,encode:r}){return new gt(t,e,r)}var gt=class{name;code;encode;constructor(e,r,n){this.name=e,this.code=r,this.encode=n}digest(e){if(e instanceof Uint8Array){let r=this.encode(e);return r instanceof Uint8Array?Y(this.code,r):r.then(n=>Y(this.code,n))}else throw Error("Unknown type, must be binary type")}};var mo=wt({name:"sha2-256",code:18,encode:t=>O(bt.default.createHash("sha256").update(t).digest())}),xo=wt({name:"sha2-512",code:19,encode:t=>O(bt.default.createHash("sha512").update(t).digest())});function wr(t,e){let{bytes:r,version:n}=t;switch(n){case 0:return wo(r,vt(t),e??P.encoder);default:return bo(r,vt(t),e??G.encoder)}}var br=new WeakMap;function vt(t){let e=br.get(t);if(e==null){let r=new Map;return br.set(t,r),r}return e}var J=class t{code;version;multihash;bytes;"/";constructor(e,r,n,o){this.code=r,this.version=e,this.multihash=n,this.bytes=o,this["/"]=o}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:r}=this;if(e!==ge)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(r.code!==yo)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return t.createV0(r)}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:r}=this.multihash,n=Y(e,r);return t.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 t.equals(this,e)}static equals(e,r){let n=r;return n!=null&&e.code===n.code&&e.version===n.version&&hr(e.multihash,n.multihash)}toString(e){return wr(this,e)}toJSON(){return{"/":wr(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 r=e;if(r instanceof t)return r;if(r["/"]!=null&&r["/"]===r.bytes||r.asCID===r){let{version:n,code:o,multihash:s,bytes:i}=r;return new t(n,o,s,i??yr(n,o,s.bytes))}else if(r[vo]===!0){let{version:n,multihash:o,code:s}=r,i=$e(o);return t.create(n,s,i)}else return null}static create(e,r,n){if(typeof r!="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(r!==ge)throw new Error(`Version 0 CID must use dag-pb (code: ${ge}) block encoding`);return new t(e,r,n,n.bytes)}case 1:{let o=yr(e,r,n.bytes);return new t(e,r,n,o)}default:throw new Error("Invalid version")}}static createV0(e){return t.create(0,ge,e)}static createV1(e,r){return t.create(1,e,r)}static decode(e){let[r,n]=t.decodeFirst(e);if(n.length!==0)throw new Error("Incorrect length");return r}static decodeFirst(e){let r=t.inspectBytes(e),n=r.size-r.multihashSize,o=O(e.subarray(n,n+r.multihashSize));if(o.byteLength!==r.multihashSize)throw new Error("Incorrect length");let s=o.subarray(r.multihashSize-r.digestSize),i=new ce(r.multihashCode,r.digestSize,s,o);return[r.version===0?t.createV0(i):t.createV1(r.codec,i),e.subarray(r.size)]}static inspectBytes(e){let r=0,n=()=>{let[p,y]=xe(e.subarray(r));return r+=y,p},o=n(),s=ge;if(o===18?(o=0,r=0):s=n(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);let i=r,c=n(),l=n(),f=r+l,u=f-i;return{version:o,codec:s,multihashCode:c,digestSize:l,multihashSize:u,size:f}}static parse(e,r){let[n,o]=go(e,r),s=t.decode(o);if(s.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return vt(s).set(n,e),s}};function go(t,e){switch(t[0]){case"Q":{let r=e??P;return[P.prefix,r.decode(`${P.prefix}${t}`)]}case P.prefix:{let r=e??P;return[P.prefix,r.decode(t)]}case G.prefix:{let r=e??G;return[G.prefix,r.decode(t)]}case he.prefix:{let r=e??he;return[he.prefix,r.decode(t)]}default:{if(e==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[t[0],e.decode(t)]}}}function wo(t,e,r){let{prefix:n}=r;if(n!==P.prefix)throw Error(`Cannot string encode V0 in ${r.name} encoding`);let o=e.get(n);if(o==null){let s=r.encode(t).slice(1);return e.set(n,s),s}else return o}function bo(t,e,r){let{prefix:n}=r,o=e.get(n);if(o==null){let s=r.encode(t);return e.set(n,s),s}else return o}var ge=112,yo=18;function yr(t,e,r){let n=ie(t),o=n+ie(e),s=new Uint8Array(o+r.byteLength);return se(t,s,0),se(e,s,n),s.set(r,o),s}var vo=Symbol.for("@ipld/js-cid/CID");var we={...ht,...lt,...ft,...ct,...at,...dt,...pt,...Je,...Ke,...ut},Xi={...yt,...xt};function Er(t,e,r,n){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:r},decoder:{decode:n}}}var vr=Er("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),Et=Er("ascii","a",t=>{let e="a";for(let r=0;r<t.length;r++)e+=String.fromCharCode(t[r]);return e},t=>{t=t.substring(1);let e=Me(t.length);for(let r=0;r<t.length;r++)e[r]=t.charCodeAt(r);return e}),Eo={utf8:vr,"utf-8":vr,hex:we.base16,latin1:Et,ascii:Et,binary:Et,...we},Fe=Eo;function U(t,e="utf8"){let r=Fe[e];if(r==null)throw new Error(`Unsupported encoding "${e}"`);return e==="utf8"||e==="utf-8"?Ir.Buffer.from(t.buffer,t.byteOffset,t.byteLength).toString("utf8"):r.encoder.encode(t).substring(1)}var Oe=class{index=0;input="";new(e){return this.index=0,this.input=e,this}readAtomically(e){let r=this.index,n=e();return n===void 0&&(this.index=r),n}parseWith(e){let r=e();if(this.index===this.input.length)return r}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 r=this.readChar();if(r===e)return r})}readSeparator(e,r,n){return this.readAtomically(()=>{if(!(r>0&&this.readGivenChar(e)===void 0))return n()})}readNumber(e,r,n,o){return this.readAtomically(()=>{let s=0,i=0,c=this.peekChar();if(c===void 0)return;let l=c==="0",f=2**(8*o)-1;for(;;){let u=this.readAtomically(()=>{let p=this.readChar();if(p===void 0)return;let y=Number.parseInt(p,e);if(!Number.isNaN(y))return y});if(u===void 0)break;if(s*=e,s+=u,s>f||(i+=1,r!==void 0&&i>r))return}if(i!==0)return!n&&l&&i>1?void 0:s})}readIPv4Addr(){return this.readAtomically(()=>{let e=new Uint8Array(4);for(let r=0;r<e.length;r++){let n=this.readSeparator(".",r,()=>this.readNumber(10,3,!1,1));if(n===void 0)return;e[r]=n}return e})}readIPv6Addr(){let e=r=>{for(let n=0;n<r.length/2;n++){let o=n*2;if(n<r.length-3){let i=this.readSeparator(":",n,()=>this.readIPv4Addr());if(i!==void 0)return r[o]=i[0],r[o+1]=i[1],r[o+2]=i[2],r[o+3]=i[3],[o+4,!0]}let s=this.readSeparator(":",n,()=>this.readNumber(16,4,!0,2));if(s===void 0)return[o,!1];r[o]=s>>8,r[o+1]=s&255}return[r.length,!1]};return this.readAtomically(()=>{let r=new Uint8Array(16),[n,o]=e(r);if(n===16)return r;if(o||this.readGivenChar(":")===void 0||this.readGivenChar(":")===void 0)return;let s=new Uint8Array(14),i=16-(n+2),[c]=e(s.subarray(0,i));return r.set(s.subarray(0,c),16-c),r})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};var sc=new Oe;var fc=parseInt("0xFFFF",16),hc=new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);var Cr=F("node:buffer");function Ve(t,e="utf8"){let r=Fe[e];if(r==null)throw new Error(`Unsupported encoding "${e}"`);return e==="utf8"||e==="utf-8"?ne(Cr.Buffer.from(t,"utf-8")):r.decoder.decode(`${r.prefix}${t}`)}var Sr=S.isIPv4,Po=S.isIPv6,It=function(t){let e=0;if(t=t.toString().trim(),Sr(t)){let r=new Uint8Array(e+4);return t.split(/\./g).forEach(n=>{r[e++]=parseInt(n,10)&255}),r}if(Po(t)){let r=t.split(":",8),n;for(n=0;n<r.length;n++){let s=Sr(r[n]),i;s&&(i=It(r[n]),r[n]=U(i.slice(0,2),"base16")),i!=null&&++n<8&&r.splice(n,0,U(i.slice(2,4),"base16"))}if(r[0]==="")for(;r.length<8;)r.unshift("0");else if(r[r.length-1]==="")for(;r.length<8;)r.push("0");else if(r.length<8){for(n=0;n<r.length&&r[n]!=="";n++);let s=[n,1];for(n=9-r.length;n>0;n--)s.push("0");r.splice.apply(r,s)}let o=new Uint8Array(e+16);for(n=0;n<r.length;n++){let s=parseInt(r[n],16);o[e++]=s>>8&255,o[e++]=s&255}return o}throw new Error("invalid ip address")},Pr=function(t,e=0,r){e=~~e,r=r??t.length-e;let n=new DataView(t.buffer);if(r===4){let o=[];for(let s=0;s<r;s++)o.push(t[e+s]);return o.join(".")}if(r===16){let o=[];for(let s=0;s<r;s+=2)o.push(n.getUint16(e+s).toString(16));return o.join(":").replace(/(^|:)0(:0)*:0(:|$)/,"$1::$3").replace(/:{3,4}/,"::")}return""};var le={},At={},Do=[[4,32,"ip4"],[6,16,"tcp"],[33,16,"dccp"],[41,128,"ip6"],[42,-1,"ip6zone"],[43,8,"ipcidr"],[53,-1,"dns",!0],[54,-1,"dns4",!0],[55,-1,"dns6",!0],[56,-1,"dnsaddr",!0],[132,16,"sctp"],[273,16,"udp"],[275,0,"p2p-webrtc-star"],[276,0,"p2p-webrtc-direct"],[277,0,"p2p-stardust"],[280,0,"webrtc-direct"],[281,0,"webrtc"],[290,0,"p2p-circuit"],[301,0,"udt"],[302,0,"utp"],[400,-1,"unix",!1,!0],[421,-1,"ipfs"],[421,-1,"p2p"],[443,0,"https"],[444,96,"onion"],[445,296,"onion3"],[446,-1,"garlic64"],[448,0,"tls"],[449,-1,"sni"],[460,0,"quic"],[461,0,"quic-v1"],[465,0,"webtransport"],[466,-1,"certhash"],[477,0,"ws"],[478,0,"wss"],[479,0,"p2p-websocket-star"],[480,0,"http"],[481,-1,"http-path"],[777,-1,"memory"]];Do.forEach(t=>{let e=No(...t);At[e.code]=e,le[e.name]=e});function No(t,e,r,n,o){return{code:t,size:e,name:r,resolvable:!!n,path:!!o}}function E(t){if(typeof t=="number"){if(At[t]!=null)return At[t];throw new Error(`no protocol with code: ${t}`)}else if(typeof t=="string"){if(le[t]!=null)return le[t];throw new Error(`no protocol with name: ${t}`)}throw new Error(`invalid protocol id type: ${typeof t}`)}var ea=E("ip4"),ta=E("ip6"),ra=E("ipcidr");function Pt(t,e){switch(E(t).code){case 4:case 41:return Mo(e);case 42:return St(e);case 43:return U(e,"base10");case 6:case 273:case 33:case 132:return Nr(e).toString();case 53:case 54:case 55:case 56:case 400:case 449:case 777:return St(e);case 421:return Oo(e);case 444:return Dr(e);case 445:return Dr(e);case 466:return Fo(e);case 481:return globalThis.encodeURIComponent(St(e));default:return U(e,"base16")}}function Lt(t,e){switch(E(t).code){case 4:return Lr(e);case 41:return Lr(e);case 42:return Ct(e);case 43:return Ve(e,"base10");case 6:case 273:case 33:case 132:return Dt(parseInt(e,10));case 53:case 54:case 55:case 56:case 400:case 449:case 777:return Ct(e);case 421:return ko(e);case 444:return Vo(e);case 445:return _o(e);case 466:return $o(e);case 481:return Ct(globalThis.decodeURIComponent(e));default:return Ve(e,"base16")}}var Tt=Object.values(we).map(t=>t.decoder),Uo=function(){let t=Tt[0].or(Tt[1]);return Tt.slice(2).forEach(e=>t=t.or(e)),t}();function Lr(t){if(!Ce(t))throw new Error("invalid ip address");return It(t)}function Mo(t){let e=Pr(t,0,t.length);if(e==null)throw new Error("ipBuff is required");if(!Ce(e))throw new Error("invalid ip address");return e}function Dt(t){let e=new ArrayBuffer(2);return new DataView(e).setUint16(0,t),new Uint8Array(e)}function Nr(t){return new DataView(t.buffer).getUint16(t.byteOffset)}function Ct(t){let e=Ve(t),r=Uint8Array.from(oe(e.length));return q([r,e],r.length+e.length)}function St(t){let e=K(t);if(t=t.slice(R(e)),t.length!==e)throw new Error("inconsistent lengths");return U(t)}function ko(t){let e;t[0]==="Q"||t[0]==="1"?e=$e(P.decode(`z${t}`)).bytes:e=J.parse(t).multihash.bytes;let r=Uint8Array.from(oe(e.length));return q([r,e],r.length+e.length)}function $o(t){let e=Uo.decode(t),r=Uint8Array.from(oe(e.length));return q([r,e],r.length+e.length)}function Fo(t){let e=K(t),r=t.slice(R(e));if(r.length!==e)throw new Error("inconsistent lengths");return"u"+U(r,"base64url")}function Oo(t){let e=K(t),r=t.slice(R(e));if(r.length!==e)throw new Error("inconsistent lengths");return U(r,"base58btc")}function Vo(t){let e=t.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 r=G.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 o=Dt(n);return q([r,o],r.length+o.length)}function _o(t){let e=t.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 r=G.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 o=Dt(n);return q([r,o],r.length+o.length)}function Dr(t){let e=t.slice(0,t.length-2),r=t.slice(t.length-2),n=U(e,"base32"),o=Nr(r);return`${n}:${o}`}function Ur(t){t=Nt(t);let e=[],r=[],n=null,o=t.split("/").slice(1);if(o.length===1&&o[0]==="")return{bytes:new Uint8Array,string:"/",tuples:[],stringTuples:[],path:null};for(let s=0;s<o.length;s++){let i=o[s],c=E(i);if(c.size===0){e.push([c.code]),r.push([c.code]);continue}if(s++,s>=o.length)throw new _e("invalid address: "+t);if(c.path===!0){n=Nt(o.slice(s).join("/")),e.push([c.code,Lt(c.code,n)]),r.push([c.code,n]);break}let l=Lt(c.code,o[s]);e.push([c.code,l]),r.push([c.code,Pt(c.code,l)])}return{string:Mr(r),bytes:ze(e),tuples:e,stringTuples:r,path:n}}function Ut(t){let e=[],r=[],n=null,o=0;for(;o<t.length;){let s=K(t,o),i=R(s),c=E(s),l=zo(c,t.slice(o+i));if(l===0){e.push([s]),r.push([s]),o+=i;continue}let f=t.slice(o+i,o+i+l);if(o+=l+i,o>t.length)throw new _e("Invalid address Uint8Array: "+U(t,"base16"));e.push([s,f]);let u=Pt(s,f);if(r.push([s,u]),c.path===!0){n=u;break}}return{bytes:Uint8Array.from(t),string:Mr(r),tuples:e,stringTuples:r,path:n}}function Mr(t){let e=[];return t.map(r=>{let n=E(r[0]);return e.push(n.name),r.length>1&&r[1]!=null&&e.push(r[1]),null}),Nt(e.join("/"))}function ze(t){return q(t.map(e=>{let r=E(e[0]),n=Uint8Array.from(oe(r.code));return e.length>1&&e[1]!=null&&(n=q([n,e[1]])),n}))}function zo(t,e){if(t.size>0)return t.size/8;if(t.size===0)return 0;{let r=K(e instanceof Uint8Array?e:Uint8Array.from(e));return r+R(r)}}function Nt(t){return"/"+t.trim().split("/").filter(e=>e).join("/")}var _e=class extends Error{static name="ParseError";name="ParseError";constructor(e){super(`Error parsing address: ${e}`)}};function kr(t,e){if(t===e)return!0;if(t.byteLength!==e.byteLength)return!1;for(let r=0;r<t.byteLength;r++)if(t[r]!==e[r])return!1;return!0}var Bo=Symbol.for("nodejs.util.inspect.custom"),kt=Symbol.for("@multiformats/js-multiaddr/multiaddr"),Ro=[E("dns").code,E("dns4").code,E("dns6").code,E("dnsaddr").code],Mt=class extends Error{constructor(e="No available resolver"){super(e),this.name="NoAvailableResolverError"}},Be=class t{bytes;#e;#t;#r;#n;[kt]=!0;constructor(e){e==null&&(e="");let r;if(e instanceof Uint8Array)r=Ut(e);else if(typeof e=="string"){if(e.length>0&&e.charAt(0)!=="/")throw new Error(`multiaddr "${e}" must start with a "/"`);r=Ur(e)}else if(Fr(e))r=Ut(e.bytes);else throw new Error("addr must be a string, Buffer, or another Multiaddr");this.bytes=r.bytes,this.#e=r.string,this.#t=r.tuples,this.#r=r.stringTuples,this.#n=r.path}toString(){return this.#e}toJSON(){return this.toString()}toOptions(){let e,r,n,o,s="",i=E("tcp"),c=E("udp"),l=E("ip4"),f=E("ip6"),u=E("dns6"),p=E("ip6zone");for(let[a,d]of this.stringTuples())a===p.code&&(s=`%${d??""}`),Ro.includes(a)&&(r=i.name==="tcp"?"tcp":"udp",o=443,n=`${d??""}${s}`,e=a===u.code?6:4),(a===i.code||a===c.code)&&(r=E(a).name==="tcp"?"tcp":"udp",o=parseInt(d??"")),(a===l.code||a===f.code)&&(r=E(a).name==="tcp"?"tcp":"udp",n=`${d??""}${s}`,e=a===f.code?6:4);if(e==null||r==null||n==null||o==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:r,port:o}}protos(){return this.#t.map(([e])=>Object.assign({},E(e)))}protoCodes(){return this.#t.map(([e])=>e)}protoNames(){return this.#t.map(([e])=>E(e).name)}tuples(){return this.#t.map(([e,r])=>r==null?[e]:[e,r])}stringTuples(){return this.#r.map(([e,r])=>r==null?[e]:[e,r])}encapsulate(e){return e=new t(e),new t(this.toString()+e.toString())}decapsulate(e){let r=e.toString(),n=this.toString(),o=n.lastIndexOf(r);if(o<0)throw new Error(`Address ${this.toString()} does not contain subaddress: ${e.toString()}`);return new t(n.slice(0,o))}decapsulateCode(e){let r=this.tuples();for(let n=r.length-1;n>=0;n--)if(r[n][0]===e)return new t(ze(r.slice(0,n)));return this}getPeerId(){try{let e=[];this.stringTuples().forEach(([n,o])=>{n===le.p2p.code&&e.push([n,o]),n===le["p2p-circuit"].code&&(e=[])});let r=e.pop();if(r?.[1]!=null){let n=r[1];return n[0]==="Q"||n[0]==="1"?U(P.decode(`z${n}`),"base58btc"):U(J.parse(n).multihash.bytes,"base58btc")}return null}catch{return null}}getPath(){return this.#n}equals(e){return kr(this.bytes,e.bytes)}async resolve(e){let r=this.protos().find(s=>s.resolvable);if(r==null)return[this];let n=$r.get(r.name);if(n==null)throw new Mt(`no available resolver for ${r.name}`);return(await n(this,e)).map(s=>_(s))}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 r=(e??this).protos();return!(r.length!==2||r[0].code!==4&&r[0].code!==41||r[1].code!==6&&r[1].code!==273)}[Bo](){return`Multiaddr(${this.#e})`}};var $r=new Map;function Fr(t){return!!t?.[kt]}function _(t){return new Be(t)}function Or(t){return!!(t.startsWith("169.254.")||t.toLowerCase().startsWith("fe80"))}var jo={4:"IPv4",6:"IPv6"};function Wo(t){return["0.0.0.0","::"].includes(t)}function qo(t){let e=[],r=Vr.default.networkInterfaces();for(let[,n]of Object.entries(r))if(n!=null)for(let o of n)Or(o.address)||o.family===jo[t]&&e.push(o.address);return e}function _r(t,e){if(t==null)return[];let r=t.toOptions();if(Wo(r.host)){let n=[];for(let o of qo(r.family))n.push(_(`/ip${r.family}/${o}/${r.transport}/${e??r.port}`));return n}return[_(`/ip${r.family}/${r.host}/${r.transport}/${e??r.port}`)]}var $t=class extends Error{constructor(e){super(e),this.name="TimeoutError"}},Ft=class extends Error{constructor(e){super(),this.name="AbortError",this.message=e}},zr=t=>globalThis.DOMException===void 0?new Ft(t):new DOMException(t),Br=t=>{let e=t.reason===void 0?zr("This operation was aborted."):t.reason;return e instanceof Error?e:zr(e)};function Ot(t,e){let{milliseconds:r,fallback:n,message:o,customTimers:s={setTimeout,clearTimeout}}=e,i,c,f=new Promise((u,p)=>{if(typeof r!="number"||Math.sign(r)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${r}\``);if(e.signal){let{signal:a}=e;a.aborted&&p(Br(a)),c=()=>{p(Br(a))},a.addEventListener("abort",c,{once:!0})}if(r===Number.POSITIVE_INFINITY){t.then(u,p);return}let y=new $t;i=s.setTimeout.call(void 0,()=>{if(n){try{u(n())}catch(a){p(a)}return}typeof t.cancel=="function"&&t.cancel(),o===!1?u():o instanceof Error?p(o):(y.message=o??`Promise timed out after ${r} milliseconds`,p(y))},r),(async()=>{try{u(await t)}catch(a){p(a)}})()}).finally(()=>{f.clear(),c&&e.signal&&e.signal.removeEventListener("abort",c)});return f.clear=()=>{s.clearTimeout.call(void 0,i),i=void 0},f}var Go=t=>{let e=t.addEventListener||t.on||t.addListener,r=t.removeEventListener||t.off||t.removeListener;if(!e||!r)throw new TypeError("Emitter is not compatible");return{addListener:e.bind(t),removeListener:r.bind(t)}};function Ho(t,e,r){let n,o=new Promise((s,i)=>{if(r={rejectionEvents:["error"],multiArgs:!1,resolveImmediately:!1,...r},!(r.count>=0&&(r.count===Number.POSITIVE_INFINITY||Number.isInteger(r.count))))throw new TypeError("The `count` option should be at least 0 or more");r.signal?.throwIfAborted();let c=[e].flat(),l=[],{addListener:f,removeListener:u}=Go(t),p=(...a)=>{let d=r.multiArgs?a:a[0];r.filter&&!r.filter(d)||(l.push(d),r.count===l.length&&(n(),s(l)))},y=a=>{n(),i(a)};n=()=>{for(let a of c)u(a,p);for(let a of r.rejectionEvents)u(a,y)};for(let a of c)f(a,p);for(let a of r.rejectionEvents)f(a,y);r.signal&&r.signal.addEventListener("abort",()=>{y(r.signal.reason)},{once:!0}),r.resolveImmediately&&s(l)});if(o.cancel=n,typeof r.timeout=="number"){let s=Ot(o,{milliseconds:r.timeout});return s.cancel=n,s}return o}function Vt(t,e,r){typeof r=="function"&&(r={filter:r}),r={...r,count:1,resolveImmediately:!1};let n=Ho(t,e,r),o=n.then(s=>s[0]);return o.cancel=n.cancel,o}function Rr(t,e){if(typeof t!="string")throw new B(`invalid ip provided: ${t}`);if(typeof e=="string"&&(e=parseInt(e)),isNaN(e))throw new B(`invalid port provided: ${e}`);if((0,S.isIPv4)(t))return _(`/ip4/${t}/tcp/${e}`);if((0,S.isIPv6)(t))return _(`/ip6/${t}/tcp/${e}`);throw new B(`invalid ip:port for creating a multiaddr: ${t}:${e}`)}function _t(){let t={};return t.promise=new Promise((e,r)=>{t.resolve=e,t.reject=r}),t}var zt=class extends Error{type;code;constructor(e,r){super(e??"The operation was aborted"),this.type="aborted",this.name="AbortError",this.code=r??"ABORT_ERR"}};async function Bt(t,e,r,n){let o=new zt(n?.errorMessage,n?.errorCode);return r?.aborted===!0?Promise.reject(o):new Promise((s,i)=>{function c(){r?.removeEventListener("abort",u),t.removeEventListener(e,l),n?.errorEvent!=null&&t.removeEventListener(n.errorEvent,f)}let l=p=>{try{if(n?.filter?.(p)===!1)return}catch(y){c(),i(y);return}c(),s(p)},f=p=>{c(),i(p.detail)},u=()=>{c(),i(o)};r?.addEventListener("abort",u),t.addEventListener(e,l),n?.errorEvent!=null&&t.addEventListener(n.errorEvent,f)})}function jr(t){if(Jo(t))return async function*(){let e=t.getReader();try{for(;;){let{done:r,value:n}=await e.read();if(r)return;yield n}}finally{e.releaseLock()}}();if(Qo(t))return t;throw new Error("unknown stream")}function Qo(t){return t[Symbol.asyncIterator]!=null}function Jo(t){return typeof t?.getReader=="function"}function Wr(t){return async e=>{let r=async()=>{Xo(e)&&await e.return(void 0)},n,o,s=x=>{n=x,r().catch(b=>{b=new AggregateError([n,b],"The Writable emitted an error, additionally an error occurred while ending the Source")}).finally(()=>{o?.(x)})},i,c=!1,l=()=>{c=!0,i?.()},f,u=!1,p=()=>{u=!0,f?.()},y,a=()=>{y?.()},d=async()=>new Promise((x,b)=>{i=y=x,o=b,t.once("drain",a)}),T=async()=>(await r(),new Promise((x,b)=>{if(c||u||n!=null){x();return}f=i=x,o=b})),N=()=>{t.removeListener("error",s),t.removeListener("close",l),t.removeListener("finish",p),t.removeListener("drain",a)};t.once("error",s),t.once("close",l),t.once("finish",p);try{for await(let x of e){if(!t.writable||t.destroyed||n!=null)break;t.write(x)||await d()}}catch(x){n==null&&t.destroy(x),n=x}try{if(t.writable&&t.end(),await T(),n!=null)throw n}finally{N()}}}function Xo(t){return t.return!=null}function Rt(t){return{sink:Wr(t),source:jr(t)}}var qr=Z(F("os"),1),Gr=Z(F("path"),1);function ue(t,e={}){let r=t.getPath();if(r!=null)return qr.default.platform()==="win32"?{path:Gr.default.join("\\\\.\\pipe\\",r)}:{path:r};let n=t.toOptions();return{...e,...n,ipv6Only:n.family===6}}var Re=(t,e)=>{let r,n=e.logger.forComponent("libp2p:tcp:socket"),o=e.direction,s=e.metrics,i=e.metricPrefix??"",c=e.socketInactivityTimeout??12e4,l=e.socketCloseTimeout??500,f=!1,u=!1;e.listeningAddr?.getPath()!=null&&(e.remoteAddr=e.listeningAddr),e.remoteAddr?.getPath()!=null&&(e.localAddr=e.remoteAddr),t.on("error",x=>{u=!0,f||(n.error("%s socket error - %e",o,x),s?.increment({[`${i}error`]:!0})),t.destroy(),N.timeline.close=Date.now()});let p;if(e.remoteAddr!=null)p=e.remoteAddr;else{if(t.remoteAddress==null||t.remotePort==null)throw new B("Could not determine remote address or port");p=Rr(t.remoteAddress,t.remotePort)}let y=ue(p),a=y.path??`${y.host??""}:${y.port??""}`,{sink:d,source:T}=Rt(t);t.setTimeout(c),t.once("timeout",()=>{f=!0,n("%s %s socket read timeout",o,a),s?.increment({[`${i}timeout`]:!0}),t.destroy(new ee),N.timeline.close=Date.now()}),t.once("close",()=>{!f&&!u&&(n("%s %s socket close",o,a),s?.increment({[`${i}close`]:!0})),t.destroy(),N.timeline.close=Date.now()}),t.once("end",()=>{n("%s %s socket end",o,a),s?.increment({[`${i}end`]:!0})});let N={async sink(x){try{await d(async function*(){for await(let b of x)b instanceof Uint8Array?yield b:yield b.subarray()}())}catch(b){b.type!=="aborted"&&n.error("%s %s error in sink - %e",o,a,b)}t.end()},source:T,remoteAddr:p,timeline:{open:Date.now()},async close(x={}){if(t.closed){n("the %s %s socket is already closed",o,a);return}if(t.destroyed){n("the %s %s socket is already destroyed",o,a);return}if(r!=null)return r.promise;try{r=_t(),t.end();let b=Ko(t),M=x.signal??AbortSignal.timeout(l);t.writableLength>0&&(n("%s %s draining socket",o,a),await Bt(b,"drain",M,{errorEvent:"error"}),n("%s %s socket drained",o,a)),await Promise.all([Bt(b,"close",M,{errorEvent:"error"}),t.destroy()])}catch(b){this.abort(b)}finally{r.resolve()}},abort:x=>{n("%s %s socket abort due to error - %e",o,a,x),t.destroy(),N.timeline.close=Date.now()},log:n};return N};function Ko(t){return{addEventListener:(r,n)=>{t.addListener(r,n)},removeEventListener:(r,n)=>{t.removeListener(r,n)}}}var C;(function(t){t[t.INACTIVE=0]="INACTIVE",t[t.ACTIVE=1]="ACTIVE",t[t.PAUSED=2]="PAUSED"})(C||(C={}));var je=class extends Te{context;server;sockets=new Set;status={code:C.INACTIVE};metrics;addr;log;shutdownController;constructor(e){if(super(),this.context=e,e.keepAlive=e.keepAlive??!0,e.noDelay=e.noDelay??!0,this.shutdownController=new AbortController,Ae(1/0,this.shutdownController.signal),this.log=e.logger.forComponent("libp2p:tcp:listener"),this.addr="unknown",this.server=Hr.default.createServer(e,this.onSocket.bind(this)),e.maxConnections!==void 0&&(this.server.maxConnections=e.maxConnections),e.closeServerOnMaxConnections!=null&&e.closeServerOnMaxConnections.closeAbove<e.closeServerOnMaxConnections.listenBelow)throw new B("closeAbove must be >= listenBelow");this.server.on("listening",()=>{if(e.metrics!=null){let r=this.server.address();r==null?this.addr="unknown":typeof r=="string"?this.addr=r:this.addr=`${r.address}:${r.port}`,e.metrics?.registerMetricGroup("libp2p_tcp_inbound_connections_total",{label:"address",help:"Current active connections in TCP listener",calculate:()=>({[this.addr]:this.sockets.size})}),this.metrics={status:e.metrics.registerMetricGroup("libp2p_tcp_listener_status_info",{label:"address",help:"Current status of the TCP listener socket"}),errors:e.metrics.registerMetricGroup("libp2p_tcp_listener_errors_total",{label:"address",help:"Total count of TCP listener errors by type"}),events:e.metrics.registerMetricGroup("libp2p_tcp_listener_events_total",{label:"address",help:"Total count of TCP listener events by type"})},this.metrics?.status.update({[this.addr]:C.ACTIVE})}this.safeDispatchEvent("listening")}).on("error",r=>{this.metrics?.errors.increment({[`${this.addr} listen_error`]:!0}),this.safeDispatchEvent("error",{detail:r})}).on("close",()=>{this.metrics?.status.update({[this.addr]:this.status.code}),this.status.code!==C.PAUSED&&this.safeDispatchEvent("close")}).on("drop",()=>{this.metrics?.events.increment({[`${this.addr} drop`]:!0})})}onSocket(e){if(this.metrics?.events.increment({[`${this.addr} connection`]:!0}),this.status.code!==C.ACTIVE)throw e.destroy(),new Ee("Server is not listening yet");let r;try{r=Re(e,{listeningAddr:this.status.listeningAddr,socketInactivityTimeout:this.context.socketInactivityTimeout,socketCloseTimeout:this.context.socketCloseTimeout,metrics:this.metrics?.events,metricPrefix:`${this.addr} `,logger:this.context.logger,direction:"inbound"})}catch(n){this.log.error("inbound connection failed",n),this.metrics?.errors.increment({[`${this.addr} inbound_to_connection`]:!0}),e.destroy();return}this.log("new inbound connection %s",r.remoteAddr),this.sockets.add(e),this.context.upgrader.upgradeInbound(r,{signal:this.shutdownController.signal}).then(()=>{this.log("inbound connection upgraded %s",r.remoteAddr),e.once("close",()=>{this.sockets.delete(e),this.context.closeServerOnMaxConnections!=null&&this.sockets.size<this.context.closeServerOnMaxConnections.listenBelow&&this.resume().catch(n=>{this.log.error("error attempting to listen server once connection count under limit",n),this.context.closeServerOnMaxConnections?.onListenError?.(n)})}),this.context.closeServerOnMaxConnections!=null&&this.sockets.size>=this.context.closeServerOnMaxConnections.closeAbove&&this.pause()}).catch(async n=>{this.log.error("inbound connection upgrade failed",n),this.metrics?.errors.increment({[`${this.addr} inbound_upgrade`]:!0}),this.sockets.delete(e),r.abort(n)})}getAddrs(){if(this.status.code===C.INACTIVE)return[];let e=this.server.address();return e==null?[]:typeof e=="string"?[_(`/unix/${e}`)]:_r(this.status.listeningAddr,e.port)}updateAnnounceAddrs(){}async listen(e){if(this.status.code===C.ACTIVE||this.status.code===C.PAUSED)throw new Ie("server is already listening");try{this.status={code:C.ACTIVE,listeningAddr:e,netConfig:ue(e,this.context)},await this.resume()}catch(r){throw this.status={code:C.INACTIVE},r}}async close(){let e=[];this.server.listening&&e.push(Vt(this.server,"close")),this.pause(!0),this.shutdownController.abort(),this.sockets.forEach(r=>{r.readable&&(e.push(Vt(r,"close")),r.destroy())}),await Promise.all(e)}async resume(){if(this.server.listening||this.status.code===C.INACTIVE)return;let e=this.status.netConfig;await new Promise((r,n)=>{this.server.once("error",n),this.server.listen(e,r)}),this.status={...this.status,code:C.ACTIVE},this.log("listening on %s",this.server.address())}pause(e=!1){if(!this.server.listening&&this.status.code===C.PAUSED&&e){this.status={code:C.INACTIVE};return}!this.server.listening||this.status.code!==C.ACTIVE||(this.log("closing server on %s",this.server.address()),this.status=e?{code:C.INACTIVE}:{...this.status,code:C.PAUSED},this.server.close())}};var We=class{opts;metrics;components;log;constructor(e,r={}){this.log=e.logger.forComponent("libp2p:tcp"),this.opts=r,this.components=e,e.metrics!=null&&(this.metrics={events:e.metrics.registerCounterGroup("libp2p_tcp_dialer_events_total",{label:"event",help:"Total count of TCP dialer events by type"}),errors:e.metrics.registerCounterGroup("libp2p_tcp_dialer_errors_total",{label:"event",help:"Total count of TCP dialer events by type"})})}[qt]=!0;[Symbol.toStringTag]="@libp2p/tcp";[Ht]=["@libp2p/transport"];async dial(e,r){r.keepAlive=r.keepAlive??!0,r.noDelay=r.noDelay??!0;let n=await this._connect(e,r),o;try{o=Re(n,{remoteAddr:e,socketInactivityTimeout:this.opts.outboundSocketInactivityTimeout,socketCloseTimeout:this.opts.socketCloseTimeout,metrics:this.metrics?.events,logger:this.components.logger,direction:"outbound"})}catch(s){thr