dsh-chrome-bridge 2.0.3 → 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 (49) hide show
  1. package/README.en.md +1 -1
  2. package/README.md +1 -1
  3. package/core/ext.js +8 -1
  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 +10 -10
  10. package/features/frames.js +5 -2
  11. package/i18n/en.js +34 -7
  12. package/i18n/ru.js +34 -7
  13. package/i18n/zh.js +34 -7
  14. package/nav.js +103 -32
  15. package/package.json +1 -1
  16. package/refs.js +309 -73
  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 +31 -5
  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/tabs.js +16 -2
  27. package/tools/wait.js +14 -6
  28. package/vendor/extension/in-page-cursor.js +1 -1
  29. package/vendor/extension/manifest.json +1 -1
  30. package/vendor/extension/popup.css +1 -0
  31. package/vendor/extension/popup.html +6 -3
  32. package/vendor/extension/popup.js +19 -13
  33. package/vendor/extension/sw/actions.js +573 -0
  34. package/vendor/extension/sw/boot.js +2 -1
  35. package/vendor/extension/sw/cdp.js +139 -11
  36. package/vendor/extension/sw/conditions.js +176 -0
  37. package/vendor/extension/sw/confirm.js +39 -7
  38. package/vendor/extension/sw/cursor.js +176 -14
  39. package/vendor/extension/sw/dispatch.js +6 -1
  40. package/vendor/extension/sw/frames.js +543 -47
  41. package/vendor/extension/sw/lifecycle.js +82 -0
  42. package/vendor/extension/sw/ops.js +801 -139
  43. package/vendor/extension/sw/page-access.js +292 -0
  44. package/vendor/extension/sw/popup-api.js +28 -7
  45. package/vendor/extension/sw/snapshot.js +251 -0
  46. package/vendor/extension/sw/state.js +16 -5
  47. package/vendor/extension/sw/tabui.js +9 -2
  48. package/vendor/in-page-cursor.js +1 -1
  49. package/vendor/skill/SKILL.md +8 -7
@@ -0,0 +1,573 @@
1
+ import { ensure, evaluate, POINT_HELPER, send } from './cdp.js'
2
+ import { waitCondition } from './conditions.js'
3
+ import { areAllFramesAllowed, hasProtectedSites, isUrlAllowed } from './confirm.js'
4
+ import { clickPoint, cursorFx, cursorMove, makeClickGuard, moveForAction, RELEASED_MSG } from './cursor.js'
5
+ import { trackOpened } from './dispatch.js'
6
+ import { frameAction, isSensitiveField, sensitiveValue } from './frames.js'
7
+ import { getOps } from './ops.js'
8
+ import { hashUrl, isOpaqueOrigin, originOf, pageAccess, receiptOf, receiptState } from './page-access.js'
9
+ import { S } from './state.js'
10
+ import { isExtUrl, timeLeft, within } from './util.js'
11
+ import { labels } from './tabui.js'
12
+
13
+ async function control(id, deadline, controlEpoch) {
14
+ let seq
15
+ const check = makeClickGuard(id, undefined, () => {
16
+ if (controlEpoch !== undefined && (S.controlEpoch.get(id) || 0) !== controlEpoch) throw new Error(RELEASED_MSG)
17
+ if (seq !== undefined && (!S.attached.has(id) || S.attachSeq.get(id) !== seq)) throw new Error('target_closed / ' + RELEASED_MSG)
18
+ })
19
+ check()
20
+ await within(ensure(id), timeLeft(deadline), '等待调试器超时')
21
+ check()
22
+ seq = S.attachSeq.get(id)
23
+ const page = await pageAccess(id)
24
+ const forbid = () => { throw new Error('USER_DENIED_SENSITIVE') }
25
+ if (page.reason === 'protected') forbid()
26
+ const origin = originOf(page.url)
27
+ let frameGeneration = -1
28
+ let verifiedListEpoch = -1
29
+ const baseGuard = () => {
30
+ check()
31
+ timeLeft(deadline)
32
+ const url = S.tabUrl.get(id)
33
+ if (isExtUrl(url) || (hasProtectedSites() && url && !isUrlAllowed(id, url))) forbid()
34
+ if (ctxRef.expectedNavGen !== undefined && (S.mainNavGeneration.get(id) || 0) !== ctxRef.expectedNavGen) {
35
+ throw new Error('BATCH_NAVIGATED 页面在步骤之间已变化或刷新,已停止后续步骤')
36
+ }
37
+ }
38
+ const ctxRef = { expectedNavGen: undefined }
39
+ const guard = () => {
40
+ baseGuard()
41
+ if (hasProtectedSites() && (frameGeneration !== S.frameGeneration.get(id) || verifiedListEpoch !== S.protectedListEpoch)) forbid()
42
+ }
43
+ const verifyFramesOnly = async () => {
44
+ if (!hasProtectedSites()) return
45
+ for (let tries = 0; tries < 3; tries++) {
46
+ const targetGen = S.frameGeneration.get(id)
47
+ const listEpoch = S.protectedListEpoch
48
+ if (frameGeneration === targetGen && verifiedListEpoch === listEpoch) return
49
+ if (!await areAllFramesAllowed(id, false, true)) forbid()
50
+ if (S.frameGeneration.get(id) === targetGen && S.protectedListEpoch === listEpoch) {
51
+ frameGeneration = targetGen
52
+ verifiedListEpoch = listEpoch
53
+ return
54
+ }
55
+ }
56
+ forbid()
57
+ }
58
+ const verifyFrames = async () => {
59
+ baseGuard()
60
+ await verifyFramesOnly()
61
+ baseGuard()
62
+ }
63
+ const read = async (body, gesture = false) => {
64
+ await verifyFrames()
65
+ const value = await evaluate(id, `(async () => {
66
+ if (location.origin !== ${JSON.stringify(origin)}) throw new Error('页面已变化');
67
+ ${body}
68
+ })()`, gesture, timeLeft(deadline), baseGuard)
69
+ await verifyFrames()
70
+ return value
71
+ }
72
+ await verifyFramesOnly()
73
+ guard()
74
+ return { id, deadline, check, baseGuard, guard, verifyFrames, verifyFramesOnly, read, setExpectedNavGen(g) { ctxRef.expectedNavGen = g } }
75
+ }
76
+
77
+ // Stored weak refs and the reverse map must name the same, still-active document.
78
+ function resolveRef(ref, docId) {
79
+ const state = window.__dshSnap, el = state?.refs?.get(ref)?.deref()
80
+ let view = el?.ownerDocument?.defaultView
81
+ if (!el?.isConnected || !view || state.ids?.get(el) !== ref ||
82
+ (docId !== undefined && state.documentId !== docId)) throw new Error('REF_GONE ' + ref)
83
+ while (view !== window) {
84
+ const frame = view.frameElement
85
+ if (!frame?.isConnected || frame.contentDocument !== view.document) throw new Error('REF_GONE ' + ref)
86
+ view = frame.ownerDocument.defaultView
87
+ }
88
+ return el
89
+ }
90
+
91
+ function elementJS(args) {
92
+ if (args.ref !== undefined && args.ref !== null) return `(${resolveRef})(${JSON.stringify(Number(args.ref))}, ${JSON.stringify(args.expectedDocId)})`
93
+ if (args.activeElement) {
94
+ return `(() => {
95
+ let el = document.activeElement;
96
+ for (let i = 0; el && i < 32; i++) {
97
+ const next = el.shadowRoot?.activeElement || (() => { try { return el.contentDocument?.activeElement; } catch { return null; } })();
98
+ if (!next || next === el) break;
99
+ el = next;
100
+ }
101
+ return el;
102
+ })()`
103
+ }
104
+ return `document.querySelector(${JSON.stringify(args.selector)})`
105
+ }
106
+
107
+ // Bounding-box offsets are only meaningful for positive axis-aligned transforms.
108
+ function framePoint(frame, x, y) {
109
+ const view = frame.ownerDocument.defaultView
110
+ for (let n = frame; n; n = n.assignedSlot || n.parentElement || n.getRootNode().host) {
111
+ const style = view.getComputedStyle(n)
112
+ if ((style.perspective && style.perspective !== 'none') || (style.rotate && style.rotate !== 'none') ||
113
+ (style.scale && style.scale !== 'none' && style.scale.split(/\s+/).some(v => parseFloat(v) <= 0)))
114
+ throw new Error('框架变换无法安全定位')
115
+ if (style.transform && style.transform !== 'none') {
116
+ const m = new view.DOMMatrixReadOnly(style.transform)
117
+ if (!m.is2D || m.b || m.c || m.a <= 0 || m.d <= 0) throw new Error('框架变换无法安全定位')
118
+ }
119
+ }
120
+ const r = frame.getBoundingClientRect(), st = view.getComputedStyle(frame)
121
+ return {
122
+ x: r.left + (x + frame.clientLeft + (parseFloat(st.paddingLeft) || 0)) * r.width / frame.offsetWidth,
123
+ y: r.top + (y + frame.clientTop + (parseFloat(st.paddingTop) || 0)) * r.height / frame.offsetHeight,
124
+ }
125
+ }
126
+
127
+ async function refPoint(ctx, args, beforePress) {
128
+ const expr = elementJS(args)
129
+ return ctx.read(`${POINT_HELPER}
130
+ const el = ${expr};
131
+ const frames = [];
132
+ for (let view = el.ownerDocument.defaultView; view !== window; view = view.parent) frames.push(view.frameElement);
133
+ if (!${!!beforePress}) {
134
+ for (const frame of [...frames].reverse()) await __dsh_scroll_wait(frame);
135
+ await __dsh_scroll_wait(el);
136
+ }
137
+ if (${expr} !== el) throw new Error('REF_GONE ' + ${JSON.stringify(args.ref)});
138
+ const rect = el.getBoundingClientRect();
139
+ if (rect.width <= 0 || rect.height <= 0) throw new Error('目标元素不可见');
140
+ let x = rect.left + rect.width / 2, y = rect.top + rect.height / 2;
141
+ const covered = (node, x, y) => {
142
+ const root = node.getRootNode();
143
+ const hit = root.elementFromPoint?.(x, y);
144
+ return !hit || !(hit === node || node.contains(hit));
145
+ };
146
+ if (covered(el, x, y)) {
147
+ if (!${!!beforePress}) {
148
+ el.scrollIntoView({ block: 'center', inline: 'center', behavior: 'instant' });
149
+ await new Promise(res => { requestAnimationFrame(() => requestAnimationFrame(res)); setTimeout(res, 120); });
150
+ if (${expr} !== el) throw new Error('REF_GONE ' + ${JSON.stringify(args.ref)});
151
+ const r2 = el.getBoundingClientRect();
152
+ if (r2.width <= 0 || r2.height <= 0) throw new Error('目标元素不可见');
153
+ x = r2.left + r2.width / 2; y = r2.top + r2.height / 2;
154
+ }
155
+ if (covered(el, x, y)) throw new Error('目标元素被遮挡');
156
+ }
157
+ for (const frame of frames) {
158
+ ({ x, y } = (${framePoint})(frame, x, y));
159
+ if (covered(frame, x, y)) throw new Error('目标框架被遮挡');
160
+ }
161
+ if (!__dsh_in_view(x, y)) throw new Error('目标元素在视口外');
162
+ const masked = (${isSensitiveField})(el, el.ownerDocument.defaultView.getComputedStyle(el), true);
163
+ return { x: Math.round(x), y: Math.round(y), tag: el.tagName.toLowerCase(), documentId: window.__dshSnap.documentId,
164
+ text: masked ? '••••' : (el.getAttribute('aria-label') || el.innerText || '').slice(0, 60) };
165
+ `)
166
+ }
167
+
168
+ async function clickRef(ctx, args) {
169
+ const target = await refPoint(ctx, args)
170
+ const beforePress = async () => {
171
+ await ctx.verifyFrames()
172
+ if (ctx.verifyDoc) await ctx.verifyDoc()
173
+ const now = await refPoint(ctx, { ...args, expectedDocId: target.documentId }, true)
174
+ if (now.x !== target.x || now.y !== target.y) throw new Error('目标位置已变化')
175
+ await ctx.verifyFrames()
176
+ if (ctx.verifyDoc) await ctx.verifyDoc()
177
+ }
178
+ const hit = await clickPoint(ctx.id, target.x, target.y, { ...args, deadline: ctx.deadline, check: ctx.baseGuard, pressCheck: ctx.guard,
179
+ verifyFrames: ctx.verifyFrames, verifyFramesOnly: ctx.verifyFramesOnly, beforePress, docBinding: ctx.docBinding, expectedNavGen: ctx.expectedNavGen,
180
+ releaseBinding: ctx.releaseBinding, releaseNavGen: ctx.releaseNavGen,
181
+ cursor: args.noCursor ? null : { label: labels[S.UI_LANG].click + ' [' + args.ref + ']' } })
182
+ return { ...hit, target }
183
+ }
184
+
185
+ async function clickFrameRef(ctx, args) {
186
+ const target = await getOps().frameLocate({ tabId: ctx.id, ref: args.ref, timeoutMs: timeLeft(ctx.deadline) })
187
+ if (!target || target.gone) throw new Error('REF_GONE ' + args.ref)
188
+ const pressX = Math.round(target.x), pressY = Math.round(target.y)
189
+ let verifiedFrameGen = null
190
+ const beforePress = async () => {
191
+ await ctx.verifyFrames()
192
+ if (ctx.verifyDoc) await ctx.verifyDoc()
193
+ const startFrameGen = S.frameGeneration.get(ctx.id) || 0
194
+ const now = await getOps().frameLocate({
195
+ tabId: ctx.id, ref: args.ref, verifyHit: true, verifyPoint: { x: pressX, y: pressY }, timeoutMs: timeLeft(ctx.deadline),
196
+ })
197
+ if (!now || now.gone) throw new Error(now?.reason === 'moved' ? '目标位置已变化' : 'REF_GONE ' + args.ref)
198
+ if ((target.documentId && now.documentId !== target.documentId) ||
199
+ Math.round(now.x) !== pressX || Math.round(now.y) !== pressY ||
200
+ (S.frameGeneration.get(ctx.id) || 0) !== startFrameGen) {
201
+ throw new Error('目标位置已变化')
202
+ }
203
+ verifiedFrameGen = startFrameGen
204
+ await ctx.verifyFrames()
205
+ if (ctx.verifyDoc) await ctx.verifyDoc()
206
+ if ((S.frameGeneration.get(ctx.id) || 0) !== verifiedFrameGen) throw new Error('目标位置已变化')
207
+ }
208
+ const framePressCheck = () => {
209
+ ctx.guard()
210
+ if (verifiedFrameGen !== null && (S.frameGeneration.get(ctx.id) || 0) !== verifiedFrameGen) {
211
+ throw new Error('目标位置已变化')
212
+ }
213
+ }
214
+ const frameVerifyFramesOnly = async () => {
215
+ framePressCheck()
216
+ await ctx.verifyFramesOnly()
217
+ framePressCheck()
218
+ }
219
+ const hit = await clickPoint(ctx.id, pressX, pressY, { ...args, deadline: ctx.deadline, check: ctx.baseGuard, pressCheck: framePressCheck,
220
+ verifyFrames: ctx.verifyFrames, verifyFramesOnly: ctx.verifyFramesOnly, pressVerifyFramesOnly: frameVerifyFramesOnly, beforePress, docBinding: ctx.docBinding, expectedNavGen: ctx.expectedNavGen,
221
+ releaseBinding: ctx.releaseBinding, releaseNavGen: ctx.releaseNavGen,
222
+ cursor: args.noCursor ? null : { label: labels[S.UI_LANG].click + ' [' + args.ref + ']' } })
223
+ return { ...hit, target: { ...target, x: pressX, y: pressY } }
224
+ }
225
+
226
+ function buildDocGuardJs(args) {
227
+ return (args.expectedDocToken != null || args.expectedUrl != null || args.expectedUrlHash != null)
228
+ ? `const __tok = globalThis.performance?.timeOrigin ?? window.__dshDocToken;
229
+ const __hash = (${hashUrl})(location.href);
230
+ if (__tok == null ||
231
+ (${args.expectedDocToken != null} && __tok !== ${JSON.stringify(args.expectedDocToken)}) ||
232
+ (${Boolean(args.expectedUrl)} && location.href !== ${JSON.stringify(args.expectedUrl || '')}) ||
233
+ (${Boolean(args.expectedUrlHash)} && __hash !== ${JSON.stringify(args.expectedUrlHash || '')})) return { navigated: true };`
234
+ : ''
235
+ }
236
+
237
+ async function fillFields(ctx, args) {
238
+ const filledRefs = []
239
+ let selected
240
+ const docGuardJs = buildDocGuardJs(args)
241
+ for (const field of args.fields) {
242
+ ctx.baseGuard()
243
+ const expr = elementJS({ ...field, expectedDocId: args.expectedDocId })
244
+ const result = await ctx.read(`
245
+ ${docGuardJs}
246
+ let el;
247
+ try { el = ${expr}; } catch (e) { if (String(e).includes('REF_GONE')) return { gone: true }; throw e; }
248
+ if (!el) return { missing: true };
249
+ const isMasked = () => (${isSensitiveField})(el, el.ownerDocument.defaultView.getComputedStyle(el), true);
250
+ const masked = isMasked();
251
+ const status = await (${frameAction})(0, ${JSON.stringify(field.action)}, ${JSON.stringify({ value: String(field.value ?? ''), checked: field.checked !== false })}, el);
252
+ const options = status === 'noOption' && el.tagName === 'SELECT' ? [...el.options].map(o => o.value).slice(0, 20) : undefined;
253
+ return { ok: status === 'ok' || (typeof status === 'object' && status !== null), status, options, masked: masked || isMasked() };
254
+ `, true)
255
+ ctx.baseGuard()
256
+ if (result?.navigated) throw new Error('BATCH_NAVIGATED 页面在步骤之间已变化或刷新,已停止后续步骤')
257
+ if (!result?.ok) {
258
+ const target = field.ref ?? field.selector ?? 'active'
259
+ const reason = result?.gone ? 'REF_GONE ' + field.ref
260
+ : result?.missing ? '找不到元素' : '字段未接受修改'
261
+ return { filledRefs, failedRef: target, status: result?.gone ? 'gone' : result?.missing ? 'missing' : result?.status, options: result?.options, reason }
262
+ }
263
+ if (result.status && typeof result.status === 'object') selected = result.status
264
+ if (typeof field.value === 'string' && field.value && (result.masked || sensitiveValue(field.value))) ctx.secrets.add(field.value)
265
+ filledRefs.push(field.ref ?? field.selector ?? 'active')
266
+ }
267
+ if (args.submitRef == null) return { filledRefs, submitted: false, ...(selected && { selected }) }
268
+ try {
269
+ const hit = await clickRef(ctx, { ...args, ref: args.submitRef })
270
+ return { ...hit, filledRefs, submitted: true, ...(selected && { selected }) }
271
+ } catch (error) {
272
+ if (!error.message.includes('REF_GONE')) throw error
273
+ return { filledRefs, failedRef: args.submitRef, submitted: false, reason: 'REF_GONE ' + args.submitRef }
274
+ }
275
+ }
276
+
277
+ async function runAction(ctx, args) {
278
+ const { kind } = args
279
+ const options = {
280
+ deadline: ctx.deadline, check: ctx.baseGuard, pressCheck: ctx.guard,
281
+ verifyFrames: ctx.verifyFrames, verifyFramesOnly: ctx.verifyFramesOnly,
282
+ docBinding: ctx.docBinding, docGuardJs: buildDocGuardJs(args), expectedNavGen: ctx.expectedNavGen,
283
+ releaseBinding: ctx.releaseBinding, releaseNavGen: ctx.releaseNavGen,
284
+ beforePress: async () => {
285
+ await ctx.verifyFrames()
286
+ if (ctx.verifyDoc) await ctx.verifyDoc()
287
+ },
288
+ onSensitive: value => ctx.secrets.add(value),
289
+ }
290
+ if (kind === 'clickRef') return clickRef(ctx, args)
291
+ if (kind === 'clickFrameRef') return clickFrameRef(ctx, args)
292
+ if (kind === 'fillFields') return fillFields(ctx, args)
293
+ if (kind === 'scroll' && (args.ref != null || args.selector)) {
294
+ const out = await ctx.read(`${buildDocGuardJs(args)}
295
+ const el = ${elementJS(args)};
296
+ if (!el) throw new Error('找不到滚动元素');
297
+ return { res: (${frameAction})(0, 'scroll', ${JSON.stringify({ dx: args.deltaX, dy: args.deltaY })}, el) };`)
298
+ if (out?.navigated) throw new Error('BATCH_NAVIGATED 页面在步骤之间已变化或刷新,已停止后续步骤')
299
+ return out?.res
300
+ }
301
+ if (args.ref != null && kind === 'hover') {
302
+ const pt = await refPoint(ctx, args)
303
+ await ctx.verifyFrames()
304
+ if (ctx.verifyDoc) await ctx.verifyDoc()
305
+ return { ...await getOps().hover({ ...args, selector: undefined, x: pt.x, y: pt.y }, options), target: pt }
306
+ }
307
+ if (args.ref != null && kind === 'type') {
308
+ const out = await ctx.read(`${buildDocGuardJs(args)}
309
+ const el = ${elementJS(args)}; el.focus(); return { ok: el.getRootNode().activeElement === el };`)
310
+ if (out?.navigated) throw new Error('BATCH_NAVIGATED 页面在步骤之间已变化或刷新,已停止后续步骤')
311
+ if (!out?.ok) throw new Error('聚焦失败')
312
+ args = { ...args, selector: undefined }
313
+ }
314
+ await ctx.verifyFrames()
315
+ return getOps()[kind](args, options)
316
+ }
317
+
318
+ function expectedCondition(expect) {
319
+ if (expect === undefined) return null
320
+ if (!expect || typeof expect !== 'object') throw new Error('Invalid expect')
321
+ const { kind, timeoutMs } = expect
322
+ if (timeoutMs !== undefined && (!Number.isFinite(timeoutMs) || timeoutMs < 1)) throw new Error('Invalid expect timeout')
323
+ if (['dom', 'load', 'idle'].includes(kind)) return { phase: kind, timeoutMs }
324
+ if (kind !== undefined && !['selector', 'text', 'url', 'gone'].includes(kind)) throw new Error('Invalid expect kind')
325
+ const keys = ['selector', 'text', 'url'].filter(key => typeof expect[key] === 'string' && expect[key].length)
326
+ if (keys.length !== 1 || (kind && kind !== 'gone' && kind !== keys[0])) throw new Error('Expected one selector, text or URL')
327
+ return { [keys[0]]: expect[keys[0]], visible: expect.visible, gone: kind === 'gone' || expect.gone === true, timeoutMs }
328
+ }
329
+
330
+ const kinds = new Set(['click', 'clickEl', 'clickText', 'clickRef', 'clickFrameRef', 'type', 'key', 'hover', 'scroll', 'fillFields'])
331
+ export async function act(args) {
332
+ if (!kinds.has(args.kind)) throw new Error('Invalid act kind')
333
+ const expect = expectedCondition(args.expect)
334
+ if (args.kind === 'fillFields' && (!Array.isArray(args.fields) || !args.fields.length || args.fields.some(field =>
335
+ !((Number.isSafeInteger(field?.ref) && field.ref > 0) ||
336
+ (field?.ref == null && typeof field?.selector === 'string' && field.selector.length > 0) ||
337
+ (field?.ref == null && !field?.selector && field?.activeElement === true && field.action !== 'select')) ||
338
+ !['fill', 'check', 'select'].includes(field.action) ||
339
+ (field.action === 'check' ? typeof field.checked !== 'boolean' : typeof field.value !== 'string')))) throw new Error('Invalid fields')
340
+ const id = Number(args.tabId), deadline = Date.now() + (args.timeoutMs ?? 30000)
341
+ const ctx = await control(id, deadline, args.controlEpoch)
342
+ ctx.secrets = new Set()
343
+ const batchBound = args.expectedDocToken != null || args.expectedUrl != null || args.expectedUrlHash != null || Number.isInteger(args.expectedNavGen)
344
+ const needBefore = args.receipt !== false || batchBound
345
+ const startNavGen = batchBound ? (Number.isInteger(args.expectedNavGen) ? args.expectedNavGen : (S.mainNavGeneration.get(id) || 0)) : undefined
346
+ if (batchBound) {
347
+ if ((S.mainNavGeneration.get(id) || 0) !== startNavGen) {
348
+ throw new Error('BATCH_NAVIGATED 页面在步骤之间已变化或刷新,已停止后续步骤')
349
+ }
350
+ ctx.setExpectedNavGen(startNavGen)
351
+ ctx.expectedNavGen = startNavGen
352
+ ctx.docBinding = {
353
+ ...(args.expectedDocToken != null && { expectedDocToken: args.expectedDocToken }),
354
+ ...(args.expectedUrl && { expectedUrl: args.expectedUrl }),
355
+ ...(args.expectedUrlHash && { expectedUrlHash: args.expectedUrlHash }),
356
+ }
357
+ }
358
+ const before = needBefore && await receiptState(id, deadline, batchBound ? ctx.baseGuard : ctx.check)
359
+ const validTok = (tok) => (typeof tok === 'number' && Number.isFinite(tok)) || (typeof tok === 'string' && tok.length > 0)
360
+ const validBeforeTok = validTok(before?.docToken)
361
+ if (batchBound) {
362
+ if (!before || before.reason || !validBeforeTok ||
363
+ (S.mainNavGeneration.get(id) || 0) !== startNavGen ||
364
+ (args.expectedUrl && before.url !== args.expectedUrl) ||
365
+ (args.expectedUrlHash && hashUrl(before.url) !== args.expectedUrlHash) ||
366
+ (args.expectedDocToken != null && before.docToken !== args.expectedDocToken)) {
367
+ throw new Error('BATCH_NAVIGATED 页面在步骤之间已变化或刷新,已停止后续步骤')
368
+ }
369
+ ctx.docBinding = {
370
+ ...ctx.docBinding,
371
+ expectedDocToken: before.docToken,
372
+ ...(before.url && !ctx.docBinding.expectedUrl && !ctx.docBinding.expectedUrlHash ? { expectedUrlHash: hashUrl(before.url) } : {}),
373
+ }
374
+ ctx.verifyDoc = async () => {
375
+ ctx.baseGuard()
376
+ const cur = await evaluate(id, `({ url: location.href, urlHash: (${hashUrl})(location.href), docToken: (globalThis.performance?.timeOrigin ?? window.__dshDocToken) })`, false, Math.min(1000, timeLeft(deadline)), ctx.baseGuard).catch(() => null)
377
+ if (!cur || !validTok(cur.docToken) ||
378
+ (S.mainNavGeneration.get(id) || 0) !== startNavGen ||
379
+ (args.expectedUrl && cur.url !== args.expectedUrl) ||
380
+ (args.expectedUrlHash && cur.urlHash !== args.expectedUrlHash) ||
381
+ cur.docToken !== before.docToken) {
382
+ throw new Error('BATCH_NAVIGATED 页面在步骤之间已变化或刷新,已停止后续步骤')
383
+ }
384
+ }
385
+ }
386
+ ctx.releaseNavGen = ctx.expectedNavGen ?? (S.mainNavGeneration.get(id) || 0)
387
+ ctx.releaseBinding = ctx.docBinding || (validBeforeTok
388
+ ? { expectedDocToken: before.docToken, ...(before.url ? { expectedUrlHash: hashUrl(before.url) } : {}) }
389
+ : undefined)
390
+ const clicks = ['click', 'clickRef', 'clickFrameRef', 'clickEl', 'clickText', 'key'].includes(args.kind) || args.submit || args.submitRef != null
391
+ const run = () => runAction(ctx, args)
392
+ const result = clicks ? await trackOpened(id, run, !!args.chooser) : await run()
393
+ ctx.check()
394
+ if (expect && result.failedRef === undefined) {
395
+ const after = await pageAccess(id)
396
+ result.expectMet = false
397
+ if (!after.reason && Date.now() < deadline) {
398
+ try {
399
+ const { matched } = await waitCondition({ ...expect, tabId: id,
400
+ timeoutMs: Math.min(expect.timeoutMs ?? 15000, deadline - Date.now()) }, { check: ctx.check, phase: expect.phase })
401
+ result.expectMet = matched
402
+ } catch (error) {
403
+ if (!error.message.includes('USER_DENIED_SENSITIVE') || (await pageAccess(id)).reason !== 'protected') throw error
404
+ }
405
+ }
406
+ }
407
+ if (before) {
408
+ const secrets = [...new Set([...ctx.secrets, ...(before.secrets || [])])]
409
+ const beforeOrigin = originOf(before.url)
410
+ const after = await receiptState(id, deadline, ctx.check, [], beforeOrigin, before.url)
411
+ result.receipt = receiptOf(id, before, after, result.openedTabs, secrets)
412
+ if (batchBound && (S.mainNavGeneration.get(id) || 0) !== startNavGen) result.receipt.navigated = true
413
+ if (result.openedTabs) result.openedTabs = result.receipt.openedTabs
414
+ }
415
+ return result
416
+ }
417
+
418
+ async function planDrag(args, resolve, scroll, project, token) {
419
+ const target = end => {
420
+ if (end.ref != null) return resolve(Number(end.ref), args.expectedDocId)
421
+ if (end.selector) return document.querySelector(end.selector)
422
+ if (end.text) {
423
+ let best = null, area = Infinity, exact = false
424
+ for (const el of document.body.querySelectorAll('*')) {
425
+ const s = el.innerText?.trim()
426
+ if (!s?.includes(end.text)) continue
427
+ const r = el.getBoundingClientRect(), size = r.width * r.height
428
+ if (!size || (exact && s !== end.text) || ((s === end.text) === exact && size >= area)) continue
429
+ best = el; area = size; exact = s === end.text
430
+ }
431
+ return best
432
+ }
433
+ if (![end.x, end.y].every(Number.isFinite)) throw new Error('Invalid drag coordinates')
434
+ return document.elementFromPoint(end.x, end.y)
435
+ }
436
+ const src = target(args.from), dst = target(args.to)
437
+ if (!src || !dst) throw new Error('找不到拖拽目标')
438
+ const byElement = end => end.ref != null || end.selector || end.text
439
+ const chain = el => {
440
+ const frames = []
441
+ for (let view = el.ownerDocument.defaultView; view && view !== window; view = view.parent) frames.push(view.frameElement)
442
+ return frames
443
+ }
444
+ if (byElement(args.from)) {
445
+ for (const frame of chain(src).reverse()) await scroll(frame)
446
+ await scroll(src)
447
+ }
448
+ const position = (el, end) => {
449
+ if (!el.isConnected) throw new Error('拖拽目标已失效')
450
+ if (!byElement(end)) return { x: end.x, y: end.y }
451
+ if (end.ref != null && resolve(Number(end.ref), args.expectedDocId) !== el) throw new Error('REF_GONE ' + end.ref)
452
+ const r = el.getBoundingClientRect()
453
+ let x = r.left + r.width / 2, y = r.top + r.height / 2
454
+ if (!r.width || !r.height) throw new Error('拖拽目标不可见')
455
+ for (const f of chain(el)) {
456
+ const point = project(f, x, y)
457
+ x = point.x
458
+ y = point.y
459
+ }
460
+ return { x: Math.round(x), y: Math.round(y) }
461
+ }
462
+ const from = position(src, args.from), to = position(dst, args.to)
463
+ for (const p of [from, to]) if (p.x < 0 || p.y < 0 || p.x >= innerWidth || p.y >= innerHeight) throw new Error('拖拽目标在视口外')
464
+ if (from.x === to.x && from.y === to.y) throw new Error('拖拽起点与终点相同')
465
+ const draggable = src.closest?.('[draggable="true"]')
466
+ const html5 = Boolean(args.html5 || draggable)
467
+ if (html5) {
468
+ const source = draggable || src, transfer = new DataTransfer()
469
+ const dispatch = type => {
470
+ const el = type === 'dragstart' || type === 'dragend' ? source : dst
471
+ if (!el.isConnected) throw new Error('拖拽目标已失效')
472
+ const pt = type === 'dragstart' ? from : to
473
+ const box = el.getBoundingClientRect()
474
+ const xy = el.ownerDocument.defaultView === window ? pt : { x: box.left + box.width / 2, y: box.top + box.height / 2 }
475
+ return !el.dispatchEvent(new el.ownerDocument.defaultView.DragEvent(type, { bubbles: true, composed: true,
476
+ cancelable: true, clientX: xy.x, clientY: xy.y, dataTransfer: transfer }))
477
+ }
478
+ const expiry = setTimeout(() => { if (window.__dshDrag?.token === token) delete window.__dshDrag }, args.timeoutMs)
479
+ window.__dshDrag = { token, dispatch, clear() { clearTimeout(expiry); delete window.__dshDrag } }
480
+ }
481
+ return { from, to, html5 }
482
+ }
483
+
484
+ export async function dragGesture(args) {
485
+ const id = Number(args.tabId), deadline = Date.now() + (args.timeoutMs ?? 15000)
486
+ const ctx = await control(id, deadline, args.controlEpoch)
487
+ const before = args.receipt && await receiptState(id, deadline, ctx.check)
488
+ const token = crypto.randomUUID()
489
+ const endpoints = {
490
+ from: { ...args.from, ...(args.fromSelector && { selector: args.fromSelector }) },
491
+ to: { ...args.to, ...(args.toSelector && { selector: args.toSelector }) },
492
+ html5: args.html5, expectedDocId: args.expectedDocId, timeoutMs: timeLeft(deadline),
493
+ }
494
+ const plan = await ctx.read(`${POINT_HELPER}
495
+ return (${planDrag})(${JSON.stringify(endpoints)}, ${resolveRef}, __dsh_scroll_wait, ${framePoint}, ${JSON.stringify(token)});`)
496
+ const { from, to } = plan
497
+ const steps = Math.max(1, Math.min(60, Math.trunc(args.steps) || 10))
498
+ const cursor = !args.noCursor && S.showCursor
499
+ const fx = name => cursorFx(id, `(window.__dshCursor.${name}(), 1)`, deadline)
500
+ const startReleaseAll = S.releaseAllEpoch
501
+ const press = {}
502
+ let p = from, htmlStarted = false, htmlEnded = false, primaryErr = null, releaseErr = null
503
+ const mouse = async (type, pos, buttons, meta) => {
504
+ await ctx.verifyFrames()
505
+ return send(id, 'Input.dispatchMouseEvent', {
506
+ type, x: pos.x, y: pos.y, button: buttons ? 'left' : 'none', buttons, ...(type === 'mousePressed' && { clickCount: 1 }),
507
+ }, timeLeft(deadline), ctx.guard, meta)
508
+ }
509
+ try {
510
+ if (cursor) {
511
+ await ctx.verifyFrames()
512
+ await moveForAction(id, from.x, from.y, { deadline, agentMs: 1500, check: ctx.baseGuard })
513
+ await ctx.verifyFrames()
514
+ await fx('down')
515
+ await ctx.verifyFrames()
516
+ await cursorMove(id, to.x, to.y, { deadline, straight: true, duration: steps * 16 })
517
+ }
518
+ if (plan.html5) {
519
+ for (const type of ['dragstart', 'dragenter', 'dragover', 'drop', 'dragend']) {
520
+ const cancelled = await ctx.read(`const drag = window.__dshDrag;
521
+ if (drag?.token !== ${JSON.stringify(token)}) throw new Error('拖拽目标已失效');
522
+ return drag.dispatch(${JSON.stringify(type)});`, true)
523
+ if (type === 'dragstart') htmlStarted = true
524
+ if (type === 'dragend') htmlEnded = true
525
+ if (type === 'dragover') plan.accepted = cancelled
526
+ }
527
+ } else {
528
+ await mouse('mouseMoved', from, 0)
529
+ await mouse('mousePressed', from, 1, press)
530
+ for (let i = 1; i <= steps; i++) {
531
+ p = { x: Math.round(from.x + (to.x - from.x) * i / steps), y: Math.round(from.y + (to.y - from.y) * i / steps) }
532
+ await mouse('mouseMoved', p, 1)
533
+ }
534
+ }
535
+ await ctx.verifyFrames()
536
+ } catch (err) {
537
+ primaryErr = err
538
+ throw err
539
+ } finally {
540
+ // Never use send() for cleanup. It would reattach a released debugger.
541
+ const canRelease = () => press.attachSeq && S.attached.has(id) && press.attachSeq === S.attachSeq.get(id) &&
542
+ !S.releasing.has(id) && !S.paused && S.releaseAllEpoch === startReleaseAll
543
+ if (canRelease()) {
544
+ try {
545
+ await ctx.verifyFramesOnly()
546
+ if (canRelease()) {
547
+ await within(chrome.debugger.sendCommand({ tabId: id }, 'Input.dispatchMouseEvent',
548
+ { type: 'mouseReleased', x: p.x, y: p.y, button: 'left', buttons: 0, clickCount: 1 }),
549
+ Math.max(1, deadline - Date.now()), '释放拖拽超时')
550
+ S.postReleaseAt.set(id, Date.now())
551
+ }
552
+ } catch (err) {
553
+ if (!primaryErr) releaseErr = err
554
+ }
555
+ }
556
+ if (plan.html5 || cursor) {
557
+ try {
558
+ await ctx.verifyFrames()
559
+ if (plan.html5) await ctx.read(`const drag = window.__dshDrag;
560
+ if (drag?.token === ${JSON.stringify(token)}) {
561
+ try { if (${htmlStarted && !htmlEnded}) drag.dispatch('dragend') } finally { drag.clear() }
562
+ }`)
563
+ if (cursor) {
564
+ await fx('up')
565
+ }
566
+ } catch { /* user takeover also hides the cursor */ }
567
+ }
568
+ }
569
+ if (releaseErr) throw releaseErr
570
+ ctx.check()
571
+ if (before) plan.receipt = receiptOf(id, before, await receiptState(id, deadline, ctx.check, [], originOf(before.url), before.url))
572
+ return plan
573
+ }
@@ -51,7 +51,7 @@ export function boot() {
51
51
  chrome.alarms.create('dsh-keepalive', { periodInMinutes: 1 })
52
52
  chrome.alarms.onAlarm.addListener((a) => {
53
53
  if (a.name !== 'dsh-keepalive') return
54
- detachIdle().catch((e) => log('detachIdle 失败:', String(e && e.message || e))) // 空闲超过 60 秒的标签页断开调试
54
+ detachIdle().catch((e) => log('detachIdle 失败:', String(e && e.message || e))) // 空闲超过 5 分钟的标签页断开调试
55
55
  if (!S.port) connect()
56
56
  else post({ id: 'ka-' + Date.now(), ok: true, keepalive: true })
57
57
  })
@@ -79,6 +79,7 @@ export function boot() {
79
79
  chrome.tabs.onRemoved.addListener((tabId) => {
80
80
  S.recentTabs.delete(tabId)
81
81
  S.tabUrl.delete(tabId)
82
+ S.frameGeneration.delete(tabId)
82
83
  for (const sess of S.SESSIONS.values()) sess.tabs.delete(tabId)
83
84
  if (S.activeDownload?.tabId === tabId) S.activeDownload.interrupt()
84
85
  clearPending(tabId)