fastqa-mcp 0.0.0-stage → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,359 @@
1
+ import { chromium, devices } from 'playwright';
2
+ import { snapshotInPage, domSettleInPage, deepTextInPage, iframeInfoInPage } from './snapshot.js';
3
+ const env = process.env;
4
+ export const DEFAULT_TIMEOUT = Number(env.FASTQA_TIMEOUT_MS || 5000);
5
+ export class Session {
6
+ browser;
7
+ context;
8
+ page;
9
+ /** last snapshot lines (for diffs) and ref -> selector hints (for stale refs + recording) */
10
+ lastLines = [];
11
+ hints = new Map();
12
+ tape = [];
13
+ evidence = { console: [], pageErrors: [], failedRequests: [] };
14
+ inflight = 0;
15
+ pending = new Set();
16
+ refBase = 0;
17
+ log = [];
18
+ /** start of the current act batch / flow run; expect_request and expect_no_errors look from here */
19
+ mark = 0;
20
+ device;
21
+ addLog(e) {
22
+ this.log.push({ t: Date.now(), ...e });
23
+ if (this.log.length > 2000)
24
+ this.log.splice(0, 500);
25
+ }
26
+ since(t) { return this.log.filter((e) => e.t >= t); }
27
+ /** device: a Playwright device name such as "iPhone 13" or "Pixel 7"; switching device opens a new context. */
28
+ async ensure(fresh = false, device) {
29
+ if (device !== undefined && device !== (this.device ?? '')) {
30
+ fresh = true;
31
+ this.device = device || undefined;
32
+ }
33
+ if (fresh)
34
+ await this.closeContext();
35
+ if (!this.browser)
36
+ this.browser = await launch();
37
+ if (!this.context) {
38
+ const [w, h] = (env.FASTQA_VIEWPORT || '1280x800').split('x').map(Number);
39
+ this.context = this.browser.contexts()[0] && env.FASTQA_CDP_URL
40
+ ? this.browser.contexts()[0]
41
+ : await this.browser.newContext(this.device
42
+ ? { ...deviceProfile(this.device), ignoreHTTPSErrors: true }
43
+ : { viewport: { width: w, height: h }, ignoreHTTPSErrors: true });
44
+ this.context.setDefaultTimeout(DEFAULT_TIMEOUT);
45
+ }
46
+ if (!this.page || this.page.isClosed()) {
47
+ this.page = this.context.pages()[0] ?? (await this.context.newPage());
48
+ this.attach(this.page);
49
+ this.context.on('page', (p) => { this.page = p; this.attach(p); });
50
+ }
51
+ return this.page;
52
+ }
53
+ attach(page) {
54
+ page.on('console', (m) => {
55
+ if (/favicon/.test(m.location()?.url || ''))
56
+ return;
57
+ if (m.type() === 'error' || m.type() === 'warning')
58
+ push(this.evidence.console, `[${m.type()}] ${m.text()}`);
59
+ if (m.type() === 'error' && !/Failed to load resource/.test(m.text()))
60
+ this.addLog({ kind: 'console', text: m.text() });
61
+ });
62
+ page.on('pageerror', (e) => {
63
+ push(this.evidence.pageErrors, String(e?.message || e));
64
+ this.addLog({ kind: 'pageerror', text: String(e?.message || e) });
65
+ });
66
+ // A request counts as in flight until its response headers arrive (bodies the app never reads must not block settle).
67
+ page.on('request', (r) => { this.pending.add(r); this.inflight = this.pending.size; });
68
+ page.on('response', (res) => {
69
+ const r = res.request();
70
+ this.pending.delete(r);
71
+ this.inflight = this.pending.size;
72
+ if (['fetch', 'xhr', 'document'].includes(r.resourceType()))
73
+ this.addLog({ kind: 'http', method: r.method(), url: r.url(), status: res.status(), text: `${res.status()} ${r.method()} ${r.url()}` });
74
+ if (res.status() >= 400 && !/favicon/.test(r.url()))
75
+ push(this.evidence.failedRequests, `${res.status()} ${r.method()} ${r.url()}`);
76
+ });
77
+ page.on('requestfinished', (r) => { this.pending.delete(r); this.inflight = this.pending.size; });
78
+ page.on('requestfailed', (r) => {
79
+ this.pending.delete(r);
80
+ this.inflight = this.pending.size;
81
+ if (/ERR_ABORTED/.test(r.failure()?.errorText ?? ''))
82
+ return; // navigation noise
83
+ this.addLog({ kind: 'http', method: r.method(), url: r.url(), status: 0, text: `FAILED ${r.method()} ${r.url()}` });
84
+ push(this.evidence.failedRequests, `FAILED ${r.method()} ${r.url()} ${r.failure()?.errorText ?? ''}`);
85
+ });
86
+ }
87
+ async closeContext() {
88
+ if (this.context && !env.FASTQA_CDP_URL)
89
+ await this.context.close().catch(() => { });
90
+ this.context = undefined;
91
+ this.page = undefined;
92
+ this.inflight = 0;
93
+ this.pending.clear();
94
+ this.lastLines = [];
95
+ this.hints.clear();
96
+ }
97
+ async close() {
98
+ await this.closeContext();
99
+ await this.browser?.close().catch(() => { });
100
+ this.browser = undefined;
101
+ }
102
+ /** Wait until network is idle-ish and DOM is quiet. Bounded so it never costs more than ~maxMs. */
103
+ async settle(maxMs = 2000) {
104
+ const page = this.page;
105
+ const start = Date.now();
106
+ await page.waitForLoadState('domcontentloaded', { timeout: maxMs }).catch(() => { });
107
+ while (this.inflight > 0 && Date.now() - start < maxMs)
108
+ await sleep(25);
109
+ const left = Math.max(50, maxMs - (Date.now() - start));
110
+ await page.evaluate(domSettleInPage, { quietMs: 80, maxMs: left }).catch(() => { });
111
+ }
112
+ async snapshot(mode = 'interactive', root, max = Number(env.FASTQA_MAX_LINES || 250)) {
113
+ const page = this.page;
114
+ let res;
115
+ for (let i = 0; i < 3 && !res; i++) {
116
+ try {
117
+ res = await page.evaluate(snapshotInPage, { mode, root, max, base: this.refBase });
118
+ }
119
+ catch (e) {
120
+ if (!/context was destroyed|navigat/i.test(String(e)))
121
+ throw e;
122
+ await page.waitForLoadState('domcontentloaded').catch(() => { });
123
+ }
124
+ }
125
+ if (!res)
126
+ throw new Error('Page kept navigating; could not take a snapshot');
127
+ this.refBase = Math.max(this.refBase, res.maxRef);
128
+ const items = [...res.items];
129
+ let truncated = res.truncated;
130
+ // iframes (same- and cross-origin): each visible frame gets its own indented block
131
+ if (!root) {
132
+ for (const fr of await this.listFrames()) {
133
+ if (items.length >= max) {
134
+ truncated = true;
135
+ break;
136
+ }
137
+ try {
138
+ const r = await fr.frame.evaluate(snapshotInPage, { mode, max: max - items.length, base: this.refBase });
139
+ this.refBase = Math.max(this.refBase, r.maxRef);
140
+ const indent = ' '.repeat(fr.chain.length);
141
+ items.push({ line: `${' '.repeat(fr.chain.length - 1)}frame ${JSON.stringify(fr.label)} [${fr.chain[fr.chain.length - 1]}]` });
142
+ for (const it of r.items)
143
+ items.push({ ...it, line: indent + it.line, frame: fr.chain });
144
+ truncated ||= r.truncated;
145
+ }
146
+ catch { /* frame navigated or detached mid-snapshot */ }
147
+ }
148
+ }
149
+ for (const it of items)
150
+ if (it.ref && it.hint)
151
+ this.hints.set(it.ref, { hint: it.hint, code: it.code, frame: it.frame });
152
+ return { items, truncated, url: res.url, title: res.title };
153
+ }
154
+ /** Visible child frames with their selector chain from the top page (nested frames supported). */
155
+ async listFrames() {
156
+ const page = this.page;
157
+ const out = [];
158
+ for (const f of page.frames()) {
159
+ if (f === page.mainFrame() || f.isDetached())
160
+ continue;
161
+ const chain = [];
162
+ let label = '';
163
+ let cur = f;
164
+ let ok = true;
165
+ while (cur && cur.parentFrame()) {
166
+ const el = await cur.frameElement().catch(() => null);
167
+ if (!el || !(await el.isVisible().catch(() => false))) {
168
+ ok = false;
169
+ break;
170
+ }
171
+ const info = await el.evaluate(iframeInfoInPage).catch(() => null);
172
+ if (!info) {
173
+ ok = false;
174
+ break;
175
+ }
176
+ chain.unshift(info.sel);
177
+ if (!label)
178
+ label = info.label;
179
+ cur = cur.parentFrame();
180
+ }
181
+ if (ok && chain.length)
182
+ out.push({ frame: f, chain, label });
183
+ }
184
+ return out.sort((x, y) => x.chain.length - y.chain.length);
185
+ }
186
+ /** Page or nested FrameLocator for a selector chain. */
187
+ scope(chain) {
188
+ let sc = this.page;
189
+ for (const sel of chain ?? [])
190
+ sc = sc.frameLocator(sel);
191
+ return sc;
192
+ }
193
+ static codePrefix(chain) {
194
+ return 'page' + (chain ?? []).map((sel) => `.frameLocator(${JSON.stringify(sel)})`).join('');
195
+ }
196
+ /** Frames to search for a step: an explicit chain, a fuzzy frame name, or main + every visible frame. */
197
+ async scopesFor(frame) {
198
+ if (Array.isArray(frame))
199
+ return [frame];
200
+ const frames = await this.listFrames();
201
+ if (frame) {
202
+ const f = frame.toLowerCase();
203
+ const hit = frames.filter((x) => x.label.toLowerCase().includes(f) || x.chain.some((c) => c.toLowerCase().includes(f)));
204
+ return hit.length ? hit.map((x) => x.chain) : [[frame]]; // fall back to treating it as an iframe selector
205
+ }
206
+ return [[], ...frames.map((x) => x.chain)];
207
+ }
208
+ /** Visible text across the page, its open shadow roots and all visible iframes, tagged by frame chain. */
209
+ async deepTexts() {
210
+ const page = this.page;
211
+ const out = [{ chain: [], text: await page.evaluate(deepTextInPage).catch(() => '') }];
212
+ for (const fr of await this.listFrames())
213
+ out.push({ chain: fr.chain, text: await fr.frame.evaluate(deepTextInPage).catch(() => '') });
214
+ return out;
215
+ }
216
+ /** Compact text: header + lines */
217
+ static render(res) {
218
+ const lines = res.items.map((i) => i.line);
219
+ return `url: ${res.url}\ntitle: ${res.title}\n` + lines.join('\n') + (res.truncated ? '\n… (truncated; use snapshot with root=<css> to scope)' : '');
220
+ }
221
+ /** Diff vs previous snapshot keyed by line content. */
222
+ diff(newLines) {
223
+ const strip = (l) => l.replace(/^e\d+ /, '');
224
+ const before = new Map();
225
+ for (const l of this.lastLines)
226
+ before.set(strip(l), (before.get(strip(l)) || 0) + 1);
227
+ const added = [];
228
+ for (const l of newLines) {
229
+ const k = strip(l);
230
+ const n = before.get(k) || 0;
231
+ if (n > 0)
232
+ before.set(k, n - 1);
233
+ else
234
+ added.push(l);
235
+ }
236
+ const after = new Map();
237
+ for (const l of newLines)
238
+ after.set(strip(l), (after.get(strip(l)) || 0) + 1);
239
+ const removed = [];
240
+ for (const l of this.lastLines) {
241
+ const k = strip(l);
242
+ const n = after.get(k) || 0;
243
+ if (n > 0)
244
+ after.set(k, n - 1);
245
+ else
246
+ removed.push(l);
247
+ }
248
+ return { added, removed };
249
+ }
250
+ /**
251
+ * Resolve a target string to a locator. Works across open shadow DOM (Playwright locators pierce it)
252
+ * and across iframes (searched main frame first, then each visible frame).
253
+ * - "e12" -> ref from the last snapshot (falls back to its recorded selector if the node was re-rendered)
254
+ * - "css=..", "#id", "[..]", "role=..", "text=..", "xpath=.." -> raw Playwright selector
255
+ * - "testid=x" -> getByTestId
256
+ * - anything else -> semantic: label / placeholder / role+name / text, chosen by intent
257
+ */
258
+ async resolve(target, intent, timeout = DEFAULT_TIMEOUT, frame) {
259
+ const t = target.trim();
260
+ const fr = (c) => (c && c.length ? c : undefined);
261
+ if (/^e\d+$/.test(t)) {
262
+ const h = this.hints.get(t);
263
+ const sc = this.scope(h?.frame);
264
+ const byRef = sc.locator(`[data-fq="${t}"]`);
265
+ const pre = Session.codePrefix(h?.frame);
266
+ if (await byRef.count()) {
267
+ return { loc: byRef.first(), record: h?.hint ?? `[data-fq="${t}"]`, code: (h?.code ?? `page.locator('[data-fq="${t}"]')`).replace(/^page/, pre), frame: fr(h?.frame) };
268
+ }
269
+ if (!h)
270
+ throw new Error(`Unknown ref ${t}. Take a snapshot first.`);
271
+ return { loc: sc.locator(h.hint).first(), record: h.hint, code: (h.code ?? `page.locator(${JSON.stringify(h.hint)})`).replace(/^page/, pre), frame: fr(h.frame) };
272
+ }
273
+ const deadline = Date.now() + timeout;
274
+ let scopes = await this.scopesFor(frame);
275
+ let polls = 0;
276
+ do {
277
+ // pass 1: exact matches in every scope; pass 2: fuzzy. So an exact button in an iframe beats loose text in the page.
278
+ for (const exactPass of [true, false])
279
+ for (const chain of scopes) {
280
+ const sc = this.scope(chain);
281
+ const pre = Session.codePrefix(chain);
282
+ for (const [loc, code] of this.candidates(sc, t, intent).filter((c) => /exact: true|getByTestId|page\.locator/.test(c[1]) === exactPass)) {
283
+ const v = loc.filter({ visible: true });
284
+ if ((await v.count().catch(() => 0)) > 0) {
285
+ const raw = !/^(testid=|css=|xpath=|role=|text=|#|\[|\.|\/\/)/.test(t) ? `${code}.first()` : code;
286
+ return { loc: v.first(), record: t, code: raw.replace(/^page/, pre), frame: fr(chain) };
287
+ }
288
+ }
289
+ }
290
+ await sleep(100);
291
+ if (++polls % 5 === 0 && !Array.isArray(frame))
292
+ scopes = await this.scopesFor(frame); // frames may appear late
293
+ } while (Date.now() < deadline);
294
+ throw new Error(`No visible element matches "${t}"${frame ? ` in frame "${frame}"` : ''} (tried ${intent === 'fill' ? 'label, placeholder, textbox' : 'role+name, label, text'} in page, shadow DOM and iframes)`);
295
+ }
296
+ candidates(sc, t, intent) {
297
+ if (/^testid=/.test(t)) {
298
+ const id = t.slice(7);
299
+ return [[sc.getByTestId(id), `page.getByTestId(${JSON.stringify(id)})`]];
300
+ }
301
+ if (/^(css=|xpath=|role=|text=|#|\[|\.|\/\/)/.test(t)) {
302
+ const sel = t.replace(/^css=/, '');
303
+ return [[sc.locator(sel), `page.locator(${JSON.stringify(sel)})`]];
304
+ }
305
+ const s = JSON.stringify(t);
306
+ const c = [];
307
+ if (intent === 'fill') {
308
+ c.push([sc.getByLabel(t, { exact: true }), `page.getByLabel(${s}, { exact: true })`], [sc.getByPlaceholder(t, { exact: true }), `page.getByPlaceholder(${s}, { exact: true })`], [sc.getByRole('textbox', { name: t, exact: true }), `page.getByRole('textbox', { name: ${s}, exact: true })`], [sc.getByRole('combobox', { name: t, exact: true }), `page.getByRole('combobox', { name: ${s}, exact: true })`], [sc.getByLabel(t), `page.getByLabel(${s})`], [sc.getByPlaceholder(t), `page.getByPlaceholder(${s})`]);
309
+ }
310
+ else {
311
+ const roles = ['button', 'link', 'tab', 'menuitem', 'checkbox', 'radio', 'switch', 'option', 'combobox'];
312
+ for (const r of roles)
313
+ c.push([sc.getByRole(r, { name: t, exact: true }), `page.getByRole('${r}', { name: ${s}, exact: true })`]);
314
+ c.push([sc.getByLabel(t, { exact: true }), `page.getByLabel(${s}, { exact: true })`]);
315
+ c.push([sc.getByText(t, { exact: true }), `page.getByText(${s}, { exact: true })`]);
316
+ for (const r of ['button', 'link'])
317
+ c.push([sc.getByRole(r, { name: t }), `page.getByRole('${r}', { name: ${s} })`]);
318
+ c.push([sc.getByText(t), `page.getByText(${s})`]);
319
+ }
320
+ return c;
321
+ }
322
+ takeEvidence() {
323
+ const e = this.evidence;
324
+ this.evidence = { console: [], pageErrors: [], failedRequests: [] };
325
+ return e;
326
+ }
327
+ }
328
+ function push(arr, s) { if (arr.length < 50)
329
+ arr.push(s.slice(0, 300)); }
330
+ export const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
331
+ function deviceProfile(name) {
332
+ const key = Object.keys(devices).find((k) => k.toLowerCase() === name.toLowerCase());
333
+ if (!key)
334
+ throw new Error(`Unknown device "${name}". Examples: "iPhone 13", "Pixel 7", "iPad Mini", "Galaxy S9+".`);
335
+ const { defaultBrowserType, ...profile } = devices[key];
336
+ return profile;
337
+ }
338
+ async function launch() {
339
+ if (env.FASTQA_CDP_URL)
340
+ return chromium.connectOverCDP(env.FASTQA_CDP_URL);
341
+ const headless = !/^(1|true|yes)$/i.test(env.FASTQA_HEADED || '');
342
+ const args = ['--disable-dev-shm-usage', '--no-first-run', '--disable-extensions'];
343
+ const tries = [];
344
+ if (env.FASTQA_CHROME)
345
+ tries.push({ executablePath: env.FASTQA_CHROME });
346
+ tries.push({}); // Playwright-bundled chromium
347
+ tries.push({ channel: 'chrome' }); // installed Google Chrome
348
+ tries.push({ channel: 'msedge' });
349
+ let last;
350
+ for (const t of tries) {
351
+ try {
352
+ return await chromium.launch({ headless, args, ...t });
353
+ }
354
+ catch (e) {
355
+ last = e;
356
+ }
357
+ }
358
+ throw new Error(`Could not launch a browser. Run "npx playwright install chromium" or set FASTQA_CHROME. Last error: ${String(last).split('\n')[0]}`);
359
+ }
@@ -0,0 +1,306 @@
1
+ // Runs inside the page. Must be fully self-contained (it is serialized by page.evaluate).
2
+ // Produces a compact, one-line-per-element view of the page and stamps stable refs (data-fq="eN").
3
+ export function snapshotInPage(opts) {
4
+ const w = window;
5
+ w.__fq = w.__fq || { n: 0 };
6
+ w.__fq.n = Math.max(w.__fq.n, opts.base || 0); // refs stay unique across navigations
7
+ const INTERACTIVE = 'a[href],button,input:not([type=hidden]),select,textarea,summary,' +
8
+ '[role=button],[role=link],[role=checkbox],[role=radio],[role=tab],[role=menuitem],' +
9
+ '[role=option],[role=switch],[role=combobox],[role=textbox],[role=slider],' +
10
+ '[contenteditable=""],[contenteditable=true]';
11
+ const INFO = 'h1,h2,h3,[role=alert],[role=status],[aria-live=assertive],[aria-live=polite],[role=dialog],dialog[open]';
12
+ const TEXT = 'p,li,td,th,dt,dd,span,div,strong,em,small,b,i,code,pre,blockquote,figcaption,caption';
13
+ const clip = (s, n = 60) => {
14
+ s = (s || '').replace(/\s+/g, ' ').trim();
15
+ return s.length > n ? s.slice(0, n - 1) + '…' : s;
16
+ };
17
+ const q = (s) => JSON.stringify(s);
18
+ const visible = (el) => {
19
+ const anyEl = el;
20
+ if (typeof anyEl.checkVisibility === 'function') {
21
+ if (!anyEl.checkVisibility({ checkOpacity: true, checkVisibilityCSS: true }))
22
+ return false;
23
+ }
24
+ const r = el.getBoundingClientRect();
25
+ return r.width > 0 && r.height > 0;
26
+ };
27
+ const roleOf = (el) => {
28
+ const explicit = el.getAttribute('role');
29
+ if (explicit)
30
+ return explicit;
31
+ const tag = el.tagName.toLowerCase();
32
+ if (tag === 'a')
33
+ return 'link';
34
+ if (tag === 'button' || tag === 'summary')
35
+ return 'button';
36
+ if (tag === 'select')
37
+ return el.multiple ? 'listbox' : 'combobox';
38
+ if (tag === 'textarea')
39
+ return 'textbox';
40
+ if (tag === 'input') {
41
+ const t = (el.type || 'text').toLowerCase();
42
+ if (['button', 'submit', 'reset', 'image'].includes(t))
43
+ return 'button';
44
+ if (t === 'checkbox')
45
+ return 'checkbox';
46
+ if (t === 'radio')
47
+ return 'radio';
48
+ if (t === 'range')
49
+ return 'slider';
50
+ if (t === 'search')
51
+ return 'searchbox';
52
+ return 'textbox';
53
+ }
54
+ if (/^h[1-6]$/.test(tag))
55
+ return 'heading';
56
+ if (tag === 'dialog')
57
+ return 'dialog';
58
+ if (el.getAttribute('contenteditable') !== null)
59
+ return 'textbox';
60
+ return tag;
61
+ };
62
+ const nameOf = (el) => {
63
+ const aria = el.getAttribute('aria-label');
64
+ if (aria)
65
+ return clip(aria);
66
+ const lb = el.getAttribute('aria-labelledby');
67
+ if (lb) {
68
+ const rn = el.getRootNode();
69
+ const t = lb.split(/\s+/).map((id) => (rn.getElementById?.(id) ?? document.getElementById(id))?.textContent || '').join(' ');
70
+ if (t.trim())
71
+ return clip(t);
72
+ }
73
+ const id = el.getAttribute('id');
74
+ if (id) {
75
+ const lab = el.getRootNode().querySelector?.(`label[for="${CSS.escape(id)}"]`);
76
+ if (lab?.textContent?.trim())
77
+ return clip(lab.textContent);
78
+ }
79
+ const tag = el.tagName.toLowerCase();
80
+ if (tag === 'input' || tag === 'textarea' || tag === 'select') {
81
+ const wrap = el.closest('label');
82
+ if (wrap) {
83
+ const clone = wrap.cloneNode(true);
84
+ clone.querySelectorAll('input,select,textarea').forEach((n) => n.remove());
85
+ if (clone.textContent?.trim())
86
+ return clip(clone.textContent);
87
+ }
88
+ const ph = el.getAttribute('placeholder');
89
+ if (ph)
90
+ return clip(ph);
91
+ const t = el.type;
92
+ if (['submit', 'button', 'reset'].includes(t))
93
+ return clip(el.value);
94
+ }
95
+ const title = el.getAttribute('title') || el.getAttribute('alt');
96
+ if (title)
97
+ return clip(title);
98
+ const img = el.querySelector('img[alt]');
99
+ const txt = el.innerText || el.textContent || '';
100
+ if (txt.trim())
101
+ return clip(txt);
102
+ if (img)
103
+ return clip(img.getAttribute('alt') || '');
104
+ return '';
105
+ };
106
+ const stateOf = (el, role) => {
107
+ const parts = [];
108
+ const h = el;
109
+ if (role === 'textbox' || role === 'searchbox') {
110
+ const v = el.getAttribute('contenteditable') !== null ? (el.textContent || '') : h.value;
111
+ if (v)
112
+ parts.push(h.type === 'password' ? '=•••' : '=' + q(clip(v, 40)));
113
+ }
114
+ if (role === 'combobox' && el.tagName === 'SELECT') {
115
+ const s = el;
116
+ const opt = s.options[s.selectedIndex];
117
+ if (opt)
118
+ parts.push('=' + q(clip(opt.text, 40)));
119
+ parts.push('options:' + Array.from(s.options).slice(0, 8).map((o) => clip(o.text, 20)).join('|') + (s.options.length > 8 ? '|…' : ''));
120
+ }
121
+ if (role === 'checkbox' || role === 'radio' || role === 'switch') {
122
+ const checked = h.checked ?? el.getAttribute('aria-checked') === 'true';
123
+ if (checked || el.getAttribute('aria-checked') === 'true')
124
+ parts.push('[checked]');
125
+ }
126
+ if (h.disabled || el.getAttribute('aria-disabled') === 'true')
127
+ parts.push('[disabled]');
128
+ if (el.getAttribute('aria-expanded') === 'true')
129
+ parts.push('[expanded]');
130
+ if (el.getAttribute('aria-selected') === 'true')
131
+ parts.push('[selected]');
132
+ if (h.required)
133
+ parts.push('[required]');
134
+ const inv = el.getAttribute('aria-invalid');
135
+ if (inv === 'true')
136
+ parts.push('[invalid]');
137
+ return parts.join(' ');
138
+ };
139
+ const hintOf = (el, role, name) => {
140
+ for (const a of ['data-testid', 'data-test', 'data-qa', 'data-cy']) {
141
+ const v = el.getAttribute(a);
142
+ if (v) {
143
+ const sel = `[${a}=${q(v)}]`;
144
+ return { hint: sel, code: a === 'data-testid' ? `page.getByTestId(${q(v)})` : `page.locator(${q(sel)})` };
145
+ }
146
+ }
147
+ const id = el.getAttribute('id');
148
+ if (id && !/\d{3,}|^[a-f0-9-]{16,}$|:r/.test(id) && !(el.getRootNode() instanceof ShadowRoot) && document.querySelectorAll('#' + CSS.escape(id)).length === 1) {
149
+ const sel = '#' + CSS.escape(id);
150
+ return { hint: sel, code: `page.locator(${q(sel)})` };
151
+ }
152
+ const nm = (el.getAttribute('aria-label') || name).replace(/…$/, '');
153
+ if (nm && !name.endsWith('…')) {
154
+ return {
155
+ hint: `role=${role}[name=${q(nm)}]`,
156
+ code: `page.getByRole(${q(role)}, { name: ${q(nm)}, exact: true })`,
157
+ };
158
+ }
159
+ // last resort: positional css
160
+ const path = [];
161
+ let cur = el;
162
+ while (cur && cur !== document.body && path.length < 5) {
163
+ const p = cur.parentElement;
164
+ const tag = cur.tagName.toLowerCase();
165
+ const sib = p ? Array.from(p.children).filter((c) => c.tagName === cur.tagName) : [];
166
+ path.unshift(sib.length > 1 ? `${tag}:nth-of-type(${sib.indexOf(cur) + 1})` : tag);
167
+ cur = p;
168
+ }
169
+ const sel = path.join(' > ');
170
+ return { hint: sel, code: `page.locator(${q(sel)})` };
171
+ };
172
+ const root = (opts.root && document.querySelector(opts.root)) || document.body;
173
+ const items = [];
174
+ const seenText = new Set();
175
+ let truncated = false;
176
+ // Deep walk: light DOM in document order, descending into OPEN shadow roots right after their host.
177
+ // (Closed shadow roots are unreachable from page JS by design.)
178
+ const all = [];
179
+ const walk = (node) => {
180
+ for (const child of Array.from(node.children)) {
181
+ all.push(child);
182
+ if (child.shadowRoot)
183
+ walk(child.shadowRoot);
184
+ walk(child);
185
+ }
186
+ };
187
+ walk(root);
188
+ if (root.shadowRoot)
189
+ walk(root.shadowRoot);
190
+ const interactive = new Set(all.filter((e) => e.matches(INTERACTIVE)));
191
+ const info = new Set(all.filter((e) => e.matches(INFO)));
192
+ for (const el of all) {
193
+ if (items.length >= opts.max) {
194
+ truncated = true;
195
+ break;
196
+ }
197
+ const isI = interactive.has(el);
198
+ const isInfo = info.has(el);
199
+ const isText = !isI && !isInfo && opts.mode === 'full' && el.matches(TEXT);
200
+ if (!isI && !isInfo && !isText)
201
+ continue;
202
+ if (!visible(el))
203
+ continue;
204
+ if (isI) {
205
+ // skip interactive elements nested in another interactive element (e.g. span[role=button] inside <a>)
206
+ const parentI = el.parentElement?.closest(INTERACTIVE);
207
+ if (parentI && interactive.has(parentI) && visible(parentI))
208
+ continue;
209
+ const role = roleOf(el);
210
+ const name = nameOf(el);
211
+ let ref = el.getAttribute('data-fq');
212
+ if (!ref) {
213
+ ref = 'e' + (++w.__fq.n);
214
+ el.setAttribute('data-fq', ref);
215
+ }
216
+ const st = stateOf(el, role);
217
+ const { hint, code } = hintOf(el, role, name);
218
+ items.push({ ref, line: `${ref} ${role}${name ? ' ' + q(name) : ''}${st ? ' ' + st : ''}`, hint, code });
219
+ continue;
220
+ }
221
+ if (isInfo) {
222
+ const role = roleOf(el);
223
+ const txt = clip(el.innerText || el.textContent || '', 100);
224
+ if (!txt)
225
+ continue;
226
+ const tag = el.tagName.toLowerCase();
227
+ const label = /^h[1-3]$/.test(tag) ? tag : role === 'dialog' ? 'dialog' : role === 'alert' ? 'alert' : 'status';
228
+ const key = label + txt;
229
+ if (seenText.has(key))
230
+ continue;
231
+ seenText.add(key);
232
+ seenText.add(txt);
233
+ items.push({ line: `${label} ${q(txt)}` });
234
+ continue;
235
+ }
236
+ // full mode: leaf-ish text blocks only (own text, no block children with text)
237
+ const own = Array.from(el.childNodes).filter((n) => n.nodeType === 3).map((n) => n.textContent || '').join(' ').trim();
238
+ if (own.length < 2)
239
+ continue;
240
+ if (el.closest(INTERACTIVE) || el.closest(INFO))
241
+ continue;
242
+ const txt = clip(el.innerText || own, 100);
243
+ if (seenText.has(txt))
244
+ continue;
245
+ seenText.add(txt);
246
+ items.push({ line: `· ${q(txt)}` });
247
+ }
248
+ return { items, truncated, url: location.href, title: document.title, maxRef: w.__fq.n };
249
+ }
250
+ // Resolves when the DOM has been quiet for `quietMs`, or after `maxMs`.
251
+ export function domSettleInPage(args) {
252
+ return new Promise((resolve) => {
253
+ let timer;
254
+ let finished = false;
255
+ const done = () => { if (finished)
256
+ return; finished = true; obs.disconnect(); resolve(true); };
257
+ const obs = new MutationObserver(() => { clearTimeout(timer); timer = setTimeout(done, args.quietMs); });
258
+ obs.observe(document, { subtree: true, childList: true, attributes: true, characterData: true });
259
+ timer = setTimeout(done, args.quietMs);
260
+ setTimeout(done, args.maxMs);
261
+ });
262
+ }
263
+ // Visible text of the page including open shadow roots (innerText does not cross shadow boundaries).
264
+ export function deepTextInPage() {
265
+ const out = [];
266
+ const skip = new Set(['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEMPLATE']);
267
+ const walk = (node) => {
268
+ for (const child of Array.from(node.childNodes)) {
269
+ if (child.nodeType === 3) {
270
+ const p = child.parentElement;
271
+ const t = (child.textContent || '').trim();
272
+ if (t && (!p?.checkVisibility || p.checkVisibility({ checkOpacity: true, checkVisibilityCSS: true })))
273
+ out.push(t);
274
+ }
275
+ else if (child.nodeType === 1) {
276
+ const el = child;
277
+ if (skip.has(el.tagName))
278
+ continue;
279
+ if (el.shadowRoot)
280
+ walk(el.shadowRoot);
281
+ if (el.tagName === 'INPUT' || el.tagName === 'TEXTAREA')
282
+ continue;
283
+ walk(el);
284
+ }
285
+ }
286
+ };
287
+ walk(document.body || document.documentElement);
288
+ return out.join(' ').replace(/\s+/g, ' ');
289
+ }
290
+ // Runs on an <iframe> element in its parent document: a stable selector + human label for it.
291
+ export function iframeInfoInPage(el) {
292
+ const f = el;
293
+ const q = (v) => JSON.stringify(v);
294
+ const label = f.title || f.name || f.getAttribute('aria-label') || f.id || (f.src ? new URL(f.src, location.href).pathname : 'iframe');
295
+ if (f.id)
296
+ return { sel: `iframe#${CSS.escape(f.id)}`, label };
297
+ if (f.name)
298
+ return { sel: `iframe[name=${q(f.name)}]`, label };
299
+ if (f.title)
300
+ return { sel: `iframe[title=${q(f.title)}]`, label };
301
+ const src = f.getAttribute('src');
302
+ if (src && !src.startsWith('data:') && !src.startsWith('about:'))
303
+ return { sel: `iframe[src=${q(src)}]`, label };
304
+ const all = Array.from(el.getRootNode().querySelectorAll('iframe'));
305
+ return { sel: `iframe >> nth=${all.indexOf(el)}`, label };
306
+ }