@helia/libp2p 1.0.4-da4aa40a → 1.0.4-f028ccf8
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 +2 -2
- package/dist/index.min.js.map +2 -2
- package/dist/src/index.js +3 -3
- package/dist/src/index.js.map +1 -1
- package/dist/src/routing.js +1 -1
- package/dist/src/routing.js.map +1 -1
- package/package.json +3 -3
- package/src/index.ts +3 -3
- package/src/routing.ts +1 -1
package/dist/index.min.js
CHANGED
|
@@ -23,7 +23,7 @@ ${[...t.errors.entries()].map(([s,i])=>`
|
|
|
23
23
|
`),t),n.trace('responded with "%s" for "%s"',s,s),o.unwrap(),s;if(s==="ls"){let i=new G(...e.map(a=>Os.single(L(`${a}
|
|
24
24
|
`))),L(`
|
|
25
25
|
`));n.trace('respond with "%s" for %s',e,s),await o.write(i,t),n.trace('responded with "%s" for %s',e,s);continue}n.trace('respond with "na" for "%s"',s),await o.write(L(`na
|
|
26
|
-
`),t),n('responded with "na" for "%s"',s)}}var E3=class extends oe{id;remoteAddr;remotePeer;direction;timeline;direct;multiplexer;encryption;limits;log;maConn;muxer;components;outboundStreamProtocolNegotiationTimeout;inboundStreamProtocolNegotiationTimeout;closeTimeout;constructor(e,t){super(),this.components=e,this.id=t.id,this.remoteAddr=t.maConn.remoteAddr,this.remotePeer=t.remotePeer,this.direction=t.direction??"outbound",this.timeline=t.maConn.timeline,this.encryption=t.cryptoProtocol,this.limits=t.limits,this.maConn=t.maConn,this.log=t.maConn.log,this.outboundStreamProtocolNegotiationTimeout=t.outboundStreamProtocolNegotiationTimeout??1e4,this.inboundStreamProtocolNegotiationTimeout=t.inboundStreamProtocolNegotiationTimeout??1e4,this.closeTimeout=t.closeTimeout??1e3,this.direct=Zm(t.maConn.remoteAddr),this.onIncomingStream=this.onIncomingStream.bind(this),this.remoteAddr.getComponents().find(n=>n.code===421)==null&&(this.remoteAddr=this.remoteAddr.encapsulate(`/p2p/${this.remotePeer}`)),t.muxer!=null&&(this.multiplexer=t.muxer.protocol,this.muxer=t.muxer,this.muxer.addEventListener("stream",this.onIncomingStream)),this.maConn.addEventListener("close",n=>{this.dispatchEvent(new eo(n.local,n.error))})}[Symbol.toStringTag]="Connection";[d6]=!0;get streams(){return this.muxer?.streams??[]}get status(){return this.maConn.status}newStream=async(e,t={})=>{if(this.muxer==null)throw new So("Connection is not multiplexed");if(this.muxer.status!=="open")throw new jo(`The connection muxer is "${this.muxer.status}" and not "open"`);if(this.maConn.status!=="open")throw new jo(`The connection is "${this.status}" and not "open"`);if(this.limits!=null&&t?.runOnLimitedConnection!==!0)throw new $a("Cannot open protocol stream on limited connection");Array.isArray(e)||(e=[e]),t.onProgress?.(new Q("connection:open-stream",{connection:this,protocols:e})),this.log.trace("starting new stream for protocols %s",e);let n=await this.muxer.createStream({...t,protocol:e.length===1?e[0]:void 0});this.log.trace("started new stream %s for protocols %s",n.id,e);try{if(t.signal==null){n.log("no abort signal was passed while trying to negotiate protocols %s falling back to default timeout",e);let c=AbortSignal.timeout(this.outboundStreamProtocolNegotiationTimeout);t={...t,signal:c}}n.protocol===""?(n.log.trace("selecting protocol from protocols %s",e),n.protocol=await Zi(n,e,t),n.log("negotiated protocol %s",n.protocol)):n.log("pre-negotiated protocol %s",n.protocol);let o=o_(n.protocol,this.components.registrar,t),s=C9(n.protocol,"outbound",this);if(s>o){let c=new ii(`Too many outbound protocol streams for protocol "${n.protocol}" - ${s}/${o}`);throw n.abort(c),c}await this.components.peerStore.merge(this.remotePeer,{protocols:[n.protocol]}),this.components.metrics?.trackProtocolStream(n);let i=this.components.registrar.getMiddleware(n.protocol),a=await this.runMiddlewareChain(n,this,i);return t.onProgress?.(new Q("connection:opened-stream",{connection:this,stream:a})),a}catch(o){throw n.status==="open"?n.abort(o):this.log.error("could not create new outbound stream on connection %s %a for protocols %s - %e",this.direction==="inbound"?"from":"to",this.remoteAddr,e,o),o}};async onIncomingStream(e){let t=e.detail,n=AbortSignal.timeout(this.inboundStreamProtocolNegotiationTimeout);t.log("start protocol negotiation, timing out after %dms",this.inboundStreamProtocolNegotiationTimeout);try{if(t.protocol===""){let l=this.components.registrar.getProtocols();t.log.trace("selecting protocol from protocols %s",l),t.protocol=await Ji(t,l,{signal:n}),t.log("negotiated protocol %s",t.protocol)}else t.log("pre-negotiated protocol %s",t.protocol);let o=n_(t.protocol,this.components.registrar);if(C9(t.protocol,"inbound",this)>o)throw new Tu(`Too many inbound protocol streams for protocol "${t.protocol}" - limit ${o}`);await this.components.peerStore.merge(this.remotePeer,{protocols:[t.protocol]},{signal:n}),this.components.metrics?.trackProtocolStream(t);let{handler:i,options:a}=this.components.registrar.getHandler(t.protocol);if(this.limits!=null&&a.runOnLimitedConnection!==!0)throw new $a("Cannot open protocol stream on limited connection");let c=this.components.registrar.getMiddleware(t.protocol);c.push(async(l,u,d)=>{await i(l,u),d(l,u)}),await this.runMiddlewareChain(t,this,c)}catch(o){t.abort(o)}}async runMiddlewareChain(e,t,n){for(let o=0;o<n.length;o++){let s=n[o];e.log.trace("running middleware",o,s),await new Promise((i,a)=>{try{let c=s(e,t,(l,u)=>{e=l,t=u,i()});c instanceof Promise&&c.catch(a)}catch(c){a(c)}}),e.log.trace("ran middleware",o,s)}return e}async close(e={}){if(this.log("closing connection to %a",this.remoteAddr),e.signal==null){let t=AbortSignal.timeout(this.closeTimeout);e={...e,signal:t}}await this.muxer?.close(e),await this.maConn.close(e)}abort(e){this.muxer?.abort(e),this.maConn.abort(e)}};function _9(r,e){return new E3(r,e)}function n_(r,e){try{let{options:t}=e.getHandler(r);if(t.maxInboundStreams!=null)return t.maxInboundStreams}catch(t){if(t.name!=="UnhandledProtocolError")throw t}return y3}function o_(r,e,t={}){try{let{options:n}=e.getHandler(r);if(n.maxOutboundStreams!=null)return n.maxOutboundStreams}catch(n){if(n.name!=="UnhandledProtocolError")throw n}return t.maxOutboundStreams??b3}function C9(r,e,t){let n=0;return t.streams.forEach(o=>{o.direction===e&&o.protocol===r&&n++}),n}var rh=class{components;connectionEncrypters;streamMuxers;inboundUpgradeTimeout;inboundStreamProtocolNegotiationTimeout;outboundStreamProtocolNegotiationTimeout;events;metrics;connectionCloseTimeout;constructor(e,t){this.components=e,this.connectionEncrypters=lt({name:"libp2p_upgrader_connection_encrypters",metrics:this.components.metrics}),t.connectionEncrypters.forEach(n=>{this.connectionEncrypters.set(n.protocol,n)}),this.streamMuxers=lt({name:"libp2p_upgrader_stream_multiplexers",metrics:this.components.metrics}),t.streamMuxers.forEach(n=>{this.streamMuxers.set(n.protocol,n)}),this.inboundUpgradeTimeout=t.inboundUpgradeTimeout??1e4,this.inboundStreamProtocolNegotiationTimeout=t.inboundStreamProtocolNegotiationTimeout??1e4,this.outboundStreamProtocolNegotiationTimeout=t.outboundStreamProtocolNegotiationTimeout??1e4,this.connectionCloseTimeout=t.connectionCloseTimeout??1e3,this.events=e.events,this.metrics={dials:e.metrics?.registerCounterGroup("libp2p_connection_manager_dials_total"),errors:e.metrics?.registerCounterGroup("libp2p_connection_manager_dial_errors_total"),inboundErrors:e.metrics?.registerCounterGroup("libp2p_connection_manager_dials_inbound_errors_total"),outboundErrors:e.metrics?.registerCounterGroup("libp2p_connection_manager_dials_outbound_errors_total")}}[Symbol.toStringTag]="@libp2p/upgrader";async shouldBlockConnection(e,...t){let n=this.components.connectionGater[e];if(n==null)return;if(await n.apply(this.components.connectionGater,t)===!0)throw new Lf(`The multiaddr connection is blocked by gater.${e}`)}createInboundAbortSignal(e){let t=me([AbortSignal.timeout(this.inboundUpgradeTimeout),e]);return t}async upgradeInbound(e,t){let n=!1,o=this.createInboundAbortSignal(t.signal);try{if(this.metrics.dials?.increment({inbound:!0}),n=this.components.connectionManager.acceptIncomingConnection(e),!n)throw new Pf("Connection denied");await ke(this.shouldBlockConnection("denyInboundConnection",e),o),await this._performUpgrade(e,"inbound",{...t,signal:o})}catch(s){throw this.metrics.errors?.increment({inbound:!0}),this.metrics.inboundErrors?.increment({[s.name??"Error"]:!0}),s}finally{o.clear(),n&&this.components.connectionManager.afterUpgradeInbound()}}async upgradeOutbound(e,t){try{this.metrics.dials?.increment({outbound:!0});let n=e.remoteAddr.getComponents().findLast(i=>i.code===421)?.value,o;n!=null&&(o=Oe(n),await ke(this.shouldBlockConnection("denyOutboundConnection",o,e),t.signal));let s="outbound";return t.initiator===!1&&(s="inbound"),await this._performUpgrade(e,s,t)}catch(n){throw this.metrics.errors?.increment({outbound:!0}),this.metrics.outboundErrors?.increment({[n.name??"Error"]:!0}),n}}async _performUpgrade(e,t,n){let o=e,s,i,a,c,l=`${parseInt(String(Math.random()*1e9)).toString(36)}${Date.now()}`;if(e.log=e.log.newScope(`${t}:${l}`),this.components.metrics?.trackMultiaddrConnection(e),e.log.trace("starting the %s connection upgrade",t),n?.skipProtection!==!0){let d=this.components.connectionProtector;d!=null&&(e.log("protecting the %s connection",t),o=await d.protect(o,n))}try{if(s_(n)){if(n.remotePeer==null)throw new Gr(`${t} connection that skipped encryption must have a peer id`);c="native",s=n.remotePeer}else{let d=e.remoteAddr.getComponents().findLast(h=>h.code===421)?.value,f;d!=null&&(f=Oe(d)),n?.onProgress?.(new Q(`upgrader:encrypt-${t}-connection`)),{connection:o,remotePeer:s,protocol:c,streamMuxer:i}=await(t==="inbound"?this._encryptInbound(o,{...n,remotePeer:f}):this._encryptOutbound(o,{...n,remotePeer:f}))}if(s.equals(this.components.peerId)){let d=new si("Can not dial self");throw e.abort(d),d}await this.shouldBlockConnection(t==="inbound"?"denyInboundEncryptedConnection":"denyOutboundEncryptedConnection",s,e),n?.muxerFactory!=null?i=n.muxerFactory:i==null&&this.streamMuxers.size>0&&(n?.onProgress?.(new Q(`upgrader:multiplex-${t}-connection`)),i=await(t==="inbound"?this._multiplexInbound(o,this.streamMuxers,n):this._multiplexOutbound(o,this.streamMuxers,n)))}catch(d){throw e.log.error("failed to upgrade %s connection %s %a - %e",t,t==="inbound"?"from":"to",e.remoteAddr,d),d}i!=null&&(e.log("create muxer %s",i.protocol),a=i.createStreamMuxer(o)),await this.shouldBlockConnection(t==="inbound"?"denyInboundUpgradedConnection":"denyOutboundUpgradedConnection",s,e);let u=this._createConnection({id:l,cryptoProtocol:c,direction:t,maConn:e,stream:o,muxer:a,remotePeer:s,limits:n?.limits,closeTimeout:this.connectionCloseTimeout});return u.log("successfully upgraded connection"),u}_createConnection(e){let t=_9(this.components,{...e,outboundStreamProtocolNegotiationTimeout:this.outboundStreamProtocolNegotiationTimeout,inboundStreamProtocolNegotiationTimeout:this.inboundStreamProtocolNegotiationTimeout});return t.addEventListener("close",()=>{this.events.safeDispatchEvent("connection:close",{detail:t})}),this.events.safeDispatchEvent("connection:open",{detail:t}),t}async _encryptInbound(e,t){let n=Array.from(this.connectionEncrypters.keys());try{let o=await Ji(e,n,t),s=this.connectionEncrypters.get(o);if(s==null)throw new $s(`no crypto module found for ${o}`);return e.log("encrypting inbound connection using %s",o),{...await s.secureInbound(e,t),protocol:o}}catch(o){throw new $s(o.message)}}async _encryptOutbound(e,t){let n=Array.from(this.connectionEncrypters.keys());try{e.log.trace("selecting encrypter from %s",n);let o=await Zi(e,n,t),s=this.connectionEncrypters.get(o);if(s==null)throw new $s(`no crypto module found for ${o}`);return e.log("encrypting outbound connection using %s",o),{...await s.secureOutbound(e,t),protocol:o}}catch(o){throw new $s(o.message)}}async _multiplexOutbound(e,t,n){let o=Array.from(t.keys());e.log("outbound selecting muxer %s",o);try{e.log.trace("selecting stream muxer from %s",o);let s=await Zi(e,o,n),i=t.get(s);if(i==null)throw new So(`No muxer configured for protocol "${s}"`);return e.log("selected %s as muxer protocol",s),i}catch(s){throw e.log.error("error multiplexing outbound connection - %e",s),new So(String(s))}}async _multiplexInbound(e,t,n){let o=Array.from(t.keys());e.log("inbound handling muxers %s",o);try{e.log.trace("selecting stream muxer from %s",o);let s=await Ji(e,o,n),i=t.get(s);if(i==null)throw new So(`No muxer configured for protocol "${s}"`);return e.log("selected %s as muxer protocol",s),i}catch(s){throw e.log.error("error multiplexing inbound connection - %e",s),s}}getConnectionEncrypters(){return this.connectionEncrypters}getStreamMuxers(){return this.streamMuxers}};function s_(r){return r.skipEncryption===!0}var nh="3.3.4",oh="js-libp2p";function sh(r,e){return`${r??oh}/${e??nh} browser/${globalThis.navigator.userAgent}`}var al=class extends oe{peerId;peerStore;contentRouting;peerRouting;metrics;services;logger;status;components;log;constructor(e){super(),this.status="stopped";let t=new oe,n=t.dispatchEvent.bind(t);t.dispatchEvent=l=>{let u=n(l),d=this.dispatchEvent(new CustomEvent(l.type,{detail:l.detail}));return u||d},this.peerId=e.peerId,this.logger=e.logger??Li(),this.log=this.logger.forComponent("libp2p"),this.services={};let o=e.nodeInfo?.name??oh,s=e.nodeInfo?.version??nh,i=this.components=a9({peerId:e.peerId,privateKey:e.privateKey,nodeInfo:{name:o,version:s,userAgent:e.nodeInfo?.userAgent??sh(o,s)},logger:this.logger,events:t,datastore:e.datastore??new gf,connectionGater:l9(e.connectionGater),dns:e.dns});e.metrics!=null&&(this.metrics=this.configureComponent("metrics",e.metrics(this.components))),this.peerStore=this.configureComponent("peerStore",r9(i,{addressFilter:this.components.connectionGater.filterMultiaddrForPeer,...e.peerStore})),i.events.addEventListener("peer:update",l=>{if(l.detail.previous==null){let u={id:l.detail.peer.id,multiaddrs:l.detail.peer.addresses.map(d=>d.multiaddr)};i.events.safeDispatchEvent("peer:discovery",{detail:u})}}),e.connectionProtector!=null&&this.configureComponent("connectionProtector",e.connectionProtector(i)),this.components.upgrader=new rh(this.components,{connectionEncrypters:(e.connectionEncrypters??[]).map((l,u)=>this.configureComponent(`connection-encryption-${u}`,l(this.components))),streamMuxers:(e.streamMuxers??[]).map((l,u)=>this.configureComponent(`stream-muxers-${u}`,l(this.components))),inboundUpgradeTimeout:e.connectionManager?.inboundUpgradeTimeout,inboundStreamProtocolNegotiationTimeout:e.connectionManager?.inboundStreamProtocolNegotiationTimeout,outboundStreamProtocolNegotiationTimeout:e.connectionManager?.outboundStreamProtocolNegotiationTimeout,connectionCloseTimeout:e.connectionManager?.connectionCloseTimeout}),this.configureComponent("transportManager",new th(this.components,e.transportManager)),this.configureComponent("connectionManager",new jf(this.components,e.connectionManager)),e.connectionMonitor?.enabled!==!1&&this.configureComponent("connectionMonitor",new Yf(this.components,e.connectionMonitor)),this.configureComponent("registrar",new eh(this.components)),this.configureComponent("addressManager",new xf(this.components,e.addresses));let a=(e.peerRouters??[]).map((l,u)=>this.configureComponent(`peer-router-${u}`,l(this.components)));this.peerRouting=this.components.peerRouting=this.configureComponent("peerRouting",new Zf(this.components,{routers:a}));let c=(e.contentRouters??[]).map((l,u)=>this.configureComponent(`content-router-${u}`,l(this.components)));if(this.contentRouting=this.components.contentRouting=this.configureComponent("contentRouting",new Qf(this.components,{routers:c})),this.configureComponent("randomWalk",new Jf(this.components)),(e.peerDiscovery??[]).forEach((l,u)=>{this.configureComponent(`peer-discovery-${u}`,l(this.components)).addEventListener("peer",f=>{this.#e(f)})}),e.transports?.forEach((l,u)=>{this.components.transportManager.add(this.configureComponent(`transport-${u}`,l(this.components)))}),e.services!=null)for(let l of Object.keys(e.services)){let u=e.services[l],d=u(this.components);if(d==null){this.log.error("service factory %s returned null or undefined instance",l);continue}this.services[l]=d,this.configureComponent(l,d),d[Wo]!=null&&(this.log("registering service %s for content routing",l),c.push(d[Wo])),d[Zo]!=null&&(this.log("registering service %s for peer routing",l),a.push(d[Zo])),d[Xo]!=null&&(this.log("registering service %s for peer discovery",l),d[Xo].addEventListener?.("peer",f=>{this.#e(f)}))}c9(i)}configureComponent(e,t){return t==null&&this.log.error("component %s was null or undefined",e),this.components[e]=t,t}async start(){if(this.status==="stopped"){this.status="starting",this.log("libp2p is starting");try{await this.components.beforeStart?.(),await this.components.start(),await this.components.afterStart?.(),this.status="started",this.safeDispatchEvent("start",{detail:this}),this.log("libp2p has started with peer id %p",this.peerId)}catch(e){throw this.log.error("an error occurred starting libp2p - %e",e),this.status="started",await this.stop(),e}}}async stop(){this.status==="started"&&(this.log("libp2p is stopping"),this.status="stopping",await this.components.beforeStop?.(),await this.components.stop(),await this.components.afterStop?.(),this.status="stopped",this.safeDispatchEvent("stop",{detail:this}),this.log("libp2p has stopped"))}getConnections(e){return this.components.connectionManager.getConnections(e)}getDialQueue(){return this.components.connectionManager.getDialQueue()}getPeers(){let e=new sr;for(let t of this.components.connectionManager.getConnections())e.add(t.remotePeer);return Array.from(e)}async dial(e,t={}){return this.components.connectionManager.openConnection(e,{priority:75,...t})}async dialProtocol(e,t,n={}){if(t==null)throw new x("no protocols were provided to open a stream");if(t=Array.isArray(t)?t:[t],t.length===0)throw new x("no protocols were provided to open a stream");return this.components.connectionManager.openStream(e,t,n)}getMultiaddrs(){return this.components.addressManager.getAddresses()}getProtocols(){return this.components.registrar.getProtocols()}async hangUp(e,t={}){rn(e)&&(e=Oe(e.getComponents().findLast(n=>n.code===421)?.value??"")),await this.components.connectionManager.closeConnections(e,t)}async getPublicKey(e,t={}){if(this.log("getPublicKey %p",e),e.publicKey!=null)return e.publicKey;try{let i=await this.peerStore.get(e,t);if(i.id.publicKey!=null)return i.id.publicKey}catch(i){if(i.name!=="NotFoundError")throw i}let n=Xe([L("/pk/"),e.toMultihash().bytes]),o=await this.contentRouting.get(n,t),s=et(o);return await this.peerStore.patch(e,{publicKey:s},t),s}async handle(e,t,n){Array.isArray(e)||(e=[e]),await Promise.all(e.map(async o=>{await this.components.registrar.handle(o,t,n)}))}async unhandle(e,t){Array.isArray(e)||(e=[e]),await Promise.all(e.map(async n=>{await this.components.registrar.unhandle(n,t)}))}async register(e,t,n){return this.components.registrar.register(e,t,n)}unregister(e){this.components.registrar.unregister(e)}use(e,t){this.components.registrar.use(e,Array.isArray(t)?t:[t])}unuse(e){this.components.registrar.unuse(e)}async isDialable(e,t={}){return this.components.connectionManager.isDialable(e,t)}#e(e){let{detail:t}=e;if(t.id.toString()===this.peerId.toString()){this.log.error("peer discovery mechanism discovered self");return}this.components.peerStore.merge(t.id,{multiaddrs:t.multiaddrs}).catch(n=>{this.log.error("could not update multiaddrs of discovered peer - %e",n)})}};async function L9(r={}){r.privateKey??=await sd("Ed25519");let e=new al({...await L8(r),peerId:_8(r.privateKey)});return r.start!==!1&&await e.start(),e}var i_=["dial","dialProtocol","hangUp","handle","unhandle","getMultiaddrs","getProtocols"];function x3(r){return r==null?!1:r instanceof al?!0:i_.every(e=>typeof r[e]=="function")}function a_(r){return r[Symbol.asyncIterator]!=null}function c_(r,e){let t=0;if(a_(r))return(async function*(){for await(let c of r)yield e(c,t++)})();let n=Ri(r),{value:o,done:s}=n.next();if(s===!0)return(function*(){})();let i=e(o,t++);if(typeof i.then=="function")return(async function*(){yield await i;for(let c of n)yield e(c,t++)})();let a=e;return(function*(){yield i;for(let c of n)yield a(c,t++)})()}var Ur=c_;function v3(r){return{...r,id:r.id.toCID(),router:"libp2p-router"}}var S3=class{name="libp2p-router";libp2p;constructor(e){this.libp2p=e}async provide(e,t){await this.libp2p.contentRouting.provide(e,t)}async cancelReprovide(e,t){await this.libp2p.contentRouting.cancelReprovide(e,t)}async*findProviders(e,t){yield*Ur(this.libp2p.contentRouting.findProviders(e,t),n=>({...v3(n)}))}async put(e,t,n){await this.libp2p.contentRouting.put(e,t,n)}async get(e,t){return ie(await this.libp2p.contentRouting.get(e,t))}async findPeer(e,t){return v3(await this.libp2p.peerRouting.findPeer(mt(e),t))}async*getClosestPeers(e,t){yield*Ur(this.libp2p.peerRouting.getClosestPeers(e,t),v3)}toString(){return"Libp2pRouter()"}};function P9(r){return new S3(r)}var cl=Uint32Array.from([1732584193,4023233417,2562383102,271733878,3285377520]),Ao=new Uint32Array(80),A3=class extends as{A=cl[0]|0;B=cl[1]|0;C=cl[2]|0;D=cl[3]|0;E=cl[4]|0;constructor(){super(64,20,8,!1)}get(){let{A:e,B:t,C:n,D:o,E:s}=this;return[e,t,n,o,s]}set(e,t,n,o,s){this.A=e|0,this.B=t|0,this.C=n|0,this.D=o|0,this.E=s|0}process(e,t){for(let c=0;c<16;c++,t+=4)Ao[c]=e.getUint32(t,!1);for(let c=16;c<80;c++)Ao[c]=Bu(Ao[c-3]^Ao[c-8]^Ao[c-14]^Ao[c-16],1);let{A:n,B:o,C:s,D:i,E:a}=this;for(let c=0;c<80;c++){let l,u;c<20?(l=Fu(o,s,i),u=1518500249):c<40?(l=o^s^i,u=1859775393):c<60?(l=$u(o,s,i),u=2400959708):(l=o^s^i,u=3395469782);let d=Bu(n,5)+l+a+u+Ao[c]|0;a=i,i=s,s=Bu(o,30),o=n,n=d}n=n+this.A|0,o=o+this.B|0,s=s+this.C|0,i=i+this.D|0,a=a+this.E|0,this.set(n,o,s,i,a)}roundClean(){vt(Ao)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0),vt(this.buffer)}},k9=Za(()=>new A3);function D9(r,e,t,n){Sn(r);let o=t5({dkLen:32,asyncTick:10},n),{c:s,dkLen:i,asyncTick:a}=o;if(Vt(s,"c"),Vt(i,"dkLen"),Vt(a,"asyncTick"),s<1)throw new Error("iterations (c) must be >= 1");if(i<1)throw new Error('"dkLen" must be >= 1');if(i>(2**32-1)*r.outputLen)throw new Error("derived key too long");let c=Np(e,"password"),l=Np(t,"salt"),u=new Uint8Array(i),d=Es.create(r,c),f=d._cloneInto().update(l);return{c:s,dkLen:i,asyncTick:a,DK:u,PRF:d,PRFSalt:f}}function N9(r,e,t,n,o){return r.destroy(),e.destroy(),n&&n.destroy(),vt(o),t}function O9(r,e,t,n){let{c:o,dkLen:s,DK:i,PRF:a,PRFSalt:c}=D9(r,e,t,n),l,u=new Uint8Array(4),d=is(u),f=new Uint8Array(a.outputLen);for(let h=1,m=0;m<s;h++,m+=a.outputLen){let y=i.subarray(m,m+a.outputLen);d.setInt32(0,h,!1),(l=c._cloneInto(l)).update(u).digestInto(f),y.set(f.subarray(0,y.length));for(let g=1;g<o;g++){a._cloneInto(l).update(f).digestInto(f);for(let p=0;p<y.length;p++)y[p]^=f[p]}}return N9(a,c,i,l,f)}async function ih(r,e,t,n){let{c:o,dkLen:s,asyncTick:i,DK:a,PRF:c,PRFSalt:l}=D9(r,e,t,n),u,d=new Uint8Array(4),f=is(d),h=new Uint8Array(c.outputLen);for(let m=1,y=0;y<s;m++,y+=c.outputLen){let g=a.subarray(y,y+c.outputLen);f.setInt32(0,m,!1),(u=l._cloneInto(u)).update(d).digestInto(h),g.set(h.subarray(0,g.length)),await e5(o-1,i,()=>{c._cloneInto(u).update(h).digestInto(h);for(let p=0;p<g.length;p++)g[p]^=h[p]})}return N9(c,l,a,u,h)}var M9={sha1:k9,"sha2-256":pr,"sha2-512":Qr};function ll(r,e,t,n,o){if(o!=="sha1"&&o!=="sha2-256"&&o!=="sha2-512"){let a=Object.keys(M9).join(" / ");throw new x(`Hash '${o}' is unknown or not supported. Must be ${a}`)}let s=M9[o],i=O9(s,r,e,{c:t,dkLen:n});return xn.encode(i).substring(1)}var My=ri(z9(),1);var T3={keyLength:64,iterationCount:1e4,salt:"you should override this value with a crypto secure random number",hash:"sha2-512"};var ea={};se(ea,{create:()=>x_,derivedEmptyPasswordKey:()=>ah});var ah={alg:"A128GCM",ext:!0,k:"scm9jmO_4BJAgdwWGVulLg",key_ops:["encrypt","decrypt"],kty:"oct"};function x_(r){let e=r?.algorithm??"AES-GCM",t=r?.keyLength??16,n=r?.nonceLength??12,o=r?.digest??"SHA-256",s=r?.saltLength??16,i=r?.iterations??32767,a=We.get();t*=8;async function c(d,f){let h=a.getRandomValues(new Uint8Array(s)),m=a.getRandomValues(new Uint8Array(n)),y={name:e,iv:m};typeof f=="string"&&(f=L(f));let g;if(f.length===0){g=await a.subtle.importKey("jwk",ah,{name:"AES-GCM"},!0,["encrypt"]);try{let b={name:"PBKDF2",salt:h,iterations:i,hash:{name:o}},E=await a.subtle.importKey("raw",ie(f),{name:"PBKDF2"},!1,["deriveKey"]);g=await a.subtle.deriveKey(b,E,{name:e,length:t},!0,["encrypt"])}catch{g=await a.subtle.importKey("jwk",ah,{name:"AES-GCM"},!0,["encrypt"])}}else{let b={name:"PBKDF2",salt:h,iterations:i,hash:{name:o}},E=await a.subtle.importKey("raw",ie(f),{name:"PBKDF2"},!1,["deriveKey"]);g=await a.subtle.deriveKey(b,E,{name:e,length:t},!0,["encrypt"])}let p=await a.subtle.encrypt(y,g,ie(d));return Xe([h,y.iv,new Uint8Array(p)])}async function l(d,f){let h=d.subarray(0,s),m=d.subarray(s,s+n),y=d.subarray(s+n),g={name:e,iv:m};typeof f=="string"&&(f=L(f));let p;if(f.length===0)try{let E={name:"PBKDF2",salt:h,iterations:i,hash:{name:o}},v=await a.subtle.importKey("raw",ie(f),{name:"PBKDF2"},!1,["deriveKey"]);p=await a.subtle.deriveKey(E,v,{name:e,length:t},!0,["decrypt"])}catch{p=await a.subtle.importKey("jwk",ah,{name:"AES-GCM"},!0,["decrypt"])}else{let E={name:"PBKDF2",salt:h,iterations:i,hash:{name:o}},v=await a.subtle.importKey("raw",ie(f),{name:"PBKDF2"},!1,["deriveKey"]);p=await a.subtle.deriveKey(E,v,{name:e,length:t},!0,["decrypt"])}let b=await a.subtle.decrypt(g,p,ie(y));return new Uint8Array(b)}return{encrypt:c,decrypt:l}}var he=ri(G9());function Vs(r,e){let t=0;if(r.length===1)return r[0];for(let n=r.length-1;n>=0;n--)t+=r[r.length-1-n]*Math.pow(2,e*n);return t}function To(r,e,t=-1){let n=t,o=r,s=0,i=Math.pow(2,e);for(let a=1;a<8;a++){if(r<i){let c;if(n<0)c=new ArrayBuffer(a),s=a;else{if(n<a)return new ArrayBuffer(0);c=new ArrayBuffer(n),s=n}let l=new Uint8Array(c);for(let u=a-1;u>=0;u--){let d=Math.pow(2,u*e);l[s-u-1]=Math.floor(o/d),o-=l[s-u-1]*d}return c}i*=Math.pow(2,e)}return new ArrayBuffer(0)}function uh(...r){let e=0,t=0;for(let s of r)e+=s.length;let n=new ArrayBuffer(e),o=new Uint8Array(n);for(let s of r)o.set(s,t),t+=s.length;return o}function C3(){let r=new Uint8Array(this.valueHex);if(this.valueHex.byteLength>=2){let a=r[0]===255&&r[1]&128,c=r[0]===0&&(r[1]&128)===0;(a||c)&&this.warnings.push("Needlessly long format")}let e=new ArrayBuffer(this.valueHex.byteLength),t=new Uint8Array(e);for(let a=0;a<this.valueHex.byteLength;a++)t[a]=0;t[0]=r[0]&128;let n=Vs(t,8),o=new ArrayBuffer(this.valueHex.byteLength),s=new Uint8Array(o);for(let a=0;a<this.valueHex.byteLength;a++)s[a]=r[a];return s[0]&=127,Vs(s,8)-n}function W9(r){let e=r<0?r*-1:r,t=128;for(let n=1;n<8;n++){if(e<=t){if(r<0){let i=t-e,a=To(i,8,n),c=new Uint8Array(a);return c[0]|=128,a}let o=To(e,8,n),s=new Uint8Array(o);if(s[0]&128){let i=o.slice(0),a=new Uint8Array(i);o=new ArrayBuffer(o.byteLength+1),s=new Uint8Array(o);for(let c=0;c<i.byteLength;c++)s[c+1]=a[c];s[0]=0}return o}t*=Math.pow(2,8)}return new ArrayBuffer(0)}function j9(r,e){if(r.byteLength!==e.byteLength)return!1;let t=new Uint8Array(r),n=new Uint8Array(e);for(let o=0;o<t.length;o++)if(t[o]!==n[o])return!1;return!0}function Wt(r,e){let t=r.toString(10);if(e<t.length)return"";let n=e-t.length,o=new Array(n);for(let i=0;i<n;i++)o[i]="0";return o.join("").concat(t)}var HX=Math.log(2);function dh(){if(typeof BigInt>"u")throw new Error("BigInt is not defined. Your environment doesn't implement BigInt.")}function _3(r){let e=0,t=0;for(let o=0;o<r.length;o++){let s=r[o];e+=s.byteLength}let n=new Uint8Array(e);for(let o=0;o<r.length;o++){let s=r[o];n.set(new Uint8Array(s),t),t+=s.byteLength}return n.buffer}function qn(r,e,t,n){return e instanceof Uint8Array?e.byteLength?t<0?(r.error="Wrong parameter: inputOffset less than zero",!1):n<0?(r.error="Wrong parameter: inputLength less than zero",!1):e.byteLength-t-n<0?(r.error="End of input reached before message was fully decoded (inconsistent offset and length values)",!1):!0:(r.error="Wrong parameter: inputBuffer has zero length",!1):(r.error="Wrong parameter: inputBuffer must be 'Uint8Array'",!1)}var fl=class{constructor(){this.items=[]}write(e){this.items.push(e)}final(){return _3(this.items)}},ul=[new Uint8Array([1])],Y9="0123456789";var ra="",cn=new ArrayBuffer(0),R3=new Uint8Array(0),hl="EndOfContent",X9="OCTET STRING",Z9="BIT STRING";function zn(r){var e;return e=class extends r{get valueHex(){return this.valueHexView.slice().buffer}set valueHex(n){this.valueHexView=new Uint8Array(n)}constructor(...n){var o;super(...n);let s=n[0]||{};this.isHexOnly=(o=s.isHexOnly)!==null&&o!==void 0?o:!1,this.valueHexView=s.valueHex?he.BufferSourceConverter.toUint8Array(s.valueHex):R3}fromBER(n,o,s,i){let a=n instanceof ArrayBuffer?new Uint8Array(n):n;if(!qn(this,a,o,s))return-1;let c=o+s;return this.valueHexView=a.subarray(o,c),this.valueHexView.length?(this.blockLength=s,c):(this.warnings.push("Zero buffer length"),o)}toBER(n=!1){return this.isHexOnly?n?new ArrayBuffer(this.valueHexView.byteLength):this.valueHexView.byteLength===this.valueHexView.buffer.byteLength?this.valueHexView.buffer:this.valueHexView.slice().buffer:(this.error="Flag 'isHexOnly' is not set, abort",cn)}toJSON(){return{...super.toJSON(),isHexOnly:this.isHexOnly,valueHex:he.Convert.ToHex(this.valueHexView)}}},e.NAME="hexBlock",e}var $n=class{static blockName(){return this.NAME}get valueBeforeDecode(){return this.valueBeforeDecodeView.slice().buffer}set valueBeforeDecode(e){this.valueBeforeDecodeView=new Uint8Array(e)}constructor({blockLength:e=0,error:t=ra,warnings:n=[],valueBeforeDecode:o=R3}={}){this.blockLength=e,this.error=t,this.warnings=n,this.valueBeforeDecodeView=he.BufferSourceConverter.toUint8Array(o)}toJSON(){return{blockName:this.constructor.NAME,blockLength:this.blockLength,error:this.error,warnings:this.warnings,valueBeforeDecode:he.Convert.ToHex(this.valueBeforeDecodeView)}}};$n.NAME="baseBlock";var bt=class extends $n{fromBER(e,t,n,o){throw TypeError("User need to make a specific function in a class which extends 'ValueBlock'")}toBER(e,t){throw TypeError("User need to make a specific function in a class which extends 'ValueBlock'")}};bt.NAME="valueBlock";var fh=class extends zn($n){constructor({idBlock:e={}}={}){var t,n,o,s;super(),e?(this.isHexOnly=(t=e.isHexOnly)!==null&&t!==void 0?t:!1,this.valueHexView=e.valueHex?he.BufferSourceConverter.toUint8Array(e.valueHex):R3,this.tagClass=(n=e.tagClass)!==null&&n!==void 0?n:-1,this.tagNumber=(o=e.tagNumber)!==null&&o!==void 0?o:-1,this.isConstructed=(s=e.isConstructed)!==null&&s!==void 0?s:!1):(this.tagClass=-1,this.tagNumber=-1,this.isConstructed=!1)}toBER(e=!1){let t=0;switch(this.tagClass){case 1:t|=0;break;case 2:t|=64;break;case 3:t|=128;break;case 4:t|=192;break;default:return this.error="Unknown tag class",cn}if(this.isConstructed&&(t|=32),this.tagNumber<31&&!this.isHexOnly){let o=new Uint8Array(1);if(!e){let s=this.tagNumber;s&=31,t|=s,o[0]=t}return o.buffer}if(!this.isHexOnly){let o=To(this.tagNumber,7),s=new Uint8Array(o),i=o.byteLength,a=new Uint8Array(i+1);if(a[0]=t|31,!e){for(let c=0;c<i-1;c++)a[c+1]=s[c]|128;a[i]=s[i-1]}return a.buffer}let n=new Uint8Array(this.valueHexView.byteLength+1);if(n[0]=t|31,!e){let o=this.valueHexView;for(let s=0;s<o.length-1;s++)n[s+1]=o[s]|128;n[this.valueHexView.byteLength]=o[o.length-1]}return n.buffer}fromBER(e,t,n){let o=he.BufferSourceConverter.toUint8Array(e);if(!qn(this,o,t,n))return-1;let s=o.subarray(t,t+n);if(s.length===0)return this.error="Zero buffer length",-1;switch(s[0]&192){case 0:this.tagClass=1;break;case 64:this.tagClass=2;break;case 128:this.tagClass=3;break;case 192:this.tagClass=4;break;default:return this.error="Unknown tag class",-1}this.isConstructed=(s[0]&32)===32,this.isHexOnly=!1;let a=s[0]&31;if(a!==31)this.tagNumber=a,this.blockLength=1;else{let c=0;for(;;){let u=c+1;if(u>=s.length)return this.error="End of input reached before message was fully decoded",-1;if(c++,(s[u]&128)===0)break}this.blockLength=c+1;let l=this.valueHexView=new Uint8Array(c);for(let u=0;u<c;u++)l[u]=s[u+1]&127;this.blockLength<=9?this.tagNumber=Vs(l,7):(this.isHexOnly=!0,this.warnings.push("Tag too long, represented as hex-coded"))}if(this.tagClass===1&&this.isConstructed)switch(this.tagNumber){case 1:case 2:case 5:case 6:case 9:case 13:case 14:case 23:case 24:case 31:case 32:case 33:case 34:return this.error="Constructed encoding used for primitive type",-1}return t+this.blockLength}toJSON(){return{...super.toJSON(),tagClass:this.tagClass,tagNumber:this.tagNumber,isConstructed:this.isConstructed}}};fh.NAME="identificationBlock";var hh=class extends $n{constructor({lenBlock:e={}}={}){var t,n,o;super(),this.isIndefiniteForm=(t=e.isIndefiniteForm)!==null&&t!==void 0?t:!1,this.longFormUsed=(n=e.longFormUsed)!==null&&n!==void 0?n:!1,this.length=(o=e.length)!==null&&o!==void 0?o:0}fromBER(e,t,n){let o=he.BufferSourceConverter.toUint8Array(e);if(!qn(this,o,t,n))return-1;let s=o.subarray(t,t+n);if(s.length===0)return this.error="Zero buffer length",-1;if(s[0]===255)return this.error="Length block 0xFF is reserved by standard",-1;if(this.isIndefiniteForm=s[0]===128,this.isIndefiniteForm)return this.blockLength=1,t+this.blockLength;if(this.longFormUsed=!!(s[0]&128),this.longFormUsed===!1)return this.length=s[0],this.blockLength=1,t+this.blockLength;let i=s[0]&127;if(i>8)return this.error="Too big integer",-1;if(i+1>s.length)return this.error="End of input reached before message was fully decoded",-1;let a=t+1,c=o.subarray(a,a+i);return c[i-1]===0&&this.warnings.push("Needlessly long encoded length"),this.length=Vs(c,8),this.longFormUsed&&this.length<=127&&this.warnings.push("Unnecessary usage of long length form"),this.blockLength=i+1,t+this.blockLength}toBER(e=!1){let t,n;if(this.length>127&&(this.longFormUsed=!0),this.isIndefiniteForm)return t=new ArrayBuffer(1),e===!1&&(n=new Uint8Array(t),n[0]=128),t;if(this.longFormUsed){let o=To(this.length,8);if(o.byteLength>127)return this.error="Too big length",cn;if(t=new ArrayBuffer(o.byteLength+1),e)return t;let s=new Uint8Array(o);n=new Uint8Array(t),n[0]=o.byteLength|128;for(let i=0;i<o.byteLength;i++)n[i+1]=s[i];return t}return t=new ArrayBuffer(1),e===!1&&(n=new Uint8Array(t),n[0]=this.length),t}toJSON(){return{...super.toJSON(),isIndefiniteForm:this.isIndefiniteForm,longFormUsed:this.longFormUsed,length:this.length}}};hh.NAME="lengthBlock";var q={},ut=class extends $n{constructor({name:e=ra,optional:t=!1,primitiveSchema:n,...o}={},s){super(o),this.name=e,this.optional=t,n&&(this.primitiveSchema=n),this.idBlock=new fh(o),this.lenBlock=new hh(o),this.valueBlock=s?new s(o):new bt(o)}fromBER(e,t,n,o){let s=this.valueBlock.fromBER(e,t,this.lenBlock.isIndefiniteForm?n:this.lenBlock.length,o);return s===-1?(this.error=this.valueBlock.error,s):(this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.valueBlock.error.length||(this.blockLength+=this.valueBlock.blockLength),s)}toBER(e,t){let n=t||new fl;t||J9(this);let o=this.idBlock.toBER(e);if(n.write(o),this.lenBlock.isIndefiniteForm)n.write(new Uint8Array([128]).buffer),this.valueBlock.toBER(e,n),n.write(new ArrayBuffer(2));else{let s=this.valueBlock.toBER(e);this.lenBlock.length=s.byteLength;let i=this.lenBlock.toBER(e);n.write(i),n.write(s)}return t?cn:n.final()}toJSON(){let e={...super.toJSON(),idBlock:this.idBlock.toJSON(),lenBlock:this.lenBlock.toJSON(),valueBlock:this.valueBlock.toJSON(),name:this.name,optional:this.optional};return this.primitiveSchema&&(e.primitiveSchema=this.primitiveSchema.toJSON()),e}toString(e="ascii"){return e==="ascii"?this.onAsciiEncoding():he.Convert.ToHex(this.toBER())}onAsciiEncoding(){let e=this.constructor.NAME,t=he.Convert.ToHex(this.valueBlock.valueBeforeDecodeView);return`${e} : ${t}`}isEqual(e){if(this===e)return!0;if(!(e instanceof this.constructor))return!1;let t=this.toBER(),n=e.toBER();return j9(t,n)}};ut.NAME="BaseBlock";function J9(r){var e;if(r instanceof q.Constructed)for(let t of r.valueBlock.value)J9(t)&&(r.lenBlock.isIndefiniteForm=!0);return!!(!((e=r.lenBlock)===null||e===void 0)&&e.isIndefiniteForm)}var ph=class extends ut{getValue(){return this.valueBlock.value}setValue(e){this.valueBlock.value=e}constructor({value:e=ra,...t}={},n){super(t,n),e&&this.fromString(e)}fromBER(e,t,n){let o=this.valueBlock.fromBER(e,t,this.lenBlock.isIndefiniteForm?n:this.lenBlock.length);return o===-1?(this.error=this.valueBlock.error,o):(this.fromBuffer(this.valueBlock.valueHexView),this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.valueBlock.error.length||(this.blockLength+=this.valueBlock.blockLength),o)}onAsciiEncoding(){return`${this.constructor.NAME} : '${this.valueBlock.value}'`}};ph.NAME="BaseStringBlock";var mh=class extends zn(bt){constructor({isHexOnly:e=!0,...t}={}){super(t),this.isHexOnly=e}};mh.NAME="PrimitiveValueBlock";var ey,gh=class extends ut{constructor(e={}){super(e,mh),this.idBlock.isConstructed=!1}};ey=gh;q.Primitive=ey;gh.NAME="PRIMITIVE";var L_=100,P_=1e4,k_=16*1024*1024,D_="Maximum ASN.1 nesting depth exceeded",N_="Maximum ASN.1 node count exceeded",O_="Maximum ASN.1 content length exceeded";function wl(r={}){var e,t,n;return{depth:0,maxDepth:(e=r.maxDepth)!==null&&e!==void 0?e:L_,nodesCount:0,maxNodes:(t=r.maxNodes)!==null&&t!==void 0?t:P_,maxContentLength:(n=r.maxContentLength)!==null&&n!==void 0?n:k_}}function M_(r){let e=new ut({},bt);return e.error=r,{offset:-1,result:e}}function B_(r){if(r.nodesCount+=1,r.nodesCount>r.maxNodes)return N_}function U_(r,e){if(r>e.maxContentLength)return O_}function L3(r,e,t,n){let o=n.depth+1;if(o>n.maxDepth)return M_(D_);n.depth=o;try{return ty(r,e,t,n)}finally{n.depth-=1}}function F_(r,e){if(r instanceof e)return r;let t=new e;return t.idBlock=r.idBlock,t.lenBlock=r.lenBlock,t.warnings=r.warnings,t.valueBeforeDecodeView=r.valueBeforeDecodeView,t}function ty(r,e=0,t=r.length,n=wl()){let o=e,s=new ut({},bt),i=new $n;if(!qn(i,r,e,t))return s.error=i.error,{offset:-1,result:s};if(!r.subarray(e,e+t).length)return s.error="Zero buffer length",{offset:-1,result:s};let c=B_(n);if(c)return s.error=c,{offset:-1,result:s};let l=s.idBlock.fromBER(r,e,t);if(s.idBlock.warnings.length&&s.warnings.concat(s.idBlock.warnings),l===-1)return s.error=s.idBlock.error,{offset:-1,result:s};if(e=l,t-=s.idBlock.blockLength,l=s.lenBlock.fromBER(r,e,t),s.lenBlock.warnings.length&&s.warnings.concat(s.lenBlock.warnings),l===-1)return s.error=s.lenBlock.error,{offset:-1,result:s};e=l,t-=s.lenBlock.blockLength;let u=s.lenBlock.isIndefiniteForm?t:s.lenBlock.length,d=U_(u,n);if(d)return s.error=d,{offset:-1,result:s};if(!s.idBlock.isConstructed&&s.lenBlock.isIndefiniteForm)return s.error="Indefinite length form used for primitive encoding form",{offset:-1,result:s};let f=ut;switch(s.idBlock.tagClass){case 1:if(s.idBlock.tagNumber>=37&&s.idBlock.isHexOnly===!1)return s.error="UNIVERSAL 37 and upper tags are reserved by ASN.1 standard",{offset:-1,result:s};switch(s.idBlock.tagNumber){case 0:if(s.idBlock.isConstructed&&s.lenBlock.length>0)return s.error="Type [UNIVERSAL 0] is reserved",{offset:-1,result:s};f=q.EndOfContent;break;case 1:f=q.Boolean;break;case 2:f=q.Integer;break;case 3:f=q.BitString;break;case 4:f=q.OctetString;break;case 5:f=q.Null;break;case 6:f=q.ObjectIdentifier;break;case 10:f=q.Enumerated;break;case 12:f=q.Utf8String;break;case 13:f=q.RelativeObjectIdentifier;break;case 14:f=q.TIME;break;case 15:return s.error="[UNIVERSAL 15] is reserved by ASN.1 standard",{offset:-1,result:s};case 16:f=q.Sequence;break;case 17:f=q.Set;break;case 18:f=q.NumericString;break;case 19:f=q.PrintableString;break;case 20:f=q.TeletexString;break;case 21:f=q.VideotexString;break;case 22:f=q.IA5String;break;case 23:f=q.UTCTime;break;case 24:f=q.GeneralizedTime;break;case 25:f=q.GraphicString;break;case 26:f=q.VisibleString;break;case 27:f=q.GeneralString;break;case 28:f=q.UniversalString;break;case 29:f=q.CharacterString;break;case 30:f=q.BmpString;break;case 31:f=q.DATE;break;case 32:f=q.TimeOfDay;break;case 33:f=q.DateTime;break;case 34:f=q.Duration;break;default:{let h=s.idBlock.isConstructed?new q.Constructed:new q.Primitive;h.idBlock=s.idBlock,h.lenBlock=s.lenBlock,h.warnings=s.warnings,s=h}}break;default:f=s.idBlock.isConstructed?q.Constructed:q.Primitive}return s=F_(s,f),l=s.fromBER(r,e,u,n),s.valueBeforeDecodeView=r.subarray(o,o+s.blockLength),{offset:l,result:s}}function Qh(r,e={}){if(!r.byteLength){let t=new ut({},bt);return t.error="Input buffer has zero length",{offset:-1,result:t}}return ty(he.BufferSourceConverter.toUint8Array(r).slice(),0,r.byteLength,wl(e))}function $_(r,e){return r?1:e}var sn=class extends bt{constructor({value:e=[],isIndefiniteForm:t=!1,...n}={}){super(n),this.value=e,this.isIndefiniteForm=t}fromBER(e,t,n,o){let s=he.BufferSourceConverter.toUint8Array(e),i=o??wl();if(!qn(this,s,t,n))return-1;if(this.valueBeforeDecodeView=s.subarray(t,t+n),this.valueBeforeDecodeView.length===0)return this.warnings.push("Zero buffer length"),t;let a=t;for(;$_(this.isIndefiniteForm,n)>0;){let c=L3(s,a,n,i);if(c.offset===-1)return this.error=c.result.error,this.warnings.concat(c.result.warnings),-1;if(a=c.offset,this.blockLength+=c.result.blockLength,n-=c.result.blockLength,this.value.push(c.result),this.isIndefiniteForm&&c.result.constructor.NAME===hl)break}return this.isIndefiniteForm&&(this.value[this.value.length-1].constructor.NAME===hl?this.value.pop():this.warnings.push("No EndOfContent block encoded")),a}toBER(e,t){let n=t||new fl;for(let o=0;o<this.value.length;o++)this.value[o].toBER(e,n);return t?cn:n.final()}toJSON(){let e={...super.toJSON(),isIndefiniteForm:this.isIndefiniteForm,value:[]};for(let t of this.value)e.value.push(t.toJSON());return e}};sn.NAME="ConstructedValueBlock";var ry,Io=class extends ut{constructor(e={}){super(e,sn),this.idBlock.isConstructed=!0}fromBER(e,t,n,o){this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm;let s=this.valueBlock.fromBER(e,t,this.lenBlock.isIndefiniteForm?n:this.lenBlock.length,o);return s===-1?(this.error=this.valueBlock.error,s):(this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.valueBlock.error.length||(this.blockLength+=this.valueBlock.blockLength),s)}onAsciiEncoding(){let e=[];for(let n of this.valueBlock.value)e.push(n.toString("ascii").split(`
|
|
26
|
+
`),t),n('responded with "na" for "%s"',s)}}var E3=class extends oe{id;remoteAddr;remotePeer;direction;timeline;direct;multiplexer;encryption;limits;log;maConn;muxer;components;outboundStreamProtocolNegotiationTimeout;inboundStreamProtocolNegotiationTimeout;closeTimeout;constructor(e,t){super(),this.components=e,this.id=t.id,this.remoteAddr=t.maConn.remoteAddr,this.remotePeer=t.remotePeer,this.direction=t.direction??"outbound",this.timeline=t.maConn.timeline,this.encryption=t.cryptoProtocol,this.limits=t.limits,this.maConn=t.maConn,this.log=t.maConn.log,this.outboundStreamProtocolNegotiationTimeout=t.outboundStreamProtocolNegotiationTimeout??1e4,this.inboundStreamProtocolNegotiationTimeout=t.inboundStreamProtocolNegotiationTimeout??1e4,this.closeTimeout=t.closeTimeout??1e3,this.direct=Zm(t.maConn.remoteAddr),this.onIncomingStream=this.onIncomingStream.bind(this),this.remoteAddr.getComponents().find(n=>n.code===421)==null&&(this.remoteAddr=this.remoteAddr.encapsulate(`/p2p/${this.remotePeer}`)),t.muxer!=null&&(this.multiplexer=t.muxer.protocol,this.muxer=t.muxer,this.muxer.addEventListener("stream",this.onIncomingStream)),this.maConn.addEventListener("close",n=>{this.dispatchEvent(new eo(n.local,n.error))})}[Symbol.toStringTag]="Connection";[d6]=!0;get streams(){return this.muxer?.streams??[]}get status(){return this.maConn.status}newStream=async(e,t={})=>{if(this.muxer==null)throw new So("Connection is not multiplexed");if(this.muxer.status!=="open")throw new jo(`The connection muxer is "${this.muxer.status}" and not "open"`);if(this.maConn.status!=="open")throw new jo(`The connection is "${this.status}" and not "open"`);if(this.limits!=null&&t?.runOnLimitedConnection!==!0)throw new $a("Cannot open protocol stream on limited connection");Array.isArray(e)||(e=[e]),t.onProgress?.(new Q("connection:open-stream",{connection:this,protocols:e})),this.log.trace("starting new stream for protocols %s",e);let n=await this.muxer.createStream({...t,protocol:e.length===1?e[0]:void 0});this.log.trace("started new stream %s for protocols %s",n.id,e);try{if(t.signal==null){n.log("no abort signal was passed while trying to negotiate protocols %s falling back to default timeout",e);let c=AbortSignal.timeout(this.outboundStreamProtocolNegotiationTimeout);t={...t,signal:c}}n.protocol===""?(n.log.trace("selecting protocol from protocols %s",e),n.protocol=await Zi(n,e,t),n.log("negotiated protocol %s",n.protocol)):n.log("pre-negotiated protocol %s",n.protocol);let o=o_(n.protocol,this.components.registrar,t),s=C9(n.protocol,"outbound",this);if(s>o){let c=new ii(`Too many outbound protocol streams for protocol "${n.protocol}" - ${s}/${o}`);throw n.abort(c),c}await this.components.peerStore.merge(this.remotePeer,{protocols:[n.protocol]}),this.components.metrics?.trackProtocolStream(n);let i=this.components.registrar.getMiddleware(n.protocol),a=await this.runMiddlewareChain(n,this,i);return t.onProgress?.(new Q("connection:opened-stream",{connection:this,stream:a})),a}catch(o){throw n.status==="open"?n.abort(o):this.log.error("could not create new outbound stream on connection %s %a for protocols %s - %e",this.direction==="inbound"?"from":"to",this.remoteAddr,e,o),o}};async onIncomingStream(e){let t=e.detail,n=AbortSignal.timeout(this.inboundStreamProtocolNegotiationTimeout);t.log("start protocol negotiation, timing out after %dms",this.inboundStreamProtocolNegotiationTimeout);try{if(t.protocol===""){let l=this.components.registrar.getProtocols();t.log.trace("selecting protocol from protocols %s",l),t.protocol=await Ji(t,l,{signal:n}),t.log("negotiated protocol %s",t.protocol)}else t.log("pre-negotiated protocol %s",t.protocol);let o=n_(t.protocol,this.components.registrar);if(C9(t.protocol,"inbound",this)>o)throw new Tu(`Too many inbound protocol streams for protocol "${t.protocol}" - limit ${o}`);await this.components.peerStore.merge(this.remotePeer,{protocols:[t.protocol]},{signal:n}),this.components.metrics?.trackProtocolStream(t);let{handler:i,options:a}=this.components.registrar.getHandler(t.protocol);if(this.limits!=null&&a.runOnLimitedConnection!==!0)throw new $a("Cannot open protocol stream on limited connection");let c=this.components.registrar.getMiddleware(t.protocol);c.push(async(l,u,d)=>{await i(l,u),d(l,u)}),await this.runMiddlewareChain(t,this,c)}catch(o){t.abort(o)}}async runMiddlewareChain(e,t,n){for(let o=0;o<n.length;o++){let s=n[o];e.log.trace("running middleware",o,s),await new Promise((i,a)=>{try{let c=s(e,t,(l,u)=>{e=l,t=u,i()});c instanceof Promise&&c.catch(a)}catch(c){a(c)}}),e.log.trace("ran middleware",o,s)}return e}async close(e={}){if(this.log("closing connection to %a",this.remoteAddr),e.signal==null){let t=AbortSignal.timeout(this.closeTimeout);e={...e,signal:t}}await this.muxer?.close(e),await this.maConn.close(e)}abort(e){this.muxer?.abort(e),this.maConn.abort(e)}};function _9(r,e){return new E3(r,e)}function n_(r,e){try{let{options:t}=e.getHandler(r);if(t.maxInboundStreams!=null)return t.maxInboundStreams}catch(t){if(t.name!=="UnhandledProtocolError")throw t}return y3}function o_(r,e,t={}){try{let{options:n}=e.getHandler(r);if(n.maxOutboundStreams!=null)return n.maxOutboundStreams}catch(n){if(n.name!=="UnhandledProtocolError")throw n}return t.maxOutboundStreams??b3}function C9(r,e,t){let n=0;return t.streams.forEach(o=>{o.direction===e&&o.protocol===r&&n++}),n}var rh=class{components;connectionEncrypters;streamMuxers;inboundUpgradeTimeout;inboundStreamProtocolNegotiationTimeout;outboundStreamProtocolNegotiationTimeout;events;metrics;connectionCloseTimeout;constructor(e,t){this.components=e,this.connectionEncrypters=lt({name:"libp2p_upgrader_connection_encrypters",metrics:this.components.metrics}),t.connectionEncrypters.forEach(n=>{this.connectionEncrypters.set(n.protocol,n)}),this.streamMuxers=lt({name:"libp2p_upgrader_stream_multiplexers",metrics:this.components.metrics}),t.streamMuxers.forEach(n=>{this.streamMuxers.set(n.protocol,n)}),this.inboundUpgradeTimeout=t.inboundUpgradeTimeout??1e4,this.inboundStreamProtocolNegotiationTimeout=t.inboundStreamProtocolNegotiationTimeout??1e4,this.outboundStreamProtocolNegotiationTimeout=t.outboundStreamProtocolNegotiationTimeout??1e4,this.connectionCloseTimeout=t.connectionCloseTimeout??1e3,this.events=e.events,this.metrics={dials:e.metrics?.registerCounterGroup("libp2p_connection_manager_dials_total"),errors:e.metrics?.registerCounterGroup("libp2p_connection_manager_dial_errors_total"),inboundErrors:e.metrics?.registerCounterGroup("libp2p_connection_manager_dials_inbound_errors_total"),outboundErrors:e.metrics?.registerCounterGroup("libp2p_connection_manager_dials_outbound_errors_total")}}[Symbol.toStringTag]="@libp2p/upgrader";async shouldBlockConnection(e,...t){let n=this.components.connectionGater[e];if(n==null)return;if(await n.apply(this.components.connectionGater,t)===!0)throw new Lf(`The multiaddr connection is blocked by gater.${e}`)}createInboundAbortSignal(e){let t=me([AbortSignal.timeout(this.inboundUpgradeTimeout),e]);return t}async upgradeInbound(e,t){let n=!1,o=this.createInboundAbortSignal(t.signal);try{if(this.metrics.dials?.increment({inbound:!0}),n=this.components.connectionManager.acceptIncomingConnection(e),!n)throw new Pf("Connection denied");await ke(this.shouldBlockConnection("denyInboundConnection",e),o),await this._performUpgrade(e,"inbound",{...t,signal:o})}catch(s){throw this.metrics.errors?.increment({inbound:!0}),this.metrics.inboundErrors?.increment({[s.name??"Error"]:!0}),s}finally{o.clear(),n&&this.components.connectionManager.afterUpgradeInbound()}}async upgradeOutbound(e,t){try{this.metrics.dials?.increment({outbound:!0});let n=e.remoteAddr.getComponents().findLast(i=>i.code===421)?.value,o;n!=null&&(o=Oe(n),await ke(this.shouldBlockConnection("denyOutboundConnection",o,e),t.signal));let s="outbound";return t.initiator===!1&&(s="inbound"),await this._performUpgrade(e,s,t)}catch(n){throw this.metrics.errors?.increment({outbound:!0}),this.metrics.outboundErrors?.increment({[n.name??"Error"]:!0}),n}}async _performUpgrade(e,t,n){let o=e,s,i,a,c,l=`${parseInt(String(Math.random()*1e9)).toString(36)}${Date.now()}`;if(e.log=e.log.newScope(`${t}:${l}`),this.components.metrics?.trackMultiaddrConnection(e),e.log.trace("starting the %s connection upgrade",t),n?.skipProtection!==!0){let d=this.components.connectionProtector;d!=null&&(e.log("protecting the %s connection",t),o=await d.protect(o,n))}try{if(s_(n)){if(n.remotePeer==null)throw new Gr(`${t} connection that skipped encryption must have a peer id`);c="native",s=n.remotePeer}else{let d=e.remoteAddr.getComponents().findLast(h=>h.code===421)?.value,f;d!=null&&(f=Oe(d)),n?.onProgress?.(new Q(`upgrader:encrypt-${t}-connection`)),{connection:o,remotePeer:s,protocol:c,streamMuxer:i}=await(t==="inbound"?this._encryptInbound(o,{...n,remotePeer:f}):this._encryptOutbound(o,{...n,remotePeer:f}))}if(s.equals(this.components.peerId)){let d=new si("Can not dial self");throw e.abort(d),d}await this.shouldBlockConnection(t==="inbound"?"denyInboundEncryptedConnection":"denyOutboundEncryptedConnection",s,e),n?.muxerFactory!=null?i=n.muxerFactory:i==null&&this.streamMuxers.size>0&&(n?.onProgress?.(new Q(`upgrader:multiplex-${t}-connection`)),i=await(t==="inbound"?this._multiplexInbound(o,this.streamMuxers,n):this._multiplexOutbound(o,this.streamMuxers,n)))}catch(d){throw e.log.error("failed to upgrade %s connection %s %a - %e",t,t==="inbound"?"from":"to",e.remoteAddr,d),d}i!=null&&(e.log("create muxer %s",i.protocol),a=i.createStreamMuxer(o)),await this.shouldBlockConnection(t==="inbound"?"denyInboundUpgradedConnection":"denyOutboundUpgradedConnection",s,e);let u=this._createConnection({id:l,cryptoProtocol:c,direction:t,maConn:e,stream:o,muxer:a,remotePeer:s,limits:n?.limits,closeTimeout:this.connectionCloseTimeout});return u.log("successfully upgraded connection"),u}_createConnection(e){let t=_9(this.components,{...e,outboundStreamProtocolNegotiationTimeout:this.outboundStreamProtocolNegotiationTimeout,inboundStreamProtocolNegotiationTimeout:this.inboundStreamProtocolNegotiationTimeout});return t.addEventListener("close",()=>{this.events.safeDispatchEvent("connection:close",{detail:t})}),this.events.safeDispatchEvent("connection:open",{detail:t}),t}async _encryptInbound(e,t){let n=Array.from(this.connectionEncrypters.keys());try{let o=await Ji(e,n,t),s=this.connectionEncrypters.get(o);if(s==null)throw new $s(`no crypto module found for ${o}`);return e.log("encrypting inbound connection using %s",o),{...await s.secureInbound(e,t),protocol:o}}catch(o){throw new $s(o.message)}}async _encryptOutbound(e,t){let n=Array.from(this.connectionEncrypters.keys());try{e.log.trace("selecting encrypter from %s",n);let o=await Zi(e,n,t),s=this.connectionEncrypters.get(o);if(s==null)throw new $s(`no crypto module found for ${o}`);return e.log("encrypting outbound connection using %s",o),{...await s.secureOutbound(e,t),protocol:o}}catch(o){throw new $s(o.message)}}async _multiplexOutbound(e,t,n){let o=Array.from(t.keys());e.log("outbound selecting muxer %s",o);try{e.log.trace("selecting stream muxer from %s",o);let s=await Zi(e,o,n),i=t.get(s);if(i==null)throw new So(`No muxer configured for protocol "${s}"`);return e.log("selected %s as muxer protocol",s),i}catch(s){throw e.log.error("error multiplexing outbound connection - %e",s),new So(String(s))}}async _multiplexInbound(e,t,n){let o=Array.from(t.keys());e.log("inbound handling muxers %s",o);try{e.log.trace("selecting stream muxer from %s",o);let s=await Ji(e,o,n),i=t.get(s);if(i==null)throw new So(`No muxer configured for protocol "${s}"`);return e.log("selected %s as muxer protocol",s),i}catch(s){throw e.log.error("error multiplexing inbound connection - %e",s),s}}getConnectionEncrypters(){return this.connectionEncrypters}getStreamMuxers(){return this.streamMuxers}};function s_(r){return r.skipEncryption===!0}var nh="3.3.4",oh="js-libp2p";function sh(r,e){return`${r??oh}/${e??nh} browser/${globalThis.navigator.userAgent}`}var al=class extends oe{peerId;peerStore;contentRouting;peerRouting;metrics;services;logger;status;components;log;constructor(e){super(),this.status="stopped";let t=new oe,n=t.dispatchEvent.bind(t);t.dispatchEvent=l=>{let u=n(l),d=this.dispatchEvent(new CustomEvent(l.type,{detail:l.detail}));return u||d},this.peerId=e.peerId,this.logger=e.logger??Li(),this.log=this.logger.forComponent("libp2p"),this.services={};let o=e.nodeInfo?.name??oh,s=e.nodeInfo?.version??nh,i=this.components=a9({peerId:e.peerId,privateKey:e.privateKey,nodeInfo:{name:o,version:s,userAgent:e.nodeInfo?.userAgent??sh(o,s)},logger:this.logger,events:t,datastore:e.datastore??new gf,connectionGater:l9(e.connectionGater),dns:e.dns});e.metrics!=null&&(this.metrics=this.configureComponent("metrics",e.metrics(this.components))),this.peerStore=this.configureComponent("peerStore",r9(i,{addressFilter:this.components.connectionGater.filterMultiaddrForPeer,...e.peerStore})),i.events.addEventListener("peer:update",l=>{if(l.detail.previous==null){let u={id:l.detail.peer.id,multiaddrs:l.detail.peer.addresses.map(d=>d.multiaddr)};i.events.safeDispatchEvent("peer:discovery",{detail:u})}}),e.connectionProtector!=null&&this.configureComponent("connectionProtector",e.connectionProtector(i)),this.components.upgrader=new rh(this.components,{connectionEncrypters:(e.connectionEncrypters??[]).map((l,u)=>this.configureComponent(`connection-encryption-${u}`,l(this.components))),streamMuxers:(e.streamMuxers??[]).map((l,u)=>this.configureComponent(`stream-muxers-${u}`,l(this.components))),inboundUpgradeTimeout:e.connectionManager?.inboundUpgradeTimeout,inboundStreamProtocolNegotiationTimeout:e.connectionManager?.inboundStreamProtocolNegotiationTimeout,outboundStreamProtocolNegotiationTimeout:e.connectionManager?.outboundStreamProtocolNegotiationTimeout,connectionCloseTimeout:e.connectionManager?.connectionCloseTimeout}),this.configureComponent("transportManager",new th(this.components,e.transportManager)),this.configureComponent("connectionManager",new jf(this.components,e.connectionManager)),e.connectionMonitor?.enabled!==!1&&this.configureComponent("connectionMonitor",new Yf(this.components,e.connectionMonitor)),this.configureComponent("registrar",new eh(this.components)),this.configureComponent("addressManager",new xf(this.components,e.addresses));let a=(e.peerRouters??[]).map((l,u)=>this.configureComponent(`peer-router-${u}`,l(this.components)));this.peerRouting=this.components.peerRouting=this.configureComponent("peerRouting",new Zf(this.components,{routers:a}));let c=(e.contentRouters??[]).map((l,u)=>this.configureComponent(`content-router-${u}`,l(this.components)));if(this.contentRouting=this.components.contentRouting=this.configureComponent("contentRouting",new Qf(this.components,{routers:c})),this.configureComponent("randomWalk",new Jf(this.components)),(e.peerDiscovery??[]).forEach((l,u)=>{this.configureComponent(`peer-discovery-${u}`,l(this.components)).addEventListener("peer",f=>{this.#e(f)})}),e.transports?.forEach((l,u)=>{this.components.transportManager.add(this.configureComponent(`transport-${u}`,l(this.components)))}),e.services!=null)for(let l of Object.keys(e.services)){let u=e.services[l],d=u(this.components);if(d==null){this.log.error("service factory %s returned null or undefined instance",l);continue}this.services[l]=d,this.configureComponent(l,d),d[Wo]!=null&&(this.log("registering service %s for content routing",l),c.push(d[Wo])),d[Zo]!=null&&(this.log("registering service %s for peer routing",l),a.push(d[Zo])),d[Xo]!=null&&(this.log("registering service %s for peer discovery",l),d[Xo].addEventListener?.("peer",f=>{this.#e(f)}))}c9(i)}configureComponent(e,t){return t==null&&this.log.error("component %s was null or undefined",e),this.components[e]=t,t}async start(){if(this.status==="stopped"){this.status="starting",this.log("libp2p is starting");try{await this.components.beforeStart?.(),await this.components.start(),await this.components.afterStart?.(),this.status="started",this.safeDispatchEvent("start",{detail:this}),this.log("libp2p has started with peer id %p",this.peerId)}catch(e){throw this.log.error("an error occurred starting libp2p - %e",e),this.status="started",await this.stop(),e}}}async stop(){this.status==="started"&&(this.log("libp2p is stopping"),this.status="stopping",await this.components.beforeStop?.(),await this.components.stop(),await this.components.afterStop?.(),this.status="stopped",this.safeDispatchEvent("stop",{detail:this}),this.log("libp2p has stopped"))}getConnections(e){return this.components.connectionManager.getConnections(e)}getDialQueue(){return this.components.connectionManager.getDialQueue()}getPeers(){let e=new sr;for(let t of this.components.connectionManager.getConnections())e.add(t.remotePeer);return Array.from(e)}async dial(e,t={}){return this.components.connectionManager.openConnection(e,{priority:75,...t})}async dialProtocol(e,t,n={}){if(t==null)throw new x("no protocols were provided to open a stream");if(t=Array.isArray(t)?t:[t],t.length===0)throw new x("no protocols were provided to open a stream");return this.components.connectionManager.openStream(e,t,n)}getMultiaddrs(){return this.components.addressManager.getAddresses()}getProtocols(){return this.components.registrar.getProtocols()}async hangUp(e,t={}){rn(e)&&(e=Oe(e.getComponents().findLast(n=>n.code===421)?.value??"")),await this.components.connectionManager.closeConnections(e,t)}async getPublicKey(e,t={}){if(this.log("getPublicKey %p",e),e.publicKey!=null)return e.publicKey;try{let i=await this.peerStore.get(e,t);if(i.id.publicKey!=null)return i.id.publicKey}catch(i){if(i.name!=="NotFoundError")throw i}let n=Xe([L("/pk/"),e.toMultihash().bytes]),o=await this.contentRouting.get(n,t),s=et(o);return await this.peerStore.patch(e,{publicKey:s},t),s}async handle(e,t,n){Array.isArray(e)||(e=[e]),await Promise.all(e.map(async o=>{await this.components.registrar.handle(o,t,n)}))}async unhandle(e,t){Array.isArray(e)||(e=[e]),await Promise.all(e.map(async n=>{await this.components.registrar.unhandle(n,t)}))}async register(e,t,n){return this.components.registrar.register(e,t,n)}unregister(e){this.components.registrar.unregister(e)}use(e,t){this.components.registrar.use(e,Array.isArray(t)?t:[t])}unuse(e){this.components.registrar.unuse(e)}async isDialable(e,t={}){return this.components.connectionManager.isDialable(e,t)}#e(e){let{detail:t}=e;if(t.id.toString()===this.peerId.toString()){this.log.error("peer discovery mechanism discovered self");return}this.components.peerStore.merge(t.id,{multiaddrs:t.multiaddrs}).catch(n=>{this.log.error("could not update multiaddrs of discovered peer - %e",n)})}};async function L9(r={}){r.privateKey??=await sd("Ed25519");let e=new al({...await L8(r),peerId:_8(r.privateKey)});return r.start!==!1&&await e.start(),e}var i_=["dial","dialProtocol","hangUp","handle","unhandle","getMultiaddrs","getProtocols"];function x3(r){return r==null?!1:r instanceof al?!0:i_.every(e=>typeof r[e]=="function")}function a_(r){return r[Symbol.asyncIterator]!=null}function c_(r,e){let t=0;if(a_(r))return(async function*(){for await(let c of r)yield e(c,t++)})();let n=Ri(r),{value:o,done:s}=n.next();if(s===!0)return(function*(){})();let i=e(o,t++);if(typeof i.then=="function")return(async function*(){yield await i;for(let c of n)yield e(c,t++)})();let a=e;return(function*(){yield i;for(let c of n)yield a(c,t++)})()}var Ur=c_;function v3(r){return{...r,id:r.id.toCID(),routing:"libp2p-router"}}var S3=class{name="libp2p-router";libp2p;constructor(e){this.libp2p=e}async provide(e,t){await this.libp2p.contentRouting.provide(e,t)}async cancelReprovide(e,t){await this.libp2p.contentRouting.cancelReprovide(e,t)}async*findProviders(e,t){yield*Ur(this.libp2p.contentRouting.findProviders(e,t),n=>({...v3(n)}))}async put(e,t,n){await this.libp2p.contentRouting.put(e,t,n)}async get(e,t){return ie(await this.libp2p.contentRouting.get(e,t))}async findPeer(e,t){return v3(await this.libp2p.peerRouting.findPeer(mt(e),t))}async*getClosestPeers(e,t){yield*Ur(this.libp2p.peerRouting.getClosestPeers(e,t),v3)}toString(){return"Libp2pRouter()"}};function P9(r){return new S3(r)}var cl=Uint32Array.from([1732584193,4023233417,2562383102,271733878,3285377520]),Ao=new Uint32Array(80),A3=class extends as{A=cl[0]|0;B=cl[1]|0;C=cl[2]|0;D=cl[3]|0;E=cl[4]|0;constructor(){super(64,20,8,!1)}get(){let{A:e,B:t,C:n,D:o,E:s}=this;return[e,t,n,o,s]}set(e,t,n,o,s){this.A=e|0,this.B=t|0,this.C=n|0,this.D=o|0,this.E=s|0}process(e,t){for(let c=0;c<16;c++,t+=4)Ao[c]=e.getUint32(t,!1);for(let c=16;c<80;c++)Ao[c]=Bu(Ao[c-3]^Ao[c-8]^Ao[c-14]^Ao[c-16],1);let{A:n,B:o,C:s,D:i,E:a}=this;for(let c=0;c<80;c++){let l,u;c<20?(l=Fu(o,s,i),u=1518500249):c<40?(l=o^s^i,u=1859775393):c<60?(l=$u(o,s,i),u=2400959708):(l=o^s^i,u=3395469782);let d=Bu(n,5)+l+a+u+Ao[c]|0;a=i,i=s,s=Bu(o,30),o=n,n=d}n=n+this.A|0,o=o+this.B|0,s=s+this.C|0,i=i+this.D|0,a=a+this.E|0,this.set(n,o,s,i,a)}roundClean(){vt(Ao)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0),vt(this.buffer)}},k9=Za(()=>new A3);function D9(r,e,t,n){Sn(r);let o=t5({dkLen:32,asyncTick:10},n),{c:s,dkLen:i,asyncTick:a}=o;if(Vt(s,"c"),Vt(i,"dkLen"),Vt(a,"asyncTick"),s<1)throw new Error("iterations (c) must be >= 1");if(i<1)throw new Error('"dkLen" must be >= 1');if(i>(2**32-1)*r.outputLen)throw new Error("derived key too long");let c=Np(e,"password"),l=Np(t,"salt"),u=new Uint8Array(i),d=Es.create(r,c),f=d._cloneInto().update(l);return{c:s,dkLen:i,asyncTick:a,DK:u,PRF:d,PRFSalt:f}}function N9(r,e,t,n,o){return r.destroy(),e.destroy(),n&&n.destroy(),vt(o),t}function O9(r,e,t,n){let{c:o,dkLen:s,DK:i,PRF:a,PRFSalt:c}=D9(r,e,t,n),l,u=new Uint8Array(4),d=is(u),f=new Uint8Array(a.outputLen);for(let h=1,m=0;m<s;h++,m+=a.outputLen){let y=i.subarray(m,m+a.outputLen);d.setInt32(0,h,!1),(l=c._cloneInto(l)).update(u).digestInto(f),y.set(f.subarray(0,y.length));for(let g=1;g<o;g++){a._cloneInto(l).update(f).digestInto(f);for(let p=0;p<y.length;p++)y[p]^=f[p]}}return N9(a,c,i,l,f)}async function ih(r,e,t,n){let{c:o,dkLen:s,asyncTick:i,DK:a,PRF:c,PRFSalt:l}=D9(r,e,t,n),u,d=new Uint8Array(4),f=is(d),h=new Uint8Array(c.outputLen);for(let m=1,y=0;y<s;m++,y+=c.outputLen){let g=a.subarray(y,y+c.outputLen);f.setInt32(0,m,!1),(u=l._cloneInto(u)).update(d).digestInto(h),g.set(h.subarray(0,g.length)),await e5(o-1,i,()=>{c._cloneInto(u).update(h).digestInto(h);for(let p=0;p<g.length;p++)g[p]^=h[p]})}return N9(c,l,a,u,h)}var M9={sha1:k9,"sha2-256":pr,"sha2-512":Qr};function ll(r,e,t,n,o){if(o!=="sha1"&&o!=="sha2-256"&&o!=="sha2-512"){let a=Object.keys(M9).join(" / ");throw new x(`Hash '${o}' is unknown or not supported. Must be ${a}`)}let s=M9[o],i=O9(s,r,e,{c:t,dkLen:n});return xn.encode(i).substring(1)}var My=ri(z9(),1);var T3={keyLength:64,iterationCount:1e4,salt:"you should override this value with a crypto secure random number",hash:"sha2-512"};var ea={};se(ea,{create:()=>x_,derivedEmptyPasswordKey:()=>ah});var ah={alg:"A128GCM",ext:!0,k:"scm9jmO_4BJAgdwWGVulLg",key_ops:["encrypt","decrypt"],kty:"oct"};function x_(r){let e=r?.algorithm??"AES-GCM",t=r?.keyLength??16,n=r?.nonceLength??12,o=r?.digest??"SHA-256",s=r?.saltLength??16,i=r?.iterations??32767,a=We.get();t*=8;async function c(d,f){let h=a.getRandomValues(new Uint8Array(s)),m=a.getRandomValues(new Uint8Array(n)),y={name:e,iv:m};typeof f=="string"&&(f=L(f));let g;if(f.length===0){g=await a.subtle.importKey("jwk",ah,{name:"AES-GCM"},!0,["encrypt"]);try{let b={name:"PBKDF2",salt:h,iterations:i,hash:{name:o}},E=await a.subtle.importKey("raw",ie(f),{name:"PBKDF2"},!1,["deriveKey"]);g=await a.subtle.deriveKey(b,E,{name:e,length:t},!0,["encrypt"])}catch{g=await a.subtle.importKey("jwk",ah,{name:"AES-GCM"},!0,["encrypt"])}}else{let b={name:"PBKDF2",salt:h,iterations:i,hash:{name:o}},E=await a.subtle.importKey("raw",ie(f),{name:"PBKDF2"},!1,["deriveKey"]);g=await a.subtle.deriveKey(b,E,{name:e,length:t},!0,["encrypt"])}let p=await a.subtle.encrypt(y,g,ie(d));return Xe([h,y.iv,new Uint8Array(p)])}async function l(d,f){let h=d.subarray(0,s),m=d.subarray(s,s+n),y=d.subarray(s+n),g={name:e,iv:m};typeof f=="string"&&(f=L(f));let p;if(f.length===0)try{let E={name:"PBKDF2",salt:h,iterations:i,hash:{name:o}},v=await a.subtle.importKey("raw",ie(f),{name:"PBKDF2"},!1,["deriveKey"]);p=await a.subtle.deriveKey(E,v,{name:e,length:t},!0,["decrypt"])}catch{p=await a.subtle.importKey("jwk",ah,{name:"AES-GCM"},!0,["decrypt"])}else{let E={name:"PBKDF2",salt:h,iterations:i,hash:{name:o}},v=await a.subtle.importKey("raw",ie(f),{name:"PBKDF2"},!1,["deriveKey"]);p=await a.subtle.deriveKey(E,v,{name:e,length:t},!0,["decrypt"])}let b=await a.subtle.decrypt(g,p,ie(y));return new Uint8Array(b)}return{encrypt:c,decrypt:l}}var he=ri(G9());function Vs(r,e){let t=0;if(r.length===1)return r[0];for(let n=r.length-1;n>=0;n--)t+=r[r.length-1-n]*Math.pow(2,e*n);return t}function To(r,e,t=-1){let n=t,o=r,s=0,i=Math.pow(2,e);for(let a=1;a<8;a++){if(r<i){let c;if(n<0)c=new ArrayBuffer(a),s=a;else{if(n<a)return new ArrayBuffer(0);c=new ArrayBuffer(n),s=n}let l=new Uint8Array(c);for(let u=a-1;u>=0;u--){let d=Math.pow(2,u*e);l[s-u-1]=Math.floor(o/d),o-=l[s-u-1]*d}return c}i*=Math.pow(2,e)}return new ArrayBuffer(0)}function uh(...r){let e=0,t=0;for(let s of r)e+=s.length;let n=new ArrayBuffer(e),o=new Uint8Array(n);for(let s of r)o.set(s,t),t+=s.length;return o}function C3(){let r=new Uint8Array(this.valueHex);if(this.valueHex.byteLength>=2){let a=r[0]===255&&r[1]&128,c=r[0]===0&&(r[1]&128)===0;(a||c)&&this.warnings.push("Needlessly long format")}let e=new ArrayBuffer(this.valueHex.byteLength),t=new Uint8Array(e);for(let a=0;a<this.valueHex.byteLength;a++)t[a]=0;t[0]=r[0]&128;let n=Vs(t,8),o=new ArrayBuffer(this.valueHex.byteLength),s=new Uint8Array(o);for(let a=0;a<this.valueHex.byteLength;a++)s[a]=r[a];return s[0]&=127,Vs(s,8)-n}function W9(r){let e=r<0?r*-1:r,t=128;for(let n=1;n<8;n++){if(e<=t){if(r<0){let i=t-e,a=To(i,8,n),c=new Uint8Array(a);return c[0]|=128,a}let o=To(e,8,n),s=new Uint8Array(o);if(s[0]&128){let i=o.slice(0),a=new Uint8Array(i);o=new ArrayBuffer(o.byteLength+1),s=new Uint8Array(o);for(let c=0;c<i.byteLength;c++)s[c+1]=a[c];s[0]=0}return o}t*=Math.pow(2,8)}return new ArrayBuffer(0)}function j9(r,e){if(r.byteLength!==e.byteLength)return!1;let t=new Uint8Array(r),n=new Uint8Array(e);for(let o=0;o<t.length;o++)if(t[o]!==n[o])return!1;return!0}function Wt(r,e){let t=r.toString(10);if(e<t.length)return"";let n=e-t.length,o=new Array(n);for(let i=0;i<n;i++)o[i]="0";return o.join("").concat(t)}var HX=Math.log(2);function dh(){if(typeof BigInt>"u")throw new Error("BigInt is not defined. Your environment doesn't implement BigInt.")}function _3(r){let e=0,t=0;for(let o=0;o<r.length;o++){let s=r[o];e+=s.byteLength}let n=new Uint8Array(e);for(let o=0;o<r.length;o++){let s=r[o];n.set(new Uint8Array(s),t),t+=s.byteLength}return n.buffer}function qn(r,e,t,n){return e instanceof Uint8Array?e.byteLength?t<0?(r.error="Wrong parameter: inputOffset less than zero",!1):n<0?(r.error="Wrong parameter: inputLength less than zero",!1):e.byteLength-t-n<0?(r.error="End of input reached before message was fully decoded (inconsistent offset and length values)",!1):!0:(r.error="Wrong parameter: inputBuffer has zero length",!1):(r.error="Wrong parameter: inputBuffer must be 'Uint8Array'",!1)}var fl=class{constructor(){this.items=[]}write(e){this.items.push(e)}final(){return _3(this.items)}},ul=[new Uint8Array([1])],Y9="0123456789";var ra="",cn=new ArrayBuffer(0),R3=new Uint8Array(0),hl="EndOfContent",X9="OCTET STRING",Z9="BIT STRING";function zn(r){var e;return e=class extends r{get valueHex(){return this.valueHexView.slice().buffer}set valueHex(n){this.valueHexView=new Uint8Array(n)}constructor(...n){var o;super(...n);let s=n[0]||{};this.isHexOnly=(o=s.isHexOnly)!==null&&o!==void 0?o:!1,this.valueHexView=s.valueHex?he.BufferSourceConverter.toUint8Array(s.valueHex):R3}fromBER(n,o,s,i){let a=n instanceof ArrayBuffer?new Uint8Array(n):n;if(!qn(this,a,o,s))return-1;let c=o+s;return this.valueHexView=a.subarray(o,c),this.valueHexView.length?(this.blockLength=s,c):(this.warnings.push("Zero buffer length"),o)}toBER(n=!1){return this.isHexOnly?n?new ArrayBuffer(this.valueHexView.byteLength):this.valueHexView.byteLength===this.valueHexView.buffer.byteLength?this.valueHexView.buffer:this.valueHexView.slice().buffer:(this.error="Flag 'isHexOnly' is not set, abort",cn)}toJSON(){return{...super.toJSON(),isHexOnly:this.isHexOnly,valueHex:he.Convert.ToHex(this.valueHexView)}}},e.NAME="hexBlock",e}var $n=class{static blockName(){return this.NAME}get valueBeforeDecode(){return this.valueBeforeDecodeView.slice().buffer}set valueBeforeDecode(e){this.valueBeforeDecodeView=new Uint8Array(e)}constructor({blockLength:e=0,error:t=ra,warnings:n=[],valueBeforeDecode:o=R3}={}){this.blockLength=e,this.error=t,this.warnings=n,this.valueBeforeDecodeView=he.BufferSourceConverter.toUint8Array(o)}toJSON(){return{blockName:this.constructor.NAME,blockLength:this.blockLength,error:this.error,warnings:this.warnings,valueBeforeDecode:he.Convert.ToHex(this.valueBeforeDecodeView)}}};$n.NAME="baseBlock";var bt=class extends $n{fromBER(e,t,n,o){throw TypeError("User need to make a specific function in a class which extends 'ValueBlock'")}toBER(e,t){throw TypeError("User need to make a specific function in a class which extends 'ValueBlock'")}};bt.NAME="valueBlock";var fh=class extends zn($n){constructor({idBlock:e={}}={}){var t,n,o,s;super(),e?(this.isHexOnly=(t=e.isHexOnly)!==null&&t!==void 0?t:!1,this.valueHexView=e.valueHex?he.BufferSourceConverter.toUint8Array(e.valueHex):R3,this.tagClass=(n=e.tagClass)!==null&&n!==void 0?n:-1,this.tagNumber=(o=e.tagNumber)!==null&&o!==void 0?o:-1,this.isConstructed=(s=e.isConstructed)!==null&&s!==void 0?s:!1):(this.tagClass=-1,this.tagNumber=-1,this.isConstructed=!1)}toBER(e=!1){let t=0;switch(this.tagClass){case 1:t|=0;break;case 2:t|=64;break;case 3:t|=128;break;case 4:t|=192;break;default:return this.error="Unknown tag class",cn}if(this.isConstructed&&(t|=32),this.tagNumber<31&&!this.isHexOnly){let o=new Uint8Array(1);if(!e){let s=this.tagNumber;s&=31,t|=s,o[0]=t}return o.buffer}if(!this.isHexOnly){let o=To(this.tagNumber,7),s=new Uint8Array(o),i=o.byteLength,a=new Uint8Array(i+1);if(a[0]=t|31,!e){for(let c=0;c<i-1;c++)a[c+1]=s[c]|128;a[i]=s[i-1]}return a.buffer}let n=new Uint8Array(this.valueHexView.byteLength+1);if(n[0]=t|31,!e){let o=this.valueHexView;for(let s=0;s<o.length-1;s++)n[s+1]=o[s]|128;n[this.valueHexView.byteLength]=o[o.length-1]}return n.buffer}fromBER(e,t,n){let o=he.BufferSourceConverter.toUint8Array(e);if(!qn(this,o,t,n))return-1;let s=o.subarray(t,t+n);if(s.length===0)return this.error="Zero buffer length",-1;switch(s[0]&192){case 0:this.tagClass=1;break;case 64:this.tagClass=2;break;case 128:this.tagClass=3;break;case 192:this.tagClass=4;break;default:return this.error="Unknown tag class",-1}this.isConstructed=(s[0]&32)===32,this.isHexOnly=!1;let a=s[0]&31;if(a!==31)this.tagNumber=a,this.blockLength=1;else{let c=0;for(;;){let u=c+1;if(u>=s.length)return this.error="End of input reached before message was fully decoded",-1;if(c++,(s[u]&128)===0)break}this.blockLength=c+1;let l=this.valueHexView=new Uint8Array(c);for(let u=0;u<c;u++)l[u]=s[u+1]&127;this.blockLength<=9?this.tagNumber=Vs(l,7):(this.isHexOnly=!0,this.warnings.push("Tag too long, represented as hex-coded"))}if(this.tagClass===1&&this.isConstructed)switch(this.tagNumber){case 1:case 2:case 5:case 6:case 9:case 13:case 14:case 23:case 24:case 31:case 32:case 33:case 34:return this.error="Constructed encoding used for primitive type",-1}return t+this.blockLength}toJSON(){return{...super.toJSON(),tagClass:this.tagClass,tagNumber:this.tagNumber,isConstructed:this.isConstructed}}};fh.NAME="identificationBlock";var hh=class extends $n{constructor({lenBlock:e={}}={}){var t,n,o;super(),this.isIndefiniteForm=(t=e.isIndefiniteForm)!==null&&t!==void 0?t:!1,this.longFormUsed=(n=e.longFormUsed)!==null&&n!==void 0?n:!1,this.length=(o=e.length)!==null&&o!==void 0?o:0}fromBER(e,t,n){let o=he.BufferSourceConverter.toUint8Array(e);if(!qn(this,o,t,n))return-1;let s=o.subarray(t,t+n);if(s.length===0)return this.error="Zero buffer length",-1;if(s[0]===255)return this.error="Length block 0xFF is reserved by standard",-1;if(this.isIndefiniteForm=s[0]===128,this.isIndefiniteForm)return this.blockLength=1,t+this.blockLength;if(this.longFormUsed=!!(s[0]&128),this.longFormUsed===!1)return this.length=s[0],this.blockLength=1,t+this.blockLength;let i=s[0]&127;if(i>8)return this.error="Too big integer",-1;if(i+1>s.length)return this.error="End of input reached before message was fully decoded",-1;let a=t+1,c=o.subarray(a,a+i);return c[i-1]===0&&this.warnings.push("Needlessly long encoded length"),this.length=Vs(c,8),this.longFormUsed&&this.length<=127&&this.warnings.push("Unnecessary usage of long length form"),this.blockLength=i+1,t+this.blockLength}toBER(e=!1){let t,n;if(this.length>127&&(this.longFormUsed=!0),this.isIndefiniteForm)return t=new ArrayBuffer(1),e===!1&&(n=new Uint8Array(t),n[0]=128),t;if(this.longFormUsed){let o=To(this.length,8);if(o.byteLength>127)return this.error="Too big length",cn;if(t=new ArrayBuffer(o.byteLength+1),e)return t;let s=new Uint8Array(o);n=new Uint8Array(t),n[0]=o.byteLength|128;for(let i=0;i<o.byteLength;i++)n[i+1]=s[i];return t}return t=new ArrayBuffer(1),e===!1&&(n=new Uint8Array(t),n[0]=this.length),t}toJSON(){return{...super.toJSON(),isIndefiniteForm:this.isIndefiniteForm,longFormUsed:this.longFormUsed,length:this.length}}};hh.NAME="lengthBlock";var q={},ut=class extends $n{constructor({name:e=ra,optional:t=!1,primitiveSchema:n,...o}={},s){super(o),this.name=e,this.optional=t,n&&(this.primitiveSchema=n),this.idBlock=new fh(o),this.lenBlock=new hh(o),this.valueBlock=s?new s(o):new bt(o)}fromBER(e,t,n,o){let s=this.valueBlock.fromBER(e,t,this.lenBlock.isIndefiniteForm?n:this.lenBlock.length,o);return s===-1?(this.error=this.valueBlock.error,s):(this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.valueBlock.error.length||(this.blockLength+=this.valueBlock.blockLength),s)}toBER(e,t){let n=t||new fl;t||J9(this);let o=this.idBlock.toBER(e);if(n.write(o),this.lenBlock.isIndefiniteForm)n.write(new Uint8Array([128]).buffer),this.valueBlock.toBER(e,n),n.write(new ArrayBuffer(2));else{let s=this.valueBlock.toBER(e);this.lenBlock.length=s.byteLength;let i=this.lenBlock.toBER(e);n.write(i),n.write(s)}return t?cn:n.final()}toJSON(){let e={...super.toJSON(),idBlock:this.idBlock.toJSON(),lenBlock:this.lenBlock.toJSON(),valueBlock:this.valueBlock.toJSON(),name:this.name,optional:this.optional};return this.primitiveSchema&&(e.primitiveSchema=this.primitiveSchema.toJSON()),e}toString(e="ascii"){return e==="ascii"?this.onAsciiEncoding():he.Convert.ToHex(this.toBER())}onAsciiEncoding(){let e=this.constructor.NAME,t=he.Convert.ToHex(this.valueBlock.valueBeforeDecodeView);return`${e} : ${t}`}isEqual(e){if(this===e)return!0;if(!(e instanceof this.constructor))return!1;let t=this.toBER(),n=e.toBER();return j9(t,n)}};ut.NAME="BaseBlock";function J9(r){var e;if(r instanceof q.Constructed)for(let t of r.valueBlock.value)J9(t)&&(r.lenBlock.isIndefiniteForm=!0);return!!(!((e=r.lenBlock)===null||e===void 0)&&e.isIndefiniteForm)}var ph=class extends ut{getValue(){return this.valueBlock.value}setValue(e){this.valueBlock.value=e}constructor({value:e=ra,...t}={},n){super(t,n),e&&this.fromString(e)}fromBER(e,t,n){let o=this.valueBlock.fromBER(e,t,this.lenBlock.isIndefiniteForm?n:this.lenBlock.length);return o===-1?(this.error=this.valueBlock.error,o):(this.fromBuffer(this.valueBlock.valueHexView),this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.valueBlock.error.length||(this.blockLength+=this.valueBlock.blockLength),o)}onAsciiEncoding(){return`${this.constructor.NAME} : '${this.valueBlock.value}'`}};ph.NAME="BaseStringBlock";var mh=class extends zn(bt){constructor({isHexOnly:e=!0,...t}={}){super(t),this.isHexOnly=e}};mh.NAME="PrimitiveValueBlock";var ey,gh=class extends ut{constructor(e={}){super(e,mh),this.idBlock.isConstructed=!1}};ey=gh;q.Primitive=ey;gh.NAME="PRIMITIVE";var L_=100,P_=1e4,k_=16*1024*1024,D_="Maximum ASN.1 nesting depth exceeded",N_="Maximum ASN.1 node count exceeded",O_="Maximum ASN.1 content length exceeded";function wl(r={}){var e,t,n;return{depth:0,maxDepth:(e=r.maxDepth)!==null&&e!==void 0?e:L_,nodesCount:0,maxNodes:(t=r.maxNodes)!==null&&t!==void 0?t:P_,maxContentLength:(n=r.maxContentLength)!==null&&n!==void 0?n:k_}}function M_(r){let e=new ut({},bt);return e.error=r,{offset:-1,result:e}}function B_(r){if(r.nodesCount+=1,r.nodesCount>r.maxNodes)return N_}function U_(r,e){if(r>e.maxContentLength)return O_}function L3(r,e,t,n){let o=n.depth+1;if(o>n.maxDepth)return M_(D_);n.depth=o;try{return ty(r,e,t,n)}finally{n.depth-=1}}function F_(r,e){if(r instanceof e)return r;let t=new e;return t.idBlock=r.idBlock,t.lenBlock=r.lenBlock,t.warnings=r.warnings,t.valueBeforeDecodeView=r.valueBeforeDecodeView,t}function ty(r,e=0,t=r.length,n=wl()){let o=e,s=new ut({},bt),i=new $n;if(!qn(i,r,e,t))return s.error=i.error,{offset:-1,result:s};if(!r.subarray(e,e+t).length)return s.error="Zero buffer length",{offset:-1,result:s};let c=B_(n);if(c)return s.error=c,{offset:-1,result:s};let l=s.idBlock.fromBER(r,e,t);if(s.idBlock.warnings.length&&s.warnings.concat(s.idBlock.warnings),l===-1)return s.error=s.idBlock.error,{offset:-1,result:s};if(e=l,t-=s.idBlock.blockLength,l=s.lenBlock.fromBER(r,e,t),s.lenBlock.warnings.length&&s.warnings.concat(s.lenBlock.warnings),l===-1)return s.error=s.lenBlock.error,{offset:-1,result:s};e=l,t-=s.lenBlock.blockLength;let u=s.lenBlock.isIndefiniteForm?t:s.lenBlock.length,d=U_(u,n);if(d)return s.error=d,{offset:-1,result:s};if(!s.idBlock.isConstructed&&s.lenBlock.isIndefiniteForm)return s.error="Indefinite length form used for primitive encoding form",{offset:-1,result:s};let f=ut;switch(s.idBlock.tagClass){case 1:if(s.idBlock.tagNumber>=37&&s.idBlock.isHexOnly===!1)return s.error="UNIVERSAL 37 and upper tags are reserved by ASN.1 standard",{offset:-1,result:s};switch(s.idBlock.tagNumber){case 0:if(s.idBlock.isConstructed&&s.lenBlock.length>0)return s.error="Type [UNIVERSAL 0] is reserved",{offset:-1,result:s};f=q.EndOfContent;break;case 1:f=q.Boolean;break;case 2:f=q.Integer;break;case 3:f=q.BitString;break;case 4:f=q.OctetString;break;case 5:f=q.Null;break;case 6:f=q.ObjectIdentifier;break;case 10:f=q.Enumerated;break;case 12:f=q.Utf8String;break;case 13:f=q.RelativeObjectIdentifier;break;case 14:f=q.TIME;break;case 15:return s.error="[UNIVERSAL 15] is reserved by ASN.1 standard",{offset:-1,result:s};case 16:f=q.Sequence;break;case 17:f=q.Set;break;case 18:f=q.NumericString;break;case 19:f=q.PrintableString;break;case 20:f=q.TeletexString;break;case 21:f=q.VideotexString;break;case 22:f=q.IA5String;break;case 23:f=q.UTCTime;break;case 24:f=q.GeneralizedTime;break;case 25:f=q.GraphicString;break;case 26:f=q.VisibleString;break;case 27:f=q.GeneralString;break;case 28:f=q.UniversalString;break;case 29:f=q.CharacterString;break;case 30:f=q.BmpString;break;case 31:f=q.DATE;break;case 32:f=q.TimeOfDay;break;case 33:f=q.DateTime;break;case 34:f=q.Duration;break;default:{let h=s.idBlock.isConstructed?new q.Constructed:new q.Primitive;h.idBlock=s.idBlock,h.lenBlock=s.lenBlock,h.warnings=s.warnings,s=h}}break;default:f=s.idBlock.isConstructed?q.Constructed:q.Primitive}return s=F_(s,f),l=s.fromBER(r,e,u,n),s.valueBeforeDecodeView=r.subarray(o,o+s.blockLength),{offset:l,result:s}}function Qh(r,e={}){if(!r.byteLength){let t=new ut({},bt);return t.error="Input buffer has zero length",{offset:-1,result:t}}return ty(he.BufferSourceConverter.toUint8Array(r).slice(),0,r.byteLength,wl(e))}function $_(r,e){return r?1:e}var sn=class extends bt{constructor({value:e=[],isIndefiniteForm:t=!1,...n}={}){super(n),this.value=e,this.isIndefiniteForm=t}fromBER(e,t,n,o){let s=he.BufferSourceConverter.toUint8Array(e),i=o??wl();if(!qn(this,s,t,n))return-1;if(this.valueBeforeDecodeView=s.subarray(t,t+n),this.valueBeforeDecodeView.length===0)return this.warnings.push("Zero buffer length"),t;let a=t;for(;$_(this.isIndefiniteForm,n)>0;){let c=L3(s,a,n,i);if(c.offset===-1)return this.error=c.result.error,this.warnings.concat(c.result.warnings),-1;if(a=c.offset,this.blockLength+=c.result.blockLength,n-=c.result.blockLength,this.value.push(c.result),this.isIndefiniteForm&&c.result.constructor.NAME===hl)break}return this.isIndefiniteForm&&(this.value[this.value.length-1].constructor.NAME===hl?this.value.pop():this.warnings.push("No EndOfContent block encoded")),a}toBER(e,t){let n=t||new fl;for(let o=0;o<this.value.length;o++)this.value[o].toBER(e,n);return t?cn:n.final()}toJSON(){let e={...super.toJSON(),isIndefiniteForm:this.isIndefiniteForm,value:[]};for(let t of this.value)e.value.push(t.toJSON());return e}};sn.NAME="ConstructedValueBlock";var ry,Io=class extends ut{constructor(e={}){super(e,sn),this.idBlock.isConstructed=!0}fromBER(e,t,n,o){this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm;let s=this.valueBlock.fromBER(e,t,this.lenBlock.isIndefiniteForm?n:this.lenBlock.length,o);return s===-1?(this.error=this.valueBlock.error,s):(this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.valueBlock.error.length||(this.blockLength+=this.valueBlock.blockLength),s)}onAsciiEncoding(){let e=[];for(let n of this.valueBlock.value)e.push(n.toString("ascii").split(`
|
|
27
27
|
`).map(o=>` ${o}`).join(`
|
|
28
28
|
`));let t=this.idBlock.tagClass===3?`[${this.idBlock.tagNumber}]`:this.constructor.NAME;return e.length?`${t} :
|
|
29
29
|
${e.join(`
|
|
@@ -91,7 +91,7 @@ a=end-of-candidates
|
|
|
91
91
|
`:`
|
|
92
92
|
`;try{r.sdp=r.sdp.replace(/\na=ice-ufrag:[^\n]*\n/,`
|
|
93
93
|
a=ice-ufrag:`+e+t).replace(/\na=ice-pwd:[^\n]*\n/,`
|
|
94
|
-
a=ice-pwd:`+e+t)}catch{}return r}var o6=L("libp2p-webrtc-noise:");function cv(r,e,t){let n=r.trim().toLowerCase().replaceAll(":",""),o=L(n,"hex"),s=kt(dt.code,o),i=t6.decode(r6(e)),a=o6.byteLength+s.bytes.byteLength+i.byteLength;return t==="server"?Xe([o6,i,s.bytes],a):Xe([o6,s.bytes,i],a)}function jD(r,e){return r.role==="server"}async function lv(r,e,t,n){let o=r.createDataChannel("",{negotiated:!0,id:0});try{if(n.role==="client"){n.log.trace("client creating local offer");let d=await r.createOffer();n.log.trace("client created local offer %s",d.sdp);let f=n6(d,t);n.log.trace("client setting local offer %s",f.sdp),await r.setLocalDescription(f);let h=sv(n.remoteAddr,t);n.log.trace("client setting server description %s",h.sdp),await r.setRemoteDescription(h)}else{let d=iv(n.remoteAddr,t);n.log.trace("server setting client %s %s",d.type,d.sdp),await r.setRemoteDescription(d),n.log.trace("server creating local answer");let f=await r.createAnswer();n.log.trace("server created local answer");let h=n6(f,t);n.log.trace("server setting local description %s",f.sdp),await r.setLocalDescription(h)}if(o.readyState!=="open"&&(n.log.trace("%s wait for handshake channel to open, starting status %s",n.role,o.readyState),await Xn(o,"open",n)),n.log.trace("%s handshake channel opened",n.role),jD(n,r)){let d=r.remoteFingerprint()?.value??"";n.remoteAddr=n.remoteAddr.encapsulate(ov(d))}let s=nv(r.localDescription?.sdp);if(s==null)throw new zo("Could not get fingerprint from local description sdp");n.log.trace("%s performing noise handshake",n.role);let i=cv(s,n.remoteAddr,n.role),a=h1({prologueBytes:i})(n),c=yu({channel:o,direction:"outbound",isHandshake:!0,log:n.log,...n.dataChannel??{}}),l=bu({peerConnection:r,remoteAddr:n.remoteAddr,metrics:n.events,direction:n.role==="client"?"outbound":"inbound",log:n.logger.forComponent("libp2p:webrtc-direct:connection")});if(r.addEventListener("connectionstatechange",()=>{switch(r.connectionState){case"failed":case"disconnected":case"closed":l.close().catch(d=>{n.log.error("error closing connection - %e",d),l.abort(d)});break;default:break}}),n.events?.increment({peer_connection:!0}),n.role==="client"){n.log.trace("%s secure inbound",n.role);let d=await a.secureInbound(c,{remotePeer:n.remotePeer,signal:n.signal,skipStreamMuxerNegotiation:!0});return n.log.trace("%s upgrade outbound",n.role),await n.upgrader.upgradeOutbound(l,{skipProtection:!0,skipEncryption:!0,remotePeer:d.remotePeer,muxerFactory:e,signal:n.signal})}n.log.trace("%s secure outbound",n.role);let u=await a.secureOutbound(c,{remotePeer:n.remotePeer,signal:n.signal,skipStreamMuxerNegotiation:!0});l.remoteAddr=l.remoteAddr.encapsulate(`/p2p/${u.remotePeer}`),n.log.trace("%s upgrade inbound",n.role),await n.upgrader.upgradeInbound(l,{skipProtection:!0,skipEncryption:!0,remotePeer:u.remotePeer,muxerFactory:e,signal:n.signal})}catch(s){throw o.close(),r.close(),s}}async function uv(r,e,t={}){let n=t.certificate;n==null&&(n=await RTCPeerConnection.generateCertificate({name:"ECDSA",namedCurve:"P-256"}));let o=typeof t.rtcConfiguration=="function"?await t.rtcConfiguration():t.rtcConfiguration,s=new RTCPeerConnection({...o??{},certificates:[n]}),i=new qo({peerConnection:s,metrics:t.events,dataChannelOptions:t.dataChannel});return{peerConnection:s,muxerFactory:i}}var ip=class{log;metrics;components;init;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:webrtc-direct"),this.components=e,this.init=t,e.metrics!=null&&(this.metrics={dialerEvents:e.metrics.registerCounterGroup("libp2p_webrtc-direct_dialer_events_total",{label:"event",help:"Total count of WebRTC-direct dial events by type"})})}[to]=!0;[Symbol.toStringTag]="@libp2p/webrtc-direct";[ue]=["@libp2p/transport"];async dial(e,t){this.log("dial %a",e),t.signal.throwIfAborted();let n,o=e.getComponents().findLast(c=>c.code===421)?.value;o!=null&&(n=Oe(o));let s=Xx(),{peerConnection:i,muxerFactory:a}=await uv("client",s,{rtcConfiguration:typeof this.init.rtcConfiguration=="function"?await this.init.rtcConfiguration():this.init.rtcConfiguration??{},dataChannel:this.init.dataChannel});try{return await lv(i,a,s,{role:"client",log:this.log,logger:this.components.logger,events:this.metrics?.dialerEvents,signal:t.signal,remoteAddr:e,dataChannel:this.init.dataChannel,upgrader:t.upgrader,peerId:this.components.peerId,remotePeer:n,privateKey:this.components.privateKey})}catch(c){throw i.close(),c}}createListener(e){throw new ep("WebRTCDirectTransport.createListener")}listenFilter(e){return[]}dialFilter(e){return e.filter(Uc.exactMatch)}};function dv(r){return e=>new ip(e,r)}function fv(r){return e=>new sp(e,r)}var YD=r=>{let e=r.addEventListener||r.on||r.addListener,t=r.removeEventListener||r.off||r.removeListener;if(!e||!t)throw new TypeError("Emitter is not compatible");return{addListener:e.bind(r),removeListener:t.bind(r)}};function QD(r,e,t){let n,o=new Promise((s,i)=>{if(t={rejectionEvents:["error"],multiArgs:!1,rejectionMultiArgs:!1,resolveImmediately:!1,...t},!(t.count>=0&&(t.count===Number.POSITIVE_INFINITY||Number.isInteger(t.count))))throw new TypeError("The `count` option should be at least 0 or more");t.signal?.throwIfAborted();let a=[e].flat(),c=[],{addListener:l,removeListener:u}=YD(r),d=async(...h)=>{let m=t.multiArgs?h:h[0];if(t.filter)try{if(!await t.filter(m))return}catch(y){n(),i(y);return}c.push(m),t.count===c.length&&(n(),s(c))},f=(...h)=>{n(),i(t.rejectionMultiArgs?h:h[0])};n=()=>{for(let h of a)u(h,d);for(let h of t.rejectionEvents)a.includes(h)||u(h,f)};for(let h of a)l(h,d);for(let h of t.rejectionEvents)a.includes(h)||l(h,f);t.signal&&t.signal.addEventListener("abort",()=>{f(t.signal.reason)},{once:!0}),t.resolveImmediately&&s(c)});if(o.cancel=n,typeof t.timeout=="number"){let s=Ot(o,{milliseconds:t.timeout});return s.cancel=()=>{n(),s.clear()},s}return o}function hv(r,e,t){typeof t=="function"&&(t={filter:t}),t={...t,count:1,resolveImmediately:!1};let n=QD(r,e,t),o=n.then(s=>s[0]);return o.cancel=n.cancel,o}function pv(){throw new Error("WebSocket Servers can not be created in the browser!")}var XD=1024*1024*4,ZD=10,s6=class extends bo{websocket;maxBufferedAmount;checkBufferedAmountTask;constructor(e){super(e),this.websocket=e.websocket,this.maxBufferedAmount=e.maxBufferedAmount??XD,this.checkBufferedAmountTask=Wi(this.checkBufferedAmount.bind(this),e.bufferedAmountPollInterval??ZD),this.websocket.addEventListener("close",t=>{if(this.log('closed - code %d, reason "%s", wasClean %s',t.code,t.reason,t.wasClean),this.checkBufferedAmountTask.stop(),!t.wasClean){this.onRemoteReset();return}this.onTransportClosed()},{once:!0}),this.websocket.addEventListener("message",t=>{try{let n;if(typeof t.data=="string")n=L(t.data);else if(t.data instanceof ArrayBuffer)n=new Uint8Array(t.data,0,t.data.byteLength);else{this.abort(new Error("Incorrect binary type"));return}this.onData(n)}catch(n){this.log.error("error receiving data - %e",n)}})}sendData(e){for(let n of e)this.websocket.send(ie(n));let t=this.websocket.bufferedAmount<this.maxBufferedAmount;return t||this.checkBufferedAmountTask.start(),{sentBytes:e.byteLength,canSendMore:t}}sendReset(){this.websocket.close(1006)}async sendClose(e){this.websocket.close(),e?.signal?.throwIfAborted()}sendPause(){}sendResume(){}checkBufferedAmount(){this.log("buffered amount now %d",this.websocket.bufferedAmount),this.websocket.bufferedAmount===0&&(this.checkBufferedAmountTask.stop(),this.safeDispatchEvent("drain"))}};function mv(r){return new s6(r)}var i6=class{log;init;logger;metrics;components;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:websockets"),this.logger=e.logger,this.components=e,this.init=t,e.metrics!=null&&(this.metrics={dialerEvents:e.metrics.registerCounterGroup("libp2p_websockets_dialer_events_total",{label:"event",help:"Total count of WebSockets dialer events by type"})})}[to]=!0;[Symbol.toStringTag]="@libp2p/websockets";[ue]=["@libp2p/transport"];async dial(e,t){this.log("dialing %s",e),t=t??{};let n=mv({websocket:await this._connect(e,t),remoteAddr:e,metrics:this.metrics?.dialerEvents,direction:"outbound",log:this.components.logger.forComponent("libp2p:websockets:connection"),maxBufferedAmount:this.init.maxBufferedAmount,bufferedAmountPollInterval:this.init.bufferedAmountPollInterval});this.log("new outbound connection %s",n.remoteAddr);let o=await t.upgrader.upgradeOutbound(n,t);return this.log("outbound connection %s upgraded",n.remoteAddr),o}async _connect(e,t){t?.signal?.throwIfAborted();let n=q1(e);this.log("create websocket connection to %s",n);let o=new WebSocket(n);o.binaryType="arraybuffer";try{t.onProgress?.(new Q("websockets:open-connection")),await hv(o,"open",t)}catch(s){if(t.signal?.aborted)throw this.metrics?.dialerEvents.increment({abort:!0}),new ni(`Could not connect to ${n}`);this.metrics?.dialerEvents.increment({error:!0});try{o.close()}catch{}throw s}return this.log("connected %s",e),this.metrics?.dialerEvents.increment({connect:!0}),o}createListener(e){return pv({logger:this.logger,events:this.components.events,metrics:this.components.metrics},{...this.init,...e})}listenFilter(e){return e.filter(t=>kn.exactMatch(t)||Ds.exactMatch(t))}dialFilter(e){return this.listenFilter(e)}};function gv(r={}){return e=>new i6(e,r)}var yv={list:["/dnsaddr/bootstrap.libp2p.io/p2p/QmNnooDu7bfjPFoTZYxMNLWUQJyrVwtbZg5gBMjTezGAJN","/dnsaddr/bootstrap.libp2p.io/p2p/QmbLHAnMoJPWSCR5Zhtx6BHJX9KiKNN6tpvbUcqanj75Nb","/dnsaddr/bootstrap.libp2p.io/p2p/QmcZf59bWwK5XFi76CZX8cbJ4BhTzzA3gU1ZjYZcYW3dwt","/dnsaddr/va1.bootstrap.libp2p.io/p2p/12D3KooWKnDdG3iXw9eTFijk3EWSunZcFi54Zka4wmtqtt6rPxc8","/ip4/104.131.131.82/tcp/4001/p2p/QmaCpDMGvV2BGHeYERUEnRQAwe3N8SzbUtfsmvsqQLuvuJ"]};function ap(r={}){let e;return r.name!=null&&r.version!=null&&(e=`${r.name}/${r.version} ${sh()}`),{privateKey:r.privateKey,dns:r.dns,nodeInfo:{userAgent:e},addresses:{listen:["/p2p-circuit","/webrtc"]},transports:[xw(),fv(),dv(),gv()],connectionEncrypters:[h1()],streamMuxers:[ew(),Fx()],peerDiscovery:[uw(yv)],services:{autoNAT:lw(),dcutr:Aw(),delegatedContentRouting:ow(_1()),delegatedPeerRouting:sw(_1()),dht:Nx({clientMode:!0}),identify:ex(),identifyPush:tx(),keychain:Jh(r.keychain),ping:zx(),http:WE()}}}async function bv(r,e){let t=e??{};t.privateKey==null&&e.datastore!=null&&(t.privateKey=await O3(e.datastore,e.keychain));let n=ap({...t,name:t.nodeInfo?.name??r.info.name,version:t.nodeInfo?.version??r.info.version});return n.datastore=n.datastore??e.datastore,await L9({...n,...t})}async function JD(r,e){return x3(e)?e:bv(r,{...e,dns:r.dns,logger:r.logger,datastore:r.datastore})}function eN(r,e){let t;Object.defineProperty(r,"libp2p",{configurable:!0,enumerable:!0,get(){if(t!=null)return t;throw new xr}});let n={name:"libp2p",start:async o=>{if(t==null){t=await JD(o,e);let s=o.routing.findProviders.bind(o.routing);o.routing.findProviders=async function*(c,l){yield*K2(s.call(o.routing,c,l),async u=>{if(u.router!=="libp2p-router"){let d=a6(u);await t.peerStore.merge(d.id,d)}})};let i=o.routing.findPeer.bind(o.routing);o.routing.findPeer=async function(c,l){let u=await i(c,l);if(u.router!=="libp2p-router"){let d=a6(u);await t.peerStore.merge(d.id,d)}return u};let a=o.routing.getClosestPeers.bind(o.routing);o.routing.getClosestPeers=async function*(c,l){yield*K2(a.call(o.routing,c,l),async u=>{if(u.router!=="libp2p-router"){let d=a6(u);await t.peerStore.merge(d.id,d)}})}}try{o.hasRouter("libp2p-router")||o.addRouter(P9(t)),x3(o.libp2p)&&await o.libp2p.start()}catch(s){if(s.name!=="NotStartedError")throw s}},stop:async()=>{await t?.stop()}};return r.addMixin(n),r}function a6(r){return{id:mt(r.id),multiaddrs:r.multiaddrs}}return Av(tN);})();
|
|
94
|
+
a=ice-pwd:`+e+t)}catch{}return r}var o6=L("libp2p-webrtc-noise:");function cv(r,e,t){let n=r.trim().toLowerCase().replaceAll(":",""),o=L(n,"hex"),s=kt(dt.code,o),i=t6.decode(r6(e)),a=o6.byteLength+s.bytes.byteLength+i.byteLength;return t==="server"?Xe([o6,i,s.bytes],a):Xe([o6,s.bytes,i],a)}function jD(r,e){return r.role==="server"}async function lv(r,e,t,n){let o=r.createDataChannel("",{negotiated:!0,id:0});try{if(n.role==="client"){n.log.trace("client creating local offer");let d=await r.createOffer();n.log.trace("client created local offer %s",d.sdp);let f=n6(d,t);n.log.trace("client setting local offer %s",f.sdp),await r.setLocalDescription(f);let h=sv(n.remoteAddr,t);n.log.trace("client setting server description %s",h.sdp),await r.setRemoteDescription(h)}else{let d=iv(n.remoteAddr,t);n.log.trace("server setting client %s %s",d.type,d.sdp),await r.setRemoteDescription(d),n.log.trace("server creating local answer");let f=await r.createAnswer();n.log.trace("server created local answer");let h=n6(f,t);n.log.trace("server setting local description %s",f.sdp),await r.setLocalDescription(h)}if(o.readyState!=="open"&&(n.log.trace("%s wait for handshake channel to open, starting status %s",n.role,o.readyState),await Xn(o,"open",n)),n.log.trace("%s handshake channel opened",n.role),jD(n,r)){let d=r.remoteFingerprint()?.value??"";n.remoteAddr=n.remoteAddr.encapsulate(ov(d))}let s=nv(r.localDescription?.sdp);if(s==null)throw new zo("Could not get fingerprint from local description sdp");n.log.trace("%s performing noise handshake",n.role);let i=cv(s,n.remoteAddr,n.role),a=h1({prologueBytes:i})(n),c=yu({channel:o,direction:"outbound",isHandshake:!0,log:n.log,...n.dataChannel??{}}),l=bu({peerConnection:r,remoteAddr:n.remoteAddr,metrics:n.events,direction:n.role==="client"?"outbound":"inbound",log:n.logger.forComponent("libp2p:webrtc-direct:connection")});if(r.addEventListener("connectionstatechange",()=>{switch(r.connectionState){case"failed":case"disconnected":case"closed":l.close().catch(d=>{n.log.error("error closing connection - %e",d),l.abort(d)});break;default:break}}),n.events?.increment({peer_connection:!0}),n.role==="client"){n.log.trace("%s secure inbound",n.role);let d=await a.secureInbound(c,{remotePeer:n.remotePeer,signal:n.signal,skipStreamMuxerNegotiation:!0});return n.log.trace("%s upgrade outbound",n.role),await n.upgrader.upgradeOutbound(l,{skipProtection:!0,skipEncryption:!0,remotePeer:d.remotePeer,muxerFactory:e,signal:n.signal})}n.log.trace("%s secure outbound",n.role);let u=await a.secureOutbound(c,{remotePeer:n.remotePeer,signal:n.signal,skipStreamMuxerNegotiation:!0});l.remoteAddr=l.remoteAddr.encapsulate(`/p2p/${u.remotePeer}`),n.log.trace("%s upgrade inbound",n.role),await n.upgrader.upgradeInbound(l,{skipProtection:!0,skipEncryption:!0,remotePeer:u.remotePeer,muxerFactory:e,signal:n.signal})}catch(s){throw o.close(),r.close(),s}}async function uv(r,e,t={}){let n=t.certificate;n==null&&(n=await RTCPeerConnection.generateCertificate({name:"ECDSA",namedCurve:"P-256"}));let o=typeof t.rtcConfiguration=="function"?await t.rtcConfiguration():t.rtcConfiguration,s=new RTCPeerConnection({...o??{},certificates:[n]}),i=new qo({peerConnection:s,metrics:t.events,dataChannelOptions:t.dataChannel});return{peerConnection:s,muxerFactory:i}}var ip=class{log;metrics;components;init;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:webrtc-direct"),this.components=e,this.init=t,e.metrics!=null&&(this.metrics={dialerEvents:e.metrics.registerCounterGroup("libp2p_webrtc-direct_dialer_events_total",{label:"event",help:"Total count of WebRTC-direct dial events by type"})})}[to]=!0;[Symbol.toStringTag]="@libp2p/webrtc-direct";[ue]=["@libp2p/transport"];async dial(e,t){this.log("dial %a",e),t.signal.throwIfAborted();let n,o=e.getComponents().findLast(c=>c.code===421)?.value;o!=null&&(n=Oe(o));let s=Xx(),{peerConnection:i,muxerFactory:a}=await uv("client",s,{rtcConfiguration:typeof this.init.rtcConfiguration=="function"?await this.init.rtcConfiguration():this.init.rtcConfiguration??{},dataChannel:this.init.dataChannel});try{return await lv(i,a,s,{role:"client",log:this.log,logger:this.components.logger,events:this.metrics?.dialerEvents,signal:t.signal,remoteAddr:e,dataChannel:this.init.dataChannel,upgrader:t.upgrader,peerId:this.components.peerId,remotePeer:n,privateKey:this.components.privateKey})}catch(c){throw i.close(),c}}createListener(e){throw new ep("WebRTCDirectTransport.createListener")}listenFilter(e){return[]}dialFilter(e){return e.filter(Uc.exactMatch)}};function dv(r){return e=>new ip(e,r)}function fv(r){return e=>new sp(e,r)}var YD=r=>{let e=r.addEventListener||r.on||r.addListener,t=r.removeEventListener||r.off||r.removeListener;if(!e||!t)throw new TypeError("Emitter is not compatible");return{addListener:e.bind(r),removeListener:t.bind(r)}};function QD(r,e,t){let n,o=new Promise((s,i)=>{if(t={rejectionEvents:["error"],multiArgs:!1,rejectionMultiArgs:!1,resolveImmediately:!1,...t},!(t.count>=0&&(t.count===Number.POSITIVE_INFINITY||Number.isInteger(t.count))))throw new TypeError("The `count` option should be at least 0 or more");t.signal?.throwIfAborted();let a=[e].flat(),c=[],{addListener:l,removeListener:u}=YD(r),d=async(...h)=>{let m=t.multiArgs?h:h[0];if(t.filter)try{if(!await t.filter(m))return}catch(y){n(),i(y);return}c.push(m),t.count===c.length&&(n(),s(c))},f=(...h)=>{n(),i(t.rejectionMultiArgs?h:h[0])};n=()=>{for(let h of a)u(h,d);for(let h of t.rejectionEvents)a.includes(h)||u(h,f)};for(let h of a)l(h,d);for(let h of t.rejectionEvents)a.includes(h)||l(h,f);t.signal&&t.signal.addEventListener("abort",()=>{f(t.signal.reason)},{once:!0}),t.resolveImmediately&&s(c)});if(o.cancel=n,typeof t.timeout=="number"){let s=Ot(o,{milliseconds:t.timeout});return s.cancel=()=>{n(),s.clear()},s}return o}function hv(r,e,t){typeof t=="function"&&(t={filter:t}),t={...t,count:1,resolveImmediately:!1};let n=QD(r,e,t),o=n.then(s=>s[0]);return o.cancel=n.cancel,o}function pv(){throw new Error("WebSocket Servers can not be created in the browser!")}var XD=1024*1024*4,ZD=10,s6=class extends bo{websocket;maxBufferedAmount;checkBufferedAmountTask;constructor(e){super(e),this.websocket=e.websocket,this.maxBufferedAmount=e.maxBufferedAmount??XD,this.checkBufferedAmountTask=Wi(this.checkBufferedAmount.bind(this),e.bufferedAmountPollInterval??ZD),this.websocket.addEventListener("close",t=>{if(this.log('closed - code %d, reason "%s", wasClean %s',t.code,t.reason,t.wasClean),this.checkBufferedAmountTask.stop(),!t.wasClean){this.onRemoteReset();return}this.onTransportClosed()},{once:!0}),this.websocket.addEventListener("message",t=>{try{let n;if(typeof t.data=="string")n=L(t.data);else if(t.data instanceof ArrayBuffer)n=new Uint8Array(t.data,0,t.data.byteLength);else{this.abort(new Error("Incorrect binary type"));return}this.onData(n)}catch(n){this.log.error("error receiving data - %e",n)}})}sendData(e){for(let n of e)this.websocket.send(ie(n));let t=this.websocket.bufferedAmount<this.maxBufferedAmount;return t||this.checkBufferedAmountTask.start(),{sentBytes:e.byteLength,canSendMore:t}}sendReset(){this.websocket.close(1006)}async sendClose(e){this.websocket.close(),e?.signal?.throwIfAborted()}sendPause(){}sendResume(){}checkBufferedAmount(){this.log("buffered amount now %d",this.websocket.bufferedAmount),this.websocket.bufferedAmount===0&&(this.checkBufferedAmountTask.stop(),this.safeDispatchEvent("drain"))}};function mv(r){return new s6(r)}var i6=class{log;init;logger;metrics;components;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:websockets"),this.logger=e.logger,this.components=e,this.init=t,e.metrics!=null&&(this.metrics={dialerEvents:e.metrics.registerCounterGroup("libp2p_websockets_dialer_events_total",{label:"event",help:"Total count of WebSockets dialer events by type"})})}[to]=!0;[Symbol.toStringTag]="@libp2p/websockets";[ue]=["@libp2p/transport"];async dial(e,t){this.log("dialing %s",e),t=t??{};let n=mv({websocket:await this._connect(e,t),remoteAddr:e,metrics:this.metrics?.dialerEvents,direction:"outbound",log:this.components.logger.forComponent("libp2p:websockets:connection"),maxBufferedAmount:this.init.maxBufferedAmount,bufferedAmountPollInterval:this.init.bufferedAmountPollInterval});this.log("new outbound connection %s",n.remoteAddr);let o=await t.upgrader.upgradeOutbound(n,t);return this.log("outbound connection %s upgraded",n.remoteAddr),o}async _connect(e,t){t?.signal?.throwIfAborted();let n=q1(e);this.log("create websocket connection to %s",n);let o=new WebSocket(n);o.binaryType="arraybuffer";try{t.onProgress?.(new Q("websockets:open-connection")),await hv(o,"open",t)}catch(s){if(t.signal?.aborted)throw this.metrics?.dialerEvents.increment({abort:!0}),new ni(`Could not connect to ${n}`);this.metrics?.dialerEvents.increment({error:!0});try{o.close()}catch{}throw s}return this.log("connected %s",e),this.metrics?.dialerEvents.increment({connect:!0}),o}createListener(e){return pv({logger:this.logger,events:this.components.events,metrics:this.components.metrics},{...this.init,...e})}listenFilter(e){return e.filter(t=>kn.exactMatch(t)||Ds.exactMatch(t))}dialFilter(e){return this.listenFilter(e)}};function gv(r={}){return e=>new i6(e,r)}var yv={list:["/dnsaddr/bootstrap.libp2p.io/p2p/QmNnooDu7bfjPFoTZYxMNLWUQJyrVwtbZg5gBMjTezGAJN","/dnsaddr/bootstrap.libp2p.io/p2p/QmbLHAnMoJPWSCR5Zhtx6BHJX9KiKNN6tpvbUcqanj75Nb","/dnsaddr/bootstrap.libp2p.io/p2p/QmcZf59bWwK5XFi76CZX8cbJ4BhTzzA3gU1ZjYZcYW3dwt","/dnsaddr/va1.bootstrap.libp2p.io/p2p/12D3KooWKnDdG3iXw9eTFijk3EWSunZcFi54Zka4wmtqtt6rPxc8","/ip4/104.131.131.82/tcp/4001/p2p/QmaCpDMGvV2BGHeYERUEnRQAwe3N8SzbUtfsmvsqQLuvuJ"]};function ap(r={}){let e;return r.name!=null&&r.version!=null&&(e=`${r.name}/${r.version} ${sh()}`),{privateKey:r.privateKey,dns:r.dns,nodeInfo:{userAgent:e},addresses:{listen:["/p2p-circuit","/webrtc"]},transports:[xw(),fv(),dv(),gv()],connectionEncrypters:[h1()],streamMuxers:[ew(),Fx()],peerDiscovery:[uw(yv)],services:{autoNAT:lw(),dcutr:Aw(),delegatedContentRouting:ow(_1()),delegatedPeerRouting:sw(_1()),dht:Nx({clientMode:!0}),identify:ex(),identifyPush:tx(),keychain:Jh(r.keychain),ping:zx(),http:WE()}}}async function bv(r,e){let t=e??{};t.privateKey==null&&e.datastore!=null&&(t.privateKey=await O3(e.datastore,e.keychain));let n=ap({...t,name:t.nodeInfo?.name??r.info.name,version:t.nodeInfo?.version??r.info.version});return n.datastore=n.datastore??e.datastore,await L9({...n,...t})}async function JD(r,e){return x3(e)?e:bv(r,{...e,dns:r.dns,logger:r.logger,datastore:r.datastore})}function eN(r,e){let t;Object.defineProperty(r,"libp2p",{configurable:!0,enumerable:!0,get(){if(t!=null)return t;throw new xr}});let n={name:"libp2p",start:async o=>{if(t==null){t=await JD(o,e);let s=o.routing.findProviders.bind(o.routing);o.routing.findProviders=async function*(c,l){yield*K2(s.call(o.routing,c,l),async u=>{if(u.routing!=="libp2p-router"){let d=a6(u);await t.peerStore.merge(d.id,d)}})};let i=o.routing.findPeer.bind(o.routing);o.routing.findPeer=async function(c,l){let u=await i(c,l);if(u.routing!=="libp2p-router"){let d=a6(u);await t.peerStore.merge(d.id,d)}return u};let a=o.routing.getClosestPeers.bind(o.routing);o.routing.getClosestPeers=async function*(c,l){yield*K2(a.call(o.routing,c,l),async u=>{if(u.routing!=="libp2p-router"){let d=a6(u);await t.peerStore.merge(d.id,d)}})}}try{o.hasRouter("libp2p-router")||o.addRouter(P9(t)),x3(o.libp2p)&&await o.libp2p.start()}catch(s){if(s.name!=="NotStartedError")throw s}},stop:async()=>{await t?.stop()}};return r.addMixin(n),r}function a6(r){return{id:mt(r.id),multiaddrs:r.multiaddrs}}return Av(tN);})();
|
|
95
95
|
/*! Bundled license information:
|
|
96
96
|
|
|
97
97
|
pvtsutils/build/index.js:
|