// 极简 CDP 客户端:Node 22+ 原生 WebSocket,无需 puppeteer / playwright。 // 与 dev/real-cdp.mjs 同一套思路,额外提供「连接断开回调」与事件订阅失败隔离, // 供无人值守的 runner/headless.mjs 在断线时判断是否需要重建浏览器。 export async function connect(wsUrl, opts = {}) { const ws = new WebSocket(wsUrl); await new Promise(function (res, rej) { ws.addEventListener('open', res, { once: true }); ws.addEventListener('error', rej, { once: true }); }); let id = 0; const pending = new Map(); const events = []; const waiters = []; const listeners = []; const state = { closed: false }; ws.addEventListener('close', function () { state.closed = true; // 断线后所有未完成的调用直接拒绝,避免 runner 卡死在 await 上 for (const [, p] of pending) { try { p.rej(new Error('CDP 连接已断开')); } catch (e) { /* ignore */ } } pending.clear(); if (typeof opts.onClose === 'function') { try { opts.onClose(); } catch (e) { /* ignore */ } } }); ws.addEventListener('message', function (ev) { const msg = JSON.parse(ev.data); if (msg.id != null && pending.has(msg.id)) { const { res, rej } = pending.get(msg.id); pending.delete(msg.id); if (msg.error) rej(new Error(msg.error.message)); else res(msg.result); return; } events.push(msg); for (const fn of listeners) { try { fn(msg); } catch (e) { /* 忽略订阅者异常 */ } } for (let i = waiters.length - 1; i >= 0; i--) { if (waiters[i].match(msg)) waiters.splice(i, 1)[0].res(msg); } }); const send = function (method, params = {}) { return new Promise(function (res, rej) { if (state.closed) { rej(new Error('CDP 连接已断开')); return; } const mid = ++id; pending.set(mid, { res, rej }); try { ws.send(JSON.stringify({ id: mid, method, params })); } catch (e) { pending.delete(mid); rej(e); } }); }; const waitEvent = function (name, timeoutMs = 30000) { return new Promise(function (res, rej) { const timer = setTimeout(function () { rej(new Error('等待事件超时: ' + name)); }, timeoutMs); waiters.push({ match: (m) => m.method === name, res: (m) => { clearTimeout(timer); res(m.params); }, }); }); }; const onEvent = function (fn) { listeners.push(fn); }; return { ws, send, waitEvent, onEvent, events, get closed() { return state.closed; }, close: function () { try { ws.close(); } catch (e) { /* ignore */ } }, }; } export const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); export async function httpJson(url, method = 'GET') { const r = await fetch(url, { method }); const t = await r.text(); try { return JSON.parse(t); } catch (e) { return t; } }