{"size": 1155, "ext": "js", "max_stars_repo_path": "lib/server-swarm.js", "max_stars_repo_name": "falafeljan/hyperswarm-ws", "max_stars_repo_stars_event_min_datetime": "2019-11-28T13:51:44.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-19T19:32:35.000Z", "max_issues_repo_path": "lib/server-swarm.js", "max_issues_repo_name": "falafeljan/hyperswarm-ws", "max_issues_repo_issues_event_min_datetime": "2019-10-31T19:50:52.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-06T10:50:24.000Z", "max_forks_repo_path": "lib/server-swarm.js", "max_forks_repo_name": "jankaszel/hyperswarm-ws", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": 8, "max_issues_count": 3, "max_forks_count": null, "avg_line_length": 19.9137931034, "max_line_length": 64, "alphanum_fraction": 0.5974025974}
const assert = require('assert')
const websocket = require('websocket-stream')
const HyperswarmProxyServer = require('hyperswarm-proxy/server')

class ServerSwarm extends HyperswarmProxyServer {
  constructor (opts = {}) {
    super(opts)
    this.pingInterval = opts.pingInterval || 3500

    if (opts.server) {
      this.listenOnServer(opts.server)
    }
  }

  listenOnServer (server) {
    if (this.wss) {
      assert.fail('WebSocket server has already been created.')
    }

    this.wss = websocket.createServer({ server }, socket => {
      socket.on('error', err => {
        if (err.code !== 'ECONNRESET') {
          throw err
        }
      })
      this.handleStream(socket)
    })

    this._heartbeat()
  }

  _heartbeat () {
    if (!this.wss) {
      return
    }

    for (const client of this.wss.clients) {
      client.ping()
    }

    this._pingIntervalRef = setTimeout(() => {
      this._heartbeat()
    }, this.pingInterval)
  }

  destroy (cb) {
    if (this._pingIntervalRef) {
      clearTimeout(this._pingIntervalRef)
    }

    this.wss.close(() => {
      super.destroy(cb)
    })
  }
}

module.exports = { ServerSwarm }
