dsh-builtin-browser 0.5.6 → 0.5.7

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 (63) hide show
  1. package/CHANGELOG.md +82 -0
  2. package/README.en.md +67 -99
  3. package/README.md +67 -100
  4. package/client.js +381 -322
  5. package/desktop-bridge/install.mjs +122 -33
  6. package/desktop-bridge/plugin-browser-bridge.js +9 -4
  7. package/docs/tool-reference.md +20 -1
  8. package/lib/browser/runtime.d.ts +3 -1
  9. package/lib/browser/runtime.js +9 -0
  10. package/lib/browser/types.d.ts +42 -0
  11. package/lib/browser-electron/authenticated-route.d.ts +27 -0
  12. package/lib/browser-electron/authenticated-route.js +39 -0
  13. package/lib/browser-electron/bridge-endpoint.js +7 -0
  14. package/lib/browser-electron/bridge-install.d.ts +48 -0
  15. package/lib/browser-electron/bridge-install.js +98 -0
  16. package/lib/browser-electron/bridge-status.js +21 -2
  17. package/lib/browser-electron/desktop-bridge-host.d.ts +7 -4
  18. package/lib/browser-electron/desktop-bridge-host.js +36 -15
  19. package/lib/browser-electron/electron-provision.d.ts +1 -1
  20. package/lib/browser-electron/electron-provision.js +31 -11
  21. package/lib/browser-electron/entry.js +84 -8
  22. package/lib/browser-electron/host-main.js +48 -27
  23. package/lib/browser-electron/provider.d.ts +9 -2
  24. package/lib/browser-electron/provider.js +76 -6
  25. package/lib/browser-electron/remote-host.js +4 -4
  26. package/lib/browser-electron/runtime-route.d.ts +3 -5
  27. package/lib/browser-electron/runtime-status.js +4 -2
  28. package/lib/browser-electron/settings-route.d.ts +5 -18
  29. package/lib/browser-electron/settings-route.js +4 -14
  30. package/lib/browser-electron/settings-store.d.ts +17 -0
  31. package/lib/browser-electron/settings-store.js +24 -0
  32. package/lib/browser-electron/system-browser.d.ts +5 -2
  33. package/lib/browser-electron/system-browser.js +12 -4
  34. package/lib/tool-browser/index.js +1041 -4
  35. package/lib/tool-browser/page-probe.d.ts +86 -0
  36. package/lib/tool-browser/page-probe.js +460 -0
  37. package/package.json +4 -2
  38. package/scripts/verify-runtime-status.mjs +14 -0
  39. package/skills/dsh-builtin-browser/SKILL.md +64 -0
  40. package/skills/dsh-builtin-browser/references/batch.md +23 -0
  41. package/skills/dsh-builtin-browser/references/deliver.md +31 -0
  42. package/skills/dsh-builtin-browser/references/locate.md +11 -0
  43. package/skills/dsh-builtin-browser/references/recover.md +11 -0
  44. package/skills/dsh-builtin-browser/references/verify.md +13 -0
  45. package/src/browser/runtime.ts +11 -0
  46. package/src/browser/types.ts +19 -0
  47. package/src/browser-electron/authenticated-route.ts +56 -0
  48. package/src/browser-electron/bridge-endpoint.ts +7 -0
  49. package/src/browser-electron/bridge-install.ts +122 -0
  50. package/src/browser-electron/bridge-status.ts +22 -2
  51. package/src/browser-electron/desktop-bridge-host.ts +33 -15
  52. package/src/browser-electron/electron-provision.ts +30 -12
  53. package/src/browser-electron/entry.ts +76 -8
  54. package/src/browser-electron/host-main.ts +41 -22
  55. package/src/browser-electron/provider.ts +90 -6
  56. package/src/browser-electron/remote-host.ts +4 -4
  57. package/src/browser-electron/runtime-route.ts +3 -5
  58. package/src/browser-electron/runtime-status.ts +4 -2
  59. package/src/browser-electron/settings-route.ts +9 -32
  60. package/src/browser-electron/settings-store.ts +39 -0
  61. package/src/browser-electron/system-browser.ts +9 -3
  62. package/src/tool-browser/index.ts +991 -7
  63. package/src/tool-browser/page-probe.ts +474 -0
@@ -0,0 +1,474 @@
1
+ /**
2
+ * The page-side probe: one script that makes a page observable without touching the host.
3
+ *
4
+ * WHY THIS EXISTS
5
+ * Three capabilities the model needs are not tools here yet: what the console said, which network
6
+ * responses arrived, and what happened to a JavaScript dialog. All three live *inside* the page, and
7
+ * a dialog blocks the page until someone answers it — which is why a `confirm()` used to hang a whole
8
+ * tool call with no explanation.
9
+ *
10
+ * The obvious implementation is CDP event capture (`Runtime.consoleAPICalled`, `Network.*`,
11
+ * `Page.javascriptDialogOpening`) inside the host. That would mean a new capability in all three
12
+ * carriers — the self-hosted child, the driven Chrome and the sidebar bridge — plus a protocol
13
+ * version for the bridge. This probe instead installs itself with the `execute` path every carrier
14
+ * already has, so it works everywhere on day one and cannot drift per carrier.
15
+ *
16
+ * What it costs, stated plainly:
17
+ * - `console` and `network` see what the PAGE can see. A response that never reached `fetch`/`XHR`
18
+ * (a document navigation, an `<img>` failure the browser handled internally) appears only as a
19
+ * resource-timing entry, with no status code. CDP would know more.
20
+ * - Dialog capture works by replacing `window.alert/confirm/prompt` BEFORE they are called. A dialog
21
+ * produced by the browser itself (`beforeunload`, HTTP auth, permission prompts) is not covered.
22
+ * - It is an override, so a page that captured `window.fetch` earlier keeps its own copy. Installed
23
+ * at first use, which is early enough for every ordinary page and honest about the rest.
24
+ *
25
+ * Idempotent by version: installing twice keeps the buffers that already exist.
26
+ * @module dsh-browser/tool-browser/page-probe
27
+ */
28
+
29
+ import type { BrowserPageOperationRequest, BrowserProbeMethod } from '../browser/types.js'
30
+
31
+ /** Bumped when the probe's shape changes; an older probe is replaced rather than trusted. */
32
+ export const PROBE_VERSION = 4
33
+
34
+ /** Where the probe keeps itself, and the only global it adds. */
35
+ const PROBE_KEY = '__dshProbe'
36
+
37
+ /**
38
+ * The installer, as one expression that returns the installed version.
39
+ *
40
+ * Written as a string because it runs in the page, not here. Keep it dependency-free and ES5-safe:
41
+ * a page may be older than the harness.
42
+ */
43
+ export const PROBE_INSTALL_SCRIPT = `(() => {
44
+ const KEY = ${JSON.stringify(PROBE_KEY)}
45
+ const VERSION = ${PROBE_VERSION}
46
+ const previous = globalThis[KEY]
47
+ if (previous && previous.version === VERSION) return VERSION
48
+ if (previous) {
49
+ if (typeof previous.dispose !== 'function') throw new Error('reload this page to replace the older browser probe')
50
+ previous.dispose()
51
+ }
52
+ const restore = []
53
+ const replace = (target, key, value) => {
54
+ const original = target[key]
55
+ target[key] = value
56
+ restore.push(() => { if (target[key] === value) target[key] = original })
57
+ }
58
+
59
+ const state = {
60
+ version: VERSION,
61
+ startedAt: Date.now(),
62
+ console: [],
63
+ network: [],
64
+ dialogs: [],
65
+ dialogPolicy: 'native',
66
+ networkSequence: 0,
67
+ pending: 0,
68
+ lastNetworkAt: Date.now(),
69
+ lastMutationAt: Date.now(),
70
+ }
71
+ const cap = (list, item, limit) => { list.push(item); if (list.length > limit) list.splice(0, list.length - limit) }
72
+ const asText = (value) => {
73
+ try { return typeof value === 'string' ? value : JSON.stringify(value) } catch (error) { return String(value) }
74
+ }
75
+ const short = (value, limit) => { const text = String(value == null ? '' : value); return text.length > limit ? text.slice(0, limit) + '…' : text }
76
+
77
+ for (const level of ['log', 'info', 'warn', 'error', 'debug']) {
78
+ const original = console[level]
79
+ if (typeof original !== 'function') continue
80
+ replace(console, level, function () {
81
+ const parts = []
82
+ for (let i = 0; i < arguments.length; i += 1) parts.push(asText(arguments[i]))
83
+ cap(state.console, { at: Date.now(), level: level, text: short(parts.join(' '), 500) }, 200)
84
+ return original.apply(this, arguments)
85
+ })
86
+ }
87
+
88
+ const note = (entry) => { state.lastNetworkAt = Date.now(); entry.receivedAt = state.lastNetworkAt; entry.sequence = ++state.networkSequence; cap(state.network, entry, 300) }
89
+ const nativeFetch = globalThis.fetch
90
+ if (typeof nativeFetch === 'function') {
91
+ replace(globalThis, 'fetch', function (input, init) {
92
+ const url = typeof input === 'string' ? input : (input && input.url) || String(input)
93
+ const method = String((init && init.method) || (input && input.method) || 'GET').toUpperCase()
94
+ const started = Date.now()
95
+ state.pending += 1
96
+ const settle = (status) => {
97
+ state.pending = Math.max(0, state.pending - 1)
98
+ note({ at: started, kind: 'fetch', method: method, url: short(url, 300), status: status, ms: Date.now() - started })
99
+ }
100
+ return nativeFetch.apply(this, arguments).then(
101
+ (response) => { settle(response.status); return response },
102
+ (error) => { settle(0); throw error },
103
+ )
104
+ })
105
+ }
106
+
107
+ const XHR = globalThis.XMLHttpRequest
108
+ if (XHR && XHR.prototype && typeof XHR.prototype.send === 'function') {
109
+ const open = XHR.prototype.open
110
+ const send = XHR.prototype.send
111
+ replace(XHR.prototype, 'open', function (method, url) {
112
+ this.__dshNetwork = { method: String(method || 'GET').toUpperCase(), url: String(url || ''), at: Date.now() }
113
+ return open.apply(this, arguments)
114
+ })
115
+ replace(XHR.prototype, 'send', function () {
116
+ const meta = this.__dshNetwork || { method: 'GET', url: '', at: Date.now() }
117
+ state.pending += 1
118
+ const done = () => {
119
+ state.pending = Math.max(0, state.pending - 1)
120
+ note({ at: meta.at, kind: 'xhr', method: meta.method, url: short(meta.url, 300), status: this.status || 0, ms: Date.now() - meta.at })
121
+ this.removeEventListener('loadend', done)
122
+ }
123
+ this.addEventListener('loadend', done)
124
+ return send.apply(this, arguments)
125
+ })
126
+ }
127
+
128
+ if (typeof PerformanceObserver === 'function') {
129
+ try {
130
+ const seen = new Set()
131
+ const observer = new PerformanceObserver((list) => {
132
+ const entries = list.getEntries()
133
+ for (let i = 0; i < entries.length; i += 1) {
134
+ const entry = entries[i]
135
+ const key = entry.name + '|' + entry.startTime
136
+ if (seen.has(key)) continue
137
+ seen.add(key)
138
+ note({ at: Math.round((performance.timeOrigin || Date.now()) + entry.startTime), kind: 'resource', method: 'GET', url: short(entry.name, 300), status: 0, ms: Math.round(entry.duration), bytes: entry.transferSize || 0 })
139
+ }
140
+ })
141
+ observer.observe({ type: 'resource', buffered: true })
142
+ restore.push(() => observer.disconnect())
143
+ } catch (error) { /* a page with no resource timing still has fetch and XHR */ }
144
+ }
145
+
146
+ const nativeDialogs = {}
147
+ const dialogWrappers = {}
148
+ for (const kind of ['alert', 'confirm', 'prompt']) {
149
+ const original = globalThis[kind]
150
+ if (typeof original !== 'function') continue
151
+ nativeDialogs[kind] = original
152
+ const wrapper = function (message, value) {
153
+ const accept = state.dialogPolicy === 'accept'
154
+ cap(state.dialogs, { at: Date.now(), kind: kind, message: short(message, 300), policy: state.dialogPolicy, answered: accept ? 'accepted' : 'dismissed' }, 50)
155
+ if (!accept) return kind === 'confirm' ? false : kind === 'prompt' ? null : undefined
156
+ return kind === 'prompt' ? String(value == null ? '' : value) : kind === 'confirm' ? true : undefined
157
+ }
158
+ dialogWrappers[kind] = wrapper
159
+ restore.push(() => { if (globalThis[kind] === wrapper) globalThis[kind] = nativeDialogs[kind] })
160
+ }
161
+
162
+ try {
163
+ const observer = new MutationObserver(() => { state.lastMutationAt = Date.now() })
164
+ observer.observe(document.documentElement || document, { subtree: true, childList: true, attributes: true })
165
+ restore.push(() => observer.disconnect())
166
+ } catch (error) { /* no observer: quiet time falls back to network only */ }
167
+
168
+ const describe = (node) => {
169
+ if (!node || !node.tagName) return 'unknown'
170
+ const name = (node.getAttribute && (node.getAttribute('aria-label') || node.getAttribute('name'))) || ''
171
+ const text = short((node.innerText || '').trim().replace(/\\s+/g, ' '), 60)
172
+ return node.tagName.toLowerCase() + (name ? '[' + name + ']' : '') + (text ? ' "' + text + '"' : '')
173
+ }
174
+
175
+ state.settle = function () {
176
+ const quietFrom = Math.max(state.lastNetworkAt, state.lastMutationAt)
177
+ return { pending: state.pending, quietMs: Date.now() - quietFrom, readyState: String(document.readyState) }
178
+ }
179
+
180
+ state.find = function (target, scroll) {
181
+ if (!target) return null
182
+ let node = null
183
+ try {
184
+ if (target.css) node = document.querySelector(String(target.css))
185
+ else if (target.xpath) node = document.evaluate(String(target.xpath), document, null, 9, null).singleNodeValue
186
+ else if (target.text) {
187
+ const wanted = String(target.text).trim().toLowerCase()
188
+ const nodes = document.querySelectorAll('button, a, [role=button], input, label, [role=tab], [role=option], [role=link]')
189
+ for (let i = 0; i < nodes.length; i += 1) {
190
+ const value = ((nodes[i].innerText || nodes[i].getAttribute('aria-label') || nodes[i].value || '') + '').trim().toLowerCase()
191
+ if (value && value.indexOf(wanted) !== -1) { node = nodes[i]; break }
192
+ }
193
+ }
194
+ } catch (error) { return null }
195
+ if (!node) return null
196
+ if (scroll === true && typeof node.scrollIntoView === 'function') node.scrollIntoView({ block: 'center', inline: 'center', behavior: 'instant' })
197
+ const rect = node.getBoundingClientRect()
198
+ return { x: Math.round(rect.left + rect.width / 2), y: Math.round(rect.top + rect.height / 2), w: Math.round(rect.width), h: Math.round(rect.height), described: describe(node) }
199
+ }
200
+
201
+ const DISMISS = /(accept|agree|allow|continue|close|got it|dismiss|ok|agree|同意|接受|允许|继续|关闭|知道了|我知道了|我同意)/i
202
+
203
+ state.overlayAt = function (x, y) {
204
+ const top = document.elementFromPoint(Number(x), Number(y))
205
+ if (!top) return { covers: null, dismiss: null }
206
+ let node = top
207
+ let depth = 0
208
+ while (node && depth < 8) {
209
+ let style = null
210
+ try { style = getComputedStyle(node) } catch (error) { style = null }
211
+ const floating = style && (style.position === 'fixed' || style.position === 'sticky' || Number(style.zIndex) >= 100)
212
+ if (floating) {
213
+ const buttons = node.querySelectorAll('button, [role=button], a')
214
+ for (let i = 0; i < buttons.length && i < 60; i += 1) {
215
+ const label = ((buttons[i].innerText || '') + ' ' + (buttons[i].getAttribute('aria-label') || '')).trim()
216
+ if (DISMISS.test(label)) {
217
+ const rect = buttons[i].getBoundingClientRect()
218
+ return { covers: describe(top), dismiss: { label: short(label, 40), x: Math.round(rect.left + rect.width / 2), y: Math.round(rect.top + rect.height / 2) } }
219
+ }
220
+ }
221
+ return { covers: describe(top), dismiss: null }
222
+ }
223
+ node = node.parentElement
224
+ depth += 1
225
+ }
226
+ return { covers: describe(top), dismiss: null }
227
+ }
228
+
229
+ state.read = function (kind, filter, limit) {
230
+ const list = kind === 'console' ? state.console : kind === 'network' ? state.network : state.dialogs
231
+ const needle = filter ? String(filter).toLowerCase() : ''
232
+ const rows = needle === '' ? list : list.filter((row) => ((row.url || '') + ' ' + (row.text || '') + ' ' + (row.message || '')).toLowerCase().indexOf(needle) !== -1)
233
+ const max = Math.max(0, Math.min(Number(limit) || 20, 100))
234
+ return rows.slice(Math.max(0, rows.length - max))
235
+ }
236
+
237
+ state.clear = function (kind) {
238
+ if (kind === 'console') state.console.length = 0
239
+ else if (kind === 'network') state.network.length = 0
240
+ else if (kind === 'dialogs') state.dialogs.length = 0
241
+ return true
242
+ }
243
+
244
+ state.setDialogPolicy = function (policy) {
245
+ if (policy !== 'native' && policy !== 'accept' && policy !== 'dismiss') return state.dialogPolicy
246
+ const previousPolicy = state.dialogPolicy
247
+ state.dialogPolicy = policy
248
+ for (const kind of Object.keys(nativeDialogs)) {
249
+ if (policy === 'native') {
250
+ if (globalThis[kind] === dialogWrappers[kind]) globalThis[kind] = nativeDialogs[kind]
251
+ } else {
252
+ if (previousPolicy === 'native' && globalThis[kind] !== dialogWrappers[kind]) nativeDialogs[kind] = globalThis[kind]
253
+ globalThis[kind] = dialogWrappers[kind]
254
+ }
255
+ }
256
+ return state.dialogPolicy
257
+ }
258
+
259
+ state.dialogStatus = function () { return state.dialogPolicy }
260
+ state.networkCursor = function () { return { startedAt: state.startedAt, sequence: state.networkSequence } }
261
+ state.dispose = function () {
262
+ for (const undo of restore.reverse()) { try { undo() } catch (error) {} }
263
+ if (globalThis[KEY] === state) delete globalThis[KEY]
264
+ }
265
+
266
+ state.findText = function (text, all) {
267
+ const needle = String(text || '')
268
+ const out = []
269
+ if (needle === '') return out
270
+ const wanted = needle.toLowerCase()
271
+ const root = document.body || document.documentElement
272
+ if (!root || typeof document.createTreeWalker !== 'function') return out
273
+ const walker = document.createTreeWalker(root, 4, null) // 4 = SHOW_TEXT
274
+ let node = walker.nextNode()
275
+ while (node) {
276
+ const value = node.nodeValue || ''
277
+ let at = value.toLowerCase().indexOf(wanted)
278
+ while (at !== -1) {
279
+ const range = document.createRange()
280
+ range.setStart(node, at)
281
+ range.setEnd(node, at + needle.length)
282
+ const rect = range.getBoundingClientRect()
283
+ out.push({
284
+ text: short(value.slice(Math.max(0, at - 20), at + needle.length + 20).replace(/\s+/g, ' ').trim(), 80),
285
+ x: Math.round(rect.left + rect.width / 2),
286
+ y: Math.round(rect.top + rect.height / 2),
287
+ host: node.parentElement ? describe(node.parentElement) : 'text',
288
+ })
289
+ if (out.length >= (all ? 50 : 5)) return out
290
+ at = value.toLowerCase().indexOf(wanted, at + 1)
291
+ }
292
+ node = walker.nextNode()
293
+ }
294
+ return out
295
+ }
296
+
297
+ const hoverEvent = (type, node, x, y) => {
298
+ const init = { bubbles: type.indexOf('enter') === -1, cancelable: true, composed: true, clientX: x, clientY: y, button: 0, buttons: 0 }
299
+ try {
300
+ if (type.indexOf('pointer') === 0 && typeof PointerEvent === 'function') return new PointerEvent(type, Object.assign({ pointerId: 1, pointerType: 'mouse', isPrimary: true }, init))
301
+ if (typeof MouseEvent === 'function') return new MouseEvent(type.replace('pointer', 'mouse'), init)
302
+ } catch (error) { return null }
303
+ return null
304
+ }
305
+
306
+ state.hoverAt = function (x, y) {
307
+ const node = document.elementFromPoint(Number(x), Number(y))
308
+ if (!node) return false
309
+ const types = ['pointerover', 'pointerenter', 'mouseover', 'mouseenter', 'mousemove']
310
+ let fired = 0
311
+ for (let i = 0; i < types.length; i += 1) {
312
+ const event = hoverEvent(types[i], node, Number(x), Number(y))
313
+ if (event && typeof node.dispatchEvent === 'function') { node.dispatchEvent(event); fired += 1 }
314
+ }
315
+ return fired > 0
316
+ }
317
+
318
+ state.summary = function () {
319
+ const body = document.body ? document.body.innerText : ''
320
+ const query = (selector) => { try { return document.querySelectorAll(selector).length } catch (error) { return 0 } }
321
+ const settled = state.settle()
322
+ return {
323
+ url: String(location.href),
324
+ title: String(document.title || ''),
325
+ readyState: settled.readyState,
326
+ pending: settled.pending,
327
+ quietMs: settled.quietMs,
328
+ inputs: query('input, textarea, select'),
329
+ buttons: query('button, [role=button]'),
330
+ links: query('a[href]'),
331
+ scrollX: Math.round(globalThis.scrollX || 0),
332
+ scrollY: Math.round(globalThis.scrollY || 0),
333
+ selection: short(globalThis.getSelection ? String(globalThis.getSelection()) : '', 120),
334
+ text: short(String(body || '').replace(/\s+/g, ' ').trim(), 400),
335
+ }
336
+ }
337
+ globalThis[KEY] = state
338
+ return VERSION
339
+ })()`
340
+
341
+ /**
342
+ * One probe call, evaluated in the page, with its result serialised as JSON.
343
+ *
344
+ * JSON in, JSON out, because that is the only shape every carrier's `execute` can carry reliably.
345
+ * @param method - the probe function to call (`read`, `settle`, `find`, `overlayAt`, `clear`, …).
346
+ * @param args - arguments, already JSON-serialisable.
347
+ * @returns a script whose value is the JSON text of the result (or an error object).
348
+ */
349
+ export function probeCallScript(method: string, args: readonly unknown[] = []): string {
350
+ return `(() => {
351
+ const probe = globalThis[${JSON.stringify(PROBE_KEY)}]
352
+ if (!probe) return JSON.stringify({ error: 'probe-not-installed' })
353
+ if (typeof probe[${JSON.stringify(method)}] !== 'function') return JSON.stringify({ error: 'probe-method-missing' })
354
+ try { return JSON.stringify(probe[${JSON.stringify(method)}].apply(probe, ${JSON.stringify(args)})) } catch (error) { return JSON.stringify({ error: String(error) }) }
355
+ })()`
356
+ }
357
+
358
+ /**
359
+ * Dispatch a pointer drag in the page, for elements that accept synthetic pointer events.
360
+ *
361
+ * Uses `PointerEvent` when the page has it and `MouseEvent` otherwise, because a canvas app that
362
+ * listens for `mousedown` never sees a pointer event. This is a page-level gesture: a page that
363
+ * demands trusted input (some canvas editors) ignores it, exactly like `click_sequence`'s
364
+ * coordinate clicks are the trusted counterpart.
365
+ * @param from - start point in viewport CSS pixels.
366
+ * @param to - end point.
367
+ * @param steps - intermediate moves; more steps make a slider or a canvas app follow the path.
368
+ * @returns a script value: `{ ok: true, moved, at }` or `{ ok: false, reason }`.
369
+ */
370
+ export function dragScript(
371
+ from: { readonly x: number; readonly y: number },
372
+ to: { readonly x: number; readonly y: number },
373
+ steps = 12,
374
+ ): string {
375
+ const points = JSON.stringify({ from, to, steps })
376
+ return `(() => {
377
+ const spec = ${points}
378
+ const at = (x, y) => document.elementFromPoint(x, y)
379
+ const start = at(spec.from.x, spec.from.y)
380
+ if (!start) return JSON.stringify({ ok: false, reason: 'nothing at the start point' })
381
+ const make = (type, x, y, extra) => {
382
+ const init = Object.assign({ bubbles: true, cancelable: true, composed: true, clientX: x, clientY: y, button: 0, buttons: type === 'pointerup' || type === 'mouseup' ? 0 : 1 }, extra || {})
383
+ try {
384
+ if (type.indexOf('pointer') === 0 && typeof PointerEvent === 'function') return new PointerEvent(type, Object.assign({ pointerId: 1, pointerType: 'mouse', isPrimary: true }, init))
385
+ if (typeof MouseEvent === 'function') return new MouseEvent(type.replace('pointer', 'mouse'), init)
386
+ } catch (error) { /* fall through to the null below */ }
387
+ return null
388
+ }
389
+ const fire = (node, type, x, y, extra) => {
390
+ const event = make(type, x, y, extra)
391
+ if (event !== null && node && typeof node.dispatchEvent === 'function') { node.dispatchEvent(event); return true }
392
+ return false
393
+ }
394
+ if (!fire(start, 'pointerdown', spec.from.x, spec.from.y)) {
395
+ return JSON.stringify({ ok: false, reason: 'this page exposes no event constructors to dispatch a drag' })
396
+ }
397
+ fire(start, 'mousedown', spec.from.x, spec.from.y)
398
+ const total = Math.max(1, Math.min(Number(spec.steps) || 12, 60))
399
+ for (let i = 1; i <= total; i += 1) {
400
+ const x = Math.round(spec.from.x + (spec.to.x - spec.from.x) * (i / total))
401
+ const y = Math.round(spec.from.y + (spec.to.y - spec.from.y) * (i / total))
402
+ const node = at(x, y) || start
403
+ fire(node, 'pointermove', x, y)
404
+ fire(node, 'mousemove', x, y)
405
+ }
406
+ const end = at(spec.to.x, spec.to.y) || start
407
+ fire(end, 'pointerup', spec.to.x, spec.to.y)
408
+ fire(end, 'mouseup', spec.to.x, spec.to.y)
409
+ return JSON.stringify({ ok: true, moved: total, at: spec.to })
410
+ })()`
411
+ }
412
+
413
+ /**
414
+ * Put a local file into an `<input type=file>`, without CDP.
415
+ *
416
+ * The page cannot read a disk path, so the bytes travel in as base64 and are rebuilt as a `File`
417
+ * in page context, then attached through a `DataTransfer`. That is what a drag-and-drop handler
418
+ * sees, so frameworks that read `input.files` or a drop event both work. The admission decision
419
+ * (which path may be read at all) belongs to the caller; this only carries the bytes.
420
+ * @param target - how to find the input: a CSS selector or visible text near it.
421
+ * @param file - name, MIME type and base64 of the bytes.
422
+ * @returns a script value: `{ ok: true, name, size }` or `{ ok: false, reason }`.
423
+ */
424
+ export function uploadScript(
425
+ target: { readonly by: 'css' | 'text' | 'xpath'; readonly value: string },
426
+ file: { readonly name: string; readonly mime: string; readonly base64: string },
427
+ ): string {
428
+ const spec = JSON.stringify({ target, file })
429
+ return `(() => {
430
+ const spec = ${spec}
431
+ const probe = globalThis[${JSON.stringify(PROBE_KEY)}]
432
+ const where = probe ? probe.find(spec.target) : null
433
+ let node = null
434
+ try {
435
+ if (spec.target.by === 'css') node = document.querySelector(spec.target.value)
436
+ else if (spec.target.by === 'xpath') node = document.evaluate(spec.target.value, document, null, 9, null).singleNodeValue
437
+ else if (where) node = document.elementFromPoint(where.x, where.y)
438
+ } catch (error) { node = null }
439
+ if (node && node.tagName !== 'INPUT' && node.querySelector) {
440
+ const nested = node.querySelector('input[type=file]')
441
+ if (nested) node = nested
442
+ }
443
+ if (!node || node.tagName !== 'INPUT' || String(node.type).toLowerCase() !== 'file') {
444
+ return JSON.stringify({ ok: false, reason: 'no file input at that target (' + (where ? where.described : 'nothing matched') + ')' })
445
+ }
446
+ const binary = atob(spec.file.base64)
447
+ const bytes = new Uint8Array(binary.length)
448
+ for (let i = 0; i < binary.length; i += 1) bytes[i] = binary.charCodeAt(i)
449
+ const blob = new File([bytes], spec.file.name, { type: spec.file.mime || 'application/octet-stream' })
450
+ const transfer = new DataTransfer()
451
+ transfer.items.add(blob)
452
+ node.files = transfer.files
453
+ node.dispatchEvent(new Event('input', { bubbles: true }))
454
+ node.dispatchEvent(new Event('change', { bubbles: true }))
455
+ return JSON.stringify({ ok: true, name: blob.name, size: blob.size, files: node.files ? node.files.length : 0 })
456
+ })()`
457
+ }
458
+ /** Build a fixed page operation, rejecting unknown operations before any code runs. */
459
+ export function pageOperationScript(request: BrowserPageOperationRequest): string {
460
+ switch (request.operation) {
461
+ case 'install': return PROBE_INSTALL_SCRIPT
462
+ case 'url': return 'JSON.stringify(location.href)'
463
+ case 'text': return 'JSON.stringify((document.body ? document.body.innerText : "").indexOf(' + JSON.stringify(request.text) + ') !== -1)'
464
+ case 'drag': return dragScript(request.from, request.to, request.steps)
465
+ case 'upload': return uploadScript(request.target, request.file)
466
+ case 'probe': {
467
+ const methods: readonly BrowserProbeMethod[] = ['read', 'clear', 'settle', 'find', 'overlayAt', 'summary',
468
+ 'findText', 'hoverAt', 'setDialogPolicy', 'dialogStatus', 'networkCursor']
469
+ if (!methods.includes(request.method)) throw new Error('browser: unsupported fixed page operation')
470
+ return probeCallScript(request.method, request.args)
471
+ }
472
+ default: throw new Error('browser: unsupported fixed page operation')
473
+ }
474
+ }