cdp.js 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142
  1. /**
  2. * 最小 CDP 客户端
  3. * ===============
  4. * 只依赖 Node 22 自带的全局 WebSocket(undici 实现),不引 ws / puppeteer。
  5. *
  6. * 为什么不用 Playwright:桌面端的外壳本来就是直接连 Chrome DevTools 协议
  7. * (见 resources/plugin/cocorobo/browser.mjs),页面工具要复现的语义(挑页签、
  8. * 执行脚本、投文件、硬刷新)在 CDP 里都是一等公民;引一个浏览器框架反而会把
  9. * "哪条命令对应桌面端哪个行为"这层对应关系藏起来。
  10. *
  11. * 一个连接 = 一个 target(页签)。多页签就是多条连接,省掉 sessionId 复用的复杂度。
  12. */
  13. const DEFAULT_TIMEOUT = 30_000
  14. export class CDPError extends Error {
  15. constructor (message, info) {
  16. super(message)
  17. this.name = 'CDPError'
  18. this.code = (info && info.code) || ''
  19. this.method = (info && info.method) || ''
  20. }
  21. }
  22. export class CDP {
  23. #ws = null
  24. #nextId = 1
  25. #pending = new Map()
  26. #listeners = new Map()
  27. #closed = false
  28. #opening = null
  29. constructor (url, options = {}) {
  30. this.url = url
  31. this.timeoutMs = options.timeoutMs || DEFAULT_TIMEOUT
  32. this.label = options.label || 'cdp'
  33. }
  34. static async connect (url, options) {
  35. const client = new CDP(url, options)
  36. await client.opened()
  37. return client
  38. }
  39. opened () {
  40. if (this.#opening) return this.#opening
  41. this.#opening = new Promise((resolve, reject) => {
  42. let ws
  43. try {
  44. ws = new WebSocket(this.url)
  45. } catch (err) {
  46. reject(new CDPError(`WebSocket 建连失败:${err.message}`))
  47. return
  48. }
  49. this.#ws = ws
  50. const timer = setTimeout(() => {
  51. try { ws.close() } catch { /* 已经关了 */ }
  52. reject(new CDPError('连接 CDP 超时'))
  53. }, this.timeoutMs)
  54. timer.unref?.()
  55. const settle = (fn, arg) => {
  56. clearTimeout(timer)
  57. fn(arg)
  58. }
  59. ws.addEventListener('message', (event) => {
  60. if (typeof event.data !== 'string') return
  61. let msg
  62. try { msg = JSON.parse(event.data) } catch { return }
  63. this.#dispatch(msg)
  64. })
  65. ws.addEventListener('open', () => settle(resolve))
  66. ws.addEventListener('error', () => settle(reject, new CDPError(`连接 ${this.label} 失败`)))
  67. ws.addEventListener('close', () => {
  68. this.#closed = true
  69. for (const [, entry] of this.#pending) {
  70. clearTimeout(entry.timer)
  71. entry.reject(new CDPError(`连接已关闭(${this.label})`))
  72. }
  73. this.#pending.clear()
  74. for (const fn of this.#listeners.get('close') || []) {
  75. try { fn() } catch { /* 订阅方自己处理 */ }
  76. }
  77. })
  78. })
  79. return this.#opening
  80. }
  81. #dispatch (msg) {
  82. if (msg.id != null) {
  83. const entry = this.#pending.get(msg.id)
  84. if (!entry) return
  85. this.#pending.delete(msg.id)
  86. clearTimeout(entry.timer)
  87. if (msg.error) entry.reject(new CDPError(msg.error.message, { code: msg.error.code, method: entry.method }))
  88. else entry.resolve(msg.result)
  89. return
  90. }
  91. if (!msg.method) return
  92. for (const fn of this.#listeners.get(msg.method) || []) {
  93. try { fn(msg.params || {}) } catch { /* 单个订阅者异常不影响其它 */ }
  94. }
  95. }
  96. send (method, params = {}, options = {}) {
  97. if (this.#closed || !this.#ws) return Promise.reject(new CDPError('连接未就绪'))
  98. const id = this.#nextId++
  99. const timeoutMs = options.timeoutMs || this.timeoutMs
  100. return new Promise((resolve, reject) => {
  101. const timer = setTimeout(() => {
  102. this.#pending.delete(id)
  103. reject(new CDPError(`CDP ${method} 超时(${timeoutMs}ms)`, { method }))
  104. }, timeoutMs)
  105. timer.unref?.()
  106. this.#pending.set(id, { resolve, reject, timer, method })
  107. try {
  108. this.#ws.send(JSON.stringify({ id, method, params }))
  109. } catch (err) {
  110. clearTimeout(timer)
  111. this.#pending.delete(id)
  112. reject(new CDPError(`发送 ${method} 失败:${err.message}`, { method }))
  113. }
  114. })
  115. }
  116. on (method, fn) {
  117. if (!this.#listeners.has(method)) this.#listeners.set(method, new Set())
  118. this.#listeners.get(method).add(fn)
  119. return () => this.off(method, fn)
  120. }
  121. off (method, fn) {
  122. const set = this.#listeners.get(method)
  123. if (set) set.delete(fn)
  124. }
  125. close () {
  126. this.#closed = true
  127. try { this.#ws?.close() } catch { /* 已经关了 */ }
  128. }
  129. }