()
| 108 | class Cdp { |
| 109 | constructor(url) { this.url = url; this.id = 1; this.pending = new Map(); this.listeners = new Map() } |
| 110 | connect() { |
| 111 | return new Promise((res, rej) => { |
| 112 | this.ws = new WebSocket(this.url) |
| 113 | this.ws.on('open', res); this.ws.on('error', rej) |
| 114 | this.ws.on('message', (raw) => { |
| 115 | const m = JSON.parse(String(raw)) |
| 116 | if (m.id && this.pending.has(m.id)) { const { resolve, reject } = this.pending.get(m.id); this.pending.delete(m.id); m.error ? reject(new Error(m.error.message)) : resolve(m.result ?? {}) } |
| 117 | else if (m.method) for (const l of this.listeners.get(m.method) ?? []) l(m.params ?? {}) |
| 118 | }) |
| 119 | }) |
| 120 | } |
| 121 | send(method, params = {}) { const id = this.id++; return new Promise((res, rej) => { this.pending.set(id, { resolve: res, reject: rej }); this.ws.send(JSON.stringify({ id, method, params })) }) } |
| 122 | on(method, l) { const a = this.listeners.get(method) ?? []; a.push(l); this.listeners.set(method, a) } |
| 123 | close() { this.ws?.terminate?.(); this.ws?.close() } |
no test coverage detected