dsh-chrome-bridge 2.0.2 → 2.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.
Files changed (53) hide show
  1. package/README.en.md +1 -1
  2. package/README.md +1 -1
  3. package/core/ext.js +44 -15
  4. package/core/hosts.js +3 -4
  5. package/core/receipt.js +228 -31
  6. package/core/session.js +11 -14
  7. package/core/tooldef.js +10 -1
  8. package/core/transport.js +67 -17
  9. package/drag.js +118 -36
  10. package/features/frames.js +5 -2
  11. package/i18n/en.js +37 -7
  12. package/i18n/ru.js +37 -7
  13. package/i18n/zh.js +37 -7
  14. package/nav.js +103 -32
  15. package/package.json +1 -1
  16. package/refs.js +317 -77
  17. package/tools/batch.js +311 -0
  18. package/tools/click.js +37 -11
  19. package/tools/dialog.js +19 -2
  20. package/tools/drag.js +52 -9
  21. package/tools/fill.js +71 -22
  22. package/tools/index.js +3 -1
  23. package/tools/input.js +97 -36
  24. package/tools/nav.js +46 -23
  25. package/tools/read.js +2 -0
  26. package/tools/screenshot.js +10 -1
  27. package/tools/tabs.js +16 -2
  28. package/tools/wait.js +14 -6
  29. package/vendor/cb +3 -2
  30. package/vendor/extension/in-page-cursor.js +49 -11
  31. package/vendor/extension/manifest.json +1 -1
  32. package/vendor/extension/popup.css +1 -0
  33. package/vendor/extension/popup.html +6 -3
  34. package/vendor/extension/popup.js +19 -13
  35. package/vendor/extension/sw/actions.js +573 -0
  36. package/vendor/extension/sw/boot.js +7 -1
  37. package/vendor/extension/sw/cdp.js +219 -33
  38. package/vendor/extension/sw/conditions.js +176 -0
  39. package/vendor/extension/sw/confirm.js +39 -7
  40. package/vendor/extension/sw/cursor.js +534 -49
  41. package/vendor/extension/sw/dispatch.js +43 -8
  42. package/vendor/extension/sw/frames.js +643 -49
  43. package/vendor/extension/sw/imaging.js +35 -17
  44. package/vendor/extension/sw/lifecycle.js +82 -0
  45. package/vendor/extension/sw/ops.js +1028 -148
  46. package/vendor/extension/sw/page-access.js +292 -0
  47. package/vendor/extension/sw/popup-api.js +42 -10
  48. package/vendor/extension/sw/record.js +22 -5
  49. package/vendor/extension/sw/snapshot.js +251 -0
  50. package/vendor/extension/sw/state.js +24 -5
  51. package/vendor/extension/sw/tabui.js +10 -2
  52. package/vendor/in-page-cursor.js +49 -11
  53. package/vendor/skill/SKILL.md +8 -7
@@ -1,5 +1,5 @@
1
1
  import { dropChooser, inspectChooser, releaseHold } from './chooser.js'
2
- import { beginAgentInput, installInputListener, markCursor, refreshControls } from './cursor.js'
2
+ import { agentInputSpec, beginAgentInput, bumpControlEpoch, cancelAgentInput, endAgentInput, installInputListener, markCursor, refreshControls, RELEASED_MSG } from './cursor.js'
3
3
  import { getOps } from './ops.js'
4
4
  import { setPaused } from './popup-api.js'
5
5
  import { CDP_VERSION, CHOOSER_TTL_MS, DETACH_IDLE_MS, NET_MAX, PAUSED_MSG, S } from './state.js'
@@ -15,10 +15,14 @@ function shouldKeepAlive(fn) { return subscribe(S.keepAlive, fn) }
15
15
  function rememberAttached(id) {
16
16
  if (S.attached.has(id)) return
17
17
  S.attached.add(id)
18
+ S.attachSeq.set(id, (S.attachSeq.get(id) || 0) + 1)
18
19
  notify(S.tabAttached, id)
19
20
  }
20
21
 
21
22
  function forgetAttached(id, reason) {
23
+ S.mainDocuments.delete(id)
24
+ S.recentSecrets.delete(id)
25
+ for (const [key, snap] of S.frameSnapshots) if (snap.tabId === id) S.frameSnapshots.delete(key)
22
26
  if (S.attached.delete(id)) notify(S.tabDetached, id, reason)
23
27
  }
24
28
 
@@ -50,12 +54,24 @@ async function ensure(tabId) {
50
54
  try { await chrome.debugger.attach({ tabId: id }, CDP_VERSION) }
51
55
  catch (e) { if (!String(e.message || e).includes('Already attached')) throw e }
52
56
  try {
53
- for (const d of ['Page', 'DOM', 'Runtime', 'Network', 'Log']) {
57
+ const enable = async (method, params = {}, optional = false) => {
58
+ check()
59
+ try { await chrome.debugger.sendCommand({ tabId: id }, method, params) }
60
+ catch (error) { if (!optional) throw error }
54
61
  check()
55
- await chrome.debugger.sendCommand({ tabId: id }, d + '.enable', {})
56
62
  }
57
- check()
58
- await chrome.debugger.sendCommand({ tabId: id }, 'Emulation.setFocusEmulationEnabled', { enabled: true })
63
+ await Promise.all([
64
+ ...['Page', 'DOM', 'Runtime', 'Network', 'Log'].map(domain => enable(domain + '.enable')),
65
+ enable('Emulation.setFocusEmulationEnabled', { enabled: true }),
66
+ enable('Page.setLifecycleEventsEnabled', { enabled: true }, true),
67
+ chrome.debugger.sendCommand({ tabId: id }, 'Page.getFrameTree', {}).then((res) => {
68
+ const f = res?.frameTree?.frame
69
+ if (f?.id) {
70
+ S.mainDocuments.set(id, { id: f.id, loaderId: f.loaderId })
71
+ if (typeof f.url === 'string' && f.url) S.tabUrl.set(id, f.url)
72
+ }
73
+ }).catch(() => {}),
74
+ ])
59
75
  check()
60
76
  rememberAttached(id)
61
77
  await installInputListener(id)
@@ -79,28 +95,120 @@ async function ensure(tabId) {
79
95
  /** 慢的 CDP 命令单独放宽:整页 / 大页面截图 15 秒常常不够 */
80
96
  const CDP_TIMEOUT_MS = { 'Page.captureScreenshot': 60_000 }
81
97
 
82
- async function send(tabId, method, params, timeoutMs = CDP_TIMEOUT_MS[method] || 15000) {
98
+ async function send(tabId, method, params, timeoutMs = CDP_TIMEOUT_MS[method] || 15000, check, meta) {
83
99
  const id = Number(tabId)
84
- // 每条命令前都重查暂停:用户中途按了暂停,进行中的点击 / 输入不再往下发
100
+ const epoch = S.controlEpoch.get(id) || 0
101
+ // 每条命令前都重查暂停与放开守卫:用户中途暂停或放开,进行中的点击 / 输入不再往下发
85
102
  if (S.paused) throw new Error(PAUSED_MSG)
103
+ if (typeof check === 'function') check()
86
104
  // 必修:以前只有 evaluate 之前才 ensure,key/hover/scroll/dialog 这些直接 send 的 op
87
105
  // 在空闲松手后永远失败。统一在这里 ensure:既能自动重连,也顺带刷新 lastUsed。
88
106
  const deadline = Date.now() + timeoutMs
89
107
  await within(ensure(id), timeoutMs, '等待调试器超时')
90
108
  timeoutMs = timeLeft(deadline)
91
109
  if (S.paused) throw new Error(PAUSED_MSG)
110
+ if (typeof check === 'function') check()
111
+ if (method.startsWith('Input.') && (S.controlEpoch.get(id) || 0) !== epoch) throw new Error(RELEASED_MSG)
92
112
  S.inflight.set(id, (S.inflight.get(id) || 0) + 1)
93
113
  let timer
114
+ let armedTokens = null
115
+ let dispatchedOk = false
94
116
  try {
95
- if (method.startsWith('Input.')) beginAgentInput(id)
117
+ if (method.startsWith('Input.')) {
118
+ const needCursorSync = S.cursorReady.has(id) && (S.pageAgentUntil.get(id) || 0) < Date.now() + 400
119
+ const docBinding = meta?.docBinding
120
+ if (docBinding) {
121
+ const bindErr = meta?.docBindingError || 'BATCH_NAVIGATED 页面在步骤之间已变化或刷新,已停止后续步骤'
122
+ const hashFn = `function(u){const s=String(u||'');let h1=0x811c9dc5,h2=0x9e3779b9;for(let i=0;i<s.length;i++){const c=s.charCodeAt(i);h1=Math.imul(h1^c,0x01000193);h2=Math.imul(h2^c,0x85ebca6b)}return (h1>>>0).toString(16).padStart(8,'0')+(h2>>>0).toString(16).padStart(8,'0')}`
123
+ const checkDocOnce = async (syncCursor) => {
124
+ const bindMs = Math.min(800, Math.max(50, timeLeft(deadline)))
125
+ let res
126
+ try {
127
+ res = await within(
128
+ chrome.debugger.sendCommand({ tabId: id }, 'Runtime.evaluate', {
129
+ expression: `(() => {
130
+ const tok = globalThis.performance?.timeOrigin ?? (typeof window !== 'undefined' ? window.__dshDocToken : null);
131
+ const href = typeof location !== 'undefined' && location?.href ? location.href : '';
132
+ const hash = (${hashFn})(href);
133
+ const ok = ((typeof tok === 'number' && Number.isFinite(tok)) || (typeof tok === 'string' && tok.length > 0)) &&
134
+ (${docBinding.expectedDocToken != null ? `tok === ${JSON.stringify(docBinding.expectedDocToken)}` : 'true'}) &&
135
+ (${docBinding.expectedUrl ? `href === ${JSON.stringify(docBinding.expectedUrl)}` : 'true'}) &&
136
+ (${docBinding.expectedUrlHash ? `hash === ${JSON.stringify(docBinding.expectedUrlHash)}` : 'true'});
137
+ if (!ok) return { ok: false };
138
+ const synced = ${syncCursor ? 'Boolean(window.__dshCursor && window.__dshCursor.beginAgent && (window.__dshCursor.beginAgent(1500), true))' : 'false'};
139
+ return { ok: true, synced };
140
+ })()`,
141
+ returnByValue: true,
142
+ }),
143
+ bindMs,
144
+ 'BATCH_NAVIGATED 文档校验超时',
145
+ )
146
+ } catch {
147
+ throw new Error(bindErr)
148
+ }
149
+ if (res?.exceptionDetails || res?.result?.value?.ok !== true) {
150
+ throw new Error(bindErr)
151
+ }
152
+ if (res.result.value.synced) S.pageAgentUntil.set(id, Date.now() + 1500)
153
+ }
154
+ // Converge cross-frame guard and document-token check so no async gap remains before Input.*.
155
+ for (let tries = 0; tries < 3; tries++) {
156
+ if (typeof meta?.verifyFramesOnly === 'function') await meta.verifyFramesOnly()
157
+ if (S.paused) throw new Error(PAUSED_MSG)
158
+ if ((S.controlEpoch.get(id) || 0) !== epoch) throw new Error(RELEASED_MSG)
159
+ const genBeforeDoc = S.frameGeneration.get(id)
160
+ const listBeforeDoc = S.protectedListEpoch
161
+ await checkDocOnce(needCursorSync && tries === 0)
162
+ if (S.paused) throw new Error(PAUSED_MSG)
163
+ if ((S.controlEpoch.get(id) || 0) !== epoch) throw new Error(RELEASED_MSG)
164
+ if (typeof meta?.verifyFramesOnly === 'function' &&
165
+ (S.frameGeneration.get(id) !== genBeforeDoc || S.protectedListEpoch !== listBeforeDoc)) {
166
+ if (tries < 2) continue
167
+ throw new Error('USER_DENIED_SENSITIVE')
168
+ }
169
+ if (typeof check === 'function') check()
170
+ break
171
+ }
172
+ timeoutMs = timeLeft(deadline)
173
+ } else if (needCursorSync) {
174
+ const syncMs = Math.min(500, Math.max(50, timeLeft(deadline)))
175
+ let synced = false
176
+ try {
177
+ const res = await within(
178
+ chrome.debugger.sendCommand({ tabId: id }, 'Runtime.evaluate', {
179
+ expression: '(window.__dshCursor && window.__dshCursor.beginAgent ? (window.__dshCursor.beginAgent(1500), true) : false)',
180
+ returnByValue: true,
181
+ }),
182
+ syncMs,
183
+ '同步光标窗口超时',
184
+ )
185
+ synced = res?.result?.value === true && !res?.exceptionDetails
186
+ } catch {}
187
+ if (synced) S.pageAgentUntil.set(id, Date.now() + 1500)
188
+ if (S.paused) throw new Error(PAUSED_MSG)
189
+ if (typeof check === 'function') check()
190
+ if ((S.controlEpoch.get(id) || 0) !== epoch) throw new Error(RELEASED_MSG)
191
+ timeoutMs = timeLeft(deadline)
192
+ }
193
+ // 仅在真正派发对应事件前才发放单次事件配额,避免同步光标或窗口期吞掉真人输入
194
+ const specs = agentInputSpec(method, params)
195
+ if (specs.length) armedTokens = beginAgentInput(id, 1500, specs)
196
+ }
197
+ if (meta && typeof meta === 'object') meta.attachSeq = S.attachSeq.get(id) || 0
96
198
  const p = chrome.debugger.sendCommand({ tabId: id }, method, params || {})
97
199
  // 兜底:任何 CDP 命令都不该把 op 挂死(历史上 mouseWheel 就不回包)
98
- return await Promise.race([
200
+ const res = await Promise.race([
99
201
  p,
100
202
  new Promise((_, rej) => { timer = setTimeout(() => rej(new Error(`CDP ${method} ${Math.round(timeoutMs / 1000)} 秒没回应`)), timeoutMs) }),
101
203
  ])
204
+ dispatchedOk = true
205
+ return res
102
206
  } finally {
103
207
  clearTimeout(timer)
208
+ if (armedTokens && armedTokens.length) {
209
+ if (dispatchedOk) endAgentInput(id, 150, armedTokens)
210
+ else cancelAgentInput(id, armedTokens)
211
+ }
104
212
  const n = (S.inflight.get(id) || 1) - 1
105
213
  if (n <= 0) S.inflight.delete(id); else S.inflight.set(id, n)
106
214
  }
@@ -111,11 +219,15 @@ async function send(tabId, method, params, timeoutMs = CDP_TIMEOUT_MS[method] ||
111
219
  * 实测:Input.dispatchMouseEvent 的 mouseWheel 在 Chrome 155 上**事件生效但不回包**,
112
220
  * 用 send() 等回复会把 scroll 挂死(客户端 45 秒超时)。这里等一小会儿就走。
113
221
  */
114
- async function sendNoReply(tabId, method, params, graceMs = 1500) {
222
+ async function sendNoReply(tabId, method, params, graceMs = 1500, check) {
115
223
  const id = Number(tabId)
224
+ const epoch = S.controlEpoch.get(id) || 0
116
225
  if (S.paused) throw new Error(PAUSED_MSG)
226
+ if (typeof check === 'function') check()
117
227
  await ensure(id)
118
228
  if (S.paused) throw new Error(PAUSED_MSG)
229
+ if (typeof check === 'function') check()
230
+ if ((S.controlEpoch.get(id) || 0) !== epoch) throw new Error(RELEASED_MSG)
119
231
  S.inflight.set(id, (S.inflight.get(id) || 0) + 1)
120
232
  let timer
121
233
  try {
@@ -137,6 +249,7 @@ function failLoadWaiter(tabId, why) {
137
249
 
138
250
  function handleDetach(src, reason) {
139
251
  if (src && src.tabId != null) {
252
+ if (reason !== 'idle') bumpControlEpoch(src.tabId)
140
253
  failLoadWaiter(src.tabId, reason === 'target_closed' ? '标签页在加载中被关掉了' : '等页面加载时调试器被断开了(多半是点掉了 Chrome 的调试提示条)')
141
254
  S.ensureInflight.delete(src.tabId)
142
255
  if (S.activeDownload?.tabId === src.tabId) S.activeDownload.interrupt()
@@ -151,11 +264,20 @@ function handleDetach(src, reason) {
151
264
  }
152
265
 
153
266
  function handleCdpEvent(src, method, params) {
154
- if (method === 'Page.loadEventFired') {
267
+ if (['Page.frameNavigated', 'Page.frameAttached', 'Page.frameDetached'].includes(method))
268
+ S.frameGeneration.set(src.tabId, (S.frameGeneration.get(src.tabId) || 0) + 1)
269
+ if (!src.sessionId) {
270
+ const phase = method === 'Page.lifecycleEvent' ? params.name : method === 'Page.domContentEventFired' ? 'DOMContentLoaded' : method === 'Page.loadEventFired' ? 'load' : null
271
+ if (phase) for (const entry of S.loadWaiters.get(src.tabId) || []) {
272
+ const frame = S.mainDocuments.get(src.tabId)
273
+ entry.observe(phase, params.frameId || frame?.id, params.loaderId || frame?.loaderId)
274
+ }
275
+ }
276
+ if (method === 'Page.loadEventFired' && !src.sessionId) {
155
277
  refreshControls(src.tabId)
156
278
  S.cursorReady.delete(src.tabId)
279
+ S.pageAgentUntil.delete(src.tabId)
157
280
  markCursor(src.tabId, false).catch(() => {}) // 导航后页内光标没了,标签上的小鼠标跟着灭
158
- for (const entry of S.loadWaiters.get(src.tabId) || []) entry.finish(true)
159
281
  }
160
282
  if (method === 'Page.javascriptDialogOpening') {
161
283
  S.dialogs.set(src.tabId, { type: params.type, message: params.message, at: Date.now() })
@@ -179,11 +301,21 @@ function handleCdpEvent(src, method, params) {
179
301
  }
180
302
  if (method === 'Page.frameNavigated' && params.frame?.parentId && S.attached.has(src.tabId))
181
303
  void installInputListener(src.tabId)
182
- if (method === 'Page.frameNavigated' && params.frame && !params.frame.parentId) {
304
+ if (!src.sessionId && method === 'Page.frameNavigated' && params.frame && !params.frame.parentId) {
305
+ S.mainNavGeneration.set(src.tabId, (S.mainNavGeneration.get(src.tabId) || 0) + 1)
306
+ S.mainDocuments.set(src.tabId, { id: params.frame.id, loaderId: params.frame.loaderId })
307
+ for (const entry of S.loadWaiters.get(src.tabId) || []) entry.rebind?.(params.frame.id, params.frame.loaderId)
183
308
  if (typeof params.frame.url === 'string' && params.frame.url) S.tabUrl.set(src.tabId, params.frame.url)
184
309
  dropChooser(src.tabId) // 换页了,原来那个文件框也没了
185
310
  S.chooserSkip.delete(src.tabId)
186
311
  }
312
+ if (!src.sessionId && method === 'Page.navigatedWithinDocument') {
313
+ const main = S.mainDocuments.get(src.tabId)
314
+ if (main?.id && params.frameId && params.frameId === main.id) {
315
+ S.mainNavGeneration.set(src.tabId, (S.mainNavGeneration.get(src.tabId) || 0) + 1)
316
+ if (typeof params.url === 'string' && params.url) S.tabUrl.set(src.tabId, params.url)
317
+ }
318
+ }
187
319
  if (method === 'Network.requestWillBeSent') {
188
320
  // WebSocket/SSE 这类连接永不 finished,netPending 得有个上限(NET 有 400,它原来没有)
189
321
  if (S.netPending.size > NET_MAX) {
@@ -257,10 +389,16 @@ function handleCdpEvent(src, method, params) {
257
389
 
258
390
  /** console 参数 → 一段字。对象/数组用 V8 带的预览拼成 {a: 1, b: "x"},不然只看得到 "Object"。 */
259
391
  function clearPending(tabId) {
260
- S.userTakeover.delete(tabId)
261
- S.agentInputUntil.delete(tabId)
262
- for (const [key, req] of S.netPending) if (req.tabId === tabId) S.netPending.delete(key)
263
- S.netChanged.delete(tabId)
392
+ const id = Number(tabId)
393
+ S.userTakeover.delete(id)
394
+ S.agentInputUntil.delete(id)
395
+ S.agentInputKindUntil.delete(`${id}:pointerdown`)
396
+ S.agentInputKindUntil.delete(`${id}:keydown`)
397
+ S.agentInputEvents.delete(id)
398
+ S.pageAgentUntil.delete(id)
399
+ S.postReleaseAt.delete(id)
400
+ for (const [key, req] of S.netPending) if (req.tabId === id) S.netPending.delete(key)
401
+ S.netChanged.delete(id)
264
402
  }
265
403
 
266
404
  function fmtArg(a) {
@@ -321,13 +459,13 @@ function pushConsole(item) {
321
459
  * 注入表达式并取值(有异常就抛,别把 undefined 当成功)。
322
460
  * userGesture 仅在调用方显式要求时启用:读页面、找元素、画光标都不带,不白送页面一次「用户激活」。
323
461
  */
324
- async function evaluate(tabId, expression, userGesture = false, timeoutMs) {
462
+ async function evaluate(tabId, expression, userGesture = false, timeoutMs, check) {
325
463
  const r = await send(tabId, 'Runtime.evaluate', {
326
464
  expression,
327
465
  returnByValue: true,
328
466
  awaitPromise: true,
329
467
  userGesture: !!userGesture,
330
- }, timeoutMs)
468
+ }, timeoutMs, check)
331
469
  if (r.exceptionDetails) {
332
470
  const d = r.exceptionDetails
333
471
  throw new Error((d.exception && (d.exception.description || d.exception.value)) || d.text || '页面 JS 抛异常')
@@ -345,7 +483,12 @@ const __dsh_visible = (el) => {
345
483
  if (st.visibility === 'hidden' || st.display === 'none' || Number(st.opacity) === 0) return false;
346
484
  return true;
347
485
  };
486
+ const __dsh_in_view = (x, y) => {
487
+ const vw = Number(window.innerWidth) || 0, vh = Number(window.innerHeight) || 0;
488
+ return (!vw || (x >= 0 && x < vw)) && (!vh || (y >= 0 && y < vh));
489
+ };
348
490
  const __dsh_cover = (el, x, y) => {
491
+ if (!__dsh_in_view(x, y)) return { offscreen: true, vw: Number(window.innerWidth) || 0, vh: Number(window.innerHeight) || 0 };
349
492
  const hit = document.elementFromPoint(x, y);
350
493
  const inside = (node, ancestor) => {
351
494
  while (node) {
@@ -354,24 +497,55 @@ const __dsh_cover = (el, x, y) => {
354
497
  }
355
498
  return false;
356
499
  };
357
- if (!hit || inside(hit, el) || inside(el, hit)) return {};
500
+ if (!hit || inside(hit, el)) return {};
501
+ const visibleInClip = (node, px, py) => {
502
+ let anc = node.parentElement || node.getRootNode?.()?.host || null;
503
+ const clipRe = /hidden|clip|auto|scroll/;
504
+ while (anc && anc !== document.body && anc !== document.documentElement) {
505
+ const as = typeof getComputedStyle === 'function' ? getComputedStyle(anc) : null;
506
+ const cx = clipRe.test(as?.overflowX || as?.overflow || '');
507
+ const cy = clipRe.test(as?.overflowY || as?.overflow || '');
508
+ if ((cx || cy) && typeof anc.getBoundingClientRect === 'function') {
509
+ const ar = anc.getBoundingClientRect();
510
+ if (cx && (ar.width <= 0 || px < ar.left || px > ar.right)) return false;
511
+ if (cy && (ar.height <= 0 || py < ar.top || py > ar.bottom)) return false;
512
+ }
513
+ anc = anc.parentElement || anc.getRootNode?.()?.host || null;
514
+ }
515
+ return true;
516
+ };
517
+ const clickableAnc = (node) => {
518
+ if (!node || node === document.body || node === document.documentElement) return false;
519
+ const tag = node.tagName;
520
+ if (tag === 'A' || tag === 'BUTTON' || tag === 'LABEL' || tag === 'SUMMARY') return true;
521
+ const role = typeof node.getAttribute === 'function' ? (node.getAttribute('role') || '') : '';
522
+ if (/^(button|link|tab|menuitem|option|checkbox|radio|switch)$/i.test(role)) return true;
523
+ if (typeof node.onclick === 'function' || (typeof node.getAttribute === 'function' && (node.getAttribute('onclick') || node.getAttribute('tabindex') != null))) return true;
524
+ const hs = typeof getComputedStyle === 'function' ? getComputedStyle(node) : null;
525
+ return hs?.cursor === 'pointer';
526
+ };
527
+ if (inside(el, hit) && clickableAnc(hit) && visibleInClip(el, x, y)) {
528
+ const st = typeof getComputedStyle === 'function' ? getComputedStyle(el) : null;
529
+ if (st?.pointerEvents === 'none') return {};
530
+ }
358
531
  return { occluded: { tag: hit.tagName.toLowerCase(), text: __dsh_norm(hit.innerText).slice(0, 80),
359
532
  id: hit.id, className: hit.getAttribute('class') || '' } };
360
533
  };
361
- const __dsh_point = (el) => {
534
+ const __dsh_scroll_wait = (el) => {
535
+ const r = el.getBoundingClientRect(), view = el.ownerDocument?.defaultView || window;
536
+ if (r.top >= 0 && r.left >= 0 && r.bottom <= view.innerHeight && r.right <= view.innerWidth && r.width > 0 && r.height > 0) {
537
+ const cx = r.left + r.width / 2, cy = r.top + r.height / 2;
538
+ const root = el.getRootNode?.();
539
+ const probe = typeof root?.elementFromPoint === 'function' ? root
540
+ : (typeof document?.elementFromPoint === 'function' ? document : null);
541
+ if (!probe) return;
542
+ const hit = probe.elementFromPoint(cx, cy);
543
+ if (hit === el || (hit && el.contains?.(hit))) return;
544
+ }
362
545
  el.scrollIntoView({ block: 'center', inline: 'center', behavior: 'instant' });
363
546
  return new Promise((res) => {
364
547
  let done = false;
365
- const finish = () => {
366
- if (done) return;
367
- done = true;
368
- const r = el.getBoundingClientRect();
369
- res({ ...__dsh_cover(el, r.left + r.width / 2, r.top + r.height / 2), x: r.left + r.width / 2, y: r.top + r.height / 2,
370
- tag: el.tagName.toLowerCase(),
371
- // 输入框没 innerText,退到 aria-label / placeholder;密码框的 value 绝不拿出来(会上名牌、进工具结果)
372
- text: __dsh_norm(el.innerText || (['button', 'submit', 'reset'].includes(el.type) ? el.value : '') || el.getAttribute('aria-label') ||
373
- el.getAttribute('placeholder') || el.getAttribute('title') || el.getAttribute('alt') || '').slice(0, 80) });
374
- };
548
+ const finish = () => { if (!done) { done = true; res(); } };
375
549
  // 后台标签页里 Chrome 会暂停 requestAnimationFrame —— 只等 rAF 的话这个 Promise
376
550
  // 永远不 resolve,整个 click-el / click-text 就卡死(45 秒超时、还不回话)。
377
551
  // 所以 rAF 之外再挂一个定时器兜底。
@@ -379,11 +553,23 @@ const __dsh_point = (el) => {
379
553
  setTimeout(finish, 120);
380
554
  });
381
555
  };
556
+ const __dsh_point = async (el) => {
557
+ await __dsh_scroll_wait(el);
558
+ if (el.isConnected === false) return null;
559
+ const r = el.getBoundingClientRect();
560
+ if (r.width < 1 || r.height < 1) return null;
561
+ return { ...__dsh_cover(el, r.left + r.width / 2, r.top + r.height / 2), x: r.left + r.width / 2, y: r.top + r.height / 2,
562
+ tag: el.tagName.toLowerCase(),
563
+ // 输入框没 innerText,退到 aria-label / placeholder;密码框的 value 绝不拿出来(会上名牌、进工具结果)
564
+ text: __dsh_norm(el.innerText || (['button', 'submit', 'reset'].includes(el.type) ? el.value : '') || el.getAttribute('aria-label') ||
565
+ el.getAttribute('placeholder') || el.getAttribute('title') || el.getAttribute('alt') || '').slice(0, 80) };
566
+ };
382
567
  `
383
568
 
384
- async function pointOf(tabId, finderJs, deadline) {
385
- const pt = await evaluate(tabId, `(async () => { ${POINT_HELPER} ${finderJs} })()`, false, deadline && timeLeft(deadline))
569
+ async function pointOf(tabId, finderJs, deadline, check) {
570
+ const pt = await evaluate(tabId, `(async () => { ${POINT_HELPER} ${finderJs} })()`, false, deadline && timeLeft(deadline), check)
386
571
  if (!pt) throw new Error('没找到目标元素(可能不可见或文字不匹配)')
572
+ if (pt.offscreen) throw new Error(`目标元素在视口外((${Math.round(pt.x)}, ${Math.round(pt.y)}) 超出 ${pt.vw}×${pt.vh}),请先滚动页面或容器`)
387
573
  return pt
388
574
  }
389
575
 
@@ -0,0 +1,176 @@
1
+ import { ensure, evaluate } from './cdp.js'
2
+ import { makeClickGuard, RELEASED_MSG } from './cursor.js'
3
+ import { hashUrl, originOf, pageAccess, receiptOf, receiptState } from './page-access.js'
4
+ import { PAUSED_MSG, S } from './state.js'
5
+ import { sleep, within } from './util.js'
6
+
7
+ function observeCondition(args, maxMs, origin, token) {
8
+ if (location.origin !== origin) return null
9
+ const matches = () => {
10
+ if (args.phase) return document.readyState === 'complete' || (args.phase !== 'load' && document.readyState === 'interactive')
11
+ if (args.url !== undefined) return location.href.includes(args.url)
12
+ if (args.text !== undefined) return (document.body?.innerText || '').includes(args.text)
13
+ const el = document.querySelector(args.selector)
14
+ if (!el || args.visible === false) return !!el
15
+ const r = el.getBoundingClientRect(), st = getComputedStyle(el)
16
+ return r.width > 0 && r.height > 0 && st.visibility !== 'hidden' && st.display !== 'none'
17
+ }
18
+ const hit = () => matches() !== !!args.gone
19
+ if (hit()) return true
20
+ return new Promise((resolve, reject) => {
21
+ let throttled = null
22
+ const observer = new MutationObserver(() => {
23
+ if (args.text !== undefined) {
24
+ if (!throttled) throttled = setTimeout(() => { throttled = null; check() }, 32)
25
+ return
26
+ }
27
+ check()
28
+ })
29
+ function finish(result, error) {
30
+ window.__dshWaits?.delete(token)
31
+ observer.disconnect()
32
+ clearTimeout(throttled)
33
+ clearInterval(tick)
34
+ clearTimeout(end)
35
+ if (error) reject(error)
36
+ else resolve(result)
37
+ }
38
+ function check() {
39
+ try { if (hit()) finish(true) } catch (error) { finish(false, error) }
40
+ }
41
+ const tick = setInterval(check, 64)
42
+ const end = setTimeout(() => finish(false), maxMs)
43
+ ;(window.__dshWaits ||= new Map()).set(token, () => finish(null))
44
+ observer.observe(document, { subtree: true, childList: true, characterData: true, attributes: true })
45
+ })
46
+ }
47
+
48
+ export async function waitCondition({ tabId, selector, text, url, gone, visible = true, timeoutMs = 15000, receipt = false, controlEpoch, noReattach = false, expectedUrl, expectedUrlHash, expectedDocToken, expectedNavGen: reqNavGen }, { phase, check } = {}) {
49
+ const id = Number(tabId), at = Date.now(), deadline = at + timeoutMs
50
+ const args = { selector, text, url, gone, visible, phase }
51
+ if (!phase && [selector, text, url].filter(x => typeof x === 'string' && x.length > 0).length !== 1)
52
+ throw new Error('Expected one selector, text or URL')
53
+ const batchBound = expectedDocToken != null || expectedUrl != null || expectedUrlHash != null || Number.isInteger(reqNavGen)
54
+ let expectedNavGen = Number.isInteger(reqNavGen) ? reqNavGen : undefined
55
+ const guard = makeClickGuard(id, undefined, () => {
56
+ if (S.releasing.has(id)) throw new Error(RELEASED_MSG)
57
+ if (Number.isInteger(controlEpoch) && (S.controlEpoch.get(id) || 0) !== controlEpoch) throw new Error(RELEASED_MSG)
58
+ if (expectedNavGen !== undefined && (S.mainNavGeneration.get(id) || 0) !== expectedNavGen) {
59
+ throw new Error('BATCH_NAVIGATED 页面在步骤之间已变化或刷新,已停止后续步骤')
60
+ }
61
+ if (typeof check === 'function') check()
62
+ })
63
+ guard()
64
+ if (noReattach && !S.attached.has(id)) throw new Error(RELEASED_MSG)
65
+ await within(ensure(id), Math.max(1, timeoutMs), '等待调试器超时')
66
+ const seq = S.attachSeq.get(id)
67
+ const session = () => {
68
+ if (S.paused) throw new Error('PAUSED ' + PAUSED_MSG)
69
+ guard()
70
+ if (!S.attached.has(id) || S.attachSeq.get(id) !== seq) throw new Error('target_closed / ' + RELEASED_MSG)
71
+ }
72
+ const needBefore = receipt || batchBound
73
+ if (batchBound && expectedNavGen === undefined) expectedNavGen = S.mainNavGeneration.get(id) || 0
74
+ const before = needBefore && await receiptState(id, deadline, session)
75
+ if (batchBound) {
76
+ if (!before || before.reason || before.docToken == null ||
77
+ (S.mainNavGeneration.get(id) || 0) !== expectedNavGen ||
78
+ (expectedUrl && before.url !== expectedUrl) ||
79
+ (expectedUrlHash && hashUrl(before.url) !== expectedUrlHash) ||
80
+ (expectedDocToken != null && before.docToken !== expectedDocToken)) {
81
+ throw new Error('BATCH_NAVIGATED 页面在步骤之间已变化或刷新,已停止后续步骤')
82
+ }
83
+ }
84
+ function cancelObserver(token) {
85
+ if (!S.attached.has(id) || S.attachSeq.get(id) !== seq) return
86
+ void chrome.debugger.sendCommand({ tabId: id }, 'Runtime.evaluate', {
87
+ expression: `window.__dshWaits?.get(${JSON.stringify(token)})?.()`,
88
+ }).catch(() => {})
89
+ }
90
+ async function observe(page, remaining) {
91
+ const token = crypto.randomUUID(), generation = S.frameGeneration.get(id)
92
+ const expr = `(${observeCondition})(${JSON.stringify(args)},${remaining},${JSON.stringify(originOf(page.url))},${JSON.stringify(token)})`
93
+ let timer, settledInDocument = false
94
+ const signal = new Promise((resolve, reject) => {
95
+ timer = setInterval(() => {
96
+ try {
97
+ session()
98
+ if (S.frameGeneration.get(id) !== generation || S.dialogs.has(id)) resolve(null)
99
+ else if (Date.now() >= deadline) resolve(false)
100
+ } catch (error) { reject(error) }
101
+ }, 25)
102
+ })
103
+ try {
104
+ const result = evaluate(id, expr, false, remaining + 100, session).then(value => {
105
+ settledInDocument = true
106
+ return value
107
+ })
108
+ return await Promise.race([result, signal])
109
+ } catch (error) {
110
+ session()
111
+ if (!/context.*(?:destroyed|not found)|cannot find context|navigat|inspected target navigated/i.test(error.message)) throw error
112
+ return null
113
+ } finally {
114
+ clearInterval(timer)
115
+ if (!settledInDocument) cancelObserver(token)
116
+ }
117
+ }
118
+
119
+ while (Date.now() < deadline) {
120
+ session()
121
+ const page = await pageAccess(id)
122
+ if (page.reason === 'protected') throw new Error('USER_DENIED_SENSITIVE')
123
+ if (page.reason === 'dialog') break
124
+ const remaining = deadline - Date.now()
125
+ if (remaining <= 0) break
126
+ const matched = await observe(page, remaining)
127
+ session()
128
+ if (matched === false) break
129
+ if (!matched) { await sleep(16); continue }
130
+ const after = await pageAccess(id)
131
+ if (after.reason === 'protected') throw new Error('USER_DENIED_SENSITIVE')
132
+ if (after.reason || after.url !== page.url) continue
133
+ if (phase === 'idle') {
134
+ const idleStart = Date.now()
135
+ let quiet = false
136
+ while (Date.now() < deadline) {
137
+ session()
138
+ const busy = [...S.netPending.values()].some(r => r.tabId === id && !['EventSource', 'WebSocket'].includes(r.type))
139
+ if (!busy && Date.now() - Math.max(idleStart, S.netChanged.get(id) || 0) >= 500) {
140
+ quiet = true
141
+ break
142
+ }
143
+ await sleep(Math.min(25, Math.max(1, deadline - Date.now())))
144
+ }
145
+ if (!quiet) break
146
+ }
147
+ session()
148
+ const out = { matched: true, waitedMs: Date.now() - at }
149
+ if (before) {
150
+ const after = await receiptState(id, Math.max(Date.now() + 500, deadline), session, [], originOf(before.url), before.url)
151
+ session()
152
+ if (batchBound && (after.reason === 'origin_changed' || after.docToken == null ||
153
+ (expectedUrl && after.url !== expectedUrl) ||
154
+ (expectedUrlHash && hashUrl(after.url) !== expectedUrlHash) ||
155
+ (expectedDocToken != null && after.docToken !== expectedDocToken))) {
156
+ throw new Error('BATCH_NAVIGATED 页面在步骤之间已变化或刷新,已停止后续步骤')
157
+ }
158
+ if (receipt) out.receipt = receiptOf(id, before, after)
159
+ }
160
+ return out
161
+ }
162
+ session()
163
+ const out = { matched: false, waitedMs: Date.now() - at }
164
+ if (before && (receipt || batchBound)) {
165
+ const after = await receiptState(id, Math.max(Date.now() + 500, deadline), session, [], originOf(before.url), before.url)
166
+ session()
167
+ if (batchBound && (after.reason === 'origin_changed' || after.docToken == null ||
168
+ (expectedUrl && after.url !== expectedUrl) ||
169
+ (expectedUrlHash && hashUrl(after.url) !== expectedUrlHash) ||
170
+ (expectedDocToken != null && after.docToken !== expectedDocToken))) {
171
+ throw new Error('BATCH_NAVIGATED 页面在步骤之间已变化或刷新,已停止后续步骤')
172
+ }
173
+ if (receipt) out.receipt = receiptOf(id, before, after)
174
+ }
175
+ return out
176
+ }