@liyuera/dsh-chrome-browser 0.3.0 → 0.4.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.
Files changed (92) hide show
  1. package/README.md +216 -10
  2. package/extension/manifest.json +4 -3
  3. package/extension/service-worker.js +721 -68
  4. package/lib/activity.d.ts +65 -0
  5. package/lib/activity.d.ts.map +1 -0
  6. package/lib/activity.js +111 -0
  7. package/lib/activity.js.map +1 -0
  8. package/lib/backend.d.ts +193 -11
  9. package/lib/backend.d.ts.map +1 -1
  10. package/lib/backend.js +344 -39
  11. package/lib/backend.js.map +1 -1
  12. package/lib/cdp.d.ts +7 -1
  13. package/lib/cdp.d.ts.map +1 -1
  14. package/lib/cdp.js +17 -1
  15. package/lib/cdp.js.map +1 -1
  16. package/lib/chrome.d.ts +8 -0
  17. package/lib/chrome.d.ts.map +1 -1
  18. package/lib/chrome.js +20 -0
  19. package/lib/chrome.js.map +1 -1
  20. package/lib/client/BrowserActivity.d.ts +22 -0
  21. package/lib/client/BrowserActivity.d.ts.map +1 -0
  22. package/lib/client/BrowserActivity.js +100 -0
  23. package/lib/client/BrowserActivity.js.map +1 -0
  24. package/lib/client/activity.d.ts +27 -0
  25. package/lib/client/activity.d.ts.map +1 -0
  26. package/lib/client/activity.js +57 -0
  27. package/lib/client/activity.js.map +1 -0
  28. package/lib/client/index.d.ts +4 -6
  29. package/lib/client/index.d.ts.map +1 -1
  30. package/lib/client/index.js +13 -19
  31. package/lib/client/index.js.map +1 -1
  32. package/lib/client/tab-catalog.d.ts +11 -1
  33. package/lib/client/tab-catalog.d.ts.map +1 -1
  34. package/lib/client/tab-catalog.js.map +1 -1
  35. package/lib/client/tab-source.d.ts +8 -2
  36. package/lib/client/tab-source.d.ts.map +1 -1
  37. package/lib/client/tab-source.js.map +1 -1
  38. package/lib/client.js +177 -13
  39. package/lib/client.js.map +1 -1
  40. package/lib/console-events.d.ts +32 -0
  41. package/lib/console-events.d.ts.map +1 -0
  42. package/lib/console-events.js +106 -0
  43. package/lib/console-events.js.map +1 -0
  44. package/lib/console-log.d.ts +107 -0
  45. package/lib/console-log.d.ts.map +1 -0
  46. package/lib/console-log.js +158 -0
  47. package/lib/console-log.js.map +1 -0
  48. package/lib/expressions.d.ts +71 -2
  49. package/lib/expressions.d.ts.map +1 -1
  50. package/lib/expressions.js +277 -14
  51. package/lib/expressions.js.map +1 -1
  52. package/lib/help.d.ts +89 -0
  53. package/lib/help.d.ts.map +1 -0
  54. package/lib/help.js +94 -0
  55. package/lib/help.js.map +1 -0
  56. package/lib/index.d.ts +4 -2
  57. package/lib/index.d.ts.map +1 -1
  58. package/lib/index.js +30 -9
  59. package/lib/index.js.map +1 -1
  60. package/lib/presentation.d.ts +130 -0
  61. package/lib/presentation.d.ts.map +1 -0
  62. package/lib/presentation.js +361 -0
  63. package/lib/presentation.js.map +1 -0
  64. package/lib/routes.d.ts +3 -8
  65. package/lib/routes.d.ts.map +1 -1
  66. package/lib/routes.js +20 -109
  67. package/lib/routes.js.map +1 -1
  68. package/lib/skill.d.ts +50 -0
  69. package/lib/skill.d.ts.map +1 -0
  70. package/lib/skill.js +163 -0
  71. package/lib/skill.js.map +1 -0
  72. package/lib/text.d.ts +21 -0
  73. package/lib/text.d.ts.map +1 -1
  74. package/lib/text.js +18 -0
  75. package/lib/text.js.map +1 -1
  76. package/lib/tools.d.ts +22 -4
  77. package/lib/tools.d.ts.map +1 -1
  78. package/lib/tools.js +467 -75
  79. package/lib/tools.js.map +1 -1
  80. package/lib/ws.d.ts +9 -2
  81. package/lib/ws.d.ts.map +1 -1
  82. package/lib/ws.js +49 -19
  83. package/lib/ws.js.map +1 -1
  84. package/package.json +4 -3
  85. package/lib/bindings.d.ts +0 -23
  86. package/lib/bindings.d.ts.map +0 -1
  87. package/lib/bindings.js +0 -49
  88. package/lib/bindings.js.map +0 -1
  89. package/lib/client/TabPicker.d.ts +0 -54
  90. package/lib/client/TabPicker.d.ts.map +0 -1
  91. package/lib/client/TabPicker.js +0 -329
  92. package/lib/client/TabPicker.js.map +0 -1
@@ -44,6 +44,9 @@ function connect() {
44
44
  retryMs = 1000
45
45
  hostOrigin = url.replace(/^ws/u, 'http').replace(/\/chrome-browser\/ext\/ws$/u, '')
46
46
  trace('open ' + url)
47
+ // Chrome suspends this worker when idle, which detaches the debugger and
48
+ // silently ends console capture. Re-arm whatever was capturing.
49
+ void rearmConsole()
47
50
  }
48
51
  socket.onmessage = (event) => { void handle(event.data) }
49
52
  socket.onerror = () => { /* onclose follows */ }
@@ -119,10 +122,14 @@ async function handle(data) {
119
122
  trace('op ' + command.op + ' ' + command.seq)
120
123
  try {
121
124
  // One stuck op (page hang, capture on a hidden window) must never block
122
- // the sequential loop; each op gets its own absolute deadline.
125
+ // the sequential loop; each op gets its own absolute deadline. The op was
126
+ // already dispatched, so its outcome is unknown rather than failed — the
127
+ // host must not have the model retry a click or a type blindly.
123
128
  const outcome = await Promise.race([
124
129
  run(command),
125
- new Promise((resolve, reject) => setTimeout(() => reject(new Error(`${command.op} 超时(12s)`)), 12000)),
130
+ new Promise((resolve, reject) => setTimeout(() => reject(new Error(
131
+ `${command.op} 超时(12s):结果未知,不要直接重试,先确认页面当前状态`,
132
+ )), 12000)),
126
133
  ])
127
134
  results.push({ seq: command.seq, ok: true, data: safe(outcome) })
128
135
  trace('op-ok ' + command.seq)
@@ -134,6 +141,212 @@ async function handle(data) {
134
141
  if (results.length > 0) send({ kind: 'results', results })
135
142
  }
136
143
 
144
+ // ---------------------------------------------------------------- console
145
+ //
146
+ // Console capture attaches Chrome's debugger to one tab and forwards what the
147
+ // page (and the browser) logs. It cannot be a wrapper around `console`: the
148
+ // most useful messages — failed requests, CSP refusals, deprecations — are
149
+ // raised by the browser, never by a page call. Attaching shows Chrome's
150
+ // "started debugging this browser" bar on that tab until capture stops.
151
+ //
152
+ // The host holds the entries in a bounded per-tab buffer; this worker only
153
+ // forwards. It keeps the capture set in storage.session so that a suspended
154
+ // worker can re-attach instead of losing capture silently.
155
+
156
+ /** storage.session key holding the tab ids currently captured. */
157
+ const CONSOLE_TABS_KEY = 'consoleTabs'
158
+
159
+ /** Entries buffered before a flush is forced, so a logging loop cannot grow it. */
160
+ const CONSOLE_QUEUE_MAX = 50
161
+
162
+ /** Delay that batches a burst into one frame. */
163
+ const CONSOLE_FLUSH_MS = 100
164
+
165
+ let consoleQueue = []
166
+ let consoleTimer = null
167
+
168
+ /** Tab ids this worker is capturing, from session storage (survives suspension). */
169
+ async function consoleTabs() {
170
+ try {
171
+ const data = await chrome.storage.session.get(CONSOLE_TABS_KEY)
172
+ const tabs = data[CONSOLE_TABS_KEY]
173
+ return Array.isArray(tabs) ? tabs.filter(id => typeof id === 'number') : []
174
+ } catch {
175
+ return []
176
+ }
177
+ }
178
+
179
+ async function setConsoleTabs(tabs) {
180
+ await chrome.storage.session.set({ [CONSOLE_TABS_KEY]: tabs })
181
+ }
182
+
183
+ /**
184
+ * Mirrors `consoleMessageFrom` in the host's src/console-events.ts, which maps
185
+ * the same events for the CDP backend. The bridge cannot import host modules,
186
+ * so the two copies must stay in step; tests/console-capture.spec.ts requires
187
+ * them to agree on the same recorded events.
188
+ */
189
+ function renderRemote(value) {
190
+ if (typeof value !== 'object' || value === null) return String(value)
191
+ const type = typeof value.type === 'string' ? value.type : 'object'
192
+ if (type === 'undefined') return 'undefined'
193
+ if (value.value !== undefined && value.value !== null) return String(value.value)
194
+ if (value.value === null) return 'null'
195
+ const preview = typeof value.preview === 'object' && value.preview !== null ? value.preview : undefined
196
+ if (preview !== undefined) {
197
+ const properties = Array.isArray(preview.properties) ? preview.properties : []
198
+ const rendered = properties.map((property) => {
199
+ if (typeof property !== 'object' || property === null) return '?'
200
+ const name = typeof property.name === 'string' ? property.name : '?'
201
+ const shown = property.value !== undefined ? String(property.value) : String(property.type ?? '?')
202
+ return `${name}: ${shown}`
203
+ })
204
+ const head = typeof preview.description === 'string' && preview.description !== '' ? preview.description : ''
205
+ const more = preview.overflow === true ? ', …' : ''
206
+ return `${head}{${rendered.join(', ')}${more}}`
207
+ }
208
+ if (typeof value.description === 'string' && value.description !== '') return value.description
209
+ return type
210
+ }
211
+
212
+ function sourceFromStack(stackTrace) {
213
+ if (typeof stackTrace !== 'object' || stackTrace === null) return undefined
214
+ const frames = stackTrace.callFrames
215
+ if (!Array.isArray(frames)) return undefined
216
+ const first = frames[0]
217
+ if (typeof first !== 'object' || first === null) return undefined
218
+ const url = typeof first.url === 'string' ? first.url : ''
219
+ const line = typeof first.lineNumber === 'number' ? first.lineNumber + 1 : undefined
220
+ if (url === '') return undefined
221
+ return line === undefined ? url : `${url}:${line}`
222
+ }
223
+
224
+ function sourceFromEntry(entry) {
225
+ const url = typeof entry.url === 'string' ? entry.url : ''
226
+ if (url === '') return undefined
227
+ const line = typeof entry.lineNumber === 'number' ? entry.lineNumber : undefined
228
+ return line === undefined ? url : `${url}:${line}`
229
+ }
230
+
231
+ const MAX_ARG_CHARS = 2048
232
+
233
+ function consoleMessageFrom(method, params) {
234
+ if (method === 'Runtime.consoleAPICalled') {
235
+ const args = Array.isArray(params.args) ? params.args : []
236
+ const text = args.map(renderRemote).join(' ').slice(0, MAX_ARG_CHARS)
237
+ const level = typeof params.type === 'string' ? params.type : 'log'
238
+ const source = sourceFromStack(params.stackTrace)
239
+ return source === undefined ? { level, text } : { level, text, source }
240
+ }
241
+ if (method === 'Log.entryAdded') {
242
+ const entry = params.entry
243
+ if (typeof entry !== 'object' || entry === null) return undefined
244
+ const text = typeof entry.text === 'string' ? entry.text : ''
245
+ if (text === '') return undefined
246
+ const level = typeof entry.level === 'string' ? entry.level : 'info'
247
+ const source = sourceFromEntry(entry)
248
+ return source === undefined ? { level, text } : { level, text, source }
249
+ }
250
+ return undefined
251
+ }
252
+
253
+ /** Group a batch by tab and push one frame per tab. */
254
+ function flushConsole() {
255
+ if (consoleTimer !== null) {
256
+ clearTimeout(consoleTimer)
257
+ consoleTimer = null
258
+ }
259
+ if (consoleQueue.length === 0) return
260
+ const batch = consoleQueue
261
+ consoleQueue = []
262
+ const byTab = new Map()
263
+ for (const item of batch) {
264
+ const list = byTab.get(item.tabId)
265
+ const entry = item.source === undefined
266
+ ? { level: item.level, text: item.text }
267
+ : { level: item.level, text: item.text, source: item.source }
268
+ if (list === undefined) byTab.set(item.tabId, [entry])
269
+ else list.push(entry)
270
+ }
271
+ for (const [tabId, entries] of byTab) send({ kind: 'event', event: 'console', tabId, entries })
272
+ }
273
+
274
+ /**
275
+ * Buffer one message. The queue drains on a short timer or at
276
+ * CONSOLE_QUEUE_MAX, so it stays bounded even while the socket is down; a
277
+ * closed socket drops the batch rather than growing without limit.
278
+ */
279
+ function queueConsole(tabId, entry) {
280
+ consoleQueue.push({ tabId, ...entry })
281
+ if (consoleQueue.length >= CONSOLE_QUEUE_MAX) {
282
+ flushConsole()
283
+ return
284
+ }
285
+ if (consoleTimer === null) consoleTimer = setTimeout(flushConsole, CONSOLE_FLUSH_MS)
286
+ }
287
+
288
+ /** Attach the debugger to one tab, or report why it cannot be captured. */
289
+ async function startConsole(tabId) {
290
+ const id = Number(tabId)
291
+ if (!Number.isInteger(id)) throw new Error(`无效的标签页 id:${String(tabId)}`)
292
+ const targets = await chrome.debugger.getTargets()
293
+ const existing = targets.find(target => target.tabId === id && target.attached === true)
294
+ if (existing !== undefined && existing.extensionId !== chrome.runtime.id) {
295
+ throw new Error('该标签页已被另一个调试器占用(例如已打开 DevTools);请关闭后重试')
296
+ }
297
+ if (existing === undefined) await chrome.debugger.attach({ tabId: id }, '1.3')
298
+ // Log.enable also replays entries the browser buffered before enabling it.
299
+ await chrome.debugger.sendCommand({ tabId: id }, 'Runtime.enable')
300
+ await chrome.debugger.sendCommand({ tabId: id }, 'Log.enable')
301
+ const tabs = await consoleTabs()
302
+ if (!tabs.includes(id)) await setConsoleTabs([...tabs, id])
303
+ trace('console-start ' + id)
304
+ return { tabId: String(id) }
305
+ }
306
+
307
+ async function stopConsole(tabId) {
308
+ const id = Number(tabId)
309
+ const tabs = await consoleTabs()
310
+ await setConsoleTabs(tabs.filter(candidate => candidate !== id))
311
+ try {
312
+ await chrome.debugger.detach({ tabId: id })
313
+ } catch {
314
+ // Already detached, or the tab is gone: that is the state we wanted.
315
+ }
316
+ trace('console-stop ' + id)
317
+ return { tabId: String(id) }
318
+ }
319
+
320
+ /** Re-attach every captured tab, dropping the ones that can no longer be captured. */
321
+ async function rearmConsole() {
322
+ for (const id of await consoleTabs()) {
323
+ try {
324
+ await startConsole(id)
325
+ } catch (error) {
326
+ trace('console-rearm-failed ' + id + ' ' + String((error && error.message) || error).slice(0, 60))
327
+ await stopConsole(id)
328
+ }
329
+ }
330
+ }
331
+
332
+ chrome.debugger.onEvent.addListener((source, method, params) => {
333
+ if (typeof source.tabId !== 'number') return
334
+ const entry = consoleMessageFrom(method, params || {})
335
+ if (entry === undefined) return
336
+ queueConsole(String(source.tabId), entry)
337
+ })
338
+
339
+ // A user opening DevTools force-detaches us; stop claiming to capture that tab
340
+ // rather than re-attaching behind them.
341
+ chrome.debugger.onDetach.addListener((source) => {
342
+ if (typeof source.tabId !== 'number') return
343
+ void consoleTabs().then(async (tabs) => {
344
+ if (!tabs.includes(source.tabId)) return
345
+ await setConsoleTabs(tabs.filter(id => id !== source.tabId))
346
+ trace('console-detached ' + source.tabId)
347
+ })
348
+ })
349
+
137
350
  async function run(command) {
138
351
  switch (command.op) {
139
352
  case 'list-tabs': {
@@ -148,12 +361,40 @@ async function run(command) {
148
361
  }
149
362
  case 'read':
150
363
  return pageExec(command.args.tabId, readPage, [command.args.includeHtml === true])
364
+ case 'inventory':
365
+ return pageExec(command.args.tabId, pageAgent, [{ op: 'inventory' }])
366
+ case 'wait':
367
+ return pageExec(command.args.tabId, waitCondition, [command.args.selector, command.args.state])
368
+ case 'hover':
369
+ return pageExec(command.args.tabId, hoverSelector, [command.args.selector])
370
+ case 'press':
371
+ // `undefined` is not a serializable injection argument, so an omitted
372
+ // selector travels as null and pressKey treats null as "current focus".
373
+ return pageExec(command.args.tabId, pageAgent, [{
374
+ op: 'press',
375
+ key: command.args.key,
376
+ selector: command.args.selector === undefined ? null : command.args.selector,
377
+ }])
378
+ case 'select':
379
+ return pageExec(command.args.tabId, selectOption, [command.args.selector, command.args.value])
151
380
  case 'eval':
152
- return pageExec(command.args.tabId, evalExpression, [command.args.expression])
381
+ return evalInPage(command.args.tabId, command.args.expression)
153
382
  case 'click':
154
- return pageExec(command.args.tabId, clickSelector, [command.args.selector, command.args.all === true])
383
+ return pageExec(command.args.tabId, pageAgent, [
384
+ { op: 'click', selector: command.args.selector, all: command.args.all === true },
385
+ ])
155
386
  case 'type':
156
387
  return pageExec(command.args.tabId, typeInto, [command.args.selector, command.args.text || '', command.args.clear !== false])
388
+ case 'console-start':
389
+ return startConsole(command.args.tabId)
390
+ case 'console-stop':
391
+ return stopConsole(command.args.tabId)
392
+ case 'close': {
393
+ const id = Number(command.args.tabId)
394
+ if (!Number.isInteger(id)) throw new Error(`无效的标签页 id:${String(command.args.tabId)}`)
395
+ await chrome.tabs.remove(id)
396
+ return { tabId: String(id) }
397
+ }
157
398
  case 'navigate': {
158
399
  const tab = await chrome.tabs.update(Number(command.args.tabId), { url: command.args.url })
159
400
  return { id: tab.id, title: tab.title || '', url: tab.url || '', active: tab.active === true }
@@ -163,16 +404,15 @@ async function run(command) {
163
404
  return { id: tab.id, title: tab.title || '', url: tab.url || '', active: true }
164
405
  }
165
406
  case 'screenshot': {
166
- const tab = await chrome.tabs.get(Number(command.args.tabId))
167
- await chrome.tabs.update(tab.id, { active: true })
168
- // The capture below snapshots the window's visible tab; give the
169
- // activation a beat to paint.
170
- await new Promise(resolve => setTimeout(resolve, 150))
171
- const dataUrl = await captureVisibleWithCooldown(tab.windowId)
172
- // Image bytes travel back as a plain HTTP POST, never as a WS JSON
173
- // frame: an oversized base64 frame closed the bridge right after a
174
- // successful capture. The host persists the upload and returns a path.
175
- const blob = await (await fetch(dataUrl)).blob()
407
+ // Through the debugger, not `chrome.tabs.captureVisibleTab`: that one
408
+ // needs the window visible and painting, so it fails with "image readback
409
+ // failed" while the user is looking at something else — and when the
410
+ // window merely stops repainting it returns the PREVIOUS frame with no
411
+ // sign that it did. Page.captureScreenshot has neither problem.
412
+ const base64 = await captureViaDebugger(Number(command.args.tabId))
413
+ // Image bytes travel back as a plain HTTP POST, never as a WS JSON frame:
414
+ // an oversized frame closed the bridge right after a successful capture.
415
+ const blob = await (await fetch('data:image/jpeg;base64,' + base64)).blob()
176
416
  const upload = await fetch(`${hostOrigin}/chrome-browser/ext/upload`, {
177
417
  method: 'POST',
178
418
  headers: { 'content-type': 'application/octet-stream' },
@@ -192,59 +432,250 @@ async function run(command) {
192
432
  }
193
433
  }
194
434
 
195
- // Chrome rate-limits captureVisibleTab per window (invocations close in
196
- // time hit a quota error and screenshots fail). Serialize captures, keep a
197
- // 800ms minimum gap, and back off once before retrying a quota refusal.
198
- let captureChain = Promise.resolve()
199
- let lastCaptureAt = 0
200
-
201
- // A minimized or hidden window can make captureVisibleTab never settle,
202
- // which would block the whole (sequential) command loop; bound it.
203
- // JPEG at 75 keeps the payload far smaller than PNG: an oversized data URL
204
- // (tens of MB) building a JSON message can OOM-kill the MV3 worker right
205
- // after the capture, mid-send.
206
- function captureWithTimeout(windowId) {
207
- return new Promise((resolve, reject) => {
208
- const timer = setTimeout(() => {
209
- const error = new Error('截图超时(10s),请确认该窗口可见')
210
- error.isCaptureTimeout = true
211
- reject(error)
212
- }, 10000)
213
- chrome.tabs.captureVisibleTab(windowId, { format: 'jpeg', quality: 75 }).then(
214
- data => { clearTimeout(timer); resolve(data) },
215
- error => { clearTimeout(timer); reject(error) },
216
- )
217
- })
435
+ /** JPEG quality the screenshot is encoded at before upload. */
436
+ const SCREENSHOT_QUALITY = 75
437
+
438
+ /**
439
+ * Capture one tab as base64 JPEG through the debugger protocol.
440
+ *
441
+ * `Page.captureScreenshot` renders the tab rather than reading back the window's
442
+ * painted surface, so it works while the tab is in the background and cannot
443
+ * answer with a stale frame. It costs the debugger infobar on that tab, which is
444
+ * why a tab `chrome_console` already attached needs no second attach.
445
+ */
446
+ async function captureViaDebugger(tabId) {
447
+ const id = Number(tabId)
448
+ if (!Number.isInteger(id)) throw new Error(`无效的标签页 id:${String(tabId)}`)
449
+ const targets = await chrome.debugger.getTargets()
450
+ const existing = targets.find(target => target.tabId === id && target.attached === true)
451
+ if (existing !== undefined && existing.extensionId !== chrome.runtime.id) {
452
+ throw new Error('该标签页已被另一个调试器占用(例如已打开 DevTools),无法截图;请关闭 DevTools 后重试')
453
+ }
454
+ const ours = existing !== undefined
455
+ if (!ours) await chrome.debugger.attach({ tabId: id }, '1.3')
456
+ try {
457
+ const response = await chrome.debugger.sendCommand({ tabId: id }, 'Page.captureScreenshot', {
458
+ format: 'jpeg',
459
+ quality: SCREENSHOT_QUALITY,
460
+ captureBeyondViewport: false,
461
+ })
462
+ if (response === undefined || typeof response.data !== 'string' || response.data === '') {
463
+ throw new Error('截图失败:调试通道没有返回图像数据')
464
+ }
465
+ return response.data
466
+ } finally {
467
+ if (!ours) {
468
+ try {
469
+ await chrome.debugger.detach({ tabId: id })
470
+ } catch (error) {
471
+ // Already detached or the tab is gone: that is the state we wanted.
472
+ if (!/not attached|No tab/i.test(String(error && error.message))) throw error
473
+ }
474
+ }
475
+ }
218
476
  }
219
477
 
220
- async function captureVisibleWithCooldown(windowId) {
221
- const run = async () => {
222
- const waitMs = Math.max(0, lastCaptureAt + 800 - Date.now())
223
- if (waitMs > 0) await new Promise(resolve => setTimeout(resolve, waitMs))
224
- lastCaptureAt = Date.now()
225
- try {
226
- return await captureWithTimeout(windowId)
227
- } catch (error) {
228
- // A hidden window times out and a retry cannot help it; only quota
229
- // refusals deserve the back-off retry.
230
- if (error && error.isCaptureTimeout === true) throw error
231
- await new Promise(resolve => setTimeout(resolve, 1500))
232
- lastCaptureAt = Date.now()
233
- return await captureWithTimeout(windowId)
478
+ /**
479
+ * Every page-side helper, nested inside the one function Chrome injects.
480
+ *
481
+ * `chrome.scripting.executeScript` serializes a function's SOURCE and runs it in
482
+ * the page: the closure does not come along. A helper that calls another
483
+ * top-level helper, or reads a top-level const, therefore fails in the page with
484
+ * a ReferenceError while working perfectly in a test that concatenates the
485
+ * declarations into one scope. Nesting them here gives them one real scope.
486
+ * tests/extension-scope.spec.ts fails if a declaration referenced from here is
487
+ * left outside.
488
+ */
489
+ function pageAgent(request) {
490
+ const KEY_CODES = {
491
+ Enter: 13,
492
+ Escape: 27,
493
+ Tab: 9,
494
+ Backspace: 8,
495
+ Delete: 46,
496
+ ArrowUp: 38,
497
+ ArrowDown: 40,
498
+ ArrowLeft: 37,
499
+ ArrowRight: 39,
500
+ Home: 36,
501
+ End: 35,
502
+ PageUp: 33,
503
+ PageDown: 34,
504
+ ' ': 32,
505
+ }
506
+
507
+ // Must stay identical to INTERACTIVE_SELECTOR in the host's src/expressions.ts;
508
+ // a truncated value silently narrows what the inventory can see.
509
+ const INVENTORY_SELECTOR = 'a[href],button,input,select,textarea,[role=button],[role=link],'
510
+ + '[role=checkbox],[role=radio],[role=tab],[role=menuitem],[role=switch],[contenteditable=""],[contenteditable=true]'
511
+
512
+ const INVENTORY_LIMIT = 150
513
+
514
+ const MAX_NAME_CHARS = 80
515
+
516
+ function describeTarget(el) {
517
+ if (el.disabled === true) return 'disabled'
518
+ const rect = el.getBoundingClientRect()
519
+ if (rect.width === 0 || rect.height === 0) return 'invisible'
520
+ const style = getComputedStyle(el)
521
+ if (style.visibility === 'hidden' || style.display === 'none') return 'invisible'
522
+ const x = rect.left + rect.width / 2
523
+ const y = rect.top + rect.height / 2
524
+ if (x < 0 || y < 0 || x > window.innerWidth || y > window.innerHeight) return 'offscreen'
525
+ const root = el.getRootNode()
526
+ const from = root && typeof root.elementFromPoint === 'function' ? root : document
527
+ const hit = from.elementFromPoint(x, y)
528
+ if (hit === null) return 'offscreen'
529
+ return hit === el || el.contains(hit) ? 'ok' : 'covered'
530
+ }
531
+
532
+ function cssEscape(value) {
533
+ return (typeof CSS !== 'undefined' && CSS.escape)
534
+ ? CSS.escape(value)
535
+ : String(value).replace(/[^a-zA-Z0-9_-]/g, (ch) => '\\' + ch)
536
+ }
537
+
538
+ function stableSelector(el) {
539
+ if (el.id) {
540
+ const byId = '#' + cssEscape(el.id)
541
+ try {
542
+ if (document.querySelectorAll(byId).length === 1) return byId
543
+ } catch (error) {
544
+ // An id that is not a usable selector: fall through to the path.
545
+ }
546
+ }
547
+ const parts = []
548
+ let node = el
549
+ for (let depth = 0; node && node.nodeType === 1 && depth < 4; depth++) {
550
+ const tag = node.tagName.toLowerCase()
551
+ const parent = node.parentElement
552
+ if (parent === null) {
553
+ parts.unshift(tag)
554
+ break
555
+ }
556
+ const siblings = Array.from(parent.children).filter((child) => child.tagName === node.tagName)
557
+ parts.unshift(siblings.length > 1 ? tag + ':nth-of-type(' + (siblings.indexOf(node) + 1) + ')' : tag)
558
+ node = parent
559
+ }
560
+ return parts.join(' > ')
561
+ }
562
+
563
+ function nameOf(el) {
564
+ const raw = el.getAttribute('aria-label')
565
+ || (el.innerText && el.innerText.trim())
566
+ || el.value
567
+ || el.getAttribute('placeholder')
568
+ || el.getAttribute('title')
569
+ || el.getAttribute('name')
570
+ || ''
571
+ return String(raw).replace(/\s+/g, ' ').trim().slice(0, MAX_NAME_CHARS)
572
+ }
573
+
574
+ function clickSelector(selector, all) {
575
+ const matched = document.querySelectorAll(selector)
576
+ const targets = all ? Array.from(matched) : matched.length > 0 ? [matched[0]] : []
577
+ const outcome = {
578
+ matched: matched.length, clicked: 0, disabled: 0, invisible: 0, offscreen: 0, covered: 0, ariaDisabled: 0,
579
+ }
580
+ for (const el of targets) {
581
+ const state = describeTarget(el)
582
+ if (state === 'disabled') { outcome.disabled++; continue }
583
+ if (state !== 'ok') outcome[state]++
584
+ if (el.getAttribute('aria-disabled') === 'true') outcome.ariaDisabled++
585
+ el.click()
586
+ outcome.clicked++
587
+ }
588
+ return outcome
589
+ }
590
+
591
+ function interactiveInventory() {
592
+ const matched = document.querySelectorAll(INVENTORY_SELECTOR)
593
+ const items = []
594
+ for (const el of matched) {
595
+ if (items.length >= INVENTORY_LIMIT) break
596
+ const rect = el.getBoundingClientRect()
597
+ if (rect.width === 0 || rect.height === 0) continue
598
+ const style = getComputedStyle(el)
599
+ if (style.visibility === 'hidden' || style.display === 'none') continue
600
+ const state = describeTarget(el)
601
+ items.push({
602
+ selector: stableSelector(el),
603
+ role: el.getAttribute('role') || el.tagName.toLowerCase(),
604
+ name: nameOf(el),
605
+ inView: state !== 'offscreen',
606
+ disabled: el.disabled === true || el.getAttribute('aria-disabled') === 'true',
607
+ covered: state === 'covered',
608
+ })
609
+ }
610
+ return { title: document.title, url: location.href, matched: matched.length, items }
611
+ }
612
+
613
+ function pressKey(key, selector) {
614
+ const el = selector === undefined || selector === null || selector === ''
615
+ ? document.activeElement
616
+ : document.querySelector(selector)
617
+ if (el === null) return { found: false, pressed: false, submitted: false }
618
+ const node = el === null ? document.body : el
619
+ if (typeof node.focus === 'function') node.focus()
620
+ const init = { key, bubbles: true, cancelable: true, keyCode: KEY_CODES[key] || 0 }
621
+ node.dispatchEvent(new KeyboardEvent('keydown', init))
622
+ node.dispatchEvent(new KeyboardEvent('keypress', init))
623
+ node.dispatchEvent(new KeyboardEvent('keyup', init))
624
+ let submitted = false
625
+ if (key === 'Enter') {
626
+ const form = node.form || (typeof node.closest === 'function' ? node.closest('form') : null)
627
+ if (form && typeof form.requestSubmit === 'function') {
628
+ form.requestSubmit()
629
+ submitted = true
630
+ }
234
631
  }
632
+ return { found: true, pressed: true, submitted }
633
+ }
634
+
635
+ // A throw must not escape: `chrome.scripting.executeScript` answers it with
636
+ // `result: undefined` and no `error`, so a malformed selector would reach the
637
+ // model as "no element matched" — the page never saw the query at all.
638
+ try {
639
+ switch (request.op) {
640
+ case 'click': return clickSelector(request.selector, request.all === true)
641
+ case 'inventory': return interactiveInventory()
642
+ case 'press': return pressKey(request.key, request.selector)
643
+ default: return { __dshPageError: '未知的页面操作:' + request.op }
644
+ }
645
+ } catch (error) {
646
+ return { __dshPageError: String((error && error.message) || error) }
235
647
  }
236
- captureChain = captureChain.then(run, run)
237
- return captureChain
238
648
  }
239
649
 
240
- async function pageExec(tabId, func, args) {
650
+ /**
651
+ * Run one injected helper and report a throw as a failure.
652
+ *
653
+ * `chrome.scripting.executeScript` answers an exception inside the injected
654
+ * function with `result: undefined`, so a broken helper would reach the host as
655
+ * `null` — where it reads as "nothing matched". That is how a malformed CSS
656
+ * selector turned into "no element matched selector", and how an undefined
657
+ * helper turned into an empty inventory.
658
+ */
659
+ async function pageExec(tabId, func, args, world) {
241
660
  const [injection] = await chrome.scripting.executeScript({
242
661
  target: { tabId: Number(tabId) },
243
- world: 'MAIN',
662
+ world: world || 'MAIN',
244
663
  func,
245
664
  args,
246
665
  })
247
- return injection !== undefined && injection.result !== undefined ? injection.result : null
666
+ if (injection === undefined) throw new Error('无法注入该标签页(可能已关闭或不允许脚本注入)')
667
+ if (injection.error !== undefined && injection.error !== null) {
668
+ const thrown = injection.error
669
+ const message = thrown.description || thrown.value || '注入的脚本抛出了异常'
670
+ throw new Error(String(message))
671
+ }
672
+ const result = injection.result === undefined ? null : injection.result
673
+ // The MAIN world reports a throw as `result: undefined` alone, so a helper
674
+ // that fails says so in its own envelope instead.
675
+ if (typeof result === 'object' && result !== null && typeof result.__dshPageError === 'string') {
676
+ throw new Error(result.__dshPageError)
677
+ }
678
+ return result
248
679
  }
249
680
 
250
681
  /** MAIN-world helpers (functions are serialized; no outer scope). */
@@ -258,23 +689,231 @@ function readPage(includeHtml) {
258
689
  }
259
690
  }
260
691
 
692
+ /**
693
+ * Evaluate one expression and report the outcome as data.
694
+ *
695
+ * The throw must not escape this function: `chrome.scripting.executeScript`
696
+ * turns an escaping exception into `result: undefined`, which reaches the model
697
+ * as a silent `null` — a syntax error, a runtime throw and a blocked `eval`
698
+ * would all read as "the value is null". The `__dshEval` tag is what tells the
699
+ * host this envelope apart from an expression that legitimately returns an
700
+ * object with `ok`/`value` keys.
701
+ */
261
702
  function evalExpression(expression) {
262
- const value = (0, eval)(expression)
263
- return value === undefined ? 'undefined' : value
703
+ try {
704
+ const value = (0, eval)(expression)
705
+ return { __dshEval: 1, ok: true, value: value === undefined ? null : value }
706
+ } catch (error) {
707
+ return { __dshEval: 1, ok: false, error: String((error && error.message) || error) }
708
+ }
709
+ }
710
+
711
+ /** Whether a failed main-world evaluation failed because the page forbids `eval`. */
712
+ function isEvalBlocked(message) {
713
+ return /unsafe-eval|Content Security Policy|EvalError|call to eval\(\)/i.test(message)
714
+ }
715
+
716
+ /**
717
+ * Run one expression through the debugger protocol.
718
+ *
719
+ * `Runtime.evaluate` is not subject to the page's Content-Security-Policy, which
720
+ * is the whole reason this path exists: on a page whose `script-src` omits
721
+ * `unsafe-eval` — GitHub is one — neither the page's own world nor the
722
+ * extension's isolated world may call `eval`. This is also the path the CDP
723
+ * backend has always used, so an expression means the same thing on both.
724
+ *
725
+ * A per-call attach shows the debugger infobar on that tab and is refused while
726
+ * DevTools is open, so it is a fallback rather than the default.
727
+ */
728
+ async function evalViaDebugger(tabId, expression) {
729
+ const id = Number(tabId)
730
+ if (!Number.isInteger(id)) throw new Error(`无效的标签页 id:${String(tabId)}`)
731
+ const targets = await chrome.debugger.getTargets()
732
+ const existing = targets.find(target => target.tabId === id && target.attached === true)
733
+ if (existing !== undefined && existing.extensionId !== chrome.runtime.id) {
734
+ throw new Error('该标签页已被另一个调试器占用(例如已打开 DevTools),无法执行表达式;请关闭 DevTools 后重试')
735
+ }
736
+ // Console capture may already hold this tab: reuse its session and leave it attached.
737
+ const ours = existing !== undefined
738
+ if (!ours) await chrome.debugger.attach({ tabId: id }, '1.3')
739
+ try {
740
+ const response = await chrome.debugger.sendCommand({ tabId: id }, 'Runtime.evaluate', {
741
+ expression,
742
+ returnByValue: true,
743
+ awaitPromise: true,
744
+ })
745
+ if (response !== undefined && response.exceptionDetails !== undefined) {
746
+ const details = response.exceptionDetails
747
+ const thrown = details.exception
748
+ const message = (thrown !== undefined && (thrown.description || thrown.value)) || details.text || '表达式执行出错'
749
+ throw new Error(String(message))
750
+ }
751
+ const result = response === undefined ? undefined : response.result
752
+ if (result === undefined) return null
753
+ // A result the protocol could not serialize by value arrives as a description.
754
+ return Object.prototype.hasOwnProperty.call(result, 'value') ? result.value : null
755
+ } finally {
756
+ if (!ours) {
757
+ try {
758
+ await chrome.debugger.detach({ tabId: id })
759
+ } catch (error) {
760
+ // Already detached or the tab is gone: that is the state we wanted.
761
+ if (!/not attached|No tab/i.test(String(error && error.message))) throw error
762
+ }
763
+ }
764
+ }
765
+ }
766
+
767
+ /**
768
+ * Run one expression and report the outcome as data.
769
+ *
770
+ * Prefers the page's own world, because that is where the page's JavaScript
771
+ * globals live. When the page's Content-Security-Policy forbids `eval` there,
772
+ * the debugger protocol runs the same expression under no such policy and the
773
+ * answer says which route it took.
774
+ */
775
+ async function evalInPage(tabId, expression) {
776
+ const main = await pageExec(tabId, evalExpression, [expression], 'MAIN')
777
+ if (main !== null && main.ok === true) {
778
+ return { __dshEval: 1, ok: true, value: main.value, world: 'main' }
779
+ }
780
+ const mainError = main !== null && typeof main.error === 'string' ? main.error : 'evaluation failed'
781
+ if (!isEvalBlocked(mainError)) return { __dshEval: 1, ok: false, error: mainError }
782
+
783
+ try {
784
+ const value = await evalViaDebugger(tabId, expression)
785
+ return { __dshEval: 1, ok: true, value, world: 'debugger' }
786
+ } catch (error) {
787
+ const debuggerError = String((error && error.message) || error)
788
+ return {
789
+ __dshEval: 1,
790
+ ok: false,
791
+ error: '页面的 CSP 禁止主世界 eval,调试通道也无法执行。主世界: '
792
+ + mainError + ';调试通道: ' + debuggerError,
793
+ }
794
+ }
795
+ }
796
+
797
+ /**
798
+ * Why one element may not receive a working click, as a single verdict. Mirrors
799
+ * the `probe` inside CLICK_PROBE in the host's src/expressions.ts; tests/click-outcome.spec.ts
800
+ * runs both against the same stub DOM and requires identical output.
801
+ */
802
+
803
+
804
+
805
+
806
+ /**
807
+ * Wait condition. Mirrors `waitExpression` in the host's src/expressions.ts,
808
+ * which the CDP backend evaluates for the same polls; tests/primitives.spec.ts
809
+ * requires the two to agree on every state.
810
+ */
811
+ function waitCondition(selector, state) {
812
+ const el = document.querySelector(selector)
813
+ const attached = el !== null
814
+ let shown = false
815
+ if (attached) {
816
+ const rect = el.getBoundingClientRect()
817
+ if (rect.width > 0 && rect.height > 0) {
818
+ const style = getComputedStyle(el)
819
+ shown = style.visibility !== 'hidden' && style.display !== 'none'
820
+ }
821
+ }
822
+ if (state === 'attached') return attached
823
+ if (state === 'detached') return !attached
824
+ if (state === 'visible') return attached && shown
825
+ if (state === 'hidden') return !attached || !shown
826
+ return false
827
+ }
828
+
829
+ /**
830
+ * Key press. Mirrors `pressExpression` in the host's src/expressions.ts, which
831
+ * the CDP backend evaluates for the same call; tests/primitives.spec.ts requires
832
+ * the two to agree. Synthetic key events trigger no default action, so Enter
833
+ * submits the owning form explicitly.
834
+ */
835
+
836
+
837
+
838
+ /**
839
+ * Select an option. Mirrors `selectExpression` in the host's src/expressions.ts.
840
+ * A value with no matching option leaves the select unchanged and the result
841
+ * says so, rather than reporting a success the page never saw.
842
+ */
843
+ function selectOption(selector, value) {
844
+ const el = document.querySelector(selector)
845
+ if (el === null) return { matched: 0, changed: false, value: '', options: [] }
846
+ if (!(el instanceof HTMLSelectElement)) {
847
+ return { matched: 1, changed: false, value: '', options: [], reason: 'not a <select>' }
848
+ }
849
+ const all = Array.from(el.options).map((option) => option.value)
850
+ const options = all.slice(0, 30)
851
+ // Checked BEFORE assigning: assigning a value no option carries sets
852
+ // selectedIndex to -1 and clears the control, so a call that is about to be
853
+ // rejected would still wipe the selection the user had.
854
+ if (all.indexOf(value) === -1) return { matched: 1, changed: false, value: el.value, options }
855
+ const setter = Object.getOwnPropertyDescriptor(HTMLSelectElement.prototype, 'value').set
856
+ setter.call(el, value)
857
+ const changed = el.value === value
858
+ if (changed) {
859
+ el.dispatchEvent(new Event('input', { bubbles: true }))
860
+ el.dispatchEvent(new Event('change', { bubbles: true }))
861
+ }
862
+ return { matched: 1, changed, value: el.value, options }
264
863
  }
265
864
 
266
- function clickSelector(selector, all) {
267
- const matched = document.querySelectorAll(selector)
268
- let count = 0
269
- if (all) {
270
- for (const el of matched) { el.click(); count++ }
271
- } else if (matched.length > 0) {
272
- matched[0].click()
273
- count = 1
865
+ /**
866
+ * Hover. Mirrors `hoverExpression` in the host's src/expressions.ts. The events
867
+ * are synthetic: they reach the page's listeners but do not set the browser's
868
+ * own hover state, so a control revealed purely by a CSS `:hover` rule stays
869
+ * hidden. Real pointer input is not available on the bridge, so both backends
870
+ * behave the same.
871
+ */
872
+ function hoverSelector(selector) {
873
+ const el = document.querySelector(selector)
874
+ if (el === null) return { matched: 0, hovered: false }
875
+ const rect = el.getBoundingClientRect()
876
+ const init = {
877
+ bubbles: true,
878
+ cancelable: true,
879
+ view: window,
880
+ clientX: rect.left + rect.width / 2,
881
+ clientY: rect.top + rect.height / 2,
882
+ }
883
+ const Pointer = typeof PointerEvent === 'function' ? PointerEvent : MouseEvent
884
+ for (const type of ['pointerover', 'mouseover', 'pointermove', 'mousemove']) {
885
+ el.dispatchEvent(new Pointer(type, init))
886
+ }
887
+ // Enter does not bubble; it is delivered on the target only.
888
+ for (const type of ['pointerenter', 'mouseenter']) {
889
+ el.dispatchEvent(new Pointer(type, { ...init, bubbles: false }))
274
890
  }
275
- return count
891
+ return { matched: 1, hovered: true }
276
892
  }
277
893
 
894
+ /**
895
+ * Interactive-element inventory. Mirrors `inventoryExpression` in the host's
896
+ * src/expressions.ts, which the CDP backend evaluates against the same page;
897
+ * tests/inventory.spec.ts requires the two to agree. Shares `describeTarget`
898
+ * with the click probe, so `covered` means the same thing in both results.
899
+ */
900
+ + '[role=checkbox],[role=radio],[role=tab],[role=menuitem],[role=switch],[contenteditable=""],[contenteditable=true]'
901
+
902
+
903
+
904
+
905
+
906
+
907
+
908
+
909
+
910
+
911
+
912
+ /**
913
+ * Set one control's value. `clear` false inserts at the caret the way the CDP
914
+ * backend's `Input.insertText` does, rather than replacing the whole value —
915
+ * the two backends must mean the same thing by the same argument.
916
+ */
278
917
  function typeInto(selector, text, clear) {
279
918
  const el = document.querySelector(selector)
280
919
  if (!el) return false
@@ -293,7 +932,21 @@ function typeInto(selector, text, clear) {
293
932
  el instanceof HTMLTextAreaElement ? HTMLTextAreaElement.prototype : HTMLInputElement.prototype,
294
933
  'value',
295
934
  ).set
296
- setter.call(el, text)
935
+ let next = text
936
+ let caret = text.length
937
+ if (clear === false) {
938
+ const start = typeof el.selectionStart === 'number' ? el.selectionStart : el.value.length
939
+ const end = typeof el.selectionEnd === 'number' ? el.selectionEnd : start
940
+ next = el.value.slice(0, start) + text + el.value.slice(end)
941
+ caret = start + text.length
942
+ }
943
+ setter.call(el, next)
944
+ try {
945
+ el.setSelectionRange(caret, caret)
946
+ } catch (error) {
947
+ // Number and email inputs refuse setSelectionRange; the value still stands.
948
+ if (!/setSelectionRange|selection/i.test(String(error && error.message))) throw error
949
+ }
297
950
  el.dispatchEvent(new Event('input', { bubbles: true }))
298
951
  el.dispatchEvent(new Event('change', { bubbles: true }))
299
952
  } else {