helia 2.0.1-230b15b → 2.0.1-4b4bf37

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.min.js CHANGED
@@ -103,7 +103,7 @@ a=candidate:1467250027 1 UDP 1467250027 ${t} ${n} typ host\r
103
103
  a=ice-ufrag:`+e+`
104
104
  `).replace(/\na=ice-pwd:[^\n]*\n/,`
105
105
  a=ice-pwd:`+e+`
106
- `),r}var YI=Array.from("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),QI=r=>[...Array(r)].map(()=>YI.at(Math.floor(Math.random()*YI.length))).join("");var Od=C("libp2p:webrtc:transport"),qz=1e4,Vz=ie("webrtc-direct").code,fg=ie("certhash").code,Bd=class{metrics;components;init;constructor(e,t={}){this.components=e,this.init=t,e.metrics!=null&&(this.metrics={dialerEvents:e.metrics.registerCounterGroup("libp2p_webrtc_dialer_events_total",{label:"event",help:"Total count of WebRTC dial events by type"})})}async dial(e,t){let n=await this._connect(e,t);return Od(`dialing address - ${e.toString()}`),n}createListener(e){throw sR("WebRTCTransport.createListener")}filter(e){return e.filter($z)}[Symbol.toStringTag]="@libp2p/webrtc-direct";[di]=!0;async _connect(e,t){let n=new AbortController,i=n.signal,s=e.getPeerId();if(s===null)throw yd("we need to have the remote's PeerId");let o=he(s),a=ug(Ld(e)),c=await yc.generateCertificate({name:"ECDSA",namedCurve:"P-256",hash:hg(a.name)}),l=new yc({certificates:[c]});try{let u=new Promise((D,k)=>{let F=l.createDataChannel("",{negotiated:!0,id:0}),q=setTimeout(()=>{let W=`Data channel was never opened: state: ${F.readyState}`;Od.error(W),this.metrics?.dialerEvents.increment({open_error:!0}),k(S4("data",W))},qz);F.onopen=W=>{clearTimeout(q),D(F)},F.onerror=W=>{clearTimeout(q);let pe=`Error opening a data channel for handshaking: ${W.target?.toString()??"not specified"}`;Od.error(pe),this.metrics?.dialerEvents.increment({unknown_error:!0}),k(S4("data",pe))}}),h="libp2p+webrtc+v1/"+QI(32),f=await l.createOffer(),d=GI(f,h);await l.setLocalDescription(d);let p=WI(e,h);await l.setRemoteDescription(p);let m=await u,g=this.components.peerId,y=this.generateNoisePrologue(l,a.code,e),w=nc({prologueBytes:y})(),E=bc({channel:m,direction:"inbound",dataChannelOptions:this.init.dataChannel}),S={...E,sink:E.sink.bind(E),source:async function*(){for await(let D of E.source)for(let k of D)yield k}()},x=new qo({peerConnection:l,remoteAddr:e,timeline:{open:Date.now()},metrics:this.metrics?.dialerEvents}),v=fu?"iceconnectionstatechange":"connectionstatechange";l.addEventListener(v,()=>{switch(l.connectionState){case"failed":case"disconnected":case"closed":x.close().catch(D=>{Od.error("error closing connection",D)}).finally(()=>{n.abort()});break;default:break}},{signal:i}),this.metrics?.dialerEvents.increment({peer_connection:!0});let R=new Vo({peerConnection:l,metrics:this.metrics?.dialerEvents,dataChannelOptions:this.init.dataChannel});return await w.secureInbound(g,S,o),await t.upgrader.upgradeOutbound(x,{skipProtection:!0,skipEncryption:!0,muxerFactory:R})}catch(u){throw l.close(),u}}generateNoisePrologue(e,t,n){if(e.getConfiguration().certificates?.length===0)throw hu("no local certificate");let i=HI(e);if(i==null)throw hu("no local fingerprint found");let s=i.trim().toLowerCase().replaceAll(":",""),o=Y(s,"hex"),a=XI.encode(o,t),c=lg.decode(Ld(n)),l=Y("libp2p-webrtc-noise:");return _e([l,a,c])}};function $z(r){let e=r.protoCodes();return e.includes(Vz)&&e.includes(fg)&&r.getPeerId()!=null&&!e.includes(ie("p2p-circuit").code)}function jI(r){return e=>new Bd(e,r)}function ZI(r){return e=>new vd(e,r)}function JI(r){let e;try{e=ie("sni").code}catch{return null}for(let[t,n]of r)if(t===e&&n!==void 0)return n;return null}function eT(r){return r.some(([e,t])=>e===ie("tls").code)}function tn(r,e,t){let n=tT[ie(r).name];if(n===void 0)throw new Error(`Can't interpret protocol ${ie(r).name}`);let i=n(e,t);return r===ie("ip6").code?`[${i}]`:i}var tT={ip4:(r,e)=>r,ip6:(r,e)=>e.length===0?r:`[${r}]`,tcp:(r,e)=>{let t=e.pop();if(t===void 0)throw new Error("Unexpected end of multiaddr");return`tcp://${tn(t[0],t[1]??"",e)}:${r}`},udp:(r,e)=>{let t=e.pop();if(t===void 0)throw new Error("Unexpected end of multiaddr");return`udp://${tn(t[0],t[1]??"",e)}:${r}`},dnsaddr:(r,e)=>r,dns4:(r,e)=>r,dns6:(r,e)=>r,dns:(r,e)=>r,ipfs:(r,e)=>{let t=e.pop();if(t===void 0)throw new Error("Unexpected end of multiaddr");return`${tn(t[0],t[1]??"",e)}/ipfs/${r}`},p2p:(r,e)=>{let t=e.pop();if(t===void 0)throw new Error("Unexpected end of multiaddr");return`${tn(t[0],t[1]??"",e)}/p2p/${r}`},http:(r,e)=>{let t=eT(e),n=JI(e);if(t&&n!==null)return`https://${n}`;let i=t?"https://":"http://",s=e.pop();if(s===void 0)throw new Error("Unexpected end of multiaddr");let o=tn(s[0],s[1]??"",e);return o=o.replace("tcp://",""),`${i}${o}`},tls:(r,e)=>{let t=e.pop();if(t===void 0)throw new Error("Unexpected end of multiaddr");return tn(t[0],t[1]??"",e)},sni:(r,e)=>{let t=e.pop();if(t===void 0)throw new Error("Unexpected end of multiaddr");return tn(t[0],t[1]??"",e)},https:(r,e)=>{let t=e.pop();if(t===void 0)throw new Error("Unexpected end of multiaddr");let n=tn(t[0],t[1]??"",e);return n=n.replace("tcp://",""),`https://${n}`},ws:(r,e)=>{let t=eT(e),n=JI(e);if(t&&n!==null)return`wss://${n}`;let i=t?"wss://":"ws://",s=e.pop();if(s===void 0)throw new Error("Unexpected end of multiaddr");let o=tn(s[0],s[1]??"",e);return o=o.replace("tcp://",""),`${i}${o}`},wss:(r,e)=>{let t=e.pop();if(t===void 0)throw new Error("Unexpected end of multiaddr");let n=tn(t[0],t[1]??"",e);return n=n.replace("tcp://",""),`wss://${n}`},"p2p-websocket-star":(r,e)=>{let t=e.pop();if(t===void 0)throw new Error("Unexpected end of multiaddr");return`${tn(t[0],t[1]??"",e)}/p2p-websocket-star`},"p2p-webrtc-star":(r,e)=>{let t=e.pop();if(t===void 0)throw new Error("Unexpected end of multiaddr");return`${tn(t[0],t[1]??"",e)}/p2p-webrtc-star`},"p2p-webrtc-direct":(r,e)=>{let t=e.pop();if(t===void 0)throw new Error("Unexpected end of multiaddr");return`${tn(t[0],t[1]??"",e)}/p2p-webrtc-direct`}};function rT(r,e){let n=oe(r).stringTuples(),i=n.pop();if(i===void 0)throw new Error("Unexpected end of multiaddr");let s=ie(i[0]),o=tT[s.name];if(o==null)throw new Error(`No interpreter found for ${s.name}`);let a=o(i[1]??"",n);return e?.assumeHttp!==!1&&i[0]===ie("tcp").code&&(a=a.replace("tcp://","http://"),(i[1]==="443"||i[1]==="80")&&(i[1]==="443"&&(a=a.replace("http://","https://")),a=a.substring(0,a.lastIndexOf(":")))),a}var nT=async r=>{if(r.readyState>=2)throw new Error("socket closed");r.readyState!==1&&await new Promise((e,t)=>{function n(){r.removeEventListener("open",i),r.removeEventListener("error",s)}function i(){n(),e()}function s(o){n(),t(o.error??new Error(`connect ECONNREFUSED ${r.url}`))}r.addEventListener("open",i),r.addEventListener("error",s)})};var iT=(r,e)=>(e=e??{},e.closeOnEnd=e.closeOnEnd!==!1,async n=>{for await(let i of n){try{await nT(r)}catch(s){if(s.message==="socket closed")break;throw s}if(r.readyState===r.CLOSING||r.readyState===r.CLOSED)break;r.send(i)}e.closeOnEnd!=null&&r.readyState<=1&&await new Promise((i,s)=>{r.addEventListener("close",o=>{if(o.wasClean||o.code===1006)i();else{let a=Object.assign(new Error("ws error"),{event:o});s(a)}}),setTimeout(()=>{r.close()})})});var cT=te(oT(),1);function aT(r){return r instanceof ArrayBuffer||r?.constructor?.name==="ArrayBuffer"&&typeof r?.byteLength=="number"}var lT=r=>{r.binaryType="arraybuffer";let e=async()=>{await new Promise((s,o)=>{if(n){s();return}if(i!=null){o(i);return}let a=u=>{r.removeEventListener("open",c),r.removeEventListener("error",l),u()},c=()=>{a(s)},l=u=>{a(()=>{o(u.error??new Error(`connect ECONNREFUSED ${r.url}`))})};r.addEventListener("open",c),r.addEventListener("error",l)})},t=async function*(){let s=new cT.EventIterator(({push:o,stop:a,fail:c})=>{let l=h=>{let f=null;typeof h.data=="string"&&(f=Y(h.data)),aT(h.data)&&(f=new Uint8Array(h.data)),h.data instanceof Uint8Array&&(f=h.data),f!=null&&o(f)},u=h=>{c(h.error??new Error("Socket error"))};return r.addEventListener("message",l),r.addEventListener("error",u),r.addEventListener("close",a),()=>{r.removeEventListener("message",l),r.removeEventListener("error",u),r.removeEventListener("close",a)}},{highWaterMark:1/0});await e();for await(let o of s)yield aT(o)?new Uint8Array(o):o}(),n=r.readyState===1,i;return r.addEventListener("open",()=>{n=!0,i=null}),r.addEventListener("close",()=>{n=!1,i=null}),r.addEventListener("error",s=>{n||(i=s.error??new Error(`connect ECONNREFUSED ${r.url}`))}),Object.assign(t,{connected:e})};var uT=(r,e)=>{e=e??{};let t=lT(r),n=e.remoteAddress,i=e.remotePort;if(r.url!=null)try{let o=new URL(r.url);n=o.hostname,i=parseInt(o.port,10)}catch{}if(n==null||i==null)throw new Error("Remote connection did not have address and/or port");return{sink:iT(r,e),source:t,connected:async()=>{await t.connected()},close:async()=>{(r.readyState===r.CONNECTING||r.readyState===r.OPEN)&&await new Promise(o=>{r.addEventListener("close",()=>{o()}),r.close()})},destroy:()=>{r.terminate!=null?r.terminate():r.close()},remoteAddress:n,remotePort:i,socket:r}};var hT=WebSocket;var wT=te(bT(),1),eH={http:"ws",https:"wss"},tH="ws",ET=(r,e)=>(0,wT.relative)(r,e,eH,tH);function xT(r,e){let t=typeof window>"u"?"":window.location;e=e??{};let n=ET(r,t.toString()),i=new hT(n,e.websocket);return uT(i,e)}var ST=te(_T(),1),yg=typeof window=="object"&&typeof document=="object"&&document.nodeType===9,Fd=(0,ST.default)(),Kd=yg&&!Fd,RT=Fd&&!yg,IT=Fd&&yg,TT=typeof globalThis.process<"u"&&typeof globalThis.process.release<"u"&&globalThis.process.release.name==="node"&&!Fd,qd=typeof importScripts=="function"&&typeof self<"u"&&typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope,F6e=typeof globalThis.process<"u"&&typeof globalThis.process.env<"u"&&globalThis.process.env["NODE"+(()=>"_")()+"ENV"]==="test",AT=typeof navigator<"u"&&navigator.product==="ReactNative";function PT(r){return r.filter(e=>{if(e.protoCodes().includes(290))return!1;let t=e.decapsulateCode(421);return oc.matches(t)||Mo.matches(t)})}function kT(r){return r.filter(e=>{if(e.protoCodes().includes(290))return!1;let t=e.decapsulateCode(421);return Mo.matches(t)})}function NT(){throw new Error("WebSocket Servers can not be created in the browser!")}var bg=C("libp2p:websockets:socket");function LT(r,e,t){t=t??{};let n={async sink(i){t?.signal!=null&&(i=ur(i,t.signal));try{await r.sink(i)}catch(s){s.type!=="aborted"&&bg.error(s)}},source:t.signal!=null?ur(r.source,t.signal):r.source,remoteAddr:e,timeline:{open:Date.now()},async close(i={}){let s=Date.now();i.signal=i.signal??AbortSignal.timeout(500);let o=()=>{let{host:a,port:c}=n.remoteAddr.toOptions();bg("timeout closing stream to %s:%s after %dms, destroying it manually",a,c,Date.now()-s),this.abort(new b("Socket close timeout","ERR_SOCKET_CLOSE_TIMEOUT"))};i.signal.addEventListener("abort",o);try{await r.close()}catch(a){this.abort(a)}finally{i.signal.removeEventListener("abort",o),n.timeline.close=Date.now()}},abort(i){let{host:s,port:o}=n.remoteAddr.toOptions();bg("timeout closing stream to %s:%s due to error",s,o,i),r.destroy(),n.timeline.close=Date.now()}};return r.socket.addEventListener("close",()=>{n.timeline.close==null&&(n.timeline.close=Date.now())},{once:!0}),n}var Ks=C("libp2p:websockets"),wg=class{init;constructor(e){this.init=e}[Symbol.toStringTag]="@libp2p/websockets";[di]=!0;async dial(e,t){Ks("dialing %s",e),t=t??{};let n=await this._connect(e,t),i=LT(n,e);Ks("new outbound connection %s",i.remoteAddr);let s=await t.upgrader.upgradeOutbound(i);return Ks("outbound connection %s upgraded",i.remoteAddr),s}async _connect(e,t){if(t?.signal?.aborted===!0)throw new Dn;let n=e.toOptions();Ks("dialing %s:%s",n.host,n.port);let i=Ae(),s=xT(rT(e),this.init);if(s.socket.addEventListener("error",()=>{let c=new b(`Could not connect to ${e.toString()}`,"ERR_CONNECTION_FAILED");Ks.error("connection error:",c),i.reject(c)}),t.signal==null)return await Promise.race([s.connected(),i.promise]),Ks("connected %s",e),s;let o,a=new Promise((c,l)=>{if(o=()=>{l(new Dn),s.close().catch(u=>{Ks.error("error closing raw socket",u)})},t?.signal?.aborted===!0){o();return}t?.signal?.addEventListener("abort",o)});try{await Promise.race([a,i.promise,s.connected()])}finally{o!=null&&t?.signal?.removeEventListener("abort",o)}return Ks("connected %s",e),s}createListener(e){return NT({...this.init,...e})}filter(e){return e=Array.isArray(e)?e:[e],this.init?.filter!=null?this.init?.filter(e):Kd||qd?kT(e):PT(e)}};function OT(r={}){return()=>new wg(r)}var _u=C("libp2p:webtransport:stream");async function Eg(r,e,t,n,i){let s=r.writable.getWriter(),o=r.readable.getReader();await s.ready;function a(){let f=n.findIndex(d=>d===h);f!==-1&&(n.splice(f,1),h.timeline.close=Date.now(),i?.(h))}let c=!1,l=!1;(async function(){let f=await s.closed.catch(d=>d);if(f!=null){let d=f.message;d.includes("aborted by the remote server")||d.includes("STOP_SENDING")||_u.error(`WebTransport writer closed unexpectedly: streamId=${e} err=${f.message}`)}c=!0,c&&l&&a()})().catch(()=>{_u.error("WebTransport failed to cleanup closed stream")}),async function(){let f=await o.closed.catch(d=>d);f!=null&&_u.error(`WebTransport reader closed unexpectedly: streamId=${e} err=${f.message}`),l=!0,c&&l&&a()}().catch(()=>{_u.error("WebTransport failed to cleanup closed stream")});let u=!1,h={id:e,status:"open",writeStatus:"ready",readStatus:"ready",abort(f){c||(s.abort(f).catch(d=>{_u.error("could not abort stream",d)}),c=!0),l=!0,this.status="aborted",this.writeStatus="closed",this.readStatus="closed",this.timeline.reset=this.timeline.close=this.timeline.closeRead=this.timeline.closeWrite=Date.now(),a()},async close(f){this.status="closing",await Promise.all([h.closeRead(f),h.closeWrite(f)]),a(),this.status="closed",this.timeline.close=Date.now()},async closeRead(f){if(!l){this.readStatus="closing";try{await o.cancel()}catch(d){d.toString().includes("RESET_STREAM")===!0&&(c=!0)}this.timeline.closeRead=Date.now(),this.readStatus="closed",l=!0}c&&a()},async closeWrite(f){if(!c){c=!0,this.writeStatus="closing";try{await s.close()}catch(d){d.toString().includes("RESET_STREAM")===!0&&(l=!0)}this.timeline.closeWrite=Date.now(),this.writeStatus="closed"}l&&a()},direction:t,timeline:{open:Date.now()},metadata:{},source:async function*(){for(;;){let f=await o.read();if(f.done){l=!0,c&&a();return}yield new Ee(f.value)}}(),sink:async function(f){if(u)throw new Error("sink already called on stream");u=!0;try{this.writeStatus="writing";for await(let d of f)if(d instanceof Uint8Array)await s.write(d);else for(let p of d)await s.write(p);this.writeStatus="done"}finally{this.timeline.closeWrite=Date.now(),this.writeStatus="closed",await h.closeWrite()}}};return h}function xg(){return{source:{[Symbol.asyncIterator](){return{async next(){return new Promise(()=>{})}}}},sink:async r=>new Promise(()=>{})}}function BT(r,e){return e.filter(n=>!!r.find(i=>me(n,i))).length===e.length}var sH=Object.values(on).map(r=>r.decoder).reduce((r,e)=>r.or(e));function oH(r){return Tn.decode(sH.decode(r))}function MT(r){let e=r.stringTuples(),{url:t,certhashes:n,remotePeer:i}=e.reduce((s,[o,a])=>{switch(o){case ie("ip6").code:case ie("dns6").code:a?.includes(":")===!0&&(a=`[${a}]`);case ie("ip4").code:case ie("dns4").code:if(s.seenHost||s.seenPort)throw new Error("Invalid multiaddr, saw host and already saw the host or port");return{...s,url:`${s.url}${a??""}`,seenHost:!0};case ie("quic").code:case ie("quic-v1").code:case ie("webtransport").code:if(!s.seenHost||!s.seenPort)throw new Error("Invalid multiaddr, Didn't see host and port, but saw quic/webtransport");return s;case ie("udp").code:if(s.seenPort)throw new Error("Invalid multiaddr, saw port but already saw the port");return{...s,url:`${s.url}:${a??""}`,seenPort:!0};case ie("certhash").code:if(!s.seenHost||!s.seenPort)throw new Error("Invalid multiaddr, saw the certhash before seeing the host and port");return{...s,certhashes:s.certhashes.concat([oH(a??"")])};case ie("p2p").code:return{...s,remotePeer:he(a??"")};default:throw new Error(`unexpected component in multiaddr: ${o} ${ie(o).name} ${a??""} `)}},{url:"https://",seenHost:!1,seenPort:!1,certhashes:[]});return{url:t,certhashes:n,remotePeer:i}}var rn=C("libp2p:webtransport"),vg=class{components;config;constructor(e,t={}){this.components=e,this.config={maxInboundStreams:t.maxInboundStreams??1e3}}[Symbol.toStringTag]="@libp2p/webtransport";[di]=!0;async dial(e,t){t?.signal?.throwIfAborted(),rn("dialing %s",e);let n=this.components.peerId;if(n===void 0)throw new Error("Need a local peerid");t=t??{};let{url:i,certhashes:s,remotePeer:o}=MT(e);if(o==null)throw new Error("Need a target peerid");if(s.length===0)throw new Error("Expected multiaddr to contain certhashes");let a,c,l=()=>{};try{let u=!1,h=new WebTransport(`${i}/.well-known/libp2p-webtransport?type=noise`,{serverCertificateHashes:s.map(f=>({algorithm:"sha-256",value:f.digest}))});if(l=f=>{try{if(c!=null){if(c.timeline.close!=null)return;c.timeline.close=Date.now()}if(u)return;h.close(f)}catch(d){rn.error("error closing wt session",d)}finally{u=!0}},h.closed.then(async()=>{await c?.close()}).catch(f=>{rn.error("error on remote wt session close",f),c?.abort(f)}).finally(()=>{c==null&&l()}),a=()=>{a!=null&&t.signal?.removeEventListener("abort",a),l()},t.signal?.addEventListener("abort",a),await h.ready,!await this.authenticateWebTransport(h,n,o,s))throw new Error("Failed to authenticate webtransport");return c={close:async f=>{rn("Closing webtransport"),l()},abort:f=>{rn("aborting webtransport due to passed err",f),l({closeCode:0,reason:f.message})},remoteAddr:e,timeline:{open:Date.now()},...xg()},t?.signal?.throwIfAborted(),await t.upgrader.upgradeOutbound(c,{skipEncryption:!0,muxerFactory:this.webtransportMuxer(h,l),skipProtection:!0})}catch(u){throw rn.error("caught wt session err",u),l({closeCode:0,reason:u.message}),u}finally{a!=null&&t.signal?.removeEventListener("abort",a)}}async authenticateWebTransport(e,t,n,i){let s=await e.createBidirectionalStream(),o=s.writable.getWriter(),a=s.readable.getReader();await o.ready;let c={source:async function*(){for(;;){let h=await a.read();if(h.value!=null&&(yield h.value),h.done)break}}(),sink:async function(h){for await(let f of h)await o.write(f)}},l=nc()(),{remoteExtensions:u}=await l.secureOutbound(t,c,n);if(o.close().catch(h=>{rn.error(`Failed to close authentication stream writer: ${h.message}`)}),a.cancel().catch(h=>{rn.error(`Failed to close authentication stream reader: ${h.message}`)}),!BT(u?.webtransportCerthashes??[],i.map(h=>h.bytes)))throw new Error("Our certhashes are not a subset of the remote's reported certhashes");return!0}webtransportMuxer(e,t){let n=0,i=this.config;return{protocol:"webtransport",createStreamMuxer:s=>{typeof s=="function"&&(s={onIncomingStream:s});let o=[];return async function(){let c=e.incomingBidirectionalStreams.getReader();for(;;){let{done:l,value:u}=await c.read();if(l)break;if(o.length>=i.maxInboundStreams)u.writable.close().catch(h=>{rn.error(`Failed to close inbound stream that crossed our maxInboundStream limit: ${h.message}`)}),u.readable.cancel().catch(h=>{rn.error(`Failed to close inbound stream that crossed our maxInboundStream limit: ${h.message}`)});else{let h=await Eg(u,String(n++),"inbound",o,s?.onStreamEnd);o.push(h),s?.onIncomingStream?.(h)}}}().catch(()=>{rn.error("WebTransport failed to receive incoming stream")}),{protocol:"webtransport",streams:o,newStream:async c=>{let l=await e.createBidirectionalStream(),u=await Eg(l,String(n++),s?.direction??"outbound",o,s?.onStreamEnd);return o.push(u),u},close:async c=>{rn("Closing webtransport muxer"),t()},abort:c=>{rn("Aborting webtransport muxer with err:",c),t({closeCode:0,reason:c.message})},...xg()}}}}createListener(e){throw new Error("Webtransport servers are not supported in Node or the browser")}filter(e){return e.filter(t=>t.protoNames().includes("webtransport"))}};function UT(r={}){return e=>new vg(e,r)}var wi;(function(r){let e;(function(i){i.EOL="EOL"})(e=r.ValidityType||(r.ValidityType={}));let t;(function(i){i[i.EOL=0]="EOL"})(t||(t={})),function(i){i.codec=()=>lt(t)}(e=r.ValidityType||(r.ValidityType={}));let n;r.codec=()=>(n==null&&(n=le((i,s,o={})=>{o.lengthDelimited!==!1&&s.fork(),i.value!=null&&(s.uint32(10),s.bytes(i.value)),i.signature!=null&&(s.uint32(18),s.bytes(i.signature)),i.validityType!=null&&(s.uint32(24),r.ValidityType.codec().encode(i.validityType,s)),i.validity!=null&&(s.uint32(34),s.bytes(i.validity)),i.sequence!=null&&(s.uint32(40),s.uint64(i.sequence)),i.ttl!=null&&(s.uint32(48),s.uint64(i.ttl)),i.pubKey!=null&&(s.uint32(58),s.bytes(i.pubKey)),i.signatureV2!=null&&(s.uint32(66),s.bytes(i.signatureV2)),i.data!=null&&(s.uint32(74),s.bytes(i.data)),o.lengthDelimited!==!1&&s.ldelim()},(i,s)=>{let o={},a=s==null?i.len:i.pos+s;for(;i.pos<a;){let c=i.uint32();switch(c>>>3){case 1:o.value=i.bytes();break;case 2:o.signature=i.bytes();break;case 3:o.validityType=r.ValidityType.codec().decode(i);break;case 4:o.validity=i.bytes();break;case 5:o.sequence=i.uint64();break;case 6:o.ttl=i.uint64();break;case 7:o.pubKey=i.bytes();break;case 8:o.signatureV2=i.bytes();break;case 9:o.data=i.bytes();break;default:i.skipType(c&7);break}}return o})),n),r.encode=i=>ce(i,r.codec()),r.decode=i=>ae(i,r.codec())})(wi||(wi={}));var Su=te(Xo(),1);var FT="ERR_IPNS_EXPIRED_RECORD",Vd="ERR_UNRECOGNIZED_VALIDITY";var qs="ERR_SIGNATURE_VERIFICATION",KT="ERR_UNRECOGNIZED_FORMAT";var _g="ERR_UNDEFINED_PARAMETER",qT="ERR_INVALID_RECORD_DATA",VT="ERR_INVALID_EMBEDDED_KEY";var $T="ERR_RECORD_TOO_LARGE";var HT=C("ipns:utils"),aH=Y("/ipns/");function Ru(r){let e=new RegExp("(\\d{4})-(\\d{2})-(\\d{2})T(\\d{2}):(\\d{2}):(\\d{2})\\.(\\d+)Z"),t=String(r).trim().match(e);if(t==null)throw new Error("Invalid format");let n=parseInt(t[1],10),i=parseInt(t[2],10)-1,s=parseInt(t[3],10),o=parseInt(t[4],10),a=parseInt(t[5],10),c=parseInt(t[6],10),l=parseInt(t[7].slice(0,-6),10);return new Date(Date.UTC(n,i,s,o,a,c,l))}var WT=async(r,e)=>{if(e==null||r==null){let n=new Error("one or more of the provided parameters are not defined");throw HT.error(n),(0,Su.default)(n,_g)}let t;if(e.pubKey!=null){try{t=Pr(e.pubKey)}catch(i){throw HT.error(i),i}if(!(await cr(e.pubKey)).equals(r))throw(0,Su.default)(new Error("Embedded public key did not match PeerID"),VT)}else r.publicKey!=null&&(t=Pr(r.publicKey));if(t!=null)return t;throw(0,Su.default)(new Error("no public key is available"),_g)};var GT=r=>{let e=Y("ipns-signature:");return _e([e,r])};var YT=r=>{let e=wi.decode(r);return e.sequence!=null&&(e.sequence=BigInt(e.sequence)),e.ttl!=null&&(e.ttl=BigInt(e.ttl)),{value:e.value??new Uint8Array(0),signature:e.signature??new Uint8Array(0),validityType:e.validityType??wi.ValidityType.EOL,validity:e.validity??new Uint8Array(0),sequence:e.sequence??0n,pubKey:e.pubKey,ttl:e.ttl??void 0,signatureV2:e.signatureV2,data:e.data}};var QT=r=>ft(r.slice(aH.length));var XT=r=>{let e=hn(r);if(e.ValidityType===0)e.ValidityType=wi.ValidityType.EOL;else throw(0,Su.default)(new Error("Unknown validity type"),Vd);return Number.isInteger(e.Sequence)&&(e.Sequence=BigInt(e.Sequence)),Number.isInteger(e.TTL)&&(e.TTL=BigInt(e.TTL)),e};function jT(r,e){let t=e.map((n,i)=>({entry:wi.decode(n),index:i}));return t.sort((n,i)=>{if(n.entry.signatureV2!=null&&i.entry.signatureV2==null)return-1;if(n.entry.signatureV2==null&&i.entry.signatureV2!=null)return 1;let s=n.entry.sequence??0n,o=i.entry.sequence??0n;if(s>o)return-1;if(s<o)return 1;let a=n.entry.validity??new Uint8Array(0),c=i.entry.validity??new Uint8Array(0),l=Ru($(a)),u=Ru($(c));return l.getTime()>u.getTime()?-1:l.getTime()<u.getTime()?1:0}),t[0].index}var nn=te(Xo(),1);var Iu=C("ipns:validator"),cH=1024*10,lH=async(r,e)=>{let{value:t,validityType:n,validity:i}=e,s,o;if(e.signatureV2!=null&&e.data!=null)o=e.signatureV2,s=GT(e.data),uH(e);else throw(0,nn.default)(new Error("missing data or signatureV2"),qs);let a;try{a=await r.verify(s,o)}catch{a=!1}if(!a)throw Iu.error("record signature verification failed"),(0,nn.default)(new Error("record signature verification failed"),qs);if(i!=null&&n===wi.ValidityType.EOL){let c;try{c=Ru($(i))}catch{throw Iu.error("unrecognized validity format (not an rfc3339 format)"),(0,nn.default)(new Error("unrecognized validity format (not an rfc3339 format)"),KT)}if(c.getTime()<Date.now())throw Iu.error("record has expired"),(0,nn.default)(new Error("record has expired"),FT)}else if(n!=null)throw Iu.error("unrecognized validity type"),(0,nn.default)(new Error("unrecognized validity type"),Vd);Iu("ipns entry for %b is valid",t)},uH=r=>{if(r.data==null)throw(0,nn.default)(new Error("Record data is missing"),qT);let e=XT(r.data);if(!me(e.Value,r.value))throw(0,nn.default)(new Error('Field "value" did not match between protobuf and CBOR'),qs);if(!me(e.Validity,r.validity))throw(0,nn.default)(new Error('Field "validity" did not match between protobuf and CBOR'),qs);if(e.ValidityType!==r.validityType)throw(0,nn.default)(new Error('Field "validityType" did not match between protobuf and CBOR'),qs);if(e.Sequence!==r.sequence)throw(0,nn.default)(new Error('Field "sequence" did not match between protobuf and CBOR'),qs);if(e.TTL!==r.ttl)throw(0,nn.default)(new Error('Field "ttl" did not match between protobuf and CBOR'),qs)};async function ZT(r,e){if(e.byteLength>cH)throw(0,nn.default)(new Error("record too large"),$T);let t=QT(r),n=YT(e),i=await WT(t,n);await lH(i,n)}var Rg=te(Dr(),1);var JT="libp2p",eA="autonat",tA="1.0.0";var Ie;(function(r){let e;(function(l){l.DIAL="DIAL",l.DIAL_RESPONSE="DIAL_RESPONSE"})(e=r.MessageType||(r.MessageType={}));let t;(function(l){l[l.DIAL=0]="DIAL",l[l.DIAL_RESPONSE=1]="DIAL_RESPONSE"})(t||(t={})),function(l){l.codec=()=>lt(t)}(e=r.MessageType||(r.MessageType={}));let n;(function(l){l.OK="OK",l.E_DIAL_ERROR="E_DIAL_ERROR",l.E_DIAL_REFUSED="E_DIAL_REFUSED",l.E_BAD_REQUEST="E_BAD_REQUEST",l.E_INTERNAL_ERROR="E_INTERNAL_ERROR"})(n=r.ResponseStatus||(r.ResponseStatus={}));let i;(function(l){l[l.OK=0]="OK",l[l.E_DIAL_ERROR=100]="E_DIAL_ERROR",l[l.E_DIAL_REFUSED=101]="E_DIAL_REFUSED",l[l.E_BAD_REQUEST=200]="E_BAD_REQUEST",l[l.E_INTERNAL_ERROR=300]="E_INTERNAL_ERROR"})(i||(i={})),function(l){l.codec=()=>lt(i)}(n=r.ResponseStatus||(r.ResponseStatus={}));let s;(function(l){let u;l.codec=()=>(u==null&&(u=le((h,f,d={})=>{if(d.lengthDelimited!==!1&&f.fork(),h.id!=null&&(f.uint32(10),f.bytes(h.id)),h.addrs!=null)for(let p of h.addrs)f.uint32(18),f.bytes(p);d.lengthDelimited!==!1&&f.ldelim()},(h,f)=>{let d={addrs:[]},p=f==null?h.len:h.pos+f;for(;h.pos<p;){let m=h.uint32();switch(m>>>3){case 1:d.id=h.bytes();break;case 2:d.addrs.push(h.bytes());break;default:h.skipType(m&7);break}}return d})),u),l.encode=h=>ce(h,l.codec()),l.decode=h=>ae(h,l.codec())})(s=r.PeerInfo||(r.PeerInfo={}));let o;(function(l){let u;l.codec=()=>(u==null&&(u=le((h,f,d={})=>{d.lengthDelimited!==!1&&f.fork(),h.peer!=null&&(f.uint32(10),r.PeerInfo.codec().encode(h.peer,f)),d.lengthDelimited!==!1&&f.ldelim()},(h,f)=>{let d={},p=f==null?h.len:h.pos+f;for(;h.pos<p;){let m=h.uint32();switch(m>>>3){case 1:d.peer=r.PeerInfo.codec().decode(h,h.uint32());break;default:h.skipType(m&7);break}}return d})),u),l.encode=h=>ce(h,l.codec()),l.decode=h=>ae(h,l.codec())})(o=r.Dial||(r.Dial={}));let a;(function(l){let u;l.codec=()=>(u==null&&(u=le((h,f,d={})=>{d.lengthDelimited!==!1&&f.fork(),h.status!=null&&(f.uint32(8),r.ResponseStatus.codec().encode(h.status,f)),h.statusText!=null&&(f.uint32(18),f.string(h.statusText)),h.addr!=null&&(f.uint32(26),f.bytes(h.addr)),d.lengthDelimited!==!1&&f.ldelim()},(h,f)=>{let d={},p=f==null?h.len:h.pos+f;for(;h.pos<p;){let m=h.uint32();switch(m>>>3){case 1:d.status=r.ResponseStatus.codec().decode(h);break;case 2:d.statusText=h.string();break;case 3:d.addr=h.bytes();break;default:h.skipType(m&7);break}}return d})),u),l.encode=h=>ce(h,l.codec()),l.decode=h=>ae(h,l.codec())})(a=r.DialResponse||(r.DialResponse={}));let c;r.codec=()=>(c==null&&(c=le((l,u,h={})=>{h.lengthDelimited!==!1&&u.fork(),l.type!=null&&(u.uint32(8),r.MessageType.codec().encode(l.type,u)),l.dial!=null&&(u.uint32(18),r.Dial.codec().encode(l.dial,u)),l.dialResponse!=null&&(u.uint32(26),r.DialResponse.codec().encode(l.dialResponse,u)),h.lengthDelimited!==!1&&u.ldelim()},(l,u)=>{let h={},f=u==null?l.len:l.pos+u;for(;l.pos<f;){let d=l.uint32();switch(d>>>3){case 1:h.type=r.MessageType.codec().decode(l);break;case 2:h.dial=r.Dial.codec().decode(l,l.uint32());break;case 3:h.dialResponse=r.DialResponse.codec().decode(l,l.uint32());break;default:l.skipType(d&7);break}}return h})),c),r.encode=l=>ce(l,r.codec()),r.decode=l=>ae(l,r.codec())})(Ie||(Ie={}));var Ve=C("libp2p:autonat"),Sg=4,Ig=class{components;startupDelay;refreshInterval;protocol;timeout;maxInboundStreams;maxOutboundStreams;verifyAddressTimeout;started;constructor(e,t){this.components=e,this.started=!1,this.protocol=`/${t.protocolPrefix??JT}/${eA}/${tA}`,this.timeout=t.timeout??3e4,this.maxInboundStreams=t.maxInboundStreams??1,this.maxOutboundStreams=t.maxOutboundStreams??1,this.startupDelay=t.startupDelay??5e3,this.refreshInterval=t.refreshInterval??6e4,this._verifyExternalAddresses=this._verifyExternalAddresses.bind(this)}isStarted(){return this.started}async start(){this.started||(await this.components.registrar.handle(this.protocol,e=>{this.handleIncomingAutonatStream(e).catch(t=>{Ve.error("error handling incoming autonat stream",t)})},{maxInboundStreams:this.maxInboundStreams,maxOutboundStreams:this.maxOutboundStreams}),this.verifyAddressTimeout=setTimeout(this._verifyExternalAddresses,this.startupDelay),this.started=!0)}async stop(){await this.components.registrar.unhandle(this.protocol),clearTimeout(this.verifyAddressTimeout),this.started=!1}async handleIncomingAutonatStream(e){let t=AbortSignal.timeout(this.timeout),n=()=>{e.stream.abort(new b("handleIncomingAutonatStream timeout",z.ERR_TIMEOUT))};t.addEventListener("abort",n,{once:!0});try{(0,Rg.setMaxListeners)?.(1/0,t)}catch{}let i=this.components.addressManager.getAddresses().map(s=>s.toOptions().host);try{let s=this;await Ce(e.stream,o=>Ct(o),async function*(o){let a=await zi(o);if(a==null){Ve("no message received"),yield Ie.encode({type:Ie.MessageType.DIAL_RESPONSE,dialResponse:{status:Ie.ResponseStatus.E_BAD_REQUEST,statusText:"No message was sent"}});return}let c;try{c=Ie.decode(a)}catch(m){Ve.error("could not decode message",m),yield Ie.encode({type:Ie.MessageType.DIAL_RESPONSE,dialResponse:{status:Ie.ResponseStatus.E_BAD_REQUEST,statusText:"Could not decode message"}});return}let l=c.dial;if(l==null){Ve.error("dial was missing from message"),yield Ie.encode({type:Ie.MessageType.DIAL_RESPONSE,dialResponse:{status:Ie.ResponseStatus.E_BAD_REQUEST,statusText:"No Dial message found in message"}});return}let u,h=l.peer;if(h==null||h.id==null){Ve.error("PeerId missing from message"),yield Ie.encode({type:Ie.MessageType.DIAL_RESPONSE,dialResponse:{status:Ie.ResponseStatus.E_BAD_REQUEST,statusText:"missing peer info"}});return}try{u=ft(h.id)}catch(m){Ve.error("invalid PeerId",m),yield Ie.encode({type:Ie.MessageType.DIAL_RESPONSE,dialResponse:{status:Ie.ResponseStatus.E_BAD_REQUEST,statusText:"bad peer id"}});return}if(Ve("incoming request from %p",u),!e.connection.remotePeer.equals(u)){Ve("target peer %p did not equal sending peer %p",u,e.connection.remotePeer),yield Ie.encode({type:Ie.MessageType.DIAL_RESPONSE,dialResponse:{status:Ie.ResponseStatus.E_BAD_REQUEST,statusText:"peer id mismatch"}});return}let f=h.addrs.map(m=>oe(m)).filter(m=>{let g=m.toOptions().host===e.connection.remoteAddr.toOptions().host;return Ve.trace("request to dial %a was sent from %a is same host %s",m,e.connection.remoteAddr,g),g}).filter(m=>{let g=m.toOptions().host,y=!(kr(g)??!1);return Ve.trace("host %s was public %s",g,y),y}).filter(m=>{let g=m.toOptions().host,y=!i.includes(g);return Ve.trace("host %s was not our host %s",g,y),y}).filter(m=>{let g=!!s.components.transportManager.transportForMultiaddr(m);return Ve.trace("transport for %a is supported %s",m,g),g}).map(m=>(m.getPeerId()==null&&(m=m.encapsulate(`/p2p/${u.toString()}`)),m));if(f.length===0){Ve("no valid multiaddrs for %p in message",u),yield Ie.encode({type:Ie.MessageType.DIAL_RESPONSE,dialResponse:{status:Ie.ResponseStatus.E_DIAL_REFUSED,statusText:"no dialable addresses"}});return}Ve("dial multiaddrs %s for peer %p",f.map(m=>m.toString()).join(", "),u);let d="",p=f[0];for await(let m of f){let g;p=m;try{if(g=await s.components.connectionManager.openConnection(m,{signal:t}),!g.remoteAddr.equals(m))throw Ve.error("tried to dial %a but dialed %a",m,g.remoteAddr),new Error("Unexpected remote address");Ve("Success %p",u),yield Ie.encode({type:Ie.MessageType.DIAL_RESPONSE,dialResponse:{status:Ie.ResponseStatus.OK,addr:g.remoteAddr.decapsulateCode(ie("p2p").code).bytes}});return}catch(y){Ve("could not dial %p",u,y),d=y.message}finally{g!=null&&await g.close()}}yield Ie.encode({type:Ie.MessageType.DIAL_RESPONSE,dialResponse:{status:Ie.ResponseStatus.E_DIAL_ERROR,statusText:d,addr:p.bytes}})},o=>_t(o),e.stream)}catch(s){Ve.error("error handling incoming autonat stream",s)}finally{t.removeEventListener("abort",n)}}_verifyExternalAddresses(){this.verifyExternalAddresses().catch(e=>{Ve.error("error verifying external address",e)})}async verifyExternalAddresses(){if(clearTimeout(this.verifyAddressTimeout),!this.isStarted())return;let e=this.components.addressManager,t=e.getObservedAddrs().filter(s=>{let o=s.toOptions();return!(kr(o.host)??!1)});if(t.length===0){Ve("no public addresses found, not requesting verification"),this.verifyAddressTimeout=setTimeout(this._verifyExternalAddresses,this.refreshInterval);return}let n=AbortSignal.timeout(this.timeout);try{(0,Rg.setMaxListeners)?.(1/0,n)}catch{}let i=this;try{Ve("verify multiaddrs %s",t.map(h=>h.toString()).join(", "));let s=Ie.encode({type:Ie.MessageType.DIAL,dial:{peer:{id:this.components.peerId.toBytes(),addrs:t.map(h=>h.bytes)}}}),a=(await I0()).toBytes(),c={},l=[],u=async h=>{let f=()=>{};try{Ve("asking %p to verify multiaddr",h.id);let d=await i.components.connectionManager.openConnection(h.id,{signal:n}),p=await d.newStream(this.protocol,{signal:n});f=()=>{p.abort(new b("verifyAddress timeout",z.ERR_TIMEOUT))},n.addEventListener("abort",f,{once:!0});let m=await Ce([s],y=>_t(y),p,y=>Ct(y),async y=>zi(y));if(m==null){Ve("no response received from %p",d.remotePeer);return}let g=Ie.decode(m);if(g.type!==Ie.MessageType.DIAL_RESPONSE||g.dialResponse==null){Ve("invalid autonat response from %p",d.remotePeer);return}if(g.dialResponse.status===Ie.ResponseStatus.OK){let y=d.remoteAddr.toOptions(),w;if(y.family===4)w=y.host.split(".")[0];else if(y.family===6)w=y.host.split(":")[0];else{Ve('remote address "%s" was not IP4 or IP6?',y.host);return}if(l.includes(w)){Ve("already have response from network segment %d - %s",w,y.host);return}l.push(w)}return g.dialResponse}catch(d){Ve.error("error asking remote to verify multiaddr",d)}finally{n.removeEventListener("abort",f)}};for await(let h of Fo(An(this.components.peerRouting.getClosestPeers(a,{signal:n}),f=>async()=>u(f)),{concurrency:Sg}))try{if(h==null)continue;let f=h.addr==null?t[0]:oe(h.addr);if(Ve("autonat response for %a is %s",f,h.status),h.status===Ie.ResponseStatus.E_BAD_REQUEST||h.status===Ie.ResponseStatus.E_DIAL_REFUSED||h.addr==null&&t.length>1)continue;if(!t.some(p=>p.equals(f))){Ve("peer reported %a as %s but it was not in our observed address list",f,h.status);continue}let d=f.toString();if(c[d]==null&&(c[d]={success:0,failure:0}),h.status===Ie.ResponseStatus.OK?c[d].success++:h.status===Ie.ResponseStatus.E_DIAL_ERROR&&c[d].failure++,c[d].success===Sg){Ve("%a is externally dialable",f),e.confirmObservedAddr(f);return}if(c[d].failure===Sg){Ve("%a is not externally dialable",f),e.removeObservedAddr(f);return}}catch(f){Ve.error("could not verify external address",f)}}finally{this.verifyAddressTimeout=setTimeout(this._verifyExternalAddresses,this.refreshInterval)}}};function rA(r={}){return e=>new Ig(e,r)}var xH=te(Dr(),1);var Tg="/libp2p/relay";var nA="circuit-relay-relay";var iA=BigInt(131072),Vs="/libp2p/circuit/relay/0.2.0/hop",$d="/libp2p/circuit/relay/0.2.0/stop",gH=30*1e3,yH=30*1e3;var Zi;(function(r){let e;(function(i){i.RESERVE="RESERVE",i.CONNECT="CONNECT",i.STATUS="STATUS"})(e=r.Type||(r.Type={}));let t;(function(i){i[i.RESERVE=0]="RESERVE",i[i.CONNECT=1]="CONNECT",i[i.STATUS=2]="STATUS"})(t||(t={})),function(i){i.codec=()=>lt(t)}(e=r.Type||(r.Type={}));let n;r.codec=()=>(n==null&&(n=le((i,s,o={})=>{o.lengthDelimited!==!1&&s.fork(),i.type!=null&&(s.uint32(8),r.Type.codec().encode(i.type,s)),i.peer!=null&&(s.uint32(18),Ac.codec().encode(i.peer,s)),i.reservation!=null&&(s.uint32(26),zd.codec().encode(i.reservation,s)),i.limit!=null&&(s.uint32(34),Dc.codec().encode(i.limit,s)),i.status!=null&&(s.uint32(40),Ut.codec().encode(i.status,s)),o.lengthDelimited!==!1&&s.ldelim()},(i,s)=>{let o={},a=s==null?i.len:i.pos+s;for(;i.pos<a;){let c=i.uint32();switch(c>>>3){case 1:o.type=r.Type.codec().decode(i);break;case 2:o.peer=Ac.codec().decode(i,i.uint32());break;case 3:o.reservation=zd.codec().decode(i,i.uint32());break;case 4:o.limit=Dc.codec().decode(i,i.uint32());break;case 5:o.status=Ut.codec().decode(i);break;default:i.skipType(c&7);break}}return o})),n),r.encode=i=>ce(i,r.codec()),r.decode=i=>ae(i,r.codec())})(Zi||(Zi={}));var jn;(function(r){let e;(function(i){i.CONNECT="CONNECT",i.STATUS="STATUS"})(e=r.Type||(r.Type={}));let t;(function(i){i[i.CONNECT=0]="CONNECT",i[i.STATUS=1]="STATUS"})(t||(t={})),function(i){i.codec=()=>lt(t)}(e=r.Type||(r.Type={}));let n;r.codec=()=>(n==null&&(n=le((i,s,o={})=>{o.lengthDelimited!==!1&&s.fork(),i.type!=null&&(s.uint32(8),r.Type.codec().encode(i.type,s)),i.peer!=null&&(s.uint32(18),Ac.codec().encode(i.peer,s)),i.limit!=null&&(s.uint32(26),Dc.codec().encode(i.limit,s)),i.status!=null&&(s.uint32(32),Ut.codec().encode(i.status,s)),o.lengthDelimited!==!1&&s.ldelim()},(i,s)=>{let o={},a=s==null?i.len:i.pos+s;for(;i.pos<a;){let c=i.uint32();switch(c>>>3){case 1:o.type=r.Type.codec().decode(i);break;case 2:o.peer=Ac.codec().decode(i,i.uint32());break;case 3:o.limit=Dc.codec().decode(i,i.uint32());break;case 4:o.status=Ut.codec().decode(i);break;default:i.skipType(c&7);break}}return o})),n),r.encode=i=>ce(i,r.codec()),r.decode=i=>ae(i,r.codec())})(jn||(jn={}));var Ac;(function(r){let e;r.codec=()=>(e==null&&(e=le((t,n,i={})=>{if(i.lengthDelimited!==!1&&n.fork(),t.id!=null&&t.id.byteLength>0&&(n.uint32(10),n.bytes(t.id)),t.addrs!=null)for(let s of t.addrs)n.uint32(18),n.bytes(s);i.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let i={id:new Uint8Array(0),addrs:[]},s=n==null?t.len:t.pos+n;for(;t.pos<s;){let o=t.uint32();switch(o>>>3){case 1:i.id=t.bytes();break;case 2:i.addrs.push(t.bytes());break;default:t.skipType(o&7);break}}return i})),e),r.encode=t=>ce(t,r.codec()),r.decode=t=>ae(t,r.codec())})(Ac||(Ac={}));var zd;(function(r){let e;r.codec=()=>(e==null&&(e=le((t,n,i={})=>{if(i.lengthDelimited!==!1&&n.fork(),t.expire!=null&&t.expire!==0n&&(n.uint32(8),n.uint64(t.expire)),t.addrs!=null)for(let s of t.addrs)n.uint32(18),n.bytes(s);t.voucher!=null&&(n.uint32(26),n.bytes(t.voucher)),i.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let i={expire:0n,addrs:[]},s=n==null?t.len:t.pos+n;for(;t.pos<s;){let o=t.uint32();switch(o>>>3){case 1:i.expire=t.uint64();break;case 2:i.addrs.push(t.bytes());break;case 3:i.voucher=t.bytes();break;default:t.skipType(o&7);break}}return i})),e),r.encode=t=>ce(t,r.codec()),r.decode=t=>ae(t,r.codec())})(zd||(zd={}));var Dc;(function(r){let e;r.codec=()=>(e==null&&(e=le((t,n,i={})=>{i.lengthDelimited!==!1&&n.fork(),t.duration!=null&&(n.uint32(8),n.uint32(t.duration)),t.data!=null&&(n.uint32(16),n.uint64(t.data)),i.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let i={},s=n==null?t.len:t.pos+n;for(;t.pos<s;){let o=t.uint32();switch(o>>>3){case 1:i.duration=t.uint32();break;case 2:i.data=t.uint64();break;default:t.skipType(o&7);break}}return i})),e),r.encode=t=>ce(t,r.codec()),r.decode=t=>ae(t,r.codec())})(Dc||(Dc={}));var Ut;(function(r){r.UNUSED="UNUSED",r.OK="OK",r.RESERVATION_REFUSED="RESERVATION_REFUSED",r.RESOURCE_LIMIT_EXCEEDED="RESOURCE_LIMIT_EXCEEDED",r.PERMISSION_DENIED="PERMISSION_DENIED",r.CONNECTION_FAILED="CONNECTION_FAILED",r.NO_RESERVATION="NO_RESERVATION",r.MALFORMED_MESSAGE="MALFORMED_MESSAGE",r.UNEXPECTED_MESSAGE="UNEXPECTED_MESSAGE"})(Ut||(Ut={}));var Ag;(function(r){r[r.UNUSED=0]="UNUSED",r[r.OK=100]="OK",r[r.RESERVATION_REFUSED=200]="RESERVATION_REFUSED",r[r.RESOURCE_LIMIT_EXCEEDED=201]="RESOURCE_LIMIT_EXCEEDED",r[r.PERMISSION_DENIED=202]="PERMISSION_DENIED",r[r.CONNECTION_FAILED=203]="CONNECTION_FAILED",r[r.NO_RESERVATION=204]="NO_RESERVATION",r[r.MALFORMED_MESSAGE=400]="MALFORMED_MESSAGE",r[r.UNEXPECTED_MESSAGE=401]="UNEXPECTED_MESSAGE"})(Ag||(Ag={}));(function(r){r.codec=()=>lt(Ag)})(Ut||(Ut={}));var Dg;(function(r){let e;r.codec=()=>(e==null&&(e=le((t,n,i={})=>{i.lengthDelimited!==!1&&n.fork(),t.relay!=null&&t.relay.byteLength>0&&(n.uint32(10),n.bytes(t.relay)),t.peer!=null&&t.peer.byteLength>0&&(n.uint32(18),n.bytes(t.peer)),t.expiration!=null&&t.expiration!==0n&&(n.uint32(24),n.uint64(t.expiration)),i.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let i={relay:new Uint8Array(0),peer:new Uint8Array(0),expiration:0n},s=n==null?t.len:t.pos+n;for(;t.pos<s;){let o=t.uint32();switch(o>>>3){case 1:i.relay=t.bytes();break;case 2:i.peer=t.bytes();break;case 3:i.expiration=t.uint64();break;default:t.skipType(o&7);break}}return i})),e),r.encode=t=>ce(t,r.codec()),r.decode=t=>ae(t,r.codec())})(Dg||(Dg={}));var w7e=C("libp2p:circuit-relay:utils");async function Cg(r){let e=new TextEncoder().encode(r),t=await Ne.digest(e);return we.createV0(t)}function Pg(r){let e=r*BigInt(1e3),t=new Date().getTime();return Number(e-BigInt(t))}var EH=te(lA(),1);var k7e=C("libp2p:circuit-relay:advert-service");var c9e=C("libp2p:circuit-relay:server");var vH=C("libp2p:stream:converter");function kg(r){let{stream:e,remoteAddr:t}=r,{sink:n,source:i}=e,s=async function*(){for await(let c of i)c instanceof Uint8Array?yield c:yield*c}(),o={async sink(c){try{await n(c),a()}catch(l){l.type!=="aborted"&&vH(l)}},source:s,remoteAddr:t,timeline:{open:Date.now(),close:void 0},async close(c){a(),await e.close(c)},abort(c){a(),e.abort(c)}};function a(){o.timeline.close==null&&(o.timeline.close=Date.now())}return o}var $s=C("libp2p:circuit-relay:discover-relays"),Hd=class extends Ue{peerId;peerStore;contentRouting;registrar;started;topologyId;constructor(e){super(),this.started=!1,this.peerId=e.peerId,this.peerStore=e.peerStore,this.contentRouting=e.contentRouting,this.registrar=e.registrar}isStarted(){return this.started}async start(){this.topologyId=await this.registrar.register(Vs,{onConnect:e=>{this.safeDispatchEvent("relay:discover",{detail:e})}}),this.discover().catch(e=>{$s.error("error listening on relays",e)}),this.started=!0}stop(){this.topologyId!=null&&this.registrar.unregister(this.topologyId),this.started=!1}async discover(){$s("searching peer store for relays");let e=await this.peerStore.all({filters:[t=>t.protocols.includes(Vs)],orders:[()=>Math.random()<.5?1:-1]});for(let t of e)$s("found relay peer %p in content peer store",t.id),this.safeDispatchEvent("relay:discover",{detail:t.id});$s("found %d relay peers in peer store",e.length);try{$s("searching content routing for relays");let t=await Cg(Tg),n=0;for await(let i of this.contentRouting.findProviders(t))if(i.multiaddrs.length>0&&!i.id.equals(this.peerId)){let s=i.id;n++,await this.peerStore.merge(s,{multiaddrs:i.multiaddrs}),$s("found relay peer %p in content routing",s),this.safeDispatchEvent("relay:discover",{detail:s})}$s("found %d relay peers in content routing",n)}catch(t){$s.error("failed when finding relays on the network",t)}}};var Ng=C("libp2p:circuit-relay:transport:listener"),Lg=class extends Ue{connectionManager;relayStore;listeningAddrs;constructor(e){super(),this.connectionManager=e.connectionManager,this.relayStore=e.relayStore,this.listeningAddrs=new lr,this.relayStore.addEventListener("relay:removed",t=>{this.#e(t.detail)})}async listen(e){Ng("listen on %a",e);let t=e.getPeerId(),n;if(t!=null){let s=he(t),o=this.connectionManager.getConnectionsMap().get(s)??[];o.length>0&&(n=o[0])}if(n==null){let s=e.toString().split("/p2p-circuit").find(a=>a!==""),o=oe(s);n=await this.connectionManager.openConnection(o)}if(!this.relayStore.hasReservation(n.remotePeer)){await this.relayStore.addRelay(n.remotePeer,"configured");return}let i=this.relayStore.getReservation(n.remotePeer);if(i==null)throw new b("Did not have reservation after making reservation","ERR_NO_RESERVATION");if(this.listeningAddrs.has(n.remotePeer)){Ng("already listening on relay %p",n.remotePeer);return}this.listeningAddrs.set(n.remotePeer,i.addrs.map(s=>oe(s).encapsulate("/p2p-circuit"))),this.safeDispatchEvent("listening",{})}getAddrs(){return[...this.listeningAddrs.values()].flat()}async close(){}#e(e){let t=this.listeningAddrs.has(e);Ng("relay peer removed %p - had reservation",e,t),this.listeningAddrs.delete(e),t&&this.safeDispatchEvent("close",{})}};function hA(r){return new Lg(r)}var Ir=C("libp2p:circuit-relay:transport:reservation-store"),SH=60*1e3*10,RH=60*1e3*5,IH=30*1e3,Wd=class extends Ue{peerId;connectionManager;transportManager;peerStore;events;reserveQueue;reservations;maxDiscoveredRelays;maxReservationQueueLength;reservationCompletionTimeout;started;constructor(e,t){super(),this.peerId=e.peerId,this.connectionManager=e.connectionManager,this.transportManager=e.transportManager,this.peerStore=e.peerStore,this.events=e.events,this.reservations=new lr,this.maxDiscoveredRelays=t?.discoverRelays??0,this.maxReservationQueueLength=t?.maxReservationQueueLength??100,this.reservationCompletionTimeout=t?.reservationCompletionTimeout??1e4,this.started=!1,this.reserveQueue=new Ha({concurrency:t?.reservationConcurrency??1}),this.events.addEventListener("peer:disconnect",n=>{this.#t(n.detail)})}isStarted(){return this.started}async start(){this.started=!0}async stop(){this.reserveQueue.clear(),this.reservations.forEach(({timeout:e})=>{clearTimeout(e)}),this.reservations.clear(),this.started=!1}async addRelay(e,t){if(this.peerId.equals(e)){Ir("not trying to use self as relay");return}if(this.reserveQueue.size>this.maxReservationQueueLength){Ir("not adding relay as the queue is full");return}if(this.reserveQueue.hasJob(e)){Ir("relay peer is already in the reservation queue");return}Ir("add relay %p",e),await this.reserveQueue.add(async()=>{try{let n=this.reservations.get(e);if(n!=null){if(Pg(n.reservation.expire)>SH){Ir("already have reservation on relay peer %p and it expires in more than 10 minutes",e);return}clearTimeout(n.timeout),this.reservations.delete(e)}if(t==="discovered"&&[...this.reservations.values()].reduce((u,h)=>(h.type==="discovered"&&u++,u),0)>=this.maxDiscoveredRelays){Ir("already have enough discovered relays");return}let i=AbortSignal.timeout(this.reservationCompletionTimeout),s=await this.connectionManager.openConnection(e,{signal:i});if(s.remoteAddr.protoNames().includes("p2p-circuit")){Ir("not creating reservation over relayed connection");return}let o=await this.#e(s,{signal:i});Ir("created reservation on relay peer %p",e);let a=Pg(o.expire),c=Math.min(Math.max(a-RH,IH),Math.pow(2,31)-1),l=setTimeout(()=>{this.addRelay(e,t).catch(u=>{Ir.error("could not refresh reservation to relay %p",e,u)})},c);this.reservations.set(e,{timeout:l,reservation:o,type:t}),await this.peerStore.merge(e,{tags:{[nA]:{value:1,ttl:a}}}),await this.transportManager.listen([oe(`/p2p/${e.toString()}/p2p-circuit`)])}catch(n){Ir.error("could not reserve slot on %p",e,n);let i=this.reservations.get(e);i!=null&&clearTimeout(i.timeout),this.reservations.delete(e)}},{peerId:e})}hasReservation(e){return this.reservations.has(e)}getReservation(e){return this.reservations.get(e)?.reservation}async#e(e,t){t.signal?.throwIfAborted(),Ir("requesting reservation from %p",e.remotePeer);let n=await e.newStream(Vs,t),s=rr(n).pb(Zi);await s.write({type:Zi.Type.RESERVE},t);let o;try{o=await s.read(t)}catch(c){throw Ir.error("error parsing reserve message response from %p because",e.remotePeer,c),c}finally{await n.close()}if(o.status===Ut.OK&&o.reservation!=null)return o.reservation;let a=`reservation failed with status ${o.status??"undefined"}`;throw Ir.error(a),new Error(a)}#t(e){let t=this.reservations.get(e);t!=null&&(Ir("connection to relay %p closed, removing reservation from local store",e),clearTimeout(t.timeout),this.reservations.delete(e),this.safeDispatchEvent("relay:removed",{detail:e}),this.reservations.size<this.maxDiscoveredRelays&&(Ir("not enough relays %d/%d",this.reservations.size,this.maxDiscoveredRelays),this.safeDispatchEvent("relay:not-enough-relays",{})))}};var dr=C("libp2p:circuit-relay:transport"),TH=r=>{if(r.peer==null)return!1;try{r.peer.addrs.forEach(oe)}catch{return!1}return!0},Og={maxInboundStopStreams:Ts,maxOutboundStopStreams:Ts,stopTimeout:3e4},Bg=class{discovery;registrar;peerStore;connectionManager;peerId;upgrader;addressManager;connectionGater;reservationStore;maxInboundStopStreams;maxOutboundStopStreams;stopTimeout;started;constructor(e,t){this.registrar=e.registrar,this.peerStore=e.peerStore,this.connectionManager=e.connectionManager,this.peerId=e.peerId,this.upgrader=e.upgrader,this.addressManager=e.addressManager,this.connectionGater=e.connectionGater,this.maxInboundStopStreams=t.maxInboundStopStreams??Og.maxInboundStopStreams,this.maxOutboundStopStreams=t.maxOutboundStopStreams??Og.maxOutboundStopStreams,this.stopTimeout=t.stopTimeout??Og.stopTimeout,t.discoverRelays!=null&&t.discoverRelays>0&&(this.discovery=new Hd(e),this.discovery.addEventListener("relay:discover",n=>{this.reservationStore.addRelay(n.detail,"discovered").catch(i=>{dr.error("could not add discovered relay %p",n.detail,i)})})),this.reservationStore=new Wd(e,t),this.reservationStore.addEventListener("relay:not-enough-relays",()=>{this.discovery?.discover().catch(n=>{dr.error("could not discover relays",n)})}),this.started=!1}isStarted(){return this.started}async start(){await this.reservationStore.start(),await this.discovery?.start(),await this.registrar.handle($d,e=>{this.onStop(e).catch(t=>{dr.error("error while handling STOP protocol",t),e.stream.abort(t)})},{maxInboundStreams:this.maxInboundStopStreams,maxOutboundStreams:this.maxOutboundStopStreams,runOnTransientConnection:!0}),this.started=!0}async stop(){this.discovery?.stop(),await this.reservationStore.stop(),await this.registrar.unhandle($d),this.started=!1}[di]=!0;[Symbol.toStringTag]="libp2p/circuit-relay-v2";async dial(e,t={}){if(e.protoCodes().filter(p=>p===290).length!==1){let p="Invalid circuit relay address";throw dr.error(p,e),new b(p,z.ERR_RELAYED_DIAL)}let n=e.toString().split("/p2p-circuit"),i=oe(n[0]),s=oe(n[n.length-1]),o=i.getPeerId(),a=s.getPeerId();if(o==null||a==null){let p=`Circuit relay dial to ${e.toString()} failed as address did not have peer ids`;throw dr.error(p),new b(p,z.ERR_RELAYED_DIAL)}let c=he(o),l=he(a),u=!1,f=this.connectionManager.getConnections(c)[0];f==null&&(await this.peerStore.merge(c,{multiaddrs:[i]}),f=await this.connectionManager.openConnection(c,t),u=!0);let d;try{return d=await f.newStream([Vs]),await this.connectV2({stream:d,connection:f,destinationPeer:l,destinationAddr:s,relayAddr:i,ma:e,disconnectOnFailure:u})}catch(p){throw dr.error(`Circuit relay dial to destination ${l.toString()} via relay ${c.toString()} failed`,p),d?.abort(p),u&&await f.close(),p}}async connectV2({stream:e,connection:t,destinationPeer:n,destinationAddr:i,relayAddr:s,ma:o,disconnectOnFailure:a}){try{let c=rr(e),l=c.pb(Zi);await l.write({type:Zi.Type.CONNECT,peer:{id:n.toBytes(),addrs:[oe(i).bytes]}});let u=await l.read();if(u.status!==Ut.OK)throw new b(`failed to connect via relay with status ${u?.status?.toString()??"undefined"}`,z.ERR_HOP_REQUEST_FAILED);let h=kg({stream:c.unwrap(),remoteAddr:o,localAddr:s.encapsulate(`/p2p-circuit/p2p/${this.peerId.toString()}`)});return dr("new outbound transient connection %a",h.remoteAddr),await this.upgrader.upgradeOutbound(h,{transient:!0})}catch(c){throw dr.error(`Circuit relay dial to destination ${n.toString()} via relay ${t.remotePeer.toString()} failed`,c),a&&await t.close(),c}}createListener(e){return hA({connectionManager:this.connectionManager,relayStore:this.reservationStore})}filter(e){return e=Array.isArray(e)?e:[e],e.filter(t=>Yn.matches(t))}async onStop({connection:e,stream:t}){let n=AbortSignal.timeout(this.stopTimeout),i=rr(t).pb(jn),s=await i.read({signal:n});if(dr("new circuit relay v2 stop stream from %p with type %s",e.remotePeer,s.type),s?.type===void 0){dr.error("type was missing from circuit v2 stop protocol request from %s",e.remotePeer),await i.write({type:jn.Type.STATUS,status:Ut.MALFORMED_MESSAGE},{signal:n}),await t.close();return}if(s.type!==jn.Type.CONNECT){dr.error("invalid stop connect request via peer %p",e.remotePeer),await i.write({type:jn.Type.STATUS,status:Ut.UNEXPECTED_MESSAGE},{signal:n}),await t.close();return}if(!TH(s)){dr.error("invalid stop connect request via peer %p",e.remotePeer),await i.write({type:jn.Type.STATUS,status:Ut.MALFORMED_MESSAGE},{signal:n}),await t.close();return}let o=ft(s.peer.id);if(await this.connectionGater.denyInboundRelayedConnection?.(e.remotePeer,o)===!0){dr.error("connection gater denied inbound relayed connection from %p",e.remotePeer),await i.write({type:jn.Type.STATUS,status:Ut.PERMISSION_DENIED},{signal:n}),await t.close();return}dr.trace("sending success response to %p",e.remotePeer),await i.write({type:jn.Type.STATUS,status:Ut.OK},{signal:n});let a=e.remoteAddr.encapsulate(`/p2p-circuit/p2p/${o.toString()}`),c=this.addressManager.getAddresses()[0],l=kg({stream:i.unwrap().unwrap(),remoteAddr:a,localAddr:c});dr("new inbound transient connection %a",l.remoteAddr),await this.upgrader.upgradeInbound(l,{transient:!0}),dr("%s connection %a upgraded","inbound",l.remoteAddr)}};function Mg(r={}){return e=>new Bg(e,r)}var fA=()=>{let r=new Error("Delay aborted");return r.name="AbortError",r},AH=new WeakMap;function DH({clearTimeout:r,setTimeout:e}={}){return(t,{value:n,signal:i}={})=>{if(i?.aborted)return Promise.reject(fA());let s,o,a,c=r??clearTimeout,l=()=>{c(s),a(fA())},u=()=>{i&&i.removeEventListener("abort",l)},h=new Promise((f,d)=>{o=()=>{u(),f(n)},a=d,s=(e??setTimeout)(o,t)});return i&&i.addEventListener("abort",l,{once:!0}),AH.set(h,()=>{c(s),s=null,o()}),h}}var CH=DH(),dA=CH;var Zn;(function(r){let e;(function(i){i.UNUSED="UNUSED",i.CONNECT="CONNECT",i.SYNC="SYNC"})(e=r.Type||(r.Type={}));let t;(function(i){i[i.UNUSED=0]="UNUSED",i[i.CONNECT=100]="CONNECT",i[i.SYNC=300]="SYNC"})(t||(t={})),function(i){i.codec=()=>lt(t)}(e=r.Type||(r.Type={}));let n;r.codec=()=>(n==null&&(n=le((i,s,o={})=>{if(o.lengthDelimited!==!1&&s.fork(),i.type!=null&&(s.uint32(8),r.Type.codec().encode(i.type,s)),i.observedAddresses!=null)for(let a of i.observedAddresses)s.uint32(18),s.bytes(a);o.lengthDelimited!==!1&&s.ldelim()},(i,s)=>{let o={observedAddresses:[]},a=s==null?i.len:i.pos+s;for(;i.pos<a;){let c=i.uint32();switch(c>>>3){case 1:o.type=r.Type.codec().decode(i);break;case 2:o.observedAddresses.push(i.bytes());break;default:i.skipType(c&7);break}}return o})),n),r.encode=i=>ce(i,r.codec()),r.decode=i=>ae(i,r.codec())})(Zn||(Zn={}));var pt=C("libp2p:dcutr"),pA=1024*4,mA=100,Gd={timeout:5e3,retries:3,maxInboundStreams:1,maxOutboundStreams:1},Yd=class{started;timeout;retries;maxInboundStreams;maxOutboundStreams;peerStore;registrar;connectionManager;addressManager;transportManager;topologyId;constructor(e,t){this.started=!1,this.peerStore=e.peerStore,this.registrar=e.registrar,this.addressManager=e.addressManager,this.connectionManager=e.connectionManager,this.transportManager=e.transportManager,this.timeout=t.timeout??Gd.timeout,this.retries=t.retries??Gd.retries,this.maxInboundStreams=t.maxInboundStreams??Gd.maxInboundStreams,this.maxOutboundStreams=t.maxOutboundStreams??Gd.maxOutboundStreams}isStarted(){return this.started}async start(){this.started||(this.topologyId=await this.registrar.register(Tu,{onConnect:(e,t)=>{t.transient&&t.direction==="inbound"&&this.upgradeInbound(t).catch(n=>{pt.error("error during outgoing DCUtR attempt",n)})}}),await this.registrar.handle(Tu,e=>{this.handleIncomingUpgrade(e.stream,e.connection).catch(t=>{pt.error("error during incoming DCUtR attempt",t),e.stream.abort(t)})},{maxInboundStreams:this.maxInboundStreams,maxOutboundStreams:this.maxOutboundStreams,runOnTransientConnection:!0}),this.started=!0)}async stop(){await this.registrar.unhandle(Tu),this.topologyId!=null&&this.registrar.unregister(this.topologyId),this.started=!1}async upgradeInbound(e){if(await this.attemptUnilateralConnectionUpgrade(e))return;let t;for(let n=0;n<this.retries;n++){let i={signal:AbortSignal.timeout(this.timeout)};try{t=await e.newStream([Tu],{signal:i.signal,runOnTransientConnection:!0});let s=rr(t,{maxDataLength:pA}).pb(Zn);pt("B sending connect to %p",e.remotePeer);let o=Date.now();await s.write({type:Zn.Type.CONNECT,observedAddresses:this.addressManager.getAddresses().map(h=>h.bytes)},i),pt("B receiving connect from %p",e.remotePeer);let a=await s.read(i);if(a.type!==Zn.Type.CONNECT)throw pt("A sent wrong message type"),new b("DCUtR message type was incorrect",z.ERR_INVALID_MESSAGE);let c=this.getDialableMultiaddrs(a.observedAddresses);if(c.length===0)throw pt("A did not have any dialable multiaddrs"),new b("DCUtR connect message had no multiaddrs",z.ERR_INVALID_MESSAGE);let l=Date.now()-o;pt("A sending sync, rtt %dms",l),await s.write({type:Zn.Type.SYNC,observedAddresses:[]},i),pt("A waiting for half RTT"),await dA(l/2),pt("B dialing",c);let u=await this.connectionManager.openConnection(c,{signal:i.signal,priority:mA});pt("DCUtR to %p succeeded to address %a, closing relayed connection",e.remotePeer,u.remoteAddr),await e.close(i);break}catch(s){if(pt.error("error while attempting DCUtR on attempt %d of %d",n+1,this.retries,s),t?.abort(s),n===this.retries)throw s}finally{t!=null&&await t.close(i)}}}async attemptUnilateralConnectionUpgrade(e){let n=(await this.peerStore.get(e.remotePeer)).addresses.map(i=>{let s=i.multiaddr;return s.getPeerId()==null?s.encapsulate(`/p2p/${e.remotePeer}`):s}).filter(i=>this.isPublicAndDialable(i));if(n.length>0){let i=AbortSignal.timeout(this.timeout);try{pt("attempting unilateral connection upgrade to %a",n);let s=await this.connectionManager.openConnection(n,{signal:i,force:!0});if(s.transient)throw new Error("Could not open a new, non-transient, connection");return pt("unilateral connection upgrade to %p succeeded via %a, closing relayed connection",e.remotePeer,s.remoteAddr),await e.close(),!0}catch(s){pt.error("unilateral connection upgrade to %p on addresses %a failed",e.remotePeer,n,s)}}else pt("peer %p has no public addresses, not attempting unilateral connection upgrade",e.remotePeer);return!1}async handleIncomingUpgrade(e,t){let n={signal:AbortSignal.timeout(this.timeout)};try{let i=rr(e,{maxDataLength:pA}).pb(Zn);pt("A receiving connect");let s=await i.read(n);if(s.type!==Zn.Type.CONNECT)throw pt("B sent wrong message type"),new b("DCUtR message type was incorrect",z.ERR_INVALID_MESSAGE);if(s.observedAddresses.length===0)throw pt("B sent no multiaddrs"),new b("DCUtR connect message had no multiaddrs",z.ERR_INVALID_MESSAGE);let o=this.getDialableMultiaddrs(s.observedAddresses);if(o.length===0)throw pt("B had no dialable multiaddrs"),new b("DCUtR connect message had no dialable multiaddrs",z.ERR_INVALID_MESSAGE);if(pt("A sending connect"),await i.write({type:Zn.Type.CONNECT,observedAddresses:this.addressManager.getAddresses().map(l=>l.bytes)}),pt("A receiving sync"),(await i.read(n)).type!==Zn.Type.SYNC)throw new b("DCUtR message type was incorrect",z.ERR_INVALID_MESSAGE);pt("A dialing",o);let c=await this.connectionManager.openConnection(o,{signal:n.signal,priority:mA,force:!0});pt("DCUtR to %p succeeded via %a, closing relayed connection",t.remotePeer,c.remoteAddr),await t.close(n)}catch(i){pt.error("incoming DCUtR from %p failed",t.remotePeer,i),e.abort(i)}finally{await e.close(n)}}getDialableMultiaddrs(e){let t=[];for(let n of e)if(!(n==null||n.length===0))try{let i=oe(n);if(!this.isPublicAndDialable(i))continue;t.push(i)}catch{}return t}isPublicAndDialable(e){if(Ml.matches(e))return!1;if(eE.matches(e))return!0;if(!iE.matches(e)||this.transportManager.transportForMultiaddr(e)==null)return!1;let n=e.toOptions();return kr(n.host)===!1}};var Tu="/libp2p/dcutr";function gA(r={}){return e=>new Yd(e,r)}var yA="0.46.10";var Ug=`js-libp2p/${yA}`;var bA="0.1.0",wA="id",EA="id/push",xA="1.0.0",vA="1.0.0";var Kg=te(Dr(),1);var zs;(function(r){let e;r.codec=()=>(e==null&&(e=le((t,n,i={})=>{if(i.lengthDelimited!==!1&&n.fork(),t.protocolVersion!=null&&(n.uint32(42),n.string(t.protocolVersion)),t.agentVersion!=null&&(n.uint32(50),n.string(t.agentVersion)),t.publicKey!=null&&(n.uint32(10),n.bytes(t.publicKey)),t.listenAddrs!=null)for(let s of t.listenAddrs)n.uint32(18),n.bytes(s);if(t.observedAddr!=null&&(n.uint32(34),n.bytes(t.observedAddr)),t.protocols!=null)for(let s of t.protocols)n.uint32(26),n.string(s);t.signedPeerRecord!=null&&(n.uint32(66),n.bytes(t.signedPeerRecord)),i.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let i={listenAddrs:[],protocols:[]},s=n==null?t.len:t.pos+n;for(;t.pos<s;){let o=t.uint32();switch(o>>>3){case 5:i.protocolVersion=t.string();break;case 6:i.agentVersion=t.string();break;case 1:i.publicKey=t.bytes();break;case 2:i.listenAddrs.push(t.bytes());break;case 4:i.observedAddr=t.bytes();break;case 3:i.protocols.push(t.string());break;case 8:i.signedPeerRecord=t.bytes();break;default:t.skipType(o&7);break}}return i})),e),r.encode=t=>ce(t,r.codec()),r.decode=t=>ae(t,r.codec())})(zs||(zs={}));var pr=C("libp2p:identify"),Fg=1024*8,sn={protocolPrefix:"ipfs",agentVersion:Ug,timeout:6e4,maxInboundStreams:1,maxOutboundStreams:1,maxPushIncomingStreams:1,maxPushOutgoingStreams:1,maxObservedAddresses:10,maxIdentifyMessageSize:8192,runOnConnectionOpen:!0,runOnTransientConnection:!0},Qd=class{identifyProtocolStr;identifyPushProtocolStr;host;started;timeout;peerId;peerStore;registrar;connectionManager;addressManager;maxInboundStreams;maxOutboundStreams;maxPushIncomingStreams;maxPushOutgoingStreams;maxIdentifyMessageSize;maxObservedAddresses;events;runOnTransientConnection;constructor(e,t){this.started=!1,this.peerId=e.peerId,this.peerStore=e.peerStore,this.registrar=e.registrar,this.addressManager=e.addressManager,this.connectionManager=e.connectionManager,this.events=e.events,this.identifyProtocolStr=`/${t.protocolPrefix??sn.protocolPrefix}/${wA}/${xA}`,this.identifyPushProtocolStr=`/${t.protocolPrefix??sn.protocolPrefix}/${EA}/${vA}`,this.timeout=t.timeout??sn.timeout,this.maxInboundStreams=t.maxInboundStreams??sn.maxInboundStreams,this.maxOutboundStreams=t.maxOutboundStreams??sn.maxOutboundStreams,this.maxPushIncomingStreams=t.maxPushIncomingStreams??sn.maxPushIncomingStreams,this.maxPushOutgoingStreams=t.maxPushOutgoingStreams??sn.maxPushOutgoingStreams,this.maxIdentifyMessageSize=t.maxIdentifyMessageSize??sn.maxIdentifyMessageSize,this.maxObservedAddresses=t.maxObservedAddresses??sn.maxObservedAddresses,this.runOnTransientConnection=t.runOnTransientConnection??sn.runOnTransientConnection,this.host={protocolVersion:`${t.protocolPrefix??sn.protocolPrefix}/${bA}`,agentVersion:t.agentVersion??sn.agentVersion},(t.runOnConnectionOpen??sn.runOnConnectionOpen)&&e.events.addEventListener("connection:open",n=>{let i=n.detail;this.identify(i).catch(s=>{pr.error("error during identify trigged by connection:open",s)})}),e.events.addEventListener("self:peer:update",n=>{this.push().catch(i=>{pr.error(i)})}),this.host.agentVersion===Ug&&(TT||RT?this.host.agentVersion+=` UserAgent=${globalThis.process.version}`:(Kd||qd||IT||AT)&&(this.host.agentVersion+=` UserAgent=${globalThis.navigator.userAgent}`))}isStarted(){return this.started}async start(){this.started||(await this.peerStore.merge(this.peerId,{metadata:{AgentVersion:Y(this.host.agentVersion),ProtocolVersion:Y(this.host.protocolVersion)}}),await this.registrar.handle(this.identifyProtocolStr,e=>{this._handleIdentify(e).catch(t=>{pr.error(t)})},{maxInboundStreams:this.maxInboundStreams,maxOutboundStreams:this.maxOutboundStreams,runOnTransientConnection:this.runOnTransientConnection}),await this.registrar.handle(this.identifyPushProtocolStr,e=>{this._handlePush(e).catch(t=>{pr.error(t)})},{maxInboundStreams:this.maxPushIncomingStreams,maxOutboundStreams:this.maxPushOutgoingStreams,runOnTransientConnection:this.runOnTransientConnection}),this.started=!0)}async stop(){await this.registrar.unhandle(this.identifyProtocolStr),await this.registrar.unhandle(this.identifyPushProtocolStr),this.started=!1}async pushToConnections(e){let t=this.addressManager.getAddresses().map(u=>u.decapsulateCode(ie("p2p").code)),n=new Gr({peerId:this.peerId,multiaddrs:t}),i=await bn.seal(n,this.peerId),s=this.registrar.getProtocols(),o=await this.peerStore.get(this.peerId),a=$(o.metadata.get("AgentVersion")??Y(this.host.agentVersion)),c=$(o.metadata.get("ProtocolVersion")??Y(this.host.protocolVersion)),l=e.map(async u=>{let h,f=AbortSignal.timeout(this.timeout);try{(0,Kg.setMaxListeners)?.(1/0,f)}catch{}try{h=await u.newStream([this.identifyPushProtocolStr],{signal:f,runOnTransientConnection:this.runOnTransientConnection}),await rr(h,{maxDataLength:this.maxIdentifyMessageSize??Fg}).pb(zs).write({listenAddrs:t.map(p=>p.bytes),signedPeerRecord:i.marshal(),protocols:s,agentVersion:a,protocolVersion:c},{signal:f}),await h.close({signal:f})}catch(d){pr.error("could not push identify update to peer",d),h?.abort(d)}});await Promise.all(l)}async push(){if(!this.isStarted())return;let e=[];await Promise.all(this.connectionManager.getConnections().map(async t=>{try{if(!(await this.peerStore.get(t.remotePeer)).protocols.includes(this.identifyPushProtocolStr))return;e.push(t)}catch(n){if(n.code!==z.ERR_NOT_FOUND)throw n}})),await this.pushToConnections(e)}async _identify(e,t={}){let n;t.signal=t.signal??AbortSignal.timeout(this.timeout);try{n=await e.newStream([this.identifyProtocolStr],{...t,runOnTransientConnection:this.runOnTransientConnection});let s=await rr(n,{maxDataLength:this.maxIdentifyMessageSize??Fg}).pb(zs).read(t);return await n.close(t),s}catch(i){throw pr.error("error while reading identify message",i),n?.abort(i),i}}async identify(e,t={}){let n=await this._identify(e,t),{publicKey:i,protocols:s,observedAddr:o}=n;if(i==null)throw new b("public key was missing from identify message",z.ERR_MISSING_PUBLIC_KEY);let a=await cr(i);if(!e.remotePeer.equals(a))throw new b("identified peer does not match the expected peer",z.ERR_INVALID_PEER);if(this.peerId.equals(a))throw new b("identified peer is our own peer id?",z.ERR_INVALID_PEER);let c=PH(o);pr("identify completed for peer %p and protocols %o",a,s),pr("our observed address is %a",c),c!=null&&this.addressManager.getObservedAddrs().length<(this.maxObservedAddresses??1/0)&&(pr("storing our observed address %a",c),this.addressManager.addObservedAddr(c));let l=await this.#e(e.remotePeer,n),u={peerId:a,protocolVersion:n.protocolVersion,agentVersion:n.agentVersion,publicKey:n.publicKey,listenAddrs:n.listenAddrs.map(h=>oe(h)),observedAddr:n.observedAddr==null?void 0:oe(n.observedAddr),protocols:n.protocols,signedPeerRecord:l};return this.events.safeDispatchEvent("peer:identify",{detail:u}),u}async _handleIdentify(e){let{connection:t,stream:n}=e,i=AbortSignal.timeout(this.timeout);try{(0,Kg.setMaxListeners)?.(1/0,i)}catch{}try{let s=this.peerId.publicKey??new Uint8Array(0),o=await this.peerStore.get(this.peerId),a=this.addressManager.getAddresses().map(u=>u.decapsulateCode(ie("p2p").code)),c=o.peerRecordEnvelope;if(a.length>0&&c==null){let u=new Gr({peerId:this.peerId,multiaddrs:a});c=(await bn.seal(u,this.peerId)).marshal().subarray()}await rr(n).pb(zs).write({protocolVersion:this.host.protocolVersion,agentVersion:this.host.agentVersion,publicKey:s,listenAddrs:a.map(u=>u.bytes),signedPeerRecord:c,observedAddr:t.remoteAddr.bytes,protocols:o.protocols},{signal:i}),await n.close({signal:i})}catch(s){pr.error("could not respond to identify request",s),n.abort(s)}}async _handlePush(e){let{connection:t,stream:n}=e;try{if(this.peerId.equals(t.remotePeer))throw new Error("received push from ourselves?");let i={signal:AbortSignal.timeout(this.timeout)},o=await rr(n,{maxDataLength:this.maxIdentifyMessageSize??Fg}).pb(zs).read(i);await n.close(i),await this.#e(t.remotePeer,o)}catch(i){pr.error("received invalid message",i),n.abort(i);return}pr("handled push from %p",t.remotePeer)}async#e(e,t){if(pr("received identify from %p",e),t==null)throw new Error("Message was null or undefined");let n={addresses:t.listenAddrs.map(s=>({isCertified:!1,multiaddr:oe(s)})),protocols:t.protocols,metadata:new Map,peerRecordEnvelope:t.signedPeerRecord},i;if(t.signedPeerRecord!=null){pr("received signedPeerRecord in push from %p",e);let s=t.signedPeerRecord,o=await bn.openAndCertify(s,Gr.DOMAIN),a=Gr.createFromProtobuf(o.payload);if(!a.peerId.equals(o.peerId))throw new Error("signing key does not match PeerId in the PeerRecord");if(!e.equals(a.peerId))throw new Error("signing key does not match remote PeerId");let c;try{c=await this.peerStore.get(a.peerId)}catch(l){if(l.code!=="ERR_NOT_FOUND")throw l}if(c!=null&&(n.metadata=c.metadata,c.peerRecordEnvelope!=null)){let l=await bn.createFromProtobuf(c.peerRecordEnvelope),u=Gr.createFromProtobuf(l.payload);u.seqNumber>=a.seqNumber&&(pr("sequence number was lower or equal to existing sequence number - stored: %d received: %d",u.seqNumber,a.seqNumber),a=u,s=c.peerRecordEnvelope)}n.peerRecordEnvelope=s,n.addresses=a.multiaddrs.map(l=>({isCertified:!0,multiaddr:l})),i={seq:a.seqNumber,addresses:a.multiaddrs}}else pr("%p did not send a signed peer record",e);return t.agentVersion!=null&&n.metadata.set("AgentVersion",Y(t.agentVersion)),t.protocolVersion!=null&&n.metadata.set("ProtocolVersion",Y(t.protocolVersion)),await this.peerStore.patch(e,n),i}};function PH(r){if(r!=null&&r.length>0)try{return oe(r)}catch{}}function _A(r={}){return e=>new Qd(e,r)}var SA={list:["/dnsaddr/bootstrap.libp2p.io/p2p/QmNnooDu7bfjPFoTZYxMNLWUQJyrVwtbZg5gBMjTezGAJN","/dnsaddr/bootstrap.libp2p.io/p2p/QmQCU2EcMqAqQPR2i9bChDtGNJchTbq5TbXJJ16u19uLTa","/dnsaddr/bootstrap.libp2p.io/p2p/QmbLHAnMoJPWSCR5Zhtx6BHJX9KiKNN6tpvbUcqanj75Nb","/dnsaddr/bootstrap.libp2p.io/p2p/QmcZf59bWwK5XFi76CZX8cbJ4BhTzzA3gU1ZjYZcYW3dwt","/ip4/104.131.131.82/tcp/4001/p2p/QmaCpDMGvV2BGHeYERUEnRQAwe3N8SzbUtfsmvsqQLuvuJ"]};function RA(){return{addresses:{listen:["/webrtc"]},transports:[ZI(),jI(),UT(),OT(),Mg({discoverRelays:1})],connectionEncryption:[nc()],streamMuxers:[r_(),iR()],peerDiscovery:[p_(SA)],contentRouters:[x_("https://cid.contact")],services:{identify:_A(),autoNAT:rA(),pubsub:pv(),dcutr:gA(),dht:J_({clientMode:!0,validators:{ipns:ZT},selectors:{ipns:jT}})}}}async function IA(r,e){let t=RA();return e=e??{},Ax({datastore:r,...t,...e,start:!1})}var qg="2.0.1-230b15b",Xd="helia";var kH=C("helia");async function NH(r={}){let e=r.datastore??new Qs,t=r.blockstore??new Oc,n;LH(r.libp2p)?n=r.libp2p:n=await IA(e,r.libp2p);let i=new Bh({...r,datastore:e,blockstore:t,libp2p:n});return r.start!==!1&&await i.start(),i.libp2p.isStarted()?await TA(i):i.libp2p.addEventListener("start",()=>{TA(i).catch(s=>{kH.error("could not add Helia to agent version",s)})}),i}function LH(r){return r==null?!1:["dial","dialProtocol","hangUp","handle","unhandle","getMultiaddrs","getProtocols"].every(t=>typeof r[t]=="function")}async function TA(r){let t=(await r.libp2p.peerStore.get(r.libp2p.peerId)).metadata.get("AgentVersion");if(t==null)return;let n=new TextDecoder().decode(t);n.match(/js-libp2p\/\d+\.\d+\.\d+\sUserAgent=/)!=null&&(n.includes(Xd)?n=`${Xd}/${qg} ${n.split(" ").slice(1).join(" ")}`:n=`${Xd}/${qg} ${n}`,await r.libp2p.peerStore.merge(r.libp2p.peerId,{metadata:{AgentVersion:new TextEncoder().encode(n)}}))}return Du(OH);})();
106
+ `),r}var YI=Array.from("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),QI=r=>[...Array(r)].map(()=>YI.at(Math.floor(Math.random()*YI.length))).join("");var Od=C("libp2p:webrtc:transport"),qz=1e4,Vz=ie("webrtc-direct").code,fg=ie("certhash").code,Bd=class{metrics;components;init;constructor(e,t={}){this.components=e,this.init=t,e.metrics!=null&&(this.metrics={dialerEvents:e.metrics.registerCounterGroup("libp2p_webrtc_dialer_events_total",{label:"event",help:"Total count of WebRTC dial events by type"})})}async dial(e,t){let n=await this._connect(e,t);return Od(`dialing address - ${e.toString()}`),n}createListener(e){throw sR("WebRTCTransport.createListener")}filter(e){return e.filter($z)}[Symbol.toStringTag]="@libp2p/webrtc-direct";[di]=!0;async _connect(e,t){let n=new AbortController,i=n.signal,s=e.getPeerId();if(s===null)throw yd("we need to have the remote's PeerId");let o=he(s),a=ug(Ld(e)),c=await yc.generateCertificate({name:"ECDSA",namedCurve:"P-256",hash:hg(a.name)}),l=new yc({certificates:[c]});try{let u=new Promise((D,k)=>{let F=l.createDataChannel("",{negotiated:!0,id:0}),q=setTimeout(()=>{let W=`Data channel was never opened: state: ${F.readyState}`;Od.error(W),this.metrics?.dialerEvents.increment({open_error:!0}),k(S4("data",W))},qz);F.onopen=W=>{clearTimeout(q),D(F)},F.onerror=W=>{clearTimeout(q);let pe=`Error opening a data channel for handshaking: ${W.target?.toString()??"not specified"}`;Od.error(pe),this.metrics?.dialerEvents.increment({unknown_error:!0}),k(S4("data",pe))}}),h="libp2p+webrtc+v1/"+QI(32),f=await l.createOffer(),d=GI(f,h);await l.setLocalDescription(d);let p=WI(e,h);await l.setRemoteDescription(p);let m=await u,g=this.components.peerId,y=this.generateNoisePrologue(l,a.code,e),w=nc({prologueBytes:y})(),E=bc({channel:m,direction:"inbound",dataChannelOptions:this.init.dataChannel}),S={...E,sink:E.sink.bind(E),source:async function*(){for await(let D of E.source)for(let k of D)yield k}()},x=new qo({peerConnection:l,remoteAddr:e,timeline:{open:Date.now()},metrics:this.metrics?.dialerEvents}),v=fu?"iceconnectionstatechange":"connectionstatechange";l.addEventListener(v,()=>{switch(l.connectionState){case"failed":case"disconnected":case"closed":x.close().catch(D=>{Od.error("error closing connection",D)}).finally(()=>{n.abort()});break;default:break}},{signal:i}),this.metrics?.dialerEvents.increment({peer_connection:!0});let R=new Vo({peerConnection:l,metrics:this.metrics?.dialerEvents,dataChannelOptions:this.init.dataChannel});return await w.secureInbound(g,S,o),await t.upgrader.upgradeOutbound(x,{skipProtection:!0,skipEncryption:!0,muxerFactory:R})}catch(u){throw l.close(),u}}generateNoisePrologue(e,t,n){if(e.getConfiguration().certificates?.length===0)throw hu("no local certificate");let i=HI(e);if(i==null)throw hu("no local fingerprint found");let s=i.trim().toLowerCase().replaceAll(":",""),o=Y(s,"hex"),a=XI.encode(o,t),c=lg.decode(Ld(n)),l=Y("libp2p-webrtc-noise:");return _e([l,a,c])}};function $z(r){let e=r.protoCodes();return e.includes(Vz)&&e.includes(fg)&&r.getPeerId()!=null&&!e.includes(ie("p2p-circuit").code)}function jI(r){return e=>new Bd(e,r)}function ZI(r){return e=>new vd(e,r)}function JI(r){let e;try{e=ie("sni").code}catch{return null}for(let[t,n]of r)if(t===e&&n!==void 0)return n;return null}function eT(r){return r.some(([e,t])=>e===ie("tls").code)}function tn(r,e,t){let n=tT[ie(r).name];if(n===void 0)throw new Error(`Can't interpret protocol ${ie(r).name}`);let i=n(e,t);return r===ie("ip6").code?`[${i}]`:i}var tT={ip4:(r,e)=>r,ip6:(r,e)=>e.length===0?r:`[${r}]`,tcp:(r,e)=>{let t=e.pop();if(t===void 0)throw new Error("Unexpected end of multiaddr");return`tcp://${tn(t[0],t[1]??"",e)}:${r}`},udp:(r,e)=>{let t=e.pop();if(t===void 0)throw new Error("Unexpected end of multiaddr");return`udp://${tn(t[0],t[1]??"",e)}:${r}`},dnsaddr:(r,e)=>r,dns4:(r,e)=>r,dns6:(r,e)=>r,dns:(r,e)=>r,ipfs:(r,e)=>{let t=e.pop();if(t===void 0)throw new Error("Unexpected end of multiaddr");return`${tn(t[0],t[1]??"",e)}/ipfs/${r}`},p2p:(r,e)=>{let t=e.pop();if(t===void 0)throw new Error("Unexpected end of multiaddr");return`${tn(t[0],t[1]??"",e)}/p2p/${r}`},http:(r,e)=>{let t=eT(e),n=JI(e);if(t&&n!==null)return`https://${n}`;let i=t?"https://":"http://",s=e.pop();if(s===void 0)throw new Error("Unexpected end of multiaddr");let o=tn(s[0],s[1]??"",e);return o=o.replace("tcp://",""),`${i}${o}`},tls:(r,e)=>{let t=e.pop();if(t===void 0)throw new Error("Unexpected end of multiaddr");return tn(t[0],t[1]??"",e)},sni:(r,e)=>{let t=e.pop();if(t===void 0)throw new Error("Unexpected end of multiaddr");return tn(t[0],t[1]??"",e)},https:(r,e)=>{let t=e.pop();if(t===void 0)throw new Error("Unexpected end of multiaddr");let n=tn(t[0],t[1]??"",e);return n=n.replace("tcp://",""),`https://${n}`},ws:(r,e)=>{let t=eT(e),n=JI(e);if(t&&n!==null)return`wss://${n}`;let i=t?"wss://":"ws://",s=e.pop();if(s===void 0)throw new Error("Unexpected end of multiaddr");let o=tn(s[0],s[1]??"",e);return o=o.replace("tcp://",""),`${i}${o}`},wss:(r,e)=>{let t=e.pop();if(t===void 0)throw new Error("Unexpected end of multiaddr");let n=tn(t[0],t[1]??"",e);return n=n.replace("tcp://",""),`wss://${n}`},"p2p-websocket-star":(r,e)=>{let t=e.pop();if(t===void 0)throw new Error("Unexpected end of multiaddr");return`${tn(t[0],t[1]??"",e)}/p2p-websocket-star`},"p2p-webrtc-star":(r,e)=>{let t=e.pop();if(t===void 0)throw new Error("Unexpected end of multiaddr");return`${tn(t[0],t[1]??"",e)}/p2p-webrtc-star`},"p2p-webrtc-direct":(r,e)=>{let t=e.pop();if(t===void 0)throw new Error("Unexpected end of multiaddr");return`${tn(t[0],t[1]??"",e)}/p2p-webrtc-direct`}};function rT(r,e){let n=oe(r).stringTuples(),i=n.pop();if(i===void 0)throw new Error("Unexpected end of multiaddr");let s=ie(i[0]),o=tT[s.name];if(o==null)throw new Error(`No interpreter found for ${s.name}`);let a=o(i[1]??"",n);return e?.assumeHttp!==!1&&i[0]===ie("tcp").code&&(a=a.replace("tcp://","http://"),(i[1]==="443"||i[1]==="80")&&(i[1]==="443"&&(a=a.replace("http://","https://")),a=a.substring(0,a.lastIndexOf(":")))),a}var nT=async r=>{if(r.readyState>=2)throw new Error("socket closed");r.readyState!==1&&await new Promise((e,t)=>{function n(){r.removeEventListener("open",i),r.removeEventListener("error",s)}function i(){n(),e()}function s(o){n(),t(o.error??new Error(`connect ECONNREFUSED ${r.url}`))}r.addEventListener("open",i),r.addEventListener("error",s)})};var iT=(r,e)=>(e=e??{},e.closeOnEnd=e.closeOnEnd!==!1,async n=>{for await(let i of n){try{await nT(r)}catch(s){if(s.message==="socket closed")break;throw s}if(r.readyState===r.CLOSING||r.readyState===r.CLOSED)break;r.send(i)}e.closeOnEnd!=null&&r.readyState<=1&&await new Promise((i,s)=>{r.addEventListener("close",o=>{if(o.wasClean||o.code===1006)i();else{let a=Object.assign(new Error("ws error"),{event:o});s(a)}}),setTimeout(()=>{r.close()})})});var cT=te(oT(),1);function aT(r){return r instanceof ArrayBuffer||r?.constructor?.name==="ArrayBuffer"&&typeof r?.byteLength=="number"}var lT=r=>{r.binaryType="arraybuffer";let e=async()=>{await new Promise((s,o)=>{if(n){s();return}if(i!=null){o(i);return}let a=u=>{r.removeEventListener("open",c),r.removeEventListener("error",l),u()},c=()=>{a(s)},l=u=>{a(()=>{o(u.error??new Error(`connect ECONNREFUSED ${r.url}`))})};r.addEventListener("open",c),r.addEventListener("error",l)})},t=async function*(){let s=new cT.EventIterator(({push:o,stop:a,fail:c})=>{let l=h=>{let f=null;typeof h.data=="string"&&(f=Y(h.data)),aT(h.data)&&(f=new Uint8Array(h.data)),h.data instanceof Uint8Array&&(f=h.data),f!=null&&o(f)},u=h=>{c(h.error??new Error("Socket error"))};return r.addEventListener("message",l),r.addEventListener("error",u),r.addEventListener("close",a),()=>{r.removeEventListener("message",l),r.removeEventListener("error",u),r.removeEventListener("close",a)}},{highWaterMark:1/0});await e();for await(let o of s)yield aT(o)?new Uint8Array(o):o}(),n=r.readyState===1,i;return r.addEventListener("open",()=>{n=!0,i=null}),r.addEventListener("close",()=>{n=!1,i=null}),r.addEventListener("error",s=>{n||(i=s.error??new Error(`connect ECONNREFUSED ${r.url}`))}),Object.assign(t,{connected:e})};var uT=(r,e)=>{e=e??{};let t=lT(r),n=e.remoteAddress,i=e.remotePort;if(r.url!=null)try{let o=new URL(r.url);n=o.hostname,i=parseInt(o.port,10)}catch{}if(n==null||i==null)throw new Error("Remote connection did not have address and/or port");return{sink:iT(r,e),source:t,connected:async()=>{await t.connected()},close:async()=>{(r.readyState===r.CONNECTING||r.readyState===r.OPEN)&&await new Promise(o=>{r.addEventListener("close",()=>{o()}),r.close()})},destroy:()=>{r.terminate!=null?r.terminate():r.close()},remoteAddress:n,remotePort:i,socket:r}};var hT=WebSocket;var wT=te(bT(),1),eH={http:"ws",https:"wss"},tH="ws",ET=(r,e)=>(0,wT.relative)(r,e,eH,tH);function xT(r,e){let t=typeof window>"u"?"":window.location;e=e??{};let n=ET(r,t.toString()),i=new hT(n,e.websocket);return uT(i,e)}var ST=te(_T(),1),yg=typeof window=="object"&&typeof document=="object"&&document.nodeType===9,Fd=(0,ST.default)(),Kd=yg&&!Fd,RT=Fd&&!yg,IT=Fd&&yg,TT=typeof globalThis.process<"u"&&typeof globalThis.process.release<"u"&&globalThis.process.release.name==="node"&&!Fd,qd=typeof importScripts=="function"&&typeof self<"u"&&typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope,F6e=typeof globalThis.process<"u"&&typeof globalThis.process.env<"u"&&globalThis.process.env["NODE"+(()=>"_")()+"ENV"]==="test",AT=typeof navigator<"u"&&navigator.product==="ReactNative";function PT(r){return r.filter(e=>{if(e.protoCodes().includes(290))return!1;let t=e.decapsulateCode(421);return oc.matches(t)||Mo.matches(t)})}function kT(r){return r.filter(e=>{if(e.protoCodes().includes(290))return!1;let t=e.decapsulateCode(421);return Mo.matches(t)})}function NT(){throw new Error("WebSocket Servers can not be created in the browser!")}var bg=C("libp2p:websockets:socket");function LT(r,e,t){t=t??{};let n={async sink(i){t?.signal!=null&&(i=ur(i,t.signal));try{await r.sink(i)}catch(s){s.type!=="aborted"&&bg.error(s)}},source:t.signal!=null?ur(r.source,t.signal):r.source,remoteAddr:e,timeline:{open:Date.now()},async close(i={}){let s=Date.now();i.signal=i.signal??AbortSignal.timeout(500);let o=()=>{let{host:a,port:c}=n.remoteAddr.toOptions();bg("timeout closing stream to %s:%s after %dms, destroying it manually",a,c,Date.now()-s),this.abort(new b("Socket close timeout","ERR_SOCKET_CLOSE_TIMEOUT"))};i.signal.addEventListener("abort",o);try{await r.close()}catch(a){this.abort(a)}finally{i.signal.removeEventListener("abort",o),n.timeline.close=Date.now()}},abort(i){let{host:s,port:o}=n.remoteAddr.toOptions();bg("timeout closing stream to %s:%s due to error",s,o,i),r.destroy(),n.timeline.close=Date.now()}};return r.socket.addEventListener("close",()=>{n.timeline.close==null&&(n.timeline.close=Date.now())},{once:!0}),n}var Ks=C("libp2p:websockets"),wg=class{init;constructor(e){this.init=e}[Symbol.toStringTag]="@libp2p/websockets";[di]=!0;async dial(e,t){Ks("dialing %s",e),t=t??{};let n=await this._connect(e,t),i=LT(n,e);Ks("new outbound connection %s",i.remoteAddr);let s=await t.upgrader.upgradeOutbound(i);return Ks("outbound connection %s upgraded",i.remoteAddr),s}async _connect(e,t){if(t?.signal?.aborted===!0)throw new Dn;let n=e.toOptions();Ks("dialing %s:%s",n.host,n.port);let i=Ae(),s=xT(rT(e),this.init);if(s.socket.addEventListener("error",()=>{let c=new b(`Could not connect to ${e.toString()}`,"ERR_CONNECTION_FAILED");Ks.error("connection error:",c),i.reject(c)}),t.signal==null)return await Promise.race([s.connected(),i.promise]),Ks("connected %s",e),s;let o,a=new Promise((c,l)=>{if(o=()=>{l(new Dn),s.close().catch(u=>{Ks.error("error closing raw socket",u)})},t?.signal?.aborted===!0){o();return}t?.signal?.addEventListener("abort",o)});try{await Promise.race([a,i.promise,s.connected()])}finally{o!=null&&t?.signal?.removeEventListener("abort",o)}return Ks("connected %s",e),s}createListener(e){return NT({...this.init,...e})}filter(e){return e=Array.isArray(e)?e:[e],this.init?.filter!=null?this.init?.filter(e):Kd||qd?kT(e):PT(e)}};function OT(r={}){return()=>new wg(r)}var _u=C("libp2p:webtransport:stream");async function Eg(r,e,t,n,i){let s=r.writable.getWriter(),o=r.readable.getReader();await s.ready;function a(){let f=n.findIndex(d=>d===h);f!==-1&&(n.splice(f,1),h.timeline.close=Date.now(),i?.(h))}let c=!1,l=!1;(async function(){let f=await s.closed.catch(d=>d);if(f!=null){let d=f.message;d.includes("aborted by the remote server")||d.includes("STOP_SENDING")||_u.error(`WebTransport writer closed unexpectedly: streamId=${e} err=${f.message}`)}c=!0,c&&l&&a()})().catch(()=>{_u.error("WebTransport failed to cleanup closed stream")}),async function(){let f=await o.closed.catch(d=>d);f!=null&&_u.error(`WebTransport reader closed unexpectedly: streamId=${e} err=${f.message}`),l=!0,c&&l&&a()}().catch(()=>{_u.error("WebTransport failed to cleanup closed stream")});let u=!1,h={id:e,status:"open",writeStatus:"ready",readStatus:"ready",abort(f){c||(s.abort(f).catch(d=>{_u.error("could not abort stream",d)}),c=!0),l=!0,this.status="aborted",this.writeStatus="closed",this.readStatus="closed",this.timeline.reset=this.timeline.close=this.timeline.closeRead=this.timeline.closeWrite=Date.now(),a()},async close(f){this.status="closing",await Promise.all([h.closeRead(f),h.closeWrite(f)]),a(),this.status="closed",this.timeline.close=Date.now()},async closeRead(f){if(!l){this.readStatus="closing";try{await o.cancel()}catch(d){d.toString().includes("RESET_STREAM")===!0&&(c=!0)}this.timeline.closeRead=Date.now(),this.readStatus="closed",l=!0}c&&a()},async closeWrite(f){if(!c){c=!0,this.writeStatus="closing";try{await s.close()}catch(d){d.toString().includes("RESET_STREAM")===!0&&(l=!0)}this.timeline.closeWrite=Date.now(),this.writeStatus="closed"}l&&a()},direction:t,timeline:{open:Date.now()},metadata:{},source:async function*(){for(;;){let f=await o.read();if(f.done){l=!0,c&&a();return}yield new Ee(f.value)}}(),sink:async function(f){if(u)throw new Error("sink already called on stream");u=!0;try{this.writeStatus="writing";for await(let d of f)if(d instanceof Uint8Array)await s.write(d);else for(let p of d)await s.write(p);this.writeStatus="done"}finally{this.timeline.closeWrite=Date.now(),this.writeStatus="closed",await h.closeWrite()}}};return h}function xg(){return{source:{[Symbol.asyncIterator](){return{async next(){return new Promise(()=>{})}}}},sink:async r=>new Promise(()=>{})}}function BT(r,e){return e.filter(n=>!!r.find(i=>me(n,i))).length===e.length}var sH=Object.values(on).map(r=>r.decoder).reduce((r,e)=>r.or(e));function oH(r){return Tn.decode(sH.decode(r))}function MT(r){let e=r.stringTuples(),{url:t,certhashes:n,remotePeer:i}=e.reduce((s,[o,a])=>{switch(o){case ie("ip6").code:case ie("dns6").code:a?.includes(":")===!0&&(a=`[${a}]`);case ie("ip4").code:case ie("dns4").code:if(s.seenHost||s.seenPort)throw new Error("Invalid multiaddr, saw host and already saw the host or port");return{...s,url:`${s.url}${a??""}`,seenHost:!0};case ie("quic").code:case ie("quic-v1").code:case ie("webtransport").code:if(!s.seenHost||!s.seenPort)throw new Error("Invalid multiaddr, Didn't see host and port, but saw quic/webtransport");return s;case ie("udp").code:if(s.seenPort)throw new Error("Invalid multiaddr, saw port but already saw the port");return{...s,url:`${s.url}:${a??""}`,seenPort:!0};case ie("certhash").code:if(!s.seenHost||!s.seenPort)throw new Error("Invalid multiaddr, saw the certhash before seeing the host and port");return{...s,certhashes:s.certhashes.concat([oH(a??"")])};case ie("p2p").code:return{...s,remotePeer:he(a??"")};default:throw new Error(`unexpected component in multiaddr: ${o} ${ie(o).name} ${a??""} `)}},{url:"https://",seenHost:!1,seenPort:!1,certhashes:[]});return{url:t,certhashes:n,remotePeer:i}}var rn=C("libp2p:webtransport"),vg=class{components;config;constructor(e,t={}){this.components=e,this.config={maxInboundStreams:t.maxInboundStreams??1e3}}[Symbol.toStringTag]="@libp2p/webtransport";[di]=!0;async dial(e,t){t?.signal?.throwIfAborted(),rn("dialing %s",e);let n=this.components.peerId;if(n===void 0)throw new Error("Need a local peerid");t=t??{};let{url:i,certhashes:s,remotePeer:o}=MT(e);if(o==null)throw new Error("Need a target peerid");if(s.length===0)throw new Error("Expected multiaddr to contain certhashes");let a,c,l=()=>{};try{let u=!1,h=new WebTransport(`${i}/.well-known/libp2p-webtransport?type=noise`,{serverCertificateHashes:s.map(f=>({algorithm:"sha-256",value:f.digest}))});if(l=f=>{try{if(c!=null){if(c.timeline.close!=null)return;c.timeline.close=Date.now()}if(u)return;h.close(f)}catch(d){rn.error("error closing wt session",d)}finally{u=!0}},h.closed.then(async()=>{await c?.close()}).catch(f=>{rn.error("error on remote wt session close",f),c?.abort(f)}).finally(()=>{c==null&&l()}),a=()=>{a!=null&&t.signal?.removeEventListener("abort",a),l()},t.signal?.addEventListener("abort",a),await h.ready,!await this.authenticateWebTransport(h,n,o,s))throw new Error("Failed to authenticate webtransport");return c={close:async f=>{rn("Closing webtransport"),l()},abort:f=>{rn("aborting webtransport due to passed err",f),l({closeCode:0,reason:f.message})},remoteAddr:e,timeline:{open:Date.now()},...xg()},t?.signal?.throwIfAborted(),await t.upgrader.upgradeOutbound(c,{skipEncryption:!0,muxerFactory:this.webtransportMuxer(h,l),skipProtection:!0})}catch(u){throw rn.error("caught wt session err",u),l({closeCode:0,reason:u.message}),u}finally{a!=null&&t.signal?.removeEventListener("abort",a)}}async authenticateWebTransport(e,t,n,i){let s=await e.createBidirectionalStream(),o=s.writable.getWriter(),a=s.readable.getReader();await o.ready;let c={source:async function*(){for(;;){let h=await a.read();if(h.value!=null&&(yield h.value),h.done)break}}(),sink:async function(h){for await(let f of h)await o.write(f)}},l=nc()(),{remoteExtensions:u}=await l.secureOutbound(t,c,n);if(o.close().catch(h=>{rn.error(`Failed to close authentication stream writer: ${h.message}`)}),a.cancel().catch(h=>{rn.error(`Failed to close authentication stream reader: ${h.message}`)}),!BT(u?.webtransportCerthashes??[],i.map(h=>h.bytes)))throw new Error("Our certhashes are not a subset of the remote's reported certhashes");return!0}webtransportMuxer(e,t){let n=0,i=this.config;return{protocol:"webtransport",createStreamMuxer:s=>{typeof s=="function"&&(s={onIncomingStream:s});let o=[];return async function(){let c=e.incomingBidirectionalStreams.getReader();for(;;){let{done:l,value:u}=await c.read();if(l)break;if(o.length>=i.maxInboundStreams)u.writable.close().catch(h=>{rn.error(`Failed to close inbound stream that crossed our maxInboundStream limit: ${h.message}`)}),u.readable.cancel().catch(h=>{rn.error(`Failed to close inbound stream that crossed our maxInboundStream limit: ${h.message}`)});else{let h=await Eg(u,String(n++),"inbound",o,s?.onStreamEnd);o.push(h),s?.onIncomingStream?.(h)}}}().catch(()=>{rn.error("WebTransport failed to receive incoming stream")}),{protocol:"webtransport",streams:o,newStream:async c=>{let l=await e.createBidirectionalStream(),u=await Eg(l,String(n++),s?.direction??"outbound",o,s?.onStreamEnd);return o.push(u),u},close:async c=>{rn("Closing webtransport muxer"),t()},abort:c=>{rn("Aborting webtransport muxer with err:",c),t({closeCode:0,reason:c.message})},...xg()}}}}createListener(e){throw new Error("Webtransport servers are not supported in Node or the browser")}filter(e){return e.filter(t=>t.protoNames().includes("webtransport"))}};function UT(r={}){return e=>new vg(e,r)}var wi;(function(r){let e;(function(i){i.EOL="EOL"})(e=r.ValidityType||(r.ValidityType={}));let t;(function(i){i[i.EOL=0]="EOL"})(t||(t={})),function(i){i.codec=()=>lt(t)}(e=r.ValidityType||(r.ValidityType={}));let n;r.codec=()=>(n==null&&(n=le((i,s,o={})=>{o.lengthDelimited!==!1&&s.fork(),i.value!=null&&(s.uint32(10),s.bytes(i.value)),i.signature!=null&&(s.uint32(18),s.bytes(i.signature)),i.validityType!=null&&(s.uint32(24),r.ValidityType.codec().encode(i.validityType,s)),i.validity!=null&&(s.uint32(34),s.bytes(i.validity)),i.sequence!=null&&(s.uint32(40),s.uint64(i.sequence)),i.ttl!=null&&(s.uint32(48),s.uint64(i.ttl)),i.pubKey!=null&&(s.uint32(58),s.bytes(i.pubKey)),i.signatureV2!=null&&(s.uint32(66),s.bytes(i.signatureV2)),i.data!=null&&(s.uint32(74),s.bytes(i.data)),o.lengthDelimited!==!1&&s.ldelim()},(i,s)=>{let o={},a=s==null?i.len:i.pos+s;for(;i.pos<a;){let c=i.uint32();switch(c>>>3){case 1:o.value=i.bytes();break;case 2:o.signature=i.bytes();break;case 3:o.validityType=r.ValidityType.codec().decode(i);break;case 4:o.validity=i.bytes();break;case 5:o.sequence=i.uint64();break;case 6:o.ttl=i.uint64();break;case 7:o.pubKey=i.bytes();break;case 8:o.signatureV2=i.bytes();break;case 9:o.data=i.bytes();break;default:i.skipType(c&7);break}}return o})),n),r.encode=i=>ce(i,r.codec()),r.decode=i=>ae(i,r.codec())})(wi||(wi={}));var Su=te(Xo(),1);var FT="ERR_IPNS_EXPIRED_RECORD",Vd="ERR_UNRECOGNIZED_VALIDITY";var qs="ERR_SIGNATURE_VERIFICATION",KT="ERR_UNRECOGNIZED_FORMAT";var _g="ERR_UNDEFINED_PARAMETER",qT="ERR_INVALID_RECORD_DATA",VT="ERR_INVALID_EMBEDDED_KEY";var $T="ERR_RECORD_TOO_LARGE";var HT=C("ipns:utils"),aH=Y("/ipns/");function Ru(r){let e=new RegExp("(\\d{4})-(\\d{2})-(\\d{2})T(\\d{2}):(\\d{2}):(\\d{2})\\.(\\d+)Z"),t=String(r).trim().match(e);if(t==null)throw new Error("Invalid format");let n=parseInt(t[1],10),i=parseInt(t[2],10)-1,s=parseInt(t[3],10),o=parseInt(t[4],10),a=parseInt(t[5],10),c=parseInt(t[6],10),l=parseInt(t[7].slice(0,-6),10);return new Date(Date.UTC(n,i,s,o,a,c,l))}var WT=async(r,e)=>{if(e==null||r==null){let n=new Error("one or more of the provided parameters are not defined");throw HT.error(n),(0,Su.default)(n,_g)}let t;if(e.pubKey!=null){try{t=Pr(e.pubKey)}catch(i){throw HT.error(i),i}if(!(await cr(e.pubKey)).equals(r))throw(0,Su.default)(new Error("Embedded public key did not match PeerID"),VT)}else r.publicKey!=null&&(t=Pr(r.publicKey));if(t!=null)return t;throw(0,Su.default)(new Error("no public key is available"),_g)};var GT=r=>{let e=Y("ipns-signature:");return _e([e,r])};var YT=r=>{let e=wi.decode(r);return e.sequence!=null&&(e.sequence=BigInt(e.sequence)),e.ttl!=null&&(e.ttl=BigInt(e.ttl)),{value:e.value??new Uint8Array(0),signature:e.signature??new Uint8Array(0),validityType:e.validityType??wi.ValidityType.EOL,validity:e.validity??new Uint8Array(0),sequence:e.sequence??0n,pubKey:e.pubKey,ttl:e.ttl??void 0,signatureV2:e.signatureV2,data:e.data}};var QT=r=>ft(r.slice(aH.length));var XT=r=>{let e=hn(r);if(e.ValidityType===0)e.ValidityType=wi.ValidityType.EOL;else throw(0,Su.default)(new Error("Unknown validity type"),Vd);return Number.isInteger(e.Sequence)&&(e.Sequence=BigInt(e.Sequence)),Number.isInteger(e.TTL)&&(e.TTL=BigInt(e.TTL)),e};function jT(r,e){let t=e.map((n,i)=>({entry:wi.decode(n),index:i}));return t.sort((n,i)=>{if(n.entry.signatureV2!=null&&i.entry.signatureV2==null)return-1;if(n.entry.signatureV2==null&&i.entry.signatureV2!=null)return 1;let s=n.entry.sequence??0n,o=i.entry.sequence??0n;if(s>o)return-1;if(s<o)return 1;let a=n.entry.validity??new Uint8Array(0),c=i.entry.validity??new Uint8Array(0),l=Ru($(a)),u=Ru($(c));return l.getTime()>u.getTime()?-1:l.getTime()<u.getTime()?1:0}),t[0].index}var nn=te(Xo(),1);var Iu=C("ipns:validator"),cH=1024*10,lH=async(r,e)=>{let{value:t,validityType:n,validity:i}=e,s,o;if(e.signatureV2!=null&&e.data!=null)o=e.signatureV2,s=GT(e.data),uH(e);else throw(0,nn.default)(new Error("missing data or signatureV2"),qs);let a;try{a=await r.verify(s,o)}catch{a=!1}if(!a)throw Iu.error("record signature verification failed"),(0,nn.default)(new Error("record signature verification failed"),qs);if(i!=null&&n===wi.ValidityType.EOL){let c;try{c=Ru($(i))}catch{throw Iu.error("unrecognized validity format (not an rfc3339 format)"),(0,nn.default)(new Error("unrecognized validity format (not an rfc3339 format)"),KT)}if(c.getTime()<Date.now())throw Iu.error("record has expired"),(0,nn.default)(new Error("record has expired"),FT)}else if(n!=null)throw Iu.error("unrecognized validity type"),(0,nn.default)(new Error("unrecognized validity type"),Vd);Iu("ipns entry for %b is valid",t)},uH=r=>{if(r.data==null)throw(0,nn.default)(new Error("Record data is missing"),qT);let e=XT(r.data);if(!me(e.Value,r.value))throw(0,nn.default)(new Error('Field "value" did not match between protobuf and CBOR'),qs);if(!me(e.Validity,r.validity))throw(0,nn.default)(new Error('Field "validity" did not match between protobuf and CBOR'),qs);if(e.ValidityType!==r.validityType)throw(0,nn.default)(new Error('Field "validityType" did not match between protobuf and CBOR'),qs);if(e.Sequence!==r.sequence)throw(0,nn.default)(new Error('Field "sequence" did not match between protobuf and CBOR'),qs);if(e.TTL!==r.ttl)throw(0,nn.default)(new Error('Field "ttl" did not match between protobuf and CBOR'),qs)};async function ZT(r,e){if(e.byteLength>cH)throw(0,nn.default)(new Error("record too large"),$T);let t=QT(r),n=YT(e),i=await WT(t,n);await lH(i,n)}var Rg=te(Dr(),1);var JT="libp2p",eA="autonat",tA="1.0.0";var Ie;(function(r){let e;(function(l){l.DIAL="DIAL",l.DIAL_RESPONSE="DIAL_RESPONSE"})(e=r.MessageType||(r.MessageType={}));let t;(function(l){l[l.DIAL=0]="DIAL",l[l.DIAL_RESPONSE=1]="DIAL_RESPONSE"})(t||(t={})),function(l){l.codec=()=>lt(t)}(e=r.MessageType||(r.MessageType={}));let n;(function(l){l.OK="OK",l.E_DIAL_ERROR="E_DIAL_ERROR",l.E_DIAL_REFUSED="E_DIAL_REFUSED",l.E_BAD_REQUEST="E_BAD_REQUEST",l.E_INTERNAL_ERROR="E_INTERNAL_ERROR"})(n=r.ResponseStatus||(r.ResponseStatus={}));let i;(function(l){l[l.OK=0]="OK",l[l.E_DIAL_ERROR=100]="E_DIAL_ERROR",l[l.E_DIAL_REFUSED=101]="E_DIAL_REFUSED",l[l.E_BAD_REQUEST=200]="E_BAD_REQUEST",l[l.E_INTERNAL_ERROR=300]="E_INTERNAL_ERROR"})(i||(i={})),function(l){l.codec=()=>lt(i)}(n=r.ResponseStatus||(r.ResponseStatus={}));let s;(function(l){let u;l.codec=()=>(u==null&&(u=le((h,f,d={})=>{if(d.lengthDelimited!==!1&&f.fork(),h.id!=null&&(f.uint32(10),f.bytes(h.id)),h.addrs!=null)for(let p of h.addrs)f.uint32(18),f.bytes(p);d.lengthDelimited!==!1&&f.ldelim()},(h,f)=>{let d={addrs:[]},p=f==null?h.len:h.pos+f;for(;h.pos<p;){let m=h.uint32();switch(m>>>3){case 1:d.id=h.bytes();break;case 2:d.addrs.push(h.bytes());break;default:h.skipType(m&7);break}}return d})),u),l.encode=h=>ce(h,l.codec()),l.decode=h=>ae(h,l.codec())})(s=r.PeerInfo||(r.PeerInfo={}));let o;(function(l){let u;l.codec=()=>(u==null&&(u=le((h,f,d={})=>{d.lengthDelimited!==!1&&f.fork(),h.peer!=null&&(f.uint32(10),r.PeerInfo.codec().encode(h.peer,f)),d.lengthDelimited!==!1&&f.ldelim()},(h,f)=>{let d={},p=f==null?h.len:h.pos+f;for(;h.pos<p;){let m=h.uint32();switch(m>>>3){case 1:d.peer=r.PeerInfo.codec().decode(h,h.uint32());break;default:h.skipType(m&7);break}}return d})),u),l.encode=h=>ce(h,l.codec()),l.decode=h=>ae(h,l.codec())})(o=r.Dial||(r.Dial={}));let a;(function(l){let u;l.codec=()=>(u==null&&(u=le((h,f,d={})=>{d.lengthDelimited!==!1&&f.fork(),h.status!=null&&(f.uint32(8),r.ResponseStatus.codec().encode(h.status,f)),h.statusText!=null&&(f.uint32(18),f.string(h.statusText)),h.addr!=null&&(f.uint32(26),f.bytes(h.addr)),d.lengthDelimited!==!1&&f.ldelim()},(h,f)=>{let d={},p=f==null?h.len:h.pos+f;for(;h.pos<p;){let m=h.uint32();switch(m>>>3){case 1:d.status=r.ResponseStatus.codec().decode(h);break;case 2:d.statusText=h.string();break;case 3:d.addr=h.bytes();break;default:h.skipType(m&7);break}}return d})),u),l.encode=h=>ce(h,l.codec()),l.decode=h=>ae(h,l.codec())})(a=r.DialResponse||(r.DialResponse={}));let c;r.codec=()=>(c==null&&(c=le((l,u,h={})=>{h.lengthDelimited!==!1&&u.fork(),l.type!=null&&(u.uint32(8),r.MessageType.codec().encode(l.type,u)),l.dial!=null&&(u.uint32(18),r.Dial.codec().encode(l.dial,u)),l.dialResponse!=null&&(u.uint32(26),r.DialResponse.codec().encode(l.dialResponse,u)),h.lengthDelimited!==!1&&u.ldelim()},(l,u)=>{let h={},f=u==null?l.len:l.pos+u;for(;l.pos<f;){let d=l.uint32();switch(d>>>3){case 1:h.type=r.MessageType.codec().decode(l);break;case 2:h.dial=r.Dial.codec().decode(l,l.uint32());break;case 3:h.dialResponse=r.DialResponse.codec().decode(l,l.uint32());break;default:l.skipType(d&7);break}}return h})),c),r.encode=l=>ce(l,r.codec()),r.decode=l=>ae(l,r.codec())})(Ie||(Ie={}));var Ve=C("libp2p:autonat"),Sg=4,Ig=class{components;startupDelay;refreshInterval;protocol;timeout;maxInboundStreams;maxOutboundStreams;verifyAddressTimeout;started;constructor(e,t){this.components=e,this.started=!1,this.protocol=`/${t.protocolPrefix??JT}/${eA}/${tA}`,this.timeout=t.timeout??3e4,this.maxInboundStreams=t.maxInboundStreams??1,this.maxOutboundStreams=t.maxOutboundStreams??1,this.startupDelay=t.startupDelay??5e3,this.refreshInterval=t.refreshInterval??6e4,this._verifyExternalAddresses=this._verifyExternalAddresses.bind(this)}isStarted(){return this.started}async start(){this.started||(await this.components.registrar.handle(this.protocol,e=>{this.handleIncomingAutonatStream(e).catch(t=>{Ve.error("error handling incoming autonat stream",t)})},{maxInboundStreams:this.maxInboundStreams,maxOutboundStreams:this.maxOutboundStreams}),this.verifyAddressTimeout=setTimeout(this._verifyExternalAddresses,this.startupDelay),this.started=!0)}async stop(){await this.components.registrar.unhandle(this.protocol),clearTimeout(this.verifyAddressTimeout),this.started=!1}async handleIncomingAutonatStream(e){let t=AbortSignal.timeout(this.timeout),n=()=>{e.stream.abort(new b("handleIncomingAutonatStream timeout",z.ERR_TIMEOUT))};t.addEventListener("abort",n,{once:!0});try{(0,Rg.setMaxListeners)?.(1/0,t)}catch{}let i=this.components.addressManager.getAddresses().map(s=>s.toOptions().host);try{let s=this;await Ce(e.stream,o=>Ct(o),async function*(o){let a=await zi(o);if(a==null){Ve("no message received"),yield Ie.encode({type:Ie.MessageType.DIAL_RESPONSE,dialResponse:{status:Ie.ResponseStatus.E_BAD_REQUEST,statusText:"No message was sent"}});return}let c;try{c=Ie.decode(a)}catch(m){Ve.error("could not decode message",m),yield Ie.encode({type:Ie.MessageType.DIAL_RESPONSE,dialResponse:{status:Ie.ResponseStatus.E_BAD_REQUEST,statusText:"Could not decode message"}});return}let l=c.dial;if(l==null){Ve.error("dial was missing from message"),yield Ie.encode({type:Ie.MessageType.DIAL_RESPONSE,dialResponse:{status:Ie.ResponseStatus.E_BAD_REQUEST,statusText:"No Dial message found in message"}});return}let u,h=l.peer;if(h==null||h.id==null){Ve.error("PeerId missing from message"),yield Ie.encode({type:Ie.MessageType.DIAL_RESPONSE,dialResponse:{status:Ie.ResponseStatus.E_BAD_REQUEST,statusText:"missing peer info"}});return}try{u=ft(h.id)}catch(m){Ve.error("invalid PeerId",m),yield Ie.encode({type:Ie.MessageType.DIAL_RESPONSE,dialResponse:{status:Ie.ResponseStatus.E_BAD_REQUEST,statusText:"bad peer id"}});return}if(Ve("incoming request from %p",u),!e.connection.remotePeer.equals(u)){Ve("target peer %p did not equal sending peer %p",u,e.connection.remotePeer),yield Ie.encode({type:Ie.MessageType.DIAL_RESPONSE,dialResponse:{status:Ie.ResponseStatus.E_BAD_REQUEST,statusText:"peer id mismatch"}});return}let f=h.addrs.map(m=>oe(m)).filter(m=>{let g=m.toOptions().host===e.connection.remoteAddr.toOptions().host;return Ve.trace("request to dial %a was sent from %a is same host %s",m,e.connection.remoteAddr,g),g}).filter(m=>{let g=m.toOptions().host,y=!(kr(g)??!1);return Ve.trace("host %s was public %s",g,y),y}).filter(m=>{let g=m.toOptions().host,y=!i.includes(g);return Ve.trace("host %s was not our host %s",g,y),y}).filter(m=>{let g=!!s.components.transportManager.transportForMultiaddr(m);return Ve.trace("transport for %a is supported %s",m,g),g}).map(m=>(m.getPeerId()==null&&(m=m.encapsulate(`/p2p/${u.toString()}`)),m));if(f.length===0){Ve("no valid multiaddrs for %p in message",u),yield Ie.encode({type:Ie.MessageType.DIAL_RESPONSE,dialResponse:{status:Ie.ResponseStatus.E_DIAL_REFUSED,statusText:"no dialable addresses"}});return}Ve("dial multiaddrs %s for peer %p",f.map(m=>m.toString()).join(", "),u);let d="",p=f[0];for await(let m of f){let g;p=m;try{if(g=await s.components.connectionManager.openConnection(m,{signal:t}),!g.remoteAddr.equals(m))throw Ve.error("tried to dial %a but dialed %a",m,g.remoteAddr),new Error("Unexpected remote address");Ve("Success %p",u),yield Ie.encode({type:Ie.MessageType.DIAL_RESPONSE,dialResponse:{status:Ie.ResponseStatus.OK,addr:g.remoteAddr.decapsulateCode(ie("p2p").code).bytes}});return}catch(y){Ve("could not dial %p",u,y),d=y.message}finally{g!=null&&await g.close()}}yield Ie.encode({type:Ie.MessageType.DIAL_RESPONSE,dialResponse:{status:Ie.ResponseStatus.E_DIAL_ERROR,statusText:d,addr:p.bytes}})},o=>_t(o),e.stream)}catch(s){Ve.error("error handling incoming autonat stream",s)}finally{t.removeEventListener("abort",n)}}_verifyExternalAddresses(){this.verifyExternalAddresses().catch(e=>{Ve.error("error verifying external address",e)})}async verifyExternalAddresses(){if(clearTimeout(this.verifyAddressTimeout),!this.isStarted())return;let e=this.components.addressManager,t=e.getObservedAddrs().filter(s=>{let o=s.toOptions();return!(kr(o.host)??!1)});if(t.length===0){Ve("no public addresses found, not requesting verification"),this.verifyAddressTimeout=setTimeout(this._verifyExternalAddresses,this.refreshInterval);return}let n=AbortSignal.timeout(this.timeout);try{(0,Rg.setMaxListeners)?.(1/0,n)}catch{}let i=this;try{Ve("verify multiaddrs %s",t.map(h=>h.toString()).join(", "));let s=Ie.encode({type:Ie.MessageType.DIAL,dial:{peer:{id:this.components.peerId.toBytes(),addrs:t.map(h=>h.bytes)}}}),a=(await I0()).toBytes(),c={},l=[],u=async h=>{let f=()=>{};try{Ve("asking %p to verify multiaddr",h.id);let d=await i.components.connectionManager.openConnection(h.id,{signal:n}),p=await d.newStream(this.protocol,{signal:n});f=()=>{p.abort(new b("verifyAddress timeout",z.ERR_TIMEOUT))},n.addEventListener("abort",f,{once:!0});let m=await Ce([s],y=>_t(y),p,y=>Ct(y),async y=>zi(y));if(m==null){Ve("no response received from %p",d.remotePeer);return}let g=Ie.decode(m);if(g.type!==Ie.MessageType.DIAL_RESPONSE||g.dialResponse==null){Ve("invalid autonat response from %p",d.remotePeer);return}if(g.dialResponse.status===Ie.ResponseStatus.OK){let y=d.remoteAddr.toOptions(),w;if(y.family===4)w=y.host.split(".")[0];else if(y.family===6)w=y.host.split(":")[0];else{Ve('remote address "%s" was not IP4 or IP6?',y.host);return}if(l.includes(w)){Ve("already have response from network segment %d - %s",w,y.host);return}l.push(w)}return g.dialResponse}catch(d){Ve.error("error asking remote to verify multiaddr",d)}finally{n.removeEventListener("abort",f)}};for await(let h of Fo(An(this.components.peerRouting.getClosestPeers(a,{signal:n}),f=>async()=>u(f)),{concurrency:Sg}))try{if(h==null)continue;let f=h.addr==null?t[0]:oe(h.addr);if(Ve("autonat response for %a is %s",f,h.status),h.status===Ie.ResponseStatus.E_BAD_REQUEST||h.status===Ie.ResponseStatus.E_DIAL_REFUSED||h.addr==null&&t.length>1)continue;if(!t.some(p=>p.equals(f))){Ve("peer reported %a as %s but it was not in our observed address list",f,h.status);continue}let d=f.toString();if(c[d]==null&&(c[d]={success:0,failure:0}),h.status===Ie.ResponseStatus.OK?c[d].success++:h.status===Ie.ResponseStatus.E_DIAL_ERROR&&c[d].failure++,c[d].success===Sg){Ve("%a is externally dialable",f),e.confirmObservedAddr(f);return}if(c[d].failure===Sg){Ve("%a is not externally dialable",f),e.removeObservedAddr(f);return}}catch(f){Ve.error("could not verify external address",f)}}finally{this.verifyAddressTimeout=setTimeout(this._verifyExternalAddresses,this.refreshInterval)}}};function rA(r={}){return e=>new Ig(e,r)}var xH=te(Dr(),1);var Tg="/libp2p/relay";var nA="circuit-relay-relay";var iA=BigInt(131072),Vs="/libp2p/circuit/relay/0.2.0/hop",$d="/libp2p/circuit/relay/0.2.0/stop",gH=30*1e3,yH=30*1e3;var Zi;(function(r){let e;(function(i){i.RESERVE="RESERVE",i.CONNECT="CONNECT",i.STATUS="STATUS"})(e=r.Type||(r.Type={}));let t;(function(i){i[i.RESERVE=0]="RESERVE",i[i.CONNECT=1]="CONNECT",i[i.STATUS=2]="STATUS"})(t||(t={})),function(i){i.codec=()=>lt(t)}(e=r.Type||(r.Type={}));let n;r.codec=()=>(n==null&&(n=le((i,s,o={})=>{o.lengthDelimited!==!1&&s.fork(),i.type!=null&&(s.uint32(8),r.Type.codec().encode(i.type,s)),i.peer!=null&&(s.uint32(18),Ac.codec().encode(i.peer,s)),i.reservation!=null&&(s.uint32(26),zd.codec().encode(i.reservation,s)),i.limit!=null&&(s.uint32(34),Dc.codec().encode(i.limit,s)),i.status!=null&&(s.uint32(40),Ut.codec().encode(i.status,s)),o.lengthDelimited!==!1&&s.ldelim()},(i,s)=>{let o={},a=s==null?i.len:i.pos+s;for(;i.pos<a;){let c=i.uint32();switch(c>>>3){case 1:o.type=r.Type.codec().decode(i);break;case 2:o.peer=Ac.codec().decode(i,i.uint32());break;case 3:o.reservation=zd.codec().decode(i,i.uint32());break;case 4:o.limit=Dc.codec().decode(i,i.uint32());break;case 5:o.status=Ut.codec().decode(i);break;default:i.skipType(c&7);break}}return o})),n),r.encode=i=>ce(i,r.codec()),r.decode=i=>ae(i,r.codec())})(Zi||(Zi={}));var jn;(function(r){let e;(function(i){i.CONNECT="CONNECT",i.STATUS="STATUS"})(e=r.Type||(r.Type={}));let t;(function(i){i[i.CONNECT=0]="CONNECT",i[i.STATUS=1]="STATUS"})(t||(t={})),function(i){i.codec=()=>lt(t)}(e=r.Type||(r.Type={}));let n;r.codec=()=>(n==null&&(n=le((i,s,o={})=>{o.lengthDelimited!==!1&&s.fork(),i.type!=null&&(s.uint32(8),r.Type.codec().encode(i.type,s)),i.peer!=null&&(s.uint32(18),Ac.codec().encode(i.peer,s)),i.limit!=null&&(s.uint32(26),Dc.codec().encode(i.limit,s)),i.status!=null&&(s.uint32(32),Ut.codec().encode(i.status,s)),o.lengthDelimited!==!1&&s.ldelim()},(i,s)=>{let o={},a=s==null?i.len:i.pos+s;for(;i.pos<a;){let c=i.uint32();switch(c>>>3){case 1:o.type=r.Type.codec().decode(i);break;case 2:o.peer=Ac.codec().decode(i,i.uint32());break;case 3:o.limit=Dc.codec().decode(i,i.uint32());break;case 4:o.status=Ut.codec().decode(i);break;default:i.skipType(c&7);break}}return o})),n),r.encode=i=>ce(i,r.codec()),r.decode=i=>ae(i,r.codec())})(jn||(jn={}));var Ac;(function(r){let e;r.codec=()=>(e==null&&(e=le((t,n,i={})=>{if(i.lengthDelimited!==!1&&n.fork(),t.id!=null&&t.id.byteLength>0&&(n.uint32(10),n.bytes(t.id)),t.addrs!=null)for(let s of t.addrs)n.uint32(18),n.bytes(s);i.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let i={id:new Uint8Array(0),addrs:[]},s=n==null?t.len:t.pos+n;for(;t.pos<s;){let o=t.uint32();switch(o>>>3){case 1:i.id=t.bytes();break;case 2:i.addrs.push(t.bytes());break;default:t.skipType(o&7);break}}return i})),e),r.encode=t=>ce(t,r.codec()),r.decode=t=>ae(t,r.codec())})(Ac||(Ac={}));var zd;(function(r){let e;r.codec=()=>(e==null&&(e=le((t,n,i={})=>{if(i.lengthDelimited!==!1&&n.fork(),t.expire!=null&&t.expire!==0n&&(n.uint32(8),n.uint64(t.expire)),t.addrs!=null)for(let s of t.addrs)n.uint32(18),n.bytes(s);t.voucher!=null&&(n.uint32(26),n.bytes(t.voucher)),i.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let i={expire:0n,addrs:[]},s=n==null?t.len:t.pos+n;for(;t.pos<s;){let o=t.uint32();switch(o>>>3){case 1:i.expire=t.uint64();break;case 2:i.addrs.push(t.bytes());break;case 3:i.voucher=t.bytes();break;default:t.skipType(o&7);break}}return i})),e),r.encode=t=>ce(t,r.codec()),r.decode=t=>ae(t,r.codec())})(zd||(zd={}));var Dc;(function(r){let e;r.codec=()=>(e==null&&(e=le((t,n,i={})=>{i.lengthDelimited!==!1&&n.fork(),t.duration!=null&&(n.uint32(8),n.uint32(t.duration)),t.data!=null&&(n.uint32(16),n.uint64(t.data)),i.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let i={},s=n==null?t.len:t.pos+n;for(;t.pos<s;){let o=t.uint32();switch(o>>>3){case 1:i.duration=t.uint32();break;case 2:i.data=t.uint64();break;default:t.skipType(o&7);break}}return i})),e),r.encode=t=>ce(t,r.codec()),r.decode=t=>ae(t,r.codec())})(Dc||(Dc={}));var Ut;(function(r){r.UNUSED="UNUSED",r.OK="OK",r.RESERVATION_REFUSED="RESERVATION_REFUSED",r.RESOURCE_LIMIT_EXCEEDED="RESOURCE_LIMIT_EXCEEDED",r.PERMISSION_DENIED="PERMISSION_DENIED",r.CONNECTION_FAILED="CONNECTION_FAILED",r.NO_RESERVATION="NO_RESERVATION",r.MALFORMED_MESSAGE="MALFORMED_MESSAGE",r.UNEXPECTED_MESSAGE="UNEXPECTED_MESSAGE"})(Ut||(Ut={}));var Ag;(function(r){r[r.UNUSED=0]="UNUSED",r[r.OK=100]="OK",r[r.RESERVATION_REFUSED=200]="RESERVATION_REFUSED",r[r.RESOURCE_LIMIT_EXCEEDED=201]="RESOURCE_LIMIT_EXCEEDED",r[r.PERMISSION_DENIED=202]="PERMISSION_DENIED",r[r.CONNECTION_FAILED=203]="CONNECTION_FAILED",r[r.NO_RESERVATION=204]="NO_RESERVATION",r[r.MALFORMED_MESSAGE=400]="MALFORMED_MESSAGE",r[r.UNEXPECTED_MESSAGE=401]="UNEXPECTED_MESSAGE"})(Ag||(Ag={}));(function(r){r.codec=()=>lt(Ag)})(Ut||(Ut={}));var Dg;(function(r){let e;r.codec=()=>(e==null&&(e=le((t,n,i={})=>{i.lengthDelimited!==!1&&n.fork(),t.relay!=null&&t.relay.byteLength>0&&(n.uint32(10),n.bytes(t.relay)),t.peer!=null&&t.peer.byteLength>0&&(n.uint32(18),n.bytes(t.peer)),t.expiration!=null&&t.expiration!==0n&&(n.uint32(24),n.uint64(t.expiration)),i.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let i={relay:new Uint8Array(0),peer:new Uint8Array(0),expiration:0n},s=n==null?t.len:t.pos+n;for(;t.pos<s;){let o=t.uint32();switch(o>>>3){case 1:i.relay=t.bytes();break;case 2:i.peer=t.bytes();break;case 3:i.expiration=t.uint64();break;default:t.skipType(o&7);break}}return i})),e),r.encode=t=>ce(t,r.codec()),r.decode=t=>ae(t,r.codec())})(Dg||(Dg={}));var w7e=C("libp2p:circuit-relay:utils");async function Cg(r){let e=new TextEncoder().encode(r),t=await Ne.digest(e);return we.createV0(t)}function Pg(r){let e=r*BigInt(1e3),t=new Date().getTime();return Number(e-BigInt(t))}var EH=te(lA(),1);var k7e=C("libp2p:circuit-relay:advert-service");var c9e=C("libp2p:circuit-relay:server");var vH=C("libp2p:stream:converter");function kg(r){let{stream:e,remoteAddr:t}=r,{sink:n,source:i}=e,s=async function*(){for await(let c of i)c instanceof Uint8Array?yield c:yield*c}(),o={async sink(c){try{await n(c),a()}catch(l){l.type!=="aborted"&&vH(l)}},source:s,remoteAddr:t,timeline:{open:Date.now(),close:void 0},async close(c){a(),await e.close(c)},abort(c){a(),e.abort(c)}};function a(){o.timeline.close==null&&(o.timeline.close=Date.now())}return o}var $s=C("libp2p:circuit-relay:discover-relays"),Hd=class extends Ue{peerId;peerStore;contentRouting;registrar;started;topologyId;constructor(e){super(),this.started=!1,this.peerId=e.peerId,this.peerStore=e.peerStore,this.contentRouting=e.contentRouting,this.registrar=e.registrar}isStarted(){return this.started}async start(){this.topologyId=await this.registrar.register(Vs,{onConnect:e=>{this.safeDispatchEvent("relay:discover",{detail:e})}}),this.discover().catch(e=>{$s.error("error listening on relays",e)}),this.started=!0}stop(){this.topologyId!=null&&this.registrar.unregister(this.topologyId),this.started=!1}async discover(){$s("searching peer store for relays");let e=await this.peerStore.all({filters:[t=>t.protocols.includes(Vs)],orders:[()=>Math.random()<.5?1:-1]});for(let t of e)$s("found relay peer %p in content peer store",t.id),this.safeDispatchEvent("relay:discover",{detail:t.id});$s("found %d relay peers in peer store",e.length);try{$s("searching content routing for relays");let t=await Cg(Tg),n=0;for await(let i of this.contentRouting.findProviders(t))if(i.multiaddrs.length>0&&!i.id.equals(this.peerId)){let s=i.id;n++,await this.peerStore.merge(s,{multiaddrs:i.multiaddrs}),$s("found relay peer %p in content routing",s),this.safeDispatchEvent("relay:discover",{detail:s})}$s("found %d relay peers in content routing",n)}catch(t){$s.error("failed when finding relays on the network",t)}}};var Ng=C("libp2p:circuit-relay:transport:listener"),Lg=class extends Ue{connectionManager;relayStore;listeningAddrs;constructor(e){super(),this.connectionManager=e.connectionManager,this.relayStore=e.relayStore,this.listeningAddrs=new lr,this.relayStore.addEventListener("relay:removed",t=>{this.#e(t.detail)})}async listen(e){Ng("listen on %a",e);let t=e.getPeerId(),n;if(t!=null){let s=he(t),o=this.connectionManager.getConnectionsMap().get(s)??[];o.length>0&&(n=o[0])}if(n==null){let s=e.toString().split("/p2p-circuit").find(a=>a!==""),o=oe(s);n=await this.connectionManager.openConnection(o)}if(!this.relayStore.hasReservation(n.remotePeer)){await this.relayStore.addRelay(n.remotePeer,"configured");return}let i=this.relayStore.getReservation(n.remotePeer);if(i==null)throw new b("Did not have reservation after making reservation","ERR_NO_RESERVATION");if(this.listeningAddrs.has(n.remotePeer)){Ng("already listening on relay %p",n.remotePeer);return}this.listeningAddrs.set(n.remotePeer,i.addrs.map(s=>oe(s).encapsulate("/p2p-circuit"))),this.safeDispatchEvent("listening",{})}getAddrs(){return[...this.listeningAddrs.values()].flat()}async close(){}#e(e){let t=this.listeningAddrs.has(e);Ng("relay peer removed %p - had reservation",e,t),this.listeningAddrs.delete(e),t&&this.safeDispatchEvent("close",{})}};function hA(r){return new Lg(r)}var Ir=C("libp2p:circuit-relay:transport:reservation-store"),SH=60*1e3*10,RH=60*1e3*5,IH=30*1e3,Wd=class extends Ue{peerId;connectionManager;transportManager;peerStore;events;reserveQueue;reservations;maxDiscoveredRelays;maxReservationQueueLength;reservationCompletionTimeout;started;constructor(e,t){super(),this.peerId=e.peerId,this.connectionManager=e.connectionManager,this.transportManager=e.transportManager,this.peerStore=e.peerStore,this.events=e.events,this.reservations=new lr,this.maxDiscoveredRelays=t?.discoverRelays??0,this.maxReservationQueueLength=t?.maxReservationQueueLength??100,this.reservationCompletionTimeout=t?.reservationCompletionTimeout??1e4,this.started=!1,this.reserveQueue=new Ha({concurrency:t?.reservationConcurrency??1}),this.events.addEventListener("peer:disconnect",n=>{this.#t(n.detail)})}isStarted(){return this.started}async start(){this.started=!0}async stop(){this.reserveQueue.clear(),this.reservations.forEach(({timeout:e})=>{clearTimeout(e)}),this.reservations.clear(),this.started=!1}async addRelay(e,t){if(this.peerId.equals(e)){Ir("not trying to use self as relay");return}if(this.reserveQueue.size>this.maxReservationQueueLength){Ir("not adding relay as the queue is full");return}if(this.reserveQueue.hasJob(e)){Ir("relay peer is already in the reservation queue");return}Ir("add relay %p",e),await this.reserveQueue.add(async()=>{try{let n=this.reservations.get(e);if(n!=null){if(Pg(n.reservation.expire)>SH){Ir("already have reservation on relay peer %p and it expires in more than 10 minutes",e);return}clearTimeout(n.timeout),this.reservations.delete(e)}if(t==="discovered"&&[...this.reservations.values()].reduce((u,h)=>(h.type==="discovered"&&u++,u),0)>=this.maxDiscoveredRelays){Ir("already have enough discovered relays");return}let i=AbortSignal.timeout(this.reservationCompletionTimeout),s=await this.connectionManager.openConnection(e,{signal:i});if(s.remoteAddr.protoNames().includes("p2p-circuit")){Ir("not creating reservation over relayed connection");return}let o=await this.#e(s,{signal:i});Ir("created reservation on relay peer %p",e);let a=Pg(o.expire),c=Math.min(Math.max(a-RH,IH),Math.pow(2,31)-1),l=setTimeout(()=>{this.addRelay(e,t).catch(u=>{Ir.error("could not refresh reservation to relay %p",e,u)})},c);this.reservations.set(e,{timeout:l,reservation:o,type:t}),await this.peerStore.merge(e,{tags:{[nA]:{value:1,ttl:a}}}),await this.transportManager.listen([oe(`/p2p/${e.toString()}/p2p-circuit`)])}catch(n){Ir.error("could not reserve slot on %p",e,n);let i=this.reservations.get(e);i!=null&&clearTimeout(i.timeout),this.reservations.delete(e)}},{peerId:e})}hasReservation(e){return this.reservations.has(e)}getReservation(e){return this.reservations.get(e)?.reservation}async#e(e,t){t.signal?.throwIfAborted(),Ir("requesting reservation from %p",e.remotePeer);let n=await e.newStream(Vs,t),s=rr(n).pb(Zi);await s.write({type:Zi.Type.RESERVE},t);let o;try{o=await s.read(t)}catch(c){throw Ir.error("error parsing reserve message response from %p because",e.remotePeer,c),c}finally{await n.close()}if(o.status===Ut.OK&&o.reservation!=null)return o.reservation;let a=`reservation failed with status ${o.status??"undefined"}`;throw Ir.error(a),new Error(a)}#t(e){let t=this.reservations.get(e);t!=null&&(Ir("connection to relay %p closed, removing reservation from local store",e),clearTimeout(t.timeout),this.reservations.delete(e),this.safeDispatchEvent("relay:removed",{detail:e}),this.reservations.size<this.maxDiscoveredRelays&&(Ir("not enough relays %d/%d",this.reservations.size,this.maxDiscoveredRelays),this.safeDispatchEvent("relay:not-enough-relays",{})))}};var dr=C("libp2p:circuit-relay:transport"),TH=r=>{if(r.peer==null)return!1;try{r.peer.addrs.forEach(oe)}catch{return!1}return!0},Og={maxInboundStopStreams:Ts,maxOutboundStopStreams:Ts,stopTimeout:3e4},Bg=class{discovery;registrar;peerStore;connectionManager;peerId;upgrader;addressManager;connectionGater;reservationStore;maxInboundStopStreams;maxOutboundStopStreams;stopTimeout;started;constructor(e,t){this.registrar=e.registrar,this.peerStore=e.peerStore,this.connectionManager=e.connectionManager,this.peerId=e.peerId,this.upgrader=e.upgrader,this.addressManager=e.addressManager,this.connectionGater=e.connectionGater,this.maxInboundStopStreams=t.maxInboundStopStreams??Og.maxInboundStopStreams,this.maxOutboundStopStreams=t.maxOutboundStopStreams??Og.maxOutboundStopStreams,this.stopTimeout=t.stopTimeout??Og.stopTimeout,t.discoverRelays!=null&&t.discoverRelays>0&&(this.discovery=new Hd(e),this.discovery.addEventListener("relay:discover",n=>{this.reservationStore.addRelay(n.detail,"discovered").catch(i=>{dr.error("could not add discovered relay %p",n.detail,i)})})),this.reservationStore=new Wd(e,t),this.reservationStore.addEventListener("relay:not-enough-relays",()=>{this.discovery?.discover().catch(n=>{dr.error("could not discover relays",n)})}),this.started=!1}isStarted(){return this.started}async start(){await this.reservationStore.start(),await this.discovery?.start(),await this.registrar.handle($d,e=>{this.onStop(e).catch(t=>{dr.error("error while handling STOP protocol",t),e.stream.abort(t)})},{maxInboundStreams:this.maxInboundStopStreams,maxOutboundStreams:this.maxOutboundStopStreams,runOnTransientConnection:!0}),this.started=!0}async stop(){this.discovery?.stop(),await this.reservationStore.stop(),await this.registrar.unhandle($d),this.started=!1}[di]=!0;[Symbol.toStringTag]="libp2p/circuit-relay-v2";async dial(e,t={}){if(e.protoCodes().filter(p=>p===290).length!==1){let p="Invalid circuit relay address";throw dr.error(p,e),new b(p,z.ERR_RELAYED_DIAL)}let n=e.toString().split("/p2p-circuit"),i=oe(n[0]),s=oe(n[n.length-1]),o=i.getPeerId(),a=s.getPeerId();if(o==null||a==null){let p=`Circuit relay dial to ${e.toString()} failed as address did not have peer ids`;throw dr.error(p),new b(p,z.ERR_RELAYED_DIAL)}let c=he(o),l=he(a),u=!1,f=this.connectionManager.getConnections(c)[0];f==null&&(await this.peerStore.merge(c,{multiaddrs:[i]}),f=await this.connectionManager.openConnection(c,t),u=!0);let d;try{return d=await f.newStream([Vs]),await this.connectV2({stream:d,connection:f,destinationPeer:l,destinationAddr:s,relayAddr:i,ma:e,disconnectOnFailure:u})}catch(p){throw dr.error(`Circuit relay dial to destination ${l.toString()} via relay ${c.toString()} failed`,p),d?.abort(p),u&&await f.close(),p}}async connectV2({stream:e,connection:t,destinationPeer:n,destinationAddr:i,relayAddr:s,ma:o,disconnectOnFailure:a}){try{let c=rr(e),l=c.pb(Zi);await l.write({type:Zi.Type.CONNECT,peer:{id:n.toBytes(),addrs:[oe(i).bytes]}});let u=await l.read();if(u.status!==Ut.OK)throw new b(`failed to connect via relay with status ${u?.status?.toString()??"undefined"}`,z.ERR_HOP_REQUEST_FAILED);let h=kg({stream:c.unwrap(),remoteAddr:o,localAddr:s.encapsulate(`/p2p-circuit/p2p/${this.peerId.toString()}`)});return dr("new outbound transient connection %a",h.remoteAddr),await this.upgrader.upgradeOutbound(h,{transient:!0})}catch(c){throw dr.error(`Circuit relay dial to destination ${n.toString()} via relay ${t.remotePeer.toString()} failed`,c),a&&await t.close(),c}}createListener(e){return hA({connectionManager:this.connectionManager,relayStore:this.reservationStore})}filter(e){return e=Array.isArray(e)?e:[e],e.filter(t=>Yn.matches(t))}async onStop({connection:e,stream:t}){let n=AbortSignal.timeout(this.stopTimeout),i=rr(t).pb(jn),s=await i.read({signal:n});if(dr("new circuit relay v2 stop stream from %p with type %s",e.remotePeer,s.type),s?.type===void 0){dr.error("type was missing from circuit v2 stop protocol request from %s",e.remotePeer),await i.write({type:jn.Type.STATUS,status:Ut.MALFORMED_MESSAGE},{signal:n}),await t.close();return}if(s.type!==jn.Type.CONNECT){dr.error("invalid stop connect request via peer %p",e.remotePeer),await i.write({type:jn.Type.STATUS,status:Ut.UNEXPECTED_MESSAGE},{signal:n}),await t.close();return}if(!TH(s)){dr.error("invalid stop connect request via peer %p",e.remotePeer),await i.write({type:jn.Type.STATUS,status:Ut.MALFORMED_MESSAGE},{signal:n}),await t.close();return}let o=ft(s.peer.id);if(await this.connectionGater.denyInboundRelayedConnection?.(e.remotePeer,o)===!0){dr.error("connection gater denied inbound relayed connection from %p",e.remotePeer),await i.write({type:jn.Type.STATUS,status:Ut.PERMISSION_DENIED},{signal:n}),await t.close();return}dr.trace("sending success response to %p",e.remotePeer),await i.write({type:jn.Type.STATUS,status:Ut.OK},{signal:n});let a=e.remoteAddr.encapsulate(`/p2p-circuit/p2p/${o.toString()}`),c=this.addressManager.getAddresses()[0],l=kg({stream:i.unwrap().unwrap(),remoteAddr:a,localAddr:c});dr("new inbound transient connection %a",l.remoteAddr),await this.upgrader.upgradeInbound(l,{transient:!0}),dr("%s connection %a upgraded","inbound",l.remoteAddr)}};function Mg(r={}){return e=>new Bg(e,r)}var fA=()=>{let r=new Error("Delay aborted");return r.name="AbortError",r},AH=new WeakMap;function DH({clearTimeout:r,setTimeout:e}={}){return(t,{value:n,signal:i}={})=>{if(i?.aborted)return Promise.reject(fA());let s,o,a,c=r??clearTimeout,l=()=>{c(s),a(fA())},u=()=>{i&&i.removeEventListener("abort",l)},h=new Promise((f,d)=>{o=()=>{u(),f(n)},a=d,s=(e??setTimeout)(o,t)});return i&&i.addEventListener("abort",l,{once:!0}),AH.set(h,()=>{c(s),s=null,o()}),h}}var CH=DH(),dA=CH;var Zn;(function(r){let e;(function(i){i.UNUSED="UNUSED",i.CONNECT="CONNECT",i.SYNC="SYNC"})(e=r.Type||(r.Type={}));let t;(function(i){i[i.UNUSED=0]="UNUSED",i[i.CONNECT=100]="CONNECT",i[i.SYNC=300]="SYNC"})(t||(t={})),function(i){i.codec=()=>lt(t)}(e=r.Type||(r.Type={}));let n;r.codec=()=>(n==null&&(n=le((i,s,o={})=>{if(o.lengthDelimited!==!1&&s.fork(),i.type!=null&&(s.uint32(8),r.Type.codec().encode(i.type,s)),i.observedAddresses!=null)for(let a of i.observedAddresses)s.uint32(18),s.bytes(a);o.lengthDelimited!==!1&&s.ldelim()},(i,s)=>{let o={observedAddresses:[]},a=s==null?i.len:i.pos+s;for(;i.pos<a;){let c=i.uint32();switch(c>>>3){case 1:o.type=r.Type.codec().decode(i);break;case 2:o.observedAddresses.push(i.bytes());break;default:i.skipType(c&7);break}}return o})),n),r.encode=i=>ce(i,r.codec()),r.decode=i=>ae(i,r.codec())})(Zn||(Zn={}));var pt=C("libp2p:dcutr"),pA=1024*4,mA=100,Gd={timeout:5e3,retries:3,maxInboundStreams:1,maxOutboundStreams:1},Yd=class{started;timeout;retries;maxInboundStreams;maxOutboundStreams;peerStore;registrar;connectionManager;addressManager;transportManager;topologyId;constructor(e,t){this.started=!1,this.peerStore=e.peerStore,this.registrar=e.registrar,this.addressManager=e.addressManager,this.connectionManager=e.connectionManager,this.transportManager=e.transportManager,this.timeout=t.timeout??Gd.timeout,this.retries=t.retries??Gd.retries,this.maxInboundStreams=t.maxInboundStreams??Gd.maxInboundStreams,this.maxOutboundStreams=t.maxOutboundStreams??Gd.maxOutboundStreams}isStarted(){return this.started}async start(){this.started||(this.topologyId=await this.registrar.register(Tu,{onConnect:(e,t)=>{t.transient&&t.direction==="inbound"&&this.upgradeInbound(t).catch(n=>{pt.error("error during outgoing DCUtR attempt",n)})}}),await this.registrar.handle(Tu,e=>{this.handleIncomingUpgrade(e.stream,e.connection).catch(t=>{pt.error("error during incoming DCUtR attempt",t),e.stream.abort(t)})},{maxInboundStreams:this.maxInboundStreams,maxOutboundStreams:this.maxOutboundStreams,runOnTransientConnection:!0}),this.started=!0)}async stop(){await this.registrar.unhandle(Tu),this.topologyId!=null&&this.registrar.unregister(this.topologyId),this.started=!1}async upgradeInbound(e){if(await this.attemptUnilateralConnectionUpgrade(e))return;let t;for(let n=0;n<this.retries;n++){let i={signal:AbortSignal.timeout(this.timeout)};try{t=await e.newStream([Tu],{signal:i.signal,runOnTransientConnection:!0});let s=rr(t,{maxDataLength:pA}).pb(Zn);pt("B sending connect to %p",e.remotePeer);let o=Date.now();await s.write({type:Zn.Type.CONNECT,observedAddresses:this.addressManager.getAddresses().map(h=>h.bytes)},i),pt("B receiving connect from %p",e.remotePeer);let a=await s.read(i);if(a.type!==Zn.Type.CONNECT)throw pt("A sent wrong message type"),new b("DCUtR message type was incorrect",z.ERR_INVALID_MESSAGE);let c=this.getDialableMultiaddrs(a.observedAddresses);if(c.length===0)throw pt("A did not have any dialable multiaddrs"),new b("DCUtR connect message had no multiaddrs",z.ERR_INVALID_MESSAGE);let l=Date.now()-o;pt("A sending sync, rtt %dms",l),await s.write({type:Zn.Type.SYNC,observedAddresses:[]},i),pt("A waiting for half RTT"),await dA(l/2),pt("B dialing",c);let u=await this.connectionManager.openConnection(c,{signal:i.signal,priority:mA});pt("DCUtR to %p succeeded to address %a, closing relayed connection",e.remotePeer,u.remoteAddr),await e.close(i);break}catch(s){if(pt.error("error while attempting DCUtR on attempt %d of %d",n+1,this.retries,s),t?.abort(s),n===this.retries)throw s}finally{t!=null&&await t.close(i)}}}async attemptUnilateralConnectionUpgrade(e){let n=(await this.peerStore.get(e.remotePeer)).addresses.map(i=>{let s=i.multiaddr;return s.getPeerId()==null?s.encapsulate(`/p2p/${e.remotePeer}`):s}).filter(i=>this.isPublicAndDialable(i));if(n.length>0){let i=AbortSignal.timeout(this.timeout);try{pt("attempting unilateral connection upgrade to %a",n);let s=await this.connectionManager.openConnection(n,{signal:i,force:!0});if(s.transient)throw new Error("Could not open a new, non-transient, connection");return pt("unilateral connection upgrade to %p succeeded via %a, closing relayed connection",e.remotePeer,s.remoteAddr),await e.close(),!0}catch(s){pt.error("unilateral connection upgrade to %p on addresses %a failed",e.remotePeer,n,s)}}else pt("peer %p has no public addresses, not attempting unilateral connection upgrade",e.remotePeer);return!1}async handleIncomingUpgrade(e,t){let n={signal:AbortSignal.timeout(this.timeout)};try{let i=rr(e,{maxDataLength:pA}).pb(Zn);pt("A receiving connect");let s=await i.read(n);if(s.type!==Zn.Type.CONNECT)throw pt("B sent wrong message type"),new b("DCUtR message type was incorrect",z.ERR_INVALID_MESSAGE);if(s.observedAddresses.length===0)throw pt("B sent no multiaddrs"),new b("DCUtR connect message had no multiaddrs",z.ERR_INVALID_MESSAGE);let o=this.getDialableMultiaddrs(s.observedAddresses);if(o.length===0)throw pt("B had no dialable multiaddrs"),new b("DCUtR connect message had no dialable multiaddrs",z.ERR_INVALID_MESSAGE);if(pt("A sending connect"),await i.write({type:Zn.Type.CONNECT,observedAddresses:this.addressManager.getAddresses().map(l=>l.bytes)}),pt("A receiving sync"),(await i.read(n)).type!==Zn.Type.SYNC)throw new b("DCUtR message type was incorrect",z.ERR_INVALID_MESSAGE);pt("A dialing",o);let c=await this.connectionManager.openConnection(o,{signal:n.signal,priority:mA,force:!0});pt("DCUtR to %p succeeded via %a, closing relayed connection",t.remotePeer,c.remoteAddr),await t.close(n)}catch(i){pt.error("incoming DCUtR from %p failed",t.remotePeer,i),e.abort(i)}finally{await e.close(n)}}getDialableMultiaddrs(e){let t=[];for(let n of e)if(!(n==null||n.length===0))try{let i=oe(n);if(!this.isPublicAndDialable(i))continue;t.push(i)}catch{}return t}isPublicAndDialable(e){if(Ml.matches(e))return!1;if(eE.matches(e))return!0;if(!iE.matches(e)||this.transportManager.transportForMultiaddr(e)==null)return!1;let n=e.toOptions();return kr(n.host)===!1}};var Tu="/libp2p/dcutr";function gA(r={}){return e=>new Yd(e,r)}var yA="0.46.10";var Ug=`js-libp2p/${yA}`;var bA="0.1.0",wA="id",EA="id/push",xA="1.0.0",vA="1.0.0";var Kg=te(Dr(),1);var zs;(function(r){let e;r.codec=()=>(e==null&&(e=le((t,n,i={})=>{if(i.lengthDelimited!==!1&&n.fork(),t.protocolVersion!=null&&(n.uint32(42),n.string(t.protocolVersion)),t.agentVersion!=null&&(n.uint32(50),n.string(t.agentVersion)),t.publicKey!=null&&(n.uint32(10),n.bytes(t.publicKey)),t.listenAddrs!=null)for(let s of t.listenAddrs)n.uint32(18),n.bytes(s);if(t.observedAddr!=null&&(n.uint32(34),n.bytes(t.observedAddr)),t.protocols!=null)for(let s of t.protocols)n.uint32(26),n.string(s);t.signedPeerRecord!=null&&(n.uint32(66),n.bytes(t.signedPeerRecord)),i.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let i={listenAddrs:[],protocols:[]},s=n==null?t.len:t.pos+n;for(;t.pos<s;){let o=t.uint32();switch(o>>>3){case 5:i.protocolVersion=t.string();break;case 6:i.agentVersion=t.string();break;case 1:i.publicKey=t.bytes();break;case 2:i.listenAddrs.push(t.bytes());break;case 4:i.observedAddr=t.bytes();break;case 3:i.protocols.push(t.string());break;case 8:i.signedPeerRecord=t.bytes();break;default:t.skipType(o&7);break}}return i})),e),r.encode=t=>ce(t,r.codec()),r.decode=t=>ae(t,r.codec())})(zs||(zs={}));var pr=C("libp2p:identify"),Fg=1024*8,sn={protocolPrefix:"ipfs",agentVersion:Ug,timeout:6e4,maxInboundStreams:1,maxOutboundStreams:1,maxPushIncomingStreams:1,maxPushOutgoingStreams:1,maxObservedAddresses:10,maxIdentifyMessageSize:8192,runOnConnectionOpen:!0,runOnTransientConnection:!0},Qd=class{identifyProtocolStr;identifyPushProtocolStr;host;started;timeout;peerId;peerStore;registrar;connectionManager;addressManager;maxInboundStreams;maxOutboundStreams;maxPushIncomingStreams;maxPushOutgoingStreams;maxIdentifyMessageSize;maxObservedAddresses;events;runOnTransientConnection;constructor(e,t){this.started=!1,this.peerId=e.peerId,this.peerStore=e.peerStore,this.registrar=e.registrar,this.addressManager=e.addressManager,this.connectionManager=e.connectionManager,this.events=e.events,this.identifyProtocolStr=`/${t.protocolPrefix??sn.protocolPrefix}/${wA}/${xA}`,this.identifyPushProtocolStr=`/${t.protocolPrefix??sn.protocolPrefix}/${EA}/${vA}`,this.timeout=t.timeout??sn.timeout,this.maxInboundStreams=t.maxInboundStreams??sn.maxInboundStreams,this.maxOutboundStreams=t.maxOutboundStreams??sn.maxOutboundStreams,this.maxPushIncomingStreams=t.maxPushIncomingStreams??sn.maxPushIncomingStreams,this.maxPushOutgoingStreams=t.maxPushOutgoingStreams??sn.maxPushOutgoingStreams,this.maxIdentifyMessageSize=t.maxIdentifyMessageSize??sn.maxIdentifyMessageSize,this.maxObservedAddresses=t.maxObservedAddresses??sn.maxObservedAddresses,this.runOnTransientConnection=t.runOnTransientConnection??sn.runOnTransientConnection,this.host={protocolVersion:`${t.protocolPrefix??sn.protocolPrefix}/${bA}`,agentVersion:t.agentVersion??sn.agentVersion},(t.runOnConnectionOpen??sn.runOnConnectionOpen)&&e.events.addEventListener("connection:open",n=>{let i=n.detail;this.identify(i).catch(s=>{pr.error("error during identify trigged by connection:open",s)})}),e.events.addEventListener("self:peer:update",n=>{this.push().catch(i=>{pr.error(i)})}),this.host.agentVersion===Ug&&(TT||RT?this.host.agentVersion+=` UserAgent=${globalThis.process.version}`:(Kd||qd||IT||AT)&&(this.host.agentVersion+=` UserAgent=${globalThis.navigator.userAgent}`))}isStarted(){return this.started}async start(){this.started||(await this.peerStore.merge(this.peerId,{metadata:{AgentVersion:Y(this.host.agentVersion),ProtocolVersion:Y(this.host.protocolVersion)}}),await this.registrar.handle(this.identifyProtocolStr,e=>{this._handleIdentify(e).catch(t=>{pr.error(t)})},{maxInboundStreams:this.maxInboundStreams,maxOutboundStreams:this.maxOutboundStreams,runOnTransientConnection:this.runOnTransientConnection}),await this.registrar.handle(this.identifyPushProtocolStr,e=>{this._handlePush(e).catch(t=>{pr.error(t)})},{maxInboundStreams:this.maxPushIncomingStreams,maxOutboundStreams:this.maxPushOutgoingStreams,runOnTransientConnection:this.runOnTransientConnection}),this.started=!0)}async stop(){await this.registrar.unhandle(this.identifyProtocolStr),await this.registrar.unhandle(this.identifyPushProtocolStr),this.started=!1}async pushToConnections(e){let t=this.addressManager.getAddresses().map(u=>u.decapsulateCode(ie("p2p").code)),n=new Gr({peerId:this.peerId,multiaddrs:t}),i=await bn.seal(n,this.peerId),s=this.registrar.getProtocols(),o=await this.peerStore.get(this.peerId),a=$(o.metadata.get("AgentVersion")??Y(this.host.agentVersion)),c=$(o.metadata.get("ProtocolVersion")??Y(this.host.protocolVersion)),l=e.map(async u=>{let h,f=AbortSignal.timeout(this.timeout);try{(0,Kg.setMaxListeners)?.(1/0,f)}catch{}try{h=await u.newStream([this.identifyPushProtocolStr],{signal:f,runOnTransientConnection:this.runOnTransientConnection}),await rr(h,{maxDataLength:this.maxIdentifyMessageSize??Fg}).pb(zs).write({listenAddrs:t.map(p=>p.bytes),signedPeerRecord:i.marshal(),protocols:s,agentVersion:a,protocolVersion:c},{signal:f}),await h.close({signal:f})}catch(d){pr.error("could not push identify update to peer",d),h?.abort(d)}});await Promise.all(l)}async push(){if(!this.isStarted())return;let e=[];await Promise.all(this.connectionManager.getConnections().map(async t=>{try{if(!(await this.peerStore.get(t.remotePeer)).protocols.includes(this.identifyPushProtocolStr))return;e.push(t)}catch(n){if(n.code!==z.ERR_NOT_FOUND)throw n}})),await this.pushToConnections(e)}async _identify(e,t={}){let n;t.signal=t.signal??AbortSignal.timeout(this.timeout);try{n=await e.newStream([this.identifyProtocolStr],{...t,runOnTransientConnection:this.runOnTransientConnection});let s=await rr(n,{maxDataLength:this.maxIdentifyMessageSize??Fg}).pb(zs).read(t);return await n.close(t),s}catch(i){throw pr.error("error while reading identify message",i),n?.abort(i),i}}async identify(e,t={}){let n=await this._identify(e,t),{publicKey:i,protocols:s,observedAddr:o}=n;if(i==null)throw new b("public key was missing from identify message",z.ERR_MISSING_PUBLIC_KEY);let a=await cr(i);if(!e.remotePeer.equals(a))throw new b("identified peer does not match the expected peer",z.ERR_INVALID_PEER);if(this.peerId.equals(a))throw new b("identified peer is our own peer id?",z.ERR_INVALID_PEER);let c=PH(o);pr("identify completed for peer %p and protocols %o",a,s),pr("our observed address is %a",c),c!=null&&this.addressManager.getObservedAddrs().length<(this.maxObservedAddresses??1/0)&&(pr("storing our observed address %a",c),this.addressManager.addObservedAddr(c));let l=await this.#e(e.remotePeer,n),u={peerId:a,protocolVersion:n.protocolVersion,agentVersion:n.agentVersion,publicKey:n.publicKey,listenAddrs:n.listenAddrs.map(h=>oe(h)),observedAddr:n.observedAddr==null?void 0:oe(n.observedAddr),protocols:n.protocols,signedPeerRecord:l};return this.events.safeDispatchEvent("peer:identify",{detail:u}),u}async _handleIdentify(e){let{connection:t,stream:n}=e,i=AbortSignal.timeout(this.timeout);try{(0,Kg.setMaxListeners)?.(1/0,i)}catch{}try{let s=this.peerId.publicKey??new Uint8Array(0),o=await this.peerStore.get(this.peerId),a=this.addressManager.getAddresses().map(u=>u.decapsulateCode(ie("p2p").code)),c=o.peerRecordEnvelope;if(a.length>0&&c==null){let u=new Gr({peerId:this.peerId,multiaddrs:a});c=(await bn.seal(u,this.peerId)).marshal().subarray()}await rr(n).pb(zs).write({protocolVersion:this.host.protocolVersion,agentVersion:this.host.agentVersion,publicKey:s,listenAddrs:a.map(u=>u.bytes),signedPeerRecord:c,observedAddr:t.remoteAddr.bytes,protocols:o.protocols},{signal:i}),await n.close({signal:i})}catch(s){pr.error("could not respond to identify request",s),n.abort(s)}}async _handlePush(e){let{connection:t,stream:n}=e;try{if(this.peerId.equals(t.remotePeer))throw new Error("received push from ourselves?");let i={signal:AbortSignal.timeout(this.timeout)},o=await rr(n,{maxDataLength:this.maxIdentifyMessageSize??Fg}).pb(zs).read(i);await n.close(i),await this.#e(t.remotePeer,o)}catch(i){pr.error("received invalid message",i),n.abort(i);return}pr("handled push from %p",t.remotePeer)}async#e(e,t){if(pr("received identify from %p",e),t==null)throw new Error("Message was null or undefined");let n={addresses:t.listenAddrs.map(s=>({isCertified:!1,multiaddr:oe(s)})),protocols:t.protocols,metadata:new Map,peerRecordEnvelope:t.signedPeerRecord},i;if(t.signedPeerRecord!=null){pr("received signedPeerRecord in push from %p",e);let s=t.signedPeerRecord,o=await bn.openAndCertify(s,Gr.DOMAIN),a=Gr.createFromProtobuf(o.payload);if(!a.peerId.equals(o.peerId))throw new Error("signing key does not match PeerId in the PeerRecord");if(!e.equals(a.peerId))throw new Error("signing key does not match remote PeerId");let c;try{c=await this.peerStore.get(a.peerId)}catch(l){if(l.code!=="ERR_NOT_FOUND")throw l}if(c!=null&&(n.metadata=c.metadata,c.peerRecordEnvelope!=null)){let l=await bn.createFromProtobuf(c.peerRecordEnvelope),u=Gr.createFromProtobuf(l.payload);u.seqNumber>=a.seqNumber&&(pr("sequence number was lower or equal to existing sequence number - stored: %d received: %d",u.seqNumber,a.seqNumber),a=u,s=c.peerRecordEnvelope)}n.peerRecordEnvelope=s,n.addresses=a.multiaddrs.map(l=>({isCertified:!0,multiaddr:l})),i={seq:a.seqNumber,addresses:a.multiaddrs}}else pr("%p did not send a signed peer record",e);return t.agentVersion!=null&&n.metadata.set("AgentVersion",Y(t.agentVersion)),t.protocolVersion!=null&&n.metadata.set("ProtocolVersion",Y(t.protocolVersion)),await this.peerStore.patch(e,n),i}};function PH(r){if(r!=null&&r.length>0)try{return oe(r)}catch{}}function _A(r={}){return e=>new Qd(e,r)}var SA={list:["/dnsaddr/bootstrap.libp2p.io/p2p/QmNnooDu7bfjPFoTZYxMNLWUQJyrVwtbZg5gBMjTezGAJN","/dnsaddr/bootstrap.libp2p.io/p2p/QmQCU2EcMqAqQPR2i9bChDtGNJchTbq5TbXJJ16u19uLTa","/dnsaddr/bootstrap.libp2p.io/p2p/QmbLHAnMoJPWSCR5Zhtx6BHJX9KiKNN6tpvbUcqanj75Nb","/dnsaddr/bootstrap.libp2p.io/p2p/QmcZf59bWwK5XFi76CZX8cbJ4BhTzzA3gU1ZjYZcYW3dwt","/ip4/104.131.131.82/tcp/4001/p2p/QmaCpDMGvV2BGHeYERUEnRQAwe3N8SzbUtfsmvsqQLuvuJ"]};function RA(){return{addresses:{listen:["/webrtc"]},transports:[ZI(),jI(),UT(),OT(),Mg({discoverRelays:1})],connectionEncryption:[nc()],streamMuxers:[r_(),iR()],peerDiscovery:[p_(SA)],contentRouters:[x_("https://cid.contact")],services:{identify:_A(),autoNAT:rA(),pubsub:pv(),dcutr:gA(),dht:J_({clientMode:!0,validators:{ipns:ZT},selectors:{ipns:jT}})}}}async function IA(r,e){let t=RA();return e=e??{},Ax({datastore:r,...t,...e,start:!1})}var qg="2.0.1-4b4bf37",Xd="helia";var kH=C("helia");async function NH(r={}){let e=r.datastore??new Qs,t=r.blockstore??new Oc,n;LH(r.libp2p)?n=r.libp2p:n=await IA(e,r.libp2p);let i=new Bh({...r,datastore:e,blockstore:t,libp2p:n});return r.start!==!1&&await i.start(),i.libp2p.isStarted()?await TA(i):i.libp2p.addEventListener("start",()=>{TA(i).catch(s=>{kH.error("could not add Helia to agent version",s)})}),i}function LH(r){return r==null?!1:["dial","dialProtocol","hangUp","handle","unhandle","getMultiaddrs","getProtocols"].every(t=>typeof r[t]=="function")}async function TA(r){let t=(await r.libp2p.peerStore.get(r.libp2p.peerId)).metadata.get("AgentVersion");if(t==null)return;let n=new TextDecoder().decode(t);n.match(/js-libp2p\/\d+\.\d+\.\d+\sUserAgent=/)!=null&&(n.includes(Xd)?n=`${Xd}/${qg} ${n.split(" ").slice(1).join(" ")}`:n=`${Xd}/${qg} ${n}`,await r.libp2p.peerStore.merge(r.libp2p.peerId,{metadata:{AgentVersion:new TextEncoder().encode(n)}}))}return Du(OH);})();
107
107
  /*! Bundled license information:
108
108
 
109
109
  @noble/hashes/esm/utils.js:
@@ -1,3 +1,3 @@
1
- export declare const version = "2.0.1-230b15b";
1
+ export declare const version = "2.0.1-4b4bf37";
2
2
  export declare const name = "helia";
3
3
  //# sourceMappingURL=version.d.ts.map
@@ -1,3 +1,3 @@
1
- export const version = '2.0.1-230b15b';
1
+ export const version = '2.0.1-4b4bf37';
2
2
  export const name = 'helia';
3
3
  //# sourceMappingURL=version.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "helia",
3
- "version": "2.0.1-230b15b",
3
+ "version": "2.0.1-4b4bf37",
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/master/packages/helia#readme",
@@ -52,7 +52,7 @@
52
52
  "@chainsafe/libp2p-gossipsub": "^10.0.0",
53
53
  "@chainsafe/libp2p-noise": "^13.0.0",
54
54
  "@chainsafe/libp2p-yamux": "^5.0.0",
55
- "@helia/interface": "2.0.0-230b15b",
55
+ "@helia/interface": "2.0.0-4b4bf37",
56
56
  "@ipld/dag-cbor": "^9.0.0",
57
57
  "@ipld/dag-json": "^10.0.1",
58
58
  "@ipld/dag-pb": "^4.0.3",
package/src/version.ts CHANGED
@@ -1,2 +1,2 @@
1
- export const version = '2.0.1-230b15b'
1
+ export const version = '2.0.1-4b4bf37'
2
2
  export const name = 'helia'