libp2p 1.0.12-4e0135c7d → 1.0.12-5d1f68e92

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.min.js CHANGED
@@ -46,7 +46,7 @@
46
46
  (?::(?:(?::${Ue}){0,5}:${$t}|(?::${Ue}){1,7}|:)) // ::2:3:4:5:6:7:8 ::2:3:4:5:6:7:8 ::8 ::1.2.3.4
47
47
  )(?:%[0-9a-zA-Z]{1,})? // %eth0 %1
48
48
  `.replace(/\s*\/\/.*$/gm,"").replace(/\n/g,"").trim(),NL=new RegExp(`(?:^${$t}$)|(?:^${Hc}$)`),PL=new RegExp(`^${$t}$`),OL=new RegExp(`^${Hc}$`),np=t=>t&&t.exact?NL:new RegExp(`(?:${dn(t)}${$t}${dn(t)})|(?:${dn(t)}${Hc}${dn(t)})`,"g");np.v4=t=>t&&t.exact?PL:new RegExp(`${dn(t)}${$t}${dn(t)}`,"g");np.v6=t=>t&&t.exact?OL:new RegExp(`${dn(t)}${Hc}${dn(t)}`,"g");var g2=np;var E2=we(b2(),1),{isValid:kL,parse:UL}=E2.default,ML=["0.0.0.0/8","10.0.0.0/8","100.64.0.0/10","127.0.0.0/8","169.254.0.0/16","172.16.0.0/12","192.0.0.0/24","192.0.0.0/29","192.0.0.8/32","192.0.0.9/32","192.0.0.10/32","192.0.0.170/32","192.0.0.171/32","192.0.2.0/24","192.31.196.0/24","192.52.193.0/24","192.88.99.0/24","192.168.0.0/16","192.175.48.0/24","198.18.0.0/15","198.51.100.0/24","203.0.113.0/24","240.0.0.0/4","255.255.255.255/32"],FL=ML.map(t=>new v2.Netmask(t));function KL(t){for(let e of FL)if(e.contains(t))return!0;return!1}function w2(t){return/^::$/.test(t)||/^::1$/.test(t)||/^::f{4}:([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(t)||/^::f{4}:0.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(t)||/^64:ff9b::([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(t)||/^100::([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(t)||/^2001::([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(t)||/^2001:2[0-9a-fA-F]:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(t)||/^2001:db8:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(t)||/^2002:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(t)||/^f[c-d]([0-9a-fA-F]{2,2}):/i.test(t)||/^fe[8-9a-bA-B][0-9a-fA-F]:/i.test(t)||/^ff([0-9a-fA-F]{2,2}):/i.test(t)}var A2=t=>{if(kL(t)){let e=UL(t);if(e.kind()==="ipv4")return KL(e.toNormalizedString());if(e.kind()==="ipv6")return w2(t)}else if(so(t)&&g2.v6().test(t))return w2(t)};var Wc=A2;function S2(t={}){return{denyDialPeer:async()=>!1,denyDialMultiaddr:async e=>{let r=e.stringTuples();return r[0][0]===4||r[0][0]===41?!!Wc(`${r[0][1]}`):!1},denyInboundConnection:async()=>!1,denyOutboundConnection:async()=>!1,denyInboundEncryptedConnection:async()=>!1,denyOutboundEncryptedConnection:async()=>!1,denyInboundUpgradedConnection:async()=>!1,denyOutboundUpgradedConnection:async()=>!1,filterMultiaddrForPeer:async()=>!0,...t}}function VL(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 i=0;i<t.length;i++){var o=t.charAt(i),s=o.charCodeAt(0);if(r[s]!==255)throw new TypeError(o+" is ambiguous");r[s]=i}var a=t.length,c=t.charAt(0),u=Math.log(a)/Math.log(256),f=Math.log(256)/Math.log(a);function h(l){if(l instanceof Uint8Array||(ArrayBuffer.isView(l)?l=new Uint8Array(l.buffer,l.byteOffset,l.byteLength):Array.isArray(l)&&(l=Uint8Array.from(l))),!(l instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(l.length===0)return"";for(var d=0,m=0,g=0,x=l.length;g!==x&&l[g]===0;)g++,d++;for(var b=(x-g)*f+1>>>0,v=new Uint8Array(b);g!==x;){for(var w=l[g],E=0,A=b-1;(w!==0||E<m)&&A!==-1;A--,E++)w+=256*v[A]>>>0,v[A]=w%a>>>0,w=w/a>>>0;if(w!==0)throw new Error("Non-zero carry");m=E,g++}for(var C=b-m;C!==b&&v[C]===0;)C++;for(var P=c.repeat(d);C<b;++C)P+=t.charAt(v[C]);return P}function p(l){if(typeof l!="string")throw new TypeError("Expected String");if(l.length===0)return new Uint8Array;var d=0;if(l[d]!==" "){for(var m=0,g=0;l[d]===c;)m++,d++;for(var x=(l.length-d)*u+1>>>0,b=new Uint8Array(x);l[d];){var v=r[l.charCodeAt(d)];if(v===255)return;for(var w=0,E=x-1;(v!==0||w<g)&&E!==-1;E--,w++)v+=a*b[E]>>>0,b[E]=v%256>>>0,v=v/256>>>0;if(v!==0)throw new Error("Non-zero carry");g=w,d++}if(l[d]!==" "){for(var A=x-g;A!==x&&b[A]===0;)A++;for(var C=new Uint8Array(m+(x-A)),P=m;A!==x;)C[P++]=b[A++];return C}}}function y(l){var d=p(l);if(d)return d;throw new Error(`Non-${e} character`)}return{encode:h,decodeUnsafe:p,decode:y}}var qL=VL,zL=qL,C2=zL;var BQ=new Uint8Array(0);var I2=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")};var ip=class{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")}},op=class{constructor(e,r,n){if(this.name=e,this.prefix=r,r.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=r.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 _2(this,e)}},sp=class{constructor(e){this.decoders=e}or(e){return _2(this,e)}decode(e){let r=e[0],n=this.decoders[r];if(n)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}},_2=(t,e)=>new sp({...t.decoders||{[t.prefix]:t},...e.decoders||{[e.prefix]:e}}),ap=class{constructor(e,r,n,i){this.name=e,this.prefix=r,this.baseEncode=n,this.baseDecode=i,this.encoder=new ip(e,r,n),this.decoder=new op(e,r,i)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}},T2=({name:t,prefix:e,encode:r,decode:n})=>new ap(t,e,r,n),cp=({prefix:t,name:e,alphabet:r})=>{let{encode:n,decode:i}=C2(r,e);return T2({prefix:t,name:e,encode:n,decode:o=>I2(i(o))})},$L=(t,e,r,n)=>{let i={};for(let f=0;f<e.length;++f)i[e[f]]=f;let o=t.length;for(;t[o-1]==="=";)--o;let s=new Uint8Array(o*r/8|0),a=0,c=0,u=0;for(let f=0;f<o;++f){let h=i[t[f]];if(h===void 0)throw new SyntaxError(`Non-${n} character`);c=c<<r|h,a+=r,a>=8&&(a-=8,s[u++]=255&c>>a)}if(a>=r||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return s},HL=(t,e,r)=>{let n=e[e.length-1]==="=",i=(1<<r)-1,o="",s=0,a=0;for(let c=0;c<t.length;++c)for(a=a<<8|t[c],s+=8;s>r;)s-=r,o+=e[i&a>>s];if(s&&(o+=e[i&a<<r-s]),n)for(;o.length*r&7;)o+="=";return o},Ws=({name:t,prefix:e,bitsPerChar:r,alphabet:n})=>T2({prefix:e,name:t,encode(i){return HL(i,n,r)},decode(i){return $L(i,n,r,t)}});var R2=cp({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),kQ=cp({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var FQ=Ws({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),KQ=Ws({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),B2=Ws({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),VQ=Ws({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var GL=t=>t.toString().split("/").slice(1),Ys=t=>({match:e=>e.length<1?!1:t(e[0])?e.slice(1):!1,pattern:"fn"}),Ne=t=>({match:e=>Ys(r=>r===t).match(e),pattern:t}),Xc=()=>({match:t=>Ys(e=>typeof e=="string").match(t),pattern:"{string}"}),D2=()=>({match:t=>Ys(e=>!isNaN(parseInt(e))).match(t),pattern:"{number}"}),Nt=()=>({match:t=>{if(t.length<2||t[0]!=="p2p"&&t[0]!=="ipfs")return!1;if(t[1].startsWith("Q")||t[1].startsWith("1"))try{R2.decode(`z${t[1]}`)}catch{return!1}else return!1;return t.slice(2)},pattern:"/p2p/{peerid}"}),Yc=()=>({match:t=>{if(t.length<2||t[0]!=="certhash")return!1;try{B2.decode(t[1])}catch{return!1}return t.slice(2)},pattern:"/certhash/{certhash}"}),ur=t=>({match:e=>{let r=t.match(e);return r===!1?e:r},pattern:`optional(${t.pattern})`}),fr=(...t)=>({match:e=>{let r;for(let n of t){let i=n.match(e);i!==!1&&(r==null||i.length<r.length)&&(r=i)}return r??!1},pattern:`or(${t.map(e=>e.pattern).join(", ")})`}),Pe=(...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 Ve(...t){function e(i){let o=GL(i);for(let s of t){let a=s.match(o);if(a===!1)return!1;o=a}return o}function r(i){return e(i)!==!1}function n(i){let o=e(i);return o===!1?!1:o.length===0}return{matches:r,exactMatch:n}}var fp=Pe(Ne("dns4"),Xc()),lp=Pe(Ne("dns6"),Xc()),hp=Pe(Ne("dnsaddr"),Xc()),L2=Pe(Ne("dns"),Xc()),WQ=Ve(fp),YQ=Ve(lp),QQ=Ve(hp),XQ=Ve(fr(L2,hp,fp,lp)),N2=Pe(Ne("ip4"),Ys(bc)),P2=Pe(Ne("ip6"),Ys(wc)),O2=fr(N2,P2),Qs=fr(O2,L2,fp,lp,hp),jQ=Ve(Qs),JQ=Ve(N2),ZQ=Ve(P2),eX=Ve(O2),jc=Pe(Qs,Ne("tcp"),D2()),Xs=Pe(Qs,Ne("udp"),D2()),WL=fr(jc,Xs),tX=Ve(jc),rX=Ve(Xs),dp=Pe(Xs,Ne("quic")),Jc=Pe(Xs,Ne("quic-v1")),YL=fr(dp,Jc),nX=Ve(dp),iX=Ve(Jc),up=fr(Qs,jc,Xs,dp,Jc),k2=fr(Pe(up,Ne("ws"),ur(Nt()))),oX=Ve(k2),U2=fr(Pe(up,Ne("wss"),ur(Nt())),Pe(up,Ne("tls"),Ne("ws"),ur(Nt()))),sX=Ve(U2),M2=Pe(WL,Ne("webrtc-direct"),Yc(),ur(Yc()),ur(Nt())),aX=Ve(M2),F2=Pe(Jc,Ne("webtransport"),Yc(),Yc(),ur(Nt())),cX=Ve(F2),Qc=fr(k2,U2,Pe(jc,ur(Nt())),Pe(YL,ur(Nt())),Pe(Qs,ur(Nt())),M2,F2,Nt()),uX=Ve(Qc),QL=Pe(Qc,Ne("p2p-circuit"),Nt()),pp=Ve(QL),XL=fr(Pe(Qc,Ne("p2p-circuit"),Ne("webrtc"),Nt()),Pe(Qc,Ne("webrtc"),ur(Nt())),Ne("webrtc")),fX=Ve(XL);function mp(t){try{let{address:e}=t.nodeAddress();return!!Wc(e)}catch{return!0}}function jL(t,e){let r=mp(t.multiaddr),n=mp(e.multiaddr);return r&&!n?1:!r&&n?-1:0}function JL(t,e){return t.isCertified&&!e.isCertified?-1:!t.isCertified&&e.isCertified?1:0}function ZL(t,e){let r=pp.exactMatch(t.multiaddr),n=pp.exactMatch(e.multiaddr);return r&&!n?1:!r&&n?-1:0}function So(t,e){let r=jL(t,e);if(r!==0)return r;let n=ZL(t,e);return n!==0?n:JL(t,e)}var gp=we(sh(),1),xp=we(q2(),1);function Zc(t,e,r){return`${t}?name=${e}&type=${r}`}async function z2(t,e){return await(await fetch(t,{headers:new Headers({accept:"application/dns-json"}),signal:e})).json()}function ei(t,e){return`${e}_${t}`}var yp=Object.assign((0,gp.default)("dns-over-http-resolver"),{error:(0,gp.default)("dns-over-http-resolver:error")}),bp=class{_cache;_TXTcache;_servers;_request;_abortControllers;constructor(e={}){this._cache=new xp.default({max:e?.maxCache??100}),this._TXTcache=new xp.default({max:e?.maxCache??100}),this._servers=["https://cloudflare-dns.com/dns-query","https://dns.google/resolve"],this._request=e.request??z2,this._abortControllers=[]}cancel(){this._abortControllers.forEach(e=>{e.abort()})}getServers(){return this._servers}_getShuffledServers(){let e=[...this._servers];for(let r=e.length-1;r>0;r--){let n=Math.floor(Math.random()*r),i=e[r];e[r]=e[n],e[n]=i}return e}setServers(e){this._servers=e}async resolve(e,r="A"){switch(r){case"A":return this.resolve4(e);case"AAAA":return this.resolve6(e);case"TXT":return this.resolveTxt(e);default:throw new Error(`${r} is not supported`)}}async resolve4(e){let r="A",n=this._cache.get(ei(e,r));if(n!=null)return n;let i=!1;for(let o of this._getShuffledServers()){let s=new AbortController;this._abortControllers.push(s);try{let a=await this._request(Zc(o,e,r),s.signal),c=a.Answer.map(f=>f.data),u=Math.min(...a.Answer.map(f=>f.TTL));return this._cache.set(ei(e,r),c,{ttl:u}),c}catch{s.signal.aborted&&(i=!0),yp.error(`${o} could not resolve ${e} record ${r}`)}finally{this._abortControllers=this._abortControllers.filter(a=>a!==s)}}throw i?Object.assign(new Error("queryA ECANCELLED"),{code:"ECANCELLED"}):new Error(`Could not resolve ${e} record ${r}`)}async resolve6(e){let r="AAAA",n=this._cache.get(ei(e,r));if(n!=null)return n;let i=!1;for(let o of this._getShuffledServers()){let s=new AbortController;this._abortControllers.push(s);try{let a=await this._request(Zc(o,e,r),s.signal),c=a.Answer.map(f=>f.data),u=Math.min(...a.Answer.map(f=>f.TTL));return this._cache.set(ei(e,r),c,{ttl:u}),c}catch{s.signal.aborted&&(i=!0),yp.error(`${o} could not resolve ${e} record ${r}`)}finally{this._abortControllers=this._abortControllers.filter(a=>a!==s)}}throw i?Object.assign(new Error("queryAaaa ECANCELLED"),{code:"ECANCELLED"}):new Error(`Could not resolve ${e} record ${r}`)}async resolveTxt(e){let r="TXT",n=this._TXTcache.get(ei(e,r));if(n!=null)return n;let i=!1;for(let o of this._getShuffledServers()){let s=new AbortController;this._abortControllers.push(s);try{let a=await this._request(Zc(o,e,r),s.signal),c=a.Answer.map(f=>[f.data.replace(/['"]+/g,"")]),u=Math.min(...a.Answer.map(f=>f.TTL));return this._TXTcache.set(ei(e,r),c,{ttl:u}),c}catch{s.signal.aborted&&(i=!0),yp.error(`${o} could not resolve ${e} record ${r}`)}finally{this._abortControllers=this._abortControllers.filter(a=>a!==s)}}throw i?Object.assign(new Error("queryTxt ECANCELLED"),{code:"ECANCELLED"}):new Error(`Could not resolve ${e} record ${r}`)}clearCache(){this._cache.clear(),this._TXTcache.clear()}},$2=bp;var H2=$2;var{code:iN}=ue("dnsaddr");async function Co(t,e={}){let r=new H2;e.signal!=null&&e.signal.addEventListener("abort",()=>{r.cancel()});let n=t.getPeerId(),[,i]=t.stringTuples().find(([a])=>a===iN)??[];if(i==null)throw new Error("No hostname found in multiaddr");let s=(await r.resolveTxt(`_dnsaddr.${i}`)).flat().map(a=>a.split("=")[1]).filter(Boolean);return n!=null&&(s=s.filter(a=>a.includes(n))),s}var ev=we(Z2(),1),ru=ev.default;var Mr;(function(t){t.NOT_STARTED_YET="The libp2p node is not started yet",t.ERR_PROTECTOR_REQUIRED="Private network is enforced, but no protector was provided",t.NOT_FOUND="Not found"})(Mr||(Mr={}));var V;(function(t){t.ERR_PROTECTOR_REQUIRED="ERR_PROTECTOR_REQUIRED",t.ERR_PEER_DIAL_INTERCEPTED="ERR_PEER_DIAL_INTERCEPTED",t.ERR_CONNECTION_INTERCEPTED="ERR_CONNECTION_INTERCEPTED",t.ERR_INVALID_PROTOCOLS_FOR_STREAM="ERR_INVALID_PROTOCOLS_FOR_STREAM",t.ERR_CONNECTION_ENDED="ERR_CONNECTION_ENDED",t.ERR_CONNECTION_FAILED="ERR_CONNECTION_FAILED",t.ERR_NODE_NOT_STARTED="ERR_NODE_NOT_STARTED",t.ERR_ALREADY_ABORTED="ERR_ALREADY_ABORTED",t.ERR_TOO_MANY_ADDRESSES="ERR_TOO_MANY_ADDRESSES",t.ERR_NO_VALID_ADDRESSES="ERR_NO_VALID_ADDRESSES",t.ERR_RELAYED_DIAL="ERR_RELAYED_DIAL",t.ERR_DIALED_SELF="ERR_DIALED_SELF",t.ERR_DISCOVERED_SELF="ERR_DISCOVERED_SELF",t.ERR_DUPLICATE_TRANSPORT="ERR_DUPLICATE_TRANSPORT",t.ERR_ENCRYPTION_FAILED="ERR_ENCRYPTION_FAILED",t.ERR_HOP_REQUEST_FAILED="ERR_HOP_REQUEST_FAILED",t.ERR_INVALID_KEY="ERR_INVALID_KEY",t.ERR_INVALID_MESSAGE="ERR_INVALID_MESSAGE",t.ERR_INVALID_PARAMETERS="ERR_INVALID_PARAMETERS",t.ERR_INVALID_PEER="ERR_INVALID_PEER",t.ERR_MUXER_UNAVAILABLE="ERR_MUXER_UNAVAILABLE",t.ERR_NOT_FOUND="ERR_NOT_FOUND",t.ERR_TRANSPORT_UNAVAILABLE="ERR_TRANSPORT_UNAVAILABLE",t.ERR_TRANSPORT_DIAL_FAILED="ERR_TRANSPORT_DIAL_FAILED",t.ERR_UNSUPPORTED_PROTOCOL="ERR_UNSUPPORTED_PROTOCOL",t.ERR_PROTOCOL_HANDLER_ALREADY_REGISTERED="ERR_PROTOCOL_HANDLER_ALREADY_REGISTERED",t.ERR_INVALID_MULTIADDR="ERR_INVALID_MULTIADDR",t.ERR_SIGNATURE_NOT_VALID="ERR_SIGNATURE_NOT_VALID",t.ERR_FIND_SELF="ERR_FIND_SELF",t.ERR_NO_ROUTERS_AVAILABLE="ERR_NO_ROUTERS_AVAILABLE",t.ERR_CONNECTION_NOT_MULTIPLEXED="ERR_CONNECTION_NOT_MULTIPLEXED",t.ERR_NO_DIAL_TOKENS="ERR_NO_DIAL_TOKENS",t.ERR_INVALID_CMS="ERR_INVALID_CMS",t.ERR_MISSING_KEYS="ERR_MISSING_KEYS",t.ERR_NO_KEY="ERR_NO_KEY",t.ERR_INVALID_KEY_NAME="ERR_INVALID_KEY_NAME",t.ERR_INVALID_KEY_TYPE="ERR_INVALID_KEY_TYPE",t.ERR_KEY_ALREADY_EXISTS="ERR_KEY_ALREADY_EXISTS",t.ERR_INVALID_KEY_SIZE="ERR_INVALID_KEY_SIZE",t.ERR_KEY_NOT_FOUND="ERR_KEY_NOT_FOUND",t.ERR_OLD_KEY_NAME_INVALID="ERR_OLD_KEY_NAME_INVALID",t.ERR_NEW_KEY_NAME_INVALID="ERR_NEW_KEY_NAME_INVALID",t.ERR_PASSWORD_REQUIRED="ERR_PASSWORD_REQUIRED",t.ERR_PEM_REQUIRED="ERR_PEM_REQUIRED",t.ERR_CANNOT_READ_KEY="ERR_CANNOT_READ_KEY",t.ERR_MISSING_PRIVATE_KEY="ERR_MISSING_PRIVATE_KEY",t.ERR_MISSING_PUBLIC_KEY="ERR_MISSING_PUBLIC_KEY",t.ERR_INVALID_OLD_PASS_TYPE="ERR_INVALID_OLD_PASS_TYPE",t.ERR_INVALID_NEW_PASS_TYPE="ERR_INVALID_NEW_PASS_TYPE",t.ERR_INVALID_PASS_LENGTH="ERR_INVALID_PASS_LENGTH",t.ERR_NOT_IMPLEMENTED="ERR_NOT_IMPLEMENTED",t.ERR_WRONG_PING_ACK="ERR_WRONG_PING_ACK",t.ERR_INVALID_RECORD="ERR_INVALID_RECORD",t.ERR_ALREADY_SUCCEEDED="ERR_ALREADY_SUCCEEDED",t.ERR_NO_HANDLER_FOR_PROTOCOL="ERR_NO_HANDLER_FOR_PROTOCOL",t.ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS="ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS",t.ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS="ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS",t.ERR_CONNECTION_DENIED="ERR_CONNECTION_DENIED",t.ERR_TRANSFER_LIMIT_EXCEEDED="ERR_TRANSFER_LIMIT_EXCEEDED"})(V||(V={}));var fN={addresses:{listen:[],announce:[],noAnnounce:[],announceFilter:t=>t},connectionManager:{resolvers:{dnsaddr:Co},addressSorter:So},transportManager:{faultTolerance:$r.FATAL_ALL}};function tv(t){let e=ru(fN,t);if(e.connectionProtector===null&&globalThis.process?.env?.LIBP2P_FORCE_PNET!=null)throw new _(Mr.ERR_PROTECTOR_REQUIRED,V.ERR_PROTECTOR_REQUIRED);return e}var rE=we(jv(),1);function ou(t){if(Ta(t))return{peerId:t,multiaddrs:[]};Array.isArray(t)||(t=[t]);let e;if(t.length>0){let r=t[0].getPeerId();e=r==null?void 0:se(r),t.forEach(n=>{if(!cn(n))throw new _("Invalid Multiaddr",V.ERR_INVALID_MULTIADDR);let i=n.getPeerId();if(i==null){if(e!=null)throw new _("Multiaddrs must all have the same peer id or have no peer id",V.ERR_INVALID_PARAMETERS)}else{let o=se(i);if(e==null||!e.equals(o))throw new _("Multiaddrs must all have the same peer id or have no peer id",V.ERR_INVALID_PARAMETERS)}})}return{peerId:e,multiaddrs:t}}function De(){let t={};return t.promise=new Promise((e,r)=>{t.resolve=e,t.reject=r}),t}function Up(t,e,r){let n=0,i=t.length;for(;i>0;){let o=Math.trunc(i/2),s=n+o;r(t[s],e)<=0?(n=++s,i-=o+1):i=o}return n}var Js=class{#e=[];enqueue(e,r){r={priority:0,...r};let n={priority:r.priority,run:e};if(this.size&&this.#e[this.size-1].priority>=r.priority){this.#e.push(n);return}let i=Up(this.#e,n,(o,s)=>s.priority-o.priority);this.#e.splice(i,0,n)}dequeue(){return this.#e.shift()?.run}filter(e){return this.#e.filter(r=>r.priority===e.priority).map(r=>r.run)}get size(){return this.#e.length}};var Zs=class extends Wn.default{#e;#i;#o=0;#a;#c;#p=0;#r;#u;#t;#m;#n=0;#f;#s;#y;timeout;constructor(e){if(super(),e={carryoverConcurrencyCount:!1,intervalCap:Number.POSITIVE_INFINITY,interval:0,concurrency:Number.POSITIVE_INFINITY,autoStart:!0,queueClass:Js,...e},!(typeof e.intervalCap=="number"&&e.intervalCap>=1))throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${e.intervalCap?.toString()??""}\` (${typeof e.intervalCap})`);if(e.interval===void 0||!(Number.isFinite(e.interval)&&e.interval>=0))throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${e.interval?.toString()??""}\` (${typeof e.interval})`);this.#e=e.carryoverConcurrencyCount,this.#i=e.intervalCap===Number.POSITIVE_INFINITY||e.interval===0,this.#a=e.intervalCap,this.#c=e.interval,this.#t=new e.queueClass,this.#m=e.queueClass,this.concurrency=e.concurrency,this.timeout=e.timeout,this.#y=e.throwOnTimeout===!0,this.#s=e.autoStart===!1}get#b(){return this.#i||this.#o<this.#a}get#w(){return this.#n<this.#f}#v(){this.#n--,this.#l(),this.emit("next")}#E(){this.#x(),this.#g(),this.#u=void 0}get#A(){let e=Date.now();if(this.#r===void 0){let r=this.#p-e;if(r<0)this.#o=this.#e?this.#n:0;else return this.#u===void 0&&(this.#u=setTimeout(()=>{this.#E()},r)),!0}return!1}#l(){if(this.#t.size===0)return this.#r&&clearInterval(this.#r),this.#r=void 0,this.emit("empty"),this.#n===0&&this.emit("idle"),!1;if(!this.#s){let e=!this.#A;if(this.#b&&this.#w){let r=this.#t.dequeue();return r?(this.emit("active"),r(),e&&this.#g(),!0):!1}}return!1}#g(){this.#i||this.#r!==void 0||(this.#r=setInterval(()=>{this.#x()},this.#c),this.#p=Date.now()+this.#c)}#x(){this.#o===0&&this.#n===0&&this.#r&&(clearInterval(this.#r),this.#r=void 0),this.#o=this.#e?this.#n:0,this.#h()}#h(){for(;this.#l(););}get concurrency(){return this.#f}set concurrency(e){if(!(typeof e=="number"&&e>=1))throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${e}\` (${typeof e})`);this.#f=e,this.#h()}async#S(e){return new Promise((r,n)=>{e.addEventListener("abort",()=>{n(e.reason)},{once:!0})})}async add(e,r={}){return r={timeout:this.timeout,throwOnTimeout:this.#y,...r},new Promise((n,i)=>{this.#t.enqueue(async()=>{this.#n++,this.#o++;try{r.signal?.throwIfAborted();let o=e({signal:r.signal});r.timeout&&(o=Pr(Promise.resolve(o),{milliseconds:r.timeout})),r.signal&&(o=Promise.race([o,this.#S(r.signal)]));let s=await o;n(s),this.emit("completed",s)}catch(o){if(o instanceof Nr&&!r.throwOnTimeout){n();return}i(o),this.emit("error",o)}finally{this.#v()}},r),this.emit("add"),this.#l()})}async addAll(e,r){return Promise.all(e.map(async n=>this.add(n,r)))}start(){return this.#s?(this.#s=!1,this.#h(),this):this}pause(){this.#s=!0}clear(){this.#t=new this.#m}async onEmpty(){this.#t.size!==0&&await this.#d("empty")}async onSizeLessThan(e){this.#t.size<e||await this.#d("next",()=>this.#t.size<e)}async onIdle(){this.#n===0&&this.#t.size===0||await this.#d("idle")}async#d(e,r){return new Promise(n=>{let i=()=>{r&&!r()||(this.off(e,i),n())};this.on(e,i)})}get size(){return this.#t.size}sizeBy(e){return this.#t.filter(e).length}get pending(){return this.#n}get isPaused(){return this.#s}};function jN(t,e,r){let n=0,i=t.length;for(;i>0;){let o=Math.trunc(i/2),s=n+o;r(t[s],e)<=0?(n=++s,i-=o+1):i=o}return n}var Mp=class{#e=[];enqueue(e,r){let n=r?.peerId,i=r?.priority??0;if(n==null)throw new _("missing peer id",uf);let o={priority:i,peerId:n,run:e};if(this.size>0&&this.#e[this.size-1].priority>=i){this.#e.push(o);return}let s=jN(this.#e,o,(a,c)=>c.priority-a.priority);this.#e.splice(s,0,o)}dequeue(){return this.#e.shift()?.run}filter(e){if(e.peerId!=null){let r=e.peerId;return this.#e.filter(n=>r.equals(n.peerId)).map(n=>n.run)}return this.#e.filter(r=>r.priority===e.priority).map(r=>r.run)}get size(){return this.#e.length}},su=class extends Zs{results;constructor(e={}){super({...e,queueClass:Mp}),this.results=new ot}hasJob(e){return this.sizeBy({peerId:e})>0}async joinJob(e){let r=this.results.get(e);if(r==null)throw new _("No job found for peer id","ERR_NO_JOB_FOR_PEER_ID");return r===!0&&(r=De(),this.results.set(e,r)),r.promise}async add(e,r){let n=r?.peerId;if(n==null)throw new _("missing peer id",uf);return this.results.set(r.peerId,!0),super.add(async i=>{try{let o=await e(i),s=this.results.get(n);return s!=null&&s!==!0&&s.resolve(o),o}catch(o){let s=this.results.get(n);throw s!=null&&s!==!0&&s.reject(o),o}finally{this.results.delete(n)}},r)}clear(){this.results.clear(),super.clear()}};function Jv(t,e="utf8"){let r=qc[e];if(r==null)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?globalThis.Buffer.from(t.buffer,t.byteOffset,t.byteLength).toString("utf8"):r.encoder.encode(t).substring(1)}var au="last-dial-failure";var cu=5,uu=100,fu=50,Zv=1e3*60*7;var ri={minConnections:cu,maxQueueLength:100,autoDialConcurrency:25,autoDialPriority:0,autoDialInterval:5e3,autoDialPeerRetryThreshold:Zv,autoDialDiscoveredPeersDebounce:10},lu=class{connectionManager;peerStore;queue;minConnections;autoDialPriority;autoDialIntervalMs;autoDialMaxQueueLength;autoDialPeerRetryThresholdMs;autoDialDiscoveredPeersDebounce;autoDialInterval;started;running;log;constructor(e,r){this.connectionManager=e.connectionManager,this.peerStore=e.peerStore,this.minConnections=r.minConnections??ri.minConnections,this.autoDialPriority=r.autoDialPriority??ri.autoDialPriority,this.autoDialIntervalMs=r.autoDialInterval??ri.autoDialInterval,this.autoDialMaxQueueLength=r.maxQueueLength??ri.maxQueueLength,this.autoDialPeerRetryThresholdMs=r.autoDialPeerRetryThreshold??ri.autoDialPeerRetryThreshold,this.autoDialDiscoveredPeersDebounce=r.autoDialDiscoveredPeersDebounce??ri.autoDialDiscoveredPeersDebounce,this.log=e.logger.forComponent("libp2p:connection-manager:auto-dial"),this.started=!1,this.running=!1,this.queue=new su({concurrency:r.autoDialConcurrency??ri.autoDialConcurrency}),this.queue.addListener("error",i=>{this.log.error("error during auto-dial",i)}),e.events.addEventListener("connection:close",()=>{this.autoDial().catch(i=>{this.log.error(i)})});let n;e.events.addEventListener("peer:discovery",()=>{clearTimeout(n),n=setTimeout(()=>{this.autoDial().catch(i=>{this.log.error(i)})},this.autoDialDiscoveredPeersDebounce)})}isStarted(){return this.started}start(){this.started=!0}afterStart(){this.autoDial().catch(e=>{this.log.error("error while autodialing",e)})}stop(){this.queue.clear(),clearTimeout(this.autoDialInterval),this.started=!1,this.running=!1}async autoDial(){if(!this.started||this.running)return;let e=this.connectionManager.getConnectionsMap(),r=e.size;if(r>=this.minConnections){this.minConnections>0&&this.log.trace("have enough connections %d/%d",r,this.minConnections);return}if(this.queue.size>this.autoDialMaxQueueLength){this.log("not enough connections %d/%d but auto dial queue is full",r,this.minConnections),this.sheduleNextAutodial();return}this.running=!0,this.log("not enough connections %d/%d - will dial peers to increase the number of connections",r,this.minConnections);let n=new Dt(this.connectionManager.getDialQueue().map(u=>u.peerId).filter(Boolean)),i=await this.peerStore.all({filters:[u=>u.addresses.length===0?(this.log.trace("not autodialing %p because they have no addresses",u.id),!1):e.has(u.id)?(this.log.trace("not autodialing %p because they are already connected",u.id),!1):n.has(u.id)?(this.log.trace("not autodialing %p because they are already being dialed",u.id),!1):this.queue.hasJob(u.id)?(this.log.trace("not autodialing %p because they are already being autodialed",u.id),!1):!0]}),o=i.sort(()=>Math.random()>.5?1:-1),s=new ot;for(let u of o)s.has(u.id)||s.set(u.id,[...u.tags.values()].reduce((f,h)=>f+h.value,0));let c=o.sort((u,f)=>{let h=s.get(u.id)??0,p=s.get(f.id)??0;return h>p?-1:h<p?1:0}).filter(u=>{let f=u.metadata.get(au);if(f==null)return!0;let h=parseInt(Jv(f));return isNaN(h)?!0:Date.now()-h>this.autoDialPeerRetryThresholdMs});this.log("selected %d/%d peers to dial",c.length,i.length);for(let u of c)this.queue.add(async()=>{let f=this.connectionManager.getConnectionsMap().size;if(f>=this.minConnections){this.log("got enough connections now %d/%d",f,this.minConnections),this.queue.clear();return}this.log("connecting to a peerStore stored peer %p",u.id),await this.connectionManager.openConnection(u.id,{priority:this.autoDialPriority})},{peerId:u.id}).catch(f=>{this.log.error("could not connect to peerStore stored peer",f)});this.running=!1,this.sheduleNextAutodial()}sheduleNextAutodial(){this.started&&(this.autoDialInterval=setTimeout(()=>{this.autoDial().catch(e=>{this.log.error("error while autodialing",e)})},this.autoDialIntervalMs))}};var eE={maxConnections:uu,allow:[]},hu=class{maxConnections;connectionManager;peerStore;allow;events;log;constructor(e,r={}){this.maxConnections=r.maxConnections??eE.maxConnections,this.allow=r.allow??eE.allow,this.connectionManager=e.connectionManager,this.peerStore=e.peerStore,this.events=e.events,this.log=e.logger.forComponent("libp2p:connection-manager:connection-pruner"),e.events.addEventListener("connection:open",()=>{this.maybePruneConnections().catch(n=>{this.log.error(n)})})}async maybePruneConnections(){let e=this.connectionManager.getConnections(),r=e.length,n=Math.max(r-this.maxConnections,0);if(this.log("checking max connections limit %d/%d",r,this.maxConnections),r<=this.maxConnections)return;this.log("max connections limit exceeded %d/%d, pruning %d connection(s)",r,this.maxConnections,n);let i=new ot;for(let a of e){let c=a.remotePeer;if(!i.has(c)){i.set(c,0);try{let u=await this.peerStore.get(c);i.set(c,[...u.tags.values()].reduce((f,h)=>f+h.value,0))}catch(u){u.code!=="ERR_NOT_FOUND"&&this.log.error("error loading peer tags",u)}}}let o=e.sort((a,c)=>{let u=i.get(a.remotePeer)??0,f=i.get(c.remotePeer)??0;if(u>f)return 1;if(u<f)return-1;let h=a.timeline.open,p=c.timeline.open;return h<p?1:h>p?-1:0}),s=[];for(let a of o)if(this.log("too many connections open - closing a connection to %p",a.remotePeer),this.allow.some(u=>a.remoteAddr.toString().startsWith(u.toString()))||s.push(a),s.length===n)break;await Promise.all(s.map(async a=>{try{await a.close()}catch(c){this.log.error(c)}})),this.events.safeDispatchEvent("connection:prune",{detail:s})}};function du(t){let e=new globalThis.AbortController;function r(){e.abort();for(let o of t)o?.removeEventListener!=null&&o.removeEventListener("abort",r)}for(let o of t){if(o?.aborted===!0){r();break}o?.addEventListener!=null&&o.addEventListener("abort",r)}function n(){for(let o of t)o?.removeEventListener!=null&&o.removeEventListener("abort",r)}let i=e.signal;return i.clear=n,i}function qp(t,e,r){let n=0,i=t.length;for(;i>0;){let o=Math.trunc(i/2),s=n+o;r(t[s],e)<=0?(n=++s,i-=o+1):i=o}return n}var ea=class{#e=[];enqueue(e,r){r={priority:0,...r};let n={priority:r.priority,run:e};if(this.size&&this.#e[this.size-1].priority>=r.priority){this.#e.push(n);return}let i=qp(this.#e,n,(o,s)=>s.priority-o.priority);this.#e.splice(i,0,n)}dequeue(){return this.#e.shift()?.run}filter(e){return this.#e.filter(r=>r.priority===e.priority).map(r=>r.run)}get size(){return this.#e.length}};var Do=class extends Wn.default{#e;#i;#o=0;#a;#c;#p=0;#r;#u;#t;#m;#n=0;#f;#s;#y;timeout;constructor(e){if(super(),e={carryoverConcurrencyCount:!1,intervalCap:Number.POSITIVE_INFINITY,interval:0,concurrency:Number.POSITIVE_INFINITY,autoStart:!0,queueClass:ea,...e},!(typeof e.intervalCap=="number"&&e.intervalCap>=1))throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${e.intervalCap?.toString()??""}\` (${typeof e.intervalCap})`);if(e.interval===void 0||!(Number.isFinite(e.interval)&&e.interval>=0))throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${e.interval?.toString()??""}\` (${typeof e.interval})`);this.#e=e.carryoverConcurrencyCount,this.#i=e.intervalCap===Number.POSITIVE_INFINITY||e.interval===0,this.#a=e.intervalCap,this.#c=e.interval,this.#t=new e.queueClass,this.#m=e.queueClass,this.concurrency=e.concurrency,this.timeout=e.timeout,this.#y=e.throwOnTimeout===!0,this.#s=e.autoStart===!1}get#b(){return this.#i||this.#o<this.#a}get#w(){return this.#n<this.#f}#v(){this.#n--,this.#l(),this.emit("next")}#E(){this.#x(),this.#g(),this.#u=void 0}get#A(){let e=Date.now();if(this.#r===void 0){let r=this.#p-e;if(r<0)this.#o=this.#e?this.#n:0;else return this.#u===void 0&&(this.#u=setTimeout(()=>{this.#E()},r)),!0}return!1}#l(){if(this.#t.size===0)return this.#r&&clearInterval(this.#r),this.#r=void 0,this.emit("empty"),this.#n===0&&this.emit("idle"),!1;if(!this.#s){let e=!this.#A;if(this.#b&&this.#w){let r=this.#t.dequeue();return r?(this.emit("active"),r(),e&&this.#g(),!0):!1}}return!1}#g(){this.#i||this.#r!==void 0||(this.#r=setInterval(()=>{this.#x()},this.#c),this.#p=Date.now()+this.#c)}#x(){this.#o===0&&this.#n===0&&this.#r&&(clearInterval(this.#r),this.#r=void 0),this.#o=this.#e?this.#n:0,this.#h()}#h(){for(;this.#l(););}get concurrency(){return this.#f}set concurrency(e){if(!(typeof e=="number"&&e>=1))throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${e}\` (${typeof e})`);this.#f=e,this.#h()}async#S(e){return new Promise((r,n)=>{e.addEventListener("abort",()=>{n(e.reason)},{once:!0})})}async add(e,r={}){return r={timeout:this.timeout,throwOnTimeout:this.#y,...r},new Promise((n,i)=>{this.#t.enqueue(async()=>{this.#n++,this.#o++;try{r.signal?.throwIfAborted();let o=e({signal:r.signal});r.timeout&&(o=Pr(Promise.resolve(o),{milliseconds:r.timeout})),r.signal&&(o=Promise.race([o,this.#S(r.signal)]));let s=await o;n(s),this.emit("completed",s)}catch(o){if(o instanceof Nr&&!r.throwOnTimeout){n();return}i(o),this.emit("error",o)}finally{this.#v()}},r),this.emit("add"),this.#l()})}async addAll(e,r){return Promise.all(e.map(async n=>this.add(n,r)))}start(){return this.#s?(this.#s=!1,this.#h(),this):this}pause(){this.#s=!0}clear(){this.#t=new this.#m}async onEmpty(){this.#t.size!==0&&await this.#d("empty")}async onSizeLessThan(e){this.#t.size<e||await this.#d("next",()=>this.#t.size<e)}async onIdle(){this.#n===0&&this.#t.size===0||await this.#d("idle")}async#d(e,r){return new Promise(n=>{let i=()=>{r&&!r()||(this.off(e,i),n())};this.on(e,i)})}get size(){return this.#t.size}sizeBy(e){return this.#t.filter(e).length}get pending(){return this.#n}get isPaused(){return this.#s}};async function zp(t,e){if(!t.protoNames().includes("dnsaddr"))return[t];let n=await eP(t,e),s=(await Promise.all(n.map(async a=>zp(a,e)))).flat().reduce((a,c)=>(a.find(u=>u.equals(c))==null&&a.push(c),a),[]);return e.log("resolved %s to",t,s.map(a=>a.toString())),s}async function eP(t,e){try{return t=Ke(t.toString()),await t.resolve(e)}catch(r){return e.log.error(`multiaddr ${t.toString()} could not be resolved`,r),[]}}function tE(...t){let e=[];for(let n of t)n!=null&&(wt(1/0,n),e.push(n));let r=du(e);return wt(1/0,r),r}var pu={addressSorter:So,maxParallelDials:fu,maxPeerAddrsToDial:25,dialTimeout:3e4,resolvers:{dnsaddr:Co}},mu=class{pendingDials;queue;peerId;peerStore;connectionGater;transportManager;addressSorter;maxPeerAddrsToDial;dialTimeout;inProgressDialCount;pendingDialCount;shutDownController;connections;log;constructor(e,r={}){this.addressSorter=r.addressSorter??pu.addressSorter,this.maxPeerAddrsToDial=r.maxPeerAddrsToDial??pu.maxPeerAddrsToDial,this.dialTimeout=r.dialTimeout??pu.dialTimeout,this.connections=r.connections??new ot,this.log=e.logger.forComponent("libp2p:connection-manager:dial-queue"),this.peerId=e.peerId,this.peerStore=e.peerStore,this.connectionGater=e.connectionGater,this.transportManager=e.transportManager,this.shutDownController=new AbortController,wt(1/0,this.shutDownController.signal),this.pendingDialCount=e.metrics?.registerMetric("libp2p_dial_queue_pending_dials"),this.inProgressDialCount=e.metrics?.registerMetric("libp2p_dial_queue_in_progress_dials"),this.pendingDials=[];for(let[n,i]of Object.entries(r.resolvers??{}))Ec.set(n,i);this.queue=new Do({concurrency:r.maxParallelDials??pu.maxParallelDials}),this.queue.on("add",()=>{this.pendingDialCount?.update(this.queue.size),this.inProgressDialCount?.update(this.queue.pending)}),this.queue.on("active",()=>{this.pendingDialCount?.update(this.queue.size),this.inProgressDialCount?.update(this.queue.pending)}),this.queue.on("completed",()=>{this.pendingDialCount?.update(this.queue.size),this.inProgressDialCount?.update(this.queue.pending)}),this.queue.on("error",n=>{this.log.error("error in dial queue",n),this.pendingDialCount?.update(this.queue.size),this.inProgressDialCount?.update(this.queue.pending)}),this.queue.on("empty",()=>{this.pendingDialCount?.update(this.queue.size),this.inProgressDialCount?.update(this.queue.pending)}),this.queue.on("idle",()=>{this.pendingDialCount?.update(this.queue.size),this.inProgressDialCount?.update(this.queue.pending)})}start(){this.shutDownController=new AbortController}stop(){this.shutDownController.abort(),this.queue.clear()}async dial(e,r={}){let{peerId:n,multiaddrs:i}=ou(e),o=i.map(p=>({multiaddr:p,isCertified:!1})),s=this.createDialAbortControllers(r.signal),a;try{a=await this.calculateMultiaddrs(n,o,{...r,signal:s})}catch(p){throw s.clear(),p}let c=Array.from(this.connections.values()).flat().find(p=>r.force===!0?!1:a.find(y=>y.multiaddr.equals(p.remoteAddr)));if(c!=null)return this.log("already connected to %a",c.remoteAddr),c;let u=this.pendingDials.find(p=>!!(p.peerId!=null&&n!=null&&p.peerId.equals(n)||a.map(({multiaddr:y})=>y.toString()).join()===p.multiaddrs.map(y=>y.toString()).join()));if(u!=null)return this.log("joining existing dial target for %p",n),s.clear(),u.promise;this.log("creating dial target for",a.map(({multiaddr:p})=>p.toString()));let f={id:tP(),status:"queued",peerId:n,multiaddrs:a.map(({multiaddr:p})=>p)};f.promise=this.performDial(f,{...r,signal:s}).finally(()=>{this.pendingDials=this.pendingDials.filter(p=>p.id!==f.id),s.clear()}).catch(async p=>{if(this.log.error("dial failed to %s",f.multiaddrs.map(y=>y.toString()).join(", "),p),n!=null)try{await this.peerStore.patch(n,{metadata:{[au]:zc(Date.now().toString())}})}catch(y){this.log.error("could not update last dial failure key for %p",n,y)}throw s.aborted?new _(p.message,Ra):p}),this.pendingDials.push(f);let h=await f.promise;return c=Array.from(this.connections.values()).flat().find(p=>r.force===!0?!1:p.id!==h.id&&p.remoteAddr.equals(h.remoteAddr)),c!=null?(this.log("already connected to %a",c.remoteAddr),await h.close(),c):(this.log("connection opened to %a",h.remoteAddr),h)}createDialAbortControllers(e){let r=du([AbortSignal.timeout(this.dialTimeout),this.shutDownController.signal,e]);return wt(1/0,r),r}async calculateMultiaddrs(e,r=[],n={}){if(e!=null){if(this.peerId.equals(e))throw new _("Tried to dial self",V.ERR_DIALED_SELF);if(await this.connectionGater.denyDialPeer?.(e)===!0)throw new _("The dial request is blocked by gater.allowDialPeer",V.ERR_PEER_DIAL_INTERCEPTED);if(r.length===0){this.log("loading multiaddrs for %p",e);try{let f=await this.peerStore.get(e);r.push(...f.addresses),this.log("loaded multiaddrs for %p",e,r.map(({multiaddr:h})=>h.toString()))}catch(f){if(f.code!==V.ERR_NOT_FOUND)throw f}}}let i=(await Promise.all(r.map(async f=>{let h=await zp(f.multiaddr,{...n,log:this.log});return h.length===1&&h[0].equals(f.multiaddr)?f:h.map(p=>({multiaddr:p,isCertified:!1}))}))).flat();if(e!=null){let f=`/p2p/${e.toString()}`;i=i.map(h=>h.multiaddr.protos().pop()?.path===!0?h:h.multiaddr.getPeerId()==null?{multiaddr:h.multiaddr.encapsulate(f),isCertified:h.isCertified}:h)}let o=i.filter(f=>{if(this.transportManager.transportForMultiaddr(f.multiaddr)==null)return!1;let h=f.multiaddr.getPeerId();return e!=null&&h!=null?e.equals(h):!0}),s=new Map;for(let f of o){let h=f.multiaddr.toString(),p=s.get(h);if(p!=null){p.isCertified=p.isCertified||f.isCertified||!1;continue}s.set(h,f)}let a=[...s.values()];if((a.length===0||a.length>this.maxPeerAddrsToDial)&&(this.log("addresses for %p before filtering",e??"unknown peer",i.map(({multiaddr:f})=>f.toString())),this.log("addresses for %p after filtering",e??"unknown peer",a.map(({multiaddr:f})=>f.toString()))),a.length===0)throw new _("The dial request has no valid addresses",V.ERR_NO_VALID_ADDRESSES);if(a.length>this.maxPeerAddrsToDial)throw new _("dial with more addresses than allowed",V.ERR_TOO_MANY_ADDRESSES);let c=[];for(let f of a)this.connectionGater.denyDialMultiaddr!=null&&await this.connectionGater.denyDialMultiaddr(f.multiaddr)||c.push(f);let u=c.sort(this.addressSorter);if(u.length===0)throw new _("The connection gater denied all addresses in the dial request",V.ERR_NO_VALID_ADDRESSES);return u}async performDial(e,r={}){let n=e.multiaddrs.map(()=>new AbortController);try{let i=new Do({concurrency:1});i.on("error",s=>{this.log.error("error dialing %s %o",e.multiaddrs,s)});let o=await Promise.any(e.multiaddrs.map(async(s,a)=>{let c=n[a];if(c==null)throw new _("dialAction did not come with an AbortController",V.ERR_INVALID_PARAMETERS);let u=tE(c.signal,r.signal);u.addEventListener("abort",()=>{this.log("dial to %a aborted",s)});let f=De();return await i.add(async()=>{if(u.aborted){this.log("dial to %a was aborted before reaching the head of the peer dial queue",s),f.reject(new hi);return}await this.queue.add(async()=>{try{if(u.aborted){this.log("dial to %a was aborted before reaching the head of the dial queue",s),f.reject(new hi);return}e.status="active";let h=await this.transportManager.dial(s,{...r,signal:u});if(c.signal.aborted){this.log("multiple dials succeeded, closing superfluous connection"),h.close().catch(p=>{this.log.error("error closing superfluous connection",p)}),f.reject(new hi);return}n[a]=void 0,n.forEach(p=>{p!==void 0&&p.abort()}),this.log("dial to %a succeeded",s),f.resolve(h)}catch(h){this.log.error("error during dial of %a",s,h),f.reject(h)}},{...r,signal:u}).catch(h=>{f.reject(h)})},{signal:u}).catch(h=>{f.reject(h)}).finally(()=>{u.clear()}),f.promise}));if(o==null)throw new _("successful dial led to empty object returned from peer dial queue",V.ERR_TRANSPORT_DIAL_FAILED);return e.status="success",o}catch(i){throw e.status="error",e.multiaddrs.length===1&&i.name==="AggregateError"?i.errors[0]:i}}};function tP(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var iP=50,ni={minConnections:cu,maxConnections:uu,inboundConnectionThreshold:5,maxIncomingPendingConnections:10,autoDialConcurrency:25,autoDialPriority:0,autoDialMaxQueueLength:100},yu=class{started;connections;allow;deny;maxIncomingPendingConnections;incomingPendingConnections;maxConnections;dialQueue;autoDial;connectionPruner;inboundConnectionRateLimiter;peerStore;metrics;events;log;constructor(e,r={}){this.maxConnections=r.maxConnections??ni.maxConnections;let n=r.minConnections??ni.minConnections;if(this.maxConnections<n)throw new _("Connection Manager maxConnections must be greater than minConnections",V.ERR_INVALID_PARAMETERS);this.connections=new ot,this.started=!1,this.peerStore=e.peerStore,this.metrics=e.metrics,this.events=e.events,this.log=e.logger.forComponent("libp2p:connection-manager"),this.onConnect=this.onConnect.bind(this),this.onDisconnect=this.onDisconnect.bind(this),this.events.addEventListener("connection:open",this.onConnect),this.events.addEventListener("connection:close",this.onDisconnect),this.allow=(r.allow??[]).map(i=>Ke(i)),this.deny=(r.deny??[]).map(i=>Ke(i)),this.incomingPendingConnections=0,this.maxIncomingPendingConnections=r.maxIncomingPendingConnections??ni.maxIncomingPendingConnections,this.inboundConnectionRateLimiter=new rE.RateLimiterMemory({points:r.inboundConnectionThreshold??ni.inboundConnectionThreshold,duration:1}),this.autoDial=new lu({connectionManager:this,peerStore:e.peerStore,events:e.events,logger:e.logger},{minConnections:n,autoDialConcurrency:r.autoDialConcurrency??ni.autoDialConcurrency,autoDialPriority:r.autoDialPriority??ni.autoDialPriority,maxQueueLength:r.autoDialMaxQueueLength??ni.autoDialMaxQueueLength}),this.connectionPruner=new hu({connectionManager:this,peerStore:e.peerStore,events:e.events,logger:e.logger},{maxConnections:this.maxConnections,allow:this.allow}),this.dialQueue=new mu({peerId:e.peerId,metrics:e.metrics,peerStore:e.peerStore,transportManager:e.transportManager,connectionGater:e.connectionGater,logger:e.logger},{addressSorter:r.addressSorter??So,maxParallelDials:r.maxParallelDials??fu,maxPeerAddrsToDial:r.maxPeerAddrsToDial??25,dialTimeout:r.dialTimeout??3e4,resolvers:r.resolvers??{dnsaddr:Co},connections:this.connections})}isStarted(){return this.started}async start(){this.metrics?.registerMetricGroup("libp2p_connection_manager_connections",{calculate:()=>{let e={inbound:0,outbound:0};for(let r of this.connections.values())for(let n of r)n.direction==="inbound"?e.inbound++:e.outbound++;return e}}),this.metrics?.registerMetricGroup("libp2p_protocol_streams_total",{label:"protocol",calculate:()=>{let e={};for(let r of this.connections.values())for(let n of r)for(let i of n.streams){let o=`${i.direction} ${i.protocol??"unnegotiated"}`;e[o]=(e[o]??0)+1}return e}}),this.metrics?.registerMetricGroup("libp2p_connection_manager_protocol_streams_per_connection_90th_percentile",{label:"protocol",calculate:()=>{let e={};for(let n of this.connections.values())for(let i of n){let o={};for(let s of i.streams){let a=`${s.direction} ${s.protocol??"unnegotiated"}`;o[a]=(o[a]??0)+1}for(let[s,a]of Object.entries(o))e[s]=e[s]??[],e[s].push(a)}let r={};for(let[n,i]of Object.entries(e)){i=i.sort((s,a)=>s-a);let o=Math.floor(i.length*.9);r[n]=i[o]}return r}}),this.dialQueue.start(),this.autoDial.start(),this.started=!0,this.log("started")}async afterStart(){Promise.resolve().then(async()=>{let e=await this.peerStore.all({filters:[r=>r.tags.has(Xy)]});await Promise.all(e.map(async r=>{await this.openConnection(r.id).catch(n=>{this.log.error(n)})}))}).catch(e=>{this.log.error(e)}),this.autoDial.afterStart()}async stop(){this.dialQueue.stop(),this.autoDial.stop();let e=[];for(let r of this.connections.values())for(let n of r)e.push((async()=>{try{await n.close()}catch(i){this.log.error(i)}})());this.log("closing %d connections",e.length),await Promise.all(e),this.connections.clear(),this.log("stopped")}onConnect(e){this._onConnect(e).catch(r=>{this.log.error(r)})}async _onConnect(e){let{detail:r}=e;if(!this.started){await r.close();return}let n=r.remotePeer,i=this.connections.get(n),o=!1;i!=null?i.push(r):(o=!0,this.connections.set(n,[r])),n.publicKey!=null&&n.type==="RSA"&&await this.peerStore.patch(n,{publicKey:n.publicKey}),o&&this.events.safeDispatchEvent("peer:connect",{detail:r.remotePeer})}onDisconnect(e){let{detail:r}=e;if(!this.started)return;let n=r.remotePeer,i=this.connections.get(n);i!=null&&i.length>1?(i=i.filter(o=>o.id!==r.id),this.connections.set(n,i)):i!=null&&(this.connections.delete(n),this.events.safeDispatchEvent("peer:disconnect",{detail:r.remotePeer}))}getConnections(e){if(e!=null)return this.connections.get(e)??[];let r=[];for(let n of this.connections.values())r=r.concat(n);return r}getConnectionsMap(){return this.connections}async openConnection(e,r={}){if(!this.isStarted())throw new _("Not started",V.ERR_NODE_NOT_STARTED);r.signal?.throwIfAborted();let{peerId:n}=ou(e);if(n!=null&&r.force!==!0){this.log("dial %p",n);let a=this.getConnections(n).find(c=>!c.transient);if(a!=null)return this.log("had an existing non-transient connection to %p",n),a}let i=await this.dialQueue.dial(e,{...r,priority:r.priority??iP}),o=this.connections.get(i.remotePeer);o==null&&(o=[],this.connections.set(i.remotePeer,o));let s=!1;for(let a of o)a.id===i.id&&(s=!0);return s||o.push(i),i}async closeConnections(e,r={}){let n=this.connections.get(e)??[];await Promise.all(n.map(async i=>{try{await i.close(r)}catch(o){i.abort(o)}}))}async acceptIncomingConnection(e){if(this.deny.some(i=>e.remoteAddr.toString().startsWith(i.toString())))return this.log("connection from %a refused - connection remote address was in deny list",e.remoteAddr),!1;if(this.allow.some(i=>e.remoteAddr.toString().startsWith(i.toString())))return this.incomingPendingConnections++,!0;if(this.incomingPendingConnections===this.maxIncomingPendingConnections)return this.log("connection from %a refused - incomingPendingConnections exceeded by host",e.remoteAddr),!1;if(e.remoteAddr.isThinWaistAddress()){let i=e.remoteAddr.nodeAddress().address;try{await this.inboundConnectionRateLimiter.consume(i,1)}catch{return this.log("connection from %a refused - inboundConnectionThreshold exceeded by host %s",e.remoteAddr,i),!1}}return this.getConnections().length<this.maxConnections?(this.incomingPendingConnections++,!0):(this.log("connection from %a refused - maxConnections exceeded",e.remoteAddr),!1)}afterUpgradeInbound(){this.incomingPendingConnections--}getDialQueue(){return this.dialQueue.pendingDials}};var gu=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}},Lo=class{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new gu(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 r=this.head;this.head=r.next=new gu(2*this.head.buffer.length),this.head.push(e)}}shift(){let e=this.tail.shift();if(e===void 0&&this.tail.next!=null){let r=this.tail.next;this.tail.next=null,this.tail=r,e=this.tail.shift()}return e?.value!=null&&(this.size-=this.calculateSize(e.value)),e}isEmpty(){return this.head.isEmpty()}};var Gp=class extends Error{type;code;constructor(e,r){super(e??"The operation was aborted"),this.type="aborted",this.code=r??"ABORT_ERR"}};function nE(t={}){return oP(r=>{let n=r.shift();if(n==null)return{done:!0};if(n.error!=null)throw n.error;return{done:n.done===!0,value:n.value}},t)}function oP(t,e){e=e??{};let r=e.onEnd,n=new Lo,i,o,s,a=De(),c=async()=>{try{return n.isEmpty()?s?{done:!0}:await new Promise((m,g)=>{o=x=>{o=null,n.push(x);try{m(t(n))}catch(b){g(b)}return i}}):t(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=De()})}},u=m=>o!=null?o(m):(n.push(m),i),f=m=>(n=new Lo,o!=null?o({error:m}):(n.push({error:m}),i)),h=m=>{if(s)return i;if(e?.objectMode!==!0&&m?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return u({done:!1,value:m})},p=m=>s?i:(s=!0,m!=null?f(m):u({done:!0})),y=()=>(n=new Lo,p(),{done:!0}),l=m=>(p(m),{done:!0});if(i={[Symbol.asyncIterator](){return this},next:c,return:y,throw:l,push:h,end:p,get readableLength(){return n.size},onEmpty:async m=>{let g=m?.signal;if(g?.throwIfAborted(),n.isEmpty())return;let x,b;g!=null&&(x=new Promise((v,w)=>{b=()=>{w(new Gp)},g.addEventListener("abort",b)}));try{await Promise.race([a.promise,x])}finally{b!=null&&g!=null&&g?.removeEventListener("abort",b)}}},r==null)return i;let d=i;return i={[Symbol.asyncIterator](){return this},next(){return d.next()},throw(m){return d.throw(m),r!=null&&(r(m),r=void 0),{done:!0}},return(){return d.return(),r!=null&&(r(),r=void 0),{done:!0}},push:h,end(m){return d.end(m),r!=null&&(r(m),r=void 0),i},get readableLength(){return d.readableLength},onEmpty:m=>d.onEmpty(m)},i}function sP(t){return t[Symbol.asyncIterator]!=null}function aP(...t){let e=[];for(let r of t)sP(r)||e.push(r);return e.length===t.length?function*(){for(let r of e)yield*r}():async function*(){let r=nE({objectMode:!0});Promise.resolve().then(async()=>{try{await Promise.all(t.map(async n=>{for await(let i of n)r.push(i)})),r.end()}catch(n){r.end(n)}}),yield*r}()}var ta=aP;var xu=globalThis.CustomEvent??Event;async function*ra(t,e={}){let r=e.concurrency??1/0;r<1&&(r=1/0);let n=e.ordered==null?!1:e.ordered,i=new EventTarget,o=[],s=De(),a=De(),c=!1,u,f=!1;i.addEventListener("task-complete",()=>{a.resolve()}),Promise.resolve().then(async()=>{try{for await(let l of t){if(o.length===r&&(s=De(),await s.promise),f)break;let d={done:!1};o.push(d),l().then(m=>{d.done=!0,d.ok=!0,d.value=m,i.dispatchEvent(new xu("task-complete"))},m=>{d.done=!0,d.err=m,i.dispatchEvent(new xu("task-complete"))})}c=!0,i.dispatchEvent(new xu("task-complete"))}catch(l){u=l,i.dispatchEvent(new xu("task-complete"))}});function h(){return n?o[0]?.done:!!o.find(l=>l.done)}function*p(){for(;o.length>0&&o[0].done;){let l=o[0];if(o.shift(),l.ok)yield l.value;else throw f=!0,s.resolve(),l.err;s.resolve()}}function*y(){for(;h();)for(let l=0;l<o.length;l++)if(o[l].done){let d=o[l];if(o.splice(l,1),l--,d.ok)yield d.value;else throw f=!0,s.resolve(),d.err;s.resolve()}}for(;;){if(h()||(a=De(),await a.promise),u!=null)throw u;if(n?yield*p():yield*y(),c&&o.length===0)break}}var bu=class{log;routers;started;components;constructor(e,r){this.log=e.logger.forComponent("libp2p:content-routing"),this.routers=r.routers??[],this.started=!1,this.components=e}isStarted(){return this.started}async start(){this.started=!0}async stop(){this.started=!1}async*findProviders(e,r={}){if(this.routers.length===0)throw new _("No content routers available",V.ERR_NO_ROUTERS_AVAILABLE);let n=this,i=new Dt;for await(let o of ra(async function*(){let s=ta(...n.routers.map(a=>a.findProviders(e,r)));for await(let a of s)yield async()=>{if(a.multiaddrs.length===0)try{a=await n.components.peerRouting.findPeer(a.id,{...r,useCache:!1})}catch(c){n.log.error("could not find peer multiaddrs",c);return}return a}}()))o!=null&&o.multiaddrs.length!==0&&(await this.components.peerStore.merge(o.id,{multiaddrs:o.multiaddrs}),!i.has(o.id)&&(i.add(o.id),yield o))}async provide(e,r={}){if(this.routers.length===0)throw new _("No content routers available",V.ERR_NO_ROUTERS_AVAILABLE);await Promise.all(this.routers.map(async n=>{await n.provide(e,r)}))}async put(e,r,n){if(!this.isStarted())throw new _(Mr.NOT_STARTED_YET,V.ERR_NODE_NOT_STARTED);await Promise.all(this.routers.map(async i=>{await i.put(e,r,n)}))}async get(e,r){if(!this.isStarted())throw new _(Mr.NOT_STARTED_YET,V.ERR_NODE_NOT_STARTED);return Promise.any(this.routers.map(async n=>n.get(e,r)))}};var wu=class{log;peerId;peerStore;routers;constructor(e,r){this.log=e.logger.forComponent("libp2p:peer-routing"),this.peerId=e.peerId,this.peerStore=e.peerStore,this.routers=r.routers??[]}async findPeer(e,r){if(this.routers.length===0)throw new _("No peer routers available",V.ERR_NO_ROUTERS_AVAILABLE);if(e.toString()===this.peerId.toString())throw new _("Should not try to find self",V.ERR_FIND_SELF);let n=this,i=ta(...this.routers.map(o=>async function*(){try{yield await o.findPeer(e,r)}catch(s){n.log.error(s)}}()));for await(let o of i)if(o!=null)return await this.peerStore.merge(o.id,{multiaddrs:o.multiaddrs}),o;throw new _(Mr.NOT_FOUND,V.ERR_NOT_FOUND)}async*getClosestPeers(e,r={}){if(this.routers.length===0)throw new _("No peer routers available",V.ERR_NO_ROUTERS_AVAILABLE);let n=this,i=new Dt;for await(let o of ra(async function*(){let s=ta(...n.routers.map(a=>a.getClosestPeers(e,r)));for await(let a of s)yield async()=>{if(a.multiaddrs.length===0)try{a=await n.findPeer(a.id,{...r,useCache:!1})}catch(c){n.log.error("could not find peer multiaddrs",c);return}return a}}()))o!=null&&o.multiaddrs.length!==0&&(await this.peerStore.merge(o.id,{multiaddrs:o.multiaddrs}),!i.has(o.id)&&(i.add(o.id),yield o))}};var Wp=32,Yp=64,vu=class{log;topologies;handlers;components;constructor(e){this.log=e.logger.forComponent("libp2p:registrar"),this.topologies=new Map,this.handlers=new Map,this.components=e,this._onDisconnect=this._onDisconnect.bind(this),this._onPeerUpdate=this._onPeerUpdate.bind(this),this._onPeerIdentify=this._onPeerIdentify.bind(this),this.components.events.addEventListener("peer:disconnect",this._onDisconnect),this.components.events.addEventListener("peer:update",this._onPeerUpdate),this.components.events.addEventListener("peer:identify",this._onPeerIdentify)}getProtocols(){return Array.from(new Set([...this.handlers.keys()])).sort()}getHandler(e){let r=this.handlers.get(e);if(r==null)throw new _(`No handler registered for protocol ${e}`,V.ERR_NO_HANDLER_FOR_PROTOCOL);return r}getTopologies(e){let r=this.topologies.get(e);return r==null?[]:[...r.values()]}async handle(e,r,n){if(this.handlers.has(e))throw new _(`Handler already registered for protocol ${e}`,V.ERR_PROTOCOL_HANDLER_ALREADY_REGISTERED);let i=ru.bind({ignoreUndefined:!0})({maxInboundStreams:Wp,maxOutboundStreams:Yp},n);this.handlers.set(e,{handler:r,options:i}),await this.components.peerStore.merge(this.components.peerId,{protocols:[e]})}async unhandle(e){(Array.isArray(e)?e:[e]).forEach(n=>{this.handlers.delete(n)}),await this.components.peerStore.patch(this.components.peerId,{protocols:this.getProtocols()})}async register(e,r){if(r==null)throw new _("invalid topology",V.ERR_INVALID_PARAMETERS);let n=`${(Math.random()*1e9).toString(36)}${Date.now()}`,i=this.topologies.get(e);return i==null&&(i=new Map,this.topologies.set(e,i)),i.set(n,r),n}unregister(e){for(let[r,n]of this.topologies.entries())n.has(e)&&(n.delete(e),n.size===0&&this.topologies.delete(r))}_onDisconnect(e){let r=e.detail;this.components.peerStore.get(r).then(n=>{for(let i of n.protocols){let o=this.topologies.get(i);if(o!=null)for(let s of o.values())s.onDisconnect?.(r)}}).catch(n=>{n.code!==V.ERR_NOT_FOUND&&this.log.error("could not inform topologies of disconnecting peer %p",r,n)})}_onPeerUpdate(e){let{peer:r,previous:n}=e.detail,i=(n?.protocols??[]).filter(o=>!r.protocols.includes(o));for(let o of i){let s=this.topologies.get(o);if(s!=null)for(let a of s.values())a.onDisconnect?.(r.id)}}_onPeerIdentify(e){let r=e.detail.protocols,n=e.detail.connection,i=e.detail.peerId;for(let o of r){let s=this.topologies.get(o);if(s!=null)for(let a of s.values())n.transient&&a.notifyOnTransient!==!0||a.onConnect?.(i,n)}}};var Qp=class extends Map{metric;constructor(e){super();let{name:r,metrics:n}=e;this.metric=n.registerMetric(r),this.updateComponentMetric()}set(e,r){return super.set(e,r),this.updateComponentMetric(),this}delete(e){let r=super.delete(e);return this.updateComponentMetric(),r}clear(){super.clear(),this.updateComponentMetric()}updateComponentMetric(){this.metric.update(this.size)}};function iE(t){let{name:e,metrics:r}=t,n;return r!=null?n=new Qp({name:e,metrics:r}):n=new Map,n}var Eu=class{log;components;transports;listeners;faultTolerance;started;constructor(e,r={}){this.log=e.logger.forComponent("libp2p:transports"),this.components=e,this.started=!1,this.transports=new Map,this.listeners=iE({name:"libp2p_transport_manager_listeners",metrics:this.components.metrics}),this.faultTolerance=r.faultTolerance??$r.FATAL_ALL}add(e){let r=e[Symbol.toStringTag];if(r==null)throw new _("Transport must have a valid tag",V.ERR_INVALID_KEY);if(this.transports.has(r))throw new _(`There is already a transport with the tag ${r}`,V.ERR_DUPLICATE_TRANSPORT);this.log("adding transport %s",r),this.transports.set(r,e),this.listeners.has(r)||this.listeners.set(r,[])}isStarted(){return this.started}start(){this.started=!0}async afterStart(){let e=this.components.addressManager.getListenAddrs();await this.listen(e)}async stop(){let e=[];for(let[r,n]of this.listeners)for(this.log("closing listeners for %s",r);n.length>0;){let i=n.pop();i!=null&&e.push(i.close())}await Promise.all(e),this.log("all listeners closed");for(let r of this.listeners.keys())this.listeners.set(r,[]);this.started=!1}async dial(e,r){let n=this.transportForMultiaddr(e);if(n==null)throw new _(`No transport available for address ${String(e)}`,V.ERR_TRANSPORT_UNAVAILABLE);try{return await n.dial(e,{...r,upgrader:this.components.upgrader})}catch(i){throw i.code==null&&(i.code=V.ERR_TRANSPORT_DIAL_FAILED),i}}getAddrs(){let e=[];for(let r of this.listeners.values())for(let n of r)e=[...e,...n.getAddrs()];return e}getTransports(){return Array.of(...this.transports.values())}getListeners(){return Array.of(...this.listeners.values()).flat()}transportForMultiaddr(e){for(let r of this.transports.values())if(r.filter([e]).length>0)return r}async listen(e){if(!this.isStarted())throw new _("Not started",V.ERR_NODE_NOT_STARTED);if(e==null||e.length===0){this.log("no addresses were provided for listening, this node is dial only");return}let r=[];for(let[n,i]of this.transports.entries()){let o=i.filter(e),s=[];for(let u of o){this.log("creating listener for %s on %a",n,u);let f=i.createListener({upgrader:this.components.upgrader}),h=this.listeners.get(n)??[];h==null&&(h=[],this.listeners.set(n,h)),h.push(f),f.addEventListener("listening",()=>{this.components.events.safeDispatchEvent("transport:listening",{detail:f})}),f.addEventListener("close",()=>{let p=h.findIndex(y=>y===f);h.splice(p,1),this.components.events.safeDispatchEvent("transport:close",{detail:f})}),s.push(f.listen(u))}if(s.length===0){r.push(n);continue}if((await Promise.allSettled(s)).find(u=>u.status==="fulfilled")==null&&this.faultTolerance!==$r.NO_FATAL)throw new _(`Transport (${n}) could not listen on any available address`,V.ERR_NO_VALID_ADDRESSES)}if(r.length===this.transports.size){let n=`no valid addresses were provided for transports [${r.join(", ")}]`;if(this.faultTolerance===$r.FATAL_ALL)throw new _(n,V.ERR_NO_VALID_ADDRESSES);this.log(`libp2p in dial mode only: ${n}`)}}async remove(e){let r=this.listeners.get(e)??[];this.log.trace("removing transport %s",e);let n=[];for(this.log.trace("closing listeners for %s",e);r.length>0;){let i=r.pop();i!=null&&n.push(i.close())}await Promise.all(n),this.transports.delete(e),this.listeners.delete(e)}async removeAll(){let e=[];for(let r of this.transports.keys())e.push(this.remove(r));await Promise.all(e)}};var tt="/multistream/1.0.0";var Au=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 Su(t,e,r){if(e==null)return t;if(e.aborted)return Promise.reject(new Au(r?.errorMessage,r?.errorCode));let n,i=new Au(r?.errorMessage,r?.errorCode);try{return await Promise.race([t,new Promise((o,s)=>{n=()=>{s(i)},e.addEventListener("abort",n)})])}finally{n!=null&&e.removeEventListener("abort",n)}}var Xp=class{needNext;haveNext;ended;nextResult;constructor(){this.ended=!1,this.needNext=De(),this.haveNext=De()}[Symbol.asyncIterator](){return this}async next(){if(this.nextResult==null&&await this.haveNext.promise,this.nextResult==null)throw new Error("Have next but next was undefined");let e=this.nextResult;return this.nextResult=void 0,this.needNext.resolve(),this.needNext=De(),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,r){await this._push(e,r)}async end(e,r){e!=null?await this.throw(e):await this._push(void 0,r)}async _push(e,r){if(e!=null&&this.ended)throw new Error("Cannot push value onto an ended pushable");this.nextResult!=null&&await this.needNext.promise,e!=null?this.nextResult={done:!1,value:e}:(this.ended=!0,this.nextResult={done:!0,value:void 0}),this.haveNext.resolve(),this.haveNext=De(),await Su(this.needNext.promise,r?.signal,r)}};function oE(){return new Xp}var Cu=class extends Error{code;constructor(e,r){super(e),this.code=r}},jp=class extends Cu{type;constructor(e){super(e,"ABORT_ERR"),this.type="aborted"}};function sE(t,e){let r=oE();t.sink(r).catch(async s=>{await r.end(s)}),t.sink=async s=>{for await(let a of s)await r.push(a);await r.end()};let n=t.source;t.source[Symbol.iterator]!=null?n=t.source[Symbol.iterator]():t.source[Symbol.asyncIterator]!=null&&(n=t.source[Symbol.asyncIterator]());let i=new He;return{read:async(s,a)=>{a?.signal?.throwIfAborted();let c,u=new Promise((f,h)=>{c=()=>{h(new jp("Read aborted"))},a?.signal?.addEventListener("abort",c)});try{if(s==null){let{done:h,value:p}=await Promise.race([n.next(),u]);return h===!0?new He:p}for(;i.byteLength<s;){let{value:h,done:p}=await Promise.race([n.next(),u]);if(p===!0)throw new Cu("unexpected end of input","ERR_UNEXPECTED_EOF");i.append(h)}let f=i.sublist(0,s);return i.consume(s),f}finally{c!=null&&a?.signal?.removeEventListener("abort",c)}},write:async(s,a)=>{a?.signal?.throwIfAborted(),s instanceof Uint8Array?await r.push(s,a):await r.push(s.subarray(),a)},unwrap:()=>{if(i.byteLength>0){let s=t.source;t.source=async function*(){e?.yieldBytes===!1?yield i:yield*i,yield*s}()}return t}}}function Iu(t){return t[Symbol.asyncIterator]!=null}var _u=t=>{let e=at(t),r=it(e);return yt(t,r),_u.bytes=e,r};_u.bytes=0;function ii(t,e){e=e??{};let r=e.lengthEncoder??_u;function*n(i){let o=r(i.byteLength);o instanceof Uint8Array?yield o:yield*o,i instanceof Uint8Array?yield i:yield*i}return Iu(t)?async function*(){for await(let i of t)yield*n(i)}():function*(){for(let i of t)yield*n(i)}()}ii.single=(t,e)=>{e=e??{};let r=e.lengthEncoder??_u;return new He(r(t.byteLength),t)};var No=we(L0(),1);var cP=8,uP=1024*1024*4,oi;(function(t){t[t.LENGTH=0]="LENGTH",t[t.DATA=1]="DATA"})(oi||(oi={}));var Zp=t=>{let e=zt(t);return Zp.bytes=at(e),e};Zp.bytes=0;function Jp(t,e){let r=new He,n=oi.LENGTH,i=-1,o=e?.lengthDecoder??Zp,s=e?.maxLengthLength??cP,a=e?.maxDataLength??uP;function*c(){for(;r.byteLength>0;){if(n===oi.LENGTH)try{if(i=o(r),i<0)throw(0,No.default)(new Error("invalid message length"),"ERR_INVALID_MSG_LENGTH");if(i>a)throw(0,No.default)(new Error("message length too long"),"ERR_MSG_DATA_TOO_LONG");let u=o.bytes;r.consume(u),e?.onLength!=null&&e.onLength(i),n=oi.DATA}catch(u){if(u instanceof RangeError){if(r.byteLength>s)throw(0,No.default)(new Error("message length length too long"),"ERR_MSG_LENGTH_TOO_LONG");break}throw u}if(n===oi.DATA){if(r.byteLength<i)break;let u=r.sublist(0,i);r.consume(i),e?.onData!=null&&e.onData(u),yield u,n=oi.LENGTH}}}return Iu(t)?async function*(){for await(let u of t)r.append(u),yield*c();if(r.byteLength>0)throw(0,No.default)(new Error("unexpected end of input"),"ERR_UNEXPECTED_EOF")}():function*(){for(let u of t)r.append(u),yield*c();if(r.byteLength>0)throw(0,No.default)(new Error("unexpected end of input"),"ERR_UNEXPECTED_EOF")}()}Jp.fromReader=(t,e)=>{let r=1,n=async function*(){for(;;)try{let{done:o,value:s}=await t.next(r);if(o===!0)return;s!=null&&(yield s)}catch(o){if(o.code==="ERR_UNDER_READ")return{done:!0,value:null};throw o}finally{r=1}}();return Jp(n,{...e??{},onLength:o=>{r=o}})};var Tu=class extends Error{code;constructor(e,r){super(e),this.code=r}},aE=t=>zt(t);aE.bytes=0;function na(t,e={}){let r=sE(t,e);return e.maxDataLength!=null&&e.maxLengthLength==null&&(e.maxLengthLength=at(e.maxDataLength)),{read:async i=>{let o=-1,s=new He,a=e?.lengthDecoder??aE;for(;;){s.append(await r.read(1,i));try{o=a(s)}catch(c){if(c instanceof RangeError)continue;throw c}if(e?.maxLengthLength!=null&&s.byteLength>e.maxLengthLength)throw new Tu("message length length too long","ERR_MSG_LENGTH_TOO_LONG");if(o>-1)break}if(e?.maxDataLength!=null&&o>e.maxDataLength)throw new Tu("message length too long","ERR_MSG_DATA_TOO_LONG");return r.read(o,i)},write:async(i,o)=>{await r.write(ii.single(i,e),o)},writeV:async(i,o)=>{let s=new He(...i.map(a=>ii.single(a,e)));await r.write(s,o)},unwrap:()=>r.unwrap()}}function Ru(t){return globalThis.Buffer!=null?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):t}var im={};R(im,{base10:()=>yP});function lP(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 i=0;i<t.length;i++){var o=t.charAt(i),s=o.charCodeAt(0);if(r[s]!==255)throw new TypeError(o+" is ambiguous");r[s]=i}var a=t.length,c=t.charAt(0),u=Math.log(a)/Math.log(256),f=Math.log(256)/Math.log(a);function h(l){if(l instanceof Uint8Array||(ArrayBuffer.isView(l)?l=new Uint8Array(l.buffer,l.byteOffset,l.byteLength):Array.isArray(l)&&(l=Uint8Array.from(l))),!(l instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(l.length===0)return"";for(var d=0,m=0,g=0,x=l.length;g!==x&&l[g]===0;)g++,d++;for(var b=(x-g)*f+1>>>0,v=new Uint8Array(b);g!==x;){for(var w=l[g],E=0,A=b-1;(w!==0||E<m)&&A!==-1;A--,E++)w+=256*v[A]>>>0,v[A]=w%a>>>0,w=w/a>>>0;if(w!==0)throw new Error("Non-zero carry");m=E,g++}for(var C=b-m;C!==b&&v[C]===0;)C++;for(var P=c.repeat(d);C<b;++C)P+=t.charAt(v[C]);return P}function p(l){if(typeof l!="string")throw new TypeError("Expected String");if(l.length===0)return new Uint8Array;var d=0;if(l[d]!==" "){for(var m=0,g=0;l[d]===c;)m++,d++;for(var x=(l.length-d)*u+1>>>0,b=new Uint8Array(x);l[d];){var v=r[l.charCodeAt(d)];if(v===255)return;for(var w=0,E=x-1;(v!==0||w<g)&&E!==-1;E--,w++)v+=a*b[E]>>>0,b[E]=v%256>>>0,v=v/256>>>0;if(v!==0)throw new Error("Non-zero carry");g=w,d++}if(l[d]!==" "){for(var A=x-g;A!==x&&b[A]===0;)A++;for(var C=new Uint8Array(m+(x-A)),P=m;A!==x;)C[P++]=b[A++];return C}}}function y(l){var d=p(l);if(d)return d;throw new Error(`Non-${e} character`)}return{encode:h,decodeUnsafe:p,decode:y}}var hP=lP,dP=hP,cE=dP;var _Z=new Uint8Array(0);var uE=(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},Fr=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")};var fE=t=>new TextEncoder().encode(t),lE=t=>new TextDecoder().decode(t);var em=class{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")}},tm=class{constructor(e,r,n){if(this.name=e,this.prefix=r,r.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=r.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 dE(this,e)}},rm=class{constructor(e){this.decoders=e}or(e){return dE(this,e)}decode(e){let r=e[0],n=this.decoders[r];if(n)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}},dE=(t,e)=>new rm({...t.decoders||{[t.prefix]:t},...e.decoders||{[e.prefix]:e}}),nm=class{constructor(e,r,n,i){this.name=e,this.prefix=r,this.baseEncode=n,this.baseDecode=i,this.encoder=new em(e,r,n),this.decoder=new tm(e,r,i)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}},Po=({name:t,prefix:e,encode:r,decode:n})=>new nm(t,e,r,n),mn=({prefix:t,name:e,alphabet:r})=>{let{encode:n,decode:i}=cE(r,e);return Po({prefix:t,name:e,encode:n,decode:o=>Fr(i(o))})},pP=(t,e,r,n)=>{let i={};for(let f=0;f<e.length;++f)i[e[f]]=f;let o=t.length;for(;t[o-1]==="=";)--o;let s=new Uint8Array(o*r/8|0),a=0,c=0,u=0;for(let f=0;f<o;++f){let h=i[t[f]];if(h===void 0)throw new SyntaxError(`Non-${n} character`);c=c<<r|h,a+=r,a>=8&&(a-=8,s[u++]=255&c>>a)}if(a>=r||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return s},mP=(t,e,r)=>{let n=e[e.length-1]==="=",i=(1<<r)-1,o="",s=0,a=0;for(let c=0;c<t.length;++c)for(a=a<<8|t[c],s+=8;s>r;)s-=r,o+=e[i&a>>s];if(s&&(o+=e[i&a<<r-s]),n)for(;o.length*r&7;)o+="=";return o},Le=({name:t,prefix:e,bitsPerChar:r,alphabet:n})=>Po({prefix:e,name:t,encode(i){return mP(i,n,r)},decode(i){return pP(i,n,r,t)}});var yP=mn({prefix:"9",name:"base10",alphabet:"0123456789"});var om={};R(om,{base16:()=>gP,base16upper:()=>xP});var gP=Le({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),xP=Le({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var sm={};R(sm,{base2:()=>bP});var bP=Le({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var am={};R(am,{base256emoji:()=>SP});var pE=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}"),wP=pE.reduce((t,e,r)=>(t[r]=e,t),[]),vP=pE.reduce((t,e,r)=>(t[e.codePointAt(0)]=r,t),[]);function EP(t){return t.reduce((e,r)=>(e+=wP[r],e),"")}function AP(t){let e=[];for(let r of t){let n=vP[r.codePointAt(0)];if(n===void 0)throw new Error(`Non-base256emoji character: ${r}`);e.push(n)}return new Uint8Array(e)}var SP=Po({prefix:"\u{1F680}",name:"base256emoji",encode:EP,decode:AP});var cm={};R(cm,{base32:()=>Oo,base32hex:()=>TP,base32hexpad:()=>BP,base32hexpadupper:()=>DP,base32hexupper:()=>RP,base32pad:()=>IP,base32padupper:()=>_P,base32upper:()=>CP,base32z:()=>LP});var Oo=Le({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),CP=Le({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),IP=Le({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),_P=Le({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),TP=Le({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),RP=Le({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),BP=Le({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),DP=Le({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),LP=Le({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var um={};R(um,{base36:()=>NP,base36upper:()=>PP});var NP=mn({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),PP=mn({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var fm={};R(fm,{base58btc:()=>lr,base58flickr:()=>OP});var lr=mn({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),OP=mn({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var lm={};R(lm,{base64:()=>kP,base64pad:()=>UP,base64url:()=>MP,base64urlpad:()=>FP});var kP=Le({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),UP=Le({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),MP=Le({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),FP=Le({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var hm={};R(hm,{base8:()=>KP});var KP=Le({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var dm={};R(dm,{identity:()=>VP});var VP=Po({prefix:"\0",name:"identity",encode:t=>lE(t),decode:t=>fE(t)});var qZ=new TextEncoder,zZ=new TextDecoder;var mm={};R(mm,{identity:()=>fO});var $P=gE,mE=128,HP=127,GP=~HP,WP=Math.pow(2,31);function gE(t,e,r){e=e||[],r=r||0;for(var n=r;t>=WP;)e[r++]=t&255|mE,t/=128;for(;t&GP;)e[r++]=t&255|mE,t>>>=7;return e[r]=t|0,gE.bytes=r-n+1,e}var YP=pm,QP=128,yE=127;function pm(t,n){var r=0,n=n||0,i=0,o=n,s,a=t.length;do{if(o>=a)throw pm.bytes=0,new RangeError("Could not decode varint");s=t[o++],r+=i<28?(s&yE)<<i:(s&yE)*Math.pow(2,i),i+=7}while(s>=QP);return pm.bytes=o-n,r}var XP=Math.pow(2,7),jP=Math.pow(2,14),JP=Math.pow(2,21),ZP=Math.pow(2,28),eO=Math.pow(2,35),tO=Math.pow(2,42),rO=Math.pow(2,49),nO=Math.pow(2,56),iO=Math.pow(2,63),oO=function(t){return t<XP?1:t<jP?2:t<JP?3:t<ZP?4:t<eO?5:t<tO?6:t<rO?7:t<nO?8:t<iO?9:10},sO={encode:$P,decode:YP,encodingLength:oO},aO=sO,ia=aO;var oa=(t,e=0)=>[ia.decode(t,e),ia.decode.bytes],ko=(t,e,r=0)=>(ia.encode(t,e,r),e),Uo=t=>ia.encodingLength(t);var si=(t,e)=>{let r=e.byteLength,n=Uo(t),i=n+Uo(r),o=new Uint8Array(i+r);return ko(t,o,0),ko(r,o,n),o.set(e,i),new Mo(t,r,e,o)},xE=t=>{let e=Fr(t),[r,n]=oa(e),[i,o]=oa(e.subarray(n)),s=e.subarray(n+o);if(s.byteLength!==i)throw new Error("Incorrect length");return new Mo(r,i,s,e)},bE=(t,e)=>{if(t===e)return!0;{let r=e;return t.code===r.code&&t.size===r.size&&r.bytes instanceof Uint8Array&&uE(t.bytes,r.bytes)}},Mo=class{constructor(e,r,n,i){this.code=e,this.size=r,this.digest=n,this.bytes=i}};var wE=0,cO="identity",vE=Fr,uO=t=>si(wE,vE(t)),fO={code:wE,name:cO,encode:vE,digest:uO};var xm={};R(xm,{sha256:()=>lO,sha512:()=>hO});var gm=({name:t,code:e,encode:r})=>new ym(t,e,r),ym=class{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?si(this.code,r):r.then(n=>si(this.code,n))}else throw Error("Unknown type, must be binary type")}};var AE=t=>async e=>new Uint8Array(await crypto.subtle.digest(t,e)),lO=gm({name:"sha2-256",code:18,encode:AE("SHA-256")}),hO=gm({name:"sha2-512",code:19,encode:AE("SHA-512")});var SE=(t,e)=>{let{bytes:r,version:n}=t;switch(n){case 0:return pO(r,bm(t),e||lr.encoder);default:return mO(r,bm(t),e||Oo.encoder)}};var CE=new WeakMap,bm=t=>{let e=CE.get(t);if(e==null){let r=new Map;return CE.set(t,r),r}return e},Du=class t{constructor(e,r,n,i){this.code=r,this.version=e,this.multihash=n,this.bytes=i,this["/"]=i}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!==aa)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=si(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&&e.code===n.code&&e.version===n.version&&bE(e.multihash,n.multihash)}toString(e){return SE(this,e)}toJSON(){return{"/":SE(this)}}link(){return this}get[Symbol.toStringTag](){return"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:i,multihash:o,bytes:s}=r;return new t(n,i,o,s||IE(n,i,o.bytes))}else if(r[gO]===!0){let{version:n,multihash:i,code:o}=r,s=xE(i);return t.create(n,o,s)}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!==aa)throw new Error(`Version 0 CID must use dag-pb (code: ${aa}) block encoding`);return new t(e,r,n,n.bytes)}case 1:{let i=IE(e,r,n.bytes);return new t(e,r,n,i)}default:throw new Error("Invalid version")}}static createV0(e){return t.create(0,aa,e)}static createV1(e,r){return t.create(1,e,r)}static decode(e){let[r,n]=t.decodeFirst(e);if(n.length)throw new Error("Incorrect length");return r}static decodeFirst(e){let r=t.inspectBytes(e),n=r.size-r.multihashSize,i=Fr(e.subarray(n,n+r.multihashSize));if(i.byteLength!==r.multihashSize)throw new Error("Incorrect length");let o=i.subarray(r.multihashSize-r.digestSize),s=new Mo(r.multihashCode,r.digestSize,o,i);return[r.version===0?t.createV0(s):t.createV1(r.codec,s),e.subarray(r.size)]}static inspectBytes(e){let r=0,n=()=>{let[h,p]=oa(e.subarray(r));return r+=p,h},i=n(),o=aa;if(i===18?(i=0,r=0):o=n(),i!==0&&i!==1)throw new RangeError(`Invalid CID version ${i}`);let s=r,a=n(),c=n(),u=r+c,f=u-s;return{version:i,codec:o,multihashCode:a,digestSize:c,multihashSize:f,size:u}}static parse(e,r){let[n,i]=dO(e,r),o=t.decode(i);if(o.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return bm(o).set(n,e),o}},dO=(t,e)=>{switch(t[0]){case"Q":{let r=e||lr;return[lr.prefix,r.decode(`${lr.prefix}${t}`)]}case lr.prefix:{let r=e||lr;return[lr.prefix,r.decode(t)]}case Oo.prefix:{let r=e||Oo;return[Oo.prefix,r.decode(t)]}default:{if(e==null)throw Error("To parse non base32 or base58btc encoded CID multibase decoder must be provided");return[t[0],e.decode(t)]}}},pO=(t,e,r)=>{let{prefix:n}=r;if(n!==lr.prefix)throw Error(`Cannot string encode V0 in ${r.name} encoding`);let i=e.get(n);if(i==null){let o=r.encode(t).slice(1);return e.set(n,o),o}else return i},mO=(t,e,r)=>{let{prefix:n}=r,i=e.get(n);if(i==null){let o=r.encode(t);return e.set(n,o),o}else return i},aa=112,yO=18,IE=(t,e,r)=>{let n=Uo(t),i=n+Uo(e),o=new Uint8Array(i+r.byteLength);return ko(t,o,0),ko(e,o,n),o.set(r,i),o},gO=Symbol.for("@ipld/js-cid/CID");var wm={...dm,...sm,...hm,...im,...om,...cm,...um,...fm,...lm,...am},oee={...xm,...mm};function _E(t=0){return globalThis.Buffer?.allocUnsafe!=null?Ru(globalThis.Buffer.allocUnsafe(t)):new Uint8Array(t)}function RE(t,e,r,n){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:r},decoder:{decode:n}}}var TE=RE("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),vm=RE("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=_E(t.length);for(let r=0;r<t.length;r++)e[r]=t.charCodeAt(r);return e}),xO={utf8:TE,"utf-8":TE,hex:wm.base16,latin1:vm,ascii:vm,binary:vm,...wm},Lu=xO;function ut(t,e="utf8"){let r=Lu[e];if(r==null)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?Ru(globalThis.Buffer.from(t,"utf-8")):r.decoder.decode(`${r.prefix}${t}`)}function BE(t,e="utf8"){let r=Lu[e];if(r==null)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?globalThis.Buffer.from(t.buffer,t.byteOffset,t.byteLength).toString("utf8"):r.encoder.encode(t).substring(1)}var bO=ut(`
49
- `);async function ai(t,e,r){await t.write(e,r)}async function DE(t,e,r){await t.writeV(e,r)}async function wO(t,e){let r=await t.read(e);if(r.byteLength===0||r.get(r.byteLength-1)!==bO[0])throw e.log.error("Invalid mss message - missing newline",r),new _("missing newline","ERR_INVALID_MULTISTREAM_SELECT_MESSAGE");return r.sublist(0,-1)}async function yn(t,e){let r=await wO(t,e);return BE(r.subarray())}async function ca(t,e,r){if(e=Array.isArray(e)?[...e]:[e],e.length===1)return vO(t,e[0],r);let n=na(t,{...r,maxDataLength:1024}),i=e.shift();if(i==null)throw new Error("At least one protocol must be specified");r.log.trace('select: write ["%s", "%s"]',tt,i);let o=ut(`${tt}
49
+ `);async function ai(t,e,r){await t.write(e,r)}async function DE(t,e,r){await t.writeV(e,r)}async function wO(t,e){let r=await t.read(e);if(r.byteLength===0||r.get(r.byteLength-1)!==bO[0])throw e.log.error("Invalid mss message - missing newline",r),new _("missing newline","ERR_INVALID_MULTISTREAM_SELECT_MESSAGE");return r.sublist(0,-1)}async function yn(t,e){let r=await wO(t,e);return BE(r.subarray())}async function ca(t,e,r){if(e=Array.isArray(e)?[...e]:[e],e.length===1&&r.negotiateFully===!1)return vO(t,e[0],r);let n=na(t,{...r,maxDataLength:1024}),i=e.shift();if(i==null)throw new Error("At least one protocol must be specified");r.log.trace('select: write ["%s", "%s"]',tt,i);let o=ut(`${tt}
50
50
  `),s=ut(`${i}
51
51
  `);await DE(n,[o,s],r),r.log.trace("select: reading multistream-select header");let a=await yn(n,r);if(r.log.trace('select: read "%s"',a),a===tt&&(r.log.trace("select: reading protocol response"),a=await yn(n,r),r.log.trace('select: read "%s"',a)),a===i)return{stream:n.unwrap(),protocol:i};for(let c of e){r.log.trace('select: write "%s"',c),await ai(n,ut(`${c}
52
52
  `),r),r.log.trace("select: reading protocol response");let u=await yn(n,r);if(r.log.trace('select: read "%s" for "%s"',u,c),u===c)return{stream:n.unwrap(),protocol:c}}throw new _("protocol selection failed","ERR_UNSUPPORTED_PROTOCOL")}function vO(t,e,r){let n=t.sink.bind(t),i=t.source,o=!1,s=!1,a=De(),c=!1,u=!1,f=De(),h=!1,p=!1,y=De(),l=na({sink:n,source:i},{...r,maxDataLength:1024});t.sink=async x=>{let{sink:b}=l.unwrap();await b(async function*(){let v=!1;for await(let w of x){if(u&&await f.promise,c)yield w;else{u=!0,r.log.trace('optimistic: write ["%s", "%s", data(%d)] in sink',tt,e,w.byteLength);let E=`${e}
@@ -58,7 +58,7 @@
58
58
  `),r),r.log.trace('handle: responded with "%s" for "%s"',i,i),{stream:n.unwrap(),protocol:i};if(i==="ls"){let o=new He(...e.map(s=>ii.single(ut(`${s}
59
59
  `))),ut(`
60
60
  `));r.log.trace('handle: respond with "%s" for %s',e,i),await ai(n,o,r),r.log.trace('handle: responded with "%s" for %s',e,i);continue}r.log('handle: respond with "na" for "%s"',i),await ai(n,ut(`na
61
- `),r),r.log('handle: responded with "na" for "%s"',i)}}var AO=500,Em=class{id;remoteAddr;remotePeer;direction;timeline;multiplexer;encryption;status;transient;log;tags;_newStream;_close;_abort;_getStreams;constructor(e){let{remoteAddr:r,remotePeer:n,newStream:i,close:o,abort:s,getStreams:a}=e;this.id=`${parseInt(String(Math.random()*1e9)).toString(36)}${Date.now()}`,this.remoteAddr=r,this.remotePeer=n,this.direction=e.direction,this.status="open",this.timeline=e.timeline,this.multiplexer=e.multiplexer,this.encryption=e.encryption,this.transient=e.transient??!1,this.log=e.logger.forComponent(`libp2p:connection:${this.direction}:${this.id}`),this.remoteAddr.getPeerId()==null&&(this.remoteAddr=this.remoteAddr.encapsulate(`/p2p/${this.remotePeer}`)),this._newStream=i,this._close=o,this._abort=s,this._getStreams=a,this.tags=[]}[Symbol.toStringTag]="Connection";[Qy]=!0;get streams(){return this._getStreams()}async newStream(e,r){if(this.status==="closing")throw new _("the connection is being closed","ERR_CONNECTION_BEING_CLOSED");if(this.status==="closed")throw new _("the connection is closed","ERR_CONNECTION_CLOSED");if(Array.isArray(e)||(e=[e]),this.transient&&r?.runOnTransientConnection!==!0)throw new _("Cannot open protocol stream on transient connection","ERR_TRANSIENT_CONNECTION");let n=await this._newStream(e,r);return n.direction="outbound",n}async close(e={}){if(!(this.status==="closed"||this.status==="closing")){if(this.log("closing connection to %a",this.remoteAddr),this.status="closing",e.signal==null){let r=AbortSignal.timeout(AO);wt(1/0,r),e={...e,signal:r}}try{this.log.trace("closing all streams"),await Promise.all(this.streams.map(async r=>r.close(e))),this.log.trace("closing underlying transport"),await this._close(e),this.log.trace("updating timeline with close time"),this.status="closed",this.timeline.close=Date.now()}catch(r){this.log.error("error encountered during graceful close of connection to %a",this.remoteAddr,r),this.abort(r)}}}abort(e){this.log.error("aborting connection to %a due to error",this.remoteAddr,e),this.status="closing",this.streams.forEach(r=>{r.abort(e)}),this.log.error("all streams aborted",this.streams.length),this._abort(e),this.timeline.close=Date.now(),this.status="closed"}};function NE(t){return new Em(t)}var CO=3e4;function IO(t,e){try{let{options:r}=e.getHandler(t);return r.maxInboundStreams}catch(r){if(r.code!==V.ERR_NO_HANDLER_FOR_PROTOCOL)throw r}return Wp}function _O(t,e,r={}){try{let{options:n}=e.getHandler(t);if(n.maxOutboundStreams!=null)return n.maxOutboundStreams}catch(n){if(n.code!==V.ERR_NO_HANDLER_FOR_PROTOCOL)throw n}return r.maxOutboundStreams??Yp}function PE(t,e,r){let n=0;return r.streams.forEach(i=>{i.direction===e&&i.protocol===t&&n++}),n}var Pu=class{components;connectionEncryption;muxers;inboundUpgradeTimeout;events;constructor(e,r){this.components=e,this.connectionEncryption=new Map,r.connectionEncryption.forEach(n=>{this.connectionEncryption.set(n.protocol,n)}),this.muxers=new Map,r.muxers.forEach(n=>{this.muxers.set(n.protocol,n)}),this.inboundUpgradeTimeout=r.inboundUpgradeTimeout??3e4,this.events=e.events}async shouldBlockConnection(e,r,n){let i=this.components.connectionGater[n];if(i!==void 0&&await i(e,r))throw new _(`The multiaddr connection is blocked by gater.${n}`,V.ERR_CONNECTION_INTERCEPTED)}async upgradeInbound(e,r){if(!await this.components.connectionManager.acceptIncomingConnection(e))throw new _("connection denied",V.ERR_CONNECTION_DENIED);let i,o,s,a,c,u=AbortSignal.timeout(this.inboundUpgradeTimeout),f=()=>{e.abort(new _("inbound upgrade timeout",Ra))};u.addEventListener("abort",f,{once:!0}),wt(1/0,u);try{if(await this.components.connectionGater.denyInboundConnection?.(e)===!0)throw new _("The multiaddr connection is blocked by gater.acceptConnection",V.ERR_CONNECTION_INTERCEPTED);this.components.metrics?.trackMultiaddrConnection(e),e.log("starting the inbound connection upgrade");let h=e;if(r?.skipProtection!==!0){let p=this.components.connectionProtector;p!=null&&(e.log("protecting the inbound connection"),h=await p.protect(e))}try{if(i=h,r?.skipEncryption!==!0){({conn:i,remotePeer:o,protocol:c}=await this._encryptInbound(h));let p={...h,...i};await this.shouldBlockConnection(o,p,"denyInboundEncryptedConnection")}else{let p=e.remoteAddr.getPeerId();if(p==null)throw new _("inbound connection that skipped encryption must have a peer id",V.ERR_INVALID_MULTIADDR);let y=se(p);c="native",o=y}if(s=i,r?.muxerFactory!=null)a=r.muxerFactory;else if(this.muxers.size>0){let p=await this._multiplexInbound({...h,...i},this.muxers);a=p.muxerFactory,s=p.stream}}catch(p){throw e.log.error("failed to upgrade inbound connection",p),p}return await this.shouldBlockConnection(o,e,"denyInboundUpgradedConnection"),e.log("successfully upgraded inbound connection"),this._createConnection({cryptoProtocol:c,direction:"inbound",maConn:e,upgradedConn:s,muxerFactory:a,remotePeer:o,transient:r?.transient})}finally{u.removeEventListener("abort",f),this.components.connectionManager.afterUpgradeInbound()}}async upgradeOutbound(e,r){let n=e.remoteAddr.getPeerId(),i;n!=null&&(i=se(n),await this.shouldBlockConnection(i,e,"denyOutboundConnection"));let o,s,a,c,u;this.components.metrics?.trackMultiaddrConnection(e),e.log("starting the outbound connection upgrade");let f=e;if(r?.skipProtection!==!0){let h=this.components.connectionProtector;h!=null&&(f=await h.protect(e))}try{if(o=f,r?.skipEncryption!==!0){({conn:o,remotePeer:s,protocol:c}=await this._encryptOutbound(f,i));let h={...f,...o};await this.shouldBlockConnection(s,h,"denyOutboundEncryptedConnection")}else{if(i==null)throw new _("Encryption was skipped but no peer id was passed",V.ERR_INVALID_PEER);c="native",s=i}if(a=o,r?.muxerFactory!=null)u=r.muxerFactory;else if(this.muxers.size>0){let h=await this._multiplexOutbound({...f,...o},this.muxers);u=h.muxerFactory,a=h.stream}}catch(h){throw e.log.error("failed to upgrade outbound connection",h),await e.close(h),h}return await this.shouldBlockConnection(s,e,"denyOutboundUpgradedConnection"),e.log("successfully upgraded outbound connection"),this._createConnection({cryptoProtocol:c,direction:"outbound",maConn:e,upgradedConn:a,muxerFactory:u,remotePeer:s,transient:r?.transient})}_createConnection(e){let{cryptoProtocol:r,direction:n,maConn:i,upgradedConn:o,remotePeer:s,muxerFactory:a,transient:c}=e,u,f,h;a!=null&&(u=a.createStreamMuxer({direction:n,onIncomingStream:l=>{h!=null&&Promise.resolve().then(async()=>{let d=this.components.registrar.getProtocols(),{stream:m,protocol:g}=await ua(l,d,{log:l.log,yieldBytes:!1});if(h==null)return;h.log("incoming stream opened on %s",g);let x=IO(g,this.components.registrar);if(PE(g,"inbound",h)===x){let v=new _(`Too many inbound protocol streams for protocol "${g}" - limit ${x}`,V.ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS);throw l.abort(v),v}l.source=m.source,l.sink=m.sink,l.protocol=g,m.closeWrite!=null&&(l.closeWrite=m.closeWrite),m.closeRead!=null&&(l.closeRead=m.closeRead),m.close!=null&&(l.close=m.close),await this.components.peerStore.merge(s,{protocols:[g]}),this.components.metrics?.trackProtocolStream(l,h),this._onStream({connection:h,stream:l,protocol:g})}).catch(async d=>{h.log.error("error handling incoming stream id %s",l.id,d.message,d.code,d.stack),l.timeline.close==null&&await l.close()})}}),f=async(l,d={})=>{if(u==null)throw new _("Stream is not multiplexed",V.ERR_MUXER_UNAVAILABLE);h.log("starting new stream for protocols %s",l);let m=await u.newStream();h.log.trace("started new stream %s for protocols %s",m.id,l);try{if(d.signal==null){m.log("no abort signal was passed while trying to negotiate protocols %s falling back to default timeout",l);let w=AbortSignal.timeout(CO);wt(1/0,w),d={...d,signal:w}}m.log.trace("selecting protocol from protocols %s",l);let{stream:g,protocol:x}=await ca(m,l,{...d,log:m.log,yieldBytes:!0});m.log("selected protocol %s",x);let b=_O(x,this.components.registrar,d);if(PE(x,"outbound",h)>=b){let w=new _(`Too many outbound protocol streams for protocol "${x}" - limit ${b}`,V.ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS);throw m.abort(w),w}return await this.components.peerStore.merge(s,{protocols:[x]}),m.source=g.source,m.sink=g.sink,m.protocol=x,g.closeWrite!=null&&(m.closeWrite=g.closeWrite),g.closeRead!=null&&(m.closeRead=g.closeRead),g.close!=null&&(m.close=g.close),this.components.metrics?.trackProtocolStream(m,h),m}catch(g){throw h.log.error("could not create new stream for protocols %s",l,g),m.timeline.close==null&&m.abort(g),g.code!=null?g:new _(String(g),V.ERR_UNSUPPORTED_PROTOCOL)}},Promise.all([u.sink(o.source),o.sink(u.source)]).catch(l=>{h.log.error("error piping data through muxer",l)}));let p=i.timeline;i.timeline=new Proxy(p,{set:(...l)=>(h!=null&&l[1]==="close"&&l[2]!=null&&p.close==null&&(async()=>{try{h.status==="open"&&await h.close()}catch(d){h.log.error("error closing connection after timeline close",d)}finally{this.events.safeDispatchEvent("connection:close",{detail:h})}})().catch(d=>{h.log.error("error thrown while dispatching connection:close event",d)}),Reflect.set(...l))}),i.timeline.upgraded=Date.now();let y=()=>{throw new _("connection is not multiplexed",V.ERR_CONNECTION_NOT_MULTIPLEXED)};return h=NE({remoteAddr:i.remoteAddr,remotePeer:s,status:"open",direction:n,timeline:i.timeline,multiplexer:u?.protocol,encryption:r,transient:c,logger:this.components.logger,newStream:f??y,getStreams:()=>u!=null?u.streams:[],close:async l=>{u!=null&&(h.log.trace("close muxer"),await u.close(l)),h.log.trace("close maconn"),await i.close(l),h.log.trace("closed maconn")},abort:l=>{i.abort(l),u?.abort(l)}}),this.events.safeDispatchEvent("connection:open",{detail:h}),h}_onStream(e){let{connection:r,stream:n,protocol:i}=e,{handler:o,options:s}=this.components.registrar.getHandler(i);if(r.transient&&s.runOnTransientConnection!==!0)throw new _("Cannot open protocol stream on transient connection","ERR_TRANSIENT_CONNECTION");o({connection:r,stream:n})}async _encryptInbound(e){let r=Array.from(this.connectionEncryption.keys());e.log("handling inbound crypto protocol selection",r);try{let{stream:n,protocol:i}=await ua(e,r,{log:e.log}),o=this.connectionEncryption.get(i);if(o==null)throw new Error(`no crypto module found for ${i}`);return e.log("encrypting inbound connection using",i),{...await o.secureInbound(this.components.peerId,n),protocol:i}}catch(n){throw e.log.error("encrypting inbound connection to %p failed",n),new _(n.message,V.ERR_ENCRYPTION_FAILED)}}async _encryptOutbound(e,r){let n=Array.from(this.connectionEncryption.keys());e.log("selecting outbound crypto protocol",n);try{e.log.trace("selecting encrypter from %s",n);let{stream:i,protocol:o}=await ca(e,n,{log:e.log,yieldBytes:!0}),s=this.connectionEncryption.get(o);if(s==null)throw new Error(`no crypto module found for ${o}`);return e.log("encrypting outbound connection to %p using %p",r),{...await s.secureOutbound(this.components.peerId,i,r),protocol:o}}catch(i){throw e.log.error("encrypting outbound connection to %p failed",i),new _(i.message,V.ERR_ENCRYPTION_FAILED)}}async _multiplexOutbound(e,r){let n=Array.from(r.keys());e.log("outbound selecting muxer %s",n);try{e.log.trace("selecting stream muxer from %s",n);let{stream:i,protocol:o}=await ca(e,n,{log:e.log,yieldBytes:!0});e.log("selected %s as muxer protocol",o);let s=r.get(o);return{stream:i,muxerFactory:s}}catch(i){throw e.log.error("error multiplexing outbound connection",i),new _(String(i),V.ERR_MUXER_UNAVAILABLE)}}async _multiplexInbound(e,r){let n=Array.from(r.keys());e.log("inbound handling muxers %s",n);try{let{stream:i,protocol:o}=await ua(e,n,{log:e.log}),s=r.get(o);return{stream:i,muxerFactory:s}}catch(i){throw e.log.error("error multiplexing inbound connection",i),new _(String(i),V.ERR_MUXER_UNAVAILABLE)}}};var OE="1.0.12-4e0135c7d",kE="libp2p";var Am=class extends Wo{peerId;peerStore;contentRouting;peerRouting;metrics;services;logger;status;components;log;constructor(e){super(),this.status="stopped";let r=new Wo,n=r.dispatchEvent.bind(r);r.dispatchEvent=a=>{let c=n(a),u=this.dispatchEvent(new lf(a.type,{detail:a.detail}));return c||u},wt(1/0,r),this.peerId=e.peerId,this.logger=e.logger??oc(),this.log=this.logger.forComponent("libp2p"),this.services={};let i=this.components=p2({peerId:e.peerId,nodeInfo:e.nodeInfo??{name:kE,version:OE},logger:this.logger,events:r,datastore:e.datastore??new Mc,connectionGater:S2(e.connectionGater)});this.peerStore=this.configureComponent("peerStore",new kc(i,{addressFilter:this.components.connectionGater.filterMultiaddrForPeer,...e.peerStore})),e.metrics!=null&&(this.metrics=this.configureComponent("metrics",e.metrics(this.components))),i.events.addEventListener("peer:update",a=>{if(a.detail.previous==null){let c={id:a.detail.peer.id,multiaddrs:a.detail.peer.addresses.map(u=>u.multiaddr)};i.events.safeDispatchEvent("peer:discovery",{detail:c})}}),e.connectionProtector!=null&&this.configureComponent("connectionProtector",e.connectionProtector(i)),this.components.upgrader=new Pu(this.components,{connectionEncryption:(e.connectionEncryption??[]).map((a,c)=>this.configureComponent(`connection-encryption-${c}`,a(this.components))),muxers:(e.streamMuxers??[]).map((a,c)=>this.configureComponent(`stream-muxers-${c}`,a(this.components))),inboundUpgradeTimeout:e.connectionManager.inboundUpgradeTimeout}),this.configureComponent("transportManager",new Eu(this.components,e.transportManager)),this.configureComponent("connectionManager",new yu(this.components,e.connectionManager)),this.configureComponent("registrar",new vu(this.components)),this.configureComponent("addressManager",new $c(this.components,e.addresses));let o=(e.peerRouters??[]).map((a,c)=>this.configureComponent(`peer-router-${c}`,a(this.components)));this.peerRouting=this.components.peerRouting=this.configureComponent("peerRouting",new wu(this.components,{routers:o}));let s=(e.contentRouters??[]).map((a,c)=>this.configureComponent(`content-router-${c}`,a(this.components)));if(this.contentRouting=this.components.contentRouting=this.configureComponent("contentRouting",new bu(this.components,{routers:s})),(e.peerDiscovery??[]).forEach((a,c)=>{this.configureComponent(`peer-discovery-${c}`,a(this.components)).addEventListener("peer",f=>{this.#e(f)})}),e.transports?.forEach((a,c)=>{this.components.transportManager.add(this.configureComponent(`transport-${c}`,a(this.components)))}),e.services!=null)for(let a of Object.keys(e.services)){let c=e.services[a],u=c(this.components);if(u==null){this.log.error("service factory %s returned null or undefined instance",a);continue}this.services[a]=u,this.configureComponent(a,u),u[of]!=null&&(this.log("registering service %s for content routing",a),s.push(u[of])),u[cf]!=null&&(this.log("registering service %s for peer routing",a),o.push(u[cf])),u[sf]!=null&&(this.log("registering service %s for peer discovery",a),u[sf].addEventListener?.("peer",f=>{this.#e(f)}))}}configureComponent(e,r){return r==null&&this.log.error("component %s was null or undefined",e),this.components[e]=r,r}async start(){if(this.status==="stopped"){this.status="starting",this.log("libp2p is starting");try{await this.components.beforeStart?.(),await this.components.start(),await this.components.afterStart?.(),this.status="started",this.safeDispatchEvent("start",{detail:this}),this.log("libp2p has started")}catch(e){throw this.log.error("An error occurred starting libp2p",e),this.status="started",await this.stop(),e}}}async stop(){this.status==="started"&&(this.log("libp2p is stopping"),this.status="stopping",await this.components.beforeStop?.(),await this.components.stop(),await this.components.afterStop?.(),this.status="stopped",this.safeDispatchEvent("stop",{detail:this}),this.log("libp2p has stopped"))}getConnections(e){return this.components.connectionManager.getConnections(e)}getDialQueue(){return this.components.connectionManager.getDialQueue()}getPeers(){let e=new Dt;for(let r of this.components.connectionManager.getConnections())e.add(r.remotePeer);return Array.from(e)}async dial(e,r={}){return this.components.connectionManager.openConnection(e,{priority:75,...r})}async dialProtocol(e,r,n={}){if(r==null)throw new _("no protocols were provided to open a stream",V.ERR_INVALID_PROTOCOLS_FOR_STREAM);if(r=Array.isArray(r)?r:[r],r.length===0)throw new _("no protocols were provided to open a stream",V.ERR_INVALID_PROTOCOLS_FOR_STREAM);return(await this.dial(e,n)).newStream(r,n)}getMultiaddrs(){return this.components.addressManager.getAddresses()}getProtocols(){return this.components.registrar.getProtocols()}async hangUp(e,r={}){cn(e)&&(e=se(e.getPeerId()??"")),await this.components.connectionManager.closeConnections(e,r)}async getPublicKey(e,r={}){if(this.log("getPublicKey %p",e),e.publicKey!=null)return e.publicKey;let n=await this.peerStore.get(e);if(n.id.publicKey!=null)return n.id.publicKey;let i=H1([zc("/pk/"),e.multihash.digest]),o=await this.contentRouting.get(i,r);return bs(o),await this.peerStore.patch(e,{publicKey:o}),o}async handle(e,r,n){Array.isArray(e)||(e=[e]),await Promise.all(e.map(async i=>{await this.components.registrar.handle(i,r,n)}))}async unhandle(e){Array.isArray(e)||(e=[e]),await Promise.all(e.map(async r=>{await this.components.registrar.unhandle(r)}))}async register(e,r){return this.components.registrar.register(e,r)}unregister(e){this.components.registrar.unregister(e)}#e(e){let{detail:r}=e;if(r.id.toString()===this.peerId.toString()){this.log.error(new Error(V.ERR_DISCOVERED_SELF));return}this.components.peerStore.merge(r.id,{multiaddrs:r.multiaddrs}).catch(n=>{this.log.error(n)})}};async function UE(t={}){return t.peerId??=await Gb(),new Am(tv(t))}async function RO(t={}){let e=await UE(t);return t.start!==!1&&await e.start(),e}return jE(BO);})();
61
+ `),r),r.log('handle: responded with "na" for "%s"',i)}}var AO=500,Em=class{id;remoteAddr;remotePeer;direction;timeline;multiplexer;encryption;status;transient;log;tags;_newStream;_close;_abort;_getStreams;constructor(e){let{remoteAddr:r,remotePeer:n,newStream:i,close:o,abort:s,getStreams:a}=e;this.id=`${parseInt(String(Math.random()*1e9)).toString(36)}${Date.now()}`,this.remoteAddr=r,this.remotePeer=n,this.direction=e.direction,this.status="open",this.timeline=e.timeline,this.multiplexer=e.multiplexer,this.encryption=e.encryption,this.transient=e.transient??!1,this.log=e.logger.forComponent(`libp2p:connection:${this.direction}:${this.id}`),this.remoteAddr.getPeerId()==null&&(this.remoteAddr=this.remoteAddr.encapsulate(`/p2p/${this.remotePeer}`)),this._newStream=i,this._close=o,this._abort=s,this._getStreams=a,this.tags=[]}[Symbol.toStringTag]="Connection";[Qy]=!0;get streams(){return this._getStreams()}async newStream(e,r){if(this.status==="closing")throw new _("the connection is being closed","ERR_CONNECTION_BEING_CLOSED");if(this.status==="closed")throw new _("the connection is closed","ERR_CONNECTION_CLOSED");if(Array.isArray(e)||(e=[e]),this.transient&&r?.runOnTransientConnection!==!0)throw new _("Cannot open protocol stream on transient connection","ERR_TRANSIENT_CONNECTION");let n=await this._newStream(e,r);return n.direction="outbound",n}async close(e={}){if(!(this.status==="closed"||this.status==="closing")){if(this.log("closing connection to %a",this.remoteAddr),this.status="closing",e.signal==null){let r=AbortSignal.timeout(AO);wt(1/0,r),e={...e,signal:r}}try{this.log.trace("closing all streams"),await Promise.all(this.streams.map(async r=>r.close(e))),this.log.trace("closing underlying transport"),await this._close(e),this.log.trace("updating timeline with close time"),this.status="closed",this.timeline.close=Date.now()}catch(r){this.log.error("error encountered during graceful close of connection to %a",this.remoteAddr,r),this.abort(r)}}}abort(e){this.log.error("aborting connection to %a due to error",this.remoteAddr,e),this.status="closing",this.streams.forEach(r=>{r.abort(e)}),this.log.error("all streams aborted",this.streams.length),this._abort(e),this.timeline.close=Date.now(),this.status="closed"}};function NE(t){return new Em(t)}var CO=3e4;function IO(t,e){try{let{options:r}=e.getHandler(t);return r.maxInboundStreams}catch(r){if(r.code!==V.ERR_NO_HANDLER_FOR_PROTOCOL)throw r}return Wp}function _O(t,e,r={}){try{let{options:n}=e.getHandler(t);if(n.maxOutboundStreams!=null)return n.maxOutboundStreams}catch(n){if(n.code!==V.ERR_NO_HANDLER_FOR_PROTOCOL)throw n}return r.maxOutboundStreams??Yp}function PE(t,e,r){let n=0;return r.streams.forEach(i=>{i.direction===e&&i.protocol===t&&n++}),n}var Pu=class{components;connectionEncryption;muxers;inboundUpgradeTimeout;events;constructor(e,r){this.components=e,this.connectionEncryption=new Map,r.connectionEncryption.forEach(n=>{this.connectionEncryption.set(n.protocol,n)}),this.muxers=new Map,r.muxers.forEach(n=>{this.muxers.set(n.protocol,n)}),this.inboundUpgradeTimeout=r.inboundUpgradeTimeout??3e4,this.events=e.events}async shouldBlockConnection(e,r,n){let i=this.components.connectionGater[n];if(i!==void 0&&await i(e,r))throw new _(`The multiaddr connection is blocked by gater.${n}`,V.ERR_CONNECTION_INTERCEPTED)}async upgradeInbound(e,r){if(!await this.components.connectionManager.acceptIncomingConnection(e))throw new _("connection denied",V.ERR_CONNECTION_DENIED);let i,o,s,a,c,u=AbortSignal.timeout(this.inboundUpgradeTimeout),f=()=>{e.abort(new _("inbound upgrade timeout",Ra))};u.addEventListener("abort",f,{once:!0}),wt(1/0,u);try{if(await this.components.connectionGater.denyInboundConnection?.(e)===!0)throw new _("The multiaddr connection is blocked by gater.acceptConnection",V.ERR_CONNECTION_INTERCEPTED);this.components.metrics?.trackMultiaddrConnection(e),e.log("starting the inbound connection upgrade");let h=e;if(r?.skipProtection!==!0){let p=this.components.connectionProtector;p!=null&&(e.log("protecting the inbound connection"),h=await p.protect(e))}try{if(i=h,r?.skipEncryption!==!0){({conn:i,remotePeer:o,protocol:c}=await this._encryptInbound(h));let p={...h,...i};await this.shouldBlockConnection(o,p,"denyInboundEncryptedConnection")}else{let p=e.remoteAddr.getPeerId();if(p==null)throw new _("inbound connection that skipped encryption must have a peer id",V.ERR_INVALID_MULTIADDR);let y=se(p);c="native",o=y}if(s=i,r?.muxerFactory!=null)a=r.muxerFactory;else if(this.muxers.size>0){let p=await this._multiplexInbound({...h,...i},this.muxers);a=p.muxerFactory,s=p.stream}}catch(p){throw e.log.error("failed to upgrade inbound connection",p),p}return await this.shouldBlockConnection(o,e,"denyInboundUpgradedConnection"),e.log("successfully upgraded inbound connection"),this._createConnection({cryptoProtocol:c,direction:"inbound",maConn:e,upgradedConn:s,muxerFactory:a,remotePeer:o,transient:r?.transient})}finally{u.removeEventListener("abort",f),this.components.connectionManager.afterUpgradeInbound()}}async upgradeOutbound(e,r){let n=e.remoteAddr.getPeerId(),i;n!=null&&(i=se(n),await this.shouldBlockConnection(i,e,"denyOutboundConnection"));let o,s,a,c,u;this.components.metrics?.trackMultiaddrConnection(e),e.log("starting the outbound connection upgrade");let f=e;if(r?.skipProtection!==!0){let h=this.components.connectionProtector;h!=null&&(f=await h.protect(e))}try{if(o=f,r?.skipEncryption!==!0){({conn:o,remotePeer:s,protocol:c}=await this._encryptOutbound(f,i));let h={...f,...o};await this.shouldBlockConnection(s,h,"denyOutboundEncryptedConnection")}else{if(i==null)throw new _("Encryption was skipped but no peer id was passed",V.ERR_INVALID_PEER);c="native",s=i}if(a=o,r?.muxerFactory!=null)u=r.muxerFactory;else if(this.muxers.size>0){let h=await this._multiplexOutbound({...f,...o},this.muxers);u=h.muxerFactory,a=h.stream}}catch(h){throw e.log.error("failed to upgrade outbound connection",h),await e.close(h),h}return await this.shouldBlockConnection(s,e,"denyOutboundUpgradedConnection"),e.log("successfully upgraded outbound connection"),this._createConnection({cryptoProtocol:c,direction:"outbound",maConn:e,upgradedConn:a,muxerFactory:u,remotePeer:s,transient:r?.transient})}_createConnection(e){let{cryptoProtocol:r,direction:n,maConn:i,upgradedConn:o,remotePeer:s,muxerFactory:a,transient:c}=e,u,f,h;a!=null&&(u=a.createStreamMuxer({direction:n,onIncomingStream:l=>{h!=null&&Promise.resolve().then(async()=>{let d=this.components.registrar.getProtocols(),{stream:m,protocol:g}=await ua(l,d,{log:l.log,yieldBytes:!1});if(h==null)return;h.log("incoming stream opened on %s",g);let x=IO(g,this.components.registrar);if(PE(g,"inbound",h)===x){let v=new _(`Too many inbound protocol streams for protocol "${g}" - limit ${x}`,V.ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS);throw l.abort(v),v}l.source=m.source,l.sink=m.sink,l.protocol=g,m.closeWrite!=null&&(l.closeWrite=m.closeWrite),m.closeRead!=null&&(l.closeRead=m.closeRead),m.close!=null&&(l.close=m.close),await this.components.peerStore.merge(s,{protocols:[g]}),this.components.metrics?.trackProtocolStream(l,h),this._onStream({connection:h,stream:l,protocol:g})}).catch(async d=>{h.log.error("error handling incoming stream id %s",l.id,d.message,d.code,d.stack),l.timeline.close==null&&await l.close()})}}),f=async(l,d={})=>{if(u==null)throw new _("Stream is not multiplexed",V.ERR_MUXER_UNAVAILABLE);h.log("starting new stream for protocols %s",l);let m=await u.newStream();h.log.trace("started new stream %s for protocols %s",m.id,l);try{if(d.signal==null){m.log("no abort signal was passed while trying to negotiate protocols %s falling back to default timeout",l);let w=AbortSignal.timeout(CO);wt(1/0,w),d={...d,signal:w}}m.log.trace("selecting protocol from protocols %s",l);let{stream:g,protocol:x}=await ca(m,l,{...d,log:m.log,yieldBytes:!0});m.log("selected protocol %s",x);let b=_O(x,this.components.registrar,d);if(PE(x,"outbound",h)>=b){let w=new _(`Too many outbound protocol streams for protocol "${x}" - limit ${b}`,V.ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS);throw m.abort(w),w}return await this.components.peerStore.merge(s,{protocols:[x]}),m.source=g.source,m.sink=g.sink,m.protocol=x,g.closeWrite!=null&&(m.closeWrite=g.closeWrite),g.closeRead!=null&&(m.closeRead=g.closeRead),g.close!=null&&(m.close=g.close),this.components.metrics?.trackProtocolStream(m,h),m}catch(g){throw h.log.error("could not create new stream for protocols %s",l,g),m.timeline.close==null&&m.abort(g),g.code!=null?g:new _(String(g),V.ERR_UNSUPPORTED_PROTOCOL)}},Promise.all([u.sink(o.source),o.sink(u.source)]).catch(l=>{h.log.error("error piping data through muxer",l)}));let p=i.timeline;i.timeline=new Proxy(p,{set:(...l)=>(h!=null&&l[1]==="close"&&l[2]!=null&&p.close==null&&(async()=>{try{h.status==="open"&&await h.close()}catch(d){h.log.error("error closing connection after timeline close",d)}finally{this.events.safeDispatchEvent("connection:close",{detail:h})}})().catch(d=>{h.log.error("error thrown while dispatching connection:close event",d)}),Reflect.set(...l))}),i.timeline.upgraded=Date.now();let y=()=>{throw new _("connection is not multiplexed",V.ERR_CONNECTION_NOT_MULTIPLEXED)};return h=NE({remoteAddr:i.remoteAddr,remotePeer:s,status:"open",direction:n,timeline:i.timeline,multiplexer:u?.protocol,encryption:r,transient:c,logger:this.components.logger,newStream:f??y,getStreams:()=>u!=null?u.streams:[],close:async l=>{u!=null&&(h.log.trace("close muxer"),await u.close(l)),h.log.trace("close maconn"),await i.close(l),h.log.trace("closed maconn")},abort:l=>{i.abort(l),u?.abort(l)}}),this.events.safeDispatchEvent("connection:open",{detail:h}),h}_onStream(e){let{connection:r,stream:n,protocol:i}=e,{handler:o,options:s}=this.components.registrar.getHandler(i);if(r.transient&&s.runOnTransientConnection!==!0)throw new _("Cannot open protocol stream on transient connection","ERR_TRANSIENT_CONNECTION");o({connection:r,stream:n})}async _encryptInbound(e){let r=Array.from(this.connectionEncryption.keys());e.log("handling inbound crypto protocol selection",r);try{let{stream:n,protocol:i}=await ua(e,r,{log:e.log}),o=this.connectionEncryption.get(i);if(o==null)throw new Error(`no crypto module found for ${i}`);return e.log("encrypting inbound connection using",i),{...await o.secureInbound(this.components.peerId,n),protocol:i}}catch(n){throw e.log.error("encrypting inbound connection to %p failed",n),new _(n.message,V.ERR_ENCRYPTION_FAILED)}}async _encryptOutbound(e,r){let n=Array.from(this.connectionEncryption.keys());e.log("selecting outbound crypto protocol",n);try{e.log.trace("selecting encrypter from %s",n);let{stream:i,protocol:o}=await ca(e,n,{log:e.log,yieldBytes:!0}),s=this.connectionEncryption.get(o);if(s==null)throw new Error(`no crypto module found for ${o}`);return e.log("encrypting outbound connection to %p using %p",r),{...await s.secureOutbound(this.components.peerId,i,r),protocol:o}}catch(i){throw e.log.error("encrypting outbound connection to %p failed",i),new _(i.message,V.ERR_ENCRYPTION_FAILED)}}async _multiplexOutbound(e,r){let n=Array.from(r.keys());e.log("outbound selecting muxer %s",n);try{e.log.trace("selecting stream muxer from %s",n);let{stream:i,protocol:o}=await ca(e,n,{log:e.log,yieldBytes:!0});e.log("selected %s as muxer protocol",o);let s=r.get(o);return{stream:i,muxerFactory:s}}catch(i){throw e.log.error("error multiplexing outbound connection",i),new _(String(i),V.ERR_MUXER_UNAVAILABLE)}}async _multiplexInbound(e,r){let n=Array.from(r.keys());e.log("inbound handling muxers %s",n);try{let{stream:i,protocol:o}=await ua(e,n,{log:e.log}),s=r.get(o);return{stream:i,muxerFactory:s}}catch(i){throw e.log.error("error multiplexing inbound connection",i),new _(String(i),V.ERR_MUXER_UNAVAILABLE)}}};var OE="1.0.12-5d1f68e92",kE="libp2p";var Am=class extends Wo{peerId;peerStore;contentRouting;peerRouting;metrics;services;logger;status;components;log;constructor(e){super(),this.status="stopped";let r=new Wo,n=r.dispatchEvent.bind(r);r.dispatchEvent=a=>{let c=n(a),u=this.dispatchEvent(new lf(a.type,{detail:a.detail}));return c||u},wt(1/0,r),this.peerId=e.peerId,this.logger=e.logger??oc(),this.log=this.logger.forComponent("libp2p"),this.services={};let i=this.components=p2({peerId:e.peerId,nodeInfo:e.nodeInfo??{name:kE,version:OE},logger:this.logger,events:r,datastore:e.datastore??new Mc,connectionGater:S2(e.connectionGater)});this.peerStore=this.configureComponent("peerStore",new kc(i,{addressFilter:this.components.connectionGater.filterMultiaddrForPeer,...e.peerStore})),e.metrics!=null&&(this.metrics=this.configureComponent("metrics",e.metrics(this.components))),i.events.addEventListener("peer:update",a=>{if(a.detail.previous==null){let c={id:a.detail.peer.id,multiaddrs:a.detail.peer.addresses.map(u=>u.multiaddr)};i.events.safeDispatchEvent("peer:discovery",{detail:c})}}),e.connectionProtector!=null&&this.configureComponent("connectionProtector",e.connectionProtector(i)),this.components.upgrader=new Pu(this.components,{connectionEncryption:(e.connectionEncryption??[]).map((a,c)=>this.configureComponent(`connection-encryption-${c}`,a(this.components))),muxers:(e.streamMuxers??[]).map((a,c)=>this.configureComponent(`stream-muxers-${c}`,a(this.components))),inboundUpgradeTimeout:e.connectionManager.inboundUpgradeTimeout}),this.configureComponent("transportManager",new Eu(this.components,e.transportManager)),this.configureComponent("connectionManager",new yu(this.components,e.connectionManager)),this.configureComponent("registrar",new vu(this.components)),this.configureComponent("addressManager",new $c(this.components,e.addresses));let o=(e.peerRouters??[]).map((a,c)=>this.configureComponent(`peer-router-${c}`,a(this.components)));this.peerRouting=this.components.peerRouting=this.configureComponent("peerRouting",new wu(this.components,{routers:o}));let s=(e.contentRouters??[]).map((a,c)=>this.configureComponent(`content-router-${c}`,a(this.components)));if(this.contentRouting=this.components.contentRouting=this.configureComponent("contentRouting",new bu(this.components,{routers:s})),(e.peerDiscovery??[]).forEach((a,c)=>{this.configureComponent(`peer-discovery-${c}`,a(this.components)).addEventListener("peer",f=>{this.#e(f)})}),e.transports?.forEach((a,c)=>{this.components.transportManager.add(this.configureComponent(`transport-${c}`,a(this.components)))}),e.services!=null)for(let a of Object.keys(e.services)){let c=e.services[a],u=c(this.components);if(u==null){this.log.error("service factory %s returned null or undefined instance",a);continue}this.services[a]=u,this.configureComponent(a,u),u[of]!=null&&(this.log("registering service %s for content routing",a),s.push(u[of])),u[cf]!=null&&(this.log("registering service %s for peer routing",a),o.push(u[cf])),u[sf]!=null&&(this.log("registering service %s for peer discovery",a),u[sf].addEventListener?.("peer",f=>{this.#e(f)}))}}configureComponent(e,r){return r==null&&this.log.error("component %s was null or undefined",e),this.components[e]=r,r}async start(){if(this.status==="stopped"){this.status="starting",this.log("libp2p is starting");try{await this.components.beforeStart?.(),await this.components.start(),await this.components.afterStart?.(),this.status="started",this.safeDispatchEvent("start",{detail:this}),this.log("libp2p has started")}catch(e){throw this.log.error("An error occurred starting libp2p",e),this.status="started",await this.stop(),e}}}async stop(){this.status==="started"&&(this.log("libp2p is stopping"),this.status="stopping",await this.components.beforeStop?.(),await this.components.stop(),await this.components.afterStop?.(),this.status="stopped",this.safeDispatchEvent("stop",{detail:this}),this.log("libp2p has stopped"))}getConnections(e){return this.components.connectionManager.getConnections(e)}getDialQueue(){return this.components.connectionManager.getDialQueue()}getPeers(){let e=new Dt;for(let r of this.components.connectionManager.getConnections())e.add(r.remotePeer);return Array.from(e)}async dial(e,r={}){return this.components.connectionManager.openConnection(e,{priority:75,...r})}async dialProtocol(e,r,n={}){if(r==null)throw new _("no protocols were provided to open a stream",V.ERR_INVALID_PROTOCOLS_FOR_STREAM);if(r=Array.isArray(r)?r:[r],r.length===0)throw new _("no protocols were provided to open a stream",V.ERR_INVALID_PROTOCOLS_FOR_STREAM);return(await this.dial(e,n)).newStream(r,n)}getMultiaddrs(){return this.components.addressManager.getAddresses()}getProtocols(){return this.components.registrar.getProtocols()}async hangUp(e,r={}){cn(e)&&(e=se(e.getPeerId()??"")),await this.components.connectionManager.closeConnections(e,r)}async getPublicKey(e,r={}){if(this.log("getPublicKey %p",e),e.publicKey!=null)return e.publicKey;let n=await this.peerStore.get(e);if(n.id.publicKey!=null)return n.id.publicKey;let i=H1([zc("/pk/"),e.multihash.digest]),o=await this.contentRouting.get(i,r);return bs(o),await this.peerStore.patch(e,{publicKey:o}),o}async handle(e,r,n){Array.isArray(e)||(e=[e]),await Promise.all(e.map(async i=>{await this.components.registrar.handle(i,r,n)}))}async unhandle(e){Array.isArray(e)||(e=[e]),await Promise.all(e.map(async r=>{await this.components.registrar.unhandle(r)}))}async register(e,r){return this.components.registrar.register(e,r)}unregister(e){this.components.registrar.unregister(e)}#e(e){let{detail:r}=e;if(r.id.toString()===this.peerId.toString()){this.log.error(new Error(V.ERR_DISCOVERED_SELF));return}this.components.peerStore.merge(r.id,{multiaddrs:r.multiaddrs}).catch(n=>{this.log.error(n)})}};async function UE(t={}){return t.peerId??=await Gb(),new Am(tv(t))}async function RO(t={}){let e=await UE(t);return t.start!==!1&&await e.start(),e}return jE(BO);})();
62
62
  /*! Bundled license information:
63
63
 
64
64
  @noble/hashes/esm/utils.js:
@@ -1,3 +1,3 @@
1
- export declare const version = "1.0.12-4e0135c7d";
1
+ export declare const version = "1.0.12-5d1f68e92";
2
2
  export declare const name = "libp2p";
3
3
  //# sourceMappingURL=version.d.ts.map
@@ -1,3 +1,3 @@
1
- export const version = '1.0.12-4e0135c7d';
1
+ export const version = '1.0.12-5d1f68e92';
2
2
  export const name = 'libp2p';
3
3
  //# sourceMappingURL=version.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "libp2p",
3
- "version": "1.0.12-4e0135c7d",
3
+ "version": "1.0.12-5d1f68e92",
4
4
  "description": "JavaScript implementation of libp2p, a modular peer to peer network stack",
5
5
  "license": "Apache-2.0 OR MIT",
6
6
  "homepage": "https://github.com/libp2p/js-libp2p/tree/main/packages/libp2p#readme",
@@ -84,16 +84,16 @@
84
84
  "test:webkit": "aegir test -t browser -f \"./dist/test/**/*.spec.js\" -- --browser webkit"
85
85
  },
86
86
  "dependencies": {
87
- "@libp2p/crypto": "3.0.2-4e0135c7d",
88
- "@libp2p/interface": "1.0.2-4e0135c7d",
89
- "@libp2p/interface-internal": "1.0.3-4e0135c7d",
90
- "@libp2p/logger": "4.0.2-4e0135c7d",
91
- "@libp2p/multistream-select": "5.0.3-4e0135c7d",
92
- "@libp2p/peer-collections": "5.1.1-4e0135c7d",
93
- "@libp2p/peer-id": "4.0.2-4e0135c7d",
94
- "@libp2p/peer-id-factory": "4.0.1-4e0135c7d",
95
- "@libp2p/peer-store": "10.0.3-4e0135c7d",
96
- "@libp2p/utils": "5.1.0-4e0135c7d",
87
+ "@libp2p/crypto": "3.0.2-5d1f68e92",
88
+ "@libp2p/interface": "1.0.2-5d1f68e92",
89
+ "@libp2p/interface-internal": "1.0.3-5d1f68e92",
90
+ "@libp2p/logger": "4.0.2-5d1f68e92",
91
+ "@libp2p/multistream-select": "5.0.3-5d1f68e92",
92
+ "@libp2p/peer-collections": "5.1.1-5d1f68e92",
93
+ "@libp2p/peer-id": "4.0.2-5d1f68e92",
94
+ "@libp2p/peer-id-factory": "4.0.1-5d1f68e92",
95
+ "@libp2p/peer-store": "10.0.3-5d1f68e92",
96
+ "@libp2p/utils": "5.1.0-5d1f68e92",
97
97
  "@multiformats/mafmt": "^12.1.6",
98
98
  "@multiformats/multiaddr": "^12.1.10",
99
99
  "@multiformats/multiaddr-matcher": "^1.1.0",
@@ -119,13 +119,13 @@
119
119
  },
120
120
  "devDependencies": {
121
121
  "@chainsafe/libp2p-yamux": "^6.0.1",
122
- "@libp2p/circuit-relay-v2": "1.0.8-4e0135c7d",
123
- "@libp2p/identify": "1.0.7-4e0135c7d",
124
- "@libp2p/interface-compliance-tests": "5.0.8-4e0135c7d",
125
- "@libp2p/mplex": "10.0.8-4e0135c7d",
126
- "@libp2p/plaintext": "1.0.8-4e0135c7d",
127
- "@libp2p/tcp": "9.0.8-4e0135c7d",
128
- "@libp2p/websockets": "8.0.8-4e0135c7d",
122
+ "@libp2p/circuit-relay-v2": "1.0.8-5d1f68e92",
123
+ "@libp2p/identify": "1.0.7-5d1f68e92",
124
+ "@libp2p/interface-compliance-tests": "5.0.8-5d1f68e92",
125
+ "@libp2p/mplex": "10.0.8-5d1f68e92",
126
+ "@libp2p/plaintext": "1.0.8-5d1f68e92",
127
+ "@libp2p/tcp": "9.0.8-5d1f68e92",
128
+ "@libp2p/websockets": "8.0.8-5d1f68e92",
129
129
  "aegir": "^41.0.2",
130
130
  "it-pushable": "^3.2.1",
131
131
  "p-event": "^6.0.0",
package/src/version.ts CHANGED
@@ -1,2 +1,2 @@
1
- export const version = '1.0.12-4e0135c7d'
1
+ export const version = '1.0.12-5d1f68e92'
2
2
  export const name = 'libp2p'