UNPKG

@waku/core

Version:

TypeScript implementation of the Waku v2 protocol

81 lines 2.57 kB
export class NetworkMonitor { libp2p; events; isNetworkConnected = false; constructor(options) { this.libp2p = options.libp2p; this.events = options.events; this.onConnectedEvent = this.onConnectedEvent.bind(this); this.onDisconnectedEvent = this.onDisconnectedEvent.bind(this); this.dispatchNetworkEvent = this.dispatchNetworkEvent.bind(this); } start() { this.libp2p.addEventListener("peer:connect", this.onConnectedEvent); this.libp2p.addEventListener("peer:disconnect", this.onDisconnectedEvent); try { globalThis.addEventListener("online", this.dispatchNetworkEvent); globalThis.addEventListener("offline", this.dispatchNetworkEvent); } catch (err) { // ignore } } stop() { this.libp2p.removeEventListener("peer:connect", this.onConnectedEvent); this.libp2p.removeEventListener("peer:disconnect", this.onDisconnectedEvent); try { globalThis.removeEventListener("online", this.dispatchNetworkEvent); globalThis.removeEventListener("offline", this.dispatchNetworkEvent); } catch (err) { // ignore } } /** * Returns true if the node is connected to the network via libp2p and browser. */ isConnected() { if (!this.isBrowserConnected()) { return false; } return this.isP2PConnected(); } /** * Returns true if the node is connected to the network via libp2p. */ isP2PConnected() { return this.isNetworkConnected; } /** * Returns true if the node is connected to the network via browser. */ isBrowserConnected() { try { if (globalThis?.navigator && !globalThis?.navigator?.onLine) { return false; } } catch (err) { // ignore } return true; } onConnectedEvent() { if (!this.isNetworkConnected) { this.isNetworkConnected = true; this.dispatchNetworkEvent(); } } onDisconnectedEvent() { if (this.isNetworkConnected && this.libp2p.getConnections().length === 0) { this.isNetworkConnected = false; this.dispatchNetworkEvent(); } } dispatchNetworkEvent() { this.events.dispatchEvent(new CustomEvent("waku:connection", { detail: this.isConnected() })); } } //# sourceMappingURL=network_monitor.js.map