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
@@ -0,0 +1,219 @@
1
+ import { rememberAttached } from './cdp.js'
2
+ import { hidePageCursor, installInputListener, markCursor } from './cursor.js'
3
+ import { S } from './state.js'
4
+ import { isExtUrl, log, updateBadge } from './util.js'
5
+
6
+ // ── 正在被控制的标签页:自动分组 + 扩展图标上的 🖱 角标 ──────────────────────
7
+ // 用户在标签栏上一眼就能看出"agent 正在动哪几个页面",松手(空闲断开 / 显式 detach /
8
+ // 关掉标签页 / 点掉 Chrome 那条调试提示)就自动还原,不留痕。
9
+
10
+ // 用户看得见的两处文字(标签组名、工具栏图标的悬停提示)跟 Chrome 的界面语言走:zh* 中文、ru* 俄文、其它英文。
11
+ // 认「我们的组」时几种语言的组名、以及老版本的「DSH agent 正在操作」都算,换了语言或升级后老组照样会被拆掉。
12
+
13
+ function readLanguage() {
14
+ let l = ''
15
+ try { l = String(chrome.i18n.getUILanguage() || '').toLowerCase() } catch {}
16
+ return l.startsWith('zh') ? 'zh' : l.startsWith('ru') ? 'ru' : 'en'
17
+ }
18
+
19
+ const GROUP_TITLES = { zh: 'DSH 正在操作', en: 'DSH at work', ru: 'DSH работает' }
20
+ const labels = {
21
+ zh: { click: '点击', type: '输入', hover: '悬停', up: '向上滚动', down: '向下滚动', handoff: '请接管此页面', done: '已完成' },
22
+ en: { click: 'Click', type: 'Type', hover: 'Hover', up: 'Scroll up', down: 'Scroll down', handoff: 'Your turn', done: 'Done' },
23
+ ru: { click: 'Нажатие', type: 'Ввод', hover: 'Наведение', up: 'Прокрутка вверх', down: 'Прокрутка вниз', handoff: 'Управление передано вам', done: 'Готово' },
24
+ }
25
+ const OUR_GROUP_TITLES = new Set([...Object.values(GROUP_TITLES), 'DSH agent 正在操作'])
26
+ const CURSOR_TAB_TITLE = {
27
+ zh: 'DSH 正在操作这个标签页(页面里有它的光标)',
28
+ en: 'DSH is working in this tab (its cursor is on the page)',
29
+ ru: 'DSH работает в этой вкладке (его курсор на странице)',
30
+ }
31
+ const CURSOR_ICON = { 16: 'icons/cursor16.png', 32: 'icons/cursor32.png', 48: 'icons/cursor48.png' }
32
+ // 标签页上的小鼠标:把页面 favicon 临时换成它(data URL,绕开页面 CSP 与 web_accessible_resources)
33
+ const CURSOR_FAVICON = 'data:image/png;base64,iVBOR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ZAA8O5oMq4D8AAAD//zouHuEAAAAGSURBVAMAYX64YuQ3mpYAAAAASUVORK5CYII='
34
+ const IDLE_ICON = { 16: 'icons/icon16.png', 32: 'icons/icon32.png', 48: 'icons/icon48.png' }
35
+
36
+ /** 受控标签页的 favicon 换成小鼠标(松手还原)。页面导航后 favicon 自然复原,下次控制再补。 */
37
+ async function setTabFavicon(tabId, on) {
38
+ try {
39
+ await chrome.scripting.executeScript({
40
+ target: { tabId: Number(tabId) },
41
+ func: (on, href) => {
42
+ const ID = 'dsh-bridge-cursor-favicon'
43
+ const OFF = 'data-dsh-bridge-rel'
44
+ const old = document.getElementById(ID)
45
+ if (!on) {
46
+ // 把页面自己的图标 link 换回来(rel 改回去 Chrome 就会重算);
47
+ // 页面一个都没写、靠默认 /favicon.ico 的,光删掉我们的 Chrome 不换回去 —— 补一个指向默认图标的
48
+ const parked = [...document.querySelectorAll(`link[${OFF}]`)]
49
+ if (!old && !parked.length) return
50
+ if (old) old.remove()
51
+ for (const l of parked) { l.rel = l.getAttribute(OFF); l.removeAttribute(OFF) }
52
+ if (!parked.length && !document.querySelector('link[rel~="icon"]')) {
53
+ const d = document.createElement('link')
54
+ d.rel = 'icon'
55
+ d.href = '/favicon.ico'
56
+ d.setAttribute('data-dsh-bridge', 'restore')
57
+ document.head.appendChild(d)
58
+ }
59
+ return
60
+ }
61
+ if (old) return
62
+ // 页面自己有图标的话 Chrome 会优先用它,我们的小鼠标挂不上去 —— 先把它们的 rel 停掉,松手时原样恢复
63
+ for (const l of document.querySelectorAll('link[rel~="icon"]')) {
64
+ l.setAttribute(OFF, l.rel)
65
+ l.rel = 'dsh-bridge-parked-icon'
66
+ }
67
+ const l = document.createElement('link')
68
+ l.id = ID
69
+ l.rel = 'icon'
70
+ l.type = 'image/png'
71
+ l.href = href
72
+ document.head.appendChild(l)
73
+ },
74
+ args: [on, CURSOR_FAVICON],
75
+ })
76
+ } catch {}
77
+ }
78
+
79
+ async function markTab(tabId) {
80
+ const id = Number(tabId)
81
+ S.tabEpoch.set(id, (S.tabEpoch.get(id) || 0) + 1)
82
+ updateBadge()
83
+ // 分组 = "这个标签页正在被操作";标签上的小鼠标只跟页内光标走(markCursor)
84
+ await ensureGroup(id, S.tabSessions.get(id))
85
+ }
86
+
87
+ /**
88
+ * 同一个窗口里的受控标签页共用**同一个组**(不然同时操作 3 个标签页会出现 3 个同名蓝组)。
89
+ * 优先复用:内存里记的组 id → 按标题找本窗口现成的组 → 都没有才新建。
90
+ * 用户自己固定的、已经在用户自己分组里的标签页不动:分组会取消固定、把它挪出原来的组,松手时也还原不回去。
91
+ */
92
+ const groupColors = ['blue', 'cyan', 'purple', 'green', 'orange', 'pink']
93
+
94
+ function restoreGroups() {
95
+ S.UI_LANG = readLanguage()
96
+ S.groupsReady = chrome.storage?.session?.get('ownedGroupIds').then(v => {
97
+ for (const id of v.ownedGroupIds || []) S.ownedGroupIds.add(id)
98
+ }).catch(() => {})
99
+ }
100
+
101
+ async function ensureGroup(tabId, sessionKey = 'cli') {
102
+ await S.groupsReady
103
+ if (!S.sessionColors.has(sessionKey)) S.sessionColors.set(sessionKey, sessionKey === 'cli' ? 'blue' : groupColors[S.sessionColors.size % groupColors.length])
104
+ const color = S.sessionColors.get(sessionKey)
105
+ const id = Number(tabId)
106
+ if (S.groupedTabs.has(id)) return
107
+ const tab = await chrome.tabs.get(id).catch(() => null)
108
+ if (!tab || tab.pinned) return
109
+ const wid = tab.windowId
110
+ const previous = S.groupQueues.get(wid) || Promise.resolve()
111
+ const apply = () => groupInWindow(id, wid, sessionKey, color)
112
+ const current = previous.then(apply, apply)
113
+ S.groupQueues.set(wid, current)
114
+ try { await current }
115
+ finally { if (S.groupQueues.get(wid) === current) S.groupQueues.delete(wid) }
116
+ }
117
+
118
+ async function groupInWindow(id, wid, sessionKey, color) {
119
+ const tab = await chrome.tabs.get(id).catch(() => null)
120
+ if (!tab || tab.pinned || tab.windowId !== wid) return
121
+ const key = wid + '/' + sessionKey
122
+ if (tab.groupId >= 0) {
123
+ let g = null
124
+ try { g = await chrome.tabGroups.get(tab.groupId) } catch {}
125
+ if (!g || (!OUR_GROUP_TITLES.has(g.title) && !S.ownedGroupIds.has(g.id))) return // 用户自己的组
126
+ S.groupedTabs.set(id, tab.groupId) // 本来就在我们的组里(worker 重启过之类)
127
+ S.ourGroup.set(key, tab.groupId)
128
+ return
129
+ }
130
+ const candidates = []
131
+ if (S.ourGroup.has(key)) candidates.push(S.ourGroup.get(key))
132
+ try {
133
+ // 只找本窗口的:按标题跨窗口复用,会把标签页拽到别的窗口去
134
+ for (const g of await chrome.tabGroups.query({ windowId: wid })) {
135
+ if ((S.ownedGroupIds.has(g.id) || OUR_GROUP_TITLES.has(g.title)) && (g.color || 'blue') === color && !candidates.includes(g.id)) candidates.push(g.id)
136
+ }
137
+ } catch {}
138
+ for (const gid of candidates) {
139
+ try {
140
+ if ((await chrome.tabGroups.get(gid)).windowId !== wid) continue // 记着的组被拖去了别的窗口
141
+ await chrome.tabs.group({ tabIds: [id], groupId: gid })
142
+ S.groupedTabs.set(id, gid)
143
+ S.ourGroup.set(key, gid)
144
+ await chrome.tabGroups.update(gid, { title: GROUP_TITLES[S.UI_LANG], color })
145
+ return
146
+ } catch {}
147
+ }
148
+ try {
149
+ // 新建的组一定要指明在它自己的窗口:不写的话 Chrome 建在「当前窗口」,会把别的窗口里的标签页(比如干活窗口里的)拽过来
150
+ const gid = await chrome.tabs.group({ tabIds: [id], createProperties: { windowId: wid } })
151
+ S.ownedGroupIds.add(gid)
152
+ await chrome.storage?.session?.set({ ownedGroupIds: [...S.ownedGroupIds] }).catch(e => log(String(e)))
153
+ S.groupedTabs.set(id, gid)
154
+ S.ourGroup.set(key, gid)
155
+ await chrome.tabGroups.update(gid, { title: GROUP_TITLES[S.UI_LANG], color })
156
+ } catch (e) {
157
+ console.log('[dsh-bridge] 分组失败(不影响干活):', String(e && e.message || e))
158
+ }
159
+ }
160
+
161
+ async function unmarkTab(tabId) {
162
+ const id = Number(tabId)
163
+ const epoch = S.tabEpoch.get(id) || 0 // 竞态守卫:await 期间如果有新的 mark,就放弃这次 unmark
164
+ updateBadge()
165
+ S.cursorReady.delete(id) // 必修:不清的话,松手后小鼠标灭了就再也不亮(页面里的光标其实还在)
166
+ S.cursorPos.delete(id) // 松手后再接手,光标从新目标处冒出来,不从老地方飞
167
+ await hidePageCursor(id) // 尽力把页内光标收掉(松手不留痕)
168
+ await markCursor(id, false)
169
+ if ((S.tabEpoch.get(id) || 0) !== epoch) return // 期间又被 mark 了,别拆
170
+ if (!S.groupedTabs.has(id)) return
171
+ const gid = S.groupedTabs.get(id)
172
+ S.groupedTabs.delete(id)
173
+ try {
174
+ // 用户中途把它拖进了自己的组:那是用户的组,别拆
175
+ if ((await chrome.tabs.get(id)).groupId === gid) await chrome.tabs.ungroup([id])
176
+ } catch {}
177
+ }
178
+
179
+ /**
180
+ * 自愈:service worker 会被 Chrome 随时挂起、扩展重载也会清掉内存里的分组表,
181
+ * 但 Chrome 那边的组是持久的。所以启动时对一遍账:
182
+ * · 还挂着调试会话的标签页 → 认领回分组表(继续归我们管)
183
+ * · 已经没会话、却还留在我们组里的(几种语言的组名、老版本的组名都算)→ 拆掉还原(别留孤儿组和残留角标)
184
+ */
185
+ async function reconcileGroups() {
186
+ try {
187
+ await S.groupsReady
188
+ const targets = await chrome.debugger.getTargets()
189
+ const attachedIds = new Set(targets.filter(t => t.attached && t.tabId != null && !isExtUrl(t.url)).map(t => t.tabId))
190
+ for (const id of attachedIds) {
191
+ try { await chrome.debugger.sendCommand?.({ tabId: id }, 'Page.getLayoutMetrics', {}) }
192
+ catch { attachedIds.delete(id); continue }
193
+ rememberAttached(id)
194
+ S.lastUsed.set(id, Date.now())
195
+ await installInputListener(id)
196
+ }
197
+ updateBadge()
198
+ const groups = (await chrome.tabGroups.query({})).filter(g => S.ownedGroupIds.has(g.id) || OUR_GROUP_TITLES.has(g.title))
199
+ for (const g of groups) {
200
+ const tabs = await chrome.tabs.query({ groupId: g.id })
201
+ for (const t of tabs) {
202
+ if (attachedIds.has(t.id)) {
203
+ S.groupedTabs.set(t.id, g.id)
204
+ } else if (!S.attached.has(t.id)) { // 重新确认一次:启动瞬间并发进来的 op 别被误拆
205
+ S.groupedTabs.set(t.id, g.id) // 先认领,unmarkTab 才会真的去拆
206
+ await unmarkTab(t.id)
207
+ }
208
+ }
209
+ }
210
+ } catch (e) {
211
+ console.log('[dsh-bridge] 分组对账失败(不影响干活):', String(e && e.message || e))
212
+ }
213
+ }
214
+
215
+ export {
216
+ GROUP_TITLES, labels, OUR_GROUP_TITLES, CURSOR_TAB_TITLE, CURSOR_ICON, CURSOR_FAVICON,
217
+ IDLE_ICON, setTabFavicon, markTab, groupColors, restoreGroups, ensureGroup, groupInWindow,
218
+ unmarkTab, reconcileGroups,
219
+ }
@@ -0,0 +1,166 @@
1
+ import { ACTIVITY_MAX, QUIET_CDP, QUIET_OPS, S } from './state.js'
2
+
3
+ function log(...args) {
4
+ const line = new Date().toISOString().slice(11, 19) + ' ' + args.map(a =>
5
+ typeof a === 'string' ? a : (() => { try { return JSON.stringify(a) } catch { return String(a) } })()
6
+ ).join(' ')
7
+ S.LOG.push(line)
8
+ if (S.LOG.length > 400) S.LOG.shift()
9
+ console.log(line)
10
+ }
11
+
12
+ /** 把 CDP 的英文报错翻成人能用的提示 */
13
+ function friendly(e) {
14
+ const m = String((e && e.message) || e)
15
+ // 我们自己的报错(开头一个大写记号,插件按它换成各语言的话)原样过:FILE_ACCESS_OFF 里带着 chrome://extensions 地址
16
+ if (/^(FILE_ACCESS_OFF|NO_FILE_CHOOSER|MULTI_NOT_ALLOWED|USER_PICKED|FOLDER_INPUT) /.test(m)) return e
17
+ if (m.includes('chrome://') || m.includes('Cannot access a chrome')) {
18
+ return new Error('这个标签页是 chrome:// 内部页,浏览器禁止注入。用 cb tabs 挑一个 http/https 的标签页')
19
+ }
20
+ if (m.includes('No tab with id')) return new Error('标签页已经不存在了(可能被关掉了)')
21
+ if (m.includes('Another debugger is already attached') || m.includes('Cannot attach')) {
22
+ return new Error('这个标签页被别的调试器占着(多半是 DevTools 开着)——关掉 DevTools 再试')
23
+ }
24
+ if (m.includes('Detached while handling command') || m.includes('Debugger is not attached')) {
25
+ return new Error('这个标签页空闲被断开了(或页面刚导航过)——直接重试即可,会自动重连')
26
+ }
27
+ if (m.includes('Cannot find context with specified id')) return new Error('页面刚跳转过,执行上下文没了——重试一次')
28
+ if (m.includes('No dialog is showing')) return new Error('当前没有弹窗挡着(可能被 Chrome 推迟到标签页获得焦点时才弹)')
29
+ return e instanceof Error ? e : new Error(m)
30
+ }
31
+
32
+ /**
33
+ * 这个网址是不是扩展页面:只看协议头(不分大小写)。URL 解析会吃掉的东西先去掉再比:
34
+ * 任何位置的 tab / 换行,开头的空白和控制字符。网址别处(查询串之类)出现 chrome-extension: 不算。
35
+ */
36
+ const isExtUrl = (v) => typeof v === 'string' &&
37
+ /^chrome-extension:/i.test(v.replace(/[\t\n\r]/g, '').replace(/^[\x00-\x20]+/, ''))
38
+
39
+ /** 受控标签页里,扩展自己的页面(弹窗被当成网页打开时)不算数 */
40
+ const controlledCount = () => S.attached.size
41
+
42
+ function clientKey(c) {
43
+ if (!c) return 'cli'
44
+ const kind = c.kind || 'dsh'
45
+ return c.session ? `${kind}:${c.session}` : `${kind}:pid${c.pid || '?'}`
46
+ }
47
+
48
+ function track(client, op, args, result, error, ms) {
49
+ if (QUIET_OPS.has(op)) return
50
+ if (op === 'open' && isExtUrl(args.url)) return
51
+ // CDP 的原始报错是一段 JSON({"code":-32000,"message":"…"}),弹窗里只留 message
52
+ if (error && error.trim().startsWith('{')) {
53
+ try { error = JSON.parse(error).message || error } catch {}
54
+ }
55
+ if (op === 'cdp' && QUIET_CDP.has(args.method)) return
56
+ const now = Date.now()
57
+ const key = clientKey(client)
58
+ let s = S.SESSIONS.get(key)
59
+ if (!s) {
60
+ s = { key, kind: client ? client.kind || 'dsh' : 'cli', session: (client && client.session) || null,
61
+ pid: (client && client.pid) || null, first: now, last: 0, ops: 0, errors: 0, tabs: new Set() }
62
+ S.SESSIONS.set(key, s)
63
+ }
64
+ s.last = now
65
+ s.ops++
66
+ if (error) s.errors++
67
+ const tabId = args.tabId != null ? Number(args.tabId) : result && result.tabId != null ? Number(result.tabId) : null
68
+ if (tabId != null) {
69
+ if (op === 'close') s.tabs.delete(tabId)
70
+ else s.tabs.add(tabId)
71
+ }
72
+
73
+ const call = client && client.call
74
+ const prev = call ? S.ACTIVITY.find((a) => a.call === call) : null
75
+ if (prev) {
76
+ prev.last = now
77
+ prev.ops++
78
+ prev.ms += ms
79
+ if (tabId != null && prev.tabId == null) prev.tabId = tabId
80
+ if (error) { prev.ok = false; prev.error = error }
81
+ return
82
+ }
83
+ S.ACTIVITY.push({
84
+ at: now, last: now, key, call: call || null, tool: (client && client.tool) || null,
85
+ hint: (client && client.hint) || '', op: op === 'cdp' ? `cdp:${args.method}` : op,
86
+ tabId, ok: !error, error: error || undefined, ms, ops: 1,
87
+ })
88
+ if (S.ACTIVITY.length > ACTIVITY_MAX) S.ACTIVITY.shift()
89
+ }
90
+
91
+ /** 工具栏图标角标:受控标签页数;暂停 ⏸;宿主断了 ! */
92
+ function updateBadge() {
93
+ try {
94
+ const n = controlledCount()
95
+ let text = n ? String(n) : ''
96
+ let color = '#4D6BFE'
97
+ if (S.paused) { text = '⏸'; color = '#B7791F' } else if (S.activeHandoff) { text = '✋'; color = '#B7791F' } else if (!S.port) { text = '!'; color = '#E5484D' }
98
+ chrome.action.setBadgeText({ text })
99
+ chrome.action.setBadgeBackgroundColor({ color })
100
+ if (chrome.action.setBadgeTextColor) chrome.action.setBadgeTextColor({ color: '#FFFFFF' })
101
+ } catch {}
102
+ }
103
+
104
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms))
105
+
106
+ // URL canonicalizes IPv4 aliases and bracketed IPv6 literals before this check.
107
+ function localHostname(hostname) {
108
+ let host = String(hostname || '').trim().toLowerCase().replace(/\.$/, '')
109
+ if (!host) return true
110
+ if (host.includes(':') && !host.startsWith('[')) host = `[${host}]`
111
+ if (host.startsWith('[')) {
112
+ const inner = host.slice(1, -1)
113
+ const mapped4 = /^::ffff:(\d+\.\d+\.\d+\.\d+)$/.exec(inner)
114
+ if (mapped4) return localHostname(mapped4[1])
115
+ const mappedHex = /^::ffff:([0-9a-f]+):([0-9a-f]+)$/.exec(inner)
116
+ if (mappedHex) {
117
+ const hi = parseInt(mappedHex[1], 16), lo = parseInt(mappedHex[2], 16)
118
+ return localHostname(`${hi >> 8}.${hi & 255}.${lo >> 8}.${lo & 255}`)
119
+ }
120
+ return !/^[23][0-9a-f]{3}:/.test(inner) || /^(2002:|2001:0*:)/.test(inner)
121
+ }
122
+ if (host === '168.63.129.16') return true
123
+ if (!host.includes('.') || /(?:^|\.)(?:localhost|local|internal|lan|home\.arpa|nip\.io|sslip\.io|xip\.io|localtest\.me|lvh\.me|vcap\.me)$/.test(host)) return true
124
+ if (!/^\d+\.\d+\.\d+\.\d+$/.test(host)) return false
125
+ const [a, b] = host.split('.').map(Number)
126
+ return a === 0 || a === 10 || a === 127 || a >= 224 || (a === 169 && b === 254) ||
127
+ (a === 172 && b >= 16 && b <= 31) || (a === 192 && b === 168) || (a === 100 && b >= 64 && b <= 127)
128
+ }
129
+
130
+ function checkPath(path, allowHidden = false) {
131
+ if (typeof path !== 'string' || path.includes('\0') || path.split(/[\\/]/).some(s => allowHidden ? s === '.' || s === '..' : s.startsWith('.')) ||
132
+ !(/^(?:\/|[a-z]:[\\/]|\\\\[^\\])/i.test(path))) throw new Error('路径无效:需要绝对路径,禁止不安全路径段和空字节')
133
+ }
134
+
135
+ function timeLeft(deadline) {
136
+ const remaining = deadline - Date.now()
137
+ if (remaining <= 0) throw new Error('操作超时')
138
+ return remaining
139
+ }
140
+
141
+ async function within(promise, ms, message) {
142
+ let timer
143
+ try {
144
+ return await Promise.race([promise, new Promise((_, reject) => {
145
+ timer = setTimeout(() => reject(new Error(message)), Math.max(0, ms))
146
+ })])
147
+ } finally { clearTimeout(timer) }
148
+ }
149
+
150
+ function subscribe(listeners, fn) {
151
+ listeners.add(fn)
152
+ return () => listeners.delete(fn)
153
+ }
154
+
155
+ // Chrome delivers each listener independently, including when another listener fails.
156
+ function notify(listeners, ...args) {
157
+ for (const fn of [...listeners]) {
158
+ try { Promise.resolve(fn(...args)).catch(e => log(String(e))) }
159
+ catch (e) { log(String(e)) }
160
+ }
161
+ }
162
+
163
+ export {
164
+ log, friendly, isExtUrl, controlledCount, clientKey, track, updateBadge, sleep, localHostname,
165
+ checkPath, timeLeft, within, subscribe, notify,
166
+ }
@@ -0,0 +1,26 @@
1
+ import { log } from './util.js'
2
+
3
+ /**
4
+ * 首次安装欢迎页(welcome.html):只在从 Chrome 应用商店新装的那一下打开一次。
5
+ * 三个条件同时满足才开:
6
+ * ① onInstalled 的 reason 是 install(更新、Chrome 自己升级都不算);
7
+ * ② manifest 里有 update_url —— 商店装的才有;「加载已解压的扩展程序」和 E2E 的 loadUnpacked 都没有,绝不误弹;
8
+ * ③ 不是被自动化驱动的浏览器(navigator.webdriver)。
9
+ * 开了回 true,没开回 false。
10
+ */
11
+ async function maybeOpenWelcome(details) {
12
+ if (!details || details.reason !== 'install') return false
13
+ let manifest
14
+ try { manifest = chrome.runtime.getManifest() } catch { return false }
15
+ if (!manifest || !manifest.update_url) return false
16
+ if (globalThis.navigator?.webdriver) return false
17
+ try {
18
+ await chrome.tabs.create({ url: chrome.runtime.getURL('welcome.html'), active: true })
19
+ return true
20
+ } catch (e) {
21
+ log('欢迎页打不开:', String((e && e.message) || e))
22
+ return false
23
+ }
24
+ }
25
+
26
+ export { maybeOpenWelcome }
@@ -0,0 +1,94 @@
1
+ import { S } from './state.js'
2
+
3
+ // ── DSH 自己的干活窗口 ──────────────────────────────────────────────────────
4
+
5
+ /**
6
+ * 新开的页默认放进一个单独的 Chrome 窗口:同一个用户资料,登录状态都在,但不往用户正在用的窗口里塞标签页。
7
+ * 窗口在后台开(不抢焦点),之后新开的页都进它;用户把它关了,下次再开一个。
8
+ * 普通和隐身各用各的:用户正在隐身窗口里,新页就开进隐身的干活窗口,不把隐身的事带进普通的 Cookie 和历史记录(反过来也一样)。
9
+ * 窗口 id 记在 storage.session:worker 被挂起再起来还认得;浏览器重启就清空(id 也变了)。
10
+ */
11
+
12
+ function restoreWindows() {
13
+ S.agentWindowReady = chrome.storage.session.get(['agentWindows', 'agentTabs']).then((v) => {
14
+ Object.assign(S.agentWindows, (v && v.agentWindows) || {})
15
+ for (const id of (v && v.agentTabs) || []) S.agentTabs.add(id)
16
+ }).catch(() => {})
17
+ }
18
+
19
+ function saveAgentWindows() {
20
+ chrome.storage.session.set({ agentWindows: { ...S.agentWindows }, agentTabs: [...S.agentTabs] }).catch(() => {})
21
+ }
22
+
23
+ function forgetAgentWindow(id) {
24
+ let changed = false
25
+ for (const k of Object.keys(S.agentWindows)) if (S.agentWindows[k] === id) { S.agentWindows[k] = null; changed = true }
26
+ if (changed) saveAgentWindows()
27
+ }
28
+
29
+ /** 这一种(normal / incognito)的干活窗口还在就回它的 id,没了(被关掉、浏览器重启过)回 null */
30
+ async function agentWindow(mode) {
31
+ await S.agentWindowReady
32
+ const id = S.agentWindows[mode]
33
+ if (id == null) return null
34
+ try {
35
+ const w = await chrome.windows.get(id)
36
+ if (w && w.type === 'normal' && !!w.incognito === (mode === 'incognito')) return w.id
37
+ } catch {}
38
+ forgetAgentWindow(id)
39
+ return null
40
+ }
41
+
42
+ /** 现在还在的干活窗口(两种都算),列标签页时标出来用 */
43
+ async function agentWindowIds() {
44
+ return new Set((await Promise.all(['normal', 'incognito'].map(agentWindow))).filter((id) => id != null))
45
+ }
46
+
47
+ function openInAgentWindow(url) {
48
+ const run = S.agentWindowQueue.then(() => openInAgentWindowNow(url))
49
+ S.agentWindowQueue = run.catch(() => {})
50
+ return run
51
+ }
52
+
53
+ function rememberAgentTab(t) {
54
+ S.agentTabs.add(t.id)
55
+ saveAgentWindows()
56
+ return t
57
+ }
58
+
59
+ async function openInAgentWindowNow(url) {
60
+ // 用户最后在用的普通窗口:隐身与否跟它走,新窗口的大小也照它
61
+ let cur = null
62
+ try { cur = await chrome.windows.getLastFocused({ windowTypes: ['normal'] }) } catch {}
63
+ const incognito = !!(cur && cur.incognito)
64
+ const mode = incognito ? 'incognito' : 'normal'
65
+ const wid = await agentWindow(mode)
66
+ if (wid != null) {
67
+ try {
68
+ // 窗口里正显示的是 DSH 开的页就切到新页(偷看一眼就是最新的);不动窗口焦点。
69
+ // 正显示的是用户自己拖进来的页:别把它切走,新页在后台开
70
+ const [shown] = await chrome.tabs.query({ windowId: wid, active: true })
71
+ return rememberAgentTab(await chrome.tabs.create({ windowId: wid, url, active: !shown || S.agentTabs.has(shown.id) }))
72
+ } catch (e) {
73
+ // 刚好在这一下被关掉了:下面重开一个。窗口还在就是别的错(比如网址不让开),照实报
74
+ if (await chrome.windows.get(wid).then(() => true, () => false)) throw e
75
+ forgetAgentWindow(wid)
76
+ }
77
+ }
78
+ // 跟用户当前窗口一样大、错开一点;最大化 / 全屏的不照抄,交给 Chrome 默认
79
+ const props = { url, focused: false, type: 'normal', incognito }
80
+ let w
81
+ if (cur && cur.state === 'normal' && cur.width && cur.height) {
82
+ try {
83
+ w = await chrome.windows.create({ ...props, left: cur.left + 40, top: cur.top + 40, width: cur.width, height: cur.height })
84
+ } catch {} // 窗口贴着屏幕边,错开以后一半到了屏幕外,Chrome 不让开:交给它自己摆
85
+ }
86
+ if (!w) w = await chrome.windows.create(props)
87
+ S.agentWindows[mode] = w.id
88
+ return rememberAgentTab(w.tabs[0])
89
+ }
90
+
91
+ export {
92
+ restoreWindows, saveAgentWindows, forgetAgentWindow, agentWindow, agentWindowIds,
93
+ openInAgentWindow, rememberAgentTab, openInAgentWindowNow,
94
+ }