helia 4.2.6-3bf5ab0 → 4.2.6
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 +1 -1
- package/dist/src/version.d.ts +1 -1
- package/dist/src/version.d.ts.map +1 -1
- package/dist/src/version.js +1 -1
- package/dist/src/version.js.map +1 -1
- package/dist/typedoc-urls.json +12 -0
- package/package.json +5 -5
- package/src/version.ts +1 -1
package/dist/index.min.js
CHANGED
|
@@ -35,7 +35,7 @@ a=candidate:1467250027 1 UDP 1467250027 ${t} ${n} typ host\r
|
|
|
35
35
|
a=ice-ufrag:`+e+`
|
|
36
36
|
`).replace(/\na=ice-pwd:[^\n]*\n/,`
|
|
37
37
|
a=ice-pwd:`+e+`
|
|
38
|
-
`),r}var Iy=Array.from("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),Ty=r=>[...Array(r)].map(()=>Iy.at(Math.floor(Math.random()*Iy.length))).join("");var cT=1e4,joe=te("webrtc-direct").code,Ay=te("certhash").code,Pd=class{log;metrics;components;init;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:webrtc-direct"),this.components=e,this.init=t,e.metrics!=null&&(this.metrics={dialerEvents:e.metrics.registerCounterGroup("libp2p_webrtc-direct_dialer_events_total",{label:"event",help:"Total count of WebRTC-direct dial events by type"})})}[un]=!0;[Symbol.toStringTag]="@libp2p/webrtc-direct";[Te]=["@libp2p/transport"];async dial(e,t){let n=await this._connect(e,t);return this.log("dialing address: %a",e),n}createListener(e){throw cy("WebRTCTransport.createListener")}listenFilter(e){return e.filter(q5.exactMatch)}dialFilter(e){return this.listenFilter(e)}async _connect(e,t){let n=new AbortController,o=n.signal,s=e.getPeerId();if(s===null)throw vd("we need to have the remote's PeerId");let i=pe(s),a=o3(Nd(e)),c=await ks.generateCertificate({name:"ECDSA",namedCurve:"P-256",hash:s3(a.code)}),l=new ks({...await pc(this.init.rtcConfiguration),certificates:[c]});try{let d=new Promise((S,I)=>{let F=l.createDataChannel("",{negotiated:!0,id:0}),O=setTimeout(()=>{let B=`Data channel was never opened: state: ${F.readyState}`;this.log.error(B),this.metrics?.dialerEvents.increment({open_error:!0}),I(Jp("data",B))},cT);F.onopen=B=>{clearTimeout(O),S(F)},F.onerror=B=>{clearTimeout(O);let D=`Error opening a data channel for handshaking: ${B.target?.toString()??"not specified"}`;this.log.error(D),this.metrics?.dialerEvents.increment({unknown_error:!0}),I(Jp("data",D))}}),u="libp2p+webrtc+v1/"+Ty(32),f=await l.createOffer(),h=Ry(f,u);await l.setLocalDescription(h);let p=Sy(e,u);await l.setRemoteDescription(p);let g=await d,y=this.components.peerId,w=this.generateNoisePrologue(l,a.code,e),b=Ti({prologueBytes:w})(this.components),E=Wi({channel:g,direction:"inbound",logger:this.components.logger,...this.init.dataChannel??{}}),x={...E,sink:E.sink.bind(E),source:async function*(){for await(let S of E.source)for(let I of S)yield I}()},T=new Cs(this.components,{peerConnection:l,remoteAddr:e,timeline:{open:Date.now()},metrics:this.metrics?.dialerEvents}),C=hc?"iceconnectionstatechange":"connectionstatechange";l.addEventListener(C,()=>{switch(l.connectionState){case"failed":case"disconnected":case"closed":T.close().catch(S=>{this.log.error("error closing connection",S)}).finally(()=>{n.abort()});break;default:break}},{signal:o}),this.metrics?.dialerEvents.increment({peer_connection:!0});let v=new $o(this.components,{peerConnection:l,metrics:this.metrics?.dialerEvents,dataChannelOptions:this.init.dataChannel});return await b.secureInbound(y,x,i),await t.upgrader.upgradeOutbound(T,{skipProtection:!0,skipEncryption:!0,muxerFactory:v})}catch(d){throw l.close(),d}}generateNoisePrologue(e,t,n){if(e.getConfiguration().certificates?.length===0)throw fc("no local certificate");let o=vy(e,{log:this.log});if(o==null)throw fc("no local fingerprint found");let s=o.trim().toLowerCase().replaceAll(":",""),i=L(s,"hex"),a=ir(t,i),c=n3.decode(Nd(n)),l=L("libp2p-webrtc-noise:");return ve([l,a.bytes,c])}};function Cy(r){return e=>new Pd(e,r)}function ky(r){return e=>new Dd(e,r)}var Dy=async r=>{if(r.readyState>=2)throw new Error("socket closed");r.readyState!==1&&await new Promise((e,t)=>{function n(){r.removeEventListener("open",o),r.removeEventListener("error",s)}function o(){n(),e()}function s(i){n(),t(i.error??new Error(`connect ECONNREFUSED ${r.url}`))}r.addEventListener("open",o),r.addEventListener("error",s)})};var Ny=(r,e)=>(e=e??{},e.closeOnEnd=e.closeOnEnd!==!1,async n=>{for await(let o of n){try{await Dy(r)}catch(s){if(s.message==="socket closed")break;throw s}if(r.readyState===r.CLOSING||r.readyState===r.CLOSED)break;r.send(o)}e.closeOnEnd!=null&&r.readyState<=1&&await new Promise((o,s)=>{r.addEventListener("close",i=>{if(i.wasClean||i.code===1006)o();else{let a=Object.assign(new Error("ws error"),{event:i});s(a)}}),setTimeout(()=>{r.close()})})});var By=nt(Ly(),1);function Oy(r){return r instanceof ArrayBuffer||r?.constructor?.name==="ArrayBuffer"&&typeof r?.byteLength=="number"}var My=r=>{r.binaryType="arraybuffer";let e=async()=>{await new Promise((s,i)=>{if(n){s();return}if(o!=null){i(o);return}let a=d=>{r.removeEventListener("open",c),r.removeEventListener("error",l),d()},c=()=>{a(s)},l=d=>{a(()=>{i(d.error??new Error(`connect ECONNREFUSED ${r.url}`))})};r.addEventListener("open",c),r.addEventListener("error",l)})},t=async function*(){let s=new By.EventIterator(({push:i,stop:a,fail:c})=>{let l=u=>{let f=null;typeof u.data=="string"&&(f=L(u.data)),Oy(u.data)&&(f=new Uint8Array(u.data)),u.data instanceof Uint8Array&&(f=u.data),f!=null&&i(f)},d=u=>{c(u.error??new Error("Socket error"))};return r.addEventListener("message",l),r.addEventListener("error",d),r.addEventListener("close",a),()=>{r.removeEventListener("message",l),r.removeEventListener("error",d),r.removeEventListener("close",a)}},{highWaterMark:1/0});await e();for await(let i of s)yield Oy(i)?new Uint8Array(i):i}(),n=r.readyState===1,o;return r.addEventListener("open",()=>{n=!0,o=null}),r.addEventListener("close",()=>{n=!1,o=null}),r.addEventListener("error",s=>{n||(o=s.error??new Error(`connect ECONNREFUSED ${r.url}`))}),Object.assign(t,{connected:e})};var Uy=(r,e)=>{e=e??{};let t=My(r),n=e.remoteAddress,o=e.remotePort;if(r.url!=null)try{let i=new URL(r.url);n=i.hostname,o=parseInt(i.port,10)}catch{}if(n==null||o==null)throw new Error("Remote connection did not have address and/or port");return{sink:Ny(r,e),source:t,connected:async()=>{await t.connected()},close:async()=>{(r.readyState===r.CONNECTING||r.readyState===r.OPEN)&&await new Promise(i=>{r.addEventListener("close",()=>{i()}),r.close()})},destroy:()=>{r.terminate!=null?r.terminate():r.close()},remoteAddress:n,remotePort:o,socket:r}};var Fy=WebSocket;var uT={"http:":"ws:","https:":"wss:"},Vy="ws:",Ky=(r,e)=>{if(r.startsWith("//")&&(r=`${e?.protocol??Vy}${r}`),r.startsWith("/")&&e!=null){let n=e.protocol??Vy,o=e.host,s=e.port!=null&&o?.endsWith(`:${e.port}`)!==!0?`:${e.port}`:"";r=`${n}//${o}${s}${r}`}let t=new URL(r);for(let[n,o]of Object.entries(uT))t.protocol===n&&(t.protocol=o);return t};function $y(r,e){let t=typeof window>"u"?void 0:window.location;e=e??{};let n=Ky(r,t),o=new Fy(n.toString(),e.websocket);return Uy(o,e)}function Hy(r){return r.filter(e=>{if(e.protoCodes().includes(290))return!1;let t=e.decapsulateCode(421);return Di.matches(t)||Ss.matches(t)})}function qy(r){return r.filter(e=>{if(e.protoCodes().includes(290))return!1;let t=e.decapsulateCode(421);return Ss.matches(t)})}function Gy(){throw new Error("WebSocket Servers can not be created in the browser!")}function Wy(r,e,t){let n=t.logger.forComponent("libp2p:websockets:maconn"),o=t.metrics,s=t.metricPrefix??"",i={log:n,async sink(a){try{await r.sink(async function*(){for await(let c of a)c instanceof Uint8Array?yield c:yield c.subarray()}())}catch(c){c.type!=="aborted"&&n.error(c)}},source:r.source,remoteAddr:e,timeline:{open:Date.now()},async close(a={}){let c=Date.now();if(a.signal==null){let d=AbortSignal.timeout(500);a={...a,signal:d}}let l=()=>{let{host:d,port:u}=i.remoteAddr.toOptions();n("timeout closing stream to %s:%s after %dms, destroying it manually",d,u,Date.now()-c),this.abort(new m("Socket close timeout","ERR_SOCKET_CLOSE_TIMEOUT"))};a.signal?.addEventListener("abort",l);try{await r.close()}catch(d){n.error("error closing WebSocket gracefully",d),this.abort(d)}finally{a.signal?.removeEventListener("abort",l),i.timeline.close=Date.now()}},abort(a){let{host:c,port:l}=i.remoteAddr.toOptions();n("timeout closing stream to %s:%s due to error",c,l,a),r.destroy(),i.timeline.close=Date.now(),o?.increment({[`${s}error`]:!0})}};return r.socket.addEventListener("close",()=>{o?.increment({[`${s}close`]:!0}),i.timeline.close==null&&(i.timeline.close=Date.now())},{once:!0}),i}var c3=class{log;init;logger;metrics;components;constructor(e,t){this.log=e.logger.forComponent("libp2p:websockets"),this.logger=e.logger,this.components=e,this.init=t,e.metrics!=null&&(this.metrics={dialerEvents:e.metrics.registerCounterGroup("libp2p_websockets_dialer_events_total",{label:"event",help:"Total count of WebSockets dialer events by type"})})}[un]=!0;[Symbol.toStringTag]="@libp2p/websockets";[Te]=["@libp2p/transport"];async dial(e,t){this.log("dialing %s",e),t=t??{};let n=await this._connect(e,t),o=Wy(n,e,{logger:this.logger,metrics:this.metrics?.dialerEvents});this.log("new outbound connection %s",o.remoteAddr);let s=await t.upgrader.upgradeOutbound(o,t);return this.log("outbound connection %s upgraded",o.remoteAddr),s}async _connect(e,t){t?.signal?.throwIfAborted();let n=e.toOptions();this.log("dialing %s:%s",n.host,n.port);let o=ee(),s=$y(zu(e),this.init);s.socket.addEventListener("error",()=>{let i=new m(`Could not connect to ${e.toString()}`,"ERR_CONNECTION_FAILED");this.log.error("connection error:",i),this.metrics?.dialerEvents.increment({error:!0}),o.reject(i)});try{t.onProgress?.(new H("websockets:open-connection")),await Ce(Promise.race([s.connected(),o.promise]),t.signal)}catch(i){throw t.signal?.aborted===!0&&this.metrics?.dialerEvents.increment({abort:!0}),s.close().catch(a=>{this.log.error("error closing raw socket",a)}),i}return this.log("connected %s",e),this.metrics?.dialerEvents.increment({connect:!0}),s}createListener(e){return Gy({logger:this.logger,metrics:this.components.metrics},{...this.init,...e})}listenFilter(e){return e=Array.isArray(e)?e:[e],this.init?.filter!=null?this.init?.filter(e):$1||H1?qy(e):Hy(e)}dialFilter(e){return this.listenFilter(e)}};function zy(r={}){return e=>new c3(e,r)}function l3(r){throw new Error("Not implemented")}var u3=class extends bn{writer;reader;constructor(e){super(e),this.writer=e.bidiStream.writable.getWriter(),this.reader=e.bidiStream.readable.getReader(),Promise.resolve().then(async()=>{for(;;){let t=await this.reader.read();if(t.done){e.log("remote closed write");return}t.value!=null&&this.sourcePush(new ae(t.value))}}).catch(t=>{e.log.error("error reading from stream",t),this.abort(t)}).finally(()=>{this.remoteCloseWrite()}),this.writer.closed.then(()=>{e.log("writer closed")}).catch(t=>{e.log("writer close promise rejected",t)}).finally(()=>{this.remoteCloseRead()})}sendNewStream(e){}async sendData(e,t){for await(let n of e)this.log("sendData waiting for writer to be ready"),await Ce(this.writer.ready,t?.signal),this.writer.write(n).catch(o=>{this.log.error("error sending stream data",o)})}async sendReset(e){this.log("sendReset aborting writer"),await Ce(this.writer.abort(),e?.signal),this.log("sendReset aborted writer")}async sendCloseWrite(e){this.log("sendCloseWrite closing writer"),await Ce(this.writer.close(),e?.signal),this.log("sendCloseWrite closed writer")}async sendCloseRead(e){this.log("sendCloseRead cancelling reader"),await Ce(this.reader.cancel(),e?.signal),this.log("sendCloseRead cancelled reader")}};async function d3(r,e,t,n,o,s){let i=s.forComponent(`libp2p:webtransport:stream:${t}:${e}`),a=new u3({bidiStream:r,id:e,direction:t,log:i,onEnd:()=>{let c=n.findIndex(l=>l===a);c!==-1&&n.splice(c,1),o?.(a)}});return a}function Bd(){return{source:{[Symbol.asyncIterator](){return{async next(){return new Promise(()=>{})}}}},sink:async r=>new Promise(()=>{})}}function Yy(r,e,t,n){let o=0,s=t.forComponent("libp2p:webtransport:muxer");return{protocol:"webtransport",createStreamMuxer:i=>{typeof i=="function"&&(i={onIncomingStream:i});let a=[];Promise.resolve().then(async()=>{for(;;){let{done:l,value:d}=await e.read();if(l)break;if(a.length>=n.maxInboundStreams)s(`too many inbound streams open - ${a.length}/${n.maxInboundStreams}, closing new incoming stream`),d.writable.close().catch(u=>{s.error(`failed to close inbound stream that crossed our maxInboundStream limit: ${u.message}`)}),d.readable.cancel().catch(u=>{s.error(`failed to close inbound stream that crossed our maxInboundStream limit: ${u.message}`)});else{let u=await d3(d,String(o++),"inbound",a,i?.onStreamEnd,t);a.push(u),i?.onIncomingStream?.(u)}}}).catch(l=>{s.error("could not create a new stream",l)});let c={protocol:"webtransport",streams:a,newStream:async l=>{s("new outgoing stream",l);let d=await r.createBidirectionalStream(),u=await d3(d,String(o++),i?.direction??"outbound",a,i?.onStreamEnd,t);return a.push(u),u},close:async()=>{s("closing webtransport muxer gracefully");try{r.close()}catch(l){c.abort(l)}},abort:l=>{s("closing webtransport muxer with err:",l);try{r.close()}catch(d){s.error("webtransport session threw error during close",d)}},...Bd()};return c}}}function Xy(r,e){return e.filter(n=>!!r.find(o=>J(n,o))).length===e.length}var pT=Object.values(xr).map(r=>r.decoder).reduce((r,e)=>r.or(e));function mT(r){return Bt.decode(pT.decode(r))}function f3(r){if(!Wu.matches(r))throw new m("Invalid multiaddr, was not a WebTransport address","ERR_INVALID_MULTIADDR");let e=r.stringTuples(),t=e.filter(([i,a])=>i===te("certhash").code).map(([i,a])=>mT(a??"")),n=e.filter(([i,a])=>i===te("p2p").code).map(([i,a])=>pe(a??""))[0],o=r.toOptions(),s=o.host;return o.family===6&&s?.includes(":")&&(s=`[${s}]`),{url:`https://${s}:${o.port}`,certhashes:t,remotePeer:n}}var Qy=globalThis.WebTransport;var h3=class{log;components;config;metrics;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:webtransport"),this.components=e,this.config={...t,maxInboundStreams:t.maxInboundStreams??1e3,certificates:t.certificates??[]},e.metrics!=null&&(this.metrics={dialerEvents:e.metrics.registerCounterGroup("libp2p_webtransport_dialer_events_total",{label:"event",help:"Total count of WebTransport dialer events by type"})})}[Symbol.toStringTag]="@libp2p/webtransport";[un]=!0;[Te]=["@libp2p/transport"];async dial(e,t){if(t?.signal?.aborted===!0)throw new dn;this.log("dialing %s",e);let n=this.components.peerId;if(n===void 0)throw new m("Need a local peerid","ERR_INVALID_PARAMETERS");t=t??{};let{url:o,certhashes:s,remotePeer:i}=f3(e),a,c,l=()=>{},d=!1,u=!1,f=!1;try{this.metrics?.dialerEvents.increment({pending:!0});let h=new Qy(`${o}/.well-known/libp2p-webtransport?type=noise`,{serverCertificateHashes:s.map(p=>({algorithm:"sha-256",value:p.digest}))});if(l=p=>{if(!d)try{this.metrics?.dialerEvents.increment({[p]:!0}),h.close()}catch(g){this.log.error("error closing wt session",g)}finally{c!=null&&(c.timeline.close=Date.now()),d=!0}},a=()=>{l(u?"noise_timeout":"ready_timeout")},t.signal?.addEventListener("abort",a,{once:!0}),this.log("wait for session to be ready"),t.onProgress?.(new H("webtransport:wait-for-session")),await Promise.race([h.closed,h.ready]),this.log("session became ready"),u=!0,this.metrics?.dialerEvents.increment({ready:!0}),h.closed.catch(p=>{this.log.error("error on remote wt session close",p)}).finally(()=>{l("remote_close")}),f=await Ce(this.authenticateWebTransport({wt:h,localPeer:n,remotePeer:i,certhashes:s,...t}),t.signal),!f)throw new m("Failed to authenticate webtransport","ERR_AUTHENTICATION_FAILED");return this.metrics?.dialerEvents.increment({open:!0}),c={close:async()=>{this.log("closing webtransport"),l("close")},abort:p=>{this.log("aborting webtransport due to passed err",p),l("abort")},remoteAddr:e,timeline:{open:Date.now()},log:this.components.logger.forComponent("libp2p:webtransport:maconn"),...Bd()},await t.upgrader.upgradeOutbound(c,{skipEncryption:!0,muxerFactory:Yy(h,h.incomingBidirectionalStreams.getReader(),this.components.logger,this.config),skipProtection:!0,onProgress:t.onProgress})}catch(h){throw this.log.error("caught wt session err",h),l(f?"upgrade_error":u?"noise_error":"ready_error"),h}finally{a!=null&&t.signal?.removeEventListener("abort",a)}}async authenticateWebTransport({wt:e,localPeer:t,remotePeer:n,certhashes:o,onProgress:s,signal:i}){i?.throwIfAborted(),s?.(new H("webtransport:open-authentication-stream"));let a=await e.createBidirectionalStream(),c=a.writable.getWriter(),l=a.readable.getReader(),d={source:async function*(){for(;;){let h=await l.read();if(h.value!=null&&(yield h.value),h.done)break}}(),sink:async h=>{for await(let p of h){await Ce(c.ready,i);let g=p instanceof Uint8Array?p:p.subarray();c.write(g).catch(y=>{this.log.error("could not write chunk during authentication of WebTransport stream",y)})}}},u=Ti()(this.components);s?.(new H("webtransport:secure-outbound-connection"));let{remoteExtensions:f}=await u.secureOutbound(t,d,n);if(s?.(new H("webtransport:close-authentication-stream")),c.close().catch(h=>{this.log.error(`Failed to close authentication stream writer: ${h.message}`)}),l.cancel().catch(h=>{this.log.error(`Failed to close authentication stream reader: ${h.message}`)}),!Xy(f?.webtransportCerthashes??[],o.map(h=>h.bytes)))throw new Error("Our certhashes are not a subset of the remote's reported certhashes");return!0}createListener(e){return l3(this.components,{...e,certificates:this.config.certificates,maxInboundStreams:this.config.maxInboundStreams})}listenFilter(){return[]}dialFilter(e){return globalThis.WebTransport==null?[]:e.filter(t=>{if(!Wu.exactMatch(t))return!1;let{url:n,certhashes:o}=f3(t);return n!=null&&o.length>0})}};function Zy(r={}){return e=>new h3(e,r)}var p3=nt(e1(),1);function jy(r,e){let t=e.map((n,o)=>({record:wn(n),index:o}));return t.sort((n,o)=>{let s=n.record.sequence,i=o.record.sequence;if(s>i)return-1;if(s<i)return 1;if(n.record.validityType===Jt.ValidityType.EOL&&o.record.validityType===Jt.ValidityType.EOL){let a=p3.default.fromString(n.record.validity).toDate(),c=p3.default.fromString(o.record.validity).toDate();if(a.getTime()>c.getTime())return-1;if(a.getTime()<c.getTime())return 1}return 0}),t[0].index}var Md="1.9.4",Ud="libp2p";var ew="4.2.6-3bf5ab0",tw="helia";var rw={list:["/dnsaddr/bootstrap.libp2p.io/p2p/QmNnooDu7bfjPFoTZYxMNLWUQJyrVwtbZg5gBMjTezGAJN","/dnsaddr/bootstrap.libp2p.io/p2p/QmbLHAnMoJPWSCR5Zhtx6BHJX9KiKNN6tpvbUcqanj75Nb","/dnsaddr/bootstrap.libp2p.io/p2p/QmcZf59bWwK5XFi76CZX8cbJ4BhTzzA3gU1ZjYZcYW3dwt","/ip4/104.131.131.82/tcp/4001/p2p/QmaCpDMGvV2BGHeYERUEnRQAwe3N8SzbUtfsmvsqQLuvuJ"]};function Fd(r={}){let e=`${tw}/${ew} ${Ud}/${Md} UserAgent=${globalThis.navigator.userAgent}`;return{peerId:r.peerId,dns:r.dns,addresses:{listen:["/webrtc"]},transports:[Rp({discoverRelays:1}),ky(),Cy(),Zy(),zy()],connectionEncryption:[Ti()],streamMuxers:[f7(),ry()],peerDiscovery:[T7(rw)],services:{autoNAT:g7(),dcutr:H7(),delegatedRouting:()=>mg("https://delegated-ipfs.dev"),dht:C9({clientMode:!0,validators:{ipns:n1},selectors:{ipns:jy}}),identify:n9({agentVersion:e}),identifyPush:o9({agentVersion:e}),keychain:Ed(r.keychain),ping:ay()}}}var nw=async()=>{let r=await xa("Ed25519"),e=await gT(r);if(e.type==="Ed25519")return e;throw new Error(`Generated unexpected PeerId type "${e.type}"`)};async function gT(r){return ut(e0(r.public),t0(r))}var St={ERR_INVALID_PARAMETERS:"ERR_INVALID_PARAMETERS"};var zi;(function(r){let e;(function(o){let s;o.codec=()=>(s==null&&(s=oe((i,a,c={})=>{c.lengthDelimited!==!1&&a.fork(),i.key!=null&&i.key!==""&&(a.uint32(10),a.string(i.key)),i.value!=null&&i.value.byteLength>0&&(a.uint32(18),a.bytes(i.value)),c.lengthDelimited!==!1&&a.ldelim()},(i,a)=>{let c={key:"",value:new Uint8Array(0)},l=a==null?i.len:i.pos+a;for(;i.pos<l;){let d=i.uint32();switch(d>>>3){case 1:c.key=i.string();break;case 2:c.value=i.bytes();break;default:i.skipType(d&7);break}}return c})),s),o.encode=i=>ne(i,o.codec()),o.decode=i=>re(i,o.codec())})(e=r.Peer$metadataEntry||(r.Peer$metadataEntry={}));let t;(function(o){let s;o.codec=()=>(s==null&&(s=oe((i,a,c={})=>{c.lengthDelimited!==!1&&a.fork(),i.key!=null&&i.key!==""&&(a.uint32(10),a.string(i.key)),i.value!=null&&(a.uint32(18),Kd.codec().encode(i.value,a)),c.lengthDelimited!==!1&&a.ldelim()},(i,a)=>{let c={key:""},l=a==null?i.len:i.pos+a;for(;i.pos<l;){let d=i.uint32();switch(d>>>3){case 1:c.key=i.string();break;case 2:c.value=Kd.codec().decode(i,i.uint32());break;default:i.skipType(d&7);break}}return c})),s),o.encode=i=>ne(i,o.codec()),o.decode=i=>re(i,o.codec())})(t=r.Peer$tagsEntry||(r.Peer$tagsEntry={}));let n;r.codec=()=>(n==null&&(n=oe((o,s,i={})=>{if(i.lengthDelimited!==!1&&s.fork(),o.addresses!=null)for(let a of o.addresses)s.uint32(10),Vd.codec().encode(a,s);if(o.protocols!=null)for(let a of o.protocols)s.uint32(18),s.string(a);if(o.publicKey!=null&&(s.uint32(34),s.bytes(o.publicKey)),o.peerRecordEnvelope!=null&&(s.uint32(42),s.bytes(o.peerRecordEnvelope)),o.metadata!=null&&o.metadata.size!==0)for(let[a,c]of o.metadata.entries())s.uint32(50),r.Peer$metadataEntry.codec().encode({key:a,value:c},s);if(o.tags!=null&&o.tags.size!==0)for(let[a,c]of o.tags.entries())s.uint32(58),r.Peer$tagsEntry.codec().encode({key:a,value:c},s);i.lengthDelimited!==!1&&s.ldelim()},(o,s)=>{let i={addresses:[],protocols:[],metadata:new Map,tags:new Map},a=s==null?o.len:o.pos+s;for(;o.pos<a;){let c=o.uint32();switch(c>>>3){case 1:i.addresses.push(Vd.codec().decode(o,o.uint32()));break;case 2:i.protocols.push(o.string());break;case 4:i.publicKey=o.bytes();break;case 5:i.peerRecordEnvelope=o.bytes();break;case 6:{let l=r.Peer$metadataEntry.codec().decode(o,o.uint32());i.metadata.set(l.key,l.value);break}case 7:{let l=r.Peer$tagsEntry.codec().decode(o,o.uint32());i.tags.set(l.key,l.value);break}default:o.skipType(c&7);break}}return i})),n),r.encode=o=>ne(o,r.codec()),r.decode=o=>re(o,r.codec())})(zi||(zi={}));var Vd;(function(r){let e;r.codec=()=>(e==null&&(e=oe((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.multiaddr!=null&&t.multiaddr.byteLength>0&&(n.uint32(10),n.bytes(t.multiaddr)),t.isCertified!=null&&(n.uint32(16),n.bool(t.isCertified)),o.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let o={multiaddr:new Uint8Array(0)},s=n==null?t.len:t.pos+n;for(;t.pos<s;){let i=t.uint32();switch(i>>>3){case 1:o.multiaddr=t.bytes();break;case 2:o.isCertified=t.bool();break;default:t.skipType(i&7);break}}return o})),e),r.encode=t=>ne(t,r.codec()),r.decode=t=>re(t,r.codec())})(Vd||(Vd={}));var Kd;(function(r){let e;r.codec=()=>(e==null&&(e=oe((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.value!=null&&t.value!==0&&(n.uint32(8),n.uint32(t.value)),t.expiry!=null&&(n.uint32(16),n.uint64(t.expiry)),o.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let o={value:0},s=n==null?t.len:t.pos+n;for(;t.pos<s;){let i=t.uint32();switch(i>>>3){case 1:o.value=t.uint32();break;case 2:o.expiry=t.uint64();break;default:t.skipType(i&7);break}}return o})),e),r.encode=t=>ne(t,r.codec()),r.decode=t=>re(t,r.codec())})(Kd||(Kd={}));function Yi(r,e){let t=zi.decode(e);t.publicKey!=null&&r.publicKey==null&&(r=Tm({...r,publicKey:r.publicKey}));let n=new Map,o=BigInt(Date.now());for(let[s,i]of t.tags.entries())i.expiry!=null&&i.expiry<o||n.set(s,i);return{...t,id:r,addresses:t.addresses.map(({multiaddr:s,isCertified:i})=>({multiaddr:Z(s),isCertified:i??!1})),metadata:t.metadata,peerRecordEnvelope:t.peerRecordEnvelope??void 0,tags:n}}var m3="/peers/";function Xi(r){if(!to(r)||r.type==null)throw new m("Invalid PeerId",St.ERR_INVALID_PARAMETERS);let e=r.toCID().toString();return new De(`${m3}${e}`)}async function ow(r,e,t){let n=new Map;for(let o of t){if(o==null)continue;if(o.multiaddr instanceof Uint8Array&&(o.multiaddr=Z(o.multiaddr)),!ko(o.multiaddr))throw new m("Multiaddr was invalid",St.ERR_INVALID_PARAMETERS);if(!await e(r,o.multiaddr))continue;let s=o.isCertified??!1,i=o.multiaddr.toString(),a=n.get(i);a!=null?o.isCertified=a.isCertified||s:n.set(i,{multiaddr:o.multiaddr,isCertified:s})}return[...n.values()].sort((o,s)=>o.multiaddr.toString().localeCompare(s.multiaddr.toString())).map(({isCertified:o,multiaddr:s})=>({isCertified:o,multiaddr:s.bytes}))}async function Hd(r,e,t,n){if(e==null)throw new m("Invalid PeerData",St.ERR_INVALID_PARAMETERS);if(e.publicKey!=null&&r.publicKey!=null&&!J(e.publicKey,r.publicKey))throw new m("publicKey bytes do not match peer id publicKey bytes",St.ERR_INVALID_PARAMETERS);let o=n.existingPeer;if(o!=null&&!r.equals(o.id))throw new m("peer id did not match existing peer id",St.ERR_INVALID_PARAMETERS);let s=o?.addresses??[],i=new Set(o?.protocols??[]),a=o?.metadata??new Map,c=o?.tags??new Map,l=o?.peerRecordEnvelope;if(t==="patch"){if((e.multiaddrs!=null||e.addresses!=null)&&(s=[],e.multiaddrs!=null&&s.push(...e.multiaddrs.map(u=>({isCertified:!1,multiaddr:u}))),e.addresses!=null&&s.push(...e.addresses)),e.protocols!=null&&(i=new Set(e.protocols)),e.metadata!=null){let u=e.metadata instanceof Map?[...e.metadata.entries()]:Object.entries(e.metadata);a=$d(u,{validate:sw})}if(e.tags!=null){let u=e.tags instanceof Map?[...e.tags.entries()]:Object.entries(e.tags);c=$d(u,{validate:iw,map:aw})}e.peerRecordEnvelope!=null&&(l=e.peerRecordEnvelope)}if(t==="merge"){if(e.multiaddrs!=null&&s.push(...e.multiaddrs.map(u=>({isCertified:!1,multiaddr:u}))),e.addresses!=null&&s.push(...e.addresses),e.protocols!=null&&(i=new Set([...i,...e.protocols])),e.metadata!=null){let u=e.metadata instanceof Map?[...e.metadata.entries()]:Object.entries(e.metadata);for(let[f,h]of u)h==null?a.delete(f):a.set(f,h);a=$d([...a.entries()],{validate:sw})}if(e.tags!=null){let u=e.tags instanceof Map?[...e.tags.entries()]:Object.entries(e.tags),f=new Map(c);for(let[h,p]of u)p==null?f.delete(h):f.set(h,p);c=$d([...f.entries()],{validate:iw,map:aw})}e.peerRecordEnvelope!=null&&(l=e.peerRecordEnvelope)}let d={addresses:await ow(r,n.addressFilter??(async()=>!0),s),protocols:[...i.values()].sort((u,f)=>u.localeCompare(f)),metadata:a,tags:c,publicKey:o?.id.publicKey??e.publicKey??r.publicKey,peerRecordEnvelope:l};return r.type!=="RSA"&&delete d.publicKey,d}function $d(r,e){let t=new Map;for(let[n,o]of r)o!=null&&e.validate(n,o);for(let[n,o]of r.sort(([s],[i])=>s.localeCompare(i)))o!=null&&t.set(n,e.map?.(n,o)??o);return t}function sw(r,e){if(typeof r!="string")throw new m("Metadata key must be a string",St.ERR_INVALID_PARAMETERS);if(!(e instanceof Uint8Array))throw new m("Metadata value must be a Uint8Array",St.ERR_INVALID_PARAMETERS)}function iw(r,e){if(typeof r!="string")throw new m("Tag name must be a string",St.ERR_INVALID_PARAMETERS);if(e.value!=null){if(parseInt(`${e.value}`,10)!==e.value)throw new m("Tag value must be an integer",St.ERR_INVALID_PARAMETERS);if(e.value<0||e.value>100)throw new m("Tag value must be between 0-100",St.ERR_INVALID_PARAMETERS)}if(e.ttl!=null){if(parseInt(`${e.ttl}`,10)!==e.ttl)throw new m("Tag ttl must be an integer",St.ERR_INVALID_PARAMETERS);if(e.ttl<0)throw new m("Tag ttl must be between greater than 0",St.ERR_INVALID_PARAMETERS)}}function aw(r,e){let t;return e.expiry!=null&&(t=e.expiry),e.ttl!=null&&(t=BigInt(Date.now()+Number(e.ttl))),{value:e.value??0,expiry:t}}function qd(r,e,t){let n=r.toString().split("/")[2],o=lt.decode(n),s=Ze(o),i=t.get(s);if(i!=null)return i;let a=Yi(s,e);return t.set(s,a),a}function yT(r,e){return r==null?{}:{prefix:m3,filters:(r.filters??[]).map(t=>({key:n,value:o})=>t(qd(n,o,e))),orders:(r.orders??[]).map(t=>(n,o)=>t(qd(n.key,n.value,e),qd(o.key,o.value,e)))}}var Gd=class{peerId;datastore;lock;addressFilter;constructor(e,t={}){this.peerId=e.peerId,this.datastore=e.datastore,this.addressFilter=t.addressFilter,this.lock=Ma({name:"peer-store",singleProcess:!0})}async has(e){return this.datastore.has(Xi(e))}async delete(e){if(this.peerId.equals(e))throw new m("Cannot delete self peer",St.ERR_INVALID_PARAMETERS);await this.datastore.delete(Xi(e))}async load(e){let t=await this.datastore.get(Xi(e));return Yi(e,t)}async save(e,t){let{existingBuf:n,existingPeer:o}=await this.#e(e),s=await Hd(e,t,"patch",{addressFilter:this.addressFilter});return this.#t(e,s,n,o)}async patch(e,t){let{existingBuf:n,existingPeer:o}=await this.#e(e),s=await Hd(e,t,"patch",{addressFilter:this.addressFilter,existingPeer:o});return this.#t(e,s,n,o)}async merge(e,t){let{existingBuf:n,existingPeer:o}=await this.#e(e),s=await Hd(e,t,"merge",{addressFilter:this.addressFilter,existingPeer:o});return this.#t(e,s,n,o)}async*all(e){let t=new st;for await(let{key:n,value:o}of this.datastore.query(yT(e??{},t))){let s=qd(n,o,t);s.id.equals(this.peerId)||(yield s)}}async#e(e){try{let t=await this.datastore.get(Xi(e)),n=Yi(e,t);return{existingBuf:t,existingPeer:n}}catch(t){if(t.code!=="ERR_NOT_FOUND")throw t}return{}}async#t(e,t,n,o){let s=zi.encode(t);return n!=null&&J(s,n)?{peer:Yi(e,s),previous:o,updated:!1}:(await this.datastore.put(Xi(e),s),{peer:Yi(e,s),previous:o,updated:!0})}};var Wd=class{store;events;peerId;log;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:peer-store"),this.events=e.events,this.peerId=e.peerId,this.store=new Gd(e,t)}[Symbol.toStringTag]="@libp2p/peer-store";async forEach(e,t){this.log.trace("forEach await read lock");let n=await this.store.lock.readLock();this.log.trace("forEach got read lock");try{for await(let o of this.store.all(t))e(o)}finally{this.log.trace("forEach release read lock"),n()}}async all(e){this.log.trace("all await read lock");let t=await this.store.lock.readLock();this.log.trace("all got read lock");try{return await Ya(this.store.all(e))}finally{this.log.trace("all release read lock"),t()}}async delete(e){this.log.trace("delete await write lock");let t=await this.store.lock.writeLock();this.log.trace("delete got write lock");try{await this.store.delete(e)}finally{this.log.trace("delete release write lock"),t()}}async has(e){this.log.trace("has await read lock");let t=await this.store.lock.readLock();this.log.trace("has got read lock");try{return await this.store.has(e)}finally{this.log.trace("has release read lock"),t()}}async get(e){this.log.trace("get await read lock");let t=await this.store.lock.readLock();this.log.trace("get got read lock");try{return await this.store.load(e)}finally{this.log.trace("get release read lock"),t()}}async save(e,t){this.log.trace("save await write lock");let n=await this.store.lock.writeLock();this.log.trace("save got write lock");try{let o=await this.store.save(e,t);return this.#e(e,o),o.peer}finally{this.log.trace("save release write lock"),n()}}async patch(e,t){this.log.trace("patch await write lock");let n=await this.store.lock.writeLock();this.log.trace("patch got write lock");try{let o=await this.store.patch(e,t);return this.#e(e,o),o.peer}finally{this.log.trace("patch release write lock"),n()}}async merge(e,t){this.log.trace("merge await write lock");let n=await this.store.lock.writeLock();this.log.trace("merge got write lock");try{let o=await this.store.merge(e,t);return this.#e(e,o),o.peer}finally{this.log.trace("merge release write lock"),n()}}async consumePeerRecord(e,t){let n=await mr.openAndCertify(e,Kt.DOMAIN);if(t?.equals(n.peerId)===!1)return this.log("envelope peer id was not the expected peer id - expected: %p received: %p",t,n.peerId),!1;let o=Kt.createFromProtobuf(n.payload),s;try{s=await this.get(n.peerId)}catch(i){if(i.code!=="ERR_NOT_FOUND")throw i}if(s?.peerRecordEnvelope!=null){let i=await mr.createFromProtobuf(s.peerRecordEnvelope),a=Kt.createFromProtobuf(i.payload);if(a.seqNumber>=o.seqNumber)return this.log("sequence number was lower or equal to existing sequence number - stored: %d received: %d",a.seqNumber,o.seqNumber),!1}return await this.patch(o.peerId,{peerRecordEnvelope:e,addresses:o.multiaddrs.map(i=>({isCertified:!0,multiaddr:i}))}),!0}#e(e,t){t.updated&&(this.peerId.equals(e)?this.events.safeDispatchEvent("self:peer:update",{detail:t}):this.events.safeDispatchEvent("peer:update",{detail:t}))}};function cw(r,e){let t;return function(){let n=function(){t=void 0,r()};clearTimeout(t),t=setTimeout(n,e)}}var wT=r=>r;function g3(r,e){let t=r.getPeerId();return t!=null&&pe(t).equals(e)&&(r=r.decapsulate(Z(`/p2p/${e.toString()}`))),r}var zd=class{log;components;listen;announce;observed;announceFilter;constructor(e,t={}){let{listen:n=[],announce:o=[]}=t;this.components=e,this.log=e.logger.forComponent("libp2p:address-manager"),this.listen=n.map(s=>s.toString()),this.announce=new Set(o.map(s=>s.toString())),this.observed=new Map,this.announceFilter=t.announceFilter??wT,this._updatePeerStoreAddresses=cw(this._updatePeerStoreAddresses.bind(this),1e3),e.events.addEventListener("transport:listening",()=>{this._updatePeerStoreAddresses()}),e.events.addEventListener("transport:close",()=>{this._updatePeerStoreAddresses()})}[Symbol.toStringTag]="@libp2p/address-manager";_updatePeerStoreAddresses(){let e=this.getAnnounceAddrs().concat(this.components.transportManager.getAddrs()).concat([...this.observed.entries()].filter(([t,n])=>n.confident).map(([t])=>Z(t))).map(t=>t.getPeerId()===this.components.peerId.toString()?t.decapsulate(`/p2p/${this.components.peerId.toString()}`):t);this.components.peerStore.patch(this.components.peerId,{multiaddrs:e}).catch(t=>{this.log.error("error updating addresses",t)})}getListenAddrs(){return Array.from(this.listen).map(e=>Z(e))}getAnnounceAddrs(){return Array.from(this.announce).map(e=>Z(e))}getObservedAddrs(){return Array.from(this.observed).map(([e])=>Z(e))}addObservedAddr(e){e=g3(e,this.components.peerId);let t=e.toString();this.observed.has(t)||this.observed.set(t,{confident:!1})}confirmObservedAddr(e){e=g3(e,this.components.peerId);let t=e.toString(),o=(this.observed.get(t)??{confident:!1}).confident;this.observed.set(t,{confident:!0}),o||this._updatePeerStoreAddresses()}removeObservedAddr(e){e=g3(e,this.components.peerId);let t=e.toString();this.observed.delete(t)}getAddresses(){let e=this.getAnnounceAddrs().map(n=>n.toString());e.length===0&&(e=this.components.transportManager.getAddrs().map(n=>n.toString())),e=e.concat(Array.from(this.observed).filter(([n,o])=>o.confident).map(([n])=>n));let t=new Set(e);return this.announceFilter(Array.from(t).map(n=>Z(n))).map(n=>n.protos().pop()?.path===!0||n.getPeerId()===this.components.peerId.toString()?n:n.encapsulate(`/p2p/${this.components.peerId.toString()}`))}};var y3=class{components={};_started=!1;constructor(e={}){this.components={};for(let[t,n]of Object.entries(e))this.components[t]=n;this.components.logger==null&&(this.components.logger=So())}isStarted(){return this._started}async _invokeStartableMethod(e){await Promise.all(Object.values(this.components).filter(t=>xc(t)).map(async t=>{await t[e]?.()}))}async beforeStart(){await this._invokeStartableMethod("beforeStart")}async start(){await this._invokeStartableMethod("start"),this._started=!0}async afterStart(){await this._invokeStartableMethod("afterStart")}async beforeStop(){await this._invokeStartableMethod("beforeStop")}async stop(){await this._invokeStartableMethod("stop"),this._started=!1}async afterStop(){await this._invokeStartableMethod("afterStop")}},ET=["metrics","connectionProtector","dns"],bT=["components","isStarted","beforeStart","start","afterStart","beforeStop","stop","afterStop","then","_invokeStartableMethod"];function lw(r={}){let e=new y3(r);return new Proxy(e,{get(n,o,s){if(typeof o=="string"&&!bT.includes(o)){let i=e.components[o];if(i==null&&!ET.includes(o))throw new m(`${o} not set`,"ERR_SERVICE_MISSING");return i}return Reflect.get(n,o,s)},set(n,o,s){return typeof o=="string"?e.components[o]=s:Reflect.set(n,o,s),!0}})}function uw(r){let e={};for(let t of Object.values(r.components))for(let n of xT(t))e[n]=!0;for(let t of Object.values(r.components))for(let n of _T(t))if(e[n]!==!0)throw new m(`Service "${vT(t)}" required capability "${n}" but it was not provided by any component, you may need to add additional configuration when creating your node.`,"ERR_UNMET_SERVICE_DEPENDENCIES")}function xT(r){return Array.isArray(r?.[Te])?r[Te]:[]}function _T(r){return Array.isArray(r?.[Mr])?r[Mr]:[]}function vT(r){return r?.[Symbol.toStringTag]??r?.toString()??"unknown"}function dw(r={}){return{denyDialPeer:async()=>!1,denyDialMultiaddr:async e=>{let t=e.stringTuples();return t[0][0]===4||t[0][0]===41?!!Zt(`${t[0][1]}`):!1},denyInboundConnection:async()=>!1,denyOutboundConnection:async()=>!1,denyInboundEncryptedConnection:async()=>!1,denyOutboundEncryptedConnection:async()=>!1,denyInboundUpgradedConnection:async()=>!1,denyOutboundUpgradedConnection:async()=>!1,filterMultiaddrForPeer:async()=>!0,...r}}function w3(r){try{let{address:e}=r.nodeAddress();return!!Zt(e)}catch{return!0}}function ST(r,e){let t=w3(r.multiaddr),n=w3(e.multiaddr);return t&&!n?1:!t&&n?-1:0}function RT(r,e){return r.isCertified&&!e.isCertified?-1:!r.isCertified&&e.isCertified?1:0}function AT(r,e){let t=bs.exactMatch(r.multiaddr),n=bs.exactMatch(e.multiaddr);return t&&!n?1:!t&&n?-1:0}function Qi(r,e){let t=ST(r,e);if(t!==0)return t;let n=AT(r,e);return n!==0?n:RT(r,e)}var IT=32,{code:TT}=te("dnsaddr"),E3=class extends Error{constructor(e="Max recursive depth reached"){super(e),this.name="RecursionLimitError"}},Ds=async function(e,t={}){let n=t.maxRecursiveDepth??IT;if(n===0)throw new E3("Max recursive depth reached");let[,o]=e.stringTuples().find(([l])=>l===TT)??[],i=await(t?.dns??su()).query(`_dnsaddr.${o}`,{signal:t?.signal,types:[lr.TXT]}),a=e.getPeerId(),c=[];for(let l of i.Answer){let d=l.data.replace(/["']/g,"").trim().split("=")[1];if(d==null||a!=null&&!d.includes(a))continue;let u=Z(d);if(d.startsWith("/dnsaddr")){let f=await u.resolve({...t,maxRecursiveDepth:n-1});c.push(...f.map(h=>h.toString()))}else c.push(u.toString())}return c};var Jn;(function(r){r.NOT_STARTED_YET="The libp2p node is not started yet",r.ERR_PROTECTOR_REQUIRED="Private network is enforced, but no protector was provided",r.NOT_FOUND="Not found"})(Jn||(Jn={}));var Y;(function(r){r.ERR_PROTECTOR_REQUIRED="ERR_PROTECTOR_REQUIRED",r.ERR_PEER_DIAL_INTERCEPTED="ERR_PEER_DIAL_INTERCEPTED",r.ERR_CONNECTION_INTERCEPTED="ERR_CONNECTION_INTERCEPTED",r.ERR_INVALID_PROTOCOLS_FOR_STREAM="ERR_INVALID_PROTOCOLS_FOR_STREAM",r.ERR_CONNECTION_ENDED="ERR_CONNECTION_ENDED",r.ERR_CONNECTION_FAILED="ERR_CONNECTION_FAILED",r.ERR_NODE_NOT_STARTED="ERR_NODE_NOT_STARTED",r.ERR_ALREADY_ABORTED="ERR_ALREADY_ABORTED",r.ERR_TOO_MANY_ADDRESSES="ERR_TOO_MANY_ADDRESSES",r.ERR_NO_VALID_ADDRESSES="ERR_NO_VALID_ADDRESSES",r.ERR_RELAYED_DIAL="ERR_RELAYED_DIAL",r.ERR_DIALED_SELF="ERR_DIALED_SELF",r.ERR_DISCOVERED_SELF="ERR_DISCOVERED_SELF",r.ERR_DUPLICATE_TRANSPORT="ERR_DUPLICATE_TRANSPORT",r.ERR_ENCRYPTION_FAILED="ERR_ENCRYPTION_FAILED",r.ERR_HOP_REQUEST_FAILED="ERR_HOP_REQUEST_FAILED",r.ERR_INVALID_KEY="ERR_INVALID_KEY",r.ERR_INVALID_MESSAGE="ERR_INVALID_MESSAGE",r.ERR_INVALID_PARAMETERS="ERR_INVALID_PARAMETERS",r.ERR_INVALID_PEER="ERR_INVALID_PEER",r.ERR_MUXER_UNAVAILABLE="ERR_MUXER_UNAVAILABLE",r.ERR_NOT_FOUND="ERR_NOT_FOUND",r.ERR_TRANSPORT_UNAVAILABLE="ERR_TRANSPORT_UNAVAILABLE",r.ERR_TRANSPORT_DIAL_FAILED="ERR_TRANSPORT_DIAL_FAILED",r.ERR_UNSUPPORTED_PROTOCOL="ERR_UNSUPPORTED_PROTOCOL",r.ERR_PROTOCOL_HANDLER_ALREADY_REGISTERED="ERR_PROTOCOL_HANDLER_ALREADY_REGISTERED",r.ERR_INVALID_MULTIADDR="ERR_INVALID_MULTIADDR",r.ERR_SIGNATURE_NOT_VALID="ERR_SIGNATURE_NOT_VALID",r.ERR_FIND_SELF="ERR_FIND_SELF",r.ERR_NO_ROUTERS_AVAILABLE="ERR_NO_ROUTERS_AVAILABLE",r.ERR_CONNECTION_NOT_MULTIPLEXED="ERR_CONNECTION_NOT_MULTIPLEXED",r.ERR_NO_DIAL_TOKENS="ERR_NO_DIAL_TOKENS",r.ERR_INVALID_CMS="ERR_INVALID_CMS",r.ERR_MISSING_KEYS="ERR_MISSING_KEYS",r.ERR_NO_KEY="ERR_NO_KEY",r.ERR_INVALID_KEY_NAME="ERR_INVALID_KEY_NAME",r.ERR_INVALID_KEY_TYPE="ERR_INVALID_KEY_TYPE",r.ERR_KEY_ALREADY_EXISTS="ERR_KEY_ALREADY_EXISTS",r.ERR_INVALID_KEY_SIZE="ERR_INVALID_KEY_SIZE",r.ERR_KEY_NOT_FOUND="ERR_KEY_NOT_FOUND",r.ERR_OLD_KEY_NAME_INVALID="ERR_OLD_KEY_NAME_INVALID",r.ERR_NEW_KEY_NAME_INVALID="ERR_NEW_KEY_NAME_INVALID",r.ERR_PASSWORD_REQUIRED="ERR_PASSWORD_REQUIRED",r.ERR_PEM_REQUIRED="ERR_PEM_REQUIRED",r.ERR_CANNOT_READ_KEY="ERR_CANNOT_READ_KEY",r.ERR_MISSING_PRIVATE_KEY="ERR_MISSING_PRIVATE_KEY",r.ERR_MISSING_PUBLIC_KEY="ERR_MISSING_PUBLIC_KEY",r.ERR_INVALID_OLD_PASS_TYPE="ERR_INVALID_OLD_PASS_TYPE",r.ERR_INVALID_NEW_PASS_TYPE="ERR_INVALID_NEW_PASS_TYPE",r.ERR_INVALID_PASS_LENGTH="ERR_INVALID_PASS_LENGTH",r.ERR_NOT_IMPLEMENTED="ERR_NOT_IMPLEMENTED",r.ERR_WRONG_PING_ACK="ERR_WRONG_PING_ACK",r.ERR_INVALID_RECORD="ERR_INVALID_RECORD",r.ERR_ALREADY_SUCCEEDED="ERR_ALREADY_SUCCEEDED",r.ERR_NO_HANDLER_FOR_PROTOCOL="ERR_NO_HANDLER_FOR_PROTOCOL",r.ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS="ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS",r.ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS="ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS",r.ERR_CONNECTION_DENIED="ERR_CONNECTION_DENIED",r.ERR_TRANSFER_LIMIT_EXCEEDED="ERR_TRANSFER_LIMIT_EXCEEDED"})(Y||(Y={}));var CT={addresses:{listen:[],announce:[],noAnnounce:[],announceFilter:r=>r},connectionManager:{resolvers:{dnsaddr:Ds},addressSorter:Qi},transportManager:{faultTolerance:ro.FATAL_ALL}};async function fw(r){let e=qi(CT,r);if(e.connectionProtector===null&&globalThis.process?.env?.LIBP2P_FORCE_PNET!=null)throw new m(Jn.ERR_PROTECTOR_REQUIRED,Y.ERR_PROTECTOR_REQUIRED);if(e.privateKey!=null&&!(await ut(e.privateKey.public.bytes,e.privateKey.bytes)).equals(e.peerId))throw new m("Private key doesn't match peer id",Y.ERR_INVALID_KEY);return e}function Yd(r){if(to(r))return{peerId:r,multiaddrs:[]};Array.isArray(r)||(r=[r]);let e;if(r.length>0){let t=r[0].getPeerId();e=t==null?void 0:pe(t),r.forEach(n=>{if(!ko(n))throw new m("Invalid Multiaddr",Y.ERR_INVALID_MULTIADDR);let o=n.getPeerId();if(o==null){if(e!=null)throw new m("Multiaddrs must all have the same peer id or have no peer id",Y.ERR_INVALID_PARAMETERS)}else{let s=pe(o);if(e?.equals(s)!==!0)throw new m("Multiaddrs must all have the same peer id or have no peer id",Y.ERR_INVALID_PARAMETERS)}})}return{peerId:e,multiaddrs:r}}var Xd="last-dial-failure";var Qd=5,Zd=100,jd=50,Jd=1e3*60*7;var Ns={minConnections:Qd,maxQueueLength:100,autoDialConcurrency:25,autoDialPriority:0,autoDialInterval:5e3,autoDialPeerRetryThreshold:Jd,autoDialDiscoveredPeersDebounce:10},ef=class{connectionManager;peerStore;queue;minConnections;autoDialPriority;autoDialIntervalMs;autoDialMaxQueueLength;autoDialPeerRetryThresholdMs;autoDialDiscoveredPeersDebounce;autoDialInterval;started;running;log;constructor(e,t){this.connectionManager=e.connectionManager,this.peerStore=e.peerStore,this.minConnections=t.minConnections??Ns.minConnections,this.autoDialPriority=t.autoDialPriority??Ns.autoDialPriority,this.autoDialIntervalMs=t.autoDialInterval??Ns.autoDialInterval,this.autoDialMaxQueueLength=t.maxQueueLength??Ns.maxQueueLength,this.autoDialPeerRetryThresholdMs=t.autoDialPeerRetryThreshold??Ns.autoDialPeerRetryThreshold,this.autoDialDiscoveredPeersDebounce=t.autoDialDiscoveredPeersDebounce??Ns.autoDialDiscoveredPeersDebounce,this.log=e.logger.forComponent("libp2p:connection-manager:auto-dial"),this.started=!1,this.running=!1,this.queue=new qt({concurrency:t.autoDialConcurrency??Ns.autoDialConcurrency,metricName:"libp2p_autodial_queue",metrics:e.metrics}),this.queue.addEventListener("error",o=>{this.log.error("error during auto-dial",o.detail)}),e.events.addEventListener("connection:close",()=>{this.autoDial().catch(o=>{this.log.error(o)})});let n;e.events.addEventListener("peer:discovery",()=>{clearTimeout(n),n=setTimeout(()=>{this.autoDial().catch(o=>{this.log.error(o)})},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(),t=e.size;if(t>=this.minConnections){this.minConnections>0&&this.log.trace("have enough connections %d/%d",t,this.minConnections);return}if(this.queue.size>this.autoDialMaxQueueLength){this.log("not enough connections %d/%d but auto dial queue is full",t,this.minConnections),this.sheduleNextAutodial();return}this.running=!0,this.log("not enough connections %d/%d - will dial peers to increase the number of connections",t,this.minConnections);let n=new Ct(this.connectionManager.getDialQueue().map(l=>l.peerId).filter(Boolean)),o=await this.peerStore.all({filters:[l=>l.addresses.length===0?(this.log.trace("not autodialing %p because they have no addresses",l.id),!1):e.has(l.id)?(this.log.trace("not autodialing %p because they are already connected",l.id),!1):n.has(l.id)?(this.log.trace("not autodialing %p because they are already being dialed",l.id),!1):this.queue.has(l.id)?(this.log.trace("not autodialing %p because they are already being autodialed",l.id),!1):!0]}),s=o.sort(()=>Math.random()>.5?1:-1),i=new st;for(let l of s)i.has(l.id)||i.set(l.id,[...l.tags.values()].reduce((d,u)=>d+u.value,0));let c=s.sort((l,d)=>{let u=i.get(l.id)??0,f=i.get(d.id)??0;return u>f?-1:u<f?1:0}).filter(l=>{let d=l.metadata.get(Xd);if(d==null)return!0;let u=parseInt(U(d));return isNaN(u)?!0:Date.now()-u>this.autoDialPeerRetryThresholdMs});this.log("selected %d/%d peers to dial",c.length,o.length);for(let l of c)this.queue.add(async()=>{let d=this.connectionManager.getConnectionsMap().size;if(d>=this.minConnections){this.log("got enough connections now %d/%d",d,this.minConnections),this.queue.clear();return}this.log("connecting to a peerStore stored peer %p",l.id),await this.connectionManager.openConnection(l.id,{priority:this.autoDialPriority})},{peerId:l.id}).catch(d=>{this.log.error("could not connect to peerStore stored peer",d)});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 DT=["/ipfs/id/1.0.0","/ipfs/id/push/1.0.0","/libp2p/autonat/1.0.0","/libp2p/dcutr"];async function hw(r,e){let t=r?.streams?.map(o=>o.protocol)??[],n=e?.closableProtocols??DT;if(!(t.filter(o=>o!=null&&!n.includes(o)).length>0))try{await r?.close(e)}catch(o){r?.abort(o)}}var pw={maxConnections:Zd,allow:[]},tf=class{maxConnections;connectionManager;peerStore;allow;events;log;constructor(e,t={}){this.maxConnections=t.maxConnections??pw.maxConnections,this.allow=t.allow??pw.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(),t=e.length;if(this.log("checking max connections limit %d/%d",t,this.maxConnections),t<=this.maxConnections)return;let n=new st;for(let a of e){let c=a.remotePeer;if(!n.has(c)){n.set(c,0);try{let l=await this.peerStore.get(c);n.set(c,[...l.tags.values()].reduce((d,u)=>d+u.value,0))}catch(l){l.code!=="ERR_NOT_FOUND"&&this.log.error("error loading peer tags",l)}}}let o=this.sortConnections(e,n),s=Math.max(t-this.maxConnections,0),i=[];for(let a of o)if(this.log("too many connections open - closing a connection to %p",a.remotePeer),this.allow.some(l=>a.remoteAddr.toString().startsWith(l.toString()))||i.push(a),i.length===s)break;await Promise.all(i.map(async a=>{await hw(a,{signal:AbortSignal.timeout(1e3)})})),this.events.safeDispatchEvent("connection:prune",{detail:i})}sortConnections(e,t){return e.sort((n,o)=>{let s=n.timeline.open,i=o.timeline.open;return s<i?1:s>i?-1:0}).sort((n,o)=>n.direction==="outbound"&&o.direction==="inbound"?1:n.direction==="inbound"&&o.direction==="outbound"?-1:0).sort((n,o)=>n.streams.length>o.streams.length?1:n.streams.length<o.streams.length?-1:0).sort((n,o)=>{let s=t.get(n.remotePeer)??0,i=t.get(o.remotePeer)??0;return s>i?1:s<i?-1:0})}};var rf=class extends or{constructor(e={}){super({...e,sort:(t,n)=>t.options.priority>n.options.priority?-1:t.options.priority<n.options.priority?1:0})}};async function mw(r,e){let t=!1;for(let o of vi.keys())if(t=r.protoNames().includes(o),t)break;if(!t)return[r];let n=await r.resolve(e);return e.log("resolved %s to",r,n.map(o=>o.toString())),n}var gc={addressSorter:Qi,maxParallelDials:jd,maxDialQueueLength:500,maxPeerAddrsToDial:25,dialTimeout:5e3,resolvers:{dnsaddr:Ds}},nf=class{queue;components;addressSorter;maxPeerAddrsToDial;maxDialQueueLength;dialTimeout;shutDownController;connections;log;constructor(e,t={}){this.addressSorter=t.addressSorter??gc.addressSorter,this.maxPeerAddrsToDial=t.maxPeerAddrsToDial??gc.maxPeerAddrsToDial,this.maxDialQueueLength=t.maxDialQueueLength??gc.maxDialQueueLength,this.dialTimeout=t.dialTimeout??gc.dialTimeout,this.connections=t.connections??new st,this.log=e.logger.forComponent("libp2p:connection-manager:dial-queue"),this.components=e,this.shutDownController=new AbortController,K(1/0,this.shutDownController.signal);for(let[n,o]of Object.entries(t.resolvers??{}))vi.set(n,o);this.queue=new rf({concurrency:t.maxParallelDials??gc.maxParallelDials,metricName:"libp2p_dial_queue",metrics:e.metrics}),this.queue.addEventListener("error",n=>{this.log.error("error in dial queue",n.detail)})}start(){this.shutDownController=new AbortController,K(1/0,this.shutDownController.signal)}stop(){this.shutDownController.abort(),this.queue.abort()}async dial(e,t={}){let{peerId:n,multiaddrs:o}=Yd(e),s=Array.from(this.connections.values()).flat().find(a=>t.force===!0?!1:a.remotePeer.equals(n)?!0:o.find(c=>c.equals(a.remoteAddr)));if(s!=null)return this.log("already connected to %a",s.remoteAddr),t.onProgress?.(new H("dial-queue:already-connected")),s;let i=this.queue.queue.find(a=>{if(n?.equals(a.options.peerId)===!0)return!0;let c=a.options.multiaddrs;if(c==null)return!1;for(let l of o)if(c.has(l.toString()))return!0;return!1});if(i!=null){this.log("joining existing dial target for %p",n);for(let a of o)i.options.multiaddrs.add(a.toString());return t.onProgress?.(new H("dial-queue:already-in-dial-queue")),i.join(t)}if(this.queue.size>=this.maxDialQueueLength)throw new m("Dial queue is full","ERR_DIAL_QUEUE_FULL");return this.log("creating dial target for %p",n,o.map(a=>a.toString())),t.onProgress?.(new H("dial-queue:add-to-dial-queue")),this.queue.add(async a=>{a?.onProgress?.(new H("dial-queue:start-dial"));let c=this.createDialAbortController(a?.signal),l;try{l=await this.calculateMultiaddrs(n,a?.multiaddrs,{...a,signal:c}),a?.onProgress?.(new H("dial-queue:calculated-addresses",l)),l.map(({multiaddr:d})=>d.toString()).forEach(d=>{a?.multiaddrs.add(d)})}catch(d){throw c.clear(),d}try{let d=0,u=[];for(let f of l){if(d===this.maxPeerAddrsToDial)throw this.log("dialed maxPeerAddrsToDial (%d) addresses for %p, not trying any others",d,n),new m("Peer had more than maxPeerAddrsToDial",Y.ERR_TOO_MANY_ADDRESSES);d++;try{let h=await this.components.transportManager.dial(f.multiaddr,{...a,signal:c});return this.log("dial to %a succeeded",f.multiaddr),h}catch(h){if(this.log.error("dial failed to %a",f.multiaddr,h),n!=null)try{await this.components.peerStore.patch(n,{metadata:{[Xd]:L(Date.now().toString())}})}catch(p){this.log.error("could not update last dial failure key for %p",n,p)}if(c.aborted)throw new m(h.message,fn);u.push(h)}}throw u.length===1?u[0]:new bc(u,"All multiaddr dials failed",Y.ERR_TRANSPORT_DIAL_FAILED)}finally{c.clear()}},{peerId:n,priority:t.priority??I3,multiaddrs:new Set(o.map(a=>a.toString())),signal:t.signal,onProgress:t.onProgress})}createDialAbortController(e){let t=_e([AbortSignal.timeout(this.dialTimeout),this.shutDownController.signal,e]);return K(1/0,t),t}async calculateMultiaddrs(e,t=new Set,n={}){let o=[...t].map(u=>({multiaddr:Z(u),isCertified:!1}));if(e!=null){if(this.components.peerId.equals(e))throw new m("Tried to dial self",Y.ERR_DIALED_SELF);if(await this.components.connectionGater.denyDialPeer?.(e)===!0)throw new m("The dial request is blocked by gater.allowDialPeer",Y.ERR_PEER_DIAL_INTERCEPTED);if(o.length===0){this.log("loading multiaddrs for %p",e);try{let u=await this.components.peerStore.get(e);o.push(...u.addresses),this.log("loaded multiaddrs for %p",e,o.map(({multiaddr:f})=>f.toString()))}catch(u){if(u.code!==Y.ERR_NOT_FOUND)throw u}}if(o.length===0){this.log("looking up multiaddrs for %p in the peer routing",e);try{let u=await this.components.peerRouting.findPeer(e);this.log("found multiaddrs for %p in the peer routing",e,o.map(({multiaddr:f})=>f.toString())),o.push(...u.multiaddrs.map(f=>({multiaddr:f,isCertified:!1})))}catch(u){u.code!==Y.ERR_NO_ROUTERS_AVAILABLE&&this.log.error("looking up multiaddrs for %p in the peer routing failed",e,u)}}}let s=(await Promise.all(o.map(async u=>{let f=await mw(u.multiaddr,{dns:this.components.dns,...n,log:this.log});return f.length===1&&f[0].equals(u.multiaddr)?u:f.map(h=>({multiaddr:h,isCertified:!1}))}))).flat();if(e!=null){let u=`/p2p/${e.toString()}`;s=s.map(f=>f.multiaddr.protos().pop()?.path===!0?f:f.multiaddr.getPeerId()==null?{multiaddr:f.multiaddr.encapsulate(u),isCertified:f.isCertified}:f)}let i=s.filter(u=>{if(this.components.transportManager.dialTransportForMultiaddr(u.multiaddr)==null)return!1;let f=u.multiaddr.getPeerId();return e!=null&&f!=null?e.equals(f):!0}),a=new Map;for(let u of i){let f=u.multiaddr.toString(),h=a.get(f);if(h!=null){h.isCertified=h.isCertified||u.isCertified||!1;continue}a.set(f,u)}let c=[...a.values()];if(c.length===0)throw new m("The dial request has no valid addresses",Y.ERR_NO_VALID_ADDRESSES);let l=[];for(let u of c)this.components.connectionGater.denyDialMultiaddr!=null&&await this.components.connectionGater.denyDialMultiaddr(u.multiaddr)||l.push(u);let d=l.sort(this.addressSorter);if(d.length===0)throw new m("The connection gater denied all addresses in the dial request",Y.ERR_NO_VALID_ADDRESSES);return this.log.trace("addresses for %p before filtering",e??"unknown peer",s.map(({multiaddr:u})=>u.toString())),this.log.trace("addresses for %p after filtering",e??"unknown peer",d.map(({multiaddr:u})=>u.toString())),d}async isDialable(e,t={}){Array.isArray(e)||(e=[e]);try{let n=await this.calculateMultiaddrs(void 0,new Set(e.map(o=>o.toString())),t);return t.runOnTransientConnection===!1?n.find(o=>!bs.matches(o.multiaddr))!=null:!0}catch(n){this.log.trace("error calculating if multiaddr(s) were dialable",n)}return!1}};var I3=50,eo={minConnections:Qd,maxConnections:Zd,inboundConnectionThreshold:5,maxIncomingPendingConnections:10,autoDialConcurrency:25,autoDialPriority:0,autoDialMaxQueueLength:100,autoDialPeerRetryThreshold:Jd,autoDialDiscoveredPeersDebounce:10},of=class{started;connections;allow;deny;maxIncomingPendingConnections;incomingPendingConnections;maxConnections;dialQueue;autoDial;connectionPruner;inboundConnectionRateLimiter;peerStore;metrics;events;log;constructor(e,t={}){this.maxConnections=t.maxConnections??eo.maxConnections;let n=t.minConnections??eo.minConnections;if(this.maxConnections<n)throw new m("Connection Manager maxConnections must be greater than minConnections",Y.ERR_INVALID_PARAMETERS);this.connections=new st,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=(t.allow??[]).map(o=>Z(o)),this.deny=(t.deny??[]).map(o=>Z(o)),this.incomingPendingConnections=0,this.maxIncomingPendingConnections=t.maxIncomingPendingConnections??eo.maxIncomingPendingConnections,this.inboundConnectionRateLimiter=new Gi({points:t.inboundConnectionThreshold??eo.inboundConnectionThreshold,duration:1}),this.autoDial=new ef({connectionManager:this,peerStore:e.peerStore,events:e.events,logger:e.logger},{minConnections:n,autoDialConcurrency:t.autoDialConcurrency??eo.autoDialConcurrency,autoDialPriority:t.autoDialPriority??eo.autoDialPriority,autoDialPeerRetryThreshold:t.autoDialPeerRetryThreshold??eo.autoDialPeerRetryThreshold,autoDialDiscoveredPeersDebounce:t.autoDialDiscoveredPeersDebounce??eo.autoDialDiscoveredPeersDebounce,maxQueueLength:t.autoDialMaxQueueLength??eo.autoDialMaxQueueLength}),this.connectionPruner=new tf({connectionManager:this,peerStore:e.peerStore,events:e.events,logger:e.logger},{maxConnections:this.maxConnections,allow:this.allow}),this.dialQueue=new nf(e,{addressSorter:t.addressSorter??Qi,maxParallelDials:t.maxParallelDials??jd,maxDialQueueLength:t.maxDialQueueLength??500,maxPeerAddrsToDial:t.maxPeerAddrsToDial??25,dialTimeout:t.dialTimeout??5e3,resolvers:t.resolvers??{dnsaddr:Ds},connections:this.connections})}[Symbol.toStringTag]="@libp2p/connection-manager";isStarted(){return this.started}async start(){this.metrics?.registerMetricGroup("libp2p_connection_manager_connections",{calculate:()=>{let e={inbound:0,outbound:0};for(let t of this.connections.values())for(let n of t)n.direction==="inbound"?e.inbound++:e.outbound++;return e}}),this.metrics?.registerMetricGroup("libp2p_protocol_streams_total",{label:"protocol",calculate:()=>{let e={};for(let t of this.connections.values())for(let n of t)for(let o of n.streams){let s=`${o.direction} ${o.protocol??"unnegotiated"}`;e[s]=(e[s]??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 o of n){let s={};for(let i of o.streams){let a=`${i.direction} ${i.protocol??"unnegotiated"}`;s[a]=(s[a]??0)+1}for(let[i,a]of Object.entries(s))e[i]=e[i]??[],e[i].push(a)}let t={};for(let[n,o]of Object.entries(e)){o=o.sort((i,a)=>i-a);let s=Math.floor(o.length*.9);t[n]=o[s]}return t}}),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:[t=>t.tags.has($3)]});await Promise.all(e.map(async t=>{await this.openConnection(t.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 t of this.connections.values())for(let n of t)e.push((async()=>{try{await n.close()}catch(o){this.log.error(o)}})());this.log("closing %d connections",e.length),await Promise.all(e),this.connections.clear(),this.log("stopped")}onConnect(e){this._onConnect(e).catch(t=>{this.log.error(t)})}async _onConnect(e){let{detail:t}=e;if(!this.started){await t.close();return}let n=t.remotePeer,o=this.connections.get(n),s=!1;o!=null?o.push(t):(s=!0,this.connections.set(n,[t])),n.publicKey!=null&&n.type==="RSA"&&await this.peerStore.patch(n,{publicKey:n.publicKey}),s&&this.events.safeDispatchEvent("peer:connect",{detail:t.remotePeer})}onDisconnect(e){let{detail:t}=e;if(!this.started)return;let n=t.remotePeer,o=this.connections.get(n);o!=null&&o.length>1?(o=o.filter(s=>s.id!==t.id),this.connections.set(n,o)):o!=null&&(this.connections.delete(n),this.events.safeDispatchEvent("peer:disconnect",{detail:t.remotePeer}))}getConnections(e){if(e!=null)return this.connections.get(e)??[];let t=[];for(let n of this.connections.values())t=t.concat(n);return t}getConnectionsMap(){return this.connections}async openConnection(e,t={}){if(!this.isStarted())throw new m("Not started",Y.ERR_NODE_NOT_STARTED);t.signal?.throwIfAborted();let{peerId:n}=Yd(e);if(n!=null&&t.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),t.onProgress?.(new H("dial-queue:already-connected")),a}let o=await this.dialQueue.dial(e,{...t,priority:t.priority??I3}),s=this.connections.get(o.remotePeer);s==null&&(s=[],this.connections.set(o.remotePeer,s));let i=!1;for(let a of s)a.id===o.id&&(i=!0);return i||s.push(o),o}async closeConnections(e,t={}){let n=this.connections.get(e)??[];await Promise.all(n.map(async o=>{try{await o.close(t)}catch(s){o.abort(s)}}))}async acceptIncomingConnection(e){if(this.deny.some(o=>e.remoteAddr.toString().startsWith(o.toString())))return this.log("connection from %a refused - connection remote address was in deny list",e.remoteAddr),!1;if(this.allow.some(o=>e.remoteAddr.toString().startsWith(o.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 o=e.remoteAddr.nodeAddress().address;try{await this.inboundConnectionRateLimiter.consume(o,1)}catch{return this.log("connection from %a refused - inboundConnectionThreshold exceeded by host %s",e.remoteAddr,o),!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(){let e={queued:"queued",running:"active",errored:"error",complete:"success"};return this.dialQueue.queue.queue.map(t=>({id:t.id,status:e[t.status],peerId:t.options.peerId,multiaddrs:[...t.options.multiaddrs].map(n=>Z(n))}))}async isDialable(e,t={}){return this.dialQueue.isDialable(e,t)}};var LT=1e4,OT="1.0.0",BT="ping",MT="ipfs",gw=32,sf=class{protocol;components;log;heartbeatInterval;pingIntervalMs;abortController;timeout;constructor(e,t={}){this.components=e,this.protocol=`/${t.protocolPrefix??MT}/${BT}/${OT}`,this.log=e.logger.forComponent("libp2p:connection-monitor"),this.pingIntervalMs=t.pingInterval??LT,this.timeout=new Fi({...t.pingTimeout??{},metrics:e.metrics,metricName:"libp2p_connection_monitor_ping_time_milliseconds"})}[Symbol.toStringTag]="@libp2p/connection-monitor";[Te]=["@libp2p/connection-monitor"];start(){this.abortController=new AbortController,this.heartbeatInterval=setInterval(()=>{this.components.connectionManager.getConnections().forEach(e=>{Promise.resolve().then(async()=>{let t=Date.now();try{let n=this.timeout.getTimeoutSignal({signal:this.abortController?.signal}),o=await e.newStream(this.protocol,{signal:n,runOnTransientConnection:!0}),s=f1(o);t=Date.now(),await Promise.all([s.write(je(gw),{signal:n}),s.read(gw,{signal:n})]),e.rtt=Date.now()-t,await s.unwrap().close({signal:n})}catch(n){if(n.code!=="ERR_UNSUPPORTED_PROTOCOL")throw n;e.rtt=(Date.now()-t)/2}}).catch(t=>{this.log.error("error during heartbeat, aborting connection",t),e.abort(t)})})},this.pingIntervalMs)}stop(){this.abortController?.abort(),this.heartbeatInterval!=null&&clearInterval(this.heartbeatInterval)}};var af=class{routers;started;components;constructor(e,t){this.routers=t.routers??[],this.started=!1,this.components=e}[Symbol.toStringTag]="@libp2p/content-routing";isStarted(){return this.started}async start(){this.started=!0}async stop(){this.started=!1}async*findProviders(e,t={}){if(this.routers.length===0)throw new m("No content routers available",Y.ERR_NO_ROUTERS_AVAILABLE);let n=this,o=new Ct;for await(let s of Ot(...n.routers.map(i=>i.findProviders(e,t))))s!=null&&(s.multiaddrs.length>0&&await this.components.peerStore.merge(s.id,{multiaddrs:s.multiaddrs}),!o.has(s.id)&&(o.add(s.id),yield s))}async provide(e,t={}){if(this.routers.length===0)throw new m("No content routers available",Y.ERR_NO_ROUTERS_AVAILABLE);await Promise.all(this.routers.map(async n=>{await n.provide(e,t)}))}async put(e,t,n){if(!this.isStarted())throw new m(Jn.NOT_STARTED_YET,Y.ERR_NODE_NOT_STARTED);await Promise.all(this.routers.map(async o=>{await o.put(e,t,n)}))}async get(e,t){if(!this.isStarted())throw new m(Jn.NOT_STARTED_YET,Y.ERR_NODE_NOT_STARTED);return Promise.any(this.routers.map(async n=>n.get(e,t)))}};var cf=class{log;peerId;peerStore;routers;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:peer-routing"),this.peerId=e.peerId,this.peerStore=e.peerStore,this.routers=t.routers??[]}[Symbol.toStringTag]="@libp2p/peer-routing";async findPeer(e,t){if(this.routers.length===0)throw new m("No peer routers available",Y.ERR_NO_ROUTERS_AVAILABLE);if(e.toString()===this.peerId.toString())throw new m("Should not try to find self",Y.ERR_FIND_SELF);let n=this,o=Ot(...this.routers.map(s=>async function*(){try{yield await s.findPeer(e,t)}catch(i){n.log.error(i)}}()));for await(let s of o)if(s!=null)return s.multiaddrs.length>0&&await this.peerStore.merge(s.id,{multiaddrs:s.multiaddrs}),s;throw new m(Jn.NOT_FOUND,Y.ERR_NOT_FOUND)}async*getClosestPeers(e,t={}){if(this.routers.length===0)throw new m("No peer routers available",Y.ERR_NO_ROUTERS_AVAILABLE);let n=this,o=Ia(1024);for await(let s of on(async function*(){let i=Ot(...n.routers.map(a=>a.getClosestPeers(e,t)));for await(let a of i)yield async()=>{if(a.multiaddrs.length===0)try{a=await n.findPeer(a.id,{...t,useCache:!1})}catch(c){n.log.error("could not find peer multiaddrs",c);return}return a}}()))s!=null&&(s.multiaddrs.length>0&&await this.peerStore.merge(s.id,{multiaddrs:s.multiaddrs}),!o.has(s.id.toBytes())&&(o.add(s.id.toBytes()),yield s))}};var lf=class extends me{peerRouting;log;walking;walkers;shutdownController;walkController;needNext;constructor(e){super(),this.log=e.logger.forComponent("libp2p:random-walk"),this.peerRouting=e.peerRouting,this.walkers=0,this.walking=!1,this.shutdownController=new AbortController,K(1/0,this.shutdownController.signal)}[Symbol.toStringTag]="@libp2p/random-walk";start(){this.shutdownController=new AbortController,K(1/0,this.shutdownController.signal)}stop(){this.shutdownController.abort()}async*walk(e){this.walking||this.startWalk(),this.walkers++;let t=_e([this.shutdownController.signal,e?.signal]);K(1/0,t);try{for(;;)this.needNext?.resolve(),this.needNext=ee(),yield(await nr(this,"walk:peer",t,{errorEvent:"walk:error"})).detail}finally{t.clear(),this.walkers--,this.walkers===0&&(this.walkController?.abort(),this.walkController=void 0)}}startWalk(){this.walking=!0,this.walkController=new AbortController,K(1/0,this.walkController.signal);let e=_e([this.walkController.signal,this.shutdownController.signal]);K(1/0,e);let t=Date.now(),n=0;Promise.resolve().then(async()=>{for(this.log("start walk");this.walkers>0;)try{let o=je(32),s=Date.now();for await(let i of this.peerRouting.getClosestPeers(o,{signal:e}))e.aborted&&this.log("aborting walk"),e.throwIfAborted(),this.log("found peer %p after %dms for %d walkers",i.id,Date.now()-s,this.walkers),n++,this.safeDispatchEvent("walk:peer",{detail:i}),this.walkers===1&&this.needNext!=null&&(this.log("wait for need next"),await Ce(this.needNext.promise,e)),s=Date.now();this.log("walk iteration for %b and %d walkers finished, found %d peers",o,this.walkers,n)}catch(o){this.log.error("randomwalk errored",o),this.safeDispatchEvent("walk:error",{detail:o})}this.log("no walkers left, ended walk")}).catch(o=>{this.log.error("randomwalk errored",o)}).finally(()=>{this.log("finished walk, found %d peers after %dms",n,Date.now()-t),this.walking=!1})}};var T3=32,C3=64,uf=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)}[Symbol.toStringTag]="@libp2p/registrar";getProtocols(){return Array.from(new Set([...this.handlers.keys()])).sort()}getHandler(e){let t=this.handlers.get(e);if(t==null)throw new m(`No handler registered for protocol ${e}`,Y.ERR_NO_HANDLER_FOR_PROTOCOL);return t}getTopologies(e){let t=this.topologies.get(e);return t==null?[]:[...t.values()]}async handle(e,t,n){if(this.handlers.has(e))throw new m(`Handler already registered for protocol ${e}`,Y.ERR_PROTOCOL_HANDLER_ALREADY_REGISTERED);let o=qi.bind({ignoreUndefined:!0})({maxInboundStreams:T3,maxOutboundStreams:C3},n);this.handlers.set(e,{handler:t,options:o}),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,t){if(t==null)throw new m("invalid topology",Y.ERR_INVALID_PARAMETERS);let n=`${(Math.random()*1e9).toString(36)}${Date.now()}`,o=this.topologies.get(e);return o==null&&(o=new Map,this.topologies.set(e,o)),o.set(n,t),n}unregister(e){for(let[t,n]of this.topologies.entries())n.has(e)&&(n.delete(e),n.size===0&&this.topologies.delete(t))}_onDisconnect(e){let t=e.detail;this.components.peerStore.get(t).then(n=>{for(let o of n.protocols){let s=this.topologies.get(o);if(s!=null)for(let i of s.values())i.filter?.has(t)!==!1&&(i.filter?.remove(t),i.onDisconnect?.(t))}}).catch(n=>{n.code!==Y.ERR_NOT_FOUND&&this.log.error("could not inform topologies of disconnecting peer %p",t,n)})}_onPeerUpdate(e){let{peer:t,previous:n}=e.detail,o=(n?.protocols??[]).filter(s=>!t.protocols.includes(s));for(let s of o){let i=this.topologies.get(s);if(i!=null)for(let a of i.values())a.filter?.has(t.id)!==!1&&(a.filter?.remove(t.id),a.onDisconnect?.(t.id))}}_onPeerIdentify(e){let t=e.detail.protocols,n=e.detail.connection,o=e.detail.peerId;for(let s of t){let i=this.topologies.get(s);if(i!=null)for(let a of i.values())n.transient&&a.notifyOnTransient!==!0||a.filter?.has(o)!==!0&&(a.filter?.add(o),a.onConnect?.(o,n))}}};var df=class{log;components;transports;listeners;faultTolerance;started;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:transports"),this.components=e,this.started=!1,this.transports=new Map,this.listeners=Pu({name:"libp2p_transport_manager_listeners",metrics:this.components.metrics}),this.faultTolerance=t.faultTolerance??ro.FATAL_ALL}[Symbol.toStringTag]="@libp2p/transport-manager";add(e){let t=e[Symbol.toStringTag];if(t==null)throw new m("Transport must have a valid tag",Y.ERR_INVALID_KEY);if(this.transports.has(t))throw new m(`There is already a transport with the tag ${t}`,Y.ERR_DUPLICATE_TRANSPORT);this.log("adding transport %s",t),this.transports.set(t,e),this.listeners.has(t)||this.listeners.set(t,[])}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[t,n]of this.listeners)for(this.log("closing listeners for %s",t);n.length>0;){let o=n.pop();o!=null&&e.push(o.close())}await Promise.all(e),this.log("all listeners closed");for(let t of this.listeners.keys())this.listeners.set(t,[]);this.started=!1}async dial(e,t){let n=this.dialTransportForMultiaddr(e);if(n==null)throw new m(`No transport available for address ${String(e)}`,Y.ERR_TRANSPORT_UNAVAILABLE);t?.onProgress?.(new H("transport-manager:selected-transport",n[Symbol.toStringTag]));try{return await n.dial(e,{...t,upgrader:this.components.upgrader})}catch(o){throw o.code==null&&(o.code=Y.ERR_TRANSPORT_DIAL_FAILED),o}}getAddrs(){let e=[];for(let t of this.listeners.values())for(let n of t)e=[...e,...n.getAddrs()];return e}getTransports(){return Array.of(...this.transports.values())}getListeners(){return Array.of(...this.listeners.values()).flat()}dialTransportForMultiaddr(e){for(let t of this.transports.values())if(t.dialFilter([e]).length>0)return t}listenTransportForMultiaddr(e){for(let t of this.transports.values())if(t.listenFilter([e]).length>0)return t}async listen(e){if(!this.isStarted())throw new m("Not started",Y.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 t=[];for(let[n,o]of this.transports.entries()){let s=o.listenFilter(e),i=[];for(let l of s){this.log("creating listener for %s on %a",n,l);let d=o.createListener({upgrader:this.components.upgrader}),u=this.listeners.get(n)??[];u==null&&(u=[],this.listeners.set(n,u)),u.push(d),d.addEventListener("listening",()=>{this.components.events.safeDispatchEvent("transport:listening",{detail:d})}),d.addEventListener("close",()=>{let f=u.findIndex(h=>h===d);u.splice(f,1),this.components.events.safeDispatchEvent("transport:close",{detail:d})}),i.push(d.listen(l))}if(i.length===0){t.push(n);continue}if((await Promise.allSettled(i)).find(l=>l.status==="fulfilled")==null&&this.faultTolerance!==ro.NO_FATAL)throw new m(`Transport (${n}) could not listen on any available address`,Y.ERR_NO_VALID_ADDRESSES)}if(t.length===this.transports.size){let n=`no valid addresses were provided for transports [${t.join(", ")}]`;if(this.faultTolerance===ro.FATAL_ALL)throw new m(n,Y.ERR_NO_VALID_ADDRESSES);this.log(`libp2p in dial mode only: ${n}`)}}async remove(e){let t=this.listeners.get(e)??[];this.log.trace("removing transport %s",e);let n=[];for(this.log.trace("closing listeners for %s",e);t.length>0;){let o=t.pop();o!=null&&n.push(o.close())}await Promise.all(n),this.transports.delete(e),this.listeners.delete(e)}async removeAll(){let e=[];for(let t of this.transports.keys())e.push(this.remove(t));await Promise.all(e)}};var Rt="/multistream/1.0.0";var UT=L(`
|
|
38
|
+
`),r}var Iy=Array.from("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),Ty=r=>[...Array(r)].map(()=>Iy.at(Math.floor(Math.random()*Iy.length))).join("");var cT=1e4,joe=te("webrtc-direct").code,Ay=te("certhash").code,Pd=class{log;metrics;components;init;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:webrtc-direct"),this.components=e,this.init=t,e.metrics!=null&&(this.metrics={dialerEvents:e.metrics.registerCounterGroup("libp2p_webrtc-direct_dialer_events_total",{label:"event",help:"Total count of WebRTC-direct dial events by type"})})}[un]=!0;[Symbol.toStringTag]="@libp2p/webrtc-direct";[Te]=["@libp2p/transport"];async dial(e,t){let n=await this._connect(e,t);return this.log("dialing address: %a",e),n}createListener(e){throw cy("WebRTCTransport.createListener")}listenFilter(e){return e.filter(q5.exactMatch)}dialFilter(e){return this.listenFilter(e)}async _connect(e,t){let n=new AbortController,o=n.signal,s=e.getPeerId();if(s===null)throw vd("we need to have the remote's PeerId");let i=pe(s),a=o3(Nd(e)),c=await ks.generateCertificate({name:"ECDSA",namedCurve:"P-256",hash:s3(a.code)}),l=new ks({...await pc(this.init.rtcConfiguration),certificates:[c]});try{let d=new Promise((S,I)=>{let F=l.createDataChannel("",{negotiated:!0,id:0}),O=setTimeout(()=>{let B=`Data channel was never opened: state: ${F.readyState}`;this.log.error(B),this.metrics?.dialerEvents.increment({open_error:!0}),I(Jp("data",B))},cT);F.onopen=B=>{clearTimeout(O),S(F)},F.onerror=B=>{clearTimeout(O);let D=`Error opening a data channel for handshaking: ${B.target?.toString()??"not specified"}`;this.log.error(D),this.metrics?.dialerEvents.increment({unknown_error:!0}),I(Jp("data",D))}}),u="libp2p+webrtc+v1/"+Ty(32),f=await l.createOffer(),h=Ry(f,u);await l.setLocalDescription(h);let p=Sy(e,u);await l.setRemoteDescription(p);let g=await d,y=this.components.peerId,w=this.generateNoisePrologue(l,a.code,e),b=Ti({prologueBytes:w})(this.components),E=Wi({channel:g,direction:"inbound",logger:this.components.logger,...this.init.dataChannel??{}}),x={...E,sink:E.sink.bind(E),source:async function*(){for await(let S of E.source)for(let I of S)yield I}()},T=new Cs(this.components,{peerConnection:l,remoteAddr:e,timeline:{open:Date.now()},metrics:this.metrics?.dialerEvents}),C=hc?"iceconnectionstatechange":"connectionstatechange";l.addEventListener(C,()=>{switch(l.connectionState){case"failed":case"disconnected":case"closed":T.close().catch(S=>{this.log.error("error closing connection",S)}).finally(()=>{n.abort()});break;default:break}},{signal:o}),this.metrics?.dialerEvents.increment({peer_connection:!0});let v=new $o(this.components,{peerConnection:l,metrics:this.metrics?.dialerEvents,dataChannelOptions:this.init.dataChannel});return await b.secureInbound(y,x,i),await t.upgrader.upgradeOutbound(T,{skipProtection:!0,skipEncryption:!0,muxerFactory:v})}catch(d){throw l.close(),d}}generateNoisePrologue(e,t,n){if(e.getConfiguration().certificates?.length===0)throw fc("no local certificate");let o=vy(e,{log:this.log});if(o==null)throw fc("no local fingerprint found");let s=o.trim().toLowerCase().replaceAll(":",""),i=L(s,"hex"),a=ir(t,i),c=n3.decode(Nd(n)),l=L("libp2p-webrtc-noise:");return ve([l,a.bytes,c])}};function Cy(r){return e=>new Pd(e,r)}function ky(r){return e=>new Dd(e,r)}var Dy=async r=>{if(r.readyState>=2)throw new Error("socket closed");r.readyState!==1&&await new Promise((e,t)=>{function n(){r.removeEventListener("open",o),r.removeEventListener("error",s)}function o(){n(),e()}function s(i){n(),t(i.error??new Error(`connect ECONNREFUSED ${r.url}`))}r.addEventListener("open",o),r.addEventListener("error",s)})};var Ny=(r,e)=>(e=e??{},e.closeOnEnd=e.closeOnEnd!==!1,async n=>{for await(let o of n){try{await Dy(r)}catch(s){if(s.message==="socket closed")break;throw s}if(r.readyState===r.CLOSING||r.readyState===r.CLOSED)break;r.send(o)}e.closeOnEnd!=null&&r.readyState<=1&&await new Promise((o,s)=>{r.addEventListener("close",i=>{if(i.wasClean||i.code===1006)o();else{let a=Object.assign(new Error("ws error"),{event:i});s(a)}}),setTimeout(()=>{r.close()})})});var By=nt(Ly(),1);function Oy(r){return r instanceof ArrayBuffer||r?.constructor?.name==="ArrayBuffer"&&typeof r?.byteLength=="number"}var My=r=>{r.binaryType="arraybuffer";let e=async()=>{await new Promise((s,i)=>{if(n){s();return}if(o!=null){i(o);return}let a=d=>{r.removeEventListener("open",c),r.removeEventListener("error",l),d()},c=()=>{a(s)},l=d=>{a(()=>{i(d.error??new Error(`connect ECONNREFUSED ${r.url}`))})};r.addEventListener("open",c),r.addEventListener("error",l)})},t=async function*(){let s=new By.EventIterator(({push:i,stop:a,fail:c})=>{let l=u=>{let f=null;typeof u.data=="string"&&(f=L(u.data)),Oy(u.data)&&(f=new Uint8Array(u.data)),u.data instanceof Uint8Array&&(f=u.data),f!=null&&i(f)},d=u=>{c(u.error??new Error("Socket error"))};return r.addEventListener("message",l),r.addEventListener("error",d),r.addEventListener("close",a),()=>{r.removeEventListener("message",l),r.removeEventListener("error",d),r.removeEventListener("close",a)}},{highWaterMark:1/0});await e();for await(let i of s)yield Oy(i)?new Uint8Array(i):i}(),n=r.readyState===1,o;return r.addEventListener("open",()=>{n=!0,o=null}),r.addEventListener("close",()=>{n=!1,o=null}),r.addEventListener("error",s=>{n||(o=s.error??new Error(`connect ECONNREFUSED ${r.url}`))}),Object.assign(t,{connected:e})};var Uy=(r,e)=>{e=e??{};let t=My(r),n=e.remoteAddress,o=e.remotePort;if(r.url!=null)try{let i=new URL(r.url);n=i.hostname,o=parseInt(i.port,10)}catch{}if(n==null||o==null)throw new Error("Remote connection did not have address and/or port");return{sink:Ny(r,e),source:t,connected:async()=>{await t.connected()},close:async()=>{(r.readyState===r.CONNECTING||r.readyState===r.OPEN)&&await new Promise(i=>{r.addEventListener("close",()=>{i()}),r.close()})},destroy:()=>{r.terminate!=null?r.terminate():r.close()},remoteAddress:n,remotePort:o,socket:r}};var Fy=WebSocket;var uT={"http:":"ws:","https:":"wss:"},Vy="ws:",Ky=(r,e)=>{if(r.startsWith("//")&&(r=`${e?.protocol??Vy}${r}`),r.startsWith("/")&&e!=null){let n=e.protocol??Vy,o=e.host,s=e.port!=null&&o?.endsWith(`:${e.port}`)!==!0?`:${e.port}`:"";r=`${n}//${o}${s}${r}`}let t=new URL(r);for(let[n,o]of Object.entries(uT))t.protocol===n&&(t.protocol=o);return t};function $y(r,e){let t=typeof window>"u"?void 0:window.location;e=e??{};let n=Ky(r,t),o=new Fy(n.toString(),e.websocket);return Uy(o,e)}function Hy(r){return r.filter(e=>{if(e.protoCodes().includes(290))return!1;let t=e.decapsulateCode(421);return Di.matches(t)||Ss.matches(t)})}function qy(r){return r.filter(e=>{if(e.protoCodes().includes(290))return!1;let t=e.decapsulateCode(421);return Ss.matches(t)})}function Gy(){throw new Error("WebSocket Servers can not be created in the browser!")}function Wy(r,e,t){let n=t.logger.forComponent("libp2p:websockets:maconn"),o=t.metrics,s=t.metricPrefix??"",i={log:n,async sink(a){try{await r.sink(async function*(){for await(let c of a)c instanceof Uint8Array?yield c:yield c.subarray()}())}catch(c){c.type!=="aborted"&&n.error(c)}},source:r.source,remoteAddr:e,timeline:{open:Date.now()},async close(a={}){let c=Date.now();if(a.signal==null){let d=AbortSignal.timeout(500);a={...a,signal:d}}let l=()=>{let{host:d,port:u}=i.remoteAddr.toOptions();n("timeout closing stream to %s:%s after %dms, destroying it manually",d,u,Date.now()-c),this.abort(new m("Socket close timeout","ERR_SOCKET_CLOSE_TIMEOUT"))};a.signal?.addEventListener("abort",l);try{await r.close()}catch(d){n.error("error closing WebSocket gracefully",d),this.abort(d)}finally{a.signal?.removeEventListener("abort",l),i.timeline.close=Date.now()}},abort(a){let{host:c,port:l}=i.remoteAddr.toOptions();n("timeout closing stream to %s:%s due to error",c,l,a),r.destroy(),i.timeline.close=Date.now(),o?.increment({[`${s}error`]:!0})}};return r.socket.addEventListener("close",()=>{o?.increment({[`${s}close`]:!0}),i.timeline.close==null&&(i.timeline.close=Date.now())},{once:!0}),i}var c3=class{log;init;logger;metrics;components;constructor(e,t){this.log=e.logger.forComponent("libp2p:websockets"),this.logger=e.logger,this.components=e,this.init=t,e.metrics!=null&&(this.metrics={dialerEvents:e.metrics.registerCounterGroup("libp2p_websockets_dialer_events_total",{label:"event",help:"Total count of WebSockets dialer events by type"})})}[un]=!0;[Symbol.toStringTag]="@libp2p/websockets";[Te]=["@libp2p/transport"];async dial(e,t){this.log("dialing %s",e),t=t??{};let n=await this._connect(e,t),o=Wy(n,e,{logger:this.logger,metrics:this.metrics?.dialerEvents});this.log("new outbound connection %s",o.remoteAddr);let s=await t.upgrader.upgradeOutbound(o,t);return this.log("outbound connection %s upgraded",o.remoteAddr),s}async _connect(e,t){t?.signal?.throwIfAborted();let n=e.toOptions();this.log("dialing %s:%s",n.host,n.port);let o=ee(),s=$y(zu(e),this.init);s.socket.addEventListener("error",()=>{let i=new m(`Could not connect to ${e.toString()}`,"ERR_CONNECTION_FAILED");this.log.error("connection error:",i),this.metrics?.dialerEvents.increment({error:!0}),o.reject(i)});try{t.onProgress?.(new H("websockets:open-connection")),await Ce(Promise.race([s.connected(),o.promise]),t.signal)}catch(i){throw t.signal?.aborted===!0&&this.metrics?.dialerEvents.increment({abort:!0}),s.close().catch(a=>{this.log.error("error closing raw socket",a)}),i}return this.log("connected %s",e),this.metrics?.dialerEvents.increment({connect:!0}),s}createListener(e){return Gy({logger:this.logger,metrics:this.components.metrics},{...this.init,...e})}listenFilter(e){return e=Array.isArray(e)?e:[e],this.init?.filter!=null?this.init?.filter(e):$1||H1?qy(e):Hy(e)}dialFilter(e){return this.listenFilter(e)}};function zy(r={}){return e=>new c3(e,r)}function l3(r){throw new Error("Not implemented")}var u3=class extends bn{writer;reader;constructor(e){super(e),this.writer=e.bidiStream.writable.getWriter(),this.reader=e.bidiStream.readable.getReader(),Promise.resolve().then(async()=>{for(;;){let t=await this.reader.read();if(t.done){e.log("remote closed write");return}t.value!=null&&this.sourcePush(new ae(t.value))}}).catch(t=>{e.log.error("error reading from stream",t),this.abort(t)}).finally(()=>{this.remoteCloseWrite()}),this.writer.closed.then(()=>{e.log("writer closed")}).catch(t=>{e.log("writer close promise rejected",t)}).finally(()=>{this.remoteCloseRead()})}sendNewStream(e){}async sendData(e,t){for await(let n of e)this.log("sendData waiting for writer to be ready"),await Ce(this.writer.ready,t?.signal),this.writer.write(n).catch(o=>{this.log.error("error sending stream data",o)})}async sendReset(e){this.log("sendReset aborting writer"),await Ce(this.writer.abort(),e?.signal),this.log("sendReset aborted writer")}async sendCloseWrite(e){this.log("sendCloseWrite closing writer"),await Ce(this.writer.close(),e?.signal),this.log("sendCloseWrite closed writer")}async sendCloseRead(e){this.log("sendCloseRead cancelling reader"),await Ce(this.reader.cancel(),e?.signal),this.log("sendCloseRead cancelled reader")}};async function d3(r,e,t,n,o,s){let i=s.forComponent(`libp2p:webtransport:stream:${t}:${e}`),a=new u3({bidiStream:r,id:e,direction:t,log:i,onEnd:()=>{let c=n.findIndex(l=>l===a);c!==-1&&n.splice(c,1),o?.(a)}});return a}function Bd(){return{source:{[Symbol.asyncIterator](){return{async next(){return new Promise(()=>{})}}}},sink:async r=>new Promise(()=>{})}}function Yy(r,e,t,n){let o=0,s=t.forComponent("libp2p:webtransport:muxer");return{protocol:"webtransport",createStreamMuxer:i=>{typeof i=="function"&&(i={onIncomingStream:i});let a=[];Promise.resolve().then(async()=>{for(;;){let{done:l,value:d}=await e.read();if(l)break;if(a.length>=n.maxInboundStreams)s(`too many inbound streams open - ${a.length}/${n.maxInboundStreams}, closing new incoming stream`),d.writable.close().catch(u=>{s.error(`failed to close inbound stream that crossed our maxInboundStream limit: ${u.message}`)}),d.readable.cancel().catch(u=>{s.error(`failed to close inbound stream that crossed our maxInboundStream limit: ${u.message}`)});else{let u=await d3(d,String(o++),"inbound",a,i?.onStreamEnd,t);a.push(u),i?.onIncomingStream?.(u)}}}).catch(l=>{s.error("could not create a new stream",l)});let c={protocol:"webtransport",streams:a,newStream:async l=>{s("new outgoing stream",l);let d=await r.createBidirectionalStream(),u=await d3(d,String(o++),i?.direction??"outbound",a,i?.onStreamEnd,t);return a.push(u),u},close:async()=>{s("closing webtransport muxer gracefully");try{r.close()}catch(l){c.abort(l)}},abort:l=>{s("closing webtransport muxer with err:",l);try{r.close()}catch(d){s.error("webtransport session threw error during close",d)}},...Bd()};return c}}}function Xy(r,e){return e.filter(n=>!!r.find(o=>J(n,o))).length===e.length}var pT=Object.values(xr).map(r=>r.decoder).reduce((r,e)=>r.or(e));function mT(r){return Bt.decode(pT.decode(r))}function f3(r){if(!Wu.matches(r))throw new m("Invalid multiaddr, was not a WebTransport address","ERR_INVALID_MULTIADDR");let e=r.stringTuples(),t=e.filter(([i,a])=>i===te("certhash").code).map(([i,a])=>mT(a??"")),n=e.filter(([i,a])=>i===te("p2p").code).map(([i,a])=>pe(a??""))[0],o=r.toOptions(),s=o.host;return o.family===6&&s?.includes(":")&&(s=`[${s}]`),{url:`https://${s}:${o.port}`,certhashes:t,remotePeer:n}}var Qy=globalThis.WebTransport;var h3=class{log;components;config;metrics;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:webtransport"),this.components=e,this.config={...t,maxInboundStreams:t.maxInboundStreams??1e3,certificates:t.certificates??[]},e.metrics!=null&&(this.metrics={dialerEvents:e.metrics.registerCounterGroup("libp2p_webtransport_dialer_events_total",{label:"event",help:"Total count of WebTransport dialer events by type"})})}[Symbol.toStringTag]="@libp2p/webtransport";[un]=!0;[Te]=["@libp2p/transport"];async dial(e,t){if(t?.signal?.aborted===!0)throw new dn;this.log("dialing %s",e);let n=this.components.peerId;if(n===void 0)throw new m("Need a local peerid","ERR_INVALID_PARAMETERS");t=t??{};let{url:o,certhashes:s,remotePeer:i}=f3(e),a,c,l=()=>{},d=!1,u=!1,f=!1;try{this.metrics?.dialerEvents.increment({pending:!0});let h=new Qy(`${o}/.well-known/libp2p-webtransport?type=noise`,{serverCertificateHashes:s.map(p=>({algorithm:"sha-256",value:p.digest}))});if(l=p=>{if(!d)try{this.metrics?.dialerEvents.increment({[p]:!0}),h.close()}catch(g){this.log.error("error closing wt session",g)}finally{c!=null&&(c.timeline.close=Date.now()),d=!0}},a=()=>{l(u?"noise_timeout":"ready_timeout")},t.signal?.addEventListener("abort",a,{once:!0}),this.log("wait for session to be ready"),t.onProgress?.(new H("webtransport:wait-for-session")),await Promise.race([h.closed,h.ready]),this.log("session became ready"),u=!0,this.metrics?.dialerEvents.increment({ready:!0}),h.closed.catch(p=>{this.log.error("error on remote wt session close",p)}).finally(()=>{l("remote_close")}),f=await Ce(this.authenticateWebTransport({wt:h,localPeer:n,remotePeer:i,certhashes:s,...t}),t.signal),!f)throw new m("Failed to authenticate webtransport","ERR_AUTHENTICATION_FAILED");return this.metrics?.dialerEvents.increment({open:!0}),c={close:async()=>{this.log("closing webtransport"),l("close")},abort:p=>{this.log("aborting webtransport due to passed err",p),l("abort")},remoteAddr:e,timeline:{open:Date.now()},log:this.components.logger.forComponent("libp2p:webtransport:maconn"),...Bd()},await t.upgrader.upgradeOutbound(c,{skipEncryption:!0,muxerFactory:Yy(h,h.incomingBidirectionalStreams.getReader(),this.components.logger,this.config),skipProtection:!0,onProgress:t.onProgress})}catch(h){throw this.log.error("caught wt session err",h),l(f?"upgrade_error":u?"noise_error":"ready_error"),h}finally{a!=null&&t.signal?.removeEventListener("abort",a)}}async authenticateWebTransport({wt:e,localPeer:t,remotePeer:n,certhashes:o,onProgress:s,signal:i}){i?.throwIfAborted(),s?.(new H("webtransport:open-authentication-stream"));let a=await e.createBidirectionalStream(),c=a.writable.getWriter(),l=a.readable.getReader(),d={source:async function*(){for(;;){let h=await l.read();if(h.value!=null&&(yield h.value),h.done)break}}(),sink:async h=>{for await(let p of h){await Ce(c.ready,i);let g=p instanceof Uint8Array?p:p.subarray();c.write(g).catch(y=>{this.log.error("could not write chunk during authentication of WebTransport stream",y)})}}},u=Ti()(this.components);s?.(new H("webtransport:secure-outbound-connection"));let{remoteExtensions:f}=await u.secureOutbound(t,d,n);if(s?.(new H("webtransport:close-authentication-stream")),c.close().catch(h=>{this.log.error(`Failed to close authentication stream writer: ${h.message}`)}),l.cancel().catch(h=>{this.log.error(`Failed to close authentication stream reader: ${h.message}`)}),!Xy(f?.webtransportCerthashes??[],o.map(h=>h.bytes)))throw new Error("Our certhashes are not a subset of the remote's reported certhashes");return!0}createListener(e){return l3(this.components,{...e,certificates:this.config.certificates,maxInboundStreams:this.config.maxInboundStreams})}listenFilter(){return[]}dialFilter(e){return globalThis.WebTransport==null?[]:e.filter(t=>{if(!Wu.exactMatch(t))return!1;let{url:n,certhashes:o}=f3(t);return n!=null&&o.length>0})}};function Zy(r={}){return e=>new h3(e,r)}var p3=nt(e1(),1);function jy(r,e){let t=e.map((n,o)=>({record:wn(n),index:o}));return t.sort((n,o)=>{let s=n.record.sequence,i=o.record.sequence;if(s>i)return-1;if(s<i)return 1;if(n.record.validityType===Jt.ValidityType.EOL&&o.record.validityType===Jt.ValidityType.EOL){let a=p3.default.fromString(n.record.validity).toDate(),c=p3.default.fromString(o.record.validity).toDate();if(a.getTime()>c.getTime())return-1;if(a.getTime()<c.getTime())return 1}return 0}),t[0].index}var Md="1.9.4",Ud="libp2p";var ew="4.2.6",tw="helia";var rw={list:["/dnsaddr/bootstrap.libp2p.io/p2p/QmNnooDu7bfjPFoTZYxMNLWUQJyrVwtbZg5gBMjTezGAJN","/dnsaddr/bootstrap.libp2p.io/p2p/QmbLHAnMoJPWSCR5Zhtx6BHJX9KiKNN6tpvbUcqanj75Nb","/dnsaddr/bootstrap.libp2p.io/p2p/QmcZf59bWwK5XFi76CZX8cbJ4BhTzzA3gU1ZjYZcYW3dwt","/ip4/104.131.131.82/tcp/4001/p2p/QmaCpDMGvV2BGHeYERUEnRQAwe3N8SzbUtfsmvsqQLuvuJ"]};function Fd(r={}){let e=`${tw}/${ew} ${Ud}/${Md} UserAgent=${globalThis.navigator.userAgent}`;return{peerId:r.peerId,dns:r.dns,addresses:{listen:["/webrtc"]},transports:[Rp({discoverRelays:1}),ky(),Cy(),Zy(),zy()],connectionEncryption:[Ti()],streamMuxers:[f7(),ry()],peerDiscovery:[T7(rw)],services:{autoNAT:g7(),dcutr:H7(),delegatedRouting:()=>mg("https://delegated-ipfs.dev"),dht:C9({clientMode:!0,validators:{ipns:n1},selectors:{ipns:jy}}),identify:n9({agentVersion:e}),identifyPush:o9({agentVersion:e}),keychain:Ed(r.keychain),ping:ay()}}}var nw=async()=>{let r=await xa("Ed25519"),e=await gT(r);if(e.type==="Ed25519")return e;throw new Error(`Generated unexpected PeerId type "${e.type}"`)};async function gT(r){return ut(e0(r.public),t0(r))}var St={ERR_INVALID_PARAMETERS:"ERR_INVALID_PARAMETERS"};var zi;(function(r){let e;(function(o){let s;o.codec=()=>(s==null&&(s=oe((i,a,c={})=>{c.lengthDelimited!==!1&&a.fork(),i.key!=null&&i.key!==""&&(a.uint32(10),a.string(i.key)),i.value!=null&&i.value.byteLength>0&&(a.uint32(18),a.bytes(i.value)),c.lengthDelimited!==!1&&a.ldelim()},(i,a)=>{let c={key:"",value:new Uint8Array(0)},l=a==null?i.len:i.pos+a;for(;i.pos<l;){let d=i.uint32();switch(d>>>3){case 1:c.key=i.string();break;case 2:c.value=i.bytes();break;default:i.skipType(d&7);break}}return c})),s),o.encode=i=>ne(i,o.codec()),o.decode=i=>re(i,o.codec())})(e=r.Peer$metadataEntry||(r.Peer$metadataEntry={}));let t;(function(o){let s;o.codec=()=>(s==null&&(s=oe((i,a,c={})=>{c.lengthDelimited!==!1&&a.fork(),i.key!=null&&i.key!==""&&(a.uint32(10),a.string(i.key)),i.value!=null&&(a.uint32(18),Kd.codec().encode(i.value,a)),c.lengthDelimited!==!1&&a.ldelim()},(i,a)=>{let c={key:""},l=a==null?i.len:i.pos+a;for(;i.pos<l;){let d=i.uint32();switch(d>>>3){case 1:c.key=i.string();break;case 2:c.value=Kd.codec().decode(i,i.uint32());break;default:i.skipType(d&7);break}}return c})),s),o.encode=i=>ne(i,o.codec()),o.decode=i=>re(i,o.codec())})(t=r.Peer$tagsEntry||(r.Peer$tagsEntry={}));let n;r.codec=()=>(n==null&&(n=oe((o,s,i={})=>{if(i.lengthDelimited!==!1&&s.fork(),o.addresses!=null)for(let a of o.addresses)s.uint32(10),Vd.codec().encode(a,s);if(o.protocols!=null)for(let a of o.protocols)s.uint32(18),s.string(a);if(o.publicKey!=null&&(s.uint32(34),s.bytes(o.publicKey)),o.peerRecordEnvelope!=null&&(s.uint32(42),s.bytes(o.peerRecordEnvelope)),o.metadata!=null&&o.metadata.size!==0)for(let[a,c]of o.metadata.entries())s.uint32(50),r.Peer$metadataEntry.codec().encode({key:a,value:c},s);if(o.tags!=null&&o.tags.size!==0)for(let[a,c]of o.tags.entries())s.uint32(58),r.Peer$tagsEntry.codec().encode({key:a,value:c},s);i.lengthDelimited!==!1&&s.ldelim()},(o,s)=>{let i={addresses:[],protocols:[],metadata:new Map,tags:new Map},a=s==null?o.len:o.pos+s;for(;o.pos<a;){let c=o.uint32();switch(c>>>3){case 1:i.addresses.push(Vd.codec().decode(o,o.uint32()));break;case 2:i.protocols.push(o.string());break;case 4:i.publicKey=o.bytes();break;case 5:i.peerRecordEnvelope=o.bytes();break;case 6:{let l=r.Peer$metadataEntry.codec().decode(o,o.uint32());i.metadata.set(l.key,l.value);break}case 7:{let l=r.Peer$tagsEntry.codec().decode(o,o.uint32());i.tags.set(l.key,l.value);break}default:o.skipType(c&7);break}}return i})),n),r.encode=o=>ne(o,r.codec()),r.decode=o=>re(o,r.codec())})(zi||(zi={}));var Vd;(function(r){let e;r.codec=()=>(e==null&&(e=oe((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.multiaddr!=null&&t.multiaddr.byteLength>0&&(n.uint32(10),n.bytes(t.multiaddr)),t.isCertified!=null&&(n.uint32(16),n.bool(t.isCertified)),o.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let o={multiaddr:new Uint8Array(0)},s=n==null?t.len:t.pos+n;for(;t.pos<s;){let i=t.uint32();switch(i>>>3){case 1:o.multiaddr=t.bytes();break;case 2:o.isCertified=t.bool();break;default:t.skipType(i&7);break}}return o})),e),r.encode=t=>ne(t,r.codec()),r.decode=t=>re(t,r.codec())})(Vd||(Vd={}));var Kd;(function(r){let e;r.codec=()=>(e==null&&(e=oe((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.value!=null&&t.value!==0&&(n.uint32(8),n.uint32(t.value)),t.expiry!=null&&(n.uint32(16),n.uint64(t.expiry)),o.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let o={value:0},s=n==null?t.len:t.pos+n;for(;t.pos<s;){let i=t.uint32();switch(i>>>3){case 1:o.value=t.uint32();break;case 2:o.expiry=t.uint64();break;default:t.skipType(i&7);break}}return o})),e),r.encode=t=>ne(t,r.codec()),r.decode=t=>re(t,r.codec())})(Kd||(Kd={}));function Yi(r,e){let t=zi.decode(e);t.publicKey!=null&&r.publicKey==null&&(r=Tm({...r,publicKey:r.publicKey}));let n=new Map,o=BigInt(Date.now());for(let[s,i]of t.tags.entries())i.expiry!=null&&i.expiry<o||n.set(s,i);return{...t,id:r,addresses:t.addresses.map(({multiaddr:s,isCertified:i})=>({multiaddr:Z(s),isCertified:i??!1})),metadata:t.metadata,peerRecordEnvelope:t.peerRecordEnvelope??void 0,tags:n}}var m3="/peers/";function Xi(r){if(!to(r)||r.type==null)throw new m("Invalid PeerId",St.ERR_INVALID_PARAMETERS);let e=r.toCID().toString();return new De(`${m3}${e}`)}async function ow(r,e,t){let n=new Map;for(let o of t){if(o==null)continue;if(o.multiaddr instanceof Uint8Array&&(o.multiaddr=Z(o.multiaddr)),!ko(o.multiaddr))throw new m("Multiaddr was invalid",St.ERR_INVALID_PARAMETERS);if(!await e(r,o.multiaddr))continue;let s=o.isCertified??!1,i=o.multiaddr.toString(),a=n.get(i);a!=null?o.isCertified=a.isCertified||s:n.set(i,{multiaddr:o.multiaddr,isCertified:s})}return[...n.values()].sort((o,s)=>o.multiaddr.toString().localeCompare(s.multiaddr.toString())).map(({isCertified:o,multiaddr:s})=>({isCertified:o,multiaddr:s.bytes}))}async function Hd(r,e,t,n){if(e==null)throw new m("Invalid PeerData",St.ERR_INVALID_PARAMETERS);if(e.publicKey!=null&&r.publicKey!=null&&!J(e.publicKey,r.publicKey))throw new m("publicKey bytes do not match peer id publicKey bytes",St.ERR_INVALID_PARAMETERS);let o=n.existingPeer;if(o!=null&&!r.equals(o.id))throw new m("peer id did not match existing peer id",St.ERR_INVALID_PARAMETERS);let s=o?.addresses??[],i=new Set(o?.protocols??[]),a=o?.metadata??new Map,c=o?.tags??new Map,l=o?.peerRecordEnvelope;if(t==="patch"){if((e.multiaddrs!=null||e.addresses!=null)&&(s=[],e.multiaddrs!=null&&s.push(...e.multiaddrs.map(u=>({isCertified:!1,multiaddr:u}))),e.addresses!=null&&s.push(...e.addresses)),e.protocols!=null&&(i=new Set(e.protocols)),e.metadata!=null){let u=e.metadata instanceof Map?[...e.metadata.entries()]:Object.entries(e.metadata);a=$d(u,{validate:sw})}if(e.tags!=null){let u=e.tags instanceof Map?[...e.tags.entries()]:Object.entries(e.tags);c=$d(u,{validate:iw,map:aw})}e.peerRecordEnvelope!=null&&(l=e.peerRecordEnvelope)}if(t==="merge"){if(e.multiaddrs!=null&&s.push(...e.multiaddrs.map(u=>({isCertified:!1,multiaddr:u}))),e.addresses!=null&&s.push(...e.addresses),e.protocols!=null&&(i=new Set([...i,...e.protocols])),e.metadata!=null){let u=e.metadata instanceof Map?[...e.metadata.entries()]:Object.entries(e.metadata);for(let[f,h]of u)h==null?a.delete(f):a.set(f,h);a=$d([...a.entries()],{validate:sw})}if(e.tags!=null){let u=e.tags instanceof Map?[...e.tags.entries()]:Object.entries(e.tags),f=new Map(c);for(let[h,p]of u)p==null?f.delete(h):f.set(h,p);c=$d([...f.entries()],{validate:iw,map:aw})}e.peerRecordEnvelope!=null&&(l=e.peerRecordEnvelope)}let d={addresses:await ow(r,n.addressFilter??(async()=>!0),s),protocols:[...i.values()].sort((u,f)=>u.localeCompare(f)),metadata:a,tags:c,publicKey:o?.id.publicKey??e.publicKey??r.publicKey,peerRecordEnvelope:l};return r.type!=="RSA"&&delete d.publicKey,d}function $d(r,e){let t=new Map;for(let[n,o]of r)o!=null&&e.validate(n,o);for(let[n,o]of r.sort(([s],[i])=>s.localeCompare(i)))o!=null&&t.set(n,e.map?.(n,o)??o);return t}function sw(r,e){if(typeof r!="string")throw new m("Metadata key must be a string",St.ERR_INVALID_PARAMETERS);if(!(e instanceof Uint8Array))throw new m("Metadata value must be a Uint8Array",St.ERR_INVALID_PARAMETERS)}function iw(r,e){if(typeof r!="string")throw new m("Tag name must be a string",St.ERR_INVALID_PARAMETERS);if(e.value!=null){if(parseInt(`${e.value}`,10)!==e.value)throw new m("Tag value must be an integer",St.ERR_INVALID_PARAMETERS);if(e.value<0||e.value>100)throw new m("Tag value must be between 0-100",St.ERR_INVALID_PARAMETERS)}if(e.ttl!=null){if(parseInt(`${e.ttl}`,10)!==e.ttl)throw new m("Tag ttl must be an integer",St.ERR_INVALID_PARAMETERS);if(e.ttl<0)throw new m("Tag ttl must be between greater than 0",St.ERR_INVALID_PARAMETERS)}}function aw(r,e){let t;return e.expiry!=null&&(t=e.expiry),e.ttl!=null&&(t=BigInt(Date.now()+Number(e.ttl))),{value:e.value??0,expiry:t}}function qd(r,e,t){let n=r.toString().split("/")[2],o=lt.decode(n),s=Ze(o),i=t.get(s);if(i!=null)return i;let a=Yi(s,e);return t.set(s,a),a}function yT(r,e){return r==null?{}:{prefix:m3,filters:(r.filters??[]).map(t=>({key:n,value:o})=>t(qd(n,o,e))),orders:(r.orders??[]).map(t=>(n,o)=>t(qd(n.key,n.value,e),qd(o.key,o.value,e)))}}var Gd=class{peerId;datastore;lock;addressFilter;constructor(e,t={}){this.peerId=e.peerId,this.datastore=e.datastore,this.addressFilter=t.addressFilter,this.lock=Ma({name:"peer-store",singleProcess:!0})}async has(e){return this.datastore.has(Xi(e))}async delete(e){if(this.peerId.equals(e))throw new m("Cannot delete self peer",St.ERR_INVALID_PARAMETERS);await this.datastore.delete(Xi(e))}async load(e){let t=await this.datastore.get(Xi(e));return Yi(e,t)}async save(e,t){let{existingBuf:n,existingPeer:o}=await this.#e(e),s=await Hd(e,t,"patch",{addressFilter:this.addressFilter});return this.#t(e,s,n,o)}async patch(e,t){let{existingBuf:n,existingPeer:o}=await this.#e(e),s=await Hd(e,t,"patch",{addressFilter:this.addressFilter,existingPeer:o});return this.#t(e,s,n,o)}async merge(e,t){let{existingBuf:n,existingPeer:o}=await this.#e(e),s=await Hd(e,t,"merge",{addressFilter:this.addressFilter,existingPeer:o});return this.#t(e,s,n,o)}async*all(e){let t=new st;for await(let{key:n,value:o}of this.datastore.query(yT(e??{},t))){let s=qd(n,o,t);s.id.equals(this.peerId)||(yield s)}}async#e(e){try{let t=await this.datastore.get(Xi(e)),n=Yi(e,t);return{existingBuf:t,existingPeer:n}}catch(t){if(t.code!=="ERR_NOT_FOUND")throw t}return{}}async#t(e,t,n,o){let s=zi.encode(t);return n!=null&&J(s,n)?{peer:Yi(e,s),previous:o,updated:!1}:(await this.datastore.put(Xi(e),s),{peer:Yi(e,s),previous:o,updated:!0})}};var Wd=class{store;events;peerId;log;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:peer-store"),this.events=e.events,this.peerId=e.peerId,this.store=new Gd(e,t)}[Symbol.toStringTag]="@libp2p/peer-store";async forEach(e,t){this.log.trace("forEach await read lock");let n=await this.store.lock.readLock();this.log.trace("forEach got read lock");try{for await(let o of this.store.all(t))e(o)}finally{this.log.trace("forEach release read lock"),n()}}async all(e){this.log.trace("all await read lock");let t=await this.store.lock.readLock();this.log.trace("all got read lock");try{return await Ya(this.store.all(e))}finally{this.log.trace("all release read lock"),t()}}async delete(e){this.log.trace("delete await write lock");let t=await this.store.lock.writeLock();this.log.trace("delete got write lock");try{await this.store.delete(e)}finally{this.log.trace("delete release write lock"),t()}}async has(e){this.log.trace("has await read lock");let t=await this.store.lock.readLock();this.log.trace("has got read lock");try{return await this.store.has(e)}finally{this.log.trace("has release read lock"),t()}}async get(e){this.log.trace("get await read lock");let t=await this.store.lock.readLock();this.log.trace("get got read lock");try{return await this.store.load(e)}finally{this.log.trace("get release read lock"),t()}}async save(e,t){this.log.trace("save await write lock");let n=await this.store.lock.writeLock();this.log.trace("save got write lock");try{let o=await this.store.save(e,t);return this.#e(e,o),o.peer}finally{this.log.trace("save release write lock"),n()}}async patch(e,t){this.log.trace("patch await write lock");let n=await this.store.lock.writeLock();this.log.trace("patch got write lock");try{let o=await this.store.patch(e,t);return this.#e(e,o),o.peer}finally{this.log.trace("patch release write lock"),n()}}async merge(e,t){this.log.trace("merge await write lock");let n=await this.store.lock.writeLock();this.log.trace("merge got write lock");try{let o=await this.store.merge(e,t);return this.#e(e,o),o.peer}finally{this.log.trace("merge release write lock"),n()}}async consumePeerRecord(e,t){let n=await mr.openAndCertify(e,Kt.DOMAIN);if(t?.equals(n.peerId)===!1)return this.log("envelope peer id was not the expected peer id - expected: %p received: %p",t,n.peerId),!1;let o=Kt.createFromProtobuf(n.payload),s;try{s=await this.get(n.peerId)}catch(i){if(i.code!=="ERR_NOT_FOUND")throw i}if(s?.peerRecordEnvelope!=null){let i=await mr.createFromProtobuf(s.peerRecordEnvelope),a=Kt.createFromProtobuf(i.payload);if(a.seqNumber>=o.seqNumber)return this.log("sequence number was lower or equal to existing sequence number - stored: %d received: %d",a.seqNumber,o.seqNumber),!1}return await this.patch(o.peerId,{peerRecordEnvelope:e,addresses:o.multiaddrs.map(i=>({isCertified:!0,multiaddr:i}))}),!0}#e(e,t){t.updated&&(this.peerId.equals(e)?this.events.safeDispatchEvent("self:peer:update",{detail:t}):this.events.safeDispatchEvent("peer:update",{detail:t}))}};function cw(r,e){let t;return function(){let n=function(){t=void 0,r()};clearTimeout(t),t=setTimeout(n,e)}}var wT=r=>r;function g3(r,e){let t=r.getPeerId();return t!=null&&pe(t).equals(e)&&(r=r.decapsulate(Z(`/p2p/${e.toString()}`))),r}var zd=class{log;components;listen;announce;observed;announceFilter;constructor(e,t={}){let{listen:n=[],announce:o=[]}=t;this.components=e,this.log=e.logger.forComponent("libp2p:address-manager"),this.listen=n.map(s=>s.toString()),this.announce=new Set(o.map(s=>s.toString())),this.observed=new Map,this.announceFilter=t.announceFilter??wT,this._updatePeerStoreAddresses=cw(this._updatePeerStoreAddresses.bind(this),1e3),e.events.addEventListener("transport:listening",()=>{this._updatePeerStoreAddresses()}),e.events.addEventListener("transport:close",()=>{this._updatePeerStoreAddresses()})}[Symbol.toStringTag]="@libp2p/address-manager";_updatePeerStoreAddresses(){let e=this.getAnnounceAddrs().concat(this.components.transportManager.getAddrs()).concat([...this.observed.entries()].filter(([t,n])=>n.confident).map(([t])=>Z(t))).map(t=>t.getPeerId()===this.components.peerId.toString()?t.decapsulate(`/p2p/${this.components.peerId.toString()}`):t);this.components.peerStore.patch(this.components.peerId,{multiaddrs:e}).catch(t=>{this.log.error("error updating addresses",t)})}getListenAddrs(){return Array.from(this.listen).map(e=>Z(e))}getAnnounceAddrs(){return Array.from(this.announce).map(e=>Z(e))}getObservedAddrs(){return Array.from(this.observed).map(([e])=>Z(e))}addObservedAddr(e){e=g3(e,this.components.peerId);let t=e.toString();this.observed.has(t)||this.observed.set(t,{confident:!1})}confirmObservedAddr(e){e=g3(e,this.components.peerId);let t=e.toString(),o=(this.observed.get(t)??{confident:!1}).confident;this.observed.set(t,{confident:!0}),o||this._updatePeerStoreAddresses()}removeObservedAddr(e){e=g3(e,this.components.peerId);let t=e.toString();this.observed.delete(t)}getAddresses(){let e=this.getAnnounceAddrs().map(n=>n.toString());e.length===0&&(e=this.components.transportManager.getAddrs().map(n=>n.toString())),e=e.concat(Array.from(this.observed).filter(([n,o])=>o.confident).map(([n])=>n));let t=new Set(e);return this.announceFilter(Array.from(t).map(n=>Z(n))).map(n=>n.protos().pop()?.path===!0||n.getPeerId()===this.components.peerId.toString()?n:n.encapsulate(`/p2p/${this.components.peerId.toString()}`))}};var y3=class{components={};_started=!1;constructor(e={}){this.components={};for(let[t,n]of Object.entries(e))this.components[t]=n;this.components.logger==null&&(this.components.logger=So())}isStarted(){return this._started}async _invokeStartableMethod(e){await Promise.all(Object.values(this.components).filter(t=>xc(t)).map(async t=>{await t[e]?.()}))}async beforeStart(){await this._invokeStartableMethod("beforeStart")}async start(){await this._invokeStartableMethod("start"),this._started=!0}async afterStart(){await this._invokeStartableMethod("afterStart")}async beforeStop(){await this._invokeStartableMethod("beforeStop")}async stop(){await this._invokeStartableMethod("stop"),this._started=!1}async afterStop(){await this._invokeStartableMethod("afterStop")}},ET=["metrics","connectionProtector","dns"],bT=["components","isStarted","beforeStart","start","afterStart","beforeStop","stop","afterStop","then","_invokeStartableMethod"];function lw(r={}){let e=new y3(r);return new Proxy(e,{get(n,o,s){if(typeof o=="string"&&!bT.includes(o)){let i=e.components[o];if(i==null&&!ET.includes(o))throw new m(`${o} not set`,"ERR_SERVICE_MISSING");return i}return Reflect.get(n,o,s)},set(n,o,s){return typeof o=="string"?e.components[o]=s:Reflect.set(n,o,s),!0}})}function uw(r){let e={};for(let t of Object.values(r.components))for(let n of xT(t))e[n]=!0;for(let t of Object.values(r.components))for(let n of _T(t))if(e[n]!==!0)throw new m(`Service "${vT(t)}" required capability "${n}" but it was not provided by any component, you may need to add additional configuration when creating your node.`,"ERR_UNMET_SERVICE_DEPENDENCIES")}function xT(r){return Array.isArray(r?.[Te])?r[Te]:[]}function _T(r){return Array.isArray(r?.[Mr])?r[Mr]:[]}function vT(r){return r?.[Symbol.toStringTag]??r?.toString()??"unknown"}function dw(r={}){return{denyDialPeer:async()=>!1,denyDialMultiaddr:async e=>{let t=e.stringTuples();return t[0][0]===4||t[0][0]===41?!!Zt(`${t[0][1]}`):!1},denyInboundConnection:async()=>!1,denyOutboundConnection:async()=>!1,denyInboundEncryptedConnection:async()=>!1,denyOutboundEncryptedConnection:async()=>!1,denyInboundUpgradedConnection:async()=>!1,denyOutboundUpgradedConnection:async()=>!1,filterMultiaddrForPeer:async()=>!0,...r}}function w3(r){try{let{address:e}=r.nodeAddress();return!!Zt(e)}catch{return!0}}function ST(r,e){let t=w3(r.multiaddr),n=w3(e.multiaddr);return t&&!n?1:!t&&n?-1:0}function RT(r,e){return r.isCertified&&!e.isCertified?-1:!r.isCertified&&e.isCertified?1:0}function AT(r,e){let t=bs.exactMatch(r.multiaddr),n=bs.exactMatch(e.multiaddr);return t&&!n?1:!t&&n?-1:0}function Qi(r,e){let t=ST(r,e);if(t!==0)return t;let n=AT(r,e);return n!==0?n:RT(r,e)}var IT=32,{code:TT}=te("dnsaddr"),E3=class extends Error{constructor(e="Max recursive depth reached"){super(e),this.name="RecursionLimitError"}},Ds=async function(e,t={}){let n=t.maxRecursiveDepth??IT;if(n===0)throw new E3("Max recursive depth reached");let[,o]=e.stringTuples().find(([l])=>l===TT)??[],i=await(t?.dns??su()).query(`_dnsaddr.${o}`,{signal:t?.signal,types:[lr.TXT]}),a=e.getPeerId(),c=[];for(let l of i.Answer){let d=l.data.replace(/["']/g,"").trim().split("=")[1];if(d==null||a!=null&&!d.includes(a))continue;let u=Z(d);if(d.startsWith("/dnsaddr")){let f=await u.resolve({...t,maxRecursiveDepth:n-1});c.push(...f.map(h=>h.toString()))}else c.push(u.toString())}return c};var Jn;(function(r){r.NOT_STARTED_YET="The libp2p node is not started yet",r.ERR_PROTECTOR_REQUIRED="Private network is enforced, but no protector was provided",r.NOT_FOUND="Not found"})(Jn||(Jn={}));var Y;(function(r){r.ERR_PROTECTOR_REQUIRED="ERR_PROTECTOR_REQUIRED",r.ERR_PEER_DIAL_INTERCEPTED="ERR_PEER_DIAL_INTERCEPTED",r.ERR_CONNECTION_INTERCEPTED="ERR_CONNECTION_INTERCEPTED",r.ERR_INVALID_PROTOCOLS_FOR_STREAM="ERR_INVALID_PROTOCOLS_FOR_STREAM",r.ERR_CONNECTION_ENDED="ERR_CONNECTION_ENDED",r.ERR_CONNECTION_FAILED="ERR_CONNECTION_FAILED",r.ERR_NODE_NOT_STARTED="ERR_NODE_NOT_STARTED",r.ERR_ALREADY_ABORTED="ERR_ALREADY_ABORTED",r.ERR_TOO_MANY_ADDRESSES="ERR_TOO_MANY_ADDRESSES",r.ERR_NO_VALID_ADDRESSES="ERR_NO_VALID_ADDRESSES",r.ERR_RELAYED_DIAL="ERR_RELAYED_DIAL",r.ERR_DIALED_SELF="ERR_DIALED_SELF",r.ERR_DISCOVERED_SELF="ERR_DISCOVERED_SELF",r.ERR_DUPLICATE_TRANSPORT="ERR_DUPLICATE_TRANSPORT",r.ERR_ENCRYPTION_FAILED="ERR_ENCRYPTION_FAILED",r.ERR_HOP_REQUEST_FAILED="ERR_HOP_REQUEST_FAILED",r.ERR_INVALID_KEY="ERR_INVALID_KEY",r.ERR_INVALID_MESSAGE="ERR_INVALID_MESSAGE",r.ERR_INVALID_PARAMETERS="ERR_INVALID_PARAMETERS",r.ERR_INVALID_PEER="ERR_INVALID_PEER",r.ERR_MUXER_UNAVAILABLE="ERR_MUXER_UNAVAILABLE",r.ERR_NOT_FOUND="ERR_NOT_FOUND",r.ERR_TRANSPORT_UNAVAILABLE="ERR_TRANSPORT_UNAVAILABLE",r.ERR_TRANSPORT_DIAL_FAILED="ERR_TRANSPORT_DIAL_FAILED",r.ERR_UNSUPPORTED_PROTOCOL="ERR_UNSUPPORTED_PROTOCOL",r.ERR_PROTOCOL_HANDLER_ALREADY_REGISTERED="ERR_PROTOCOL_HANDLER_ALREADY_REGISTERED",r.ERR_INVALID_MULTIADDR="ERR_INVALID_MULTIADDR",r.ERR_SIGNATURE_NOT_VALID="ERR_SIGNATURE_NOT_VALID",r.ERR_FIND_SELF="ERR_FIND_SELF",r.ERR_NO_ROUTERS_AVAILABLE="ERR_NO_ROUTERS_AVAILABLE",r.ERR_CONNECTION_NOT_MULTIPLEXED="ERR_CONNECTION_NOT_MULTIPLEXED",r.ERR_NO_DIAL_TOKENS="ERR_NO_DIAL_TOKENS",r.ERR_INVALID_CMS="ERR_INVALID_CMS",r.ERR_MISSING_KEYS="ERR_MISSING_KEYS",r.ERR_NO_KEY="ERR_NO_KEY",r.ERR_INVALID_KEY_NAME="ERR_INVALID_KEY_NAME",r.ERR_INVALID_KEY_TYPE="ERR_INVALID_KEY_TYPE",r.ERR_KEY_ALREADY_EXISTS="ERR_KEY_ALREADY_EXISTS",r.ERR_INVALID_KEY_SIZE="ERR_INVALID_KEY_SIZE",r.ERR_KEY_NOT_FOUND="ERR_KEY_NOT_FOUND",r.ERR_OLD_KEY_NAME_INVALID="ERR_OLD_KEY_NAME_INVALID",r.ERR_NEW_KEY_NAME_INVALID="ERR_NEW_KEY_NAME_INVALID",r.ERR_PASSWORD_REQUIRED="ERR_PASSWORD_REQUIRED",r.ERR_PEM_REQUIRED="ERR_PEM_REQUIRED",r.ERR_CANNOT_READ_KEY="ERR_CANNOT_READ_KEY",r.ERR_MISSING_PRIVATE_KEY="ERR_MISSING_PRIVATE_KEY",r.ERR_MISSING_PUBLIC_KEY="ERR_MISSING_PUBLIC_KEY",r.ERR_INVALID_OLD_PASS_TYPE="ERR_INVALID_OLD_PASS_TYPE",r.ERR_INVALID_NEW_PASS_TYPE="ERR_INVALID_NEW_PASS_TYPE",r.ERR_INVALID_PASS_LENGTH="ERR_INVALID_PASS_LENGTH",r.ERR_NOT_IMPLEMENTED="ERR_NOT_IMPLEMENTED",r.ERR_WRONG_PING_ACK="ERR_WRONG_PING_ACK",r.ERR_INVALID_RECORD="ERR_INVALID_RECORD",r.ERR_ALREADY_SUCCEEDED="ERR_ALREADY_SUCCEEDED",r.ERR_NO_HANDLER_FOR_PROTOCOL="ERR_NO_HANDLER_FOR_PROTOCOL",r.ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS="ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS",r.ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS="ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS",r.ERR_CONNECTION_DENIED="ERR_CONNECTION_DENIED",r.ERR_TRANSFER_LIMIT_EXCEEDED="ERR_TRANSFER_LIMIT_EXCEEDED"})(Y||(Y={}));var CT={addresses:{listen:[],announce:[],noAnnounce:[],announceFilter:r=>r},connectionManager:{resolvers:{dnsaddr:Ds},addressSorter:Qi},transportManager:{faultTolerance:ro.FATAL_ALL}};async function fw(r){let e=qi(CT,r);if(e.connectionProtector===null&&globalThis.process?.env?.LIBP2P_FORCE_PNET!=null)throw new m(Jn.ERR_PROTECTOR_REQUIRED,Y.ERR_PROTECTOR_REQUIRED);if(e.privateKey!=null&&!(await ut(e.privateKey.public.bytes,e.privateKey.bytes)).equals(e.peerId))throw new m("Private key doesn't match peer id",Y.ERR_INVALID_KEY);return e}function Yd(r){if(to(r))return{peerId:r,multiaddrs:[]};Array.isArray(r)||(r=[r]);let e;if(r.length>0){let t=r[0].getPeerId();e=t==null?void 0:pe(t),r.forEach(n=>{if(!ko(n))throw new m("Invalid Multiaddr",Y.ERR_INVALID_MULTIADDR);let o=n.getPeerId();if(o==null){if(e!=null)throw new m("Multiaddrs must all have the same peer id or have no peer id",Y.ERR_INVALID_PARAMETERS)}else{let s=pe(o);if(e?.equals(s)!==!0)throw new m("Multiaddrs must all have the same peer id or have no peer id",Y.ERR_INVALID_PARAMETERS)}})}return{peerId:e,multiaddrs:r}}var Xd="last-dial-failure";var Qd=5,Zd=100,jd=50,Jd=1e3*60*7;var Ns={minConnections:Qd,maxQueueLength:100,autoDialConcurrency:25,autoDialPriority:0,autoDialInterval:5e3,autoDialPeerRetryThreshold:Jd,autoDialDiscoveredPeersDebounce:10},ef=class{connectionManager;peerStore;queue;minConnections;autoDialPriority;autoDialIntervalMs;autoDialMaxQueueLength;autoDialPeerRetryThresholdMs;autoDialDiscoveredPeersDebounce;autoDialInterval;started;running;log;constructor(e,t){this.connectionManager=e.connectionManager,this.peerStore=e.peerStore,this.minConnections=t.minConnections??Ns.minConnections,this.autoDialPriority=t.autoDialPriority??Ns.autoDialPriority,this.autoDialIntervalMs=t.autoDialInterval??Ns.autoDialInterval,this.autoDialMaxQueueLength=t.maxQueueLength??Ns.maxQueueLength,this.autoDialPeerRetryThresholdMs=t.autoDialPeerRetryThreshold??Ns.autoDialPeerRetryThreshold,this.autoDialDiscoveredPeersDebounce=t.autoDialDiscoveredPeersDebounce??Ns.autoDialDiscoveredPeersDebounce,this.log=e.logger.forComponent("libp2p:connection-manager:auto-dial"),this.started=!1,this.running=!1,this.queue=new qt({concurrency:t.autoDialConcurrency??Ns.autoDialConcurrency,metricName:"libp2p_autodial_queue",metrics:e.metrics}),this.queue.addEventListener("error",o=>{this.log.error("error during auto-dial",o.detail)}),e.events.addEventListener("connection:close",()=>{this.autoDial().catch(o=>{this.log.error(o)})});let n;e.events.addEventListener("peer:discovery",()=>{clearTimeout(n),n=setTimeout(()=>{this.autoDial().catch(o=>{this.log.error(o)})},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(),t=e.size;if(t>=this.minConnections){this.minConnections>0&&this.log.trace("have enough connections %d/%d",t,this.minConnections);return}if(this.queue.size>this.autoDialMaxQueueLength){this.log("not enough connections %d/%d but auto dial queue is full",t,this.minConnections),this.sheduleNextAutodial();return}this.running=!0,this.log("not enough connections %d/%d - will dial peers to increase the number of connections",t,this.minConnections);let n=new Ct(this.connectionManager.getDialQueue().map(l=>l.peerId).filter(Boolean)),o=await this.peerStore.all({filters:[l=>l.addresses.length===0?(this.log.trace("not autodialing %p because they have no addresses",l.id),!1):e.has(l.id)?(this.log.trace("not autodialing %p because they are already connected",l.id),!1):n.has(l.id)?(this.log.trace("not autodialing %p because they are already being dialed",l.id),!1):this.queue.has(l.id)?(this.log.trace("not autodialing %p because they are already being autodialed",l.id),!1):!0]}),s=o.sort(()=>Math.random()>.5?1:-1),i=new st;for(let l of s)i.has(l.id)||i.set(l.id,[...l.tags.values()].reduce((d,u)=>d+u.value,0));let c=s.sort((l,d)=>{let u=i.get(l.id)??0,f=i.get(d.id)??0;return u>f?-1:u<f?1:0}).filter(l=>{let d=l.metadata.get(Xd);if(d==null)return!0;let u=parseInt(U(d));return isNaN(u)?!0:Date.now()-u>this.autoDialPeerRetryThresholdMs});this.log("selected %d/%d peers to dial",c.length,o.length);for(let l of c)this.queue.add(async()=>{let d=this.connectionManager.getConnectionsMap().size;if(d>=this.minConnections){this.log("got enough connections now %d/%d",d,this.minConnections),this.queue.clear();return}this.log("connecting to a peerStore stored peer %p",l.id),await this.connectionManager.openConnection(l.id,{priority:this.autoDialPriority})},{peerId:l.id}).catch(d=>{this.log.error("could not connect to peerStore stored peer",d)});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 DT=["/ipfs/id/1.0.0","/ipfs/id/push/1.0.0","/libp2p/autonat/1.0.0","/libp2p/dcutr"];async function hw(r,e){let t=r?.streams?.map(o=>o.protocol)??[],n=e?.closableProtocols??DT;if(!(t.filter(o=>o!=null&&!n.includes(o)).length>0))try{await r?.close(e)}catch(o){r?.abort(o)}}var pw={maxConnections:Zd,allow:[]},tf=class{maxConnections;connectionManager;peerStore;allow;events;log;constructor(e,t={}){this.maxConnections=t.maxConnections??pw.maxConnections,this.allow=t.allow??pw.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(),t=e.length;if(this.log("checking max connections limit %d/%d",t,this.maxConnections),t<=this.maxConnections)return;let n=new st;for(let a of e){let c=a.remotePeer;if(!n.has(c)){n.set(c,0);try{let l=await this.peerStore.get(c);n.set(c,[...l.tags.values()].reduce((d,u)=>d+u.value,0))}catch(l){l.code!=="ERR_NOT_FOUND"&&this.log.error("error loading peer tags",l)}}}let o=this.sortConnections(e,n),s=Math.max(t-this.maxConnections,0),i=[];for(let a of o)if(this.log("too many connections open - closing a connection to %p",a.remotePeer),this.allow.some(l=>a.remoteAddr.toString().startsWith(l.toString()))||i.push(a),i.length===s)break;await Promise.all(i.map(async a=>{await hw(a,{signal:AbortSignal.timeout(1e3)})})),this.events.safeDispatchEvent("connection:prune",{detail:i})}sortConnections(e,t){return e.sort((n,o)=>{let s=n.timeline.open,i=o.timeline.open;return s<i?1:s>i?-1:0}).sort((n,o)=>n.direction==="outbound"&&o.direction==="inbound"?1:n.direction==="inbound"&&o.direction==="outbound"?-1:0).sort((n,o)=>n.streams.length>o.streams.length?1:n.streams.length<o.streams.length?-1:0).sort((n,o)=>{let s=t.get(n.remotePeer)??0,i=t.get(o.remotePeer)??0;return s>i?1:s<i?-1:0})}};var rf=class extends or{constructor(e={}){super({...e,sort:(t,n)=>t.options.priority>n.options.priority?-1:t.options.priority<n.options.priority?1:0})}};async function mw(r,e){let t=!1;for(let o of vi.keys())if(t=r.protoNames().includes(o),t)break;if(!t)return[r];let n=await r.resolve(e);return e.log("resolved %s to",r,n.map(o=>o.toString())),n}var gc={addressSorter:Qi,maxParallelDials:jd,maxDialQueueLength:500,maxPeerAddrsToDial:25,dialTimeout:5e3,resolvers:{dnsaddr:Ds}},nf=class{queue;components;addressSorter;maxPeerAddrsToDial;maxDialQueueLength;dialTimeout;shutDownController;connections;log;constructor(e,t={}){this.addressSorter=t.addressSorter??gc.addressSorter,this.maxPeerAddrsToDial=t.maxPeerAddrsToDial??gc.maxPeerAddrsToDial,this.maxDialQueueLength=t.maxDialQueueLength??gc.maxDialQueueLength,this.dialTimeout=t.dialTimeout??gc.dialTimeout,this.connections=t.connections??new st,this.log=e.logger.forComponent("libp2p:connection-manager:dial-queue"),this.components=e,this.shutDownController=new AbortController,K(1/0,this.shutDownController.signal);for(let[n,o]of Object.entries(t.resolvers??{}))vi.set(n,o);this.queue=new rf({concurrency:t.maxParallelDials??gc.maxParallelDials,metricName:"libp2p_dial_queue",metrics:e.metrics}),this.queue.addEventListener("error",n=>{this.log.error("error in dial queue",n.detail)})}start(){this.shutDownController=new AbortController,K(1/0,this.shutDownController.signal)}stop(){this.shutDownController.abort(),this.queue.abort()}async dial(e,t={}){let{peerId:n,multiaddrs:o}=Yd(e),s=Array.from(this.connections.values()).flat().find(a=>t.force===!0?!1:a.remotePeer.equals(n)?!0:o.find(c=>c.equals(a.remoteAddr)));if(s!=null)return this.log("already connected to %a",s.remoteAddr),t.onProgress?.(new H("dial-queue:already-connected")),s;let i=this.queue.queue.find(a=>{if(n?.equals(a.options.peerId)===!0)return!0;let c=a.options.multiaddrs;if(c==null)return!1;for(let l of o)if(c.has(l.toString()))return!0;return!1});if(i!=null){this.log("joining existing dial target for %p",n);for(let a of o)i.options.multiaddrs.add(a.toString());return t.onProgress?.(new H("dial-queue:already-in-dial-queue")),i.join(t)}if(this.queue.size>=this.maxDialQueueLength)throw new m("Dial queue is full","ERR_DIAL_QUEUE_FULL");return this.log("creating dial target for %p",n,o.map(a=>a.toString())),t.onProgress?.(new H("dial-queue:add-to-dial-queue")),this.queue.add(async a=>{a?.onProgress?.(new H("dial-queue:start-dial"));let c=this.createDialAbortController(a?.signal),l;try{l=await this.calculateMultiaddrs(n,a?.multiaddrs,{...a,signal:c}),a?.onProgress?.(new H("dial-queue:calculated-addresses",l)),l.map(({multiaddr:d})=>d.toString()).forEach(d=>{a?.multiaddrs.add(d)})}catch(d){throw c.clear(),d}try{let d=0,u=[];for(let f of l){if(d===this.maxPeerAddrsToDial)throw this.log("dialed maxPeerAddrsToDial (%d) addresses for %p, not trying any others",d,n),new m("Peer had more than maxPeerAddrsToDial",Y.ERR_TOO_MANY_ADDRESSES);d++;try{let h=await this.components.transportManager.dial(f.multiaddr,{...a,signal:c});return this.log("dial to %a succeeded",f.multiaddr),h}catch(h){if(this.log.error("dial failed to %a",f.multiaddr,h),n!=null)try{await this.components.peerStore.patch(n,{metadata:{[Xd]:L(Date.now().toString())}})}catch(p){this.log.error("could not update last dial failure key for %p",n,p)}if(c.aborted)throw new m(h.message,fn);u.push(h)}}throw u.length===1?u[0]:new bc(u,"All multiaddr dials failed",Y.ERR_TRANSPORT_DIAL_FAILED)}finally{c.clear()}},{peerId:n,priority:t.priority??I3,multiaddrs:new Set(o.map(a=>a.toString())),signal:t.signal,onProgress:t.onProgress})}createDialAbortController(e){let t=_e([AbortSignal.timeout(this.dialTimeout),this.shutDownController.signal,e]);return K(1/0,t),t}async calculateMultiaddrs(e,t=new Set,n={}){let o=[...t].map(u=>({multiaddr:Z(u),isCertified:!1}));if(e!=null){if(this.components.peerId.equals(e))throw new m("Tried to dial self",Y.ERR_DIALED_SELF);if(await this.components.connectionGater.denyDialPeer?.(e)===!0)throw new m("The dial request is blocked by gater.allowDialPeer",Y.ERR_PEER_DIAL_INTERCEPTED);if(o.length===0){this.log("loading multiaddrs for %p",e);try{let u=await this.components.peerStore.get(e);o.push(...u.addresses),this.log("loaded multiaddrs for %p",e,o.map(({multiaddr:f})=>f.toString()))}catch(u){if(u.code!==Y.ERR_NOT_FOUND)throw u}}if(o.length===0){this.log("looking up multiaddrs for %p in the peer routing",e);try{let u=await this.components.peerRouting.findPeer(e);this.log("found multiaddrs for %p in the peer routing",e,o.map(({multiaddr:f})=>f.toString())),o.push(...u.multiaddrs.map(f=>({multiaddr:f,isCertified:!1})))}catch(u){u.code!==Y.ERR_NO_ROUTERS_AVAILABLE&&this.log.error("looking up multiaddrs for %p in the peer routing failed",e,u)}}}let s=(await Promise.all(o.map(async u=>{let f=await mw(u.multiaddr,{dns:this.components.dns,...n,log:this.log});return f.length===1&&f[0].equals(u.multiaddr)?u:f.map(h=>({multiaddr:h,isCertified:!1}))}))).flat();if(e!=null){let u=`/p2p/${e.toString()}`;s=s.map(f=>f.multiaddr.protos().pop()?.path===!0?f:f.multiaddr.getPeerId()==null?{multiaddr:f.multiaddr.encapsulate(u),isCertified:f.isCertified}:f)}let i=s.filter(u=>{if(this.components.transportManager.dialTransportForMultiaddr(u.multiaddr)==null)return!1;let f=u.multiaddr.getPeerId();return e!=null&&f!=null?e.equals(f):!0}),a=new Map;for(let u of i){let f=u.multiaddr.toString(),h=a.get(f);if(h!=null){h.isCertified=h.isCertified||u.isCertified||!1;continue}a.set(f,u)}let c=[...a.values()];if(c.length===0)throw new m("The dial request has no valid addresses",Y.ERR_NO_VALID_ADDRESSES);let l=[];for(let u of c)this.components.connectionGater.denyDialMultiaddr!=null&&await this.components.connectionGater.denyDialMultiaddr(u.multiaddr)||l.push(u);let d=l.sort(this.addressSorter);if(d.length===0)throw new m("The connection gater denied all addresses in the dial request",Y.ERR_NO_VALID_ADDRESSES);return this.log.trace("addresses for %p before filtering",e??"unknown peer",s.map(({multiaddr:u})=>u.toString())),this.log.trace("addresses for %p after filtering",e??"unknown peer",d.map(({multiaddr:u})=>u.toString())),d}async isDialable(e,t={}){Array.isArray(e)||(e=[e]);try{let n=await this.calculateMultiaddrs(void 0,new Set(e.map(o=>o.toString())),t);return t.runOnTransientConnection===!1?n.find(o=>!bs.matches(o.multiaddr))!=null:!0}catch(n){this.log.trace("error calculating if multiaddr(s) were dialable",n)}return!1}};var I3=50,eo={minConnections:Qd,maxConnections:Zd,inboundConnectionThreshold:5,maxIncomingPendingConnections:10,autoDialConcurrency:25,autoDialPriority:0,autoDialMaxQueueLength:100,autoDialPeerRetryThreshold:Jd,autoDialDiscoveredPeersDebounce:10},of=class{started;connections;allow;deny;maxIncomingPendingConnections;incomingPendingConnections;maxConnections;dialQueue;autoDial;connectionPruner;inboundConnectionRateLimiter;peerStore;metrics;events;log;constructor(e,t={}){this.maxConnections=t.maxConnections??eo.maxConnections;let n=t.minConnections??eo.minConnections;if(this.maxConnections<n)throw new m("Connection Manager maxConnections must be greater than minConnections",Y.ERR_INVALID_PARAMETERS);this.connections=new st,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=(t.allow??[]).map(o=>Z(o)),this.deny=(t.deny??[]).map(o=>Z(o)),this.incomingPendingConnections=0,this.maxIncomingPendingConnections=t.maxIncomingPendingConnections??eo.maxIncomingPendingConnections,this.inboundConnectionRateLimiter=new Gi({points:t.inboundConnectionThreshold??eo.inboundConnectionThreshold,duration:1}),this.autoDial=new ef({connectionManager:this,peerStore:e.peerStore,events:e.events,logger:e.logger},{minConnections:n,autoDialConcurrency:t.autoDialConcurrency??eo.autoDialConcurrency,autoDialPriority:t.autoDialPriority??eo.autoDialPriority,autoDialPeerRetryThreshold:t.autoDialPeerRetryThreshold??eo.autoDialPeerRetryThreshold,autoDialDiscoveredPeersDebounce:t.autoDialDiscoveredPeersDebounce??eo.autoDialDiscoveredPeersDebounce,maxQueueLength:t.autoDialMaxQueueLength??eo.autoDialMaxQueueLength}),this.connectionPruner=new tf({connectionManager:this,peerStore:e.peerStore,events:e.events,logger:e.logger},{maxConnections:this.maxConnections,allow:this.allow}),this.dialQueue=new nf(e,{addressSorter:t.addressSorter??Qi,maxParallelDials:t.maxParallelDials??jd,maxDialQueueLength:t.maxDialQueueLength??500,maxPeerAddrsToDial:t.maxPeerAddrsToDial??25,dialTimeout:t.dialTimeout??5e3,resolvers:t.resolvers??{dnsaddr:Ds},connections:this.connections})}[Symbol.toStringTag]="@libp2p/connection-manager";isStarted(){return this.started}async start(){this.metrics?.registerMetricGroup("libp2p_connection_manager_connections",{calculate:()=>{let e={inbound:0,outbound:0};for(let t of this.connections.values())for(let n of t)n.direction==="inbound"?e.inbound++:e.outbound++;return e}}),this.metrics?.registerMetricGroup("libp2p_protocol_streams_total",{label:"protocol",calculate:()=>{let e={};for(let t of this.connections.values())for(let n of t)for(let o of n.streams){let s=`${o.direction} ${o.protocol??"unnegotiated"}`;e[s]=(e[s]??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 o of n){let s={};for(let i of o.streams){let a=`${i.direction} ${i.protocol??"unnegotiated"}`;s[a]=(s[a]??0)+1}for(let[i,a]of Object.entries(s))e[i]=e[i]??[],e[i].push(a)}let t={};for(let[n,o]of Object.entries(e)){o=o.sort((i,a)=>i-a);let s=Math.floor(o.length*.9);t[n]=o[s]}return t}}),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:[t=>t.tags.has($3)]});await Promise.all(e.map(async t=>{await this.openConnection(t.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 t of this.connections.values())for(let n of t)e.push((async()=>{try{await n.close()}catch(o){this.log.error(o)}})());this.log("closing %d connections",e.length),await Promise.all(e),this.connections.clear(),this.log("stopped")}onConnect(e){this._onConnect(e).catch(t=>{this.log.error(t)})}async _onConnect(e){let{detail:t}=e;if(!this.started){await t.close();return}let n=t.remotePeer,o=this.connections.get(n),s=!1;o!=null?o.push(t):(s=!0,this.connections.set(n,[t])),n.publicKey!=null&&n.type==="RSA"&&await this.peerStore.patch(n,{publicKey:n.publicKey}),s&&this.events.safeDispatchEvent("peer:connect",{detail:t.remotePeer})}onDisconnect(e){let{detail:t}=e;if(!this.started)return;let n=t.remotePeer,o=this.connections.get(n);o!=null&&o.length>1?(o=o.filter(s=>s.id!==t.id),this.connections.set(n,o)):o!=null&&(this.connections.delete(n),this.events.safeDispatchEvent("peer:disconnect",{detail:t.remotePeer}))}getConnections(e){if(e!=null)return this.connections.get(e)??[];let t=[];for(let n of this.connections.values())t=t.concat(n);return t}getConnectionsMap(){return this.connections}async openConnection(e,t={}){if(!this.isStarted())throw new m("Not started",Y.ERR_NODE_NOT_STARTED);t.signal?.throwIfAborted();let{peerId:n}=Yd(e);if(n!=null&&t.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),t.onProgress?.(new H("dial-queue:already-connected")),a}let o=await this.dialQueue.dial(e,{...t,priority:t.priority??I3}),s=this.connections.get(o.remotePeer);s==null&&(s=[],this.connections.set(o.remotePeer,s));let i=!1;for(let a of s)a.id===o.id&&(i=!0);return i||s.push(o),o}async closeConnections(e,t={}){let n=this.connections.get(e)??[];await Promise.all(n.map(async o=>{try{await o.close(t)}catch(s){o.abort(s)}}))}async acceptIncomingConnection(e){if(this.deny.some(o=>e.remoteAddr.toString().startsWith(o.toString())))return this.log("connection from %a refused - connection remote address was in deny list",e.remoteAddr),!1;if(this.allow.some(o=>e.remoteAddr.toString().startsWith(o.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 o=e.remoteAddr.nodeAddress().address;try{await this.inboundConnectionRateLimiter.consume(o,1)}catch{return this.log("connection from %a refused - inboundConnectionThreshold exceeded by host %s",e.remoteAddr,o),!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(){let e={queued:"queued",running:"active",errored:"error",complete:"success"};return this.dialQueue.queue.queue.map(t=>({id:t.id,status:e[t.status],peerId:t.options.peerId,multiaddrs:[...t.options.multiaddrs].map(n=>Z(n))}))}async isDialable(e,t={}){return this.dialQueue.isDialable(e,t)}};var LT=1e4,OT="1.0.0",BT="ping",MT="ipfs",gw=32,sf=class{protocol;components;log;heartbeatInterval;pingIntervalMs;abortController;timeout;constructor(e,t={}){this.components=e,this.protocol=`/${t.protocolPrefix??MT}/${BT}/${OT}`,this.log=e.logger.forComponent("libp2p:connection-monitor"),this.pingIntervalMs=t.pingInterval??LT,this.timeout=new Fi({...t.pingTimeout??{},metrics:e.metrics,metricName:"libp2p_connection_monitor_ping_time_milliseconds"})}[Symbol.toStringTag]="@libp2p/connection-monitor";[Te]=["@libp2p/connection-monitor"];start(){this.abortController=new AbortController,this.heartbeatInterval=setInterval(()=>{this.components.connectionManager.getConnections().forEach(e=>{Promise.resolve().then(async()=>{let t=Date.now();try{let n=this.timeout.getTimeoutSignal({signal:this.abortController?.signal}),o=await e.newStream(this.protocol,{signal:n,runOnTransientConnection:!0}),s=f1(o);t=Date.now(),await Promise.all([s.write(je(gw),{signal:n}),s.read(gw,{signal:n})]),e.rtt=Date.now()-t,await s.unwrap().close({signal:n})}catch(n){if(n.code!=="ERR_UNSUPPORTED_PROTOCOL")throw n;e.rtt=(Date.now()-t)/2}}).catch(t=>{this.log.error("error during heartbeat, aborting connection",t),e.abort(t)})})},this.pingIntervalMs)}stop(){this.abortController?.abort(),this.heartbeatInterval!=null&&clearInterval(this.heartbeatInterval)}};var af=class{routers;started;components;constructor(e,t){this.routers=t.routers??[],this.started=!1,this.components=e}[Symbol.toStringTag]="@libp2p/content-routing";isStarted(){return this.started}async start(){this.started=!0}async stop(){this.started=!1}async*findProviders(e,t={}){if(this.routers.length===0)throw new m("No content routers available",Y.ERR_NO_ROUTERS_AVAILABLE);let n=this,o=new Ct;for await(let s of Ot(...n.routers.map(i=>i.findProviders(e,t))))s!=null&&(s.multiaddrs.length>0&&await this.components.peerStore.merge(s.id,{multiaddrs:s.multiaddrs}),!o.has(s.id)&&(o.add(s.id),yield s))}async provide(e,t={}){if(this.routers.length===0)throw new m("No content routers available",Y.ERR_NO_ROUTERS_AVAILABLE);await Promise.all(this.routers.map(async n=>{await n.provide(e,t)}))}async put(e,t,n){if(!this.isStarted())throw new m(Jn.NOT_STARTED_YET,Y.ERR_NODE_NOT_STARTED);await Promise.all(this.routers.map(async o=>{await o.put(e,t,n)}))}async get(e,t){if(!this.isStarted())throw new m(Jn.NOT_STARTED_YET,Y.ERR_NODE_NOT_STARTED);return Promise.any(this.routers.map(async n=>n.get(e,t)))}};var cf=class{log;peerId;peerStore;routers;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:peer-routing"),this.peerId=e.peerId,this.peerStore=e.peerStore,this.routers=t.routers??[]}[Symbol.toStringTag]="@libp2p/peer-routing";async findPeer(e,t){if(this.routers.length===0)throw new m("No peer routers available",Y.ERR_NO_ROUTERS_AVAILABLE);if(e.toString()===this.peerId.toString())throw new m("Should not try to find self",Y.ERR_FIND_SELF);let n=this,o=Ot(...this.routers.map(s=>async function*(){try{yield await s.findPeer(e,t)}catch(i){n.log.error(i)}}()));for await(let s of o)if(s!=null)return s.multiaddrs.length>0&&await this.peerStore.merge(s.id,{multiaddrs:s.multiaddrs}),s;throw new m(Jn.NOT_FOUND,Y.ERR_NOT_FOUND)}async*getClosestPeers(e,t={}){if(this.routers.length===0)throw new m("No peer routers available",Y.ERR_NO_ROUTERS_AVAILABLE);let n=this,o=Ia(1024);for await(let s of on(async function*(){let i=Ot(...n.routers.map(a=>a.getClosestPeers(e,t)));for await(let a of i)yield async()=>{if(a.multiaddrs.length===0)try{a=await n.findPeer(a.id,{...t,useCache:!1})}catch(c){n.log.error("could not find peer multiaddrs",c);return}return a}}()))s!=null&&(s.multiaddrs.length>0&&await this.peerStore.merge(s.id,{multiaddrs:s.multiaddrs}),!o.has(s.id.toBytes())&&(o.add(s.id.toBytes()),yield s))}};var lf=class extends me{peerRouting;log;walking;walkers;shutdownController;walkController;needNext;constructor(e){super(),this.log=e.logger.forComponent("libp2p:random-walk"),this.peerRouting=e.peerRouting,this.walkers=0,this.walking=!1,this.shutdownController=new AbortController,K(1/0,this.shutdownController.signal)}[Symbol.toStringTag]="@libp2p/random-walk";start(){this.shutdownController=new AbortController,K(1/0,this.shutdownController.signal)}stop(){this.shutdownController.abort()}async*walk(e){this.walking||this.startWalk(),this.walkers++;let t=_e([this.shutdownController.signal,e?.signal]);K(1/0,t);try{for(;;)this.needNext?.resolve(),this.needNext=ee(),yield(await nr(this,"walk:peer",t,{errorEvent:"walk:error"})).detail}finally{t.clear(),this.walkers--,this.walkers===0&&(this.walkController?.abort(),this.walkController=void 0)}}startWalk(){this.walking=!0,this.walkController=new AbortController,K(1/0,this.walkController.signal);let e=_e([this.walkController.signal,this.shutdownController.signal]);K(1/0,e);let t=Date.now(),n=0;Promise.resolve().then(async()=>{for(this.log("start walk");this.walkers>0;)try{let o=je(32),s=Date.now();for await(let i of this.peerRouting.getClosestPeers(o,{signal:e}))e.aborted&&this.log("aborting walk"),e.throwIfAborted(),this.log("found peer %p after %dms for %d walkers",i.id,Date.now()-s,this.walkers),n++,this.safeDispatchEvent("walk:peer",{detail:i}),this.walkers===1&&this.needNext!=null&&(this.log("wait for need next"),await Ce(this.needNext.promise,e)),s=Date.now();this.log("walk iteration for %b and %d walkers finished, found %d peers",o,this.walkers,n)}catch(o){this.log.error("randomwalk errored",o),this.safeDispatchEvent("walk:error",{detail:o})}this.log("no walkers left, ended walk")}).catch(o=>{this.log.error("randomwalk errored",o)}).finally(()=>{this.log("finished walk, found %d peers after %dms",n,Date.now()-t),this.walking=!1})}};var T3=32,C3=64,uf=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)}[Symbol.toStringTag]="@libp2p/registrar";getProtocols(){return Array.from(new Set([...this.handlers.keys()])).sort()}getHandler(e){let t=this.handlers.get(e);if(t==null)throw new m(`No handler registered for protocol ${e}`,Y.ERR_NO_HANDLER_FOR_PROTOCOL);return t}getTopologies(e){let t=this.topologies.get(e);return t==null?[]:[...t.values()]}async handle(e,t,n){if(this.handlers.has(e))throw new m(`Handler already registered for protocol ${e}`,Y.ERR_PROTOCOL_HANDLER_ALREADY_REGISTERED);let o=qi.bind({ignoreUndefined:!0})({maxInboundStreams:T3,maxOutboundStreams:C3},n);this.handlers.set(e,{handler:t,options:o}),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,t){if(t==null)throw new m("invalid topology",Y.ERR_INVALID_PARAMETERS);let n=`${(Math.random()*1e9).toString(36)}${Date.now()}`,o=this.topologies.get(e);return o==null&&(o=new Map,this.topologies.set(e,o)),o.set(n,t),n}unregister(e){for(let[t,n]of this.topologies.entries())n.has(e)&&(n.delete(e),n.size===0&&this.topologies.delete(t))}_onDisconnect(e){let t=e.detail;this.components.peerStore.get(t).then(n=>{for(let o of n.protocols){let s=this.topologies.get(o);if(s!=null)for(let i of s.values())i.filter?.has(t)!==!1&&(i.filter?.remove(t),i.onDisconnect?.(t))}}).catch(n=>{n.code!==Y.ERR_NOT_FOUND&&this.log.error("could not inform topologies of disconnecting peer %p",t,n)})}_onPeerUpdate(e){let{peer:t,previous:n}=e.detail,o=(n?.protocols??[]).filter(s=>!t.protocols.includes(s));for(let s of o){let i=this.topologies.get(s);if(i!=null)for(let a of i.values())a.filter?.has(t.id)!==!1&&(a.filter?.remove(t.id),a.onDisconnect?.(t.id))}}_onPeerIdentify(e){let t=e.detail.protocols,n=e.detail.connection,o=e.detail.peerId;for(let s of t){let i=this.topologies.get(s);if(i!=null)for(let a of i.values())n.transient&&a.notifyOnTransient!==!0||a.filter?.has(o)!==!0&&(a.filter?.add(o),a.onConnect?.(o,n))}}};var df=class{log;components;transports;listeners;faultTolerance;started;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:transports"),this.components=e,this.started=!1,this.transports=new Map,this.listeners=Pu({name:"libp2p_transport_manager_listeners",metrics:this.components.metrics}),this.faultTolerance=t.faultTolerance??ro.FATAL_ALL}[Symbol.toStringTag]="@libp2p/transport-manager";add(e){let t=e[Symbol.toStringTag];if(t==null)throw new m("Transport must have a valid tag",Y.ERR_INVALID_KEY);if(this.transports.has(t))throw new m(`There is already a transport with the tag ${t}`,Y.ERR_DUPLICATE_TRANSPORT);this.log("adding transport %s",t),this.transports.set(t,e),this.listeners.has(t)||this.listeners.set(t,[])}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[t,n]of this.listeners)for(this.log("closing listeners for %s",t);n.length>0;){let o=n.pop();o!=null&&e.push(o.close())}await Promise.all(e),this.log("all listeners closed");for(let t of this.listeners.keys())this.listeners.set(t,[]);this.started=!1}async dial(e,t){let n=this.dialTransportForMultiaddr(e);if(n==null)throw new m(`No transport available for address ${String(e)}`,Y.ERR_TRANSPORT_UNAVAILABLE);t?.onProgress?.(new H("transport-manager:selected-transport",n[Symbol.toStringTag]));try{return await n.dial(e,{...t,upgrader:this.components.upgrader})}catch(o){throw o.code==null&&(o.code=Y.ERR_TRANSPORT_DIAL_FAILED),o}}getAddrs(){let e=[];for(let t of this.listeners.values())for(let n of t)e=[...e,...n.getAddrs()];return e}getTransports(){return Array.of(...this.transports.values())}getListeners(){return Array.of(...this.listeners.values()).flat()}dialTransportForMultiaddr(e){for(let t of this.transports.values())if(t.dialFilter([e]).length>0)return t}listenTransportForMultiaddr(e){for(let t of this.transports.values())if(t.listenFilter([e]).length>0)return t}async listen(e){if(!this.isStarted())throw new m("Not started",Y.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 t=[];for(let[n,o]of this.transports.entries()){let s=o.listenFilter(e),i=[];for(let l of s){this.log("creating listener for %s on %a",n,l);let d=o.createListener({upgrader:this.components.upgrader}),u=this.listeners.get(n)??[];u==null&&(u=[],this.listeners.set(n,u)),u.push(d),d.addEventListener("listening",()=>{this.components.events.safeDispatchEvent("transport:listening",{detail:d})}),d.addEventListener("close",()=>{let f=u.findIndex(h=>h===d);u.splice(f,1),this.components.events.safeDispatchEvent("transport:close",{detail:d})}),i.push(d.listen(l))}if(i.length===0){t.push(n);continue}if((await Promise.allSettled(i)).find(l=>l.status==="fulfilled")==null&&this.faultTolerance!==ro.NO_FATAL)throw new m(`Transport (${n}) could not listen on any available address`,Y.ERR_NO_VALID_ADDRESSES)}if(t.length===this.transports.size){let n=`no valid addresses were provided for transports [${t.join(", ")}]`;if(this.faultTolerance===ro.FATAL_ALL)throw new m(n,Y.ERR_NO_VALID_ADDRESSES);this.log(`libp2p in dial mode only: ${n}`)}}async remove(e){let t=this.listeners.get(e)??[];this.log.trace("removing transport %s",e);let n=[];for(this.log.trace("closing listeners for %s",e);t.length>0;){let o=t.pop();o!=null&&n.push(o.close())}await Promise.all(n),this.transports.delete(e),this.listeners.delete(e)}async removeAll(){let e=[];for(let t of this.transports.keys())e.push(this.remove(t));await Promise.all(e)}};var Rt="/multistream/1.0.0";var UT=L(`
|
|
39
39
|
`);async function Ps(r,e,t){await r.write(e,t)}async function yw(r,e,t){await r.writeV(e,t)}async function FT(r,e){let t=await r.read(e);if(t.byteLength===0||t.get(t.byteLength-1)!==UT[0])throw e.log.error("Invalid mss message - missing newline",t),new m("missing newline","ERR_INVALID_MULTISTREAM_SELECT_MESSAGE");return t.sublist(0,-1)}async function Ho(r,e){let t=await FT(r,e);return U(t.subarray())}async function yc(r,e,t){if(e=Array.isArray(e)?[...e]:[e],e.length===1&&t.negotiateFully===!1)return VT(r,e[0],t);let n=En(r,{...t,maxDataLength:1024}),o=e.shift();if(o==null)throw new Error("At least one protocol must be specified");t.log.trace('select: write ["%s", "%s"]',Rt,o);let s=L(`${Rt}
|
|
40
40
|
`),i=L(`${o}
|
|
41
41
|
`);await yw(n,[s,i],t),t.log.trace("select: reading multistream-select header");let a=await Ho(n,t);if(t.log.trace('select: read "%s"',a),a===Rt&&(t.log.trace("select: reading protocol response"),a=await Ho(n,t),t.log.trace('select: read "%s"',a)),a===o)return{stream:n.unwrap(),protocol:o};for(let c of e){t.log.trace('select: write "%s"',c),await Ps(n,L(`${c}
|
package/dist/src/version.d.ts
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"version.d.ts","sourceRoot":"","sources":["../../src/version.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,OAAO,
|
|
1
|
+
{"version":3,"file":"version.d.ts","sourceRoot":"","sources":["../../src/version.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,OAAO,UAAU,CAAA;AAC9B,eAAO,MAAM,IAAI,UAAU,CAAA"}
|
package/dist/src/version.js
CHANGED
package/dist/src/version.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"version.js","sourceRoot":"","sources":["../../src/version.ts"],"names":[],"mappings":"AAAA,MAAM,CAAC,MAAM,OAAO,GAAG,
|
|
1
|
+
{"version":3,"file":"version.js","sourceRoot":"","sources":["../../src/version.ts"],"names":[],"mappings":"AAAA,MAAM,CAAC,MAAM,OAAO,GAAG,OAAO,CAAA;AAC9B,MAAM,CAAC,MAAM,IAAI,GAAG,OAAO,CAAA"}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
{
|
|
2
|
+
"DAGWalker": "https://ipfs.github.io/helia/interfaces/helia.DAGWalker.html",
|
|
3
|
+
".:DAGWalker": "https://ipfs.github.io/helia/interfaces/helia.DAGWalker.html",
|
|
4
|
+
"DefaultLibp2pServices": "https://ipfs.github.io/helia/interfaces/helia.DefaultLibp2pServices.html",
|
|
5
|
+
"HeliaInit": "https://ipfs.github.io/helia/interfaces/helia.HeliaInit.html",
|
|
6
|
+
".:HeliaInit": "https://ipfs.github.io/helia/interfaces/helia.HeliaInit.html",
|
|
7
|
+
"HeliaLibp2p": "https://ipfs.github.io/helia/interfaces/helia.HeliaLibp2p.html",
|
|
8
|
+
".:HeliaLibp2p": "https://ipfs.github.io/helia/interfaces/helia.HeliaLibp2p.html",
|
|
9
|
+
"createHelia": "https://ipfs.github.io/helia/functions/helia.createHelia.html",
|
|
10
|
+
".:createHelia": "https://ipfs.github.io/helia/functions/helia.createHelia.html",
|
|
11
|
+
"libp2pDefaults": "https://ipfs.github.io/helia/functions/helia.libp2pDefaults.html"
|
|
12
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "helia",
|
|
3
|
-
"version": "4.2.6
|
|
3
|
+
"version": "4.2.6",
|
|
4
4
|
"description": "An implementation of IPFS in JavaScript",
|
|
5
5
|
"license": "Apache-2.0 OR MIT",
|
|
6
6
|
"homepage": "https://github.com/ipfs/helia/tree/main/packages/helia#readme",
|
|
@@ -56,11 +56,11 @@
|
|
|
56
56
|
"dependencies": {
|
|
57
57
|
"@chainsafe/libp2p-noise": "^15.0.0",
|
|
58
58
|
"@chainsafe/libp2p-yamux": "^6.0.2",
|
|
59
|
-
"@helia/block-brokers": "3.0.4
|
|
59
|
+
"@helia/block-brokers": "^3.0.4",
|
|
60
60
|
"@helia/delegated-routing-v1-http-api-client": "^3.0.0",
|
|
61
|
-
"@helia/interface": "4.3.1
|
|
62
|
-
"@helia/routers": "1.1.1
|
|
63
|
-
"@helia/utils": "0.3.3
|
|
61
|
+
"@helia/interface": "^4.3.1",
|
|
62
|
+
"@helia/routers": "^1.1.1",
|
|
63
|
+
"@helia/utils": "^0.3.3",
|
|
64
64
|
"@libp2p/autonat": "^1.0.13",
|
|
65
65
|
"@libp2p/bootstrap": "^10.0.16",
|
|
66
66
|
"@libp2p/circuit-relay-v2": "^1.0.16",
|
package/src/version.ts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
export const version = '4.2.6
|
|
1
|
+
export const version = '4.2.6'
|
|
2
2
|
export const name = 'helia'
|