mcp-browser-dev-tools 0.1.0 → 0.2.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.
@@ -0,0 +1,1372 @@
1
+ // Runs inside the page, not in Node: the broker serializes this function with
2
+ // toString() and evaluates it in the page context with a JSON payload. It must
3
+ // not reference anything outside itself except browser globals.
4
+ export function pageScript(payload) {
5
+ const TEXT_LIMIT = 400;
6
+ const VALUE_ONLY_INPUT_TYPES = [
7
+ "date",
8
+ "time",
9
+ "datetime-local",
10
+ "month",
11
+ "week",
12
+ "color",
13
+ "range",
14
+ ];
15
+
16
+ function clipText(value, limit = TEXT_LIMIT) {
17
+ if (typeof value !== "string") {
18
+ return value ?? null;
19
+ }
20
+
21
+ return value.length > limit ? `${value.slice(0, limit)}...` : value;
22
+ }
23
+
24
+ function normalizeText(value) {
25
+ return typeof value === "string" ? value.replace(/\s+/g, " ").trim() : "";
26
+ }
27
+
28
+ function getVisibleText(element) {
29
+ if (!element) {
30
+ return "";
31
+ }
32
+
33
+ if (typeof element.innerText === "string" && element.innerText.trim()) {
34
+ return element.innerText;
35
+ }
36
+
37
+ return element.textContent ?? "";
38
+ }
39
+
40
+ // Compares the element's full visible text, with whitespace collapsed,
41
+ // so text conditions are not limited by the clipped text in the node.
42
+ function checkElementText(element, checks) {
43
+ const text = normalizeText(
44
+ typeof element.innerText === "string"
45
+ ? element.innerText
46
+ : element.textContent,
47
+ );
48
+ return checks.map(
49
+ (check) =>
50
+ (typeof check.textEquals !== "string" || text === check.textEquals) &&
51
+ (typeof check.textIncludes !== "string" ||
52
+ text.includes(check.textIncludes)) &&
53
+ (typeof check.textExcludes !== "string" ||
54
+ !text.includes(check.textExcludes)),
55
+ );
56
+ }
57
+
58
+ function getLabelTextForControl(element) {
59
+ if (!element || !element.id) {
60
+ return "";
61
+ }
62
+
63
+ const label = document.querySelector(
64
+ `label[for="${CSS.escape(element.id)}"]`,
65
+ );
66
+ return label ? normalizeText(getVisibleText(label)) : "";
67
+ }
68
+
69
+ // Text of a <label> wrapped around the control, leaving out the control
70
+ // itself (a <select> would otherwise add every option's text).
71
+ function getImplicitLabelText(element) {
72
+ if (
73
+ typeof element.closest !== "function" ||
74
+ !["INPUT", "SELECT", "TEXTAREA"].includes(element.tagName)
75
+ ) {
76
+ return "";
77
+ }
78
+
79
+ const label = element.closest("label");
80
+ if (!label) {
81
+ return "";
82
+ }
83
+
84
+ const parts = [];
85
+ const collect = (node) => {
86
+ if (node === element) {
87
+ return;
88
+ }
89
+ if (node.nodeType === 3) {
90
+ parts.push(node.textContent);
91
+ return;
92
+ }
93
+ if (
94
+ node.nodeType !== 1 ||
95
+ ["INPUT", "SELECT", "TEXTAREA"].includes(node.tagName)
96
+ ) {
97
+ return;
98
+ }
99
+ if (typeof node.contains === "function" && node.contains(element)) {
100
+ for (const child of node.childNodes ?? []) {
101
+ collect(child);
102
+ }
103
+ return;
104
+ }
105
+ parts.push(getVisibleText(node));
106
+ };
107
+ for (const node of label.childNodes ?? []) {
108
+ collect(node);
109
+ }
110
+ return normalizeText(parts.join(""));
111
+ }
112
+
113
+ function isPassword(element) {
114
+ return (
115
+ element.tagName === "INPUT" &&
116
+ (element.getAttribute("type") || "").toLowerCase() === "password"
117
+ );
118
+ }
119
+
120
+ function getAccessibleName(element) {
121
+ if (!element) {
122
+ return "";
123
+ }
124
+
125
+ const ariaLabel = element.getAttribute("aria-label");
126
+ if (ariaLabel) {
127
+ return normalizeText(ariaLabel);
128
+ }
129
+
130
+ const labelledBy = element.getAttribute("aria-labelledby");
131
+ if (labelledBy) {
132
+ const text = labelledBy
133
+ .split(/\s+/)
134
+ .map((id) => document.getElementById(id))
135
+ .filter(Boolean)
136
+ .map((node) => normalizeText(getVisibleText(node)))
137
+ .filter(Boolean)
138
+ .join(" ");
139
+ if (text) {
140
+ return text;
141
+ }
142
+ }
143
+
144
+ const labelText =
145
+ getLabelTextForControl(element) || getImplicitLabelText(element);
146
+ if (labelText) {
147
+ return labelText;
148
+ }
149
+
150
+ const alt = element.getAttribute("alt");
151
+ if (alt) {
152
+ return normalizeText(alt);
153
+ }
154
+
155
+ const title = element.getAttribute("title");
156
+ if (title) {
157
+ return normalizeText(title);
158
+ }
159
+
160
+ if (
161
+ element instanceof HTMLInputElement ||
162
+ element instanceof HTMLTextAreaElement
163
+ ) {
164
+ return isPassword(element) ? "" : normalizeText(element.value);
165
+ }
166
+
167
+ return normalizeText(getVisibleText(element));
168
+ }
169
+
170
+ function inferRole(element) {
171
+ if (!element) {
172
+ return null;
173
+ }
174
+
175
+ const explicitRole = element.getAttribute("role");
176
+ if (explicitRole) {
177
+ return explicitRole;
178
+ }
179
+
180
+ const tag = element.tagName.toLowerCase();
181
+ if (tag === "a" && element.hasAttribute("href")) return "link";
182
+ if (tag === "button") return "button";
183
+ if (tag === "dialog") return "dialog";
184
+ if (tag === "img") return "img";
185
+ if (tag === "select") return "combobox";
186
+ if (tag === "textarea") return "textbox";
187
+ if (tag === "option") return "option";
188
+ if (tag === "ul" || tag === "ol") return "list";
189
+ if (tag === "li") return "listitem";
190
+ if (tag === "input") {
191
+ const type = (element.getAttribute("type") || "text").toLowerCase();
192
+ if (type === "button" || type === "submit" || type === "reset")
193
+ return "button";
194
+ if (type === "checkbox") return "checkbox";
195
+ if (type === "radio") return "radio";
196
+ if (type === "range") return "slider";
197
+ return "textbox";
198
+ }
199
+
200
+ return null;
201
+ }
202
+
203
+ function isVisible(element) {
204
+ if (!element) {
205
+ return false;
206
+ }
207
+
208
+ const style = getComputedStyle(element);
209
+ const rect = element.getBoundingClientRect();
210
+ if (
211
+ element.hidden ||
212
+ element.getAttribute("aria-hidden") === "true" ||
213
+ style.display === "none" ||
214
+ style.visibility === "hidden" ||
215
+ style.visibility === "collapse" ||
216
+ style.pointerEvents === "none"
217
+ ) {
218
+ return false;
219
+ }
220
+
221
+ return rect.width > 0 && rect.height > 0;
222
+ }
223
+
224
+ // :disabled covers controls inside a disabled <fieldset>, whose own
225
+ // disabled property stays false.
226
+ function isDisabled(element) {
227
+ return Boolean(
228
+ element &&
229
+ (element.disabled === true ||
230
+ element.getAttribute("aria-disabled") === "true" ||
231
+ (typeof element.matches === "function" &&
232
+ element.matches(":disabled"))),
233
+ );
234
+ }
235
+
236
+ function isEditable(element) {
237
+ return Boolean(
238
+ element &&
239
+ (element.isContentEditable ||
240
+ element instanceof HTMLTextAreaElement ||
241
+ (element instanceof HTMLInputElement &&
242
+ !["button", "submit", "reset", "checkbox", "radio", "file"].includes(
243
+ (element.type || "text").toLowerCase(),
244
+ ))),
245
+ );
246
+ }
247
+
248
+ function isFocusable(element) {
249
+ if (!element || isDisabled(element)) {
250
+ return false;
251
+ }
252
+
253
+ if (typeof element.tabIndex === "number" && element.tabIndex >= 0) {
254
+ return true;
255
+ }
256
+
257
+ const tag = element.tagName.toLowerCase();
258
+ return ["a", "button", "input", "select", "textarea"].includes(tag);
259
+ }
260
+
261
+ function isClickable(element) {
262
+ if (!element || isDisabled(element)) {
263
+ return false;
264
+ }
265
+
266
+ const role = inferRole(element);
267
+ const tag = element.tagName.toLowerCase();
268
+ return (
269
+ ["button", "link", "checkbox", "radio", "option"].includes(role) ||
270
+ ["button", "a", "summary", "option"].includes(tag) ||
271
+ typeof element.onclick === "function"
272
+ );
273
+ }
274
+
275
+ function isScrollable(element) {
276
+ if (!element) {
277
+ return false;
278
+ }
279
+
280
+ return (
281
+ element.scrollHeight > element.clientHeight ||
282
+ element.scrollWidth > element.clientWidth
283
+ );
284
+ }
285
+
286
+ function toAttributeObject(element) {
287
+ return Object.fromEntries(
288
+ Array.from(element.attributes, (attribute) => [
289
+ attribute.name,
290
+ attribute.value,
291
+ ]),
292
+ );
293
+ }
294
+
295
+ function summarizeLocator(locator) {
296
+ if (!locator || typeof locator !== "object") {
297
+ return null;
298
+ }
299
+
300
+ const summary = {};
301
+ for (const key of [
302
+ "locator",
303
+ "strategy",
304
+ "query",
305
+ "role",
306
+ "name",
307
+ "error",
308
+ ]) {
309
+ if (locator[key] !== undefined) {
310
+ summary[key] = locator[key];
311
+ }
312
+ }
313
+
314
+ return summary;
315
+ }
316
+
317
+ function describeElement(element, locator) {
318
+ const rect = element.getBoundingClientRect();
319
+ const style = getComputedStyle(element);
320
+ const role = inferRole(element);
321
+ const accessibleName = getAccessibleName(element);
322
+
323
+ return {
324
+ locator: summarizeLocator(locator),
325
+ tagName: element.tagName,
326
+ id: element.getAttribute("id"),
327
+ className: element.getAttribute("class"),
328
+ childElementCount: element.childElementCount,
329
+ attributes: toAttributeObject(element),
330
+ textContent: clipText(element.textContent ?? null),
331
+ innerText: clipText(
332
+ typeof element.innerText === "string" ? element.innerText : null,
333
+ ),
334
+ value:
335
+ "value" in element && typeof element.value === "string"
336
+ ? clipText(element.value)
337
+ : null,
338
+ accessibleName: accessibleName || null,
339
+ role,
340
+ visible: isVisible(element),
341
+ disabled: isDisabled(element),
342
+ focused: document.activeElement === element,
343
+ editable: isEditable(element),
344
+ focusable: isFocusable(element),
345
+ clickable: isClickable(element),
346
+ scrollable: isScrollable(element),
347
+ checked: "checked" in element ? Boolean(element.checked) : null,
348
+ selected: "selected" in element ? Boolean(element.selected) : null,
349
+ open: "open" in element ? Boolean(element.open) : null,
350
+ box: {
351
+ x: rect.x,
352
+ y: rect.y,
353
+ width: rect.width,
354
+ height: rect.height,
355
+ top: rect.top,
356
+ right: rect.right,
357
+ bottom: rect.bottom,
358
+ left: rect.left,
359
+ },
360
+ styles: {
361
+ display: style.display,
362
+ visibility: style.visibility,
363
+ position: style.position,
364
+ zIndex: style.zIndex,
365
+ overflowX: style.overflowX,
366
+ overflowY: style.overflowY,
367
+ opacity: style.opacity,
368
+ pointerEvents: style.pointerEvents,
369
+ },
370
+ outerHTML: clipText(element.outerHTML, 1200),
371
+ };
372
+ }
373
+
374
+ function parseRoleLocator(value) {
375
+ const match = value.match(
376
+ /^([^[]+?)(?:\[name=(?:"([^"]*)"|'([^']*)')\])?$/,
377
+ );
378
+ if (!match) {
379
+ return {
380
+ role: normalizeText(value) || null,
381
+ name: null,
382
+ };
383
+ }
384
+
385
+ return {
386
+ role: normalizeText(match[1]) || null,
387
+ name: normalizeText(match[2] ?? match[3] ?? "") || null,
388
+ };
389
+ }
390
+
391
+ function collectCandidates() {
392
+ return Array.from(document.querySelectorAll("body *"));
393
+ }
394
+
395
+ const SNAPSHOT_LIMIT = 40;
396
+ const SNAPSHOT_TEXT_LIMIT = 80;
397
+ const CONTROL_ROLES = [
398
+ "button",
399
+ "link",
400
+ "checkbox",
401
+ "radio",
402
+ "switch",
403
+ "textbox",
404
+ "searchbox",
405
+ "combobox",
406
+ "spinbutton",
407
+ "slider",
408
+ "tab",
409
+ "menuitem",
410
+ "option",
411
+ ];
412
+
413
+ function resolvesTo(locator, element) {
414
+ try {
415
+ return resolveLocator(locator).element === element;
416
+ } catch {
417
+ return false;
418
+ }
419
+ }
420
+
421
+ // Suggests a locator the tools accept that resolves back to this element:
422
+ // its id, its form field name (and value), or its role and accessible
423
+ // name. Returns null when none of them does.
424
+ function suggestLocator(element, role, name) {
425
+ const id = element.getAttribute("id");
426
+ if (
427
+ id &&
428
+ /^[A-Za-z][A-Za-z0-9_-]*$/.test(id) &&
429
+ resolvesTo("#" + id, element)
430
+ ) {
431
+ return "#" + id;
432
+ }
433
+
434
+ const tag = element.tagName.toLowerCase();
435
+ const fieldName = element.getAttribute("name");
436
+ if (fieldName && ["input", "select", "textarea"].includes(tag)) {
437
+ const selector = tag + '[name="' + CSS.escape(fieldName) + '"]';
438
+ if (resolvesTo(selector, element)) {
439
+ return selector;
440
+ }
441
+ const value = element.getAttribute("value");
442
+ if (value && !isPassword(element)) {
443
+ const withValue = selector + '[value="' + CSS.escape(value) + '"]';
444
+ if (resolvesTo(withValue, element)) {
445
+ return withValue;
446
+ }
447
+ }
448
+ }
449
+
450
+ if (role && name && !name.includes('"')) {
451
+ const byRole = "role=" + role + '[name="' + name + '"]';
452
+ if (resolvesTo(byRole, element)) {
453
+ return byRole;
454
+ }
455
+ }
456
+ return null;
457
+ }
458
+
459
+ function describeControl(element, role) {
460
+ const name = normalizeText(getAccessibleName(element));
461
+ const control = {
462
+ locator: suggestLocator(element, role, name),
463
+ role,
464
+ };
465
+ if (name) {
466
+ control.name = clipText(name, SNAPSHOT_TEXT_LIMIT);
467
+ }
468
+ if (
469
+ ["textbox", "searchbox", "combobox", "spinbutton", "slider"].includes(
470
+ role,
471
+ ) &&
472
+ "value" in element &&
473
+ typeof element.value === "string" &&
474
+ !isPassword(element)
475
+ ) {
476
+ control.value = clipText(element.value, SNAPSHOT_TEXT_LIMIT);
477
+ // The accessible name of a field can fall back to its value.
478
+ if (name && name === normalizeText(element.value)) {
479
+ delete control.name;
480
+ }
481
+ }
482
+ if (role === "checkbox" || role === "radio" || role === "switch") {
483
+ control.checked =
484
+ "checked" in element
485
+ ? Boolean(element.checked)
486
+ : element.getAttribute("aria-checked") === "true";
487
+ }
488
+ if (isDisabled(element)) {
489
+ control.disabled = true;
490
+ }
491
+ return control;
492
+ }
493
+
494
+ // Lists the visible controls on the page, so an agent can fix a failed
495
+ // step without another round trip to look around.
496
+ function snapshotControls() {
497
+ const controls = [];
498
+ let more = 0;
499
+ for (const element of collectCandidates()) {
500
+ const role = inferRole(element);
501
+ const editable =
502
+ element.hasAttribute("contenteditable") && element.isContentEditable;
503
+ if (!(CONTROL_ROLES.includes(role) || editable) || !isVisible(element)) {
504
+ continue;
505
+ }
506
+ if (controls.length >= SNAPSHOT_LIMIT) {
507
+ more += 1;
508
+ continue;
509
+ }
510
+ controls.push(describeControl(element, role ?? "textbox"));
511
+ }
512
+ return { controls, moreControls: more };
513
+ }
514
+
515
+ function describePage() {
516
+ return {
517
+ url: location.href,
518
+ title: document.title,
519
+ readyState: document.readyState,
520
+ visibilityState: document.visibilityState,
521
+ viewport: {
522
+ width: window.innerWidth,
523
+ height: window.innerHeight,
524
+ devicePixelRatio: window.devicePixelRatio,
525
+ },
526
+ scroll: {
527
+ x: window.scrollX,
528
+ y: window.scrollY,
529
+ },
530
+ };
531
+ }
532
+
533
+ function parseDocumentCookies() {
534
+ const COOKIE_LIMIT = 100;
535
+ const NAME_LIMIT = 120;
536
+ const VALUE_LIMIT = 300;
537
+ const cookieText =
538
+ typeof document.cookie === "string" ? document.cookie.trim() : "";
539
+
540
+ if (!cookieText) {
541
+ return {
542
+ totalEntries: 0,
543
+ returnedEntries: 0,
544
+ truncated: false,
545
+ entries: [],
546
+ source: "document.cookie",
547
+ };
548
+ }
549
+
550
+ const rawEntries = cookieText
551
+ .split(";")
552
+ .map((entry) => entry.trim())
553
+ .filter(Boolean);
554
+ const entries = rawEntries.slice(0, COOKIE_LIMIT).map((entry) => {
555
+ const separatorIndex = entry.indexOf("=");
556
+ const name =
557
+ separatorIndex === -1 ? entry : entry.slice(0, separatorIndex);
558
+ const value =
559
+ separatorIndex === -1 ? "" : entry.slice(separatorIndex + 1);
560
+ return {
561
+ name: clipText(name, NAME_LIMIT),
562
+ value: clipText(value, VALUE_LIMIT),
563
+ };
564
+ });
565
+
566
+ return {
567
+ totalEntries: rawEntries.length,
568
+ returnedEntries: entries.length,
569
+ truncated: rawEntries.length > COOKIE_LIMIT,
570
+ entries,
571
+ source: "document.cookie",
572
+ };
573
+ }
574
+
575
+ function snapshotStorage(storage, type) {
576
+ const STORAGE_LIMIT = 100;
577
+ const KEY_LIMIT = 200;
578
+ const VALUE_LIMIT = 300;
579
+
580
+ try {
581
+ const totalEntries = storage.length;
582
+ const entries = [];
583
+ const limit = Math.min(totalEntries, STORAGE_LIMIT);
584
+
585
+ for (let index = 0; index < limit; index += 1) {
586
+ const key = storage.key(index);
587
+ if (key === null) {
588
+ continue;
589
+ }
590
+
591
+ entries.push({
592
+ key: clipText(key, KEY_LIMIT),
593
+ value: clipText(storage.getItem(key), VALUE_LIMIT),
594
+ });
595
+ }
596
+
597
+ return {
598
+ type,
599
+ totalEntries,
600
+ returnedEntries: entries.length,
601
+ truncated: totalEntries > STORAGE_LIMIT,
602
+ entries,
603
+ };
604
+ } catch (error) {
605
+ return {
606
+ type,
607
+ totalEntries: 0,
608
+ returnedEntries: 0,
609
+ truncated: false,
610
+ entries: [],
611
+ error: error instanceof Error ? error.message : String(error),
612
+ };
613
+ }
614
+ }
615
+
616
+ function summarizeStorage(storage, type) {
617
+ const SAMPLE_LIMIT = 20;
618
+ const KEY_LIMIT = 80;
619
+
620
+ try {
621
+ const totalEntries = storage.length;
622
+ const sampleKeys = [];
623
+ const limit = Math.min(totalEntries, SAMPLE_LIMIT);
624
+
625
+ for (let index = 0; index < limit; index += 1) {
626
+ const key = storage.key(index);
627
+ if (key !== null) {
628
+ sampleKeys.push(clipText(key, KEY_LIMIT));
629
+ }
630
+ }
631
+
632
+ return {
633
+ type,
634
+ totalEntries,
635
+ sampleKeys,
636
+ truncated: totalEntries > SAMPLE_LIMIT,
637
+ };
638
+ } catch (error) {
639
+ return {
640
+ type,
641
+ totalEntries: 0,
642
+ sampleKeys: [],
643
+ truncated: false,
644
+ error: error instanceof Error ? error.message : String(error),
645
+ };
646
+ }
647
+ }
648
+
649
+ function resolveLocator(rawLocator) {
650
+ const locator = typeof rawLocator === "string" ? rawLocator.trim() : "";
651
+ if (!locator) {
652
+ throw new Error("selector must be a non-empty string");
653
+ }
654
+
655
+ if (locator.startsWith("text=")) {
656
+ const query = normalizeText(locator.slice(5));
657
+ const candidates = collectCandidates();
658
+ const match =
659
+ candidates.find(
660
+ (element) =>
661
+ isVisible(element) &&
662
+ normalizeText(getVisibleText(element)) === query,
663
+ ) ??
664
+ candidates.find((element) => {
665
+ const text = normalizeText(getVisibleText(element));
666
+ return isVisible(element) && text && text.includes(query);
667
+ });
668
+
669
+ return {
670
+ locator,
671
+ strategy: "text",
672
+ query,
673
+ element: match ?? null,
674
+ };
675
+ }
676
+
677
+ if (locator.startsWith("role=")) {
678
+ const { role, name } = parseRoleLocator(locator.slice(5).trim());
679
+ const candidates = collectCandidates();
680
+ const match = candidates.find((element) => {
681
+ const elementRole = normalizeText(inferRole(element) ?? "");
682
+ const accessibleName = normalizeText(getAccessibleName(element));
683
+ if (!elementRole || elementRole !== role) {
684
+ return false;
685
+ }
686
+
687
+ if (!name) {
688
+ return true;
689
+ }
690
+
691
+ return accessibleName === name || accessibleName.includes(name);
692
+ });
693
+
694
+ return {
695
+ locator,
696
+ strategy: "role",
697
+ role,
698
+ name,
699
+ element: match ?? null,
700
+ };
701
+ }
702
+
703
+ if (locator.startsWith("name=")) {
704
+ const query = normalizeText(locator.slice(5));
705
+ const candidates = collectCandidates();
706
+ const found =
707
+ candidates.find((element) => {
708
+ const accessibleName = normalizeText(getAccessibleName(element));
709
+ return isVisible(element) && accessibleName === query;
710
+ }) ??
711
+ candidates.find((element) => {
712
+ const accessibleName = normalizeText(getAccessibleName(element));
713
+ return (
714
+ isVisible(element) &&
715
+ accessibleName &&
716
+ accessibleName.includes(query)
717
+ );
718
+ });
719
+
720
+ // A label's text names its control, so act on the control when it is
721
+ // visible; a styled checkbox hides its input and leaves the label.
722
+ const match =
723
+ found?.tagName === "LABEL" && found.control && isVisible(found.control)
724
+ ? found.control
725
+ : found;
726
+
727
+ return {
728
+ locator,
729
+ strategy: "name",
730
+ query,
731
+ element: match ?? null,
732
+ };
733
+ }
734
+
735
+ const cssSelector = locator.startsWith("css=") ? locator.slice(4) : locator;
736
+ try {
737
+ return {
738
+ locator,
739
+ strategy: "css",
740
+ query: cssSelector,
741
+ element: document.querySelector(cssSelector),
742
+ };
743
+ } catch (error) {
744
+ return {
745
+ locator,
746
+ strategy: "css",
747
+ query: cssSelector,
748
+ element: null,
749
+ error: error instanceof Error ? error.message : String(error),
750
+ };
751
+ }
752
+ }
753
+
754
+ function ensureResolved(rawLocator) {
755
+ const resolved = resolveLocator(rawLocator);
756
+ if (resolved.error) {
757
+ return {
758
+ browserFamily: payload.browserFamily,
759
+ selector: rawLocator,
760
+ found: false,
761
+ locator: summarizeLocator(resolved),
762
+ error: resolved.error,
763
+ };
764
+ }
765
+
766
+ if (!resolved.element) {
767
+ return {
768
+ browserFamily: payload.browserFamily,
769
+ selector: rawLocator,
770
+ found: false,
771
+ locator: summarizeLocator(resolved),
772
+ };
773
+ }
774
+
775
+ return resolved;
776
+ }
777
+
778
+ function dispatchInputEvents(element) {
779
+ element.dispatchEvent(
780
+ new Event("input", { bubbles: true, composed: true }),
781
+ );
782
+ element.dispatchEvent(
783
+ new Event("change", { bubbles: true, composed: true }),
784
+ );
785
+ }
786
+
787
+ // Assigning element.value directly also updates the value tracker React
788
+ // keeps on the instance, so React would treat the next input event as a
789
+ // no-op. The prototype setter bypasses that tracker.
790
+ function setNativeValue(element, value) {
791
+ const prototype = Object.getPrototypeOf(element);
792
+ const descriptor = prototype
793
+ ? Object.getOwnPropertyDescriptor(prototype, "value")
794
+ : null;
795
+ if (descriptor?.set) {
796
+ descriptor.set.call(element, value);
797
+ } else {
798
+ element.value = value;
799
+ }
800
+ }
801
+
802
+ function maybeScrollIntoView(element) {
803
+ if (!element || payload.scrollIntoView === false) {
804
+ return;
805
+ }
806
+
807
+ element.scrollIntoView({
808
+ block: "center",
809
+ inline: "center",
810
+ behavior: "instant",
811
+ });
812
+ }
813
+
814
+ function summarizeTarget(element) {
815
+ return element
816
+ ? {
817
+ tagName: element.tagName,
818
+ id: element.getAttribute("id"),
819
+ className: element.getAttribute("class"),
820
+ }
821
+ : null;
822
+ }
823
+
824
+ function getDeepActiveElement() {
825
+ let active = document.activeElement;
826
+ while (active?.shadowRoot?.activeElement) {
827
+ active = active.shadowRoot.activeElement;
828
+ }
829
+ return active;
830
+ }
831
+
832
+ function focusElement(element) {
833
+ if (typeof element.focus === "function") {
834
+ element.focus();
835
+ }
836
+
837
+ const active = getDeepActiveElement();
838
+ return Boolean(
839
+ active &&
840
+ (active === element ||
841
+ (element.isContentEditable &&
842
+ typeof active.contains === "function" &&
843
+ active.contains(element))),
844
+ );
845
+ }
846
+
847
+ function findClickablePoint(element) {
848
+ const rects =
849
+ typeof element.getClientRects === "function"
850
+ ? Array.from(element.getClientRects())
851
+ : [];
852
+ if (rects.length === 0) {
853
+ rects.push(element.getBoundingClientRect());
854
+ }
855
+
856
+ for (const rect of rects) {
857
+ const left = Math.max(rect.left, 0);
858
+ const top = Math.max(rect.top, 0);
859
+ const right = Math.min(rect.right, window.innerWidth);
860
+ const bottom = Math.min(rect.bottom, window.innerHeight);
861
+ if (right - left >= 1 && bottom - top >= 1) {
862
+ return { x: (left + right) / 2, y: (top + bottom) / 2 };
863
+ }
864
+ }
865
+
866
+ return null;
867
+ }
868
+
869
+ function hitTest(point) {
870
+ let hit = document.elementFromPoint(point.x, point.y);
871
+ while (hit?.shadowRoot) {
872
+ const inner = hit.shadowRoot.elementFromPoint(point.x, point.y);
873
+ if (!inner || inner === hit) {
874
+ break;
875
+ }
876
+ hit = inner;
877
+ }
878
+ return hit;
879
+ }
880
+
881
+ function receivesPointerAt(element, hit) {
882
+ for (let node = hit; node; node = node.parentNode ?? node.host ?? null) {
883
+ if (node === element) {
884
+ return true;
885
+ }
886
+ }
887
+
888
+ // Styled checkboxes often hide the input behind its <label>, which
889
+ // forwards the click to the control.
890
+ const label =
891
+ typeof hit?.closest === "function" ? hit.closest("label") : null;
892
+ return Boolean(label && label.control === element);
893
+ }
894
+
895
+ // Whether the page renders the element at all. innerText falls back to the
896
+ // raw text content for an element inside display: none, which the page
897
+ // does not show; unlike isVisible, size and pointer events do not matter.
898
+ function isRendered(element) {
899
+ for (let node = element; node; node = node.parentElement) {
900
+ if (getComputedStyle(node).display === "none") {
901
+ return false;
902
+ }
903
+ }
904
+ return true;
905
+ }
906
+
907
+ // Rendered and not hidden by visibility, for choosing the main content and
908
+ // links; computed visibility already reflects hidden ancestors.
909
+ function isShown(element) {
910
+ const visibility = getComputedStyle(element).visibility;
911
+ return (
912
+ isRendered(element) &&
913
+ visibility !== "hidden" &&
914
+ visibility !== "collapse"
915
+ );
916
+ }
917
+
918
+ // Readable text of one element, or of the page's main content: main or
919
+ // role=main, else a single article, else the body. Lines keep their
920
+ // breaks with runs of spaces and blank lines collapsed.
921
+ function readText() {
922
+ let root;
923
+ let source;
924
+ if (payload.selector) {
925
+ const resolved = ensureResolved(payload.selector);
926
+ if (!resolved.element) {
927
+ return resolved;
928
+ }
929
+ root = resolved.element;
930
+ source = "selector";
931
+ } else {
932
+ const main = [...document.querySelectorAll("main, [role=main]")].find(
933
+ isShown,
934
+ );
935
+ const articles = [...document.querySelectorAll("article")].filter(
936
+ isShown,
937
+ );
938
+ if (main) {
939
+ root = main;
940
+ source = "main";
941
+ } else if (articles.length === 1) {
942
+ root = articles[0];
943
+ source = "article";
944
+ } else {
945
+ root = document.body ?? document.documentElement;
946
+ source = "body";
947
+ }
948
+ }
949
+
950
+ const shown = source !== "selector" || isRendered(root);
951
+ const raw = !shown
952
+ ? ""
953
+ : typeof root.innerText === "string"
954
+ ? root.innerText
955
+ : root.textContent;
956
+ const text = (raw ?? "")
957
+ .split("\n")
958
+ .map((line) => line.replace(/[ \t\u00a0]+/g, " ").trim())
959
+ .join("\n")
960
+ .replace(/\n{3,}/g, "\n\n")
961
+ .trim();
962
+ const result = {
963
+ browserFamily: payload.browserFamily,
964
+ url: location.href,
965
+ title: document.title,
966
+ source,
967
+ ...(payload.selector
968
+ ? { selector: payload.selector, found: true, visible: shown }
969
+ : {}),
970
+ text: text.slice(0, payload.maxChars),
971
+ totalChars: text.length,
972
+ truncated: text.length > payload.maxChars,
973
+ };
974
+
975
+ if (payload.links) {
976
+ const seen = new Set();
977
+ const links = [];
978
+ for (const anchor of root.querySelectorAll("a[href]")) {
979
+ const href = anchor.href;
980
+ if (!/^https?:/i.test(href) || seen.has(href) || !isShown(anchor)) {
981
+ continue;
982
+ }
983
+ seen.add(href);
984
+ links.push({
985
+ text: normalizeText(
986
+ anchor.innerText || anchor.getAttribute("aria-label") || "",
987
+ ),
988
+ href,
989
+ });
990
+ }
991
+ result.links = links.slice(0, payload.maxLinks);
992
+ result.moreLinks = Math.max(0, links.length - payload.maxLinks);
993
+ }
994
+
995
+ return result;
996
+ }
997
+
998
+ function runAction() {
999
+ switch (payload.action) {
1000
+ case "read_text":
1001
+ return readText();
1002
+ case "controls_snapshot":
1003
+ return {
1004
+ browserFamily: payload.browserFamily,
1005
+ url: location.href,
1006
+ title: document.title,
1007
+ ...snapshotControls(),
1008
+ };
1009
+ case "page_state":
1010
+ return {
1011
+ browserFamily: payload.browserFamily,
1012
+ page: describePage(),
1013
+ };
1014
+ case "inspect": {
1015
+ const resolved = ensureResolved(payload.selector);
1016
+ if (!resolved.element) {
1017
+ return resolved;
1018
+ }
1019
+
1020
+ maybeScrollIntoView(resolved.element);
1021
+
1022
+ return {
1023
+ browserFamily: payload.browserFamily,
1024
+ selector: payload.selector,
1025
+ found: true,
1026
+ node: describeElement(resolved.element, resolved),
1027
+ ...(Array.isArray(payload.textChecks)
1028
+ ? {
1029
+ textMatches: checkElementText(
1030
+ resolved.element,
1031
+ payload.textChecks,
1032
+ ),
1033
+ }
1034
+ : {}),
1035
+ };
1036
+ }
1037
+ case "pointer_target": {
1038
+ const resolved = ensureResolved(payload.selector);
1039
+ if (!resolved.element) {
1040
+ return resolved;
1041
+ }
1042
+
1043
+ maybeScrollIntoView(resolved.element);
1044
+ const point = findClickablePoint(resolved.element);
1045
+ const hit = point ? hitTest(point) : null;
1046
+ const receivesEvents = Boolean(
1047
+ hit && receivesPointerAt(resolved.element, hit),
1048
+ );
1049
+
1050
+ return {
1051
+ browserFamily: payload.browserFamily,
1052
+ selector: payload.selector,
1053
+ found: true,
1054
+ point,
1055
+ receivesEvents,
1056
+ obscuredBy: receivesEvents ? null : summarizeTarget(hit),
1057
+ node: describeElement(resolved.element, resolved),
1058
+ };
1059
+ }
1060
+ case "prepare_type": {
1061
+ const resolved = ensureResolved(payload.selector);
1062
+ if (!resolved.element) {
1063
+ return resolved;
1064
+ }
1065
+
1066
+ const element = resolved.element;
1067
+ const clear = payload.clear !== false;
1068
+ maybeScrollIntoView(element);
1069
+
1070
+ const isTextControl =
1071
+ element instanceof HTMLInputElement ||
1072
+ element instanceof HTMLTextAreaElement;
1073
+ if (!isEditable(element) || isDisabled(element)) {
1074
+ throw new Error("Resolved element is not editable");
1075
+ }
1076
+ if (element.readOnly === true) {
1077
+ throw new Error("Resolved element is read-only");
1078
+ }
1079
+
1080
+ // Pickers such as date or color inputs do not accept typed text, so
1081
+ // their value is set directly.
1082
+ if (
1083
+ element instanceof HTMLInputElement &&
1084
+ VALUE_ONLY_INPUT_TYPES.includes((element.type || "").toLowerCase())
1085
+ ) {
1086
+ focusElement(element);
1087
+ setNativeValue(element, payload.text);
1088
+ dispatchInputEvents(element);
1089
+ return {
1090
+ browserFamily: payload.browserFamily,
1091
+ selector: payload.selector,
1092
+ found: true,
1093
+ method: "value",
1094
+ typedText: payload.text,
1095
+ node: describeElement(element, resolved),
1096
+ };
1097
+ }
1098
+
1099
+ if (!focusElement(element)) {
1100
+ throw new Error("Could not focus the resolved element");
1101
+ }
1102
+
1103
+ if (isTextControl) {
1104
+ if (clear) {
1105
+ element.select();
1106
+ } else {
1107
+ const end = element.value.length;
1108
+ try {
1109
+ element.setSelectionRange(end, end);
1110
+ } catch {
1111
+ // email and number inputs do not support selection ranges.
1112
+ }
1113
+ }
1114
+ } else {
1115
+ const range = document.createRange();
1116
+ range.selectNodeContents(element);
1117
+ if (!clear) {
1118
+ range.collapse(false);
1119
+ }
1120
+ const selection = window.getSelection();
1121
+ selection.removeAllRanges();
1122
+ selection.addRange(range);
1123
+ }
1124
+
1125
+ return {
1126
+ browserFamily: payload.browserFamily,
1127
+ selector: payload.selector,
1128
+ found: true,
1129
+ method: "native",
1130
+ node: describeElement(element, resolved),
1131
+ };
1132
+ }
1133
+ case "select": {
1134
+ const resolved = ensureResolved(payload.selector);
1135
+ if (!resolved.element) {
1136
+ return resolved;
1137
+ }
1138
+
1139
+ if (!(resolved.element instanceof HTMLSelectElement)) {
1140
+ throw new Error("Resolved element is not a <select>");
1141
+ }
1142
+
1143
+ const option =
1144
+ Array.from(resolved.element.options).find(
1145
+ (candidate) =>
1146
+ (payload.value &&
1147
+ (candidate.value === payload.value ||
1148
+ candidate.text === payload.value)) ||
1149
+ (payload.label &&
1150
+ normalizeText(candidate.text).includes(
1151
+ normalizeText(payload.label),
1152
+ )),
1153
+ ) ?? null;
1154
+
1155
+ if (!option) {
1156
+ throw new Error("No matching <option> found");
1157
+ }
1158
+
1159
+ resolved.element.value = option.value;
1160
+ dispatchInputEvents(resolved.element);
1161
+
1162
+ return {
1163
+ browserFamily: payload.browserFamily,
1164
+ selector: payload.selector,
1165
+ found: true,
1166
+ selectedValue: option.value,
1167
+ selectedLabel: option.text,
1168
+ node: describeElement(resolved.element, resolved),
1169
+ };
1170
+ }
1171
+ case "focus": {
1172
+ if (payload.selector) {
1173
+ const resolved = ensureResolved(payload.selector);
1174
+ if (!resolved.element) {
1175
+ return resolved;
1176
+ }
1177
+
1178
+ maybeScrollIntoView(resolved.element);
1179
+ if (!focusElement(resolved.element)) {
1180
+ throw new Error("Could not focus the resolved element");
1181
+ }
1182
+ }
1183
+
1184
+ return {
1185
+ browserFamily: payload.browserFamily,
1186
+ selector: payload.selector ?? null,
1187
+ found: true,
1188
+ target: summarizeTarget(getDeepActiveElement() ?? document.body),
1189
+ };
1190
+ }
1191
+ case "scroll": {
1192
+ if (payload.selector) {
1193
+ const resolved = ensureResolved(payload.selector);
1194
+ if (!resolved.element) {
1195
+ return resolved;
1196
+ }
1197
+
1198
+ resolved.element.scrollIntoView({
1199
+ block: payload.block || "center",
1200
+ inline: "nearest",
1201
+ });
1202
+
1203
+ return {
1204
+ browserFamily: payload.browserFamily,
1205
+ selector: payload.selector,
1206
+ found: true,
1207
+ scrolled: true,
1208
+ node: describeElement(resolved.element, resolved),
1209
+ };
1210
+ }
1211
+
1212
+ window.scrollBy({
1213
+ left: Number.isFinite(payload.deltaX) ? payload.deltaX : 0,
1214
+ top: Number.isFinite(payload.deltaY) ? payload.deltaY : 0,
1215
+ behavior: "instant",
1216
+ });
1217
+
1218
+ return {
1219
+ browserFamily: payload.browserFamily,
1220
+ scrolled: true,
1221
+ pageXOffset: window.pageXOffset,
1222
+ pageYOffset: window.pageYOffset,
1223
+ viewport: {
1224
+ width: window.innerWidth,
1225
+ height: window.innerHeight,
1226
+ },
1227
+ };
1228
+ }
1229
+ case "network_snapshot": {
1230
+ const entries = [
1231
+ ...performance.getEntriesByType("navigation"),
1232
+ ...performance.getEntriesByType("resource"),
1233
+ ].map((entry, index) => ({
1234
+ requestId: `snapshot-${index + 1}-${entry.name || "entry"}`,
1235
+ url: entry.name || location.href,
1236
+ method: entry.entryType === "navigation" ? "GET" : "GET",
1237
+ resourceType: entry.initiatorType || entry.entryType || null,
1238
+ startedAt: entry.startTime ?? 0,
1239
+ completedAt: (entry.startTime ?? 0) + (entry.duration ?? 0),
1240
+ duration: entry.duration ?? null,
1241
+ transferSize:
1242
+ typeof entry.transferSize === "number" ? entry.transferSize : null,
1243
+ encodedBodySize:
1244
+ typeof entry.encodedBodySize === "number"
1245
+ ? entry.encodedBodySize
1246
+ : null,
1247
+ decodedBodySize:
1248
+ typeof entry.decodedBodySize === "number"
1249
+ ? entry.decodedBodySize
1250
+ : null,
1251
+ }));
1252
+
1253
+ return {
1254
+ browserFamily: payload.browserFamily,
1255
+ entries,
1256
+ };
1257
+ }
1258
+ case "cookie_snapshot":
1259
+ return {
1260
+ browserFamily: payload.browserFamily,
1261
+ cookies: parseDocumentCookies(),
1262
+ };
1263
+ case "storage_snapshot":
1264
+ return {
1265
+ browserFamily: payload.browserFamily,
1266
+ storage: {
1267
+ localStorage: snapshotStorage(localStorage, "localStorage"),
1268
+ sessionStorage: snapshotStorage(sessionStorage, "sessionStorage"),
1269
+ },
1270
+ };
1271
+ case "debug_report": {
1272
+ const cookies = parseDocumentCookies();
1273
+ return {
1274
+ browserFamily: payload.browserFamily,
1275
+ page: describePage(),
1276
+ cookies: {
1277
+ totalEntries: cookies.totalEntries,
1278
+ returnedEntries: cookies.returnedEntries,
1279
+ truncated: cookies.truncated,
1280
+ sampleNames: cookies.entries.map((entry) => entry.name),
1281
+ },
1282
+ storage: {
1283
+ localStorage: summarizeStorage(localStorage, "localStorage"),
1284
+ sessionStorage: summarizeStorage(sessionStorage, "sessionStorage"),
1285
+ },
1286
+ };
1287
+ }
1288
+ case "restore_snapshot": {
1289
+ const snapshot = payload.snapshot ?? {};
1290
+ const clearStorage = payload.clearStorage === true;
1291
+ const snapshotUrl = snapshot.page?.url ?? null;
1292
+ const snapshotOrigin = snapshotUrl ? new URL(snapshotUrl).origin : null;
1293
+ const currentOrigin = location.origin;
1294
+
1295
+ if (snapshotOrigin && snapshotOrigin !== currentOrigin) {
1296
+ throw new Error(
1297
+ "Snapshot origin " +
1298
+ snapshotOrigin +
1299
+ " does not match current origin " +
1300
+ currentOrigin,
1301
+ );
1302
+ }
1303
+
1304
+ const restoreEntries = (storage, entries) => {
1305
+ const safeEntries = Array.isArray(entries)
1306
+ ? entries.slice(0, 100)
1307
+ : [];
1308
+ if (clearStorage) {
1309
+ storage.clear();
1310
+ }
1311
+
1312
+ for (const entry of safeEntries) {
1313
+ if (!entry || typeof entry.key !== "string") {
1314
+ continue;
1315
+ }
1316
+
1317
+ storage.setItem(
1318
+ entry.key,
1319
+ typeof entry.value === "string" ? entry.value : "",
1320
+ );
1321
+ }
1322
+
1323
+ return safeEntries.length;
1324
+ };
1325
+
1326
+ const restoreCookies = (entries) => {
1327
+ const safeEntries = Array.isArray(entries)
1328
+ ? entries.slice(0, 100)
1329
+ : [];
1330
+ for (const entry of safeEntries) {
1331
+ if (!entry || typeof entry.name !== "string") {
1332
+ continue;
1333
+ }
1334
+
1335
+ const encodedName = encodeURIComponent(entry.name);
1336
+ const encodedValue = encodeURIComponent(
1337
+ typeof entry.value === "string" ? entry.value : "",
1338
+ );
1339
+ document.cookie =
1340
+ encodedName + "=" + encodedValue + "; path=/; SameSite=Lax";
1341
+ }
1342
+
1343
+ return safeEntries.length;
1344
+ };
1345
+
1346
+ return {
1347
+ browserFamily: payload.browserFamily,
1348
+ restoredAt: new Date().toISOString(),
1349
+ clearStorage,
1350
+ snapshotOrigin: snapshotOrigin ?? currentOrigin,
1351
+ currentOrigin,
1352
+ restored: {
1353
+ cookies: restoreCookies(snapshot.cookies?.entries),
1354
+ localStorage: restoreEntries(
1355
+ localStorage,
1356
+ snapshot.storage?.localStorage?.entries,
1357
+ ),
1358
+ sessionStorage: restoreEntries(
1359
+ sessionStorage,
1360
+ snapshot.storage?.sessionStorage?.entries,
1361
+ ),
1362
+ },
1363
+ page: describePage(),
1364
+ };
1365
+ }
1366
+ default:
1367
+ throw new Error(`Unsupported page action: ${payload.action}`);
1368
+ }
1369
+ }
1370
+
1371
+ return runAction();
1372
+ }