helia 6.0.15 → 6.0.16

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.min.js CHANGED
@@ -107,7 +107,7 @@ a=end-of-candidates
107
107
  `;try{r.sdp=r.sdp.replace(/\na=ice-ufrag:[^\n]*\n/,`
108
108
  a=ice-ufrag:`+e+t).replace(/\na=ice-pwd:[^\n]*\n/,`
109
109
  a=ice-pwd:`+e+t)}catch{}return r}var Bv=B("libp2p-webrtc-noise:");function rN(r,e,t){let n=r.trim().toLowerCase().replaceAll(":",""),o=B(n,"hex"),i=zr(St.code,o),s=Dv.decode(Nv(e)),a=Bv.byteLength+i.bytes.byteLength+s.byteLength;return t==="server"?gt([Bv,s,i.bytes],a):gt([Bv,i.bytes,s],a)}var zW=j3?"iceconnectionstatechange":"connectionstatechange";function GW(r,e){return r.role==="server"}async function nN(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 u=await r.createOffer();n.log.trace("client created local offer %s",u.sdp);let d=Lv(u,t);n.log.trace("client setting local offer %s",d.sdp),await r.setLocalDescription(d);let h=JD(n.remoteAddr,t);n.log.trace("client setting server description %s",h.sdp),await r.setRemoteDescription(h)}else{let u=eN(n.remoteAddr,t);n.log.trace("server setting client %s %s",u.type,u.sdp),await r.setRemoteDescription(u),n.log.trace("server creating local answer");let d=await r.createAnswer();n.log.trace("server created local answer");let h=Lv(d,t);n.log.trace("server setting local description %s",d.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 ds(o,"open",n)),n.log.trace("%s handshake channel opened",n.role),GW(n,r)){let u=r.remoteFingerprint()?.value??"";n.remoteAddr=n.remoteAddr.encapsulate(ZD(u))}let i=QD(r.localDescription?.sdp);if(i==null)throw new ga("Could not get fingerprint from local description sdp");n.log.trace("%s performing noise handshake",n.role);let s=rN(i,n.remoteAddr,n.role),a=py({prologueBytes:s})(n),c=Rp({channel:o,direction:"outbound",isHandshake:!0,log:n.log,...n.dataChannel??{}}),l=Dp({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(zW,()=>{switch(r.connectionState){case"failed":case"disconnected":case"closed":l.close().catch(u=>{n.log.error("error closing connection - %e",u),l.abort(u)});break;default:break}}),n.events?.increment({peer_connection:!0}),n.role==="client"){n.log.trace("%s secure inbound",n.role);let u=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:u.remotePeer,muxerFactory:e,signal:n.signal})}n.log.trace("%s secure outbound",n.role);let f=await a.secureOutbound(c,{remotePeer:n.remotePeer,signal:n.signal,skipStreamMuxerNegotiation:!0});l.remoteAddr=l.remoteAddr.encapsulate(`/p2p/${f.remotePeer}`),n.log.trace("%s upgrade inbound",n.role),await n.upgrader.upgradeInbound(l,{skipProtection:!0,skipEncryption:!0,remotePeer:f.remotePeer,muxerFactory:e,signal:n.signal})}catch(i){throw o.close(),r.close(),i}}async function oN(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,i=new RTCPeerConnection({...o??{},certificates:[n]}),s=new ma({peerConnection:i,metrics:t.events,dataChannelOptions:t.dataChannel});return{peerConnection:i,muxerFactory:s}}async function iN(r){let e=await $m(r),t=await crypto.subtle.exportKey("pkcs8",e.privateKey);return["-----BEGIN PRIVATE KEY-----",...j(new Uint8Array(t),"base64pad").split(/(.{64})/).filter(Boolean),"-----END PRIVATE KEY-----"].join(`
110
- `)}var r6=class{log;metrics;components;init;certificate;privateKey;emitter;renewCertificateTask;constructor(e,t={}){if(this.log=e.logger.forComponent("libp2p:webrtc-direct"),this.components=e,this.init=t,this.emitter=new _e,t.certificateLifespan!=null&&t.certificateRenewalThreshold!=null&&t.certificateRenewalThreshold>=t.certificateLifespan)throw new P("Certificate renewal threshold must be less than certificate lifespan");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"})})}[ks]=!0;[Symbol.toStringTag]="@libp2p/webrtc-direct";[qe]=["@libp2p/transport"];async start(){this.certificate=await this.getCertificate()}async stop(){this.renewCertificateTask!=null&&clearTimeout(this.renewCertificateTask),this.certificate=void 0}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=yt(o));let i=mO(),{peerConnection:s,muxerFactory:a}=await oN("client",i,{rtcConfiguration:typeof this.init.rtcConfiguration=="function"?await this.init.rtcConfiguration():this.init.rtcConfiguration??{},dataChannel:this.init.dataChannel});try{return await nN(s,a,i,{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 s.close(),c}}createListener(e){if(this.certificate==null)throw new _n;return new t6(this.components,{...this.init,...e,certificate:this.certificate,emitter:this.emitter})}listenFilter(e){return e.filter(Ah.exactMatch)}dialFilter(e){return this.listenFilter(e)}async getCertificate(e){if(XW(this.init.certificate))return this.log("using provided TLS certificate"),this.init.certificate;let t=await this.loadOrCreatePrivateKey(),{pem:n,certhash:o}=await this.loadOrCreateCertificate(t,e);return{privateKey:await iN(t),pem:n,certhash:o}}async loadOrCreatePrivateKey(){if(this.privateKey!=null)return this.privateKey;let e=this.init.certificateKeychainName??iO,t=this.getKeychain();try{if(t==null)throw this.log("no keychain configured - not checking for stored private key"),new Xe;this.log.trace("checking for stored private key"),this.privateKey=await t.exportKey(e)}catch(n){if(n.name!=="NotFoundError")throw n;this.log.trace("generating private key"),this.privateKey=await fu("ECDSA","P-256"),t!=null?(this.log.trace("storing private key"),await t.importKey(e,this.privateKey)):this.log("no keychain configured - not storing private key")}return this.privateKey}async loadOrCreateCertificate(e,t){if(this.certificate!=null&&t!==!0)return this.certificate;let n,o=new ht(this.init.certificateDatastoreKey??oO),i=await $m(e);try{if(t===!0)throw this.log.trace("forcing renewal of TLS certificate"),new Xe;this.log.trace("checking for stored TLS certificate"),n=await this.loadCertificate(o,i)}catch(a){if(a.name!=="NotFoundError")throw a;this.log.trace("generating new TLS certificate"),n=await this.createCertificate(o,i)}let s=n.notAfter.getTime()-(this.init.certificateRenewalThreshold??Mb)-Date.now();return s<0&&(s=100),this.log("will renew TLS certificate after %d ms",s),this.renewCertificateTask=setTimeout(()=>{this.log("renewing TLS certificate"),this.getCertificate(!0).then(a=>{this.certificate=a,this.emitter.safeDispatchEvent("certificate:renew",{detail:a})}).catch(a=>{this.log.error("could not renew certificate - %e",a)})},s),{pem:n.toString("pem"),certhash:qa.encode((await St.digest(new Uint8Array(n.rawData))).bytes)}}async loadCertificate(e,t){let n=await this.components.datastore.get(e),o=new rd(n),i=o.notAfter.getTime()-(this.init.certificateRenewalThreshold??Mb);if(Date.now()>i)throw this.log("stored TLS certificate has expired"),new Xe;this.log("loaded certificate, expires in %d ms",i);let s=await o.publicKey.export(crypto),a=await crypto.subtle.exportKey("raw",s),c=await crypto.subtle.exportKey("raw",t.publicKey);if(!we(new Uint8Array(a,0,a.byteLength),new Uint8Array(c,0,c.byteLength)))throw this.log("stored TLS certificate public key did not match public key from private key"),new Xe;return this.log("loaded certificate, expiry time is %o",i),o}async createCertificate(e,t){let n=new Date,o=new Date(Date.now()+(this.init.certificateLifespan??sO));n.setMilliseconds(0),o.setMilliseconds(0);let i=await e6.createSelfSigned({serialNumber:(BigInt(Math.random().toString().replace(".",""))*100000n).toString(16),name:"CN=example.com, C=US, L=CA, O=example, ST=CA",notBefore:n,notAfter:o,keys:t,extensions:[new Jf(!1,void 0,!0)]},crypto);return this.getKeychain()!=null?(this.log.trace("storing TLS certificate"),await this.components.datastore.put(e,B(i.toString("pem")))):this.log("no keychain is configured so not storing TLS certificate since the private key will not be reused"),i}getKeychain(){try{return this.components.keychain}catch{}}};function XW(r){return r==null?!1:typeof r.privateKey=="string"&&typeof r.pem=="string"&&typeof r.certhash=="string"}function sN(r){return e=>new r6(e,r)}function aN(r){return e=>new Y3(e,r)}var Mv=class extends Error{constructor(e){super(e),this.name="TimeoutError"}},Uv=class extends Error{constructor(e){super(),this.name="AbortError",this.message=e}},cN=r=>globalThis.DOMException===void 0?new Uv(r):new DOMException(r),lN=r=>{let e=r.reason===void 0?cN("This operation was aborted."):r.reason;return e instanceof Error?e:cN(e)};function Fv(r,e){let{milliseconds:t,fallback:n,message:o,customTimers:i={setTimeout,clearTimeout}}=e,s,a,l=new Promise((f,u)=>{if(typeof t!="number"||Math.sign(t)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${t}\``);if(e.signal){let{signal:h}=e;h.aborted&&u(lN(h)),a=()=>{u(lN(h))},h.addEventListener("abort",a,{once:!0})}if(t===Number.POSITIVE_INFINITY){r.then(f,u);return}let d=new Mv;s=i.setTimeout.call(void 0,()=>{if(n){try{f(n())}catch(h){u(h)}return}typeof r.cancel=="function"&&r.cancel(),o===!1?f():o instanceof Error?u(o):(d.message=o??`Promise timed out after ${t} milliseconds`,u(d))},t),(async()=>{try{f(await r)}catch(h){u(h)}})()}).finally(()=>{l.clear(),a&&e.signal&&e.signal.removeEventListener("abort",a)});return l.clear=()=>{i.clearTimeout.call(void 0,s),s=void 0},l}var YW=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 QW(r,e,t){let n,o=new Promise((i,s)=>{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:f}=YW(r),u=async(...h)=>{let m=t.multiArgs?h:h[0];if(t.filter)try{if(!await t.filter(m))return}catch(w){n(),s(w);return}c.push(m),t.count===c.length&&(n(),i(c))},d=(...h)=>{n(),s(t.rejectionMultiArgs?h:h[0])};n=()=>{for(let h of a)f(h,u);for(let h of t.rejectionEvents)a.includes(h)||f(h,d)};for(let h of a)l(h,u);for(let h of t.rejectionEvents)a.includes(h)||l(h,d);t.signal&&t.signal.addEventListener("abort",()=>{d(t.signal.reason)},{once:!0}),t.resolveImmediately&&i(c)});if(o.cancel=n,typeof t.timeout=="number"){let i=Fv(o,{milliseconds:t.timeout});return i.cancel=()=>{n(),i.clear()},i}return o}function uN(r,e,t){typeof t=="function"&&(t={filter:t}),t={...t,count:1,resolveImmediately:!1};let n=QW(r,e,t),o=n.then(i=>i[0]);return o.cancel=n.cancel,o}function fN(){throw new Error("WebSocket Servers can not be created in the browser!")}var ZW=1024*1024*4,JW=10,$v=class extends Hs{websocket;maxBufferedAmount;checkBufferedAmountTask;constructor(e){super(e),this.websocket=e.websocket,this.maxBufferedAmount=e.maxBufferedAmount??ZW,this.checkBufferedAmountTask=ku(this.checkBufferedAmount.bind(this),e.bufferedAmountPollInterval??JW),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=B(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(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 dN(r){return new $v(r)}var jv=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"})})}[ks]=!0;[Symbol.toStringTag]="@libp2p/websockets";[qe]=["@libp2p/transport"];async dial(e,t){this.log("dialing %s",e),t=t??{};let n=dN({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=ea(e);this.log("create websocket connection to %s",n);let o=new WebSocket(n);o.binaryType="arraybuffer";try{t.onProgress?.(new oe("websockets:open-connection")),await uN(o,"open",t)}catch(i){if(t.signal?.aborted)throw this.metrics?.dialerEvents.increment({abort:!0}),new Bl(`Could not connect to ${n}`);this.metrics?.dialerEvents.increment({error:!0});try{o.close()}catch{}throw i}return this.log("connected %s",e),this.metrics?.dialerEvents.increment({connect:!0}),o}createListener(e){return fN({logger:this.logger,events:this.components.events,metrics:this.components.metrics},{...this.init,...e})}listenFilter(e){return e.filter(t=>Zi.exactMatch(t)||kc.exactMatch(t))}dialFilter(e){return this.listenFilter(e)}};function hN(r={}){return e=>new jv(e,r)}var Kv=nr(L2(),1);function pN(r,e){let t=e.map((n,o)=>({record:si(n),index:o}));return t.sort((n,o)=>{let i=n.record.sequence,s=o.record.sequence;if(i>s)return-1;if(i<s)return 1;if(n.record.validityType===un.ValidityType.EOL&&o.record.validityType===un.ValidityType.EOL){let a=Kv.default.fromString(n.record.validity).toDate(),c=Kv.default.fromString(o.record.validity).toDate();if(a.getTime()>c.getTime())return-1;if(a.getTime()<c.getTime())return 1}return 0}),t[0].index}var mN="6.0.15",gN="helia";var yN={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 n6(r={}){let e=`${gN}/${mN} ${Ug()}`;return{privateKey:r.privateKey,dns:r.dns,nodeInfo:{userAgent:e},addresses:{listen:["/p2p-circuit","/webrtc"]},transports:[lP(),aN(),sN(),hN()],connectionEncrypters:[py()],streamMuxers:[zC(),Hk()],peerDiscovery:[ZC(yN)],services:{autoNAT:QC(),dcutr:dP(),delegatedRouting:_T(Nw()),dht:Fk({clientMode:!0,validators:{ipns:K2},selectors:{ipns:pN}}),identify:nk(),identifyPush:ok(),keychain:ay(r.keychain),ping:Zk(),http:QP()}}}async function wN(r){let e=r.libp2p??{};e.privateKey==null&&r.datastore!=null&&(e.privateKey=await A7(r.datastore,r.keychain));let t=n6(e);return t.datastore=t.datastore??r.datastore,await yI({...t,...e,start:!1})}async function Vv(r={}){let e=r.datastore??new Rc,t=r.blockstore??new Oh,n;return wI(r.libp2p)?n=r.libp2p:n=await wN({...r,libp2p:{dns:r.dns,...r.libp2p,start:void 0},datastore:e}),{...r,libp2p:n,datastore:e,blockstore:t,blockBrokers:r.blockBrokers??[Rw(),xw()],routers:r.routers??[qw(n),Vw()],metrics:n.metrics}}async function ez(r={}){let e=await Vv(r),t=new h2(e);return e.start!==!1&&await t.start(),t}return DN(tz);})();
110
+ `)}var r6=class{log;metrics;components;init;certificate;privateKey;emitter;renewCertificateTask;constructor(e,t={}){if(this.log=e.logger.forComponent("libp2p:webrtc-direct"),this.components=e,this.init=t,this.emitter=new _e,t.certificateLifespan!=null&&t.certificateRenewalThreshold!=null&&t.certificateRenewalThreshold>=t.certificateLifespan)throw new P("Certificate renewal threshold must be less than certificate lifespan");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"})})}[ks]=!0;[Symbol.toStringTag]="@libp2p/webrtc-direct";[qe]=["@libp2p/transport"];async start(){this.certificate=await this.getCertificate()}async stop(){this.renewCertificateTask!=null&&clearTimeout(this.renewCertificateTask),this.certificate=void 0}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=yt(o));let i=mO(),{peerConnection:s,muxerFactory:a}=await oN("client",i,{rtcConfiguration:typeof this.init.rtcConfiguration=="function"?await this.init.rtcConfiguration():this.init.rtcConfiguration??{},dataChannel:this.init.dataChannel});try{return await nN(s,a,i,{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 s.close(),c}}createListener(e){if(this.certificate==null)throw new _n;return new t6(this.components,{...this.init,...e,certificate:this.certificate,emitter:this.emitter})}listenFilter(e){return e.filter(Ah.exactMatch)}dialFilter(e){return this.listenFilter(e)}async getCertificate(e){if(XW(this.init.certificate))return this.log("using provided TLS certificate"),this.init.certificate;let t=await this.loadOrCreatePrivateKey(),{pem:n,certhash:o}=await this.loadOrCreateCertificate(t,e);return{privateKey:await iN(t),pem:n,certhash:o}}async loadOrCreatePrivateKey(){if(this.privateKey!=null)return this.privateKey;let e=this.init.certificateKeychainName??iO,t=this.getKeychain();try{if(t==null)throw this.log("no keychain configured - not checking for stored private key"),new Xe;this.log.trace("checking for stored private key"),this.privateKey=await t.exportKey(e)}catch(n){if(n.name!=="NotFoundError")throw n;this.log.trace("generating private key"),this.privateKey=await fu("ECDSA","P-256"),t!=null?(this.log.trace("storing private key"),await t.importKey(e,this.privateKey)):this.log("no keychain configured - not storing private key")}return this.privateKey}async loadOrCreateCertificate(e,t){if(this.certificate!=null&&t!==!0)return this.certificate;let n,o=new ht(this.init.certificateDatastoreKey??oO),i=await $m(e);try{if(t===!0)throw this.log.trace("forcing renewal of TLS certificate"),new Xe;this.log.trace("checking for stored TLS certificate"),n=await this.loadCertificate(o,i)}catch(a){if(a.name!=="NotFoundError")throw a;this.log.trace("generating new TLS certificate"),n=await this.createCertificate(o,i)}let s=n.notAfter.getTime()-(this.init.certificateRenewalThreshold??Mb)-Date.now();return s<0&&(s=100),this.log("will renew TLS certificate after %d ms",s),this.renewCertificateTask=setTimeout(()=>{this.log("renewing TLS certificate"),this.getCertificate(!0).then(a=>{this.certificate=a,this.emitter.safeDispatchEvent("certificate:renew",{detail:a})}).catch(a=>{this.log.error("could not renew certificate - %e",a)})},s),{pem:n.toString("pem"),certhash:qa.encode((await St.digest(new Uint8Array(n.rawData))).bytes)}}async loadCertificate(e,t){let n=await this.components.datastore.get(e),o=new rd(n),i=o.notAfter.getTime()-(this.init.certificateRenewalThreshold??Mb);if(Date.now()>i)throw this.log("stored TLS certificate has expired"),new Xe;this.log("loaded certificate, expires in %d ms",i);let s=await o.publicKey.export(crypto),a=await crypto.subtle.exportKey("raw",s),c=await crypto.subtle.exportKey("raw",t.publicKey);if(!we(new Uint8Array(a,0,a.byteLength),new Uint8Array(c,0,c.byteLength)))throw this.log("stored TLS certificate public key did not match public key from private key"),new Xe;return this.log("loaded certificate, expiry time is %o",i),o}async createCertificate(e,t){let n=new Date,o=new Date(Date.now()+(this.init.certificateLifespan??sO));n.setMilliseconds(0),o.setMilliseconds(0);let i=await e6.createSelfSigned({serialNumber:(BigInt(Math.random().toString().replace(".",""))*100000n).toString(16),name:"CN=example.com, C=US, L=CA, O=example, ST=CA",notBefore:n,notAfter:o,keys:t,extensions:[new Jf(!1,void 0,!0)]},crypto);return this.getKeychain()!=null?(this.log.trace("storing TLS certificate"),await this.components.datastore.put(e,B(i.toString("pem")))):this.log("no keychain is configured so not storing TLS certificate since the private key will not be reused"),i}getKeychain(){try{return this.components.keychain}catch{}}};function XW(r){return r==null?!1:typeof r.privateKey=="string"&&typeof r.pem=="string"&&typeof r.certhash=="string"}function sN(r){return e=>new r6(e,r)}function aN(r){return e=>new Y3(e,r)}var Mv=class extends Error{constructor(e){super(e),this.name="TimeoutError"}},Uv=class extends Error{constructor(e){super(),this.name="AbortError",this.message=e}},cN=r=>globalThis.DOMException===void 0?new Uv(r):new DOMException(r),lN=r=>{let e=r.reason===void 0?cN("This operation was aborted."):r.reason;return e instanceof Error?e:cN(e)};function Fv(r,e){let{milliseconds:t,fallback:n,message:o,customTimers:i={setTimeout,clearTimeout}}=e,s,a,l=new Promise((f,u)=>{if(typeof t!="number"||Math.sign(t)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${t}\``);if(e.signal){let{signal:h}=e;h.aborted&&u(lN(h)),a=()=>{u(lN(h))},h.addEventListener("abort",a,{once:!0})}if(t===Number.POSITIVE_INFINITY){r.then(f,u);return}let d=new Mv;s=i.setTimeout.call(void 0,()=>{if(n){try{f(n())}catch(h){u(h)}return}typeof r.cancel=="function"&&r.cancel(),o===!1?f():o instanceof Error?u(o):(d.message=o??`Promise timed out after ${t} milliseconds`,u(d))},t),(async()=>{try{f(await r)}catch(h){u(h)}})()}).finally(()=>{l.clear(),a&&e.signal&&e.signal.removeEventListener("abort",a)});return l.clear=()=>{i.clearTimeout.call(void 0,s),s=void 0},l}var YW=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 QW(r,e,t){let n,o=new Promise((i,s)=>{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:f}=YW(r),u=async(...h)=>{let m=t.multiArgs?h:h[0];if(t.filter)try{if(!await t.filter(m))return}catch(w){n(),s(w);return}c.push(m),t.count===c.length&&(n(),i(c))},d=(...h)=>{n(),s(t.rejectionMultiArgs?h:h[0])};n=()=>{for(let h of a)f(h,u);for(let h of t.rejectionEvents)a.includes(h)||f(h,d)};for(let h of a)l(h,u);for(let h of t.rejectionEvents)a.includes(h)||l(h,d);t.signal&&t.signal.addEventListener("abort",()=>{d(t.signal.reason)},{once:!0}),t.resolveImmediately&&i(c)});if(o.cancel=n,typeof t.timeout=="number"){let i=Fv(o,{milliseconds:t.timeout});return i.cancel=()=>{n(),i.clear()},i}return o}function uN(r,e,t){typeof t=="function"&&(t={filter:t}),t={...t,count:1,resolveImmediately:!1};let n=QW(r,e,t),o=n.then(i=>i[0]);return o.cancel=n.cancel,o}function fN(){throw new Error("WebSocket Servers can not be created in the browser!")}var ZW=1024*1024*4,JW=10,$v=class extends Hs{websocket;maxBufferedAmount;checkBufferedAmountTask;constructor(e){super(e),this.websocket=e.websocket,this.maxBufferedAmount=e.maxBufferedAmount??ZW,this.checkBufferedAmountTask=ku(this.checkBufferedAmount.bind(this),e.bufferedAmountPollInterval??JW),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=B(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(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 dN(r){return new $v(r)}var jv=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"})})}[ks]=!0;[Symbol.toStringTag]="@libp2p/websockets";[qe]=["@libp2p/transport"];async dial(e,t){this.log("dialing %s",e),t=t??{};let n=dN({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=ea(e);this.log("create websocket connection to %s",n);let o=new WebSocket(n);o.binaryType="arraybuffer";try{t.onProgress?.(new oe("websockets:open-connection")),await uN(o,"open",t)}catch(i){if(t.signal?.aborted)throw this.metrics?.dialerEvents.increment({abort:!0}),new Bl(`Could not connect to ${n}`);this.metrics?.dialerEvents.increment({error:!0});try{o.close()}catch{}throw i}return this.log("connected %s",e),this.metrics?.dialerEvents.increment({connect:!0}),o}createListener(e){return fN({logger:this.logger,events:this.components.events,metrics:this.components.metrics},{...this.init,...e})}listenFilter(e){return e.filter(t=>Zi.exactMatch(t)||kc.exactMatch(t))}dialFilter(e){return this.listenFilter(e)}};function hN(r={}){return e=>new jv(e,r)}var Kv=nr(L2(),1);function pN(r,e){let t=e.map((n,o)=>({record:si(n),index:o}));return t.sort((n,o)=>{let i=n.record.sequence,s=o.record.sequence;if(i>s)return-1;if(i<s)return 1;if(n.record.validityType===un.ValidityType.EOL&&o.record.validityType===un.ValidityType.EOL){let a=Kv.default.fromString(n.record.validity).toDate(),c=Kv.default.fromString(o.record.validity).toDate();if(a.getTime()>c.getTime())return-1;if(a.getTime()<c.getTime())return 1}return 0}),t[0].index}var mN="6.0.16",gN="helia";var yN={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 n6(r={}){let e=`${gN}/${mN} ${Ug()}`;return{privateKey:r.privateKey,dns:r.dns,nodeInfo:{userAgent:e},addresses:{listen:["/p2p-circuit","/webrtc"]},transports:[lP(),aN(),sN(),hN()],connectionEncrypters:[py()],streamMuxers:[zC(),Hk()],peerDiscovery:[ZC(yN)],services:{autoNAT:QC(),dcutr:dP(),delegatedRouting:_T(Nw()),dht:Fk({clientMode:!0,validators:{ipns:K2},selectors:{ipns:pN}}),identify:nk(),identifyPush:ok(),keychain:ay(r.keychain),ping:Zk(),http:QP()}}}async function wN(r){let e=r.libp2p??{};e.privateKey==null&&r.datastore!=null&&(e.privateKey=await A7(r.datastore,r.keychain));let t=n6(e);return t.datastore=t.datastore??r.datastore,await yI({...t,...e,start:!1})}async function Vv(r={}){let e=r.datastore??new Rc,t=r.blockstore??new Oh,n;return wI(r.libp2p)?n=r.libp2p:n=await wN({...r,libp2p:{dns:r.dns,...r.libp2p,start:void 0},datastore:e}),{...r,libp2p:n,datastore:e,blockstore:t,blockBrokers:r.blockBrokers??[Rw(),xw()],routers:r.routers??[qw(n),Vw()],metrics:n.metrics}}async function ez(r={}){let e=await Vv(r),t=new h2(e);return e.start!==!1&&await t.start(),t}return DN(tz);})();
111
111
  /*! Bundled license information:
112
112
 
113
113
  pvtsutils/build/index.js: