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.
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 +231 -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 +439 -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/drag.js CHANGED
@@ -84,12 +84,15 @@ const NATIVE_JS = (from, to, a, b) => `(() => {
84
84
  bubbles: true, cancelable: true, composed: true, clientX: p.x, clientY: p.y, dataTransfer: dt,
85
85
  }));
86
86
  const A = { x: ${a.x}, y: ${a.y} }, B = { x: ${b.x}, y: ${b.y} };
87
- fire(src, 'dragstart', A);
88
- fire(tgt, 'dragenter', B);
89
- const accepted = !fire(tgt, 'dragover', B); // 页面 preventDefault 了 dragover = 这里能放
90
- fire(tgt, 'drop', B);
91
- fire(src, 'dragend', B);
92
- return { accepted };
87
+ try {
88
+ fire(src, 'dragstart', A);
89
+ fire(tgt, 'dragenter', B);
90
+ const accepted = !fire(tgt, 'dragover', B);
91
+ fire(tgt, 'drop', B);
92
+ return { accepted };
93
+ } finally {
94
+ try { fire(src, 'dragend', B); } catch {}
95
+ }
93
96
  })()`
94
97
 
95
98
  /**
@@ -123,10 +126,14 @@ export async function drag(call, tabId, from, to, { steps = 12, cursor } = {}) {
123
126
  if (cursor) await sleep(Math.min(700, await cur((c) => c.move(a.x, a.y, { label: tt('res.drag.label', { from: describe(from), to: describe(to) }) }))) + 60)
124
127
 
125
128
  if (plan.native) {
126
- await cur((c) => c.down())
127
- await sleep(await cur((c) => c.move(b.x, b.y, { duration: 420, straight: true })))
128
- const r = (await call('eval', { tabId, expression: NATIVE_JS(from, to, a, b) })).value
129
- await cur((c) => c.up())
129
+ let r
130
+ try {
131
+ await cur((c) => c.down())
132
+ await sleep(await cur((c) => c.move(b.x, b.y, { duration: 420, straight: true })))
133
+ r = (await call('eval', { tabId, expression: NATIVE_JS(from, to, a, b) })).value
134
+ } finally {
135
+ await cur((c) => c.up())
136
+ }
130
137
  if (r && r.error) throw new Error(tt('err.dragNoTarget'))
131
138
  return tt('res.drag.doneHtml5', {
132
139
  from: describe(from),
@@ -141,17 +148,28 @@ export async function drag(call, tabId, from, to, { steps = 12, cursor } = {}) {
141
148
  params: { type, x: Math.round(p.x), y: Math.round(p.y), ...extra },
142
149
  })
143
150
  await mouse('mouseMoved', a, { button: 'none', buttons: 0 })
144
- await cur((c) => c.down())
145
- await mouse('mousePressed', a, { button: 'left', buttons: 1, clickCount: 1 })
146
- const n = Math.max(2, Math.min(60, Number(steps) || 12))
147
- await cur((c) => c.move(b.x, b.y, { duration: n * 24, straight: true })) // 光标和真实鼠标一起走
148
- for (let i = 1; i <= n; i++) {
149
- const p = { x: a.x + ((b.x - a.x) * i) / n, y: a.y + ((b.y - a.y) * i) / n }
150
- await mouse('mouseMoved', p, { button: 'left', buttons: 1 })
151
- await sleep(16)
151
+ let point = a
152
+ let moved = false
153
+ try {
154
+ await cur((c) => c.down())
155
+ await mouse('mousePressed', a, { button: 'left', buttons: 1, clickCount: 1 })
156
+ const n = Math.max(2, Math.min(60, Number(steps) || 12))
157
+ await cur((c) => c.move(b.x, b.y, { duration: n * 24, straight: true }))
158
+ for (let i = 1; i <= n; i++) {
159
+ point = { x: a.x + ((b.x - a.x) * i) / n, y: a.y + ((b.y - a.y) * i) / n }
160
+ await mouse('mouseMoved', point, { button: 'left', buttons: 1 })
161
+ await sleep(16)
162
+ }
163
+ moved = true
164
+ } finally {
165
+ try {
166
+ await mouse('mouseReleased', point, { button: 'left', buttons: 0, clickCount: 1 })
167
+ } catch (error) {
168
+ if (moved) throw error
169
+ } finally {
170
+ await cur((c) => c.up())
171
+ }
152
172
  }
153
- await mouse('mouseReleased', b, { button: 'left', buttons: 0, clickCount: 1 })
154
- await cur((c) => c.up())
155
173
  return tt('res.drag.doneCoords', {
156
174
  from: describe(from),
157
175
  to: describe(to),
@@ -0,0 +1,58 @@
1
+ import { tt } from '../i18n/index.js'
2
+
3
+ // Only the explicit legacy dispatcher error means that the extension lacks this op.
4
+ async function frameOp(call, operation, tabId, args = {}) {
5
+ try {
6
+ return await call(operation, { ...args, tabId })
7
+ } catch (error) {
8
+ if (new RegExp('(?:未知操作|unknown (?:operation|op))\\s*[::]\\s*' + operation + '\\b', 'i').test(error.message)) return null
9
+ throw error
10
+ }
11
+ }
12
+
13
+ // Multiples of 10000 are reserved for overflow of the main document's ref space.
14
+ export const isFrameRef = n => Number(n) >= 10000 && Number(n) % 10000 !== 0
15
+
16
+ export async function frameField(call, tabId, operation, args) {
17
+ const ref = Number(args.ref)
18
+ const reply = await frameOp(call, operation, tabId, { ...args, ref })
19
+ if (!reply || reply.gone) throw new Error(tt('err.refGone', { ref }))
20
+ const result = reply.result
21
+ if (typeof result === 'object' || result === 'ok') return result
22
+ const errors = { disabled: 'err.fieldDisabled', wrong: 'err.fieldWrong', noOption: 'err.selectNoOption' }
23
+ throw new Error(tt(errors[result] || 'err.fieldRejected'))
24
+ }
25
+
26
+ export async function mergeFrameSnapshot(call, tabId, v, scope, query) {
27
+ const paths = v.rows.filter(row => row.crossPath).map(row => row.crossPath)
28
+ if (paths.length) {
29
+ const extra = await frameOp(call, 'frameSnapshot', tabId, { paths, scope, query: query.trim().toLowerCase() })
30
+ const byPath = new Map()
31
+ for (const group of extra?.groups || []) {
32
+ const key = group.path.join('.')
33
+ if (!byPath.has(key)) byPath.set(key, [])
34
+ byPath.get(key).push(...group.rows)
35
+ v.count += group.count
36
+ v.outside += group.outside
37
+ v.capped ||= group.capped
38
+ }
39
+ v.rows = v.rows.flatMap(row => byPath.get(row.crossPath?.join('.')) || (row.line ? [row] : []))
40
+ }
41
+ }
42
+
43
+ export async function mergeFrameTexts(call, tabId, rows) {
44
+ const paths = rows.filter(row => row.cross).map(row => row.path)
45
+ if (!paths.length) return rows
46
+ const extra = await frameOp(call, 'frameTexts', tabId, { paths })
47
+ return rows.flatMap(({ path, ...row }) => {
48
+ if (!row.cross) return [row]
49
+ const matches = extra?.groups?.filter(f => f.path.join('.') === path.join('.'))
50
+ return matches?.length ? matches.map(({ src, text }) => ({ src, text })) : [row]
51
+ }).slice(0, 30)
52
+ }
53
+
54
+ export async function locateFrame(call, tabId, ref) {
55
+ const point = await frameOp(call, 'frameLocate', tabId, { ref })
56
+ if (!point || point.gone) throw new Error(tt('err.refGone', { ref }))
57
+ return point
58
+ }
@@ -0,0 +1,203 @@
1
+ import { tt } from '../i18n/index.js'
2
+
3
+ const MIN_CODE_SIZE = 8
4
+ const CLEAR_CODE = 1 << MIN_CODE_SIZE
5
+ const EOI_CODE = CLEAR_CODE + 1
6
+ const TRANSPARENT_INDEX = 252
7
+ const HASH_SIZE = 8192
8
+ const HASH_MASK = HASH_SIZE - 1
9
+
10
+ function buildUniformPalette() {
11
+ const palette = new Uint8Array(256 * 3)
12
+ for (let r = 0; r < 6; r++) {
13
+ for (let g = 0; g < 7; g++) {
14
+ for (let b = 0; b < 6; b++) {
15
+ const index = (r * 42 + g * 6 + b) * 3
16
+ palette[index] = Math.round(r * 255 / 5)
17
+ palette[index + 1] = Math.round(g * 255 / 6)
18
+ palette[index + 2] = Math.round(b * 255 / 5)
19
+ }
20
+ }
21
+ }
22
+ for (const [index, gray] of [[252, 0], [253, 85], [254, 170], [255, 255]]) {
23
+ palette[index * 3] = palette[index * 3 + 1] = palette[index * 3 + 2] = gray
24
+ }
25
+ return palette
26
+ }
27
+
28
+ const PALETTE = buildUniformPalette()
29
+
30
+ function quantize(r, g, b) {
31
+ const ri = Math.min(5, ((r * 5 + 127) / 255) | 0)
32
+ const gi = Math.min(6, ((g * 6 + 127) / 255) | 0)
33
+ const bi = Math.min(5, ((b * 5 + 127) / 255) | 0)
34
+ return ri * 42 + gi * 6 + bi
35
+ }
36
+
37
+ function bytesOf(value) {
38
+ if (value instanceof Uint8Array) return value
39
+ if (typeof value === 'string') return new Uint8Array(Buffer.from(value, 'base64'))
40
+ if (value instanceof ArrayBuffer) return new Uint8Array(value)
41
+ if (value && value.buffer instanceof ArrayBuffer) return new Uint8Array(value.buffer, value.byteOffset || 0, value.byteLength)
42
+ return null
43
+ }
44
+
45
+ function indexedFrame(frame, pixels) {
46
+ const rgba = bytesOf(frame.rgba)
47
+ const rgb = rgba ? null : bytesOf(frame.rgb)
48
+ const out = new Uint8Array(pixels)
49
+ let transparent = false
50
+ if (rgba) {
51
+ if (rgba.length !== pixels * 4) throw new Error(tt('err.gifFrameSize'))
52
+ for (let i = 0, j = 0; j < pixels; i += 4, j++) {
53
+ if (rgba[i + 3] < 128) {
54
+ out[j] = TRANSPARENT_INDEX
55
+ transparent = true
56
+ } else {
57
+ out[j] = quantize(rgba[i], rgba[i + 1], rgba[i + 2])
58
+ }
59
+ }
60
+ } else if (rgb) {
61
+ if (rgb.length !== pixels * 3) throw new Error(tt('err.gifFrameSize'))
62
+ for (let i = 0, j = 0; j < pixels; i += 3, j++) out[j] = quantize(rgb[i], rgb[i + 1], rgb[i + 2])
63
+ } else {
64
+ throw new Error(tt('err.gifFrameSize'))
65
+ }
66
+ return { indices: out, transparent }
67
+ }
68
+
69
+ function hashProbe(keys, values, key) {
70
+ let h = Math.imul(key, 0x9e3779b1) & HASH_MASK
71
+ for (;;) {
72
+ const stored = keys[h]
73
+ if (stored === 0) return { h, found: -1 }
74
+ if (stored === key + 1) return { h, found: values[h] - 1 }
75
+ h = (h + 1) & HASH_MASK
76
+ }
77
+ }
78
+
79
+ function lzwEncode(indices, minCodeSize = MIN_CODE_SIZE) {
80
+ const clear = 1 << minCodeSize
81
+ const eoi = clear + 1
82
+ const keys = new Int32Array(HASH_SIZE)
83
+ const values = new Int32Array(HASH_SIZE)
84
+ const out = []
85
+ let next = eoi + 1
86
+ let codeSize = minCodeSize + 1
87
+ let acc = 0
88
+ let bits = 0
89
+
90
+ const write = (code) => {
91
+ acc |= code << bits
92
+ bits += codeSize
93
+ while (bits >= 8) {
94
+ out.push(acc & 0xff)
95
+ acc >>= 8
96
+ bits -= 8
97
+ }
98
+ }
99
+ const reset = () => {
100
+ keys.fill(0)
101
+ values.fill(0)
102
+ next = eoi + 1
103
+ codeSize = minCodeSize + 1
104
+ }
105
+
106
+ write(clear)
107
+ if (indices.length) {
108
+ let prefix = indices[0]
109
+ for (let i = 1; i < indices.length; i++) {
110
+ const k = indices[i]
111
+ const key = (prefix << 8) | k
112
+ const hit = hashProbe(keys, values, key)
113
+ if (hit.found >= 0) {
114
+ prefix = hit.found
115
+ continue
116
+ }
117
+ write(prefix)
118
+ if (next < 4096) {
119
+ keys[hit.h] = key + 1
120
+ values[hit.h] = next + 1
121
+ next++
122
+ if (next > (1 << codeSize) && codeSize < 12) codeSize++
123
+ } else {
124
+ write(clear)
125
+ reset()
126
+ }
127
+ prefix = k
128
+ }
129
+ write(prefix)
130
+ }
131
+ write(eoi)
132
+ if (bits > 0) out.push(acc & 0xff)
133
+ return Uint8Array.from(out)
134
+ }
135
+
136
+ function pushAscii(parts, text) {
137
+ parts.push(Buffer.from(text, 'ascii'))
138
+ }
139
+
140
+ function pushU16(parts, value) {
141
+ const b = Buffer.allocUnsafe(2)
142
+ b.writeUInt16LE(Math.max(0, Math.min(65535, Math.round(value))), 0)
143
+ parts.push(b)
144
+ }
145
+
146
+ function encodeGif({ width, height, frames, loop = 0 }) {
147
+ width = Math.round(Number(width))
148
+ height = Math.round(Number(height))
149
+ if (!Number.isInteger(width) || !Number.isInteger(height) || width < 1 || height < 1 || width > 65535 || height > 65535) {
150
+ throw new Error(tt('err.gifSize'))
151
+ }
152
+ if (!Array.isArray(frames) || !frames.length) throw new Error(tt('err.gifFrames'))
153
+ const pixels = width * height
154
+ const prepared = frames.map((frame) => indexedFrame(frame || {}, pixels))
155
+ const hasTransparency = prepared.some(f => f.transparent)
156
+
157
+ const parts = []
158
+ pushAscii(parts, 'GIF89a')
159
+ pushU16(parts, width)
160
+ pushU16(parts, height)
161
+ parts.push(Buffer.from([0xf7, 0, 0]))
162
+ parts.push(Buffer.from(PALETTE.buffer, PALETTE.byteOffset, PALETTE.byteLength))
163
+
164
+ parts.push(Buffer.from([0x21, 0xff, 0x0b]))
165
+ pushAscii(parts, 'NETSCAPE2.0')
166
+ parts.push(Buffer.from([0x03, 0x01]))
167
+ pushU16(parts, Math.max(0, Math.min(65535, Math.round(Number(loop) || 0))))
168
+ parts.push(Buffer.from([0]))
169
+
170
+ for (let i = 0; i < frames.length; i++) {
171
+ const delayCs = Math.max(2, Math.min(65535, Math.round(Number(frames[i] && frames[i].delayCs) || 10)))
172
+ parts.push(Buffer.from([0x21, 0xf9, 0x04, hasTransparency ? 0x05 : 0x00]))
173
+ pushU16(parts, delayCs)
174
+ parts.push(Buffer.from([hasTransparency ? TRANSPARENT_INDEX : 0, 0x00]))
175
+
176
+ parts.push(Buffer.from([0x2c]))
177
+ pushU16(parts, 0)
178
+ pushU16(parts, 0)
179
+ pushU16(parts, width)
180
+ pushU16(parts, height)
181
+ parts.push(Buffer.from([0x00, MIN_CODE_SIZE]))
182
+ const compressed = lzwEncode(prepared[i].indices)
183
+ for (let at = 0; at < compressed.length; at += 255) {
184
+ const end = Math.min(at + 255, compressed.length)
185
+ parts.push(Buffer.from([end - at]))
186
+ parts.push(Buffer.from(compressed.buffer, compressed.byteOffset + at, end - at))
187
+ }
188
+ parts.push(Buffer.from([0]))
189
+ }
190
+ parts.push(Buffer.from([0x3b]))
191
+ return Buffer.concat(parts)
192
+ }
193
+
194
+ export {
195
+ encodeGif,
196
+ lzwEncode,
197
+ quantize,
198
+ PALETTE,
199
+ TRANSPARENT_INDEX,
200
+ MIN_CODE_SIZE,
201
+ CLEAR_CODE,
202
+ EOI_CODE,
203
+ }
@@ -0,0 +1 @@
1
+ export {}
@@ -0,0 +1,85 @@
1
+ import { mkdir, open, unlink } from 'node:fs/promises'
2
+ import { t } from '../core/locale.js'
3
+ import { downloadsDir, humanSize, safeName, uniquePath } from '../download.js'
4
+ import { requireExtensionOp } from '../nav.js'
5
+
6
+ async function netOp(call, op, args, timeoutMs) {
7
+ try {
8
+ return await requireExtensionOp(call, op, args, timeoutMs, () => t('err.devtools.extension200'))
9
+ } catch (error) {
10
+ const messages = Object.assign(Object.create(null), {
11
+ MOCK_INVALID: () => t('err.devtools.mockInvalid'),
12
+ MOCK_LIMIT: () => t('err.devtools.mockLimit'),
13
+ HAR_INACTIVE: () => t('err.devtools.harInactive'),
14
+ })
15
+ if (messages[error.message]) throw new Error(messages[error.message](), { cause: error })
16
+ throw error
17
+ }
18
+ }
19
+
20
+ export async function writeHar(dir, filename, har) {
21
+ const base = safeName(String(filename || '').replace(/\.har$/i, '')) || 'network'
22
+ await mkdir(dir, { recursive: true })
23
+ const data = Buffer.from(JSON.stringify(har, null, 2) + '\n')
24
+ for (let i = 0; i < 1000; i++) {
25
+ const file = uniquePath(dir, base + '.har')
26
+ let handle
27
+ try {
28
+ handle = await open(file, 'wx', 0o600)
29
+ } catch (error) {
30
+ if (error.code === 'EEXIST') continue
31
+ throw error
32
+ }
33
+ try {
34
+ if (process.platform !== 'win32') await handle.chmod(0o600)
35
+ await handle.writeFile(data)
36
+ await handle.close()
37
+ return { file, bytes: data.length, count: har.log.entries.length }
38
+ } catch (error) {
39
+ await handle.close().catch(() => {})
40
+ await unlink(file).catch(() => {})
41
+ throw error
42
+ }
43
+ }
44
+ throw new Error(t('err.dlTooManyNames', { dir, name: base + '.har' }))
45
+ }
46
+
47
+ export async function mockHarAction(call, tabId, args, exec) {
48
+ switch (args.action) {
49
+ case 'mock': {
50
+ const { urlPattern, method, status, headers, body, contentType, delayMs, abort } = args
51
+ if (typeof urlPattern !== 'string' || !urlPattern.trim()) throw new Error(t('err.devtools.mockPattern'))
52
+ const result = await netOp(call, 'mockSet', { tabId, urlPattern, method, status, headers, body, contentType, delayMs, abort })
53
+ return t('res.devtools.mockSet', result)
54
+ }
55
+ case 'unmock': {
56
+ const result = await netOp(call, 'mockClear', { tabId, id: args.mockId })
57
+ return t('res.devtools.mockClear', result)
58
+ }
59
+ case 'mocks': {
60
+ const { rules } = await netOp(call, 'mockList', { tabId })
61
+ if (!rules.length) return t('res.devtools.mocksEmpty')
62
+ return [t('res.devtools.mocksCount', { n: rules.length }), ...rules.map(rule =>
63
+ t('res.devtools.mockRule', { ...rule, method: rule.method || '*', seconds: Math.ceil(rule.expiresInMs / 1000) }))].join('\n')
64
+ }
65
+ case 'har_start':
66
+ await netOp(call, 'harStart', { tabId })
67
+ return t('res.devtools.harStart')
68
+ case 'har_export': {
69
+ let dir
70
+ if (args.to === 'workdir') {
71
+ const { sessionCwd } = await import('../core/session.js')
72
+ dir = sessionCwd(exec)
73
+ } else {
74
+ dir = downloadsDir()
75
+ }
76
+ if (!dir) throw new Error(t('err.noWorkdir'))
77
+ const har = await netOp(call, 'harExport', { tabId, includeBodies: !!args.includeBodies, clear: !!args.clear }, 75_000)
78
+ if (har?.log?.version !== '1.2' || !Array.isArray(har.log.entries)) throw new Error(t('err.devtools.harInvalid'))
79
+ const { count, bytes, file } = await writeHar(dir, args.filename, har)
80
+ return t('res.devtools.harSaved', { count, size: humanSize(bytes), file })
81
+ }
82
+ default:
83
+ throw new Error(t('err.unknownAction', { action: args.action }))
84
+ }
85
+ }
@@ -0,0 +1,225 @@
1
+ import { execFileSync } from 'node:child_process'
2
+ import crypto from 'node:crypto'
3
+ import fs from 'node:fs'
4
+ import path from 'node:path'
5
+ import { shotRefs } from '../core/shots.js'
6
+ import { safeName, uniquePath } from '../download.js'
7
+ import { tt } from '../i18n/index.js'
8
+ import { encodeGif } from './gif.js'
9
+
10
+ const { O_WRONLY, O_CREAT, O_EXCL, O_NOFOLLOW } = fs.constants
11
+ const NOFOLLOW = O_NOFOLLOW || 0
12
+
13
+ function stamp(date = new Date()) {
14
+ const p = (n) => String(n).padStart(2, '0')
15
+ return `${date.getFullYear()}${p(date.getMonth() + 1)}${p(date.getDate())}-${p(date.getHours())}${p(date.getMinutes())}${p(date.getSeconds())}`
16
+ }
17
+
18
+ export function mediaName(filename, format) {
19
+ const ext = `.${format}`
20
+ let name = safeName(filename) || `browser-recording-${stamp()}`
21
+ if (name.toLowerCase().endsWith(ext)) return name
22
+ if (/\.(?:gif|mp4|webm)$/i.test(name)) name = name.replace(/\.(?:gif|mp4|webm)$/i, '')
23
+ else if (!/\.[a-z0-9]{1,12}$/i.test(name)) return `${name}${ext}`
24
+ return `${name}${ext}`
25
+ }
26
+
27
+ function writeExclusive(dir, name, data) {
28
+ for (let i = 0; i < 1000; i++) {
29
+ const candidate = uniquePath(dir, name)
30
+ let fd
31
+ try {
32
+ fd = fs.openSync(candidate, O_WRONLY | O_CREAT | O_EXCL | NOFOLLOW, 0o600)
33
+ } catch (error) {
34
+ if (error && error.code === 'EEXIST') continue
35
+ throw error
36
+ }
37
+ try {
38
+ fs.writeFileSync(fd, data)
39
+ return candidate
40
+ } catch (error) {
41
+ try { fs.unlinkSync(candidate) } catch {}
42
+ throw error
43
+ } finally {
44
+ try { fs.closeSync(fd) } catch {}
45
+ }
46
+ }
47
+ throw new Error(tt('err.recordName'))
48
+ }
49
+
50
+ export function frameDelays(frames, fps = 3, durationMs = 0) {
51
+ const list = Array.isArray(frames) ? frames : []
52
+ const nominal = 1000 / Math.max(1, Number(fps) || 3)
53
+ return list.map((frame, index) => {
54
+ const at = Number(frame.atMs) || 0
55
+ let ms
56
+ if (index + 1 < list.length) ms = (Number(list[index + 1].atMs) || 0) - at
57
+ else ms = Math.max(Number(durationMs) - at, nominal)
58
+ if (!Number.isFinite(ms) || ms <= 0) ms = nominal
59
+ return Math.max(2, Math.min(65535, Math.round(ms / 10)))
60
+ })
61
+ }
62
+
63
+ export function encodeRecordingGif(result, fps = 3) {
64
+ const width = Math.round(Number(result && result.width))
65
+ const height = Math.round(Number(result && result.height))
66
+ const frames = Array.isArray(result && result.frames) ? result.frames : []
67
+ if (!frames.length) throw new Error(tt('err.recordEmpty'))
68
+ if (!width || !height) throw new Error(tt('err.recordPixels'))
69
+ const delays = frameDelays(frames, fps, result.durationMs)
70
+ const gifFrames = frames.map((frame, index) => {
71
+ if (!frame.rgb && !frame.rgba) throw new Error(tt('err.recordPixels'))
72
+ return { ...(frame.rgb ? { rgb: frame.rgb } : { rgba: frame.rgba }), delayCs: delays[index] }
73
+ })
74
+ return encodeGif({ width, height, frames: gifFrames, loop: 0 })
75
+ }
76
+
77
+ export function ffmpegAvailable(run = execFileSync) {
78
+ try {
79
+ run('ffmpeg', ['-version'], { stdio: 'ignore', timeout: 5000, windowsHide: true })
80
+ return true
81
+ } catch {
82
+ return false
83
+ }
84
+ }
85
+
86
+ function inputRate(result, fps) {
87
+ const frames = Array.isArray(result.frames) ? result.frames.length : 0
88
+ const seconds = Number(result.durationMs) / 1000
89
+ if (!frames || !Number.isFinite(seconds) || seconds <= 0) return Math.max(1, Number(fps) || 3)
90
+ return Math.max(1, Math.min(30, frames / seconds))
91
+ }
92
+
93
+ function copyExclusive(source, dest) {
94
+ const out = fs.openSync(dest, O_WRONLY | O_CREAT | O_EXCL | NOFOLLOW, 0o600)
95
+ let input
96
+ try {
97
+ input = fs.openSync(source, fs.constants.O_RDONLY)
98
+ const buf = Buffer.allocUnsafe(1024 * 1024)
99
+ for (;;) {
100
+ const n = fs.readSync(input, buf, 0, buf.length, null)
101
+ if (!n) break
102
+ let off = 0
103
+ while (off < n) off += fs.writeSync(out, buf, off, n - off)
104
+ }
105
+ return dest
106
+ } catch (error) {
107
+ try { fs.unlinkSync(dest) } catch {}
108
+ throw error
109
+ } finally {
110
+ try { if (input !== undefined) fs.closeSync(input) } catch {}
111
+ try { fs.closeSync(out) } catch {}
112
+ }
113
+ }
114
+
115
+ function publishExclusive(temp, dir, name) {
116
+ const ext = path.extname(name)
117
+ const base = name.slice(0, name.length - ext.length)
118
+ for (let i = 0; i < 1000; i++) {
119
+ const file = path.join(dir, i ? `${base} (${i})${ext}` : name)
120
+ try {
121
+ fs.linkSync(temp, file)
122
+ return file
123
+ } catch (error) {
124
+ if (!error || error.code === 'EEXIST') continue
125
+ if (!['EXDEV', 'ENOTSUP', 'EPERM'].includes(error.code)) throw error
126
+ try {
127
+ copyExclusive(temp, file)
128
+ return file
129
+ } catch (copyError) {
130
+ if (!copyError || copyError.code !== 'EEXIST') throw copyError
131
+ }
132
+ }
133
+ }
134
+ throw new Error(tt('err.recordName'))
135
+ }
136
+
137
+ function encodeVideo(result, { dir, filename, format, fps, run }) {
138
+ const frames = Array.isArray(result.frames) ? result.frames : []
139
+ if (!frames.length) throw new Error(tt('err.recordEmpty'))
140
+ const input = Buffer.concat(frames.map(frame => Buffer.from(frame.jpeg || '', 'base64')))
141
+ if (!input.length) throw new Error(tt('err.recordEmpty'))
142
+ const name = mediaName(filename, format)
143
+ const temp = path.join(dir, `.dsh-record-${crypto.randomUUID()}.${format}`)
144
+ const rate = inputRate(result, fps).toFixed(3).replace(/\.0+$/, '').replace(/(\.\d*?)0+$/, '$1')
145
+ const video = format === 'mp4'
146
+ ? ['-c:v', 'libx264', '-pix_fmt', 'yuv420p', '-vf', 'scale=trunc(iw/2)*2:trunc(ih/2)*2', '-movflags', '+faststart']
147
+ : ['-c:v', 'libvpx-vp9', '-pix_fmt', 'yuv420p', '-deadline', 'realtime', '-cpu-used', '5', '-b:v', '0', '-crf', '34']
148
+ const args = [
149
+ '-hide_banner', '-loglevel', 'error', '-y',
150
+ '-f', 'image2pipe', '-c:v', 'mjpeg', '-framerate', rate, '-i', 'pipe:0',
151
+ '-frames:v', String(frames.length), '-an', ...video, temp,
152
+ ]
153
+ try {
154
+ run('ffmpeg', args, { input, stdio: ['pipe', 'ignore', 'pipe'], timeout: 120000, windowsHide: true, maxBuffer: 1024 * 1024 })
155
+ fs.chmodSync(temp, 0o600)
156
+ return publishExclusive(temp, dir, name)
157
+ } finally {
158
+ try { fs.unlinkSync(temp) } catch {}
159
+ }
160
+ }
161
+
162
+ function saveGif(result, { dir, filename, fps }) {
163
+ const gif = encodeRecordingGif(result, fps)
164
+ return writeExclusive(dir, mediaName(filename, 'gif'), gif)
165
+ }
166
+
167
+ export async function saveRecording(result, {
168
+ format = 'gif',
169
+ fps = 3,
170
+ dir,
171
+ filename,
172
+ run = execFileSync,
173
+ } = {}) {
174
+ if (!dir || !path.isAbsolute(dir)) throw new Error(tt('err.recordDir'))
175
+ const requested = format === 'mp4' || format === 'webm' ? format : 'gif'
176
+ let file
177
+ let actual = requested
178
+ let fallback = ''
179
+ if (requested === 'gif') {
180
+ file = saveGif(result, { dir, filename, fps })
181
+ } else if (!ffmpegAvailable(run)) {
182
+ fallback = 'missing'
183
+ actual = 'gif'
184
+ file = saveGif(result, { dir, filename, fps })
185
+ } else {
186
+ try {
187
+ file = encodeVideo(result, { dir, filename, format: requested, fps, run })
188
+ } catch {
189
+ fallback = 'failed'
190
+ actual = 'gif'
191
+ file = saveGif(result, { dir, filename, fps })
192
+ }
193
+ }
194
+ const size = fs.statSync(file).size
195
+ return {
196
+ file,
197
+ size,
198
+ format: actual,
199
+ requestedFormat: requested,
200
+ fallback,
201
+ count: Math.round(Number(result.count) || (result.frames || []).length || 0),
202
+ durationMs: Math.round(Number(result.durationMs) || 0),
203
+ width: Math.round(Number(result.width) || 0),
204
+ height: Math.round(Number(result.height) || 0),
205
+ }
206
+ }
207
+
208
+ export async function saveContactPreview(contactSheet, getAttachments) {
209
+ if (!contactSheet || !contactSheet.data || typeof getAttachments !== 'function') return ''
210
+ const attachments = getAttachments()
211
+ if (!attachments || typeof attachments.saveImages !== 'function') return ''
212
+ try {
213
+ const [ref] = await attachments.saveImages([{
214
+ data: Buffer.from(contactSheet.data, 'base64'),
215
+ mediaType: 'image/jpeg',
216
+ name: `recording-contact-${Date.now()}.jpg`,
217
+ }])
218
+ const token = crypto.randomUUID()
219
+ shotRefs.set(token, ref)
220
+ if (shotRefs.size > 20) shotRefs.delete(shotRefs.keys().next().value)
221
+ return token
222
+ } catch {
223
+ return ''
224
+ }
225
+ }