* Create a new websocket connection * @param _webSocketUrl
(_webSocketUrl)
| 31 | * @param _webSocketUrl |
| 32 | */ |
| 33 | constructor(_webSocketUrl) { |
| 34 | super() |
| 35 | this.connected = false |
| 36 | this._closed = false |
| 37 | this._pending = new Map() |
| 38 | this._connectWaiters = new Set() |
| 39 | // removeCallback(id) only receives the subscriptionId — off() needs the event |
| 40 | // name and the exact handler function too, so this holds what it needs to |
| 41 | // detach the right listener without the caller having to keep them around. |
| 42 | this._callbacks = new Map() |
| 43 | this._ws = new WebSocket(_webSocketUrl) |
| 44 | this._ws.on('open', () => { |
| 45 | // The handshake can complete after close()/_failPending() has already |
| 46 | // marked the connection closed. Don't flip connected back to true and |
| 47 | // proactively close the now-orphan socket so it does not leak. |
| 48 | if (this._closed) { |
| 49 | try { |
| 50 | this._ws.close() |
| 51 | } catch { |
| 52 | /* socket already closing */ |
| 53 | } |
| 54 | return |
| 55 | } |
| 56 | this.connected = true |
| 57 | for (const { resolve } of this._connectWaiters) { |
| 58 | resolve() |
| 59 | } |
| 60 | this._connectWaiters.clear() |
| 61 | }) |
| 62 | // Single shared response dispatcher. Avoids attaching a new 'message' |
| 63 | // listener for every in-flight send(), which previously caused |
| 64 | // MaxListenersExceededWarning under concurrent BiDi traffic |
| 65 | // (e.g. network interception during a page navigation). |
| 66 | this._ws.on('message', (data) => { |
| 67 | // Frames can arrive after close() has cleared _pending; ignore them |
| 68 | // rather than re-emitting parse errors or dispatching to nothing. |
| 69 | if (this._closed) { |
| 70 | return |
| 71 | } |
| 72 | let payload |
| 73 | try { |
| 74 | payload = JSON.parse(data.toString()) |
| 75 | } catch (err) { |
| 76 | // Surface protocol parse failures rather than silently dropping — |
| 77 | // otherwise callers see misleading send() timeouts. |
| 78 | this._emitOrWarn(new Error(`Failed to parse BiDi message: ${err.message}`), 'BiDiProtocolWarning') |
| 79 | return |
| 80 | } |
| 81 | // Messages without a numeric id are BiDi events, not command responses. |
| 82 | // Re-emit them on this EventEmitter by method name (e.g. |
| 83 | // 'browsingContext.contextCreated') so that generated domain classes can |
| 84 | // subscribe via bidi.on(methodName, callback) instead of each attaching |
| 85 | // a new raw ws.on('message', ...) listener. The existing hand-written |
| 86 | // modules (logInspector, network, etc.) continue to use their own |
| 87 | // ws.on('message', ...) listeners unchanged — this emission is purely |
| 88 | // additive and does not affect those code paths. |
| 89 | if (payload == null || typeof payload.id !== 'number') { |
| 90 | if (payload != null && typeof payload.method === 'string') { |