@jackwener/browsermcp 0.0.40-embedded.0 → 0.0.41

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 (103) hide show
  1. package/CHANGELOG.md +2 -52
  2. package/README.md +0 -91
  3. package/dist/docs/api-use.md +2 -2
  4. package/dist/src/api/tab.js +2 -2
  5. package/dist/src/api/tab.js.map +1 -1
  6. package/dist/src/backends/extension-page.js +1 -1
  7. package/dist/src/backends/extension-page.js.map +1 -1
  8. package/dist/src/docs/manifest.js +3 -6
  9. package/dist/src/docs/manifest.js.map +1 -1
  10. package/dist/src/shared/engine.js +4 -4
  11. package/dist/src/shared/engine.js.map +1 -1
  12. package/docs/api-use.md +2 -2
  13. package/extension/dist/background.js +4 -4
  14. package/extension/dist/manifest.json +1 -1
  15. package/extension/dist/page.js +45 -45
  16. package/package.json +2 -11
  17. package/dist/src/api/action-input.d.ts +0 -87
  18. package/dist/src/api/agent.d.ts +0 -10
  19. package/dist/src/api/api.d.ts +0 -54
  20. package/dist/src/api/browser.d.ts +0 -93
  21. package/dist/src/api/commands.d.ts +0 -514
  22. package/dist/src/api/content-wait.d.ts +0 -18
  23. package/dist/src/api/context.d.ts +0 -7
  24. package/dist/src/api/diff.d.ts +0 -8
  25. package/dist/src/api/errors.d.ts +0 -14
  26. package/dist/src/api/network.d.ts +0 -10
  27. package/dist/src/api/observation.d.ts +0 -4
  28. package/dist/src/api/streams.d.ts +0 -13
  29. package/dist/src/api/tab.d.ts +0 -337
  30. package/dist/src/api/webmcp.d.ts +0 -19
  31. package/dist/src/backends/backend.d.ts +0 -14
  32. package/dist/src/backends/browser-helpers.d.ts +0 -17
  33. package/dist/src/backends/extension-page.d.ts +0 -5
  34. package/dist/src/backends/managed-page.d.ts +0 -50
  35. package/dist/src/backends/page-transport.d.ts +0 -10
  36. package/dist/src/backends/page-types.d.ts +0 -82
  37. package/dist/src/docs/embedded.d.ts +0 -2
  38. package/dist/src/docs/embedded.js +0 -40
  39. package/dist/src/docs/embedded.js.map +0 -1
  40. package/dist/src/docs/manifest.d.ts +0 -23
  41. package/dist/src/docs/surface.d.ts +0 -12
  42. package/dist/src/electron/backend.d.ts +0 -50
  43. package/dist/src/electron/backend.js +0 -377
  44. package/dist/src/electron/backend.js.map +0 -1
  45. package/dist/src/electron/chrome.d.ts +0 -24
  46. package/dist/src/electron/chrome.js +0 -133
  47. package/dist/src/electron/chrome.js.map +0 -1
  48. package/dist/src/electron/driver.d.ts +0 -70
  49. package/dist/src/electron/driver.js +0 -316
  50. package/dist/src/electron/driver.js.map +0 -1
  51. package/dist/src/electron/event-buffer.d.ts +0 -16
  52. package/dist/src/electron/event-buffer.js +0 -59
  53. package/dist/src/electron/event-buffer.js.map +0 -1
  54. package/dist/src/electron/page.js +0 -1030
  55. package/dist/src/electron/registry.d.ts +0 -104
  56. package/dist/src/electron/registry.js +0 -316
  57. package/dist/src/electron/registry.js.map +0 -1
  58. package/dist/src/electron/streams.d.ts +0 -16
  59. package/dist/src/electron/streams.js +0 -48
  60. package/dist/src/electron/streams.js.map +0 -1
  61. package/dist/src/embedded/index.d.ts +0 -39
  62. package/dist/src/embedded/index.js +0 -72
  63. package/dist/src/embedded/index.js.map +0 -1
  64. package/dist/src/host/bridge.d.ts +0 -50
  65. package/dist/src/host/doctor.d.ts +0 -34
  66. package/dist/src/host/extension.d.ts +0 -3
  67. package/dist/src/host/host.d.ts +0 -3
  68. package/dist/src/host/ipc.d.ts +0 -14
  69. package/dist/src/host/jsonc-config.d.ts +0 -1
  70. package/dist/src/host/launch.d.ts +0 -11
  71. package/dist/src/host/native-messaging.d.ts +0 -28
  72. package/dist/src/host/opencode.d.ts +0 -6
  73. package/dist/src/host/pi.d.ts +0 -6
  74. package/dist/src/host/registration.d.ts +0 -24
  75. package/dist/src/host/setup.d.ts +0 -7
  76. package/dist/src/host/socket.d.ts +0 -25
  77. package/dist/src/host/state.d.ts +0 -39
  78. package/dist/src/launcher/stdio.d.ts +0 -3
  79. package/dist/src/lib/paths.d.ts +0 -1
  80. package/dist/src/lib/sources.d.ts +0 -5
  81. package/dist/src/main.d.ts +0 -2
  82. package/dist/src/mcp/catalog.d.ts +0 -202
  83. package/dist/src/mcp/js-session.d.ts +0 -64
  84. package/dist/src/mcp/server.d.ts +0 -15
  85. package/dist/src/protocol.d.ts +0 -329
  86. package/dist/src/recon/analyzer.d.ts +0 -43
  87. package/dist/src/recon/discover.d.ts +0 -48
  88. package/dist/src/runtime/runtime.d.ts +0 -148
  89. package/dist/src/shared/api-contract.d.ts +0 -86
  90. package/dist/src/shared/aria-tree.d.ts +0 -2
  91. package/dist/src/shared/closed-shadow.d.ts +0 -10
  92. package/dist/src/shared/element-ref.d.ts +0 -4
  93. package/dist/src/shared/engine.d.ts +0 -62
  94. package/dist/src/shared/inflight.d.ts +0 -14
  95. package/dist/src/shared/injected-source.d.ts +0 -2
  96. package/dist/src/shared/page-contract.d.ts +0 -272
  97. package/dist/src/sites/define.d.ts +0 -28
  98. package/dist/src/sites/drafts.d.ts +0 -39
  99. package/dist/src/sites/executor.d.ts +0 -34
  100. package/dist/src/sites/loader.d.ts +0 -101
  101. package/dist/src/sites/manifest.d.ts +0 -5
  102. package/dist/src/sites/schema.d.ts +0 -11
  103. package/dist/src/version.d.ts +0 -2
@@ -1,1030 +0,0 @@
1
- "use strict";
2
- (() => {
3
- // src/shared/page-contract.ts
4
- var ENGINE_GLOBAL = "__browsermcpInjected";
5
- var PAGE_GLOBAL = "__browsermcpPage";
6
-
7
- // src/shared/element-ref.ts
8
- var ELEMENT_REF_SOURCE = String.raw`(?:e[a-f0-9]{16}_\d+|(?:f\d+)?e\d+)`;
9
- var ELEMENT_REF = new RegExp(`^${ELEMENT_REF_SOURCE}$`);
10
- var ARIA_REF_LINE = new RegExp(String.raw`^(\s*-\s'?[\w-]+(?: "(?:[^"\\]|\\.)*"| /.*?/)?(?: \[(?!ref=)[^\]\r\n]+\])* \[ref=)(${ELEMENT_REF_SOURCE})(\](?: \[[^\]\r\n]+\])*'?)(:.*)?$`);
11
-
12
- // extension/src/page/index.ts
13
- function injected() {
14
- const i = globalThis[ENGINE_GLOBAL];
15
- if (!i) throw new Error("engine_missing");
16
- return i;
17
- }
18
- function query(selector, root = document) {
19
- const i = injected();
20
- const run = (parsed, scope) => {
21
- const at = parsed.parts.findIndex((part) => part.name === "aria-ref");
22
- if (at < 0) return i.querySelectorAll(parsed, scope);
23
- const el = requireRef(parsed.parts[at].body);
24
- const scopes = at ? run({ ...parsed, parts: parsed.parts.slice(0, at) }, scope) : [scope];
25
- const inside = scopes.some((parent) => {
26
- let node = el;
27
- for (; ; ) {
28
- if (parent === node || parent.contains(node)) return true;
29
- const host = node.getRootNode().host;
30
- if (!host) return false;
31
- node = host;
32
- }
33
- });
34
- if (!inside) return [];
35
- return at + 1 === parsed.parts.length ? [el] : run({ ...parsed, parts: parsed.parts.slice(at + 1) }, el);
36
- };
37
- return run(i.parseSelector(selector), root);
38
- }
39
- function stateOf(el, name) {
40
- try {
41
- const r = injected().elementState(el, name);
42
- return { matches: r.matches === true, received: String(r.received ?? "") };
43
- } catch (e) {
44
- return { matches: false, received: "error:" + (e?.message || String(e)) };
45
- }
46
- }
47
- var is = (el, name) => stateOf(el, name).matches;
48
- function box(el) {
49
- const r = el.getBoundingClientRect();
50
- return { x: Math.round(r.left), y: Math.round(r.top), w: Math.round(r.width), h: Math.round(r.height) };
51
- }
52
- var text = (el) => (el.innerText || el.textContent || "").replace(/\s+/g, " ").trim();
53
- function replaySelector(el) {
54
- try {
55
- return injected().generateSelector(el, { testIdAttributeName: "data-testid" }).selector;
56
- } catch {
57
- return null;
58
- }
59
- }
60
- function roleOf(el) {
61
- try {
62
- const u = injected().utils;
63
- return u?.getAriaRole && u.getAriaRole(el) || el.getAttribute("role") || "";
64
- } catch {
65
- return el.getAttribute("role") || "";
66
- }
67
- }
68
- function nameOf(el) {
69
- try {
70
- const u = injected().utils;
71
- return u?.getElementAccessibleName ? String(u.getElementAccessibleName(el, false) || "") : u?.getElementAccessibleNameText ? String(u.getElementAccessibleNameText(el, false) || "") : "";
72
- } catch {
73
- return "";
74
- }
75
- }
76
- var refEngine = null;
77
- var refScope = "";
78
- var stableId = /* @__PURE__ */ new WeakMap();
79
- var nextStableId = 1;
80
- var refToEl = /* @__PURE__ */ new Map();
81
- var annotatedRefs = [];
82
- function resetRefsIfEngineChanged() {
83
- const engine = injected();
84
- if (engine === refEngine) return;
85
- refEngine = engine;
86
- refScope = [...crypto.getRandomValues(new Uint8Array(8))].map((n) => n.toString(16).padStart(2, "0")).join("");
87
- stableId = /* @__PURE__ */ new WeakMap();
88
- nextStableId = 1;
89
- refToEl.clear();
90
- annotatedRefs = [];
91
- }
92
- function liveElement(ref) {
93
- resetRefsIfEngineChanged();
94
- const el = refToEl.get(ref)?.deref();
95
- return el?.isConnected && el.ownerDocument === document ? el : void 0;
96
- }
97
- function pageError(code, message, hint, data) {
98
- return Object.assign(new Error(message), { code, hint, ...data && { data } });
99
- }
100
- function requireRef(ref) {
101
- const el = liveElement(ref);
102
- if (!el) throw pageError("stale_ref", `Element ref ${ref} is stale or belongs to another document/frame.`, "Observe again in the intended frame and use a returned ref with its frame path.");
103
- return el;
104
- }
105
- function stableRefOf(el) {
106
- resetRefsIfEngineChanged();
107
- let ref = stableId.get(el);
108
- if (ref === void 0) {
109
- ref = `e${refScope}_${nextStableId++}`;
110
- stableId.set(el, ref);
111
- if (nextStableId % 512 === 0) {
112
- for (const [key, value] of refToEl) {
113
- const node = value.deref();
114
- if (!node?.isConnected || node.ownerDocument !== document) refToEl.delete(key);
115
- }
116
- }
117
- }
118
- refToEl.set(ref, new WeakRef(el));
119
- return ref;
120
- }
121
- function ariaRefOf(el) {
122
- return stableRefOf(el);
123
- }
124
- var REGION_ROLES = /* @__PURE__ */ new Set(["form", "dialog", "alertdialog", "region", "navigation", "main", "complementary", "banner", "contentinfo", "search", "group", "listitem", "row", "article", "tabpanel", "menu", "list", "table"]);
125
- function regionOf(el) {
126
- for (let n = el; ; ) {
127
- const parent = n.parentElement;
128
- if (!parent) {
129
- const root = n.getRootNode();
130
- if (!(root instanceof ShadowRoot)) return "page";
131
- const host = root.host;
132
- const label = host.getAttribute("aria-label");
133
- return `shadow root of <${host.localName}${host.id ? `#${host.id}` : ""}>${label ? ` "${label.slice(0, 60)}"` : ""}`;
134
- }
135
- n = parent;
136
- const role = roleOf(n);
137
- const name = REGION_ROLES.has(role) ? nameOf(n).replace(/\s+/g, " ").trim().slice(0, 60) : "";
138
- if (name || ["form", "dialog", "alertdialog", "navigation", "main", "search"].includes(role)) return `${role}${name ? ` "${name}"` : ""}`;
139
- }
140
- }
141
- var candidate = (el) => ({ ref: ariaRefOf(el), role: roleOf(el), name: nameOf(el).replace(/\s+/g, " ").trim().slice(0, 80), within: regionOf(el), tag: el.tagName.toLowerCase(), text: text(el).slice(0, 80), visible: is(el, "visible"), box: box(el) });
142
- function ambiguity(n, selector, visibleN, matches) {
143
- const candidates = matches.slice(0, 8).map(candidate);
144
- const list = candidates.map((c) => `[ref=${c.ref}] ${c.role || c.tag}${c.name ? ` "${c.name}"` : ""} in ${c.within}${c.visible ? "" : " (hidden)"}`).join("; ");
145
- return { code: "selector_ambiguous", message: `${n} elements match ${selector}${visibleN ? ` (${visibleN} visible)` : ""}: ${list}${n > 8 ? `; \u2026${n - 8} more` : ""}`, hint: "Act on one of these refs, or scope the locator with within (a container ref or selector).", candidates };
146
- }
147
- var actionElement = null;
148
- function actionTarget() {
149
- const el = actionElement;
150
- return el?.isConnected && el.ownerDocument === document ? el : null;
151
- }
152
- var actEl = actionTarget;
153
- function rememberActionTarget(el) {
154
- actionElement = el;
155
- }
156
- function clearActionTarget() {
157
- actionElement = null;
158
- }
159
- var ALIGN_BLOCKS = /* @__PURE__ */ new Set(["start", "center", "end", "nearest"]);
160
- async function resolve(args) {
161
- const { selector, fallback, strict, states, align } = args;
162
- let usedSelector = selector;
163
- let matches = query(selector);
164
- if (!matches.length && fallback) {
165
- usedSelector = fallback;
166
- matches = query(fallback);
167
- }
168
- if (!matches.length) return { error: { code: "not_found", message: `no element matches ${selector}` }, retry: true };
169
- let el = matches[0];
170
- if (matches.length > 1 && strict) {
171
- const visible = matches.filter((m) => is(m, "visible"));
172
- if (visible.length === 1) el = visible[0];
173
- else return { error: ambiguity(matches.length, selector, visible.length, visible.length > 1 ? visible : matches), retry: false };
174
- }
175
- for (const st of states) {
176
- const r = stateOf(el, st);
177
- if (r.received === "error:notconnected") return { error: { code: "stale_ref", message: "element detached during resolution" }, retry: true };
178
- if (!r.matches) return { error: { code: st === "visible" ? "not_visible" : st === "enabled" ? "not_enabled" : "not_editable", message: `element is not ${st}${r.received.startsWith("error:") ? ` (${r.received.slice(6)})` : ""}`, candidates: [candidate(el)] }, retry: true };
179
- }
180
- try {
181
- el.scrollIntoView({ block: ALIGN_BLOCKS.has(align.block) ? align.block : "center", inline: ALIGN_BLOCKS.has(align.inline) ? align.inline : "nearest", behavior: "instant" });
182
- } catch {
183
- }
184
- let prev = null;
185
- let stable = 0;
186
- const t0 = performance.now();
187
- for (; ; ) {
188
- const r = el.getBoundingClientRect();
189
- const cur = [r.left, r.top, r.width, r.height].map(Math.round).join(",");
190
- stable = prev === cur ? stable + 1 : 0;
191
- prev = cur;
192
- if (stable >= 1 || performance.now() - t0 > 700) break;
193
- await new Promise((res) => setTimeout(res, 40));
194
- }
195
- for (const st of states) if (!is(el, st)) return { error: { code: `not_${st}`, message: `element is not ${st} after scrolling` }, retry: true };
196
- const b = el.getBoundingClientRect();
197
- if (b.width <= 0 || b.height <= 0) return { error: { code: "not_visible", message: "element has no clickable box", hint: 'Retry this same target once with method:"dom". That runs HTMLElement.click() and sends no mouse event. Do not send it after a click that already returned ok.' }, retry: true };
198
- const x = Math.max(0, b.left + b.width / 2), y = Math.max(0, b.top + b.height / 2);
199
- if (x > innerWidth || y > innerHeight) return { error: { code: "not_visible", message: "element is outside the viewport" }, retry: true };
200
- const tag = el.tagName.toLowerCase();
201
- const type = el.type;
202
- const checkable = tag === "input" && (type === "checkbox" || type === "radio") || ["checkbox", "radio", "switch"].includes(el.getAttribute("role") || "");
203
- const hit = injected().expectHitTarget({ x, y }, el);
204
- rememberActionTarget(el);
205
- return {
206
- ok: true,
207
- x,
208
- y,
209
- matches_n: matches.length,
210
- tag,
211
- hit: hit === "done" ? "target" : "other",
212
- blocker: hit === "done" ? null : hit && hit.hitTargetDescription || "another element",
213
- editable: is(el, "editable"),
214
- checkable,
215
- checked: checkable ? is(el, "checked") : false,
216
- isSelect: tag === "select",
217
- ref: ariaRefOf(el),
218
- selector: replaySelector(el),
219
- usedSelector
220
- };
221
- }
222
- function pointInfo(args) {
223
- const el = document.elementFromPoint(args.x, args.y);
224
- if (!el) return null;
225
- rememberActionTarget(el);
226
- const tag = el.tagName.toLowerCase();
227
- const editable = Boolean(el.isContentEditable || (tag === "input" || tag === "textarea") && !el.readOnly && !el.disabled);
228
- return { tag, editable, isSelect: tag === "select" };
229
- }
230
- var target = () => {
231
- const el = actEl();
232
- if (!el) throw new Error("error:notconnected");
233
- return el;
234
- };
235
- var retarget = (el) => injected().retarget(el, "follow-label") || el;
236
- function targetHasFocus(el) {
237
- const active = el.getRootNode().activeElement;
238
- if (!el.isConnected || !active) return false;
239
- return active === el || el.contains(active) || el.isContentEditable && active.isContentEditable && active.contains(el);
240
- }
241
- function focus() {
242
- const el = actEl();
243
- if (!el) return "error:notconnected";
244
- const t = retarget(el);
245
- let focusTarget = t;
246
- while (focusTarget.isContentEditable && focusTarget.parentElement?.isContentEditable) focusTarget = focusTarget.parentElement;
247
- const result = String(injected().focusNode(focusTarget, false));
248
- if (result !== "done") return result;
249
- return t === document.body || t === document.documentElement || targetHasFocus(t) ? "done" : "error:focusfailed";
250
- }
251
- function readValue() {
252
- const el = actEl();
253
- if (!el) return null;
254
- const t = retarget(el);
255
- return t.isContentEditable ? t.textContent ?? "" : t.value ?? null;
256
- }
257
- function fill(args) {
258
- const el = actEl();
259
- if (!el) return "error:notconnected";
260
- try {
261
- if (retarget(el).isContentEditable) {
262
- const focused = focus();
263
- if (focused !== "done") return focused;
264
- }
265
- const result = String(injected().fill(el, args.value));
266
- return result === "needsinput" && !targetHasFocus(retarget(el)) ? "error:focusfailed" : result;
267
- } catch (e) {
268
- return "error:" + (e?.message || String(e));
269
- }
270
- }
271
- function isChecked() {
272
- const el = actEl();
273
- if (!el) return null;
274
- const r = stateOf(el, "checked");
275
- return r.received.startsWith("error:") ? null : r.matches;
276
- }
277
- function select(args) {
278
- const el = actEl();
279
- if (!el) return { error: "gone" };
280
- const i = injected();
281
- let r = i.selectOptions(el, [{ valueOrLabel: args.value }]);
282
- if (r === "error:optionsnotfound" && /^\d+$/.test(args.value)) r = i.selectOptions(el, [{ index: Number(args.value) }]);
283
- if (typeof r === "string" && r.startsWith("error:")) {
284
- const available = [...el.options ?? []].map((o) => o.label || o.value).slice(0, 50);
285
- return { error: r.slice(6), available };
286
- }
287
- return { selected: Array.isArray(r) ? r.map(String) : [] };
288
- }
289
- function caretToEnd() {
290
- const el = retarget(target());
291
- if (el.isContentEditable) {
292
- const range = el.ownerDocument.createRange();
293
- range.selectNodeContents(el);
294
- range.collapse(false);
295
- const selection = el.ownerDocument.getSelection();
296
- selection?.removeAllRanges();
297
- selection?.addRange(range);
298
- } else {
299
- const input = el;
300
- if (typeof input.setSelectionRange === "function") {
301
- try {
302
- input.setSelectionRange(input.value.length, input.value.length);
303
- } catch {
304
- }
305
- }
306
- }
307
- }
308
- function resolveUpload(args) {
309
- let matches = query(args.selector);
310
- if (!matches.length && args.fallback) matches = query(args.fallback);
311
- if (!matches.length) return { error: { code: "not_found", message: "Upload target was not found. Observe again for a fresh file-input ref." } };
312
- if (matches.length !== 1) return { error: { code: "selector_ambiguous", message: `${matches.length} upload targets match`, candidates: matches.slice(0, 8).map(candidate) } };
313
- const el = matches[0];
314
- const direct = el instanceof HTMLInputElement && el.type === "file" ? [el] : [];
315
- const controlled = el instanceof HTMLLabelElement && el.control instanceof HTMLInputElement && el.control.type === "file" ? [el.control] : [];
316
- const nested = [...el.querySelectorAll("input[type=file]")];
317
- const inForm = el.closest("form")?.querySelectorAll("input[type=file]") ?? [];
318
- const candidates = [.../* @__PURE__ */ new Set([...direct, ...controlled, ...nested, ...inForm])];
319
- if (!candidates.length) candidates.push(...document.querySelectorAll("input[type=file]"));
320
- if (candidates.length !== 1) return { error: { code: candidates.length ? "selector_ambiguous" : "not_a_file_input", message: candidates.length ? "Several file inputs are available. Target one file-input ref from tab_observe." : "No file input is associated with this target." } };
321
- const input = candidates[0];
322
- if (input.disabled) return { error: { code: "not_enabled", message: "The file input is disabled." } };
323
- if (args.files > 1 && !input.multiple) return { error: { code: "invalid_args", message: "This file input accepts only one file." } };
324
- rememberActionTarget(input);
325
- return { ok: true, ref: ariaRefOf(input), selector: replaySelector(input), matches_n: 1 };
326
- }
327
- function fileSelectionCount() {
328
- const el = actEl();
329
- return el instanceof HTMLInputElement ? el.files?.length ?? 0 : 0;
330
- }
331
- var nativeShadowRoot = Object.getOwnPropertyDescriptor(Element.prototype, "shadowRoot").get;
332
- var adoptedRoots = /* @__PURE__ */ new WeakMap();
333
- Object.defineProperty(Element.prototype, "shadowRoot", {
334
- configurable: true,
335
- enumerable: true,
336
- get() {
337
- return nativeShadowRoot.call(this) ?? adoptedRoots.get(this) ?? null;
338
- }
339
- });
340
- var SHADOW_HOST_TAGS = /* @__PURE__ */ new Set(["ARTICLE", "ASIDE", "BLOCKQUOTE", "BODY", "DIV", "FOOTER", "H1", "H2", "H3", "H4", "H5", "H6", "HEADER", "MAIN", "NAV", "P", "SECTION", "SPAN"]);
341
- var shadowChecked = /* @__PURE__ */ new WeakSet();
342
- var MAX_SHADOW_CANDIDATES = 40;
343
- function closedShadowCandidates() {
344
- const out = [];
345
- const visit = (root) => {
346
- const walker = document.createTreeWalker(root, NodeFilter.SHOW_ELEMENT);
347
- for (let n = walker.nextNode(); n && out.length < MAX_SHADOW_CANDIDATES; n = walker.nextNode()) {
348
- const shadow = n.shadowRoot;
349
- if (shadow) {
350
- visit(shadow);
351
- continue;
352
- }
353
- if (shadowChecked.has(n)) continue;
354
- const custom = n.localName.includes("-");
355
- if (custom) {
356
- if (!n.matches(":defined")) continue;
357
- } else if (!SHADOW_HOST_TAGS.has(n.tagName) || n.childElementCount || (n.textContent ?? "").trim()) continue;
358
- else {
359
- const r = n.getBoundingClientRect();
360
- if (!r.width || !r.height) continue;
361
- }
362
- shadowChecked.add(n);
363
- out.push(n);
364
- }
365
- };
366
- visit(document);
367
- return out;
368
- }
369
- function adoptShadowRoot(root) {
370
- if (!(root instanceof ShadowRoot) || !root.host || nativeShadowRoot.call(root.host)) return false;
371
- adoptedRoots.set(root.host, root);
372
- watchDocument(root, true);
373
- return true;
374
- }
375
- var OWN_LAYERS = /* @__PURE__ */ new Set(["browsermcp-overlay-root", "browsermcp-annotate"]);
376
- var STYLE_REPEAT_MS = 200;
377
- var activityState = { n: 0, last: performance.now(), installed: performance.now() };
378
- var watchedDocuments = /* @__PURE__ */ new WeakSet();
379
- var styledAt = /* @__PURE__ */ new WeakMap();
380
- var ownLayer = (node) => node instanceof Element && OWN_LAYERS.has(node.id);
381
- function bump(at) {
382
- activityState.n++;
383
- activityState.last = at;
384
- }
385
- function watchDocument(doc, counted) {
386
- if (watchedDocuments.has(doc)) return;
387
- watchedDocuments.add(doc);
388
- if (counted) bump(performance.now());
389
- new MutationObserver((records) => {
390
- const now = performance.now();
391
- let real = false;
392
- for (const r of records) {
393
- if (ownLayer(r.target) || [...r.addedNodes, ...r.removedNodes].some(ownLayer)) continue;
394
- if (r.type === "attributes") {
395
- const target2 = r.target;
396
- if (r.oldValue === target2.getAttributeNS(r.attributeNamespace, r.attributeName)) continue;
397
- if (r.attributeName === "style") {
398
- const previous = styledAt.get(target2);
399
- styledAt.set(target2, now);
400
- if (previous === void 0 ? now - activityState.installed < STYLE_REPEAT_MS : now - previous <= STYLE_REPEAT_MS) continue;
401
- }
402
- }
403
- real = true;
404
- }
405
- if (real) bump(now);
406
- }).observe(doc, { subtree: true, childList: true, attributes: true, attributeOldValue: true, characterData: true });
407
- for (const type of doc instanceof Document ? ["input", "change", "scroll"] : ["scroll"]) doc.addEventListener(type, () => bump(performance.now()), true);
408
- }
409
- function watchShadowRoots(root, counted) {
410
- const walker = document.createTreeWalker(root, NodeFilter.SHOW_ELEMENT);
411
- for (let n = walker.nextNode(); n; n = walker.nextNode()) {
412
- const shadow = n.shadowRoot;
413
- if (!shadow) continue;
414
- watchDocument(shadow, counted);
415
- watchShadowRoots(shadow, counted);
416
- }
417
- }
418
- function watchFrames(doc, counted) {
419
- for (const frame of doc.querySelectorAll("iframe,frame")) {
420
- let child = null;
421
- try {
422
- child = frame.contentDocument;
423
- } catch {
424
- child = null;
425
- }
426
- if (!child) continue;
427
- watchDocument(child, counted);
428
- watchFrames(child, counted);
429
- }
430
- }
431
- watchDocument(document, false);
432
- watchFrames(document, false);
433
- function contentProbe() {
434
- const text2 = (document.body?.innerText ?? "").replace(/\s+/g, " ").trim();
435
- return { href: location.href, ready: document.readyState, chars: text2.length, head: text2.slice(0, 200) };
436
- }
437
- var documentId = () => String(performance.timeOrigin);
438
- function activity(args = {}) {
439
- watchFrames(document, true);
440
- if (args.scan) watchShadowRoots(document, false);
441
- const now = performance.now();
442
- return { n: activityState.n, idleMs: Math.round(now - activityState.last), ready: document.readyState, url: location.href, doc: documentId() };
443
- }
444
- var probedFrame = null;
445
- function frameElement() {
446
- return probedFrame?.isConnected ? probedFrame : null;
447
- }
448
- function frameProbe(args) {
449
- probedFrame = null;
450
- const list = typeof args.step === "number" ? [...document.querySelectorAll("iframe,frame")] : query(args.step);
451
- const fe = typeof args.step === "number" ? list[args.step] : list[0];
452
- if (!fe || !/^(IFRAME|FRAME)$/.test(fe.tagName)) return { found: false };
453
- probedFrame = fe;
454
- let sameOrigin = false;
455
- try {
456
- sameOrigin = Boolean(fe.contentWindow && fe.contentWindow.document);
457
- } catch {
458
- sameOrigin = false;
459
- }
460
- if (args.scroll) try {
461
- fe.scrollIntoView({ block: "center", inline: "nearest", behavior: "instant" });
462
- } catch {
463
- }
464
- const r = fe.getBoundingClientRect();
465
- return { found: true, sameOrigin, x: r.left + fe.clientLeft, y: r.top + fe.clientTop, src: fe.src || "" };
466
- }
467
- function clearFrameProbe() {
468
- probedFrame = null;
469
- }
470
- var probeHits = 0;
471
- var probeCleanup = null;
472
- function armClickProbe() {
473
- probeCleanup?.();
474
- probeHits = 0;
475
- const on = () => {
476
- probeHits++;
477
- };
478
- document.addEventListener("pointerdown", on, true);
479
- document.addEventListener("mousedown", on, true);
480
- probeCleanup = () => {
481
- document.removeEventListener("pointerdown", on, true);
482
- document.removeEventListener("mousedown", on, true);
483
- probeCleanup = null;
484
- };
485
- }
486
- function readClickProbe() {
487
- const hit = probeHits > 0;
488
- probeCleanup?.();
489
- probeHits = 0;
490
- return hit;
491
- }
492
- function domClick(args) {
493
- let matches = query(args.selector);
494
- if (!matches.length && args.fallback) matches = query(args.fallback);
495
- if (!matches.length) return { error: { code: "not_found", message: `no element matches ${args.selector}` }, retry: true };
496
- let el = matches[0];
497
- if (matches.length > 1) {
498
- const visible = matches.filter((m) => is(m, "visible"));
499
- if (visible.length === 1) el = visible[0];
500
- else return { error: ambiguity(matches.length, args.selector, visible.length, visible.length > 1 ? visible : matches), retry: false };
501
- }
502
- const enabled = stateOf(el, "enabled");
503
- if (!enabled.matches) return { error: { code: "not_enabled", message: `element is not enabled${enabled.received.startsWith("error:") ? ` (${enabled.received.slice(6)})` : ""}`, candidates: [candidate(el)] }, retry: true };
504
- rememberActionTarget(el);
505
- el.click();
506
- const b = el.getBoundingClientRect();
507
- return { ok: true, ref: ariaRefOf(el), tag: el.tagName.toLowerCase(), selector: replaySelector(el), x: b.width > 0 ? b.left + b.width / 2 : 0, y: b.height > 0 ? b.top + b.height / 2 : 0 };
508
- }
509
- var READ_MAX_CHARS = 6e4;
510
- var READ_MAX_STEPS = 40;
511
- var READ_UNBOUNDED_GROWS = 3;
512
- function asPort(el, heightFallback) {
513
- return {
514
- read: () => ({
515
- x: el.scrollLeft || 0,
516
- y: el.scrollTop || 0,
517
- height: el.clientHeight || heightFallback,
518
- scrollHeight: el.scrollHeight || 0
519
- }),
520
- scrollTo(x, y) {
521
- const left = Math.max(0, x);
522
- const top = Math.max(0, y);
523
- try {
524
- el.scrollTo({ left, top, behavior: "instant" });
525
- } catch {
526
- }
527
- el.scrollLeft = left;
528
- el.scrollTop = top;
529
- }
530
- };
531
- }
532
- function pickPort() {
533
- const root = document.scrollingElement || document.documentElement;
534
- const doc = asPort(root, window.innerHeight || 800);
535
- let best = doc;
536
- let bestRange = doc.read().scrollHeight - doc.read().height;
537
- if (!document.body) return doc;
538
- for (const el of query("css=*", document.body)) {
539
- let oy = "";
540
- try {
541
- oy = getComputedStyle(el).overflowY;
542
- } catch {
543
- oy = "";
544
- }
545
- if (oy !== "auto" && oy !== "scroll" && oy !== "overlay") continue;
546
- const port = asPort(el, 0);
547
- const m = port.read();
548
- if (m.height <= 0) continue;
549
- const range = m.scrollHeight - m.height;
550
- if (range > bestRange + 1) {
551
- best = port;
552
- bestRange = range;
553
- }
554
- }
555
- return best;
556
- }
557
- function inClosedDetails(node) {
558
- let child = node;
559
- for (let parent = node.parentNode; parent; child = parent, parent = parent.parentNode ?? parent.host ?? null) {
560
- if (parent instanceof HTMLDetailsElement && !parent.open && child.nodeName !== "SUMMARY") return true;
561
- }
562
- return false;
563
- }
564
- function skipRead(el, visible) {
565
- if (el && inClosedDetails(el)) return true;
566
- while (el) {
567
- const tag = el.tagName;
568
- if (tag === "SCRIPT" || tag === "STYLE" || tag === "NOSCRIPT") return true;
569
- if (el.id === "browsermcp-annotate") return true;
570
- if (el.hasAttribute("hidden")) return true;
571
- const cached = visible.get(el);
572
- if (cached === false) return true;
573
- if (cached === void 0) {
574
- const style = getComputedStyle(el);
575
- const shown = style.display !== "none" && style.visibility !== "hidden" && style.visibility !== "collapse" && style.opacity !== "0";
576
- visible.set(el, shown);
577
- if (!shown) return true;
578
- }
579
- el = el.parentElement ?? el.getRootNode().host ?? null;
580
- }
581
- return false;
582
- }
583
- function shownText(root) {
584
- if (skipRead(root, /* @__PURE__ */ new WeakMap())) return "";
585
- const parts = [];
586
- const visit = (node, textShown) => {
587
- for (const n of node.childNodes) {
588
- if (node instanceof HTMLDetailsElement && !node.open && n.nodeName !== "SUMMARY") continue;
589
- if (n.nodeType === Node.TEXT_NODE) {
590
- if (textShown) parts.push(n.textContent ?? "");
591
- continue;
592
- }
593
- if (!(n instanceof Element) || /^(SCRIPT|STYLE|NOSCRIPT|TEMPLATE)$/.test(n.tagName) || n.id === "browsermcp-annotate" || n.hasAttribute("hidden")) continue;
594
- const style = getComputedStyle(n);
595
- if (style.display === "none" || style.opacity === "0") continue;
596
- const shown = style.visibility !== "hidden" && style.visibility !== "collapse";
597
- const block = n.tagName === "BR" || style.display !== "inline" && style.display !== "contents";
598
- if (block) parts.push(" ");
599
- visit(n, shown);
600
- if (n.shadowRoot) visit(n.shadowRoot, shown);
601
- if (block) parts.push(" ");
602
- }
603
- };
604
- visit(root, true);
605
- if (root.shadowRoot) visit(root.shadowRoot, true);
606
- return parts.join("").replace(/\s+/g, " ").trim();
607
- }
608
- function shownElement(el) {
609
- return is(el, "visible") && !skipRead(el, /* @__PURE__ */ new WeakMap());
610
- }
611
- function pageLines() {
612
- const out = [];
613
- if (!document.body) return out;
614
- const visible = /* @__PURE__ */ new WeakMap();
615
- const visit = (root) => {
616
- for (const n of root.childNodes) {
617
- if (root instanceof HTMLDetailsElement && !root.open && n.nodeName !== "SUMMARY") continue;
618
- if (n.nodeType === Node.TEXT_NODE) {
619
- const parent = n.parentElement ?? n.getRootNode().host;
620
- if (!skipRead(parent, visible)) {
621
- const t = (n.textContent || "").replace(/\s+/g, " ").trim();
622
- if (t) out.push({ node: n, text: t });
623
- }
624
- } else if (n instanceof Element && !skipRead(n, visible)) {
625
- visit(n);
626
- if (n.shadowRoot) visit(n.shadowRoot);
627
- }
628
- }
629
- };
630
- visit(document.body);
631
- return out;
632
- }
633
- var READ_CAPTURE_MAX_CHARS = 24e4;
634
- var READ_PREFIX = Math.random().toString(36).slice(2);
635
- var readSeq = 0;
636
- var lastRead = null;
637
- function sliceRead(capture, start, maxChars) {
638
- const text2 = capture.text.slice(start, start + maxChars);
639
- const nextStart = start + text2.length < capture.text.length ? start + text2.length : void 0;
640
- const complete = capture.reachedBottom && nextStart === void 0;
641
- return { readId: capture.id, text: text2, complete, ...!complete && { reason: nextStart !== void 0 ? "budget" : capture.reason ?? "scan_limit" }, chars: text2.length, start, ...nextStart !== void 0 && { nextStart } };
642
- }
643
- async function readText(args = {}) {
644
- const maxChars = args.maxChars && args.maxChars > 0 ? Math.round(args.maxChars) : READ_MAX_CHARS;
645
- const start = args.start && args.start > 0 ? Math.round(args.start) : 0;
646
- if (args.readId) return lastRead?.id === args.readId ? sliceRead(lastRead, start, maxChars) : { readId: args.readId, text: "", complete: false, reason: "stale", chars: 0, start };
647
- if (start) return { readId: "", text: "", complete: false, reason: "stale", chars: 0, start };
648
- const maxSteps = args.maxSteps && args.maxSteps > 0 ? Math.round(args.maxSteps) : READ_MAX_STEPS;
649
- const waitMs = args.waitMs === void 0 ? 40 : Math.max(0, args.waitMs);
650
- const wait = () => new Promise((r) => setTimeout(r, waitMs));
651
- const port = pickPort();
652
- const saved = port.read();
653
- const seen = /* @__PURE__ */ new WeakMap();
654
- const lines = [];
655
- let chars = 0;
656
- const absorb = () => {
657
- for (const { node, text: text2 } of pageLines()) {
658
- if (seen.get(node) === text2) continue;
659
- seen.set(node, text2);
660
- const separator = lines.length ? 1 : 0;
661
- const remaining = READ_CAPTURE_MAX_CHARS - chars - separator;
662
- if (remaining <= 0) break;
663
- const kept = text2.slice(0, remaining);
664
- chars += kept.length + separator;
665
- lines.push(kept);
666
- }
667
- };
668
- const finish = (reachedBottom, reason) => {
669
- lastRead = { id: `${READ_PREFIX}-${++readSeq}`, text: lines.join("\n"), reachedBottom, reason };
670
- return sliceRead(lastRead, 0, maxChars);
671
- };
672
- try {
673
- port.scrollTo(saved.x, 0);
674
- let grows = 0;
675
- let lastHeight = port.read().scrollHeight;
676
- for (let step = 0; step < maxSteps; step++) {
677
- await wait();
678
- absorb();
679
- if (chars >= READ_CAPTURE_MAX_CHARS) return finish(false, "scan_limit");
680
- const m = port.read();
681
- const reachedPriorBottom = m.y + m.height >= lastHeight - 1;
682
- if (reachedPriorBottom && m.scrollHeight > lastHeight + 1) {
683
- grows++;
684
- if (grows >= READ_UNBOUNDED_GROWS) return finish(false, "unbounded");
685
- }
686
- lastHeight = m.scrollHeight;
687
- const atBottom = m.y + m.height >= m.scrollHeight - 1;
688
- if (atBottom) {
689
- const heightBefore = m.scrollHeight;
690
- port.scrollTo(saved.x, m.y + 1);
691
- await wait();
692
- absorb();
693
- if (chars >= READ_CAPTURE_MAX_CHARS) return finish(false, "scan_limit");
694
- const after = port.read();
695
- if (after.scrollHeight <= heightBefore + 1) return finish(true);
696
- grows++;
697
- lastHeight = after.scrollHeight;
698
- if (grows >= READ_UNBOUNDED_GROWS) return finish(false, "unbounded");
699
- }
700
- const here = port.read();
701
- port.scrollTo(saved.x, here.y + Math.max(1, Math.floor(here.height * 0.8)));
702
- }
703
- return finish(false, "scan_limit");
704
- } finally {
705
- port.scrollTo(saved.x, saved.y);
706
- }
707
- }
708
- var CRED = /user[-_ ]?name|e[-_ ]?mail|one[-_ ]?time[-_ ]?code|password|passcode|passwd|\botp\b|\b(?:2fa|mfa)\b|phone|mobile|\btel\b|\bcc-|cvc|cvv|csc|card|credit|payment|security[-_ ]?code|\biban\b|account[-_ ]?number|routing|ssn|social[-_ ]?security/i;
709
- function isCredentialField(el) {
710
- if (!(el instanceof HTMLInputElement || el instanceof HTMLTextAreaElement)) return false;
711
- if (el.type === "password") return true;
712
- const hay = ["type", "autocomplete", "id", "name", "placeholder", "aria-label", "title"].map((a) => el.getAttribute(a) || "").join(" ");
713
- return CRED.test(hay);
714
- }
715
- function intersectsViewport(el) {
716
- const vw = window.visualViewport?.width ?? innerWidth, vh = window.visualViewport?.height ?? innerHeight;
717
- for (const r of el.getClientRects()) if (r.width > 0 && r.height > 0 && r.right > 0 && r.bottom > 0 && r.left < vw && r.top < vh) return true;
718
- return false;
719
- }
720
- function observationRoot(args) {
721
- if (args.ref) return requireRef(args.ref);
722
- if (!args.selector) return document;
723
- let matches = query(args.selector);
724
- if (!matches.length && args.fallback) matches = query(args.fallback);
725
- if (!matches.length) throw pageError("not_found", `No element matches ${args.selector}`, "Observe the page or find the container again.");
726
- if (matches.length > 1) {
727
- const visible = matches.filter((el) => is(el, "visible"));
728
- if (visible.length !== 1) {
729
- const a = ambiguity(matches.length, args.selector, visible.length, visible.length > 1 ? visible : matches);
730
- throw pageError(a.code, a.message, a.hint, { candidates: a.candidates });
731
- }
732
- matches = visible;
733
- }
734
- return matches[0];
735
- }
736
- var SLOT_TAGS = /* @__PURE__ */ new Set(["P", "SPAN", "DIV", "DD", "TD", "EM", "STRONG", "B", "SMALL", "LABEL", "TIME", "DATA", "OUTPUT"]);
737
- function isEmptySlot(el) {
738
- if (!SLOT_TAGS.has(el.tagName) || el.children.length || (el.textContent ?? "").trim()) return false;
739
- const box2 = el.getBoundingClientRect();
740
- return !(box2.width > 0 && box2.height > 0);
741
- }
742
- function namingTokens(el) {
743
- const tokens = [...el.classList].filter((t) => t.length <= 32 && /^[a-z][a-z0-9]*(?:[-_]{1,2}[a-z0-9]+)*$/i.test(t) && !/\d{3}|^(?:css|sc|jsx|svelte|emotion)-/i.test(t));
744
- return el.id && !/\d{3}/.test(el.id) ? [`#${el.id}`, ...tokens] : tokens;
745
- }
746
- var SELECTED_TOKEN = /^(?:.*[-_])?(?:cur|current|active|actived|selected|checked|on)$/i;
747
- function stateHints(el, empty) {
748
- let out = "";
749
- if (empty) {
750
- const names = namingTokens(el);
751
- out += names.length ? ` [empty ${names[0].startsWith("#") ? `id="${names[0].slice(1)}"` : `class="${names.slice(0, 2).join(" ")}"`}]` : " [empty]";
752
- }
753
- const details = el.tagName === "SUMMARY" && el.parentElement instanceof HTMLDetailsElement ? el.parentElement : null;
754
- if (details && !el.hasAttribute("aria-expanded")) out += details.open ? " [expanded]" : " [collapsed]";
755
- const current = el.getAttribute("aria-current");
756
- if (current && current !== "false") out += current === "true" ? " [current]" : ` [current=${current}]`;
757
- else if (!["aria-selected", "aria-pressed", "aria-checked"].some((a) => el.hasAttribute(a)) && !(el instanceof HTMLInputElement)) {
758
- const token = selectionToken(el);
759
- if (token) out += ` [selected? class="${token}"]`;
760
- }
761
- return out;
762
- }
763
- function selectionToken(el) {
764
- const parent = el.parentElement;
765
- if (!parent) return null;
766
- const siblings = [...parent.children].filter((s) => s.tagName === el.tagName);
767
- if (siblings.length < 2 || siblings.length > 50) return null;
768
- const marked = siblings.filter((s) => [...s.classList].some((t) => SELECTED_TOKEN.test(t)));
769
- if (marked.length !== 1 || marked[0] !== el) return null;
770
- return [...el.classList].find((t) => SELECTED_TOKEN.test(t));
771
- }
772
- function aria(args = {}) {
773
- const root = observationRoot(args);
774
- const i = injected();
775
- annotatedRefs = [];
776
- const raw = i.ariaSnapshot(root === document ? document.body || document.documentElement : root, { mode: "ai" });
777
- resetRefsIfEngineChanged();
778
- const elements = /* @__PURE__ */ new Map();
779
- for (const line of raw.split("\n")) {
780
- const match = ARIA_REF_LINE.exec(line);
781
- if (!match) continue;
782
- let refs;
783
- try {
784
- refs = i.querySelectorAll(i.parseSelector(`aria-ref=${match[2]}`), document);
785
- } catch {
786
- refs = [];
787
- }
788
- const el = refs[0];
789
- if (refs.length !== 1 || !el?.isConnected || el.ownerDocument !== document) {
790
- throw pageError("snapshot_ref_unavailable", `Could not resolve captured ref ${match[2]}.`, 'Use tab.observe({format:"dom"}) for independent DOM evidence.');
791
- }
792
- elements.set(match[2], el);
793
- }
794
- const out = [];
795
- let dropBelow = null;
796
- for (const line of raw.split("\n")) {
797
- const indent = line.length - line.trimStart().length;
798
- if (dropBelow !== null) {
799
- if (indent > dropBelow) continue;
800
- dropBelow = null;
801
- }
802
- const m = ARIA_REF_LINE.exec(line);
803
- if (!m) {
804
- out.push(line);
805
- continue;
806
- }
807
- const el = elements.get(m[2]);
808
- const empty = !m[4] && !m[1].includes(' "') && isEmptySlot(el);
809
- const hints = stateHints(el, empty);
810
- const closing = hints && m[3].endsWith("'") ? m[3].slice(0, -1) + hints + "'" : m[3] + hints;
811
- let rline = m[1] + stableRefOf(el) + closing + (m[4] ?? "");
812
- if (args.viewport && !args.ref && !intersectsViewport(empty && el.parentElement ? el.parentElement : el)) {
813
- dropBelow = indent;
814
- continue;
815
- }
816
- if (m[4] && isCredentialField(el)) {
817
- out.push(rline.slice(0, rline.length - m[4].length) + ": <redacted>");
818
- continue;
819
- }
820
- if (m[4]) {
821
- const val = m[4].replace(/^:\s*/, "").trim();
822
- if (val && rline.includes('"' + val + '"')) rline = rline.slice(0, rline.length - m[4].length);
823
- }
824
- out.push(rline);
825
- }
826
- annotatedRefs = [...elements.values()].map(stableRefOf);
827
- const inAx = new Set(elements.values());
828
- const missingFiles = [...root instanceof HTMLInputElement && root.type === "file" ? [root] : [], ...root.querySelectorAll("input[type=file]")].filter((el) => !inAx.has(el));
829
- for (const input of missingFiles.slice(0, 20)) {
830
- const label = input.labels?.[0]?.textContent?.trim() || input.getAttribute("aria-label") || input.name || "file upload";
831
- const hidden = !is(input, "visible") || !intersectsViewport(input);
832
- out.push(`- file-input ${JSON.stringify(label.slice(0, 100))} [ref=${stableRefOf(input)}]${hidden ? " [hidden]" : ""}${input.multiple ? " [multiple]" : ""}${input.accept ? ": " + JSON.stringify("accepts " + input.accept.slice(0, 100)) : ""}`);
833
- }
834
- if (missingFiles.length > 20) out.push(`- ${missingFiles.length - 20} more file inputs omitted`);
835
- const active = document.activeElement;
836
- const focusRef = active && active !== document.body && root.contains(active) ? ariaRefOf(active) : null;
837
- return out.join("\n") + (focusRef ? `
838
- Focused: [ref=${focusRef}]` : "");
839
- }
840
- function domAttributes(el) {
841
- const attrs = {};
842
- for (const key of ["id", "name", "type", "role", "aria-label", "aria-labelledby", "aria-describedby", "aria-expanded", "aria-selected", "aria-checked", "aria-disabled", "placeholder", "title", "href", "src", "contenteditable", "tabindex", "data-testid"]) {
843
- const value = el.getAttribute(key);
844
- if (value !== null) attrs[key] = value;
845
- }
846
- if (el instanceof HTMLInputElement || el instanceof HTMLTextAreaElement || el instanceof HTMLSelectElement) {
847
- attrs.value = isCredentialField(el) ? "<redacted>" : el.value;
848
- attrs.disabled = String(el.disabled);
849
- attrs.required = String(el.required);
850
- }
851
- if (el instanceof HTMLInputElement || el instanceof HTMLTextAreaElement) attrs.readonly = String(el.readOnly);
852
- if (el instanceof HTMLInputElement && ["checkbox", "radio"].includes(el.type)) {
853
- attrs.checked = String(el.checked);
854
- attrs.indeterminate = String(el.indeterminate);
855
- }
856
- if (el instanceof HTMLOptionElement) attrs.selected = String(el.selected);
857
- if (el instanceof HTMLSelectElement || el instanceof HTMLInputElement && el.type === "file") attrs.multiple = String(el.multiple);
858
- return attrs;
859
- }
860
- var INTERACTIVE_ROLES = /* @__PURE__ */ new Set(["button", "link", "textbox", "checkbox", "radio", "combobox", "listbox", "option", "menuitem", "menuitemcheckbox", "menuitemradio", "slider", "spinbutton", "switch", "tab", "treeitem", "searchbox"]);
861
- function isControl(el) {
862
- return /^(A|BUTTON|INPUT|SELECT|TEXTAREA|DETAILS|SUMMARY|OPTION)$/.test(el.tagName) || el.hasAttribute("onclick") || el.hasAttribute("href") || el.isContentEditable || el.hasAttribute("tabindex") && Number(el.getAttribute("tabindex")) >= 0 || INTERACTIVE_ROLES.has(el.getAttribute("role") ?? "");
863
- }
864
- function visibleDom(args = {}) {
865
- const root = observationRoot(args);
866
- const elements = [...root instanceof Element ? [root] : [], ...query("css=*", root)].filter((el) => isControl(el) && is(el, "visible") && (args.viewport === false || intersectsViewport(el)));
867
- const start = Math.max(0, Math.floor(args.start ?? 0));
868
- const limit = Math.max(1, Math.min(200, Math.floor(args.limit ?? 60)));
869
- const entries = elements.slice(start, start + limit).map((el) => {
870
- let truncated = false;
871
- const clip = (value, max) => {
872
- if (value.length <= max) return value;
873
- truncated = true;
874
- return value.slice(0, max) + "\u2026";
875
- };
876
- return { ref: ariaRefOf(el), tag: el.tagName.toLowerCase(), text: clip(isCredentialField(el) ? "<redacted>" : text(el), 160), attrs: Object.fromEntries(Object.entries(domAttributes(el)).map(([k, v]) => [k, clip(v, 300)])), truncated };
877
- });
878
- const nextStart = start + entries.length < elements.length ? start + entries.length : void 0;
879
- return { entries, total: elements.length, start, ...nextStart !== void 0 && { nextStart }, scope: args.viewport === false ? "document" : "viewport" };
880
- }
881
- function observeFrame(args = {}) {
882
- const content = args.format === "dom" ? { dom: visibleDom(args) } : { state: aria(args) };
883
- const root = observationRoot(args);
884
- const children = root ? [...root instanceof Element && /^(IFRAME|FRAME)$/.test(root.tagName) ? [root] : [], ...query("css=iframe,frame", root)].filter((el) => el.getAttribute("aria-hidden") !== "true" && is(el, "visible") && (!args.viewport || intersectsViewport(el))).map((el) => ({ ref: ariaRefOf(el), id: el.id, name: el.getAttribute("name") ?? "", src: el.getAttribute("src") ?? "" })) : [];
885
- return { ...content, children };
886
- }
887
- function readElement(args) {
888
- let matches = query(args.selector);
889
- if (!matches.length && args.fallback) matches = query(args.fallback);
890
- if (!matches.length) return { error: { code: "not_found", message: `no element matches ${args.selector}`, hint: "Observe or find the target again." } };
891
- if (matches.length > 1) {
892
- const visible = matches.filter((el2) => is(el2, "visible"));
893
- if (visible.length !== 1) return { error: ambiguity(matches.length, args.selector, visible.length, visible.length > 1 ? visible : matches) };
894
- matches = visible;
895
- }
896
- const el = matches[0];
897
- return { ref: ariaRefOf(el), tag: el.tagName.toLowerCase(), name: nameOf(el), text: isCredentialField(el) ? "<redacted>" : el.innerText ?? el.textContent ?? "", attrs: domAttributes(el) };
898
- }
899
- var describe = (el, i) => {
900
- const attrs = Object.fromEntries(Object.entries(domAttributes(el)).map(([key, value]) => [key, value.slice(0, 200)]));
901
- return { nth: i, ref: ariaRefOf(el), selector: replaySelector(el), tag: el.tagName.toLowerCase(), role: roleOf(el), name: nameOf(el).slice(0, 120), text: text(el).slice(0, 120), attrs, visible: is(el, "visible"), enabled: stateOf(el, "enabled").received.startsWith("error:") ? null : is(el, "enabled"), editable: stateOf(el, "editable").received.startsWith("error:") ? null : is(el, "editable"), box: box(el) };
902
- };
903
- function find(args) {
904
- let usedSelector = args.selector;
905
- let matches = query(args.selector);
906
- if (!matches.length && args.fallback) {
907
- usedSelector = args.fallback;
908
- matches = query(args.fallback);
909
- }
910
- const visible_n = matches.filter((m) => is(m, "visible")).length;
911
- return { matches_n: matches.length, visible_n, selector: usedSelector, entries: matches.slice(0, Math.max(1, Math.min(args.limit, 100))).map(describe) };
912
- }
913
- function findByQuery(args) {
914
- const q = args.query.trim().toLowerCase();
915
- if (!q) return { matches_n: 0, entries: [] };
916
- const entries = [];
917
- let matches = 0;
918
- for (const el of query("css=*")) {
919
- if (/^(SCRIPT|STYLE|NOSCRIPT|TEMPLATE)$/.test(el.tagName) || !is(el, "visible")) continue;
920
- const ownText = [...el.childNodes].filter((n) => n.nodeType === Node.TEXT_NODE).map((n) => n.textContent ?? "").join(" ");
921
- const evidence = [ownText, ...isControl(el) ? [text(el), nameOf(el)] : [], ...Object.values(domAttributes(el))].join(" ").toLowerCase();
922
- if (!evidence.includes(q)) continue;
923
- matches++;
924
- if (entries.length >= Math.max(1, Math.min(args.limit, 50))) continue;
925
- const ancestors = [];
926
- let node = el;
927
- while (node && ancestors.length < 8) {
928
- ancestors.push(node);
929
- node = node.parentElement ?? (node.getRootNode().host || null);
930
- }
931
- const interactive = ancestors.find(isControl);
932
- entries.push({ ...describe(el, matches - 1), path: ancestors.slice(1, 5).reverse().map((n) => `${n.tagName.toLowerCase()}${n.id ? "#" + n.id : ""}`), interactiveAncestorRef: interactive ? ariaRefOf(interactive) : null });
933
- }
934
- return { matches_n: matches, entries };
935
- }
936
- function elementAt(args) {
937
- const el = document.elementFromPoint(args.x, args.y);
938
- if (!el) return { matches_n: 0, entries: [] };
939
- const chain = [];
940
- let n = el;
941
- while (n && n !== document.body && chain.length < 4) {
942
- chain.push(n);
943
- n = n.parentElement;
944
- }
945
- return { matches_n: chain.length, entries: chain.map(describe) };
946
- }
947
- var ANNOTATE_ID = "browsermcp-annotate";
948
- function annotate() {
949
- unannotate();
950
- resetRefsIfEngineChanged();
951
- const layer = document.createElement("div");
952
- layer.id = ANNOTATE_ID;
953
- layer.setAttribute("style", "all:initial;position:fixed;inset:0;z-index:2147483645;pointer-events:none;font:11px/1 -apple-system,Segoe UI,Arial,sans-serif;");
954
- let count = 0;
955
- for (const ref of annotatedRefs) {
956
- const el = liveElement(ref);
957
- if (!el || !is(el, "visible") || !intersectsViewport(el)) continue;
958
- const r = el.getBoundingClientRect();
959
- const tag = document.createElement("span");
960
- tag.textContent = ref;
961
- tag.setAttribute("style", `position:absolute;left:${Math.max(0, r.left)}px;top:${Math.max(0, r.top - 12)}px;background:#1d4ed8;color:#fff;padding:1px 3px;border-radius:2px;white-space:nowrap;`);
962
- const outline = document.createElement("div");
963
- outline.setAttribute("style", `position:absolute;left:${r.left}px;top:${r.top}px;width:${r.width}px;height:${r.height}px;outline:1px solid rgba(29,78,216,.8);`);
964
- layer.append(outline, tag);
965
- if (++count >= 300) break;
966
- }
967
- document.documentElement.appendChild(layer);
968
- return count;
969
- }
970
- function unannotate() {
971
- document.getElementById(ANNOTATE_ID)?.remove();
972
- }
973
- var fold = (value) => value.replace(/\s+/g, " ").trim().toLowerCase();
974
- function check(args) {
975
- const failed = [];
976
- const actual = {};
977
- let element;
978
- if (args.selector !== void 0) {
979
- let matches = query(args.selector);
980
- if (!matches.length && args.fallback) matches = query(args.fallback);
981
- if (matches.length > 1) {
982
- const visible = matches.filter((el) => is(el, "visible"));
983
- if (visible.length !== 1) {
984
- const a = ambiguity(matches.length, args.selector, visible.length, visible.length > 1 ? visible : matches);
985
- throw Object.assign(new Error(a.message), { code: a.code, hint: a.hint, data: { candidates: a.candidates } });
986
- }
987
- matches = visible;
988
- }
989
- element = matches[0];
990
- actual.visible = !!element && shownElement(element) && (args.targetText === void 0 || fold(shownText(element)).includes(fold(args.targetText)));
991
- const visibilityOnly = ["text", "notText", "value", "checked", "selected", "enabled"].every((key) => args[key] === void 0);
992
- if (args.visible !== void 0 || visibilityOnly) {
993
- if (actual.visible !== (args.visible ?? true)) failed.push(`visible is ${actual.visible}, expected ${args.visible ?? true}`);
994
- }
995
- if (!element && !visibilityOnly) failed.push("target matches nothing");
996
- }
997
- if (args.selector === void 0 || element) {
998
- const root = element ?? document.body;
999
- const content = element && isCredentialField(element) ? "<redacted>" : root ? shownText(root) : "";
1000
- if (args.text !== void 0 || args.notText !== void 0) {
1001
- actual.text = content.slice(0, 1e3);
1002
- if (args.text !== void 0 && !content.includes(args.text)) failed.push(`text does not include "${args.text}"`);
1003
- if (args.notText !== void 0 && content.includes(args.notText)) failed.push(`text still includes "${args.notText}"`);
1004
- }
1005
- if (element) {
1006
- if (args.value !== void 0) {
1007
- const value = element instanceof HTMLInputElement || element instanceof HTMLTextAreaElement || element instanceof HTMLSelectElement ? element.value : element.isContentEditable ? element.textContent ?? "" : void 0;
1008
- actual.value = isCredentialField(element) ? "<redacted>" : value ?? null;
1009
- if (value !== args.value) failed.push("value does not match");
1010
- }
1011
- for (const key of ["checked", "enabled"]) {
1012
- if (args[key] === void 0) continue;
1013
- const state = stateOf(element, key);
1014
- actual[key] = state.received.startsWith("error:") ? null : state.matches;
1015
- if (actual[key] !== args[key]) failed.push(`${key} is ${actual[key]}, expected ${args[key]}`);
1016
- }
1017
- if (args.selected !== void 0) {
1018
- actual.selected = element instanceof HTMLSelectElement ? [...element.selectedOptions].map((option) => option.value) : null;
1019
- const values = actual.selected;
1020
- if (!values || values.length !== args.selected.length || !values.every((value) => args.selected.includes(value))) failed.push("selected values do not match");
1021
- }
1022
- }
1023
- }
1024
- if (args.url !== void 0 && !location.href.includes(args.url)) failed.push(`url ${location.href} does not include "${args.url}"`);
1025
- if (args.title !== void 0 && !document.title.includes(args.title)) failed.push(`title "${document.title}" does not include "${args.title}"`);
1026
- return { ok: failed.length === 0, failed, url: location.href, title: document.title, actual };
1027
- }
1028
- var api = { check, resolve, resolveUpload, fileSelectionCount, pointInfo, focus, readValue, fill, isChecked, select, caretToEnd, actionTarget, clearActionTarget, activity, contentProbe, closedShadowCandidates, adoptShadowRoot, frameProbe, frameElement, clearFrameProbe, aria, observeFrame, visibleDom, readElement, find, findByQuery, elementAt, annotate, unannotate, armClickProbe, readClickProbe, domClick, readText };
1029
- globalThis[PAGE_GLOBAL] = api;
1030
- })();