dsh-cua-linux 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +85 -0
- package/LICENSE +21 -0
- package/README.md +88 -2
- package/README.zh.md +78 -0
- package/assets/icon-180.png +0 -0
- package/assets/screenshot-1-cdp-bing.png +0 -0
- package/assets/screenshot-2-occluded.png +0 -0
- package/assets/screenshot-3-x11-wechat.png +0 -0
- package/cordis.patch.yml +6 -0
- package/index.js +474 -0
- package/lib/cdp.js +307 -0
- package/lib/png.js +95 -0
- package/lib/probe.js +175 -0
- package/lib/verify.js +162 -0
- package/lib/x11.js +306 -0
- package/package.json +62 -4
- package/screenshots.json +5 -0
package/lib/cdp.js
ADDED
|
@@ -0,0 +1,307 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* cdp.js —— Chromium DevTools Protocol 客户端(零依赖:node 内置 fetch + WebSocket)
|
|
3
|
+
*
|
|
4
|
+
* 为什么浏览器必须走这条路:
|
|
5
|
+
* 像素通道 CDP 通道
|
|
6
|
+
* ─────────────── ────────────────────────
|
|
7
|
+
* 要置顶、要焦点 不需要,窗口最小化/被遮挡都行
|
|
8
|
+
* 中文要靠剪贴板 Input.insertText 直接插任意 Unicode
|
|
9
|
+
* 定位靠坐标/OCR CSS selector,精确
|
|
10
|
+
* 一次操作 ~500ms 一次往返 ~5-20ms
|
|
11
|
+
*
|
|
12
|
+
* 前提:目标 Chromium 启动时带 --remote-debugging-port=PORT。
|
|
13
|
+
* 注意:Chrome 111+ 会校验 WS 的 Origin,需要 --remote-allow-origins=*(launch() 已带)。
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
const sleep = (ms) => new Promise((r) => setTimeout(r, ms))
|
|
17
|
+
|
|
18
|
+
/** 探测某个端口上是否有可用的 DevTools 端点。 */
|
|
19
|
+
export async function hasDebugPort(port, timeoutMs = 800) {
|
|
20
|
+
try {
|
|
21
|
+
const ctrl = AbortSignal.timeout(timeoutMs)
|
|
22
|
+
const res = await fetch(`http://127.0.0.1:${port}/json/version`, { signal: ctrl })
|
|
23
|
+
return res.ok
|
|
24
|
+
} catch {
|
|
25
|
+
return false
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* 起一个可调试的 Chromium(独立 profile,不碰用户正在用的实例)。
|
|
31
|
+
* @returns {import('node:child_process').ChildProcess}
|
|
32
|
+
*/
|
|
33
|
+
export async function launch({ port = 9222, url = 'about:blank', profileDir, headless = false, bin } = {}) {
|
|
34
|
+
const { spawn } = await import('node:child_process')
|
|
35
|
+
const os = await import('node:os')
|
|
36
|
+
const path = await import('node:path')
|
|
37
|
+
const fs = await import('node:fs')
|
|
38
|
+
|
|
39
|
+
const exe = bin || process.env.CUA_CHROME || '/usr/bin/google-chrome'
|
|
40
|
+
const profile = profileDir || path.join(os.tmpdir(), `cua-chrome-profile-${port}`)
|
|
41
|
+
fs.mkdirSync(profile, { recursive: true })
|
|
42
|
+
|
|
43
|
+
const args = [
|
|
44
|
+
`--remote-debugging-port=${port}`,
|
|
45
|
+
'--remote-allow-origins=*',
|
|
46
|
+
`--user-data-dir=${profile}`,
|
|
47
|
+
'--no-first-run',
|
|
48
|
+
'--no-default-browser-check',
|
|
49
|
+
'--disable-background-networking',
|
|
50
|
+
'--window-size=1280,900',
|
|
51
|
+
]
|
|
52
|
+
if (headless) args.push('--headless=new')
|
|
53
|
+
args.push(url)
|
|
54
|
+
|
|
55
|
+
const proc = spawn(exe, args, { detached: true, stdio: 'ignore' })
|
|
56
|
+
proc.unref()
|
|
57
|
+
return proc
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** 等 DevTools 端口就绪。 */
|
|
61
|
+
export async function waitReady(port, timeoutMs = 20000) {
|
|
62
|
+
const end = Date.now() + timeoutMs
|
|
63
|
+
while (Date.now() < end) {
|
|
64
|
+
if (await hasDebugPort(port)) return true
|
|
65
|
+
await sleep(250)
|
|
66
|
+
}
|
|
67
|
+
throw new Error(`DevTools 端口 ${port} 在 ${timeoutMs}ms 内未就绪(Chrome 是否带 --remote-debugging-port 启动?)`)
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** 一条到某个 page target 的 CDP 会话。 */
|
|
71
|
+
export class Cdp {
|
|
72
|
+
constructor(port = 9222, timeoutMs = 10000) {
|
|
73
|
+
this.port = port
|
|
74
|
+
this.timeoutMs = timeoutMs
|
|
75
|
+
this.ws = null
|
|
76
|
+
this.seq = 0
|
|
77
|
+
this.pending = new Map()
|
|
78
|
+
this.target = null
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
async listTabs() {
|
|
82
|
+
const res = await fetch(`http://127.0.0.1:${this.port}/json/list`)
|
|
83
|
+
if (!res.ok) throw new Error(`/json/list 返回 ${res.status}`)
|
|
84
|
+
const all = await res.json()
|
|
85
|
+
return all.filter((t) => t.type === 'page')
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/** 连接到某个 tab;urlSubstr 为空则取第一个。 */
|
|
89
|
+
async attach(urlSubstr = null, index = 0) {
|
|
90
|
+
let tabs = await this.listTabs()
|
|
91
|
+
if (urlSubstr) tabs = tabs.filter((t) => (t.url || '').toLowerCase().includes(urlSubstr.toLowerCase()))
|
|
92
|
+
if (!tabs.length) throw new Error(`没有匹配的 tab(urlSubstr=${JSON.stringify(urlSubstr)})`)
|
|
93
|
+
this.target = tabs[index] ?? tabs[0]
|
|
94
|
+
await this._open(this.target.webSocketDebuggerUrl)
|
|
95
|
+
for (const domain of ['Page', 'Runtime', 'DOM']) {
|
|
96
|
+
await this.send(`${domain}.enable`)
|
|
97
|
+
}
|
|
98
|
+
return this.target
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
_open(wsUrl) {
|
|
102
|
+
return new Promise((resolve, reject) => {
|
|
103
|
+
const ws = new WebSocket(wsUrl)
|
|
104
|
+
const timer = setTimeout(() => reject(new Error('WebSocket 连接超时')), this.timeoutMs)
|
|
105
|
+
ws.addEventListener('open', () => {
|
|
106
|
+
clearTimeout(timer)
|
|
107
|
+
this.ws = ws
|
|
108
|
+
ws.addEventListener('message', (ev) => this._onMessage(ev))
|
|
109
|
+
ws.addEventListener('close', () => {
|
|
110
|
+
for (const [, p] of this.pending) p.reject(new Error('CDP 连接已关闭'))
|
|
111
|
+
this.pending.clear()
|
|
112
|
+
})
|
|
113
|
+
resolve()
|
|
114
|
+
})
|
|
115
|
+
ws.addEventListener('error', (ev) => {
|
|
116
|
+
clearTimeout(timer)
|
|
117
|
+
reject(new Error(`WebSocket 连接失败(Chrome 111+ 需 --remote-allow-origins=*):${ev.message || ''}`))
|
|
118
|
+
})
|
|
119
|
+
})
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
_onMessage(ev) {
|
|
123
|
+
let msg
|
|
124
|
+
try {
|
|
125
|
+
msg = JSON.parse(typeof ev.data === 'string' ? ev.data : String(ev.data))
|
|
126
|
+
} catch {
|
|
127
|
+
return
|
|
128
|
+
}
|
|
129
|
+
if (msg.id != null && this.pending.has(msg.id)) {
|
|
130
|
+
const { resolve, reject } = this.pending.get(msg.id)
|
|
131
|
+
this.pending.delete(msg.id)
|
|
132
|
+
if (msg.error) reject(new Error(`${msg.method || 'CDP'} 失败: ${msg.error.message}`))
|
|
133
|
+
else resolve(msg.result || {})
|
|
134
|
+
}
|
|
135
|
+
// 其余是事件推送,M2 不需要
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
send(method, params = {}) {
|
|
139
|
+
if (!this.ws) throw new Error('未 attach')
|
|
140
|
+
const id = ++this.seq
|
|
141
|
+
return new Promise((resolve, reject) => {
|
|
142
|
+
const timer = setTimeout(() => {
|
|
143
|
+
this.pending.delete(id)
|
|
144
|
+
reject(new Error(`${method} 超时 ${this.timeoutMs}ms`))
|
|
145
|
+
}, this.timeoutMs)
|
|
146
|
+
this.pending.set(id, {
|
|
147
|
+
resolve: (v) => { clearTimeout(timer); resolve(v) },
|
|
148
|
+
reject: (e) => { clearTimeout(timer); reject(e) },
|
|
149
|
+
})
|
|
150
|
+
this.ws.send(JSON.stringify({ id, method, params }))
|
|
151
|
+
})
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
close() {
|
|
155
|
+
try { this.ws?.close() } catch { /* ignore */ }
|
|
156
|
+
this.ws = null
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
// ---------------- 高层封装 ----------------
|
|
160
|
+
|
|
161
|
+
async navigate(url, { wait = true, timeoutMs = 15000 } = {}) {
|
|
162
|
+
await this.send('Page.navigate', { url })
|
|
163
|
+
if (!wait) return
|
|
164
|
+
await sleep(300)
|
|
165
|
+
await this.waitFor("document.readyState === 'complete'", timeoutMs)
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
async evaluate(expression, { awaitPromise = false } = {}) {
|
|
169
|
+
const r = await this.send('Runtime.evaluate', {
|
|
170
|
+
expression, returnByValue: true, awaitPromise, userGesture: true,
|
|
171
|
+
})
|
|
172
|
+
if (r.exceptionDetails) {
|
|
173
|
+
const d = r.exceptionDetails
|
|
174
|
+
throw new Error(`JS 异常: ${d.text} ${d.exception?.description || ''}`.trim())
|
|
175
|
+
}
|
|
176
|
+
return r.result?.value
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
async waitFor(expression, timeoutMs = 10000, intervalMs = 120) {
|
|
180
|
+
const end = Date.now() + timeoutMs
|
|
181
|
+
while (Date.now() < end) {
|
|
182
|
+
try {
|
|
183
|
+
if (await this.evaluate(expression)) return true
|
|
184
|
+
} catch { /* 页面跳转中会短暂报错 */ }
|
|
185
|
+
await sleep(intervalMs)
|
|
186
|
+
}
|
|
187
|
+
throw new Error(`等待条件超时: ${expression}`)
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
waitForSelector(selector, timeoutMs) {
|
|
191
|
+
return this.waitFor(`!!document.querySelector(${JSON.stringify(selector)})`, timeoutMs)
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
/**
|
|
195
|
+
* 等元素**真正可见**(有布局尺寸),而不是「DOM 里存在」。
|
|
196
|
+
* ⚠️ 只等 selector 命中会在 DOM 已解析、还没绘制时截到空白页——Bing 上就复现过。
|
|
197
|
+
*/
|
|
198
|
+
waitVisible(selector, timeoutMs = 10000) {
|
|
199
|
+
return this.waitFor(
|
|
200
|
+
`(() => { const e = document.querySelector(${JSON.stringify(selector)});
|
|
201
|
+
if (!e) return false; const r = e.getBoundingClientRect();
|
|
202
|
+
return r.height > 0 && r.width > 0; })()`, timeoutMs)
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
/** 聚焦元素(不改值)。 */
|
|
206
|
+
async focus(selector) {
|
|
207
|
+
const okFocus = await this.evaluate(
|
|
208
|
+
`(() => { const e = document.querySelector(${JSON.stringify(selector)});
|
|
209
|
+
if (!e) return false; e.scrollIntoView({block:'center'}); e.focus(); return true; })()`)
|
|
210
|
+
if (!okFocus) throw new Error(`找不到元素: ${selector}`)
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
/**
|
|
214
|
+
* 填输入框。先 select() 再 insertText —— 任意 Unicode 都能进,中文不需要输入法。
|
|
215
|
+
*/
|
|
216
|
+
async fill(selector, text) {
|
|
217
|
+
await this.focus(selector)
|
|
218
|
+
await this.evaluate(
|
|
219
|
+
`(() => { const e = document.querySelector(${JSON.stringify(selector)});
|
|
220
|
+
if (e && e.select) e.select(); else if (e) e.value = ''; return true; })()`)
|
|
221
|
+
await this.send('Input.insertText', { text: String(text) })
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
/** 按键:Enter / Tab / Escape / Backspace / ArrowDown 等。 */
|
|
225
|
+
async press(key) {
|
|
226
|
+
const table = {
|
|
227
|
+
Enter: [13, 'Enter'], Tab: [9, 'Tab'], Escape: [27, 'Escape'],
|
|
228
|
+
Backspace: [8, 'Backspace'], ArrowDown: [40, 'ArrowDown'], ArrowUp: [38, 'ArrowUp'],
|
|
229
|
+
}
|
|
230
|
+
const [vk, code] = table[key] || [0, key]
|
|
231
|
+
const base = { key, code, windowsVirtualKeyCode: vk, nativeVirtualKeyCode: vk }
|
|
232
|
+
await this.send('Input.dispatchKeyEvent', { type: 'keyDown', ...base })
|
|
233
|
+
if (key === 'Enter') await this.send('Input.dispatchKeyEvent', { type: 'char', text: '\r', ...base })
|
|
234
|
+
await this.send('Input.dispatchKeyEvent', { type: 'keyUp', ...base })
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
/**
|
|
238
|
+
* 真实鼠标点击(不是 el.click()):触发 pointerdown/mousedown/up,行为接近人手。
|
|
239
|
+
* 坐标是视口坐标,和窗口在屏幕哪里、有没有被遮挡无关。
|
|
240
|
+
*/
|
|
241
|
+
async click(selector) {
|
|
242
|
+
await this.evaluate(
|
|
243
|
+
`(() => { const e = document.querySelector(${JSON.stringify(selector)});
|
|
244
|
+
if (e) e.scrollIntoView({block:'center'}); return true; })()`)
|
|
245
|
+
const box = await this.evaluate(
|
|
246
|
+
`(() => { const e = document.querySelector(${JSON.stringify(selector)});
|
|
247
|
+
if (!e) return null; const r = e.getBoundingClientRect();
|
|
248
|
+
return { x: r.x + r.width / 2, y: r.y + r.height / 2 }; })()`)
|
|
249
|
+
if (!box) throw new Error(`找不到元素: ${selector}`)
|
|
250
|
+
for (const type of ['mousePressed', 'mouseReleased']) {
|
|
251
|
+
await this.send('Input.dispatchMouseEvent', {
|
|
252
|
+
type, x: box.x, y: box.y, button: 'left', clickCount: 1,
|
|
253
|
+
})
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
/**
|
|
258
|
+
* 等页面「静默」:readyState=complete 且 body 文本长度连续两次一致。
|
|
259
|
+
* ⚠️ 只等 selector 出现是不够的——点提交后页面会开始一次导航,
|
|
260
|
+
* 旧文档里的 selector 可能仍然命中,于是你截到的是导航后的空白新页。
|
|
261
|
+
*/
|
|
262
|
+
async settle({ timeoutMs = 10000, quietMs = 250, needStable = 2 } = {}) {
|
|
263
|
+
const end = Date.now() + timeoutMs
|
|
264
|
+
let last = -1
|
|
265
|
+
let stable = 0
|
|
266
|
+
while (Date.now() < end) {
|
|
267
|
+
try {
|
|
268
|
+
const st = await this.evaluate(
|
|
269
|
+
"({ rs: document.readyState, len: document.body ? document.body.innerText.length : -1 })")
|
|
270
|
+
if (st.rs === 'complete' && st.len > 0 && st.len === last) stable++
|
|
271
|
+
else stable = 0
|
|
272
|
+
last = st.len
|
|
273
|
+
if (stable >= needStable) return true
|
|
274
|
+
} catch {
|
|
275
|
+
stable = 0 // 导航中执行上下文会被销毁,属正常
|
|
276
|
+
}
|
|
277
|
+
await sleep(quietMs)
|
|
278
|
+
}
|
|
279
|
+
return false
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
/** 装 MutationObserver 计数器(动作前调用),配合 watchRead 判断动作是否真的产生了变化。 */
|
|
283
|
+
async watchBegin() {
|
|
284
|
+
const { WATCH_BEGIN } = await import('./verify.js')
|
|
285
|
+
return this.evaluate(WATCH_BEGIN)
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
/** 读突变数与 URL 变化(动作后调用)。 */
|
|
289
|
+
async watchRead() {
|
|
290
|
+
const { WATCH_READ } = await import('./verify.js')
|
|
291
|
+
return this.evaluate(WATCH_READ)
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
/** 取文本:selector 为空取 body。 */
|
|
295
|
+
async text(selector = 'body') {
|
|
296
|
+
const t = await this.evaluate(
|
|
297
|
+
`(() => { const e = document.querySelector(${JSON.stringify(selector)});
|
|
298
|
+
return e ? e.innerText : null; })()`)
|
|
299
|
+
return t || ''
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
/** 截图(返回 PNG Buffer)。渲染管线直接出图,不依赖窗口是否可见。 */
|
|
303
|
+
async screenshot() {
|
|
304
|
+
const r = await this.send('Page.captureScreenshot', { format: 'png' })
|
|
305
|
+
return Buffer.from(r.data, 'base64')
|
|
306
|
+
}
|
|
307
|
+
}
|
package/lib/png.js
ADDED
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* png.js —— 最小 PNG 编码器(RGBA8,filter=0),只用 node:zlib。
|
|
3
|
+
*
|
|
4
|
+
* 为什么不引第三方包:截图这条链上每加一个依赖,用户就多一个装失败的理由;
|
|
5
|
+
* PNG 容器本身只有 IHDR/IDAT/IEND 三个块,CRC 表 40 行就够。
|
|
6
|
+
*/
|
|
7
|
+
import zlib from 'node:zlib'
|
|
8
|
+
|
|
9
|
+
const CRC_TABLE = (() => {
|
|
10
|
+
const t = new Uint32Array(256)
|
|
11
|
+
for (let n = 0; n < 256; n++) {
|
|
12
|
+
let c = n
|
|
13
|
+
for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1
|
|
14
|
+
t[n] = c >>> 0
|
|
15
|
+
}
|
|
16
|
+
return t
|
|
17
|
+
})()
|
|
18
|
+
|
|
19
|
+
function crc32(buf) {
|
|
20
|
+
let c = 0xffffffff
|
|
21
|
+
for (let i = 0; i < buf.length; i++) c = CRC_TABLE[(c ^ buf[i]) & 0xff] ^ (c >>> 8)
|
|
22
|
+
return (c ^ 0xffffffff) >>> 0
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
function chunk(type, data) {
|
|
26
|
+
const len = Buffer.alloc(4)
|
|
27
|
+
len.writeUInt32BE(data.length, 0)
|
|
28
|
+
const typeBuf = Buffer.from(type, 'ascii')
|
|
29
|
+
const crcBuf = Buffer.alloc(4)
|
|
30
|
+
crcBuf.writeUInt32BE(crc32(Buffer.concat([typeBuf, data])), 0)
|
|
31
|
+
return Buffer.concat([len, typeBuf, data, crcBuf])
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* @param {number} width
|
|
36
|
+
* @param {number} height
|
|
37
|
+
* @param {Buffer} rgba 长度必须为 width*height*4
|
|
38
|
+
* @returns {Buffer} PNG 字节
|
|
39
|
+
*/
|
|
40
|
+
export function encodePNG(width, height, rgba) {
|
|
41
|
+
if (rgba.length !== width * height * 4) {
|
|
42
|
+
throw new Error(`RGBA 长度不符: 期望 ${width * height * 4},实得 ${rgba.length}`)
|
|
43
|
+
}
|
|
44
|
+
const ihdr = Buffer.alloc(13)
|
|
45
|
+
ihdr.writeUInt32BE(width, 0)
|
|
46
|
+
ihdr.writeUInt32BE(height, 4)
|
|
47
|
+
ihdr[8] = 8 // bit depth
|
|
48
|
+
ihdr[9] = 6 // color type: RGBA
|
|
49
|
+
ihdr[10] = 0 // compression
|
|
50
|
+
ihdr[11] = 0 // filter
|
|
51
|
+
ihdr[12] = 0 // interlace
|
|
52
|
+
|
|
53
|
+
// 每行前置一个 filter 字节(0 = None)
|
|
54
|
+
const stride = width * 4
|
|
55
|
+
const raw = Buffer.alloc((stride + 1) * height)
|
|
56
|
+
for (let y = 0; y < height; y++) {
|
|
57
|
+
raw[y * (stride + 1)] = 0
|
|
58
|
+
rgba.copy(raw, y * (stride + 1) + 1, y * stride, (y + 1) * stride)
|
|
59
|
+
}
|
|
60
|
+
return Buffer.concat([
|
|
61
|
+
Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]),
|
|
62
|
+
chunk('IHDR', ihdr),
|
|
63
|
+
chunk('IDAT', zlib.deflateSync(raw, { level: 6 })),
|
|
64
|
+
chunk('IEND', Buffer.alloc(0)),
|
|
65
|
+
])
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* X11 GetImage 给的是 BGRX(32bpp)或 BGR(24bpp),转成 RGBA。
|
|
70
|
+
* @param {Buffer} data
|
|
71
|
+
* @param {number} width
|
|
72
|
+
* @param {number} height
|
|
73
|
+
*/
|
|
74
|
+
export function xImageToRGBA(data, width, height) {
|
|
75
|
+
const px = data.length / (width * height)
|
|
76
|
+
const out = Buffer.alloc(width * height * 4)
|
|
77
|
+
if (px === 4) {
|
|
78
|
+
for (let i = 0, o = 0; i < data.length; i += 4, o += 4) {
|
|
79
|
+
out[o] = data[i + 2]
|
|
80
|
+
out[o + 1] = data[i + 1]
|
|
81
|
+
out[o + 2] = data[i]
|
|
82
|
+
out[o + 3] = 255
|
|
83
|
+
}
|
|
84
|
+
} else if (px === 3) {
|
|
85
|
+
for (let i = 0, o = 0; i < data.length; i += 3, o += 4) {
|
|
86
|
+
out[o] = data[i + 2]
|
|
87
|
+
out[o + 1] = data[i + 1]
|
|
88
|
+
out[o + 2] = data[i]
|
|
89
|
+
out[o + 3] = 255
|
|
90
|
+
}
|
|
91
|
+
} else {
|
|
92
|
+
throw new Error(`不支持的像素宽度: ${px} 字节/像素`)
|
|
93
|
+
}
|
|
94
|
+
return out
|
|
95
|
+
}
|
package/lib/probe.js
ADDED
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* probe.js —— 零依赖的 Linux 桌面能力探测。
|
|
3
|
+
*
|
|
4
|
+
* 只做观测:读环境变量、查 socket 是否可连、查二进制是否在 PATH 上。
|
|
5
|
+
* 不注入输入、不写文件、不联网(CDP 端口只连 127.0.0.1)。
|
|
6
|
+
*/
|
|
7
|
+
import net from 'node:net'
|
|
8
|
+
import fs from 'node:fs'
|
|
9
|
+
import path from 'node:path'
|
|
10
|
+
import { execFile } from 'node:child_process'
|
|
11
|
+
|
|
12
|
+
const CONNECT_TIMEOUT_MS = 400
|
|
13
|
+
|
|
14
|
+
/** 连一下 socket/TCP,只判断「通不通」,不发任何数据。 */
|
|
15
|
+
function canConnect({ socketPath, host, port }) {
|
|
16
|
+
return new Promise((resolve) => {
|
|
17
|
+
let sock
|
|
18
|
+
let settled = false
|
|
19
|
+
const done = (ok, detail) => {
|
|
20
|
+
if (settled) return
|
|
21
|
+
settled = true
|
|
22
|
+
try { sock?.destroy() } catch { /* ignore */ }
|
|
23
|
+
resolve({ ok, detail })
|
|
24
|
+
}
|
|
25
|
+
try {
|
|
26
|
+
sock = socketPath
|
|
27
|
+
? net.createConnection({ path: socketPath })
|
|
28
|
+
: net.createConnection({ host, port })
|
|
29
|
+
} catch (err) {
|
|
30
|
+
return resolve({ ok: false, detail: err.code || String(err) })
|
|
31
|
+
}
|
|
32
|
+
sock.setTimeout(CONNECT_TIMEOUT_MS, () => done(false, 'timeout'))
|
|
33
|
+
sock.on('connect', () => done(true, 'connected'))
|
|
34
|
+
sock.on('error', (err) => done(false, err.code || String(err)))
|
|
35
|
+
})
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** 在 PATH 里找可执行文件(不 spawn,避免依赖 shell)。 */
|
|
39
|
+
function which(bin) {
|
|
40
|
+
const paths = String(process.env.PATH || '').split(path.delimiter).filter(Boolean)
|
|
41
|
+
for (const dir of paths) {
|
|
42
|
+
const full = path.join(dir, bin)
|
|
43
|
+
try {
|
|
44
|
+
fs.accessSync(full, fs.constants.X_OK)
|
|
45
|
+
const st = fs.statSync(full)
|
|
46
|
+
if (st.isFile()) return full
|
|
47
|
+
} catch { /* 继续找 */ }
|
|
48
|
+
}
|
|
49
|
+
return null
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** 用 xdpyinfo 查 X 扩展列表;没装就返回 null(不是失败,是未知)。 */
|
|
53
|
+
function xdpyinfoExtensions(display) {
|
|
54
|
+
return new Promise((resolve) => {
|
|
55
|
+
if (!which('xdpyinfo')) return resolve(null)
|
|
56
|
+
execFile('xdpyinfo', ['-display', display], { timeout: 1500 }, (err, stdout) => {
|
|
57
|
+
if (err || !stdout) return resolve(null)
|
|
58
|
+
const hasXtest = /\bXTEST\b/.test(stdout)
|
|
59
|
+
const exts = (stdout.match(/number of extensions:\s*(\d+)/) || [])[1]
|
|
60
|
+
resolve({ hasXtest, count: exts ? Number(exts) : null })
|
|
61
|
+
})
|
|
62
|
+
})
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
function humanBytes(n) {
|
|
66
|
+
if (!Number.isFinite(n)) return '?'
|
|
67
|
+
const mb = n / (1024 * 1024)
|
|
68
|
+
return mb >= 1024 ? `${(mb / 1024).toFixed(1)}GB` : `${mb.toFixed(0)}MB`
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* 汇总一份能力报告。
|
|
73
|
+
* @param {{cdpPorts?: number[]}} opts
|
|
74
|
+
*/
|
|
75
|
+
export async function probe(opts = {}) {
|
|
76
|
+
const cdpPorts = opts.cdpPorts && opts.cdpPorts.length ? opts.cdpPorts : [9222, 9333]
|
|
77
|
+
const env = process.env
|
|
78
|
+
const sessionType = (env.XDG_SESSION_TYPE || '').toLowerCase() || 'unknown'
|
|
79
|
+
const display = env.DISPLAY || ''
|
|
80
|
+
const wayland = env.WAYLAND_DISPLAY || ''
|
|
81
|
+
const isX11 = sessionType === 'x11' || (!wayland && !!display)
|
|
82
|
+
|
|
83
|
+
// --- X11 socket 探测 ------------------------------------------------
|
|
84
|
+
const displayNum = /:(\d+)/.exec(display)?.[1]
|
|
85
|
+
const x11 = { display, socketPath: null, fsSocket: null, abstractSocket: null, tcp: null }
|
|
86
|
+
if (displayNum) {
|
|
87
|
+
const p = `/tmp/.X11-unix/X${displayNum}`
|
|
88
|
+
x11.socketPath = p
|
|
89
|
+
x11.fsSocket = fs.existsSync(p) ? { ok: true, detail: 'exists' } : { ok: false, detail: 'ENOENT' }
|
|
90
|
+
// 抽象命名空间 socket(Xorg 常见),路径前加 \0
|
|
91
|
+
x11.abstractSocket = await canConnect({ socketPath: `\0${p}` })
|
|
92
|
+
x11.tcp = await canConnect({ host: '127.0.0.1', port: 6000 + Number(displayNum) })
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
// --- XTEST 扩展 ------------------------------------------------------
|
|
96
|
+
const xdpy = display ? await xdpyinfoExtensions(display) : null
|
|
97
|
+
|
|
98
|
+
// --- 其他输入后端 ----------------------------------------------------
|
|
99
|
+
const drivers = {
|
|
100
|
+
cuaDriver: env.CUA_DRIVER_BIN || which('cua-driver'),
|
|
101
|
+
xdotool: which('xdotool'),
|
|
102
|
+
ydotool: which('ydotool'),
|
|
103
|
+
wmctrl: which('wmctrl'),
|
|
104
|
+
}
|
|
105
|
+
const uinput = fs.existsSync('/dev/uinput')
|
|
106
|
+
const uinputWritable = (() => {
|
|
107
|
+
try { fs.accessSync('/dev/uinput', fs.constants.W_OK); return true } catch { return false }
|
|
108
|
+
})()
|
|
109
|
+
const libei = ['/usr/lib/x86_64-linux-gnu/libei.so.1', '/usr/lib/libei.so.1']
|
|
110
|
+
.some((p) => fs.existsSync(p))
|
|
111
|
+
|
|
112
|
+
// --- Chromium 调试端口 ------------------------------------------------
|
|
113
|
+
const cdp = []
|
|
114
|
+
for (const port of cdpPorts) {
|
|
115
|
+
const r = await canConnect({ host: '127.0.0.1', port })
|
|
116
|
+
cdp.push({ port, ...r })
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
// --- 组织成人话 + 结论 ------------------------------------------------
|
|
120
|
+
const ok = (v) => (v ? '✓' : '✗')
|
|
121
|
+
const lines = []
|
|
122
|
+
lines.push('## Linux computer-use capability probe')
|
|
123
|
+
lines.push('')
|
|
124
|
+
lines.push(`Session: ${sessionType || 'unknown'} DISPLAY=${display || '(unset)'} WAYLAND_DISPLAY=${wayland || '(unset)'}`)
|
|
125
|
+
lines.push(`Node: ${process.version} pid=${process.pid}`)
|
|
126
|
+
lines.push('')
|
|
127
|
+
lines.push('### Capture / input injection')
|
|
128
|
+
lines.push(`- X11 socket file ${x11.socketPath || '(no DISPLAY)'}: ${x11.fsSocket ? (x11.fsSocket.ok ? 'present' : 'missing') : '-'}`)
|
|
129
|
+
if (x11.socketPath) {
|
|
130
|
+
lines.push(`- Abstract namespace socket: ${x11.abstractSocket.ok ? 'reachable' : `unreachable (${x11.abstractSocket.detail})`}`)
|
|
131
|
+
lines.push(`- X11 TCP 6000+${displayNum}: ${x11.tcp.ok ? 'reachable' : `unreachable (${x11.tcp.detail})`}`)
|
|
132
|
+
}
|
|
133
|
+
lines.push(`- XTEST extension: ${xdpy ? (xdpy.hasXtest ? 'present (keyboard/mouse injection available)' : 'absent') : 'unknown (xdpyinfo not installed)'}`)
|
|
134
|
+
lines.push(`- /dev/uinput: ${ok(uinput)}${uinput ? ` (${uinputWritable ? 'writable' : 'not writable; needs a udev rule or root'})` : ''}`)
|
|
135
|
+
lines.push(`- libei: ${ok(libei)}${libei ? '' : ' (without it, Wayland can only fall back to uinput)'}`)
|
|
136
|
+
lines.push('')
|
|
137
|
+
lines.push('### Tooling')
|
|
138
|
+
for (const [k, v] of Object.entries(drivers)) {
|
|
139
|
+
lines.push(`- ${k}: ${v || '(not found)'}`)
|
|
140
|
+
}
|
|
141
|
+
lines.push('')
|
|
142
|
+
lines.push('### Chromium DevTools ports (CDP)')
|
|
143
|
+
for (const c of cdp) {
|
|
144
|
+
lines.push(`- 127.0.0.1:${c.port}: ${c.ok ? 'open, CDP available' : `closed (${c.detail})`}`)
|
|
145
|
+
}
|
|
146
|
+
lines.push('')
|
|
147
|
+
|
|
148
|
+
// 结论:哪条通道可用
|
|
149
|
+
const verdict = []
|
|
150
|
+
if (isX11 && (x11.fsSocket?.ok || x11.abstractSocket.ok) && xdpy?.hasXtest !== false) {
|
|
151
|
+
verdict.push('X11 pixel channel: available (XTEST injection + root-capture-then-crop)')
|
|
152
|
+
} else if (isX11) {
|
|
153
|
+
verdict.push('X11 pixel channel: limited (socket or XTEST requirement not met)')
|
|
154
|
+
}
|
|
155
|
+
if (wayland && !isX11) {
|
|
156
|
+
verdict.push(uinputWritable || libei
|
|
157
|
+
? 'Wayland native channel: needs a libei/uinput implementation (not built yet)'
|
|
158
|
+
: 'Wayland native channel: unavailable (neither uinput nor libei)')
|
|
159
|
+
}
|
|
160
|
+
if (cdp.some((c) => c.ok)) {
|
|
161
|
+
verdict.push(`CDP channel: available (port ${cdp.filter((c) => c.ok).map((c) => c.port).join('/')})`)
|
|
162
|
+
} else {
|
|
163
|
+
verdict.push('CDP channel: no DevTools port open (launch Chromium with --remote-debugging-port=9222)')
|
|
164
|
+
}
|
|
165
|
+
lines.push('### Verdict')
|
|
166
|
+
for (const v of verdict) lines.push(`- ${v}`)
|
|
167
|
+
|
|
168
|
+
const text = lines.join('\n')
|
|
169
|
+
return {
|
|
170
|
+
text,
|
|
171
|
+
data: { sessionType, display, wayland, x11, xdpy, drivers, uinput, uinputWritable, libei, cdp, verdict },
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
export { humanBytes }
|