const e = require("@hyperswarm/rpc"),
t = require("hypercore-crypto"),
s = require("hypercore-id-encoding"),
r = require("./lib/notifications"),
o = require("./lib/encoding")
class i {
constructor(e, t, s) {
;((this.push = e), (this.roomKey = t), (this.roomDiscoveryKey = s), (this.destroyed = !1))
}
async send(e, t = [e.length], { version: s = 0, attest: r = null } = {}) {
try {
for (const o of t)
await this.push.send(e, this.roomKey, {
roomDiscoveryKey: this.roomDiscoveryKey,
length: o,
version: s,
attest: r,
})
} catch (e) {
if (this.destroyed) return
throw e
}
}
destroy() {
this.destroyed = !0
}
}
module.exports = class {
constructor(e = [], t = {}) {
;((this.rpc = null),
(this.dht = t.dht || null),
(this.gatewayKeys = e.map(s.decode)),
(this.destroyed = !1),
(this.suspended = !1))
}
setDHT(e) {
this.dht = e
}
setGatewayKeys(e) {
this.gatewayKeys = e.map(s.decode)
}
room(e, s = t.discoveryKey(e)) {
return new i(this, e, s)
}
async send(e, t, s = {}) {
if (this.destroyed) throw new Error("Destroyed")
const i = await r.send(e, t, s)
if (this.destroyed) throw new Error("Destroyed")
if (0 === this.gatewayKeys.length) throw new Error("No server keys set")
const h = this._getRPC(),
n = Math.floor(Math.random() * this.gatewayKeys.length)
let d = null
for (let e = 0; e < 2 * this.gatewayKeys.length; e++) {
const t = this.gatewayKeys[(e + n) % this.gatewayKeys.length]
try {
return await h.request(t, "notify", i, { timeout: 6e4, requestEncoding: o.notification })
} catch (e) {
d = e
}
if (this.destroyed) throw new Error("Destroyed")
}
throw d
}
_getRPC() {
if (this.suspended) throw new Error("Suspended")
return (this.rpc || (this.rpc = new e({ dht: this.dht, poolLinger: 6e4 })), this.rpc)
}
suspend() {
this.suspended || (this.rpc && this.rpc.destroy(), (this.rpc = null), (this.suspended = !0))
}
resume() {
this.suspended = !1
}
destroy() {
return ((this.destroyed = !0), this.rpc ? this.rpc.destroy() : Promise.resolve())
}
static requestEncoding = o
static receive(e, t, s = {}) {
return r.receive(e, t, s)
}
}