dsh-chrome-bridge 1.20.0 → 2.0.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 (88) hide show
  1. package/README.en.md +6 -2
  2. package/README.md +6 -2
  3. package/client.js +110 -29
  4. package/core/ext.js +119 -0
  5. package/core/hosts.js +277 -0
  6. package/core/locale.js +8 -0
  7. package/core/receipt.js +56 -0
  8. package/core/session.js +157 -0
  9. package/core/shots.js +56 -0
  10. package/core/tooldef.js +142 -0
  11. package/core/transport.js +212 -0
  12. package/core/upload.js +59 -0
  13. package/devtools.js +18 -8
  14. package/download.js +879 -60
  15. package/drag.js +38 -20
  16. package/features/frames.js +58 -0
  17. package/features/gif.js +203 -0
  18. package/features/index.js +1 -0
  19. package/features/mock-har.js +85 -0
  20. package/features/record.js +225 -0
  21. package/i18n/en.js +168 -16
  22. package/i18n/ru.js +168 -16
  23. package/i18n/zh.js +168 -16
  24. package/image-guard.js +13 -6
  25. package/index.js +17 -1155
  26. package/locale/ru.json +7 -0
  27. package/nav.js +43 -5
  28. package/package.json +8 -1
  29. package/panel.js +10 -1
  30. package/refs.js +275 -230
  31. package/setup.js +214 -46
  32. package/tools/click.js +58 -0
  33. package/tools/devtools.js +61 -0
  34. package/tools/dialog.js +22 -0
  35. package/tools/download.js +50 -0
  36. package/tools/drag.js +61 -0
  37. package/tools/eval.js +22 -0
  38. package/tools/fill.js +77 -0
  39. package/tools/handoff.js +40 -0
  40. package/tools/index.js +38 -0
  41. package/tools/input.js +147 -0
  42. package/tools/nav.js +57 -0
  43. package/tools/read.js +87 -0
  44. package/tools/record.js +120 -0
  45. package/tools/screenshot.js +223 -0
  46. package/tools/tabs.js +131 -0
  47. package/tools/wait.js +56 -0
  48. package/vendor/cb +616 -35
  49. package/vendor/extension/_locales/en/messages.json +3 -0
  50. package/vendor/extension/_locales/ru/messages.json +3 -0
  51. package/vendor/extension/_locales/zh_CN/messages.json +3 -0
  52. package/vendor/extension/_locales/zh_TW/messages.json +3 -0
  53. package/vendor/extension/background.js +2 -1969
  54. package/vendor/extension/confirm.css +148 -0
  55. package/vendor/extension/confirm.html +49 -0
  56. package/vendor/extension/confirm.js +188 -0
  57. package/vendor/extension/in-page-cursor.js +599 -0
  58. package/vendor/extension/manifest.json +11 -2
  59. package/vendor/extension/popup.css +99 -5
  60. package/vendor/extension/popup.html +28 -2
  61. package/vendor/extension/popup.js +430 -45
  62. package/vendor/extension/sw/boot.js +111 -0
  63. package/vendor/extension/sw/cdp.js +411 -0
  64. package/vendor/extension/sw/chooser.js +192 -0
  65. package/vendor/extension/sw/confirm.js +608 -0
  66. package/vendor/extension/sw/cursor.js +241 -0
  67. package/vendor/extension/sw/dispatch.js +129 -0
  68. package/vendor/extension/sw/download.js +279 -0
  69. package/vendor/extension/sw/fetch-hub.js +224 -0
  70. package/vendor/extension/sw/frames.js +651 -0
  71. package/vendor/extension/sw/imaging.js +361 -0
  72. package/vendor/extension/sw/native.js +111 -0
  73. package/vendor/extension/sw/net-tools.js +525 -0
  74. package/vendor/extension/sw/ops.js +829 -0
  75. package/vendor/extension/sw/popup-api.js +303 -0
  76. package/vendor/extension/sw/profile.js +166 -0
  77. package/vendor/extension/sw/record.js +494 -0
  78. package/vendor/extension/sw/state.js +161 -0
  79. package/vendor/extension/sw/tabui.js +219 -0
  80. package/vendor/extension/sw/util.js +166 -0
  81. package/vendor/extension/sw/welcome.js +26 -0
  82. package/vendor/extension/sw/windows.js +94 -0
  83. package/vendor/extension/welcome.css +189 -0
  84. package/vendor/extension/welcome.html +70 -0
  85. package/vendor/extension/welcome.js +157 -0
  86. package/vendor/host/host.js +476 -71
  87. package/vendor/in-page-cursor.js +309 -37
  88. package/vendor/skill/SKILL.md +34 -16
package/README.en.md CHANGED
@@ -2,9 +2,13 @@
2
2
 
3
3
  Lets DSH work in the Chrome you already use: real clicks and typing, a cursor you can see on the page, and your own logins.
4
4
 
5
+ - Ships 15 native `browser_*` tools: read pages (cross-site iframes included), click (left / right / middle, double-click), type, batch form fill, downloads (including files that only exist after a click), network-idle waits, console / network inspection, network mocks and redacted HAR export, `browser_handoff` when a login, captcha, 2FA or payment step needs you, and `browser_record` to save the session as an animated GIF.
6
+ - Screenshots can number the clickable elements in view (`marks`), and actions work inside cross-site iframes; several browsers and profiles can be connected at once.
7
+ - It won't touch a page you mark as protected without asking: the list starts empty, and once you add a domain in the popup, a confirmation window (deny by default, 15-minute grants) appears before it reads or acts there.
5
8
  - Pages it opens go into a separate window, so your own window gets no new tabs and keeps focus.
6
9
  - It never touches the page you are looking at on its own.
7
- - Pause it any time: click the DSH Bridge icon in Chrome's toolbar and turn off "Let DSH control the browser".
10
+ - Pause it any time: press `Alt+Shift+X`, or click the DSH Bridge icon in Chrome's toolbar and turn off "Let DSH control the browser". Clicking Cancel on Chrome's debugging bar also pauses — only the panel can resume it.
11
+ - It hands the page back for sign-in, captcha, 2FA or a payment confirmation and waits for "I'm done"; if you use the page yourself while it is working, it steps aside.
8
12
 
9
13
  ## Install
10
14
 
@@ -23,7 +27,7 @@ Open it on the Plugins page and click "Update to …". A new version can be inst
23
27
 
24
28
  - The extension panel in Chrome follows Chrome's language: English, Chinese or Russian.
25
29
  - The settings card on the Plugins page follows DSH's language.
26
- - To give the model English or Russian tool descriptions too, see "Tool descriptions in English or Russian" in the [full guide](https://github.com/OrderG-X/dsh-chrome-bridge#-tool-descriptions-in-english-or-russian).
30
+ - To give the model English or Russian tool descriptions too, see "Tool text in English or Russian" in the [full guide](https://github.com/OrderG-X/dsh-chrome-bridge#-tool-text-in-english-or-russian).
27
31
 
28
32
  ## Requirements
29
33
 
package/README.md CHANGED
@@ -2,9 +2,13 @@
2
2
 
3
3
  让 DSH 直接操作你正在用的 Chrome:真点击、真输入,页面里看得到它的光标,你的登录状态都在。
4
4
 
5
+ - 自带 15 个 `browser_*` 原生工具:读页面(含跨站 iframe)、点击(左右中键 / 双击)、输入、批量填表、下载(含点了才生成的文件)、等网络空闲、看 console 和网络请求、网络 Mock 与脱敏 HAR,以及需要你本人过登录 / 验证码时把页面交还给你的 `browser_handoff`、把操作过程录成 GIF 动图的 `browser_record`。
6
+ - 截图可以给可点元素标编号(`marks`),也能在跨站 iframe 里操作;同时连多个浏览器 / Profile 也认得。
7
+ - 它不会擅自碰你标为受保护的页面:清单默认是空的,只有你在扩展弹窗里加了域名,读或操作它之前才会先弹确认小窗(默认拒绝,放行 15 分钟)。
5
8
  - 它新开的页放进一个单独的窗口,不往你正在用的窗口里塞,也不抢焦点。
6
9
  - 它不会擅自去动你正在看的那一页。
7
- - 随时能暂停:点 Chrome 工具栏上的 DSH Bridge 图标,关掉「允许 DSH 控制浏览器」。
10
+ - 随时能暂停:按 `Alt+Shift+X` 急停,或点 Chrome 工具栏上的 DSH Bridge 图标,关掉「允许 DSH 控制浏览器」。点 Chrome 调试提示条上的「取消」也是暂停 —— 恢复只能回面板手动打开。
11
+ - 需要登录、验证码、两步验证、确认支付时,它会把页面交回给你,等你点「我已完成」再继续;你在它操作的页面里动键鼠,它也会自动让路。
8
12
 
9
13
  ## 怎么装
10
14
 
@@ -23,7 +27,7 @@
23
27
 
24
28
  - Chrome 里的扩展面板跟着 Chrome 的语言走:中文、英文、俄文。
25
29
  - 插件页上的这张设置卡片跟着 DSH 的语言走。
26
- - 想让模型看到的工具说明也换成英文或俄文,看[完整说明](https://github.com/OrderG-X/dsh-chrome-bridge/blob/main/README.zh.md)里「工具描述支持英文 / 俄文」那一节。
30
+ - 想让模型看到的工具说明也换成英文或俄文,看[完整说明](https://github.com/OrderG-X/dsh-chrome-bridge/blob/main/README.zh.md#-工具文案支持英文--俄文)里「工具文案支持英文 / 俄文」那一节。
27
31
 
28
32
  ## 系统要求
29
33
 
package/client.js CHANGED
@@ -5,7 +5,8 @@
5
5
  * 三个开关:允许 DSH 控制浏览器(这里只能关)、页面里显示 DSH 光标、新页开在单独窗口
6
6
  * 没连上时:差哪一步、一键帮你打开安装页
7
7
  *
8
- * 数据全走插件自己挂在 DSH webServer 上的路由(plugin/panel.js),每 2.5 秒刷一次。
8
+ * 数据全走插件自己挂在 DSH webServer 上的路由(plugin/panel.js),每 2.5 秒刷一次;
9
+ * 行卡片的概要和设置页同时挂着也只跑一份轮询(模块级共享,按订阅数开关)。
9
10
  * 走官方客户端插件机制:window.__ModuleLoader__.load({ id, factory }),factory 里 apply(ctx)
10
11
  * → 注册到 plugins.bundle.config(包详情页)和 plugins.row.config(行详情页)两个 keyed slot。
11
12
  * 拿不到 react 或 DSH 的组件就安静退出 / 用最朴素的替身,别把宿主页面搞崩。
@@ -25,7 +26,7 @@ window.__ModuleLoader__.load({
25
26
  }
26
27
  const UI = opt('@deepseek-ai/dsh-client-ui-primitives') || {}
27
28
  const h = React.createElement
28
- const { useState, useEffect, useCallback, useRef } = React
29
+ const { useState, useEffect } = React
29
30
 
30
31
  const PKG = 'dsh-chrome-bridge'
31
32
  const ROW = 'chrome-bridge'
@@ -45,6 +46,11 @@ window.__ModuleLoader__.load({
45
46
  summaryIdle: '已连接,没有在控制的标签页',
46
47
  summaryOff: '还没连上 Chrome,点开看怎么装',
47
48
  summaryPaused: '已暂停:DSH 暂时不能操作浏览器',
49
+ summaryCanceled: '已暂停:你在 Chrome 调试条上点了取消',
50
+ summaryHandoff: 'DSH 在等你:去 Chrome 里处理一下',
51
+ handoffWaiting: 'DSH 停下来等你在 Chrome 里处理一下',
52
+ handoffHow: '弄好后点页面顶部浮条上的完成按钮(或 Chrome 工具栏的 DSH Bridge 里),DSH 会接着干。',
53
+ pausedCanceled: '你点了 Chrome 调试提示条上的「取消」,所以自动暂停了。',
48
54
  storeBuild: '商店版',
49
55
  localBuild: '本地版',
50
56
  controlling: '正在控制 %n 个标签页',
@@ -78,6 +84,7 @@ window.__ModuleLoader__.load({
78
84
  guide: '使用说明',
79
85
  failed: '没成功:%e',
80
86
  unreachable: '读不到插件状态,重启 DSH 后再试',
87
+ protectedSites: 'Chrome 里有 %n 个受保护网站,DSH 动它们前会先弹窗问你。增删请点 Chrome 工具栏的 DSH Bridge 图标。',
81
88
  }
82
89
  const en = {
83
90
  title: 'Chrome Bridge',
@@ -90,6 +97,11 @@ window.__ModuleLoader__.load({
90
97
  summaryIdle: 'Connected, no tabs under control',
91
98
  summaryOff: 'Not connected to Chrome yet — open for setup steps',
92
99
  summaryPaused: 'Paused: DSH cannot operate the browser',
100
+ summaryCanceled: 'Paused: you clicked Cancel on Chrome\'s debugging bar',
101
+ summaryHandoff: 'DSH is waiting for you in Chrome',
102
+ handoffWaiting: 'DSH paused to let you do something in Chrome',
103
+ handoffHow: 'When you are done, click the finish button in the bar at the top of the page (or in DSH Bridge on Chrome\'s toolbar) and DSH carries on.',
104
+ pausedCanceled: 'You clicked Cancel on Chrome\'s debugging bar, so control was paused automatically.',
93
105
  storeBuild: 'Web Store',
94
106
  localBuild: 'Local',
95
107
  controlling: 'Controlling %n tab(s)',
@@ -123,6 +135,7 @@ window.__ModuleLoader__.load({
123
135
  guide: 'Guide',
124
136
  failed: 'That did not work: %e',
125
137
  unreachable: 'Could not read the plugin status; restart DSH and try again',
138
+ protectedSites: 'Protected sites in Chrome: %n. DSH asks you before touching them; add or remove them from the DSH Bridge icon in Chrome\'s toolbar.',
126
139
  }
127
140
 
128
141
  const ru = {
@@ -136,6 +149,11 @@ window.__ModuleLoader__.load({
136
149
  summaryIdle: 'Подключено, вкладок под управлением нет',
137
150
  summaryOff: 'Chrome ещё не подключён — откройте, чтобы увидеть шаги',
138
151
  summaryPaused: 'Пауза: DSH не может работать с браузером',
152
+ summaryCanceled: 'Пауза: вы нажали «Отмена» на панели отладки Chrome',
153
+ summaryHandoff: 'DSH ждёт вас в Chrome',
154
+ handoffWaiting: 'DSH остановился и ждёт, пока вы сделаете шаг в Chrome',
155
+ handoffHow: 'Когда закончите, нажмите кнопку завершения на панели вверху страницы (или в DSH Bridge на панели инструментов Chrome) — DSH продолжит.',
156
+ pausedCanceled: 'Вы нажали «Отмена» на панели отладки Chrome, поэтому включилась пауза.',
139
157
  storeBuild: 'Из магазина',
140
158
  localBuild: 'Локальная',
141
159
  controlling: 'Вкладок под управлением: %n',
@@ -169,6 +187,7 @@ window.__ModuleLoader__.load({
169
187
  guide: 'Инструкция',
170
188
  failed: 'Не получилось: %e',
171
189
  unreachable: 'Не удалось прочитать состояние плагина; перезапустите DSH и попробуйте снова',
190
+ protectedSites: 'Защищённых сайтов в Chrome: %n. Прежде чем их трогать, DSH спросит вас; добавить или убрать их можно через значок DSH Bridge на панели инструментов Chrome.',
172
191
  }
173
192
 
174
193
  const fmt = (s, vars) => String(s).replace(/%([a-z])/g, (m, k) => (vars && k in vars ? String(vars[k]) : m))
@@ -186,6 +205,10 @@ window.__ModuleLoader__.load({
186
205
  .dcb-dot[data-s=on]{background:var(--dsw-alias-state-success-primary,#34c759);box-shadow:0 0 0 3px color-mix(in srgb,var(--dsw-alias-state-success-primary,#34c759) 22%,transparent)}
187
206
  .dcb-dot[data-s=paused]{background:var(--dsw-alias-state-warn-primary,#ff9f0a)}
188
207
  .dcb-dot[data-s=off]{background:var(--dsw-alias-state-error-primary,#ff453a)}
208
+ .dcb-dot[data-s=handoff]{background:#4d6bfe;box-shadow:0 0 0 3px color-mix(in srgb,#4d6bfe 24%,transparent)}
209
+ .dcb-ask{margin-top:6px;padding:8px 10px;border-radius:10px;display:grid;gap:2px;background:color-mix(in srgb,#4d6bfe 10%,transparent)}
210
+ .dcb-ask b{font-weight:600}
211
+ .dcb-ask q{color:var(--dsw-alias-label-primary);overflow-wrap:anywhere}
189
212
  .dcb-tabs{margin:6px 0 0;padding:0;list-style:none;display:grid;gap:2px}
190
213
  .dcb-tabs li{color:var(--dsw-alias-label-secondary);font-size:12px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
191
214
  .dcb-steps{margin:6px 0 0;padding-left:18px;display:grid;gap:4px;color:var(--dsw-alias-label-secondary)}
@@ -229,33 +252,77 @@ window.__ModuleLoader__.load({
229
252
  return res.json()
230
253
  }
231
254
 
232
- /** 2.5 秒刷一次;页面藏起来时不刷。 */
233
- function useBridgeState() {
234
- const [state, setState] = useState(null)
235
- const [error, setError] = useState('')
236
- const alive = useRef(true)
237
- const load = useCallback(async () => {
238
- try {
239
- const s = await fetchState()
240
- if (alive.current) { setState(s); setError('') }
241
- } catch (e) {
242
- if (alive.current) setError(String((e && e.message) || e))
243
- }
244
- }, [])
245
- useEffect(() => {
246
- alive.current = true
255
+ /*
256
+ * 共享轮询:行卡片的一句话概要(Summary)和设置页(Page)常常同时挂着,各跑各的就是两倍请求。
257
+ * 这里按订阅数开关一个 2.5 秒的定时器,结果推给所有订阅者;页面藏起来时不刷,切回前台立刻刷一次。
258
+ * 两道防线,免得旧结果盖掉新结果:
259
+ * seq:每次请求带个序号,晚回来的旧序号不收;
260
+ * gen:写操作(act)开始和结束时各加一,期间发出或还没回来的读(load)一律作废 ——
261
+ * 不然一个赶在 POST 生效前被服务端处理的 GET,回来会把刚点成功的「已暂停」又盖回去。
262
+ */
263
+ const shared = { state: null, error: '', subs: new Set(), timer: 0, inflight: null, inflightGen: -1, seq: 0, applied: 0, gen: 0, acting: 0 }
264
+ function emit() { for (const fn of shared.subs) fn(shared.state, shared.error) }
265
+ function take(my, s) {
266
+ if (my < shared.applied) return
267
+ shared.applied = my
268
+ shared.state = s
269
+ shared.error = ''
270
+ emit()
271
+ }
272
+ function load() {
273
+ if (shared.inflight && shared.inflightGen === shared.gen) return shared.inflight
274
+ const my = ++shared.seq
275
+ const g = shared.gen
276
+ const stale = () => g !== shared.gen || shared.acting > 0
277
+ const p = fetchState().then((s) => { if (!stale()) take(my, s) }, (e) => {
278
+ if (stale() || my < shared.applied) return
279
+ shared.error = String((e && e.message) || e)
280
+ emit()
281
+ }).finally(() => { if (shared.inflight === p) shared.inflight = null })
282
+ shared.inflight = p
283
+ shared.inflightGen = g
284
+ return p
285
+ }
286
+ function onVisible() {
287
+ if (document.visibilityState === 'visible') load()
288
+ }
289
+ function subscribe(fn) {
290
+ shared.subs.add(fn)
291
+ if (shared.subs.size === 1) {
247
292
  load()
248
- const timer = setInterval(() => {
293
+ shared.timer = setInterval(() => {
249
294
  if (typeof document === 'undefined' || document.visibilityState !== 'hidden') load()
250
295
  }, 2500)
251
- return () => { alive.current = false; clearInterval(timer) }
252
- }, [load])
253
- const act = useCallback(async (action) => {
254
- const s = await fetchState(action)
255
- if (alive.current) setState(s)
256
- return s
257
- }, [])
258
- return { state, error, act }
296
+ if (typeof document !== 'undefined') document.addEventListener('visibilitychange', onVisible)
297
+ }
298
+ return () => {
299
+ if (!shared.subs.delete(fn)) return
300
+ if (!shared.subs.size) {
301
+ clearInterval(shared.timer)
302
+ shared.timer = 0
303
+ if (typeof document !== 'undefined') document.removeEventListener('visibilitychange', onVisible)
304
+ }
305
+ }
306
+ }
307
+ async function act(action) {
308
+ const my = ++shared.seq
309
+ shared.gen++
310
+ shared.acting++
311
+ let s
312
+ try {
313
+ s = await fetchState(action)
314
+ } finally {
315
+ shared.acting--
316
+ shared.gen++
317
+ }
318
+ take(my, s)
319
+ return s
320
+ }
321
+
322
+ function useBridgeState() {
323
+ const [snap, setSnap] = useState(() => ({ state: shared.state, error: shared.error }))
324
+ useEffect(() => subscribe((state, error) => setSnap({ state, error })), [])
325
+ return { state: snap.state, error: snap.error, act }
259
326
  }
260
327
 
261
328
  function phaseOf(s) {
@@ -272,7 +339,8 @@ window.__ModuleLoader__.load({
272
339
  if (p === 'checking') return t('checking')
273
340
  if (p === 'unsupported') return t('unsupported')
274
341
  if (p === 'off') return t('summaryOff')
275
- if (p === 'paused') return t('summaryPaused')
342
+ if (p === 'paused') return state.pauseReason === 'canceled_by_user' ? t('summaryCanceled') : t('summaryPaused')
343
+ if (state.handoff) return t('summaryHandoff')
276
344
  return state.attachedCount ? fmt(t('summaryOn'), { n: state.attachedCount }) : t('summaryIdle')
277
345
  }
278
346
 
@@ -299,9 +367,13 @@ window.__ModuleLoader__.load({
299
367
 
300
368
  const statusTitle = { checking: t('checking'), on: t('connected'), paused: t('paused'), off: t('disconnected'), unsupported: t('unsupported') }[p]
301
369
  const ext = state && state.ext
370
+ // 老扩展没有 handoff / pauseReason:都当没有,什么也不多显示
371
+ const handoff = p === 'on' && state.handoff ? state.handoff : null
372
+ const canceled = p === 'paused' && state.pauseReason === 'canceled_by_user'
373
+ const protectedN = state && state.connected && Number.isInteger(state.protectedCount) ? state.protectedCount : 0
302
374
  const status = h('div', { className: 'dcb-card' },
303
375
  h('div', { className: 'dcb-row' },
304
- h('span', { className: 'dcb-dot', 'data-s': p === 'unsupported' ? 'off' : p }),
376
+ h('span', { className: 'dcb-dot', 'data-s': p === 'unsupported' ? 'off' : handoff ? 'handoff' : p }),
305
377
  h('div', { className: 'dcb-main' },
306
378
  h('div', { className: 'dcb-title' }, statusTitle,
307
379
  ext ? h('span', { className: 'dcb-tag' }, `${ext.store ? t('storeBuild') : t('localBuild')} v${ext.version}`) : null),
@@ -311,7 +383,16 @@ window.__ModuleLoader__.load({
311
383
  state && state.tabs && state.tabs.length
312
384
  ? h('ul', { className: 'dcb-tabs' }, state.tabs.map((tab, i) => h('li', { key: i, title: tab.url }, tab.title || tab.url)))
313
385
  : null,
314
- p === 'paused' ? h('p', { className: 'dcb-hint' }, t('resumeInChrome')) : null),
386
+ handoff
387
+ ? h('div', { className: 'dcb-ask', role: 'status' },
388
+ h('b', null, t('handoffWaiting')),
389
+ handoff.reason ? h('q', null, String(handoff.reason)) : null,
390
+ h('span', { className: 'dcb-hint' }, t('handoffHow')))
391
+ : null,
392
+ canceled ? h('p', { className: 'dcb-hint' }, t('pausedCanceled')) : null,
393
+ p === 'paused' ? h('p', { className: 'dcb-hint' }, t('resumeInChrome')) : null,
394
+ // 受保护网站只报个数、只说去哪改:清单的增删和放行只能在 Chrome 里点,DSH 这边碰不了
395
+ protectedN > 0 ? h('p', { className: 'dcb-hint' }, fmt(t('protectedSites'), { n: protectedN })) : null),
315
396
  state && state.connected
316
397
  ? h(Btn, { disabled: !can || !state.attachedCount, onClick: () => run({ action: 'releaseAll' }, t('released')) }, t('releaseAll'))
317
398
  : null))
package/core/ext.js ADDED
@@ -0,0 +1,119 @@
1
+ import fs from 'node:fs'
2
+ import os from 'node:os'
3
+ import path from 'node:path'
4
+ import { fileURLToPath } from 'node:url'
5
+ import { paths, extensionId } from '../setup.js'
6
+ import { call, hostUp, nudgeLegacyHost, trace } from './transport.js'
7
+
8
+ /**
9
+ * 后台标签页(或者 Chrome 窗口被别的窗口挡住)时页面是 hidden,CDP 发的鼠标/键盘事件
10
+ * 会被直接丢掉——工具照样回「已点击」,其实什么都没发生(实测:3 次点击 0 次生效)。
11
+ * 打开焦点模拟后事件就能送达(Playwright 对每个页面都这么做)。
12
+ * 空闲断开调试会话会清掉它,所以每次动手前补一下,本地一个来回,很便宜。
13
+ */
14
+ /** 这几种错不能吞:吞了接着点 / 打字,只会再弹一次确认窗、再等一次超时 */
15
+ const FATAL_CODES = new Set(['USER_ACTIVE', 'USER_DENIED_SENSITIVE', 'CONFIRM_LATE', 'EXTENSION_TIMEOUT'])
16
+ /** 超时、连接断了、桥没在跑(中 / 英 / 俄三种报错文字都认) */
17
+ const FATAL_TEXT = /超时|timed out|closed|关掉|ECONNREFUSED|ECONNRESET|EPIPE|not connected|未连接|没在跑|not running|连不上|cannot reach|已退出|refused|истекло время|закрыто|не запущен|не удаётся подключиться|отклонил/i
18
+
19
+ export async function emulateFocus(tabId) {
20
+ try {
21
+ await call('cdp', { tabId, method: 'Emulation.setFocusEmulationEnabled', params: { enabled: true } })
22
+ } catch (e) {
23
+ const message = String((e && e.message) || e || '')
24
+ if (FATAL_CODES.has(e && e.code) || /^(USER_ACTIVE|USER_DENIED_SENSITIVE|CONFIRM_LATE)\b/.test(message) || FATAL_TEXT.test(message)) throw e
25
+ // 剩下的是 CDP 不支持这条命令(旧扩展 / 旧 Chrome)、页面还没就绪这类:焦点模拟只是锦上添花,忽略
26
+ trace(`焦点模拟失败(忽略): ${message}`)
27
+ }
28
+ }
29
+
30
+ /**
31
+ * 扩展是「已解压」加载的:setup 把新文件拷进扩展目录后,Chrome 不会自己重载,跑的还是旧代码。
32
+ * 所以插件启动时对一下版本号,对不上就让扩展自己 chrome.runtime.reload()(一秒内带着新代码回来)。
33
+ *
34
+ * 只管解压版(ID 和 ~/dsh-bridge-extension 推导出来的一致)。商店版的代码由商店自己更新,
35
+ * reload 只会白白掐断宿主一下;而商店版本号常常落后本地,不跳过就会每次启动都重载。
36
+ */
37
+ let extVersion
38
+ let versionProbe
39
+ let lastVersionProbe = 0
40
+ function checkExtensionVersion() {
41
+ if (versionProbe) return versionProbe
42
+ lastVersionProbe = Date.now()
43
+ versionProbe = call('version', {}, 1200, true).then((r) => {
44
+ extVersion = r?.version
45
+ return r || {}
46
+ }).catch(() => ({})).finally(() => { versionProbe = undefined })
47
+ return versionProbe
48
+ }
49
+
50
+ export function getExtVersion() {
51
+ return extVersion
52
+ }
53
+
54
+ export function isExtAtLeast(requiredMajor, requiredMinor, requiredPatch = 0, requiredBuild = 0) {
55
+ const version = getExtVersion()
56
+ if (!/^\d+(?:\.\d+){2,3}$/.test(version || '')) return false
57
+ const [major, minor, patch, build = 0] = version.split('.').map(Number)
58
+ if (major !== requiredMajor) return major > requiredMajor
59
+ if (minor !== requiredMinor) return minor > requiredMinor
60
+ if (patch !== requiredPatch) return patch > requiredPatch
61
+ return build >= requiredBuild
62
+ }
63
+
64
+ export const hasBuiltinCursor = () => isExtAtLeast(1, 16)
65
+
66
+ export async function cursorReady() {
67
+ if (versionProbe) await versionProbe
68
+ else if (!extVersion && Date.now() - lastVersionProbe > 2000) await checkExtensionVersion()
69
+ }
70
+
71
+ export async function refreshExtension() {
72
+ if (!hostUp()) {
73
+ if (!process.env.DSH_BRIDGE_SOCK) nudgeLegacyHost()
74
+ return
75
+ }
76
+ const { version, id } = await checkExtensionVersion()
77
+ if (!version) return
78
+ let want, localId
79
+ try {
80
+ const manifestFile = path.join(paths().extDir, 'manifest.json')
81
+ want = JSON.parse(fs.readFileSync(manifestFile, 'utf8')).version
82
+ localId = extensionId(manifestFile)
83
+ } catch {
84
+ return
85
+ }
86
+ try {
87
+ if (id && id !== localId) {
88
+ trace(`扩展 ${version}(${id})不是本地解压版,不重载`)
89
+ return
90
+ }
91
+ if (version === want) return
92
+ await call('reload', {}, 5000)
93
+ extVersion = undefined
94
+ lastVersionProbe = 0
95
+ trace(`扩展 ${version} → ${want}:已让它重载`)
96
+ } catch (e) {
97
+ trace(`检查扩展版本失败(忽略): ${e && e.message}`)
98
+ }
99
+ }
100
+
101
+ /** 页内光标脚本:点东西时让用户看得见。读不到就静默降级。 */
102
+ let cursorCache
103
+ export function cursorScript() {
104
+ if (cursorCache !== undefined) return cursorCache
105
+ // 先用插件自带的那份:版本跟插件走,别的安装脚本往 ~/.dsh/chrome-cursor 里写了旧版也不受影响
106
+ const candidates = [
107
+ fileURLToPath(new URL('../vendor/in-page-cursor.js', import.meta.url)),
108
+ path.join(os.homedir(), '.dsh/chrome-cursor/in-page-cursor.js'), // setup.js 落盘的位置(cb 命令行也读它)
109
+ ]
110
+ cursorCache = ''
111
+ for (const file of candidates) {
112
+ try { cursorCache = fs.readFileSync(file, 'utf8'); break } catch {}
113
+ }
114
+ return cursorCache
115
+ }
116
+ export const withCursor = (extra = {}) => {
117
+ const script = hasBuiltinCursor() ? null : cursorScript()
118
+ return script ? { ...extra, script } : extra
119
+ }