dsh-chrome-bridge 1.20.0 → 2.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.en.md +6 -2
- package/README.md +6 -2
- package/client.js +110 -29
- package/core/ext.js +119 -0
- package/core/hosts.js +277 -0
- package/core/locale.js +8 -0
- package/core/receipt.js +56 -0
- package/core/session.js +157 -0
- package/core/shots.js +56 -0
- package/core/tooldef.js +142 -0
- package/core/transport.js +212 -0
- package/core/upload.js +59 -0
- package/devtools.js +18 -8
- package/download.js +879 -60
- package/drag.js +38 -20
- package/features/frames.js +58 -0
- package/features/gif.js +203 -0
- package/features/index.js +1 -0
- package/features/mock-har.js +85 -0
- package/features/record.js +225 -0
- package/i18n/en.js +168 -16
- package/i18n/ru.js +168 -16
- package/i18n/zh.js +168 -16
- package/image-guard.js +13 -6
- package/index.js +17 -1155
- package/locale/ru.json +7 -0
- package/nav.js +43 -5
- package/package.json +8 -1
- package/panel.js +10 -1
- package/refs.js +275 -230
- package/setup.js +214 -46
- package/tools/click.js +58 -0
- package/tools/devtools.js +61 -0
- package/tools/dialog.js +22 -0
- package/tools/download.js +50 -0
- package/tools/drag.js +61 -0
- package/tools/eval.js +22 -0
- package/tools/fill.js +77 -0
- package/tools/handoff.js +40 -0
- package/tools/index.js +38 -0
- package/tools/input.js +147 -0
- package/tools/nav.js +57 -0
- package/tools/read.js +87 -0
- package/tools/record.js +120 -0
- package/tools/screenshot.js +231 -0
- package/tools/tabs.js +131 -0
- package/tools/wait.js +56 -0
- package/vendor/cb +616 -35
- package/vendor/extension/_locales/en/messages.json +3 -0
- package/vendor/extension/_locales/ru/messages.json +3 -0
- package/vendor/extension/_locales/zh_CN/messages.json +3 -0
- package/vendor/extension/_locales/zh_TW/messages.json +3 -0
- package/vendor/extension/background.js +2 -1969
- package/vendor/extension/confirm.css +148 -0
- package/vendor/extension/confirm.html +49 -0
- package/vendor/extension/confirm.js +188 -0
- package/vendor/extension/in-page-cursor.js +599 -0
- package/vendor/extension/manifest.json +11 -2
- package/vendor/extension/popup.css +99 -5
- package/vendor/extension/popup.html +28 -2
- package/vendor/extension/popup.js +430 -45
- package/vendor/extension/sw/boot.js +111 -0
- package/vendor/extension/sw/cdp.js +411 -0
- package/vendor/extension/sw/chooser.js +192 -0
- package/vendor/extension/sw/confirm.js +608 -0
- package/vendor/extension/sw/cursor.js +241 -0
- package/vendor/extension/sw/dispatch.js +129 -0
- package/vendor/extension/sw/download.js +279 -0
- package/vendor/extension/sw/fetch-hub.js +224 -0
- package/vendor/extension/sw/frames.js +651 -0
- package/vendor/extension/sw/imaging.js +439 -0
- package/vendor/extension/sw/native.js +111 -0
- package/vendor/extension/sw/net-tools.js +525 -0
- package/vendor/extension/sw/ops.js +829 -0
- package/vendor/extension/sw/popup-api.js +303 -0
- package/vendor/extension/sw/profile.js +166 -0
- package/vendor/extension/sw/record.js +494 -0
- package/vendor/extension/sw/state.js +161 -0
- package/vendor/extension/sw/tabui.js +219 -0
- package/vendor/extension/sw/util.js +166 -0
- package/vendor/extension/sw/welcome.js +26 -0
- package/vendor/extension/sw/windows.js +94 -0
- package/vendor/extension/welcome.css +189 -0
- package/vendor/extension/welcome.html +70 -0
- package/vendor/extension/welcome.js +157 -0
- package/vendor/host/host.js +476 -71
- package/vendor/in-page-cursor.js +309 -37
- package/vendor/skill/SKILL.md +34 -16
|
@@ -0,0 +1,494 @@
|
|
|
1
|
+
import { ensure, evaluate, onCdpEvent, onTabDetached, send, shouldKeepAlive } from './cdp.js'
|
|
2
|
+
import { areAllFramesAllowed, hasProtectedSites, isUrlAllowed } from './confirm.js'
|
|
3
|
+
import { buildContactSheet, decodeFramesToRgb, downscaleBitmap, drawMarks, imageDimensions, base64ToBytes } from './imaging.js'
|
|
4
|
+
import { registerOps } from './ops.js'
|
|
5
|
+
import { sleep, timeLeft } from './util.js'
|
|
6
|
+
|
|
7
|
+
const MAX_FRAMES = 120
|
|
8
|
+
const MAX_BYTES = 30 * 1024 * 1024
|
|
9
|
+
const MAX_OUTPUT_CHARS = 24 * 1024 * 1024
|
|
10
|
+
const sessions = new Map()
|
|
11
|
+
let wired = false
|
|
12
|
+
|
|
13
|
+
const active = (s) => s && !s.stopPromise
|
|
14
|
+
const jpegBytes = (base64) => Math.floor(String(base64 || '').length * 3 / 4)
|
|
15
|
+
|
|
16
|
+
function clampWidth(value, fallback = 640) {
|
|
17
|
+
const raw = Number(value)
|
|
18
|
+
const n = Math.round(Number.isFinite(raw) ? raw : fallback)
|
|
19
|
+
return Math.max(320, Math.min(1280, n))
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
function protectedError() {
|
|
23
|
+
return new Error('USER_DENIED_SENSITIVE 录屏进入未放行的受保护网站,本次录屏已中止并丢弃')
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
function urlAllowed(tabId, url) {
|
|
27
|
+
if (typeof url !== 'string' || !url) return false
|
|
28
|
+
try { return isUrlAllowed(tabId, url) === true } catch { return false }
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
const tabUrl = (tab) => (tab && (tab.url || tab.pendingUrl)) || ''
|
|
32
|
+
|
|
33
|
+
function markProtected(s) {
|
|
34
|
+
s.protectedSite = true
|
|
35
|
+
s.frames = []
|
|
36
|
+
s.bytes = 0
|
|
37
|
+
if (s.stopPromise) {
|
|
38
|
+
s.stopReason = 'protected_site'
|
|
39
|
+
return s.stopPromise
|
|
40
|
+
}
|
|
41
|
+
return stopCapture(s, 'protected_site')
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
async function verifySessionUrl(s) {
|
|
45
|
+
const tab = await Promise.resolve().then(() => chrome.tabs.get(s.tabId)).catch(() => null)
|
|
46
|
+
const url = tabUrl(tab)
|
|
47
|
+
if (!urlAllowed(s.tabId, url) || (hasProtectedSites() && !(await areAllFramesAllowed(s.tabId)))) {
|
|
48
|
+
void markProtected(s)
|
|
49
|
+
return false
|
|
50
|
+
}
|
|
51
|
+
s.currentUrl = url
|
|
52
|
+
return true
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function normalizeFormat(format) {
|
|
56
|
+
const f = String(format || 'jpeg').toLowerCase()
|
|
57
|
+
if (f === 'jpg' || f === 'jpeg') return 'jpeg'
|
|
58
|
+
if (f === 'png') return 'png'
|
|
59
|
+
throw new Error('SHOT_FORMAT')
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
async function shotMarked({ tabId, format = 'jpeg', quality = 75, full = false, selector, maxWidth = 1280, marks = null, viewportWidth = null, timeoutMs }) {
|
|
63
|
+
const deadline = timeoutMs && Date.now() + timeoutMs
|
|
64
|
+
const type = normalizeFormat(format)
|
|
65
|
+
const params = { format: type, captureBeyondViewport: !!full }
|
|
66
|
+
if (type === 'jpeg') params.quality = Math.max(1, Math.min(100, Math.round(Number(quality) || 75)))
|
|
67
|
+
let clip = null
|
|
68
|
+
if (selector) {
|
|
69
|
+
const rect = await evaluate(tabId, `(() => {
|
|
70
|
+
const el = document.querySelector(${JSON.stringify(selector)});
|
|
71
|
+
if (!el) return null;
|
|
72
|
+
el.scrollIntoView({ block: 'center', inline: 'center', behavior: 'instant' });
|
|
73
|
+
return new Promise((res) => {
|
|
74
|
+
let done = false;
|
|
75
|
+
const finish = () => {
|
|
76
|
+
if (done) return;
|
|
77
|
+
done = true;
|
|
78
|
+
const r = el.getBoundingClientRect();
|
|
79
|
+
res({ x: r.left, y: r.top, width: r.width, height: r.height });
|
|
80
|
+
};
|
|
81
|
+
requestAnimationFrame(() => requestAnimationFrame(finish));
|
|
82
|
+
setTimeout(finish, 120);
|
|
83
|
+
});
|
|
84
|
+
})()`, false, deadline && timeLeft(deadline))
|
|
85
|
+
if (!rect) throw new Error('SHOT_SELECTOR_NOT_FOUND')
|
|
86
|
+
clip = { x: rect.x, y: rect.y, width: rect.width, height: rect.height, scale: 1 }
|
|
87
|
+
params.clip = clip
|
|
88
|
+
params.captureBeyondViewport = false
|
|
89
|
+
}
|
|
90
|
+
let vw = Number(viewportWidth)
|
|
91
|
+
let shiftedMarks = Array.isArray(marks) && marks.length ? marks : null
|
|
92
|
+
if (shiftedMarks) {
|
|
93
|
+
const view = await evaluate(tabId, `(() => ({
|
|
94
|
+
innerWidth: window.innerWidth,
|
|
95
|
+
scrollX: window.scrollX || window.pageXOffset || 0,
|
|
96
|
+
scrollY: window.scrollY || window.pageYOffset || 0,
|
|
97
|
+
pageWidth: Math.max(window.innerWidth, document.documentElement ? document.documentElement.scrollWidth : 0),
|
|
98
|
+
}))()`, false, deadline && timeLeft(deadline)).catch(() => null)
|
|
99
|
+
if (view && full) {
|
|
100
|
+
shiftedMarks = shiftedMarks.map(mark => ({ ...mark, x: Number(mark.x) + (Number(view.scrollX) || 0), y: Number(mark.y) + (Number(view.scrollY) || 0) }))
|
|
101
|
+
if (!(vw > 0)) vw = Number(view.pageWidth) || Number(view.innerWidth) || null
|
|
102
|
+
} else if (view && !(vw > 0)) {
|
|
103
|
+
vw = Number(view.innerWidth) || null
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
const r = await send(tabId, 'Page.captureScreenshot', params, deadline && timeLeft(deadline))
|
|
107
|
+
const mime = type === 'png' ? 'image/png' : 'image/jpeg'
|
|
108
|
+
const original = { data: r.data, width: 0, height: 0, mime, format: type }
|
|
109
|
+
try {
|
|
110
|
+
const size = imageDimensions(base64ToBytes(r.data), mime)
|
|
111
|
+
if (size) {
|
|
112
|
+
original.width = size.width
|
|
113
|
+
original.height = size.height
|
|
114
|
+
}
|
|
115
|
+
} catch {}
|
|
116
|
+
let image = original
|
|
117
|
+
let marked = false
|
|
118
|
+
try {
|
|
119
|
+
if (shiftedMarks) {
|
|
120
|
+
image = await drawMarks(image.data, mime, shiftedMarks, vw, type, params.quality || 82)
|
|
121
|
+
marked = image.marked === true
|
|
122
|
+
}
|
|
123
|
+
const limit = Math.floor(Number(maxWidth))
|
|
124
|
+
image = await downscaleBitmap(image.data, image.mime || mime, Number.isFinite(limit) ? limit : 0, type, params.quality || 82)
|
|
125
|
+
} catch {
|
|
126
|
+
image = original
|
|
127
|
+
marked = false
|
|
128
|
+
}
|
|
129
|
+
const t = await chrome.tabs.get(Number(tabId)).catch(() => null)
|
|
130
|
+
return { data: image.data, format: image.format || type, width: image.width || 0, height: image.height || 0,
|
|
131
|
+
url: t && t.url, title: t && t.title, full: !!full, clip, marked }
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
function probeJpeg(s, data) {
|
|
135
|
+
if (s.width && s.height) return
|
|
136
|
+
try {
|
|
137
|
+
const size = imageDimensions(base64ToBytes(data), 'image/jpeg')
|
|
138
|
+
if (size) {
|
|
139
|
+
s.width = size.width
|
|
140
|
+
s.height = size.height
|
|
141
|
+
}
|
|
142
|
+
} catch {}
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
function addFrame(s, data, source) {
|
|
146
|
+
if (!active(s) || typeof data !== 'string' || !data) return false
|
|
147
|
+
if (!urlAllowed(s.tabId, s.currentUrl)) {
|
|
148
|
+
void markProtected(s)
|
|
149
|
+
return false
|
|
150
|
+
}
|
|
151
|
+
const now = Date.now()
|
|
152
|
+
const minGap = 1000 / Math.max(1, s.fps)
|
|
153
|
+
if (source === 'screencast' && s.frames.length && now - s.lastFrameAt < minGap * 0.85) return false
|
|
154
|
+
const bytes = jpegBytes(data)
|
|
155
|
+
if (s.frames.length >= MAX_FRAMES || s.bytes + bytes > MAX_BYTES) {
|
|
156
|
+
void stopCapture(s, 'limit')
|
|
157
|
+
return false
|
|
158
|
+
}
|
|
159
|
+
if (hasProtectedSites() && s.frameCheckInflight) return false
|
|
160
|
+
probeJpeg(s, data)
|
|
161
|
+
s.frames.push({ atMs: Math.max(0, now - s.startedAt), jpeg: data })
|
|
162
|
+
s.bytes += bytes
|
|
163
|
+
s.lastFrameAt = now
|
|
164
|
+
clearTimeout(s.watchdog)
|
|
165
|
+
if (hasProtectedSites()) {
|
|
166
|
+
s.frameCheckInflight = areAllFramesAllowed(s.tabId)
|
|
167
|
+
.then((ok) => { if (!ok) void markProtected(s) })
|
|
168
|
+
.catch(() => { void markProtected(s) })
|
|
169
|
+
.finally(() => { s.frameCheckInflight = null })
|
|
170
|
+
}
|
|
171
|
+
if (s.frames.length >= MAX_FRAMES || s.bytes >= MAX_BYTES) void stopCapture(s, 'limit')
|
|
172
|
+
return true
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
function armFallbackWatchdog(s, delay = 1000) {
|
|
176
|
+
clearTimeout(s.watchdog)
|
|
177
|
+
s.watchdog = setTimeout(() => {
|
|
178
|
+
if (!active(s) || s.frames.length || s.fallbackActive) return
|
|
179
|
+
if (s.screencastStarting && !s.screencastActive) return armFallbackWatchdog(s, 500)
|
|
180
|
+
startFallback(s)
|
|
181
|
+
}, delay)
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
async function captureOnce(s) {
|
|
185
|
+
if (!active(s) || !s.fallbackActive || s.captureBusy) return
|
|
186
|
+
s.captureBusy = true
|
|
187
|
+
try {
|
|
188
|
+
if (!(await verifySessionUrl(s))) return
|
|
189
|
+
const r = await send(s.tabId, 'Page.captureScreenshot', { format: 'jpeg', quality: s.quality }, 15000)
|
|
190
|
+
if (!(await verifySessionUrl(s))) return
|
|
191
|
+
if (addFrame(s, r.data, 'fallback')) s.captureErrors = 0
|
|
192
|
+
} catch {
|
|
193
|
+
s.captureErrors++
|
|
194
|
+
if (s.captureErrors >= 4) void stopCapture(s, 'capture_failed')
|
|
195
|
+
} finally {
|
|
196
|
+
s.captureBusy = false
|
|
197
|
+
if (active(s) && s.fallbackActive) {
|
|
198
|
+
s.captureTimer = setTimeout(() => void captureOnce(s), Math.max(80, Math.round(1000 / s.fps)))
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
function startFallback(s) {
|
|
204
|
+
if (!active(s) || s.fallbackActive) return
|
|
205
|
+
if (!urlAllowed(s.tabId, s.currentUrl)) {
|
|
206
|
+
void markProtected(s)
|
|
207
|
+
return
|
|
208
|
+
}
|
|
209
|
+
s.fallbackActive = true
|
|
210
|
+
s.mode = 'fallback'
|
|
211
|
+
clearTimeout(s.watchdog)
|
|
212
|
+
if (s.screencastActive) {
|
|
213
|
+
s.screencastActive = false
|
|
214
|
+
send(s.tabId, 'Page.stopScreencast', {}, 3000).catch(() => {})
|
|
215
|
+
}
|
|
216
|
+
void captureOnce(s)
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
async function startScreencast(s) {
|
|
220
|
+
if (!active(s) || s.fallbackActive || s.screencastActive) return
|
|
221
|
+
s.screencastStarting = true
|
|
222
|
+
try {
|
|
223
|
+
if (!(await verifySessionUrl(s))) return
|
|
224
|
+
await send(s.tabId, 'Page.startScreencast', {
|
|
225
|
+
format: 'jpeg',
|
|
226
|
+
quality: s.quality,
|
|
227
|
+
maxWidth: s.maxWidth,
|
|
228
|
+
maxHeight: Math.max(2, Math.round(s.maxWidth * 1.6)),
|
|
229
|
+
everyNthFrame: 1,
|
|
230
|
+
}, 10000)
|
|
231
|
+
let ok = !s.fallbackActive && active(s)
|
|
232
|
+
if (ok) ok = await verifySessionUrl(s)
|
|
233
|
+
if (!ok) {
|
|
234
|
+
send(s.tabId, 'Page.stopScreencast', {}, 3000).catch(() => {})
|
|
235
|
+
s.screencastActive = false
|
|
236
|
+
} else {
|
|
237
|
+
s.screencastActive = true
|
|
238
|
+
s.mode = 'screencast'
|
|
239
|
+
}
|
|
240
|
+
} catch {
|
|
241
|
+
s.screencastActive = false
|
|
242
|
+
startFallback(s)
|
|
243
|
+
} finally {
|
|
244
|
+
s.screencastStarting = false
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
async function restartScreencast(s) {
|
|
249
|
+
if (!active(s) || s.fallbackActive || s.restarting) return
|
|
250
|
+
if (!urlAllowed(s.tabId, s.currentUrl)) {
|
|
251
|
+
void markProtected(s)
|
|
252
|
+
return
|
|
253
|
+
}
|
|
254
|
+
s.restarting = true
|
|
255
|
+
try {
|
|
256
|
+
if (s.screencastActive) {
|
|
257
|
+
s.screencastActive = false
|
|
258
|
+
await send(s.tabId, 'Page.stopScreencast', {}, 3000).catch(() => {})
|
|
259
|
+
}
|
|
260
|
+
await startScreencast(s)
|
|
261
|
+
} finally {
|
|
262
|
+
s.restarting = false
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
function handleFrameEvent(s, src, method, params) {
|
|
267
|
+
if (src.tabId !== s.tabId) return
|
|
268
|
+
if (method === 'Page.screencastFrame') {
|
|
269
|
+
try {
|
|
270
|
+
chrome.debugger.sendCommand({ tabId: s.tabId }, 'Page.screencastFrameAck', { sessionId: params.sessionId }).catch(() => {})
|
|
271
|
+
} catch {}
|
|
272
|
+
if (active(s) && !s.fallbackActive) addFrame(s, params.data, 'screencast')
|
|
273
|
+
return
|
|
274
|
+
}
|
|
275
|
+
if (method === 'Page.frameNavigated' && params.frame) {
|
|
276
|
+
const url = typeof params.frame.url === 'string' ? params.frame.url : ''
|
|
277
|
+
if (!urlAllowed(s.tabId, url)) {
|
|
278
|
+
void markProtected(s)
|
|
279
|
+
return
|
|
280
|
+
}
|
|
281
|
+
if (params.frame.parentId) return
|
|
282
|
+
s.currentUrl = url
|
|
283
|
+
if (!active(s) || s.fallbackActive) return
|
|
284
|
+
clearTimeout(s.restartTimer)
|
|
285
|
+
s.restartTimer = setTimeout(() => {
|
|
286
|
+
void restartScreencast(s)
|
|
287
|
+
armFallbackWatchdog(s, 1000)
|
|
288
|
+
}, 150)
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
function stopCapture(s, reason = 'stop') {
|
|
293
|
+
if (s.stopPromise) return s.stopPromise
|
|
294
|
+
s.stoppedAt = Date.now()
|
|
295
|
+
s.stopReason = reason
|
|
296
|
+
s.stopPromise = (async () => {
|
|
297
|
+
clearTimeout(s.watchdog)
|
|
298
|
+
clearTimeout(s.captureTimer)
|
|
299
|
+
clearTimeout(s.maxTimer)
|
|
300
|
+
clearTimeout(s.restartTimer)
|
|
301
|
+
s.fallbackActive = false
|
|
302
|
+
s.unsubscribe?.()
|
|
303
|
+
if (s.screencastActive) {
|
|
304
|
+
s.screencastActive = false
|
|
305
|
+
if (reason !== 'detached' && reason !== 'target_closed') await send(s.tabId, 'Page.stopScreencast', {}, 3000).catch(() => {})
|
|
306
|
+
}
|
|
307
|
+
return true
|
|
308
|
+
})()
|
|
309
|
+
s.stopPromise.then(() => s.resolveStopDone?.(), () => s.resolveStopDone?.())
|
|
310
|
+
return s.stopPromise
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
async function recordStart({ tabId, fps = 3, maxWidth = 640, quality = 68, maxDurationMs = 60000 }) {
|
|
314
|
+
const id = Number(tabId)
|
|
315
|
+
if (sessions.has(id)) throw new Error('RECORD_ACTIVE')
|
|
316
|
+
const s = {
|
|
317
|
+
tabId: id,
|
|
318
|
+
fps: Math.max(1, Math.min(8, Math.round(Number(fps) || 3))),
|
|
319
|
+
maxWidth: clampWidth(maxWidth),
|
|
320
|
+
quality: Math.max(1, Math.min(100, Math.round(Number(quality) || 68))),
|
|
321
|
+
maxDurationMs: Math.max(500, Math.min(600000, Math.round(Number(maxDurationMs) || 60000))),
|
|
322
|
+
startedAt: Date.now(),
|
|
323
|
+
stoppedAt: 0,
|
|
324
|
+
frames: [],
|
|
325
|
+
bytes: 0,
|
|
326
|
+
width: 0,
|
|
327
|
+
height: 0,
|
|
328
|
+
lastFrameAt: 0,
|
|
329
|
+
mode: 'screencast',
|
|
330
|
+
fallbackActive: false,
|
|
331
|
+
captureBusy: false,
|
|
332
|
+
captureErrors: 0,
|
|
333
|
+
screencastActive: false,
|
|
334
|
+
screencastStarting: false,
|
|
335
|
+
restarting: false,
|
|
336
|
+
stopPromise: null,
|
|
337
|
+
stopDone: null,
|
|
338
|
+
resolveStopDone: null,
|
|
339
|
+
currentUrl: '',
|
|
340
|
+
initialUrl: '',
|
|
341
|
+
protectedSite: false,
|
|
342
|
+
}
|
|
343
|
+
s.stopDone = new Promise(resolve => { s.resolveStopDone = resolve })
|
|
344
|
+
sessions.set(id, s)
|
|
345
|
+
try {
|
|
346
|
+
const firstTab = await Promise.resolve().then(() => chrome.tabs.get(id)).catch(() => null)
|
|
347
|
+
const firstUrl = tabUrl(firstTab)
|
|
348
|
+
if (!urlAllowed(id, firstUrl)) throw protectedError()
|
|
349
|
+
s.currentUrl = firstUrl
|
|
350
|
+
s.initialUrl = firstUrl
|
|
351
|
+
await ensure(id)
|
|
352
|
+
if (!(await verifySessionUrl(s))) throw protectedError()
|
|
353
|
+
s.unsubscribe = onCdpEvent((src, method, params) => handleFrameEvent(s, src, method, params))
|
|
354
|
+
s.maxTimer = setTimeout(() => void stopCapture(s, 'max_duration'), s.maxDurationMs)
|
|
355
|
+
armFallbackWatchdog(s, 1000)
|
|
356
|
+
await startScreencast(s)
|
|
357
|
+
if (s.protectedSite) throw protectedError()
|
|
358
|
+
if (!active(s) || sessions.get(id) !== s) throw new Error('RECORD_NOT_STARTED')
|
|
359
|
+
return { tabId: id, recording: true, fps: s.fps, maxWidth: s.maxWidth, quality: s.quality, maxDurationMs: s.maxDurationMs, mode: s.mode }
|
|
360
|
+
} catch (error) {
|
|
361
|
+
clearTimeout(s.watchdog)
|
|
362
|
+
clearTimeout(s.captureTimer)
|
|
363
|
+
clearTimeout(s.maxTimer)
|
|
364
|
+
clearTimeout(s.restartTimer)
|
|
365
|
+
s.unsubscribe?.()
|
|
366
|
+
s.resolveStopDone?.()
|
|
367
|
+
if (sessions.get(id) === s) sessions.delete(id)
|
|
368
|
+
throw error
|
|
369
|
+
}
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
function sampleEvenly(frames, count) {
|
|
373
|
+
if (frames.length <= count) return frames.slice()
|
|
374
|
+
if (count <= 1) return frames.slice(0, 1)
|
|
375
|
+
const out = []
|
|
376
|
+
for (let i = 0; i < count; i++) out.push(frames[Math.round(i * (frames.length - 1) / (count - 1))])
|
|
377
|
+
return out.filter(Boolean)
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
function sampleForOutput(s, needPixels, pixelWidth) {
|
|
381
|
+
const jpegChars = s.frames.reduce((sum, f) => sum + f.jpeg.length, 0)
|
|
382
|
+
let count = Math.min(MAX_FRAMES, s.frames.length)
|
|
383
|
+
if (!needPixels) {
|
|
384
|
+
if (jpegChars <= MAX_OUTPUT_CHARS) return s.frames.slice()
|
|
385
|
+
count = Math.max(1, Math.floor(s.frames.length * MAX_OUTPUT_CHARS / jpegChars))
|
|
386
|
+
return sampleEvenly(s.frames, count)
|
|
387
|
+
}
|
|
388
|
+
const sourceWidth = s.width || pixelWidth || 640
|
|
389
|
+
const width = Math.max(2, Math.floor(Math.min(pixelWidth || sourceWidth, sourceWidth) / 2) * 2)
|
|
390
|
+
const height = Math.max(2, Math.floor(((s.height || width * 0.625) * width / sourceWidth) / 2) * 2)
|
|
391
|
+
const rgbChars = width * height * 4
|
|
392
|
+
const averageJpeg = s.frames.length ? jpegChars / s.frames.length : 0
|
|
393
|
+
const perFrame = rgbChars + averageJpeg
|
|
394
|
+
count = Math.max(1, Math.min(count, Math.floor(MAX_OUTPUT_CHARS / Math.max(1, perFrame))))
|
|
395
|
+
return sampleEvenly(s.frames, count)
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
async function finishRecording(s, { needPixels = true, maxWidth = 640 } = {}) {
|
|
399
|
+
if (s.frameCheckInflight) await s.frameCheckInflight
|
|
400
|
+
if (s.protectedSite || s.stopReason === 'protected_site') throw protectedError()
|
|
401
|
+
if (!(await verifySessionUrl(s))) throw protectedError()
|
|
402
|
+
if (!s.frames.length) throw new Error('RECORD_EMPTY')
|
|
403
|
+
const outputWidth = clampWidth(maxWidth)
|
|
404
|
+
const picked = sampleForOutput(s, needPixels !== false, outputWidth)
|
|
405
|
+
const durationMs = Math.max(0, Math.round((s.stoppedAt || Date.now()) - s.startedAt))
|
|
406
|
+
let pixels = { width: 0, height: 0, frames: [] }
|
|
407
|
+
if (needPixels !== false && picked.length) pixels = await decodeFramesToRgb(picked, outputWidth)
|
|
408
|
+
const pixelByIndex = new Map(pixels.frames.map(f => [f.index, f]))
|
|
409
|
+
const sheet = picked.length ? await buildContactSheet(picked, { cols: 3, rows: 3, cellWidth: 360 }).catch(() => null) : null
|
|
410
|
+
if (!(await verifySessionUrl(s))) throw protectedError()
|
|
411
|
+
return {
|
|
412
|
+
count: picked.length,
|
|
413
|
+
captured: s.frames.length,
|
|
414
|
+
durationMs,
|
|
415
|
+
width: pixels.width || s.width || 0,
|
|
416
|
+
height: pixels.height || s.height || 0,
|
|
417
|
+
mode: s.mode,
|
|
418
|
+
stopReason: s.stopReason,
|
|
419
|
+
frames: picked.map((frame, index) => {
|
|
420
|
+
const pixel = pixelByIndex.get(index)
|
|
421
|
+
return {
|
|
422
|
+
atMs: Math.round(frame.atMs),
|
|
423
|
+
jpeg: frame.jpeg,
|
|
424
|
+
...(pixel && pixel.rgb ? { rgb: pixel.rgb } : {}),
|
|
425
|
+
}
|
|
426
|
+
}),
|
|
427
|
+
contactSheet: sheet && { data: sheet.data, width: sheet.width, height: sheet.height, format: 'jpeg' },
|
|
428
|
+
}
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
async function recordStop({ tabId, needPixels = true, maxWidth = 640 }) {
|
|
432
|
+
const id = Number(tabId)
|
|
433
|
+
const s = sessions.get(id)
|
|
434
|
+
if (!s) throw new Error('RECORD_NOT_STARTED')
|
|
435
|
+
await stopCapture(s, 'stop')
|
|
436
|
+
sessions.delete(id)
|
|
437
|
+
return finishRecording(s, { needPixels, maxWidth: clampWidth(maxWidth) })
|
|
438
|
+
}
|
|
439
|
+
|
|
440
|
+
async function recordClip({ tabId, durationMs = 5000, fps = 3, maxWidth = 640, quality = 68, needPixels = true }) {
|
|
441
|
+
const duration = Math.max(200, Math.min(60000, Math.round(Number(durationMs) || 5000)))
|
|
442
|
+
await recordStart({ tabId, fps, maxWidth, quality, maxDurationMs: duration + 1500 })
|
|
443
|
+
const s = sessions.get(Number(tabId))
|
|
444
|
+
if (!s) throw new Error('RECORD_NOT_STARTED')
|
|
445
|
+
await Promise.race([sleep(duration), s.stopDone])
|
|
446
|
+
return recordStop({ tabId, needPixels, maxWidth })
|
|
447
|
+
}
|
|
448
|
+
|
|
449
|
+
function discardSession(tabId, reason = 'target_closed') {
|
|
450
|
+
const id = Number(tabId)
|
|
451
|
+
const s = sessions.get(id)
|
|
452
|
+
if (!s) return
|
|
453
|
+
s.frames = []
|
|
454
|
+
s.bytes = 0
|
|
455
|
+
if (!s.stopPromise) void stopCapture(s, reason)
|
|
456
|
+
sessions.delete(id)
|
|
457
|
+
}
|
|
458
|
+
|
|
459
|
+
function handleRecordTabUpdated(tabId, change) {
|
|
460
|
+
const s = sessions.get(Number(tabId))
|
|
461
|
+
if (!s || !change || typeof change.url !== 'string') return
|
|
462
|
+
s.currentUrl = change.url
|
|
463
|
+
if (!urlAllowed(s.tabId, change.url)) void markProtected(s)
|
|
464
|
+
}
|
|
465
|
+
|
|
466
|
+
function initRecord() {
|
|
467
|
+
if (!wired) {
|
|
468
|
+
wired = true
|
|
469
|
+
shouldKeepAlive((tabId) => active(sessions.get(Number(tabId))))
|
|
470
|
+
onTabDetached((tabId, reason) => {
|
|
471
|
+
const id = Number(tabId)
|
|
472
|
+
const s = sessions.get(id)
|
|
473
|
+
if (!s) return
|
|
474
|
+
if (reason === 'target_closed') discardSession(id, 'target_closed')
|
|
475
|
+
else void stopCapture(s, 'detached')
|
|
476
|
+
})
|
|
477
|
+
chrome.tabs?.onUpdated?.addListener(handleRecordTabUpdated)
|
|
478
|
+
chrome.tabs?.onRemoved?.addListener((tabId) => discardSession(tabId, 'target_closed'))
|
|
479
|
+
}
|
|
480
|
+
registerOps({ shotMarked, recordStart, recordStop, recordClip })
|
|
481
|
+
return true
|
|
482
|
+
}
|
|
483
|
+
|
|
484
|
+
export {
|
|
485
|
+
initRecord,
|
|
486
|
+
shotMarked,
|
|
487
|
+
recordStart,
|
|
488
|
+
recordStop,
|
|
489
|
+
recordClip,
|
|
490
|
+
sessions as recordSessions,
|
|
491
|
+
stopCapture as stopRecordCapture,
|
|
492
|
+
MAX_FRAMES,
|
|
493
|
+
MAX_BYTES,
|
|
494
|
+
}
|
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
const HOST_NAME = 'com.dsh.bridge'
|
|
2
|
+
const CDP_VERSION = '1.3'
|
|
3
|
+
const RECONNECT_MS = 800
|
|
4
|
+
const RECONNECT_MAX_MS = 30_000 // 宿主一直起不来(Node 没了、注册文件坏了)时,重连间隔指数退避到这里封顶
|
|
5
|
+
const CHUNK_CHARS = 200 * 1024 // 单条 native 消息正文上限(保守取值)
|
|
6
|
+
|
|
7
|
+
const CHOOSER_TTL_MS = 10 * 60_000
|
|
8
|
+
const CHOOSER_SKIP_MS = 5 * 60_000
|
|
9
|
+
const CHOOSER_WAIT_MS = 100
|
|
10
|
+
|
|
11
|
+
const NET_MAX = 400
|
|
12
|
+
|
|
13
|
+
const MAX_INBOX_BYTES = 64 * 1024 * 1024
|
|
14
|
+
|
|
15
|
+
const TAKEOVER_OPS = new Set(['click', 'clickEl', 'clickText', 'type', 'key', 'select', 'hover', 'scroll', 'clickAndDownload'])
|
|
16
|
+
const HANDOFF_LOCKED = new Set([...TAKEOVER_OPS, 'upload', 'focus', 'nav', 'eval', 'cdp', 'dialog'])
|
|
17
|
+
|
|
18
|
+
const QUEUED = new Set([...TAKEOVER_OPS, 'focus', 'upload', 'nav', 'cursor'])
|
|
19
|
+
const OPEN_TRACKED = new Set(['click', 'clickEl', 'clickText', 'key', 'nav'])
|
|
20
|
+
|
|
21
|
+
const PAUSE_ALLOWED = new Set(['version', 'reload', 'ping', 'logs', 'diagnostics', 'detach', 'panel'])
|
|
22
|
+
const PAUSED_MSG = '用户在 DSH Bridge 弹窗里暂停了浏览器控制——请用户点开扩展图标、打开「允许 DSH 控制」后再试'
|
|
23
|
+
|
|
24
|
+
/** 碰到扩展页面也允许的:只是松手 / 关掉,不往里注入、不发输入 */
|
|
25
|
+
const OWN_PAGE_OK = new Set(['detach', 'close'])
|
|
26
|
+
|
|
27
|
+
/** 不算「动作」的内部操作(版本检查、焦点模拟、光标跟随……) */
|
|
28
|
+
const QUIET_OPS = new Set(['version', 'reload', 'ping', 'logs', 'diagnostics', 'panel'])
|
|
29
|
+
const QUIET_CDP = new Set(['Emulation.setFocusEmulationEnabled', 'Page.getNavigationHistory'])
|
|
30
|
+
|
|
31
|
+
const ACTIVITY_MAX = 80
|
|
32
|
+
|
|
33
|
+
const DETACH_IDLE_MS = 60_000
|
|
34
|
+
|
|
35
|
+
function freshState() {
|
|
36
|
+
return {
|
|
37
|
+
port: null,
|
|
38
|
+
connecting: false,
|
|
39
|
+
retryMs: RECONNECT_MS,
|
|
40
|
+
|
|
41
|
+
/** 已 attach CDP 的 tabId */
|
|
42
|
+
attached: new Set(),
|
|
43
|
+
/** 正在等待 loadEventFired 的 tabId → Set<entry> */
|
|
44
|
+
loadWaiters: new Map(),
|
|
45
|
+
/** 分片接收缓冲:id → { parts, received, bytes, at } */
|
|
46
|
+
inbox: new Map(),
|
|
47
|
+
/** SW 日志环(CLI 可读,免得去 chrome://extensions 开控制台) */
|
|
48
|
+
LOG: [],
|
|
49
|
+
CONSOLE: [],
|
|
50
|
+
/** 被 alert/confirm 挡住的标签页:tabId → {type, message} */
|
|
51
|
+
dialogs: new Map(),
|
|
52
|
+
/**
|
|
53
|
+
* 模型点了「上传」之类的按钮、页面要选文件:tabId → {id, owner, mode, backendNodeId, frameId, at, ready, doc, folder}。
|
|
54
|
+
* 那一下的系统选文件窗口已经拦下(不弹出来,DSH 也点不动它);点击回话把 id 交给插件,
|
|
55
|
+
* 插件 upload 不给选择器时带着这个 id 来,文件就塞给这个框(只认点它的那个请求拿到的 id)。
|
|
56
|
+
* id 是随机串:扩展重载后从头来也不会和插件手里的旧 id 撞上。
|
|
57
|
+
*/
|
|
58
|
+
choosers: new Map(),
|
|
59
|
+
/** 正在拦截的标签页:只在插件明确要求的那一下点击 / 按键里开,结束就关(用户自己点上传照常弹窗口) */
|
|
60
|
+
chooserArmed: new Set(),
|
|
61
|
+
/** 正开着拦截的那个请求:tabId → 随机串。拦下的框记在它名下,同一标签页的别的请求拿不到 */
|
|
62
|
+
chooserOwner: new Map(),
|
|
63
|
+
/** 同一标签页带拦截的点击 / 按键排队一个个来:两个会话同时点,不会把一个框算到两个请求头上 */
|
|
64
|
+
chooserLocks: new Map(),
|
|
65
|
+
/** 网页用的是拦不下来的那种选文件窗口(showOpenFilePicker 之类,拦了只会把它取消):tabId → 时刻,这之后一阵不再拦 */
|
|
66
|
+
chooserSkip: new Map(),
|
|
67
|
+
/** 网络请求环形缓冲(Network 域在 attach 时就 enable 了) */
|
|
68
|
+
NET: [],
|
|
69
|
+
netPending: new Map(),
|
|
70
|
+
netChanged: new Map(),
|
|
71
|
+
disconnectReason: null,
|
|
72
|
+
disconnectError: null,
|
|
73
|
+
inboxSweep: undefined,
|
|
74
|
+
|
|
75
|
+
agentInputUntil: new Map(),
|
|
76
|
+
userTakeover: new Map(),
|
|
77
|
+
|
|
78
|
+
tabQueues: new Map(),
|
|
79
|
+
tabSessions: new Map(),
|
|
80
|
+
/** 最近观测到的标签页主帧网址(供事件采集、Mock 与录屏同步核验来源) */
|
|
81
|
+
tabUrl: new Map(),
|
|
82
|
+
|
|
83
|
+
/** 宿主自报的状态(pid、socket 是否在听、最近一次被调用) */
|
|
84
|
+
hostInfo: null,
|
|
85
|
+
/** 用户在弹窗里按了暂停:除了这几个,其它操作一律拒绝 */
|
|
86
|
+
paused: false,
|
|
87
|
+
pauseReason: null,
|
|
88
|
+
activeHandoff: null,
|
|
89
|
+
|
|
90
|
+
/** 用户在弹窗里关了「页面里显示光标」:真实点击照做,只是不画那只蓝色光标 */
|
|
91
|
+
showCursor: true,
|
|
92
|
+
/** 用户关了「在单独窗口里干活」:新开的页回到用户当前窗口(后台标签页,不抢焦点) */
|
|
93
|
+
ownWindow: true,
|
|
94
|
+
|
|
95
|
+
/** 会话 key → { key, kind, session, pid, first, last, ops, errors, tabs:Set } */
|
|
96
|
+
SESSIONS: new Map(),
|
|
97
|
+
/** 最近动作:DSH 的一次工具调用算一条(同一个 callId 的多个 op 合并),cb 命令行一个 op 一条 */
|
|
98
|
+
ACTIVITY: [],
|
|
99
|
+
|
|
100
|
+
// 标签页最后被用到的时间 —— 空闲了就断开,别让 Chrome 一直挂着"正在调试"提示条
|
|
101
|
+
lastUsed: new Map(),
|
|
102
|
+
|
|
103
|
+
groupedTabs: new Map(), // tabId -> groupId(只记我们自己建的组)
|
|
104
|
+
ourGroup: new Map(), // windowId -> groupId(标签组是 per-window 的)
|
|
105
|
+
tabEpoch: new Map(), // tabId -> 递增序号,用来发现"mark 与 unmark 撞车"
|
|
106
|
+
|
|
107
|
+
sessionColors: new Map(),
|
|
108
|
+
groupQueues: new Map(),
|
|
109
|
+
ownedGroupIds: new Set(),
|
|
110
|
+
|
|
111
|
+
agentWindows: { normal: null, incognito: null },
|
|
112
|
+
/** DSH 在干活窗口里开的标签页:用户自己拖进来的页不算,不能把它切走 */
|
|
113
|
+
agentTabs: new Set(),
|
|
114
|
+
|
|
115
|
+
/** 开页排队:两个会话同时开页时,后来的等前一个开完(窗口建好了)再往里加,不另开第二个窗口 */
|
|
116
|
+
agentWindowQueue: Promise.resolve(),
|
|
117
|
+
|
|
118
|
+
ensureInflight: new Map(),
|
|
119
|
+
|
|
120
|
+
/** 等 Page.fileChooserOpened 的:tabId → Set<entry> */
|
|
121
|
+
chooserWaiters: new Map(),
|
|
122
|
+
|
|
123
|
+
// 正在执行的 CDP 调用计数:空闲断开不能把"正干着活"的标签页掐了
|
|
124
|
+
inflight: new Map(),
|
|
125
|
+
|
|
126
|
+
/** 页内光标:注入过一次就记住,导航后失效要重注;位置按标签页记着,换了页面从原处接着出现 */
|
|
127
|
+
cursorReady: new Set(),
|
|
128
|
+
cursorPos: new Map(),
|
|
129
|
+
|
|
130
|
+
activeDownload: null,
|
|
131
|
+
|
|
132
|
+
recentTabs: new Map(),
|
|
133
|
+
prefsReady: null,
|
|
134
|
+
groupsReady: null,
|
|
135
|
+
agentWindowReady: null,
|
|
136
|
+
startupReady: null,
|
|
137
|
+
ops: null,
|
|
138
|
+
UI_LANG: 'en',
|
|
139
|
+
helloMetadata: {},
|
|
140
|
+
cdpEvents: new Set(),
|
|
141
|
+
tabAttached: new Set(),
|
|
142
|
+
tabDetached: new Set(),
|
|
143
|
+
keepAlive: new Set(),
|
|
144
|
+
tabCreated: new Set(),
|
|
145
|
+
tabUpdated: new Set(),
|
|
146
|
+
preHooks: new Set(),
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
const S = freshState()
|
|
151
|
+
function resetState() {
|
|
152
|
+
clearTimeout(S.inboxSweep)
|
|
153
|
+
Object.assign(S, freshState())
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
export {
|
|
157
|
+
HOST_NAME, CDP_VERSION, RECONNECT_MS, RECONNECT_MAX_MS, CHUNK_CHARS, CHOOSER_TTL_MS,
|
|
158
|
+
CHOOSER_SKIP_MS, CHOOSER_WAIT_MS, NET_MAX, MAX_INBOX_BYTES, TAKEOVER_OPS, HANDOFF_LOCKED,
|
|
159
|
+
QUEUED, OPEN_TRACKED, PAUSE_ALLOWED, PAUSED_MSG, OWN_PAGE_OK, QUIET_OPS, QUIET_CDP,
|
|
160
|
+
ACTIVITY_MAX, DETACH_IDLE_MS, S, resetState,
|
|
161
|
+
}
|