@jackwener/browsermcp 0.0.36 → 0.0.37-embedded.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (88) hide show
  1. package/CHANGELOG.md +42 -0
  2. package/README.md +91 -0
  3. package/dist/src/api/action-input.d.ts +62 -0
  4. package/dist/src/api/agent.d.ts +10 -0
  5. package/dist/src/api/api.d.ts +54 -0
  6. package/dist/src/api/browser.d.ts +93 -0
  7. package/dist/src/api/commands.d.ts +452 -0
  8. package/dist/src/api/context.d.ts +7 -0
  9. package/dist/src/api/diff.d.ts +8 -0
  10. package/dist/src/api/errors.d.ts +12 -0
  11. package/dist/src/api/network.d.ts +10 -0
  12. package/dist/src/api/observation.d.ts +4 -0
  13. package/dist/src/api/streams.d.ts +13 -0
  14. package/dist/src/api/tab.d.ts +312 -0
  15. package/dist/src/api/webmcp.d.ts +19 -0
  16. package/dist/src/backends/backend.d.ts +14 -0
  17. package/dist/src/backends/browser-helpers.d.ts +17 -0
  18. package/dist/src/backends/extension-page.d.ts +5 -0
  19. package/dist/src/backends/managed-page.d.ts +50 -0
  20. package/dist/src/backends/page-transport.d.ts +10 -0
  21. package/dist/src/backends/page-types.d.ts +82 -0
  22. package/dist/src/docs/embedded.d.ts +2 -0
  23. package/dist/src/docs/embedded.js +40 -0
  24. package/dist/src/docs/embedded.js.map +1 -0
  25. package/dist/src/docs/manifest.d.ts +23 -0
  26. package/dist/src/docs/manifest.js +6 -3
  27. package/dist/src/docs/manifest.js.map +1 -1
  28. package/dist/src/docs/surface.d.ts +12 -0
  29. package/dist/src/electron/backend.d.ts +50 -0
  30. package/dist/src/electron/backend.js +375 -0
  31. package/dist/src/electron/backend.js.map +1 -0
  32. package/dist/src/electron/chrome.d.ts +24 -0
  33. package/dist/src/electron/chrome.js +133 -0
  34. package/dist/src/electron/chrome.js.map +1 -0
  35. package/dist/src/electron/driver.d.ts +43 -0
  36. package/dist/src/electron/driver.js +241 -0
  37. package/dist/src/electron/driver.js.map +1 -0
  38. package/dist/src/electron/event-buffer.d.ts +16 -0
  39. package/dist/src/electron/event-buffer.js +59 -0
  40. package/dist/src/electron/event-buffer.js.map +1 -0
  41. package/dist/src/electron/page.js +834 -0
  42. package/dist/src/electron/registry.d.ts +104 -0
  43. package/dist/src/electron/registry.js +316 -0
  44. package/dist/src/electron/registry.js.map +1 -0
  45. package/dist/src/electron/streams.d.ts +16 -0
  46. package/dist/src/electron/streams.js +48 -0
  47. package/dist/src/electron/streams.js.map +1 -0
  48. package/dist/src/embedded/index.d.ts +39 -0
  49. package/dist/src/embedded/index.js +72 -0
  50. package/dist/src/embedded/index.js.map +1 -0
  51. package/dist/src/host/bridge.d.ts +50 -0
  52. package/dist/src/host/doctor.d.ts +34 -0
  53. package/dist/src/host/extension.d.ts +3 -0
  54. package/dist/src/host/host.d.ts +3 -0
  55. package/dist/src/host/ipc.d.ts +14 -0
  56. package/dist/src/host/jsonc-config.d.ts +1 -0
  57. package/dist/src/host/launch.d.ts +11 -0
  58. package/dist/src/host/native-messaging.d.ts +28 -0
  59. package/dist/src/host/opencode.d.ts +6 -0
  60. package/dist/src/host/pi.d.ts +6 -0
  61. package/dist/src/host/registration.d.ts +24 -0
  62. package/dist/src/host/setup.d.ts +7 -0
  63. package/dist/src/host/socket.d.ts +25 -0
  64. package/dist/src/host/state.d.ts +39 -0
  65. package/dist/src/launcher/stdio.d.ts +3 -0
  66. package/dist/src/lib/paths.d.ts +1 -0
  67. package/dist/src/lib/sources.d.ts +5 -0
  68. package/dist/src/main.d.ts +2 -0
  69. package/dist/src/mcp/catalog.d.ts +202 -0
  70. package/dist/src/mcp/js-session.d.ts +64 -0
  71. package/dist/src/mcp/server.d.ts +15 -0
  72. package/dist/src/protocol.d.ts +320 -0
  73. package/dist/src/recon/analyzer.d.ts +43 -0
  74. package/dist/src/recon/discover.d.ts +48 -0
  75. package/dist/src/runtime/runtime.d.ts +148 -0
  76. package/dist/src/shared/api-contract.d.ts +86 -0
  77. package/dist/src/shared/aria-tree.d.ts +2 -0
  78. package/dist/src/shared/element-ref.d.ts +4 -0
  79. package/dist/src/shared/engine.d.ts +50 -0
  80. package/dist/src/shared/injected-source.d.ts +2 -0
  81. package/dist/src/shared/page-contract.d.ts +256 -0
  82. package/dist/src/sites/define.d.ts +28 -0
  83. package/dist/src/sites/drafts.d.ts +39 -0
  84. package/dist/src/sites/executor.d.ts +34 -0
  85. package/dist/src/sites/loader.d.ts +84 -0
  86. package/dist/src/sites/schema.d.ts +11 -0
  87. package/dist/src/version.d.ts +2 -0
  88. package/package.json +12 -3
@@ -0,0 +1,834 @@
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) {
98
+ return Object.assign(new Error(message), { code, hint });
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 candidate = (el) => ({ tag: el.tagName.toLowerCase(), role: el.getAttribute("role") || "", text: text(el).slice(0, 80), ref: ariaRefOf(el), visible: is(el, "visible"), box: box(el) });
125
+ var actionElement = null;
126
+ function actionTarget() {
127
+ const el = actionElement;
128
+ return el?.isConnected && el.ownerDocument === document ? el : null;
129
+ }
130
+ var actEl = actionTarget;
131
+ function rememberActionTarget(el) {
132
+ actionElement = el;
133
+ }
134
+ function clearActionTarget() {
135
+ actionElement = null;
136
+ }
137
+ var ALIGN_BLOCKS = /* @__PURE__ */ new Set(["start", "center", "end", "nearest"]);
138
+ async function resolve(args) {
139
+ const { selector, fallback, strict, states, align } = args;
140
+ let usedSelector = selector;
141
+ let matches = query(selector);
142
+ if (!matches.length && fallback) {
143
+ usedSelector = fallback;
144
+ matches = query(fallback);
145
+ }
146
+ if (!matches.length) return { error: { code: "not_found", message: `no element matches ${selector}` }, retry: true };
147
+ let el = matches[0];
148
+ if (matches.length > 1 && strict) {
149
+ const visible = matches.filter((m) => is(m, "visible"));
150
+ if (visible.length === 1) el = visible[0];
151
+ else return { error: { code: "selector_ambiguous", message: `${matches.length} elements match ${selector}${visible.length ? ` (${visible.length} visible)` : ""}`, hint: "Add nth, use a more specific locator, or act on a ref/selector from find.", candidates: matches.slice(0, 8).map(candidate) }, retry: false };
152
+ }
153
+ for (const st of states) {
154
+ const r = stateOf(el, st);
155
+ if (r.received === "error:notconnected") return { error: { code: "stale_ref", message: "element detached during resolution" }, retry: true };
156
+ 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 };
157
+ }
158
+ try {
159
+ el.scrollIntoView({ block: ALIGN_BLOCKS.has(align.block) ? align.block : "center", inline: ALIGN_BLOCKS.has(align.inline) ? align.inline : "nearest", behavior: "instant" });
160
+ } catch {
161
+ }
162
+ let prev = null;
163
+ let stable = 0;
164
+ const t0 = performance.now();
165
+ for (; ; ) {
166
+ const r = el.getBoundingClientRect();
167
+ const cur = [r.left, r.top, r.width, r.height].map(Math.round).join(",");
168
+ stable = prev === cur ? stable + 1 : 0;
169
+ prev = cur;
170
+ if (stable >= 1 || performance.now() - t0 > 700) break;
171
+ await new Promise((res) => setTimeout(res, 40));
172
+ }
173
+ for (const st of states) if (!is(el, st)) return { error: { code: `not_${st}`, message: `element is not ${st} after scrolling` }, retry: true };
174
+ const b = el.getBoundingClientRect();
175
+ 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 };
176
+ const x = Math.max(0, b.left + b.width / 2), y = Math.max(0, b.top + b.height / 2);
177
+ if (x > innerWidth || y > innerHeight) return { error: { code: "not_visible", message: "element is outside the viewport" }, retry: true };
178
+ const tag = el.tagName.toLowerCase();
179
+ const type = el.type;
180
+ const checkable = tag === "input" && (type === "checkbox" || type === "radio") || ["checkbox", "radio", "switch"].includes(el.getAttribute("role") || "");
181
+ const hit = injected().expectHitTarget({ x, y }, el);
182
+ rememberActionTarget(el);
183
+ return {
184
+ ok: true,
185
+ x,
186
+ y,
187
+ matches_n: matches.length,
188
+ tag,
189
+ hit: hit === "done" ? "target" : "other",
190
+ blocker: hit === "done" ? null : hit && hit.hitTargetDescription || "another element",
191
+ editable: is(el, "editable"),
192
+ checkable,
193
+ checked: checkable ? is(el, "checked") : false,
194
+ isSelect: tag === "select",
195
+ ref: ariaRefOf(el),
196
+ selector: replaySelector(el),
197
+ usedSelector
198
+ };
199
+ }
200
+ function pointInfo(args) {
201
+ const el = document.elementFromPoint(args.x, args.y);
202
+ if (!el) return null;
203
+ rememberActionTarget(el);
204
+ const tag = el.tagName.toLowerCase();
205
+ const editable = Boolean(el.isContentEditable || (tag === "input" || tag === "textarea") && !el.readOnly && !el.disabled);
206
+ return { tag, editable, isSelect: tag === "select" };
207
+ }
208
+ var target = () => {
209
+ const el = actEl();
210
+ if (!el) throw new Error("error:notconnected");
211
+ return el;
212
+ };
213
+ var retarget = (el) => injected().retarget(el, "follow-label") || el;
214
+ function targetHasFocus(el) {
215
+ const active = el.getRootNode().activeElement;
216
+ if (!el.isConnected || !active) return false;
217
+ return active === el || el.contains(active) || el.isContentEditable && active.isContentEditable && active.contains(el);
218
+ }
219
+ function focus() {
220
+ const el = actEl();
221
+ if (!el) return "error:notconnected";
222
+ const t = retarget(el);
223
+ let focusTarget = t;
224
+ while (focusTarget.isContentEditable && focusTarget.parentElement?.isContentEditable) focusTarget = focusTarget.parentElement;
225
+ const result = String(injected().focusNode(focusTarget, false));
226
+ if (result !== "done") return result;
227
+ return t === document.body || t === document.documentElement || targetHasFocus(t) ? "done" : "error:focusfailed";
228
+ }
229
+ function readValue() {
230
+ const el = actEl();
231
+ if (!el) return null;
232
+ const t = retarget(el);
233
+ return t.isContentEditable ? t.textContent ?? "" : t.value ?? null;
234
+ }
235
+ function fill(args) {
236
+ const el = actEl();
237
+ if (!el) return "error:notconnected";
238
+ try {
239
+ if (retarget(el).isContentEditable) {
240
+ const focused = focus();
241
+ if (focused !== "done") return focused;
242
+ }
243
+ const result = String(injected().fill(el, args.value));
244
+ return result === "needsinput" && !targetHasFocus(retarget(el)) ? "error:focusfailed" : result;
245
+ } catch (e) {
246
+ return "error:" + (e?.message || String(e));
247
+ }
248
+ }
249
+ function isChecked() {
250
+ const el = actEl();
251
+ if (!el) return null;
252
+ const r = stateOf(el, "checked");
253
+ return r.received.startsWith("error:") ? null : r.matches;
254
+ }
255
+ function select(args) {
256
+ const el = actEl();
257
+ if (!el) return { error: "gone" };
258
+ const i = injected();
259
+ let r = i.selectOptions(el, [{ valueOrLabel: args.value }]);
260
+ if (r === "error:optionsnotfound" && /^\d+$/.test(args.value)) r = i.selectOptions(el, [{ index: Number(args.value) }]);
261
+ if (typeof r === "string" && r.startsWith("error:")) {
262
+ const available = [...el.options ?? []].map((o) => o.label || o.value).slice(0, 50);
263
+ return { error: r.slice(6), available };
264
+ }
265
+ return { selected: Array.isArray(r) ? r.map(String) : [] };
266
+ }
267
+ function caretToEnd() {
268
+ const el = retarget(target());
269
+ if (el.isContentEditable) {
270
+ const range = el.ownerDocument.createRange();
271
+ range.selectNodeContents(el);
272
+ range.collapse(false);
273
+ const selection = el.ownerDocument.getSelection();
274
+ selection?.removeAllRanges();
275
+ selection?.addRange(range);
276
+ } else {
277
+ const input = el;
278
+ if (typeof input.setSelectionRange === "function") {
279
+ try {
280
+ input.setSelectionRange(input.value.length, input.value.length);
281
+ } catch {
282
+ }
283
+ }
284
+ }
285
+ }
286
+ function resolveUpload(args) {
287
+ let matches = query(args.selector);
288
+ if (!matches.length && args.fallback) matches = query(args.fallback);
289
+ if (!matches.length) return { error: { code: "not_found", message: "Upload target was not found. Observe again for a fresh file-input ref." } };
290
+ if (matches.length !== 1) return { error: { code: "selector_ambiguous", message: `${matches.length} upload targets match`, candidates: matches.slice(0, 8).map(candidate) } };
291
+ const el = matches[0];
292
+ const direct = el instanceof HTMLInputElement && el.type === "file" ? [el] : [];
293
+ const controlled = el instanceof HTMLLabelElement && el.control instanceof HTMLInputElement && el.control.type === "file" ? [el.control] : [];
294
+ const nested = [...el.querySelectorAll("input[type=file]")];
295
+ const inForm = el.closest("form")?.querySelectorAll("input[type=file]") ?? [];
296
+ const candidates = [.../* @__PURE__ */ new Set([...direct, ...controlled, ...nested, ...inForm])];
297
+ if (!candidates.length) candidates.push(...document.querySelectorAll("input[type=file]"));
298
+ 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." } };
299
+ const input = candidates[0];
300
+ if (input.disabled) return { error: { code: "not_enabled", message: "The file input is disabled." } };
301
+ if (args.files > 1 && !input.multiple) return { error: { code: "invalid_args", message: "This file input accepts only one file." } };
302
+ rememberActionTarget(input);
303
+ return { ok: true, ref: ariaRefOf(input), selector: replaySelector(input), matches_n: 1 };
304
+ }
305
+ function fileSelectionCount() {
306
+ const el = actEl();
307
+ return el instanceof HTMLInputElement ? el.files?.length ?? 0 : 0;
308
+ }
309
+ function settle(args) {
310
+ return new Promise((resolveP) => {
311
+ const t0 = performance.now();
312
+ let timer;
313
+ const finish = (quiet) => {
314
+ obs.disconnect();
315
+ clearTimeout(cap);
316
+ resolveP({ waitedMs: Math.round(performance.now() - t0), quiet });
317
+ };
318
+ const arm = () => {
319
+ clearTimeout(timer);
320
+ timer = setTimeout(() => finish(true), args.quietMs);
321
+ };
322
+ const obs = new MutationObserver(arm);
323
+ obs.observe(document.documentElement, { childList: true, subtree: true, attributes: true, characterData: true });
324
+ const cap = setTimeout(() => {
325
+ clearTimeout(timer);
326
+ finish(false);
327
+ }, args.maxMs);
328
+ arm();
329
+ });
330
+ }
331
+ var probedFrame = null;
332
+ function frameElement() {
333
+ return probedFrame?.isConnected ? probedFrame : null;
334
+ }
335
+ function frameProbe(args) {
336
+ probedFrame = null;
337
+ const list = typeof args.step === "number" ? [...document.querySelectorAll("iframe,frame")] : query(args.step);
338
+ const fe = typeof args.step === "number" ? list[args.step] : list[0];
339
+ if (!fe || !/^(IFRAME|FRAME)$/.test(fe.tagName)) return { found: false };
340
+ probedFrame = fe;
341
+ let sameOrigin = false;
342
+ try {
343
+ sameOrigin = Boolean(fe.contentWindow && fe.contentWindow.document);
344
+ } catch {
345
+ sameOrigin = false;
346
+ }
347
+ if (args.scroll) try {
348
+ fe.scrollIntoView({ block: "center", inline: "nearest", behavior: "instant" });
349
+ } catch {
350
+ }
351
+ const r = fe.getBoundingClientRect();
352
+ return { found: true, sameOrigin, x: r.left + fe.clientLeft, y: r.top + fe.clientTop, src: fe.src || "" };
353
+ }
354
+ function clearFrameProbe() {
355
+ probedFrame = null;
356
+ }
357
+ var probeHits = 0;
358
+ var probeCleanup = null;
359
+ function armClickProbe() {
360
+ probeCleanup?.();
361
+ probeHits = 0;
362
+ const on = () => {
363
+ probeHits++;
364
+ };
365
+ document.addEventListener("pointerdown", on, true);
366
+ document.addEventListener("mousedown", on, true);
367
+ probeCleanup = () => {
368
+ document.removeEventListener("pointerdown", on, true);
369
+ document.removeEventListener("mousedown", on, true);
370
+ probeCleanup = null;
371
+ };
372
+ }
373
+ function readClickProbe() {
374
+ const hit = probeHits > 0;
375
+ probeCleanup?.();
376
+ probeHits = 0;
377
+ return hit;
378
+ }
379
+ function domClick(args) {
380
+ let matches = query(args.selector);
381
+ if (!matches.length && args.fallback) matches = query(args.fallback);
382
+ if (!matches.length) return { error: { code: "not_found", message: `no element matches ${args.selector}` }, retry: true };
383
+ let el = matches[0];
384
+ if (matches.length > 1) {
385
+ const visible = matches.filter((m) => is(m, "visible"));
386
+ if (visible.length === 1) el = visible[0];
387
+ else return { error: { code: "selector_ambiguous", message: `${matches.length} elements match ${args.selector}${visible.length ? ` (${visible.length} visible)` : ""}`, hint: "Add nth, use a more specific locator, or act on a ref/selector from find.", candidates: matches.slice(0, 8).map(candidate) }, retry: false };
388
+ }
389
+ const enabled = stateOf(el, "enabled");
390
+ 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 };
391
+ rememberActionTarget(el);
392
+ el.click();
393
+ const b = el.getBoundingClientRect();
394
+ 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 };
395
+ }
396
+ var READ_MAX_CHARS = 6e4;
397
+ var READ_MAX_STEPS = 40;
398
+ var READ_UNBOUNDED_GROWS = 3;
399
+ function asPort(el, heightFallback) {
400
+ return {
401
+ read: () => ({
402
+ x: el.scrollLeft || 0,
403
+ y: el.scrollTop || 0,
404
+ height: el.clientHeight || heightFallback,
405
+ scrollHeight: el.scrollHeight || 0
406
+ }),
407
+ scrollTo(x, y) {
408
+ const left = Math.max(0, x);
409
+ const top = Math.max(0, y);
410
+ try {
411
+ el.scrollTo({ left, top, behavior: "instant" });
412
+ } catch {
413
+ }
414
+ el.scrollLeft = left;
415
+ el.scrollTop = top;
416
+ }
417
+ };
418
+ }
419
+ function pickPort() {
420
+ const root = document.scrollingElement || document.documentElement;
421
+ const doc = asPort(root, window.innerHeight || 800);
422
+ let best = doc;
423
+ let bestRange = doc.read().scrollHeight - doc.read().height;
424
+ if (!document.body) return doc;
425
+ for (const el of query("css=*", document.body)) {
426
+ let oy = "";
427
+ try {
428
+ oy = getComputedStyle(el).overflowY;
429
+ } catch {
430
+ oy = "";
431
+ }
432
+ if (oy !== "auto" && oy !== "scroll" && oy !== "overlay") continue;
433
+ const port = asPort(el, 0);
434
+ const m = port.read();
435
+ if (m.height <= 0) continue;
436
+ const range = m.scrollHeight - m.height;
437
+ if (range > bestRange + 1) {
438
+ best = port;
439
+ bestRange = range;
440
+ }
441
+ }
442
+ return best;
443
+ }
444
+ function skipRead(el, visible) {
445
+ while (el) {
446
+ const tag = el.tagName;
447
+ if (tag === "SCRIPT" || tag === "STYLE" || tag === "NOSCRIPT") return true;
448
+ if (el.id === "browsermcp-annotate") return true;
449
+ if (el.hasAttribute("hidden")) return true;
450
+ const cached = visible.get(el);
451
+ if (cached === false) return true;
452
+ if (cached === void 0) {
453
+ const style = getComputedStyle(el);
454
+ const shown = style.display !== "none" && style.visibility !== "hidden" && style.visibility !== "collapse";
455
+ visible.set(el, shown);
456
+ if (!shown) return true;
457
+ }
458
+ el = el.parentElement ?? el.getRootNode().host ?? null;
459
+ }
460
+ return false;
461
+ }
462
+ function pageLines() {
463
+ const out = [];
464
+ if (!document.body) return out;
465
+ const visible = /* @__PURE__ */ new WeakMap();
466
+ const visit = (root) => {
467
+ for (const n of root.childNodes) {
468
+ if (n.nodeType === Node.TEXT_NODE) {
469
+ const parent = n.parentElement ?? n.getRootNode().host;
470
+ if (!skipRead(parent, visible)) {
471
+ const t = (n.textContent || "").replace(/\s+/g, " ").trim();
472
+ if (t) out.push({ node: n, text: t });
473
+ }
474
+ } else if (n instanceof Element && !skipRead(n, visible)) {
475
+ visit(n);
476
+ if (n.shadowRoot) visit(n.shadowRoot);
477
+ }
478
+ }
479
+ };
480
+ visit(document.body);
481
+ return out;
482
+ }
483
+ var READ_CAPTURE_MAX_CHARS = 24e4;
484
+ var READ_PREFIX = Math.random().toString(36).slice(2);
485
+ var readSeq = 0;
486
+ var lastRead = null;
487
+ function sliceRead(capture, start, maxChars) {
488
+ const text2 = capture.text.slice(start, start + maxChars);
489
+ const nextStart = start + text2.length < capture.text.length ? start + text2.length : void 0;
490
+ const complete = capture.reachedBottom && nextStart === void 0;
491
+ 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 } };
492
+ }
493
+ async function readText(args = {}) {
494
+ const maxChars = args.maxChars && args.maxChars > 0 ? Math.round(args.maxChars) : READ_MAX_CHARS;
495
+ const start = args.start && args.start > 0 ? Math.round(args.start) : 0;
496
+ if (args.readId) return lastRead?.id === args.readId ? sliceRead(lastRead, start, maxChars) : { readId: args.readId, text: "", complete: false, reason: "stale", chars: 0, start };
497
+ if (start) return { readId: "", text: "", complete: false, reason: "stale", chars: 0, start };
498
+ const maxSteps = args.maxSteps && args.maxSteps > 0 ? Math.round(args.maxSteps) : READ_MAX_STEPS;
499
+ const waitMs = args.waitMs === void 0 ? 40 : Math.max(0, args.waitMs);
500
+ const wait = () => new Promise((r) => setTimeout(r, waitMs));
501
+ const port = pickPort();
502
+ const saved = port.read();
503
+ const seen = /* @__PURE__ */ new WeakMap();
504
+ const lines = [];
505
+ let chars = 0;
506
+ const absorb = () => {
507
+ for (const { node, text: text2 } of pageLines()) {
508
+ if (seen.get(node) === text2) continue;
509
+ seen.set(node, text2);
510
+ const separator = lines.length ? 1 : 0;
511
+ const remaining = READ_CAPTURE_MAX_CHARS - chars - separator;
512
+ if (remaining <= 0) break;
513
+ const kept = text2.slice(0, remaining);
514
+ chars += kept.length + separator;
515
+ lines.push(kept);
516
+ }
517
+ };
518
+ const finish = (reachedBottom, reason) => {
519
+ lastRead = { id: `${READ_PREFIX}-${++readSeq}`, text: lines.join("\n"), reachedBottom, reason };
520
+ return sliceRead(lastRead, 0, maxChars);
521
+ };
522
+ try {
523
+ port.scrollTo(saved.x, 0);
524
+ let grows = 0;
525
+ let lastHeight = port.read().scrollHeight;
526
+ for (let step = 0; step < maxSteps; step++) {
527
+ await wait();
528
+ absorb();
529
+ if (chars >= READ_CAPTURE_MAX_CHARS) return finish(false, "scan_limit");
530
+ const m = port.read();
531
+ const reachedPriorBottom = m.y + m.height >= lastHeight - 1;
532
+ if (reachedPriorBottom && m.scrollHeight > lastHeight + 1) {
533
+ grows++;
534
+ if (grows >= READ_UNBOUNDED_GROWS) return finish(false, "unbounded");
535
+ }
536
+ lastHeight = m.scrollHeight;
537
+ const atBottom = m.y + m.height >= m.scrollHeight - 1;
538
+ if (atBottom) {
539
+ const heightBefore = m.scrollHeight;
540
+ port.scrollTo(saved.x, m.y + 1);
541
+ await wait();
542
+ absorb();
543
+ if (chars >= READ_CAPTURE_MAX_CHARS) return finish(false, "scan_limit");
544
+ const after = port.read();
545
+ if (after.scrollHeight <= heightBefore + 1) return finish(true);
546
+ grows++;
547
+ lastHeight = after.scrollHeight;
548
+ if (grows >= READ_UNBOUNDED_GROWS) return finish(false, "unbounded");
549
+ }
550
+ const here = port.read();
551
+ port.scrollTo(saved.x, here.y + Math.max(1, Math.floor(here.height * 0.8)));
552
+ }
553
+ return finish(false, "scan_limit");
554
+ } finally {
555
+ port.scrollTo(saved.x, saved.y);
556
+ }
557
+ }
558
+ 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;
559
+ function isCredentialField(el) {
560
+ if (!(el instanceof HTMLInputElement || el instanceof HTMLTextAreaElement)) return false;
561
+ if (el.type === "password") return true;
562
+ const hay = ["type", "autocomplete", "id", "name", "placeholder", "aria-label", "title"].map((a) => el.getAttribute(a) || "").join(" ");
563
+ return CRED.test(hay);
564
+ }
565
+ function intersectsViewport(el) {
566
+ const vw = window.visualViewport?.width ?? innerWidth, vh = window.visualViewport?.height ?? innerHeight;
567
+ 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;
568
+ return false;
569
+ }
570
+ function observationRoot(args) {
571
+ if (args.ref) return requireRef(args.ref);
572
+ if (!args.selector) return document;
573
+ let matches = query(args.selector);
574
+ if (!matches.length && args.fallback) matches = query(args.fallback);
575
+ if (!matches.length) throw pageError("not_found", `No element matches ${args.selector}`, "Observe the page or find the container again.");
576
+ if (matches.length > 1) {
577
+ const visible = matches.filter((el) => is(el, "visible"));
578
+ if (visible.length !== 1) throw pageError("selector_ambiguous", `${matches.length} elements match ${args.selector}`, "Use a more specific locator.");
579
+ matches = visible;
580
+ }
581
+ return matches[0];
582
+ }
583
+ function aria(args = {}) {
584
+ const root = observationRoot(args);
585
+ const i = injected();
586
+ annotatedRefs = [];
587
+ const raw = i.ariaSnapshot(root === document ? document.body || document.documentElement : root, { mode: "ai" });
588
+ resetRefsIfEngineChanged();
589
+ const elements = /* @__PURE__ */ new Map();
590
+ for (const line of raw.split("\n")) {
591
+ const match = ARIA_REF_LINE.exec(line);
592
+ if (!match) continue;
593
+ let refs;
594
+ try {
595
+ refs = i.querySelectorAll(i.parseSelector(`aria-ref=${match[2]}`), document);
596
+ } catch {
597
+ refs = [];
598
+ }
599
+ const el = refs[0];
600
+ if (refs.length !== 1 || !el?.isConnected || el.ownerDocument !== document) {
601
+ throw pageError("snapshot_ref_unavailable", `Could not resolve captured ref ${match[2]}.`, 'Use tab.observe({format:"dom"}) for independent DOM evidence.');
602
+ }
603
+ elements.set(match[2], el);
604
+ }
605
+ const out = [];
606
+ let dropBelow = null;
607
+ for (const line of raw.split("\n")) {
608
+ const indent = line.length - line.trimStart().length;
609
+ if (dropBelow !== null) {
610
+ if (indent > dropBelow) continue;
611
+ dropBelow = null;
612
+ }
613
+ const m = ARIA_REF_LINE.exec(line);
614
+ if (!m) {
615
+ out.push(line);
616
+ continue;
617
+ }
618
+ const el = elements.get(m[2]);
619
+ let rline = m[1] + stableRefOf(el) + m[3] + (m[4] ?? "");
620
+ if (args.viewport && !args.ref && !intersectsViewport(el)) {
621
+ dropBelow = indent;
622
+ continue;
623
+ }
624
+ if (m[4] && isCredentialField(el)) {
625
+ out.push(rline.slice(0, rline.length - m[4].length) + ": <redacted>");
626
+ continue;
627
+ }
628
+ if (m[4]) {
629
+ const val = m[4].replace(/^:\s*/, "").trim();
630
+ if (val && rline.includes('"' + val + '"')) rline = rline.slice(0, rline.length - m[4].length);
631
+ }
632
+ out.push(rline);
633
+ }
634
+ annotatedRefs = [...elements.values()].map(stableRefOf);
635
+ const inAx = new Set(elements.values());
636
+ const missingFiles = [...root instanceof HTMLInputElement && root.type === "file" ? [root] : [], ...root.querySelectorAll("input[type=file]")].filter((el) => !inAx.has(el));
637
+ for (const input of missingFiles.slice(0, 20)) {
638
+ const label = input.labels?.[0]?.textContent?.trim() || input.getAttribute("aria-label") || input.name || "file upload";
639
+ const hidden = !is(input, "visible") || !intersectsViewport(input);
640
+ 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)) : ""}`);
641
+ }
642
+ if (missingFiles.length > 20) out.push(`- ${missingFiles.length - 20} more file inputs omitted`);
643
+ const active = document.activeElement;
644
+ const focusRef = active && active !== document.body && root.contains(active) ? ariaRefOf(active) : null;
645
+ return out.join("\n") + (focusRef ? `
646
+ Focused: [ref=${focusRef}]` : "");
647
+ }
648
+ function domAttributes(el) {
649
+ const attrs = {};
650
+ 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"]) {
651
+ const value = el.getAttribute(key);
652
+ if (value !== null) attrs[key] = value;
653
+ }
654
+ if (el instanceof HTMLInputElement || el instanceof HTMLTextAreaElement || el instanceof HTMLSelectElement) {
655
+ attrs.value = isCredentialField(el) ? "<redacted>" : el.value;
656
+ attrs.disabled = String(el.disabled);
657
+ attrs.required = String(el.required);
658
+ }
659
+ if (el instanceof HTMLInputElement || el instanceof HTMLTextAreaElement) attrs.readonly = String(el.readOnly);
660
+ if (el instanceof HTMLInputElement && ["checkbox", "radio"].includes(el.type)) {
661
+ attrs.checked = String(el.checked);
662
+ attrs.indeterminate = String(el.indeterminate);
663
+ }
664
+ if (el instanceof HTMLOptionElement) attrs.selected = String(el.selected);
665
+ if (el instanceof HTMLSelectElement || el instanceof HTMLInputElement && el.type === "file") attrs.multiple = String(el.multiple);
666
+ return attrs;
667
+ }
668
+ var INTERACTIVE_ROLES = /* @__PURE__ */ new Set(["button", "link", "textbox", "checkbox", "radio", "combobox", "listbox", "option", "menuitem", "menuitemcheckbox", "menuitemradio", "slider", "spinbutton", "switch", "tab", "treeitem", "searchbox"]);
669
+ function isControl(el) {
670
+ 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") ?? "");
671
+ }
672
+ function visibleDom(args = {}) {
673
+ const root = observationRoot(args);
674
+ const elements = [...root instanceof Element ? [root] : [], ...query("css=*", root)].filter((el) => isControl(el) && is(el, "visible") && (args.viewport === false || intersectsViewport(el)));
675
+ const start = Math.max(0, Math.floor(args.start ?? 0));
676
+ const limit = Math.max(1, Math.min(200, Math.floor(args.limit ?? 60)));
677
+ const entries = elements.slice(start, start + limit).map((el) => {
678
+ let truncated = false;
679
+ const clip = (value, max) => {
680
+ if (value.length <= max) return value;
681
+ truncated = true;
682
+ return value.slice(0, max) + "\u2026";
683
+ };
684
+ 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 };
685
+ });
686
+ const nextStart = start + entries.length < elements.length ? start + entries.length : void 0;
687
+ return { entries, total: elements.length, start, ...nextStart !== void 0 && { nextStart }, scope: args.viewport === false ? "document" : "viewport" };
688
+ }
689
+ function observeFrame(args = {}) {
690
+ const content = args.format === "dom" ? { dom: visibleDom(args) } : { state: aria(args) };
691
+ const root = observationRoot(args);
692
+ 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") ?? "" })) : [];
693
+ return { ...content, children };
694
+ }
695
+ function readElement(args) {
696
+ let matches = query(args.selector);
697
+ if (!matches.length && args.fallback) matches = query(args.fallback);
698
+ if (!matches.length) return { error: { code: "not_found", message: `no element matches ${args.selector}`, hint: "Observe or find the target again." } };
699
+ if (matches.length > 1) {
700
+ const visible = matches.filter((el2) => is(el2, "visible"));
701
+ if (visible.length !== 1) return { error: { code: "selector_ambiguous", message: `${matches.length} elements match ${args.selector}`, hint: "Use a ref from observe/find, or a more specific locator." } };
702
+ matches = visible;
703
+ }
704
+ const el = matches[0];
705
+ return { ref: ariaRefOf(el), tag: el.tagName.toLowerCase(), name: nameOf(el), text: isCredentialField(el) ? "<redacted>" : el.innerText ?? el.textContent ?? "", attrs: domAttributes(el) };
706
+ }
707
+ var describe = (el, i) => {
708
+ const attrs = Object.fromEntries(Object.entries(domAttributes(el)).map(([key, value]) => [key, value.slice(0, 200)]));
709
+ 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) };
710
+ };
711
+ function find(args) {
712
+ let usedSelector = args.selector;
713
+ let matches = query(args.selector);
714
+ if (!matches.length && args.fallback) {
715
+ usedSelector = args.fallback;
716
+ matches = query(args.fallback);
717
+ }
718
+ const visible_n = matches.filter((m) => is(m, "visible")).length;
719
+ return { matches_n: matches.length, visible_n, selector: usedSelector, entries: matches.slice(0, Math.max(1, Math.min(args.limit, 100))).map(describe) };
720
+ }
721
+ function findByQuery(args) {
722
+ const q = args.query.trim().toLowerCase();
723
+ if (!q) return { matches_n: 0, entries: [] };
724
+ const entries = [];
725
+ let matches = 0;
726
+ for (const el of query("css=*")) {
727
+ if (/^(SCRIPT|STYLE|NOSCRIPT|TEMPLATE)$/.test(el.tagName) || !is(el, "visible")) continue;
728
+ const ownText = [...el.childNodes].filter((n) => n.nodeType === Node.TEXT_NODE).map((n) => n.textContent ?? "").join(" ");
729
+ const evidence = [ownText, ...isControl(el) ? [text(el), nameOf(el)] : [], ...Object.values(domAttributes(el))].join(" ").toLowerCase();
730
+ if (!evidence.includes(q)) continue;
731
+ matches++;
732
+ if (entries.length >= Math.max(1, Math.min(args.limit, 50))) continue;
733
+ const ancestors = [];
734
+ let node = el;
735
+ while (node && ancestors.length < 8) {
736
+ ancestors.push(node);
737
+ node = node.parentElement ?? (node.getRootNode().host || null);
738
+ }
739
+ const interactive = ancestors.find(isControl);
740
+ 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 });
741
+ }
742
+ return { matches_n: matches, entries };
743
+ }
744
+ function elementAt(args) {
745
+ const el = document.elementFromPoint(args.x, args.y);
746
+ if (!el) return { matches_n: 0, entries: [] };
747
+ const chain = [];
748
+ let n = el;
749
+ while (n && n !== document.body && chain.length < 4) {
750
+ chain.push(n);
751
+ n = n.parentElement;
752
+ }
753
+ return { matches_n: chain.length, entries: chain.map(describe) };
754
+ }
755
+ var ANNOTATE_ID = "browsermcp-annotate";
756
+ function annotate() {
757
+ unannotate();
758
+ resetRefsIfEngineChanged();
759
+ const layer = document.createElement("div");
760
+ layer.id = ANNOTATE_ID;
761
+ 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;");
762
+ let count = 0;
763
+ for (const ref of annotatedRefs) {
764
+ const el = liveElement(ref);
765
+ if (!el || !is(el, "visible") || !intersectsViewport(el)) continue;
766
+ const r = el.getBoundingClientRect();
767
+ const tag = document.createElement("span");
768
+ tag.textContent = ref;
769
+ 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;`);
770
+ const outline = document.createElement("div");
771
+ 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);`);
772
+ layer.append(outline, tag);
773
+ if (++count >= 300) break;
774
+ }
775
+ document.documentElement.appendChild(layer);
776
+ return count;
777
+ }
778
+ function unannotate() {
779
+ document.getElementById(ANNOTATE_ID)?.remove();
780
+ }
781
+ function check(args) {
782
+ const failed = [];
783
+ const actual = {};
784
+ let element;
785
+ if (args.selector !== void 0) {
786
+ let matches = query(args.selector);
787
+ if (!matches.length && args.fallback) matches = query(args.fallback);
788
+ if (matches.length > 1) {
789
+ const visible = matches.filter((el) => is(el, "visible"));
790
+ if (visible.length !== 1) throw Object.assign(new Error(`${matches.length} elements match; use a scoped target or an observed ref.`), { code: "selector_ambiguous" });
791
+ matches = visible;
792
+ }
793
+ element = matches[0];
794
+ actual.visible = !!element && is(element, "visible");
795
+ const visibilityOnly = ["text", "notText", "value", "checked", "selected", "enabled"].every((key) => args[key] === void 0);
796
+ if (args.visible !== void 0 || visibilityOnly) {
797
+ if (actual.visible !== (args.visible ?? true)) failed.push(`visible is ${actual.visible}, expected ${args.visible ?? true}`);
798
+ }
799
+ if (!element && !visibilityOnly) failed.push("target matches nothing");
800
+ }
801
+ if (args.selector === void 0 || element) {
802
+ const root = element ?? document.body;
803
+ const content = element && isCredentialField(element) ? "<redacted>" : (root?.innerText ?? root?.textContent ?? "").replace(/\s+/g, " ");
804
+ if (args.text !== void 0 || args.notText !== void 0) {
805
+ actual.text = content.slice(0, 1e3);
806
+ if (args.text !== void 0 && !content.includes(args.text)) failed.push(`text does not include "${args.text}"`);
807
+ if (args.notText !== void 0 && content.includes(args.notText)) failed.push(`text still includes "${args.notText}"`);
808
+ }
809
+ if (element) {
810
+ if (args.value !== void 0) {
811
+ const value = element instanceof HTMLInputElement || element instanceof HTMLTextAreaElement || element instanceof HTMLSelectElement ? element.value : element.isContentEditable ? element.textContent ?? "" : void 0;
812
+ actual.value = isCredentialField(element) ? "<redacted>" : value ?? null;
813
+ if (value !== args.value) failed.push("value does not match");
814
+ }
815
+ for (const key of ["checked", "enabled"]) {
816
+ if (args[key] === void 0) continue;
817
+ const state = stateOf(element, key);
818
+ actual[key] = state.received.startsWith("error:") ? null : state.matches;
819
+ if (actual[key] !== args[key]) failed.push(`${key} is ${actual[key]}, expected ${args[key]}`);
820
+ }
821
+ if (args.selected !== void 0) {
822
+ actual.selected = element instanceof HTMLSelectElement ? [...element.selectedOptions].map((option) => option.value) : null;
823
+ const values = actual.selected;
824
+ if (!values || values.length !== args.selected.length || !values.every((value) => args.selected.includes(value))) failed.push("selected values do not match");
825
+ }
826
+ }
827
+ }
828
+ if (args.url !== void 0 && !location.href.includes(args.url)) failed.push(`url ${location.href} does not include "${args.url}"`);
829
+ if (args.title !== void 0 && !document.title.includes(args.title)) failed.push(`title "${document.title}" does not include "${args.title}"`);
830
+ return { ok: failed.length === 0, failed, url: location.href, title: document.title, actual };
831
+ }
832
+ var api = { check, resolve, resolveUpload, fileSelectionCount, pointInfo, focus, readValue, fill, isChecked, select, caretToEnd, actionTarget, clearActionTarget, settle, frameProbe, frameElement, clearFrameProbe, aria, observeFrame, visibleDom, readElement, find, findByQuery, elementAt, annotate, unannotate, armClickProbe, readClickProbe, domClick, readText };
833
+ globalThis[PAGE_GLOBAL] = api;
834
+ })();