mcp-browser-dev-tools 0.2.1 → 0.3.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.
@@ -1,15 +1,42 @@
1
- import { pageScript } from "./page-script.mjs";
1
+ import { inputRecorder, pageScript } from "./page-script.mjs";
2
2
 
3
3
  const PAGE_SCRIPT_SOURCE = pageScript.toString();
4
4
 
5
+ // The input recorder as a function declaration, to run with early = true
6
+ // when each new document starts or false on the current document.
7
+ export const INPUT_RECORDER_FUNCTION = inputRecorder.toString();
8
+
9
+ export function buildInputRecorderExpression(early) {
10
+ return `(${INPUT_RECORDER_FUNCTION})(${early})`;
11
+ }
12
+
5
13
  // Builds an expression that runs pageScript in the page with this payload.
6
- // With serialize, the expression evaluates to the result as a JSON string.
14
+ // With serialize, the expression evaluates to the result as a JSON string,
15
+ // or, for an action that returns a promise, to a promise of one.
7
16
  export function buildPageContextExpression(
8
17
  payload,
9
18
  { serialize = false } = {},
10
19
  ) {
11
20
  const body = `(${PAGE_SCRIPT_SOURCE})(${JSON.stringify(payload)})`;
12
- return serialize ? `JSON.stringify(${body})` : body;
21
+ return serialize
22
+ ? `((result) => result && typeof result.then === "function" ? result.then(JSON.stringify) : JSON.stringify(result))(${body})`
23
+ : body;
24
+ }
25
+
26
+ // Refs (e12) are numbered per page from refStart. The server remembers the
27
+ // page's next ref on the session and passes it on, so numbering continues
28
+ // across navigations and a ref from an earlier page never resolves on a
29
+ // later one. The page reports nextRef with each snapshot; it is bookkeeping,
30
+ // so it is removed from the result.
31
+ export function takeNextRef(session, result) {
32
+ if (result && typeof result === "object" && "nextRef" in result) {
33
+ const { nextRef, ...rest } = result;
34
+ if (Number.isInteger(nextRef) && nextRef > (session.refStart ?? 1)) {
35
+ session.refStart = nextRef;
36
+ }
37
+ return rest;
38
+ }
39
+ return result;
13
40
  }
14
41
 
15
42
  function describeTarget(target) {
@@ -62,3 +89,288 @@ export function assertEnabled(target) {
62
89
  throw notActionable(`Element "${target.selector}" is disabled`);
63
90
  }
64
91
  }
92
+
93
+ // A pointer target is a locator, which resolves to the center of its
94
+ // element's visible area, or viewport coordinates { x, y } in CSS pixels.
95
+ export function describePointer(target) {
96
+ return typeof target === "string"
97
+ ? `"${target}"`
98
+ : `(${target.x}, ${target.y})`;
99
+ }
100
+
101
+ // The fields an action reports about where it acted: the selector and its
102
+ // element, or the element found at the coordinates.
103
+ export function pointerFields(target, resolved, node = resolved.node) {
104
+ return typeof target === "string"
105
+ ? { selector: target, point: resolved.point, node }
106
+ : { point: resolved.point, target: resolved.target };
107
+ }
108
+
109
+ // A drag reports where it pressed and released, without element details.
110
+ export function dragEnd(target, resolved) {
111
+ return typeof target === "string"
112
+ ? { selector: target, point: resolved.point }
113
+ : { point: resolved.point, target: resolved.target };
114
+ }
115
+
116
+ export const DEFAULT_DRAG_STEPS = 10;
117
+
118
+ // The points a drag moves through after pressing at from, ending at to, so
119
+ // pages that track the pointer see a path rather than a jump.
120
+ export function dragPath(from, to, steps = DEFAULT_DRAG_STEPS) {
121
+ return Array.from({ length: steps }, (_, index) => {
122
+ const fraction = (index + 1) / steps;
123
+ return {
124
+ x: from.x + (to.x - from.x) * fraction,
125
+ y: from.y + (to.y - from.y) * fraction,
126
+ };
127
+ });
128
+ }
129
+
130
+ export const MOUSE_BUTTONS = ["left", "middle", "right"];
131
+
132
+ // Whether scroll sends a mouse wheel rather than scrolling from the page.
133
+ export function wheelScroll(options) {
134
+ const deltas = options.deltaX !== undefined || options.deltaY !== undefined;
135
+ return options.x !== undefined || Boolean(options.selector && deltas);
136
+ }
137
+
138
+ // An expression that takes the file input fileInput() left on the window
139
+ // under token, removing it there.
140
+ export function takeFileTarget(token) {
141
+ const key = JSON.stringify(token);
142
+ return `(() => { const targets = window.__mcpBrowserDevToolsFileTargets; const input = targets?.get(${key}); targets?.delete(${key}); return input; })()`;
143
+ }
144
+
145
+ // Checks a file input before files are set on it.
146
+ export function assertFileInput(target, files) {
147
+ if (target.disabled) {
148
+ throw notActionable(`File input "${target.selector}" is disabled`);
149
+ }
150
+ if (files.length > 1 && !target.multiple) {
151
+ throw new Error(
152
+ `File input "${target.selector}" takes one file, not ${files.length}`,
153
+ );
154
+ }
155
+ }
156
+
157
+ export function uploadResult(browserFamily, selector, files, extra = {}) {
158
+ return {
159
+ browserFamily,
160
+ selector,
161
+ found: true,
162
+ uploaded: files.map((file) => file.split(/[\\/]/).pop()),
163
+ ...extra,
164
+ };
165
+ }
166
+
167
+ // Frames: get_snapshot lists the controls inside iframes with refs like
168
+ // f2e7, element e7 of frame f2. The server keeps the frame keys; a tool
169
+ // given such a ref runs its page action in that frame, with the ref
170
+ // rewritten to the frame's own e7, and shifts the points it reports by the
171
+ // frame's position, so input lands where the element is.
172
+ export const MAX_SNAPSHOT_FRAMES = 10;
173
+
174
+ export function parseFrameRef(selector) {
175
+ const match =
176
+ typeof selector === "string"
177
+ ? selector.trim().match(/^ref=f(\d+)(e\d+)$/)
178
+ : null;
179
+ return match
180
+ ? { frameKey: `f${match[1]}`, selector: `ref=${match[2]}` }
181
+ : null;
182
+ }
183
+
184
+ // Frame keys for one session, stable for a frame while it exists. Each
185
+ // frame carries its own next ref, as the session does for the top page.
186
+ export class FrameKeys {
187
+ constructor() {
188
+ this.byKey = new Map();
189
+ this.byId = new Map();
190
+ this.next = 1;
191
+ }
192
+
193
+ keyFor(id, frame) {
194
+ let key = this.byId.get(id);
195
+ if (!key) {
196
+ key = `f${this.next++}`;
197
+ this.byId.set(id, key);
198
+ }
199
+ this.byKey.set(key, { ...(this.byKey.get(key) ?? {}), ...frame, id, key });
200
+ return key;
201
+ }
202
+
203
+ get(key) {
204
+ return this.byKey.get(key) ?? null;
205
+ }
206
+ }
207
+
208
+ export function unknownFrame(frameKey, selector) {
209
+ return {
210
+ found: false,
211
+ selector,
212
+ error: `Unknown frame ${frameKey}: frame refs come from get_snapshot, and the frame may have gone; call get_snapshot again`,
213
+ };
214
+ }
215
+
216
+ // A result from a frame names the selector the tool was given, with its
217
+ // frame, rather than the frame's own ref.
218
+ export function restoreFrameSelector(result, route, selector) {
219
+ return result &&
220
+ typeof result === "object" &&
221
+ result.selector === route.selector
222
+ ? { ...result, selector }
223
+ : result;
224
+ }
225
+
226
+ // A change report from a frame, with its refs carrying the frame's key.
227
+ export function prefixFrameReport(report, frameKey) {
228
+ if (!report || typeof report !== "object") {
229
+ return report;
230
+ }
231
+ const prefix = (line) => line.replace(/^e(\d+)/, `${frameKey}e$1`);
232
+ const lists = Object.fromEntries(
233
+ ["added", "removed", "updated"]
234
+ .filter((key) => report[key]?.lines)
235
+ .map((key) => [
236
+ key,
237
+ { ...report[key], lines: report[key].lines.map(prefix) },
238
+ ]),
239
+ );
240
+ return {
241
+ ...report,
242
+ ...lists,
243
+ ...(Array.isArray(report.nodes) ? { nodes: report.nodes.map(prefix) } : {}),
244
+ };
245
+ }
246
+
247
+ // Moves the points a page action in a frame reports into the top page's
248
+ // viewport.
249
+ export function shiftFramePoints(result, offset) {
250
+ if (!result || typeof result !== "object" || !offset) {
251
+ return result;
252
+ }
253
+ const shifted = { ...result };
254
+ if (result.point) {
255
+ shifted.point = {
256
+ x: result.point.x + offset.x,
257
+ y: result.point.y + offset.y,
258
+ };
259
+ }
260
+ if (result.node?.box) {
261
+ const box = result.node.box;
262
+ shifted.node = {
263
+ ...result.node,
264
+ box: {
265
+ ...box,
266
+ x: box.x + offset.x,
267
+ y: box.y + offset.y,
268
+ left: box.left + offset.x,
269
+ right: box.right + offset.x,
270
+ top: box.top + offset.y,
271
+ bottom: box.bottom + offset.y,
272
+ },
273
+ };
274
+ }
275
+ return shifted;
276
+ }
277
+
278
+ // A frame's snapshot lines, after a header naming the frame, with refs
279
+ // carrying the frame's key.
280
+ export function frameSnapshotLines(frameKey, frame, result) {
281
+ const header =
282
+ `${frameKey} frame ${JSON.stringify(result.title ?? "")} ${result.url ?? frame.url ?? ""}`.trim();
283
+ const lines = (result.nodes ?? []).map((line) =>
284
+ line.replace(/^e(\d+)/, `${frameKey}e$1`),
285
+ );
286
+ if (result.more > 0) {
287
+ lines.push(`(${result.more} more nodes in ${frameKey})`);
288
+ }
289
+ return [header, ...lines];
290
+ }
291
+
292
+ // Adds the frames' snapshots to the top page's: each frame with nodes gets
293
+ // a header and its lines. A frame's refs number on from its own last
294
+ // snapshot, as the top page's do. Frames without a box are left out.
295
+ export async function addFrameSnapshots({
296
+ result,
297
+ frames,
298
+ frameKeys,
299
+ runInFrame,
300
+ options,
301
+ }) {
302
+ if (!result?.found || !Array.isArray(result.nodes)) {
303
+ return result;
304
+ }
305
+ const nodes = [...result.nodes];
306
+ let shown = 0;
307
+ for (const frame of frames) {
308
+ if (shown >= MAX_SNAPSHOT_FRAMES) {
309
+ break;
310
+ }
311
+ const key = frameKeys.keyFor(frame.id, frame);
312
+ const entry = frameKeys.get(key);
313
+ let snapshot;
314
+ try {
315
+ snapshot = await runInFrame(
316
+ key,
317
+ {
318
+ action: "snapshot",
319
+ limit: options.limit,
320
+ headings: options.headings,
321
+ refStart: entry.refStart ?? 1,
322
+ },
323
+ { scroll: false },
324
+ );
325
+ } catch {
326
+ continue;
327
+ }
328
+ if (!snapshot?.found) {
329
+ continue;
330
+ }
331
+ snapshot = takeNextRef(entry, snapshot);
332
+ if (snapshot.nodes.length === 0) {
333
+ continue;
334
+ }
335
+ nodes.push(...frameSnapshotLines(key, frame, snapshot));
336
+ shown += 1;
337
+ }
338
+ return { ...result, nodes };
339
+ }
340
+
341
+ // A snapshot of one element inside a frame, named by a frame ref.
342
+ export async function frameElementSnapshot({
343
+ route,
344
+ frameKeys,
345
+ runInFrame,
346
+ options,
347
+ }) {
348
+ const entry = frameKeys.get(route.frameKey);
349
+ if (!entry) {
350
+ return unknownFrame(route.frameKey, options.selector);
351
+ }
352
+ const snapshot = await runInFrame(route.frameKey, {
353
+ action: "snapshot",
354
+ selector: route.selector,
355
+ limit: options.limit,
356
+ headings: options.headings,
357
+ refStart: entry.refStart ?? 1,
358
+ });
359
+ if (!snapshot?.found) {
360
+ return snapshot;
361
+ }
362
+ const { nodes, more, ...rest } = takeNextRef(entry, snapshot);
363
+ return {
364
+ ...rest,
365
+ nodes: nodes.map((line) => line.replace(/^e(\d+)/, `${route.frameKey}e$1`)),
366
+ more,
367
+ };
368
+ }
369
+
370
+ // The scope a delivery probe was armed in: the frame of a frame ref, else
371
+ // the top document. Passed as the probe's selector, so it is read there.
372
+ export function probeScope(target) {
373
+ return typeof target === "string" && parseFrameRef(target)
374
+ ? { selector: target }
375
+ : {};
376
+ }