testsurfer 0.1.2 → 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.
Files changed (84) hide show
  1. package/README.md +52 -149
  2. package/dist/browser.d.ts +135 -1
  3. package/dist/browser.js +378 -2
  4. package/dist/browser.js.map +1 -1
  5. package/dist/cli.d.ts +16 -0
  6. package/dist/cli.js +140 -0
  7. package/dist/cli.js.map +1 -0
  8. package/dist/client.d.ts +12 -2
  9. package/dist/client.js +73 -4
  10. package/dist/client.js.map +1 -1
  11. package/dist/diff.d.ts +19 -0
  12. package/dist/diff.js +116 -0
  13. package/dist/diff.js.map +1 -0
  14. package/dist/events.d.ts +386 -0
  15. package/dist/events.js +1035 -0
  16. package/dist/events.js.map +1 -0
  17. package/dist/expect.d.ts +135 -26
  18. package/dist/expect.js +634 -130
  19. package/dist/expect.js.map +1 -1
  20. package/dist/frame.d.ts +88 -0
  21. package/dist/frame.js +194 -0
  22. package/dist/frame.js.map +1 -0
  23. package/dist/global.d.ts +12 -0
  24. package/dist/global.js +136 -0
  25. package/dist/global.js.map +1 -0
  26. package/dist/hooks.d.ts +28 -0
  27. package/dist/hooks.js +48 -0
  28. package/dist/hooks.js.map +1 -0
  29. package/dist/index.d.ts +22 -3
  30. package/dist/index.js +21 -3
  31. package/dist/index.js.map +1 -1
  32. package/dist/injected.d.ts +15 -0
  33. package/dist/injected.js +2025 -0
  34. package/dist/injected.js.map +1 -0
  35. package/dist/locator.d.ts +374 -86
  36. package/dist/locator.js +845 -244
  37. package/dist/locator.js.map +1 -1
  38. package/dist/media.d.ts +15 -0
  39. package/dist/media.js +83 -0
  40. package/dist/media.js.map +1 -0
  41. package/dist/net.d.ts +110 -0
  42. package/dist/net.js +498 -0
  43. package/dist/net.js.map +1 -0
  44. package/dist/page.d.ts +448 -5
  45. package/dist/page.js +1187 -31
  46. package/dist/page.js.map +1 -1
  47. package/dist/png.d.ts +28 -0
  48. package/dist/png.js +197 -0
  49. package/dist/png.js.map +1 -0
  50. package/dist/pwconfig.d.ts +66 -0
  51. package/dist/pwconfig.js +77 -0
  52. package/dist/pwconfig.js.map +1 -0
  53. package/dist/register.d.ts +6 -0
  54. package/dist/register.js +9 -0
  55. package/dist/register.js.map +1 -0
  56. package/dist/request.d.ts +29 -0
  57. package/dist/request.js +75 -0
  58. package/dist/request.js.map +1 -0
  59. package/dist/runner.d.ts +99 -15
  60. package/dist/runner.js +354 -58
  61. package/dist/runner.js.map +1 -1
  62. package/dist/screenshot.d.ts +35 -0
  63. package/dist/screenshot.js +171 -0
  64. package/dist/screenshot.js.map +1 -0
  65. package/dist/selector.d.ts +55 -0
  66. package/dist/selector.js +208 -0
  67. package/dist/selector.js.map +1 -0
  68. package/dist/selectors.d.ts +13 -0
  69. package/dist/selectors.js +16 -0
  70. package/dist/selectors.js.map +1 -0
  71. package/dist/serialize.d.ts +17 -0
  72. package/dist/serialize.js +149 -0
  73. package/dist/serialize.js.map +1 -0
  74. package/dist/shim.d.ts +15 -0
  75. package/dist/shim.js +211 -0
  76. package/dist/shim.js.map +1 -0
  77. package/dist/testinfo.d.ts +62 -0
  78. package/dist/testinfo.js +23 -0
  79. package/dist/testinfo.js.map +1 -0
  80. package/dist/values.d.ts +67 -0
  81. package/dist/values.js +293 -0
  82. package/dist/values.js.map +1 -0
  83. package/package.json +10 -3
  84. package/skills/testsurfer/SKILL.md +55 -0
package/dist/locator.js CHANGED
@@ -1,316 +1,917 @@
1
1
  /**
2
- * Locators: lazy, re-resolving element handles over the a11y tree.
2
+ * Locators: lazy, re-resolving element queries.
3
3
  *
4
- * A locator stores a query (role + name, text, or label), not a ref.
5
- * Every action and assertion re-resolves the query against a fresh
6
- * view, so locators survive re-renders and navigation. Actions retry
7
- * on STALE_TOKEN and NOT_FOUND until the action timeout elapses.
4
+ * A locator stores a chain of queries, never an element. Every action
5
+ * and read resolves the chain again, in the page, through the engine
6
+ * in src/injected.ts, so locators survive re-renders and navigation.
7
+ * Single-element operations are strict: more than one match is an
8
+ * error unless first(), last() or nth() picks one. Actions wait until
9
+ * the element is attached, visible, enabled and not covered, then
10
+ * click with trusted native input at its center.
8
11
  */
9
- import { StrictModeError, TimeoutError, WireError } from "./errors.js";
10
- import { isHidden, walk } from "./tree.js";
12
+ import { parseSelector } from "./selector.js";
13
+ import { StrictModeError, TimeoutError } from "./errors.js";
11
14
  import { renderSnapshot } from "./aria.js";
12
- import { ROLE_TO_CODES } from "./roles.js";
13
- const FIELD_CODES = new Set(['tf', 'ta', 'sel', 'chk', 'rad']);
14
- const normalize = (s) => s.replace(/\s+/g, ' ').trim();
15
- function matchesName(label, expected, exact) {
16
- const norm = normalize(label);
17
- if (expected instanceof RegExp)
18
- return expected.test(norm);
19
- const want = normalize(expected);
20
- return exact ? norm === want : norm.toLowerCase() === want.toLowerCase();
15
+ import { serializeValue } from "./serialize.js";
16
+ // --- describing ----------------------------------------------------------
17
+ /** A string in Playwright's locator notation: single quotes, escaped. */
18
+ const q = (s) => `'${s.replace(/\\/g, '\\\\').replace(/'/g, "\\'")}'`;
19
+ const lit = (v) => (v instanceof RegExp ? String(v) : q(v));
20
+ function describeOptions(o) {
21
+ const parts = Object.entries(o)
22
+ .filter(([, v]) => v !== undefined)
23
+ .map(([k, v]) => `${k}: ${typeof v === 'string' || v instanceof RegExp ? lit(v) : String(v)}`);
24
+ return parts.length ? `, { ${parts.join(', ')} }` : '';
21
25
  }
22
- function matchesText(label, expected, exact) {
23
- const norm = normalize(label);
24
- if (expected instanceof RegExp)
25
- return expected.test(norm);
26
- const want = normalize(expected);
27
- return exact ? norm === want : norm.toLowerCase().includes(want.toLowerCase());
26
+ export function describeQuery(query) {
27
+ switch (query.kind) {
28
+ case 'role':
29
+ return `getByRole(${q(query.role)}${describeOptions({ ...query.options })})`;
30
+ case 'text':
31
+ return `getByText(${lit(query.text)}${query.options.exact ? ', { exact: true }' : ''})`;
32
+ case 'label':
33
+ return `getByLabel(${lit(query.text)}${query.options.exact ? ', { exact: true }' : ''})`;
34
+ case 'css':
35
+ return `locator(${q(query.selector)})`;
36
+ case 'xpath':
37
+ return `locator(${q(`xpath=${query.xpath}`)})`;
38
+ case 'attr':
39
+ return query.method === 'locator'
40
+ ? `locator(${q(`${query.attr}=${String(query.value)}`)})`
41
+ : `${query.method}(${lit(query.value)}${!query.exact || query.method === 'getByTestId' ? '' : ', { exact: true }'})`;
42
+ case 'and':
43
+ case 'or':
44
+ return `${query.left.toString()}.${query.kind}(${query.right.toString()})`;
45
+ case 'frame':
46
+ return 'contentFrame()';
47
+ case 'self':
48
+ return '';
49
+ case 'invalid':
50
+ return query.selector;
51
+ case 'handle':
52
+ return 'ElementHandle';
53
+ }
28
54
  }
29
- /** A node's label plus, for a labelled form field, its <label> text. */
30
- function names(node) {
31
- const lbl = node.attrs['lbl'];
32
- return lbl ? [node.label, lbl] : [node.label];
55
+ function describeFilter(f) {
56
+ const parts = [];
57
+ if (f.hasText !== undefined)
58
+ parts.push(`hasText: ${lit(f.hasText)}`);
59
+ if (f.hasNotText !== undefined)
60
+ parts.push(`hasNotText: ${lit(f.hasNotText)}`);
61
+ if (f.has)
62
+ parts.push(`has: ${f.has.toString()}`);
63
+ if (f.hasNot)
64
+ parts.push(`hasNot: ${f.hasNot.toString()}`);
65
+ if (f.visible !== undefined)
66
+ parts.push(`visible: ${f.visible}`);
67
+ return `filter({ ${parts.join(', ')} })`;
33
68
  }
34
- function matchesQuery(node, query) {
69
+ const wm = (v, exact = false) => v instanceof RegExp ? { re: [v.source, v.flags] } : { s: v, exact };
70
+ function wireQuery(query) {
35
71
  switch (query.kind) {
36
72
  case 'role': {
37
- const codes = ROLE_TO_CODES[query.role] ?? [query.role];
38
- if (!codes.includes(node.role))
39
- return false;
40
- const { name, exact = false, level } = query.options;
41
- if (level !== undefined && node.attrs['level'] !== String(level))
42
- return false;
43
- if (name !== undefined && !names(node).some((n) => matchesName(n, name, exact)))
44
- return false;
45
- return true;
73
+ const { name, exact, nameFull, ...rest } = query.options;
74
+ const nm = name === undefined ? undefined : nameFull && typeof name === 'string' ? { s: name, full: true } : wm(name, exact);
75
+ return { k: 'role', role: query.role, o: { ...rest, ...(nm ? { name: nm } : {}) } };
46
76
  }
47
77
  case 'text':
48
- return node.label !== '' && matchesText(node.label, query.text, query.options.exact ?? false);
49
- case 'label': {
50
- // The field's <label> text (lbl=, vibesurfer 0.2.12+) is the
51
- // label; aria-label lands in the node label itself.
52
- if (!FIELD_CODES.has(node.role))
53
- return false;
54
- const exact = query.options.exact ?? false;
55
- return names(node).some((n) => matchesText(n, query.text, exact));
56
- }
78
+ return { k: 'text', t: wm(query.text, query.options.exact), light: query.light, legacy: query.legacy };
79
+ case 'label':
80
+ return { k: 'label', t: wm(query.text, query.options.exact) };
81
+ case 'css':
82
+ return { k: 'css', sel: query.selector, light: query.light };
83
+ case 'xpath':
84
+ return { k: 'xpath', xp: query.xpath };
85
+ case 'attr':
86
+ return { k: 'attr', a: query.attr, t: wm(query.value, query.exact), testid: query.method === 'getByTestId' || query.method === 'locator' };
87
+ case 'and':
88
+ case 'or':
89
+ return { k: query.kind, l: query.left.wire(), r: query.right.wire() };
90
+ case 'frame':
91
+ return { k: 'frame' };
92
+ case 'self':
93
+ return { k: 'self' };
94
+ case 'invalid':
95
+ throw new Error(`Error: ${query.message}`);
96
+ case 'handle':
97
+ return { k: 'handle', id: query.id };
57
98
  }
58
99
  }
59
- export function describeQuery(query) {
60
- switch (query.kind) {
61
- case 'role':
62
- return `getByRole(${JSON.stringify(query.role)}${query.options.name !== undefined ? `, { name: ${String(query.options.name)} }` : ''})`;
63
- case 'text':
64
- return `getByText(${String(query.text)})`;
65
- case 'label':
66
- return `getByLabel(${String(query.text)})`;
100
+ function wireFilter(f) {
101
+ return {
102
+ hasText: f.hasText !== undefined ? wm(f.hasText) : undefined,
103
+ hasNotText: f.hasNotText !== undefined ? wm(f.hasNotText) : undefined,
104
+ has: f.has ? f.has.wire() : undefined,
105
+ hasNot: f.hasNot ? f.hasNot.wire() : undefined,
106
+ visible: f.visible,
107
+ };
108
+ }
109
+ // --- selectors -----------------------------------------------------------
110
+ export function byAttr(method, attr, value, exact) {
111
+ return { kind: 'attr', method, attr, value, exact };
112
+ }
113
+ const step = (query) => ({ query, filters: [], index: null });
114
+ /** A Playwright selector string as chain steps. */
115
+ export function selectorSteps(selector) {
116
+ try {
117
+ return parseSteps(selector);
118
+ }
119
+ catch (e) {
120
+ // Like Playwright, a bad selector fails when the locator is used, not when it is made.
121
+ return [step({ kind: 'invalid', selector, message: e instanceof Error ? e.message : String(e) })];
67
122
  }
68
123
  }
69
- export function findMatches(snap, query) {
70
- const out = [];
71
- for (const node of walk(snap)) {
72
- if (matchesQuery(node, query))
73
- out.push(node);
124
+ function parseSteps(selector) {
125
+ const parts = parseSelector(selector);
126
+ const at = parts.findIndex((p) => p.capture);
127
+ if (at < 0 || at === parts.length - 1)
128
+ return stepsOf(parts);
129
+ // A capture: keep the marked part's matches that contain the rest.
130
+ const head = stepsOf(parts.slice(0, at + 1));
131
+ const rest = stepsOf(parts.slice(at + 1));
132
+ const tail = head[head.length - 1];
133
+ tail.filters.push({ has: new Locator(null, rest) });
134
+ tail.capture = true;
135
+ return head;
136
+ }
137
+ function stepsOf(parts) {
138
+ const steps = [];
139
+ const last = (what) => {
140
+ const s = steps[steps.length - 1];
141
+ if (!s)
142
+ throw new Error(`"${what}" cannot start a selector`);
143
+ return s;
144
+ };
145
+ for (const p of parts) {
146
+ switch (p.kind) {
147
+ case 'nth':
148
+ last('nth=').index = p.index;
149
+ break;
150
+ case 'visible':
151
+ last('visible=').filters.push({ visible: p.visible });
152
+ break;
153
+ case 'css':
154
+ steps.push(step({ kind: 'css', selector: p.selector, ...(p.light ? { light: true } : {}) }));
155
+ break;
156
+ case 'xpath':
157
+ steps.push(step(p));
158
+ break;
159
+ case 'text':
160
+ steps.push(step({ kind: 'text', text: p.text, options: { exact: p.exact }, ...(p.light ? { light: true } : {}), ...(p.legacy ? { legacy: true } : {}) }));
161
+ break;
162
+ case 'attr':
163
+ steps.push(step(byAttr('locator', p.attr, p.value, true)));
164
+ break;
165
+ case 'role':
166
+ steps.push(step({ kind: 'role', role: p.role, options: p.options }));
167
+ break;
168
+ }
74
169
  }
75
- return out;
170
+ if (steps.length === 0)
171
+ throw new Error('empty selector');
172
+ return steps;
76
173
  }
77
174
  const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
78
- const POLL_MS = 10;
79
- /** Drop hid-marked matches when at least one unmarked match exists. */
80
- function preferVisible(snap, all) {
81
- const visible = all.filter((n) => !isHidden(snap, n));
82
- return visible.length > 0 ? visible : all;
83
- }
175
+ /** Retry cadence, as Playwright's: fast at first, then backing off. */
176
+ const BACKOFF = [0, 20, 50, 100, 100, 250];
177
+ const isRetry = (v) => typeof v === 'object' && v !== null && 'retry' in v && typeof v.retry === 'string';
178
+ const MIME = {
179
+ '.txt': 'text/plain', '.html': 'text/html', '.htm': 'text/html', '.css': 'text/css', '.js': 'text/javascript',
180
+ '.json': 'application/json', '.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.gif': 'image/gif',
181
+ '.svg': 'image/svg+xml', '.pdf': 'application/pdf', '.webp': 'image/webp', '.csv': 'text/csv', '.zip': 'application/zip',
182
+ };
84
183
  export class Locator {
85
- page;
86
- query;
87
- index;
88
- /** Refs from the previous visibility resolve, used as the composite layout hint. */
89
- layoutHint = [];
90
- constructor(page, query, index = null) {
91
- this.page = page;
92
- this.query = query;
93
- this.index = index;
184
+ owner;
185
+ steps;
186
+ desc;
187
+ constructor(page, steps, description) {
188
+ this.owner = page;
189
+ this.steps = Array.isArray(steps) ? steps : [step(steps)];
190
+ this.desc = description;
94
191
  }
95
192
  /** The owning page's expect timeout, used as the assertion default. */
96
193
  get expectTimeout() {
97
- return this.page.timeouts.expect;
194
+ return this.owner.timeouts.expect;
195
+ }
196
+ /** The page this locator belongs to. */
197
+ page() {
198
+ return this.owner;
98
199
  }
99
- /** Pick the first match instead of failing on multiple matches. */
200
+ /** The chain in the engine's wire form. */
201
+ wire() {
202
+ return this.steps.map((s, i) => {
203
+ if (s.capture && s.index !== null)
204
+ throw new Error("Error: Can't query n-th element in a request with the capture.");
205
+ const q = wireQuery(s.query);
206
+ // A frame hop names its <iframe> locator in errors.
207
+ if (s.query.kind === 'frame')
208
+ q['d'] = Locator.stepsText(this.owner, this.steps.slice(0, i));
209
+ return { q, f: s.filters.map(wireFilter), i: s.index };
210
+ });
211
+ }
212
+ /** Steps up to and including the last frame hop, and the rest. */
213
+ frameSplit() {
214
+ let at = -1;
215
+ this.steps.forEach((s, i) => {
216
+ if (s.query.kind === 'frame')
217
+ at = i;
218
+ });
219
+ return at < 0 ? null : { prefix: this.steps.slice(0, at + 1), rest: this.steps.slice(at + 1) };
220
+ }
221
+ static stepsText(owner, steps) {
222
+ return new Locator(owner, steps).toString();
223
+ }
224
+ /**
225
+ * and()/or(): both sides inside the same frame compose inside it;
226
+ * frame locators on different frames cannot be combined.
227
+ */
228
+ composite(kind, other) {
229
+ const a = this.frameSplit();
230
+ const b = other.frameSplit();
231
+ if (!a && !b)
232
+ return new Locator(this.owner, { kind, left: this, right: other });
233
+ const text = `${this.toString()}.${kind}(${other.toString()})`;
234
+ if (a && b && Locator.stepsText(this.owner, a.prefix) === Locator.stepsText(this.owner, b.prefix) && a.rest.length && b.rest.length) {
235
+ const inner = new Locator(this.owner, { kind, left: new Locator(this.owner, a.rest), right: new Locator(other.owner, b.rest) });
236
+ return new Locator(this.owner, [...a.prefix, ...inner.steps], text);
237
+ }
238
+ return new Locator(this.owner, {
239
+ kind: 'invalid',
240
+ selector: text,
241
+ message: `Frame locators are not allowed inside composite locators, while querying "${text}"`,
242
+ }, text);
243
+ }
244
+ get tail() {
245
+ const s = this.steps[this.steps.length - 1];
246
+ if (!s)
247
+ throw new Error('empty locator');
248
+ return s;
249
+ }
250
+ withTail(change) {
251
+ return new Locator(this.owner, [...this.steps.slice(0, -1), { ...this.tail, ...change }]);
252
+ }
253
+ /** This chain followed by `more`. */
254
+ extendWith(more) {
255
+ return new Locator(this.owner, [...this.steps, ...more]);
256
+ }
257
+ chain(query) {
258
+ return this.extendWith([step(query)]);
259
+ }
260
+ // --- building -------------------------------------------------------
100
261
  first() {
101
262
  return this.nth(0);
102
263
  }
103
- /** Pick the i-th match (0-based) instead of failing on multiple matches. */
264
+ last() {
265
+ return this.nth(-1);
266
+ }
267
+ /** The i-th match (0-based; negative counts from the end). */
104
268
  nth(index) {
105
- return new Locator(this.page, this.query, index);
269
+ // An index after an index picks among that one match.
270
+ if (this.tail.index !== null)
271
+ return this.extendWith([{ query: { kind: 'self' }, filters: [], index }]);
272
+ return this.withTail({ index });
273
+ }
274
+ filter(options) {
275
+ for (const [key, inner] of [['has', options.has], ['hasNot', options.hasNot]]) {
276
+ // An inner locator searches inside this one's matches, so it cannot hop into another frame.
277
+ if (inner && inner.frameSplit() && !this.frameSplit())
278
+ throw new Error(`Inner "${key}" locator must belong to the same frame.`);
279
+ }
280
+ // A filter after an index filters that one match.
281
+ if (this.tail.index !== null)
282
+ return this.extendWith([{ query: { kind: 'self' }, filters: [options], index: null }]);
283
+ return this.withTail({ filters: [...this.tail.filters, options] });
284
+ }
285
+ and(other) {
286
+ return this.composite('and', other);
287
+ }
288
+ or(other) {
289
+ return this.composite('or', other);
290
+ }
291
+ /** A selector (or another locator) searched inside this locator's matches. */
292
+ locator(selector, options) {
293
+ const l = typeof selector !== 'string' ? this.extendWith(selector.steps) : this.extendWith(selectorSteps(selector));
294
+ return options && Object.keys(options).length ? l.filter(options) : l;
295
+ }
296
+ getByRole(role, options = {}) {
297
+ return this.chain({ kind: 'role', role, options });
298
+ }
299
+ getByText(text, options = {}) {
300
+ return this.chain({ kind: 'text', text, options });
301
+ }
302
+ getByLabel(text, options = {}) {
303
+ return this.chain({ kind: 'label', text, options });
304
+ }
305
+ getByTestId(id) {
306
+ return this.chain(byAttr('getByTestId', this.owner.testIdAttribute, id, true));
307
+ }
308
+ getByPlaceholder(text, options = {}) {
309
+ return this.chain(byAttr('getByPlaceholder', 'placeholder', text, options.exact ?? false));
310
+ }
311
+ getByAltText(text, options = {}) {
312
+ return this.chain(byAttr('getByAltText', 'alt', text, options.exact ?? false));
313
+ }
314
+ getByTitle(text, options = {}) {
315
+ return this.chain(byAttr('getByTitle', 'title', text, options.exact ?? false));
316
+ }
317
+ /** `fn(element, arg)` in the page, keeping the result there as a handle. */
318
+ async evaluateHandle(fn, arg, options = {}) {
319
+ const h = await this.elementHandle(options);
320
+ return h.evaluateHandle(fn, arg);
321
+ }
322
+ /** The matched element as an ElementHandle (waits for it, strict). */
323
+ async elementHandle(options = {}) {
324
+ const id = await this.waitOne('locator.elementHandle', 'adopt', {}, options.timeout);
325
+ return new ElementHandle(this.owner, id);
326
+ }
327
+ /** Every current match as an ElementHandle. */
328
+ async elementHandles() {
329
+ const ids = await this.many('adoptAll');
330
+ return ids.map((id) => new ElementHandle(this.owner, id));
331
+ }
332
+ /** The first match as an ElementHandle, or null (no waiting, not strict). */
333
+ async firstHandle() {
334
+ const r = await this.run('adopt', {}, { first: true });
335
+ return r.none ? null : new ElementHandle(this.owner, r.v);
336
+ }
337
+ /** The content of the iframe this locator matches. */
338
+ contentFrame() {
339
+ return new FrameLocator(this);
340
+ }
341
+ /** The iframe matching `selector` inside this locator's matches. */
342
+ frameLocator(selector) {
343
+ return new FrameLocator(this.locator(selector));
344
+ }
345
+ /** The same locator, shown as `description` in errors and toString(). */
346
+ /** The text given to describe(), or null. */
347
+ description() {
348
+ return this.desc ?? null;
349
+ }
350
+ describe(description) {
351
+ return new Locator(this.owner, this.steps, description);
106
352
  }
107
353
  toString() {
108
- const base = describeQuery(this.query);
109
- return this.index === null ? base : `${base}.nth(${this.index})`;
354
+ if (this.desc)
355
+ return this.desc;
356
+ const out = [];
357
+ for (const s of this.steps) {
358
+ let part = describeQuery(s.query);
359
+ for (const f of s.filters)
360
+ part += `.${describeFilter(f)}`;
361
+ if (s.index !== null)
362
+ part += s.index === 0 ? '.first()' : s.index === -1 ? '.last()' : `.nth(${s.index})`;
363
+ out.push(part);
364
+ }
365
+ return out.reduce((acc, p) => (acc === '' ? p : p.startsWith('.') ? acc + p : `${acc}.${p}`), '');
366
+ }
367
+ // --- engine calls ---------------------------------------------------
368
+ run(op, args, opts = {}, fn) {
369
+ return this.owner.engineRun({ steps: this.wire(), op, args, ...opts }, fn);
370
+ }
371
+ strictError(apiName, r) {
372
+ const list = (r.strict ?? []).map((p, i) => ` ${i + 1}) ${p}`).join('\n');
373
+ return new StrictModeError(`${apiName}: Error: strict mode violation: ${this.toString()} resolved to ${r.n} elements:\n${list}\n`);
110
374
  }
111
375
  /**
112
- * All current matches against a fresh view. Visible matches are
113
- * preferred, judged from the tree alone (hid=1 on self or ancestor):
114
- * hidden duplicates of interactive elements are dropped when a
115
- * visible one exists. No layout round trip.
376
+ * Run a one-element op, waiting until something matches and the op
377
+ * stops asking to retry. Strict-mode violations fail at once.
116
378
  */
117
- async resolveAll() {
118
- const snap = await this.page.view();
119
- return preferVisible(snap, findMatches(snap, this.query));
379
+ async waitOne(apiName, op, args, timeout, fn) {
380
+ const budget = timeout ?? this.owner.timeouts.action;
381
+ const deadline = Date.now() + budget;
382
+ let why = '';
383
+ for (let i = 0;; i++) {
384
+ await this.owner.runLocatorHandlers();
385
+ const r = await this.run(op, args, {}, fn);
386
+ if (r.strict)
387
+ throw this.strictError(apiName, r);
388
+ if (!r.none) {
389
+ if (!isRetry(r.v))
390
+ return r.v;
391
+ why = r.v.retry;
392
+ }
393
+ if (budget > 0 && Date.now() >= deadline) {
394
+ throw new TimeoutError(`${apiName}: Timeout ${budget}ms exceeded.\nCall log:\n - waiting for ${this.toString()}` +
395
+ (why ? `\n - ${why}` : ''));
396
+ }
397
+ await sleep(BACKOFF[Math.min(i, BACKOFF.length - 1)]);
398
+ }
399
+ }
400
+ /** One-element op with no waiting: undefined when nothing matches. */
401
+ async peek(apiName, op, args) {
402
+ const r = await this.run(op, args);
403
+ if (r.strict)
404
+ throw this.strictError(apiName, r);
405
+ if (r.none)
406
+ return { found: false };
407
+ return { found: true, v: r.v, preview: r.p ?? '' };
408
+ }
409
+ /** A multi-element op over the current matches. */
410
+ async many(op, args, fn) {
411
+ return (await this.run(op, args, { many: true }, fn)).v;
120
412
  }
413
+ // --- actions --------------------------------------------------------
121
414
  /**
122
- * Matches that are currently visible. Interactive refs carry hid=1
123
- * in the tree, but hidden non-interactive elements (a heading inside
124
- * a `hidden` container) do not, so survivors are verified against
125
- * vs_layout's per-ref visible flag.
415
+ * Click the element. A left click without modifiers is a trusted
416
+ * native click at the element's center; other buttons, modifiers and
417
+ * multi-clicks are dispatched in the page.
126
418
  */
127
- async resolveVisible() {
128
- // Polling assertions resolve the same query repeatedly; the ref
129
- // set from the previous poll rides along as a --layout composite
130
- // hint, making the steady-state poll a single round trip. Refs
131
- // that changed since last time are fetched separately.
132
- const { snap, rects } = await this.page.viewWithLayout(this.layoutHint);
133
- const candidates = findMatches(snap, this.query).filter((n) => !isHidden(snap, n));
134
- this.layoutHint = candidates.map((n) => n.ref);
135
- if (candidates.length === 0)
136
- return [];
137
- const missing = candidates.filter((n) => !rects.has(n.ref));
138
- if (missing.length > 0) {
139
- const more = await this.page.layout(missing.map((n) => n.ref));
140
- for (const [ref, rect] of more)
141
- rects.set(ref, rect);
419
+ async click(options = {}) {
420
+ const pt = await this.waitOne('locator.click', 'clickPoint', { position: options.position, force: options.force }, options.timeout);
421
+ if (options.trial)
422
+ return;
423
+ if (options.delay)
424
+ await sleep(options.delay);
425
+ const synthetic = (options.button && options.button !== 'left') ||
426
+ (options.modifiers && options.modifiers.length > 0) ||
427
+ (options.clickCount ?? 1) > 1;
428
+ if (synthetic) {
429
+ await this.waitOne('locator.click', 'synthClick', options, options.timeout);
430
+ }
431
+ else {
432
+ let at = pt;
433
+ for (let attempt = 0;; attempt++) {
434
+ await this.owner.clickAt(at.x, at.y);
435
+ await this.run('settleFocus', {}, { first: true }).catch(() => { });
436
+ if (attempt === 2 || !(await this.clickWasLost()))
437
+ break;
438
+ // The page re-rendered between press and release, so the two
439
+ // landed on different elements and no click fired: click the
440
+ // element again while it is there.
441
+ const again = await this.run('clickPoint', { position: options.position, force: options.force }, { first: true }).catch(() => null);
442
+ if (!again || again.none || isRetry(again.v))
443
+ break;
444
+ at = again.v;
445
+ }
142
446
  }
143
- return candidates.filter((n) => rects.get(n.ref)?.visible === true);
144
447
  }
145
- /** Strict-mode selection: exactly one node, nth() overrides, null when none. */
146
- pickOne(matches) {
147
- if (this.index !== null)
148
- return matches[this.index] ?? null;
149
- if (matches.length === 0)
150
- return null;
151
- if (matches.length > 1) {
152
- const list = matches
153
- .slice(0, 5)
154
- .map((m) => ` ref=${m.ref} ${m.role} ${JSON.stringify(m.label)}`)
155
- .join('\n');
156
- throw new StrictModeError(`${this.toString()} matched ${matches.length} elements:\n${list}\nNarrow the query or use .first() / .nth(i).`);
448
+ /**
449
+ * Whether the last native click's release reached the page without a
450
+ * click event. The page can answer before the mouse events arrive
451
+ * (WebKit sends each once the last is acknowledged), so this waits
452
+ * for the release first; click follows mouseup in the same dispatch.
453
+ */
454
+ async clickWasLost() {
455
+ const deadline = Date.now() + 500;
456
+ for (;;) {
457
+ const r = await this.run('clickSeen', {}, { first: true }).catch(() => null);
458
+ if (!r || r.none || !r.v)
459
+ return false;
460
+ if (r.v.click)
461
+ return false;
462
+ if (r.v.up)
463
+ return true;
464
+ if (Date.now() >= deadline)
465
+ return false;
466
+ await sleep(10);
157
467
  }
158
- return matches[0] ?? null;
468
+ }
469
+ async dblclick(options = {}) {
470
+ await this.click({ ...options, clickCount: 2 });
471
+ }
472
+ async tap(options = {}) {
473
+ await this.click(options);
474
+ }
475
+ /** Move the pointer over the element with trusted input. */
476
+ async hover(options = {}) {
477
+ const pt = await this.waitOne('locator.hover', 'clickPoint', { position: options.position, force: options.force, enabled: false }, options.timeout);
478
+ if (options.trial)
479
+ return;
480
+ await this.owner.mouse.move(pt.x, pt.y);
481
+ }
482
+ /** Replace the field's value (inputs, textareas, contenteditable). */
483
+ async fill(value, options = {}) {
484
+ await this.waitOne('locator.fill', 'fill', { value, force: options.force }, options.timeout);
485
+ }
486
+ async clear(options = {}) {
487
+ await this.fill('', options);
159
488
  }
160
489
  /**
161
- * Resolve an action target against the cached snapshot when it is
162
- * still baseline-synced. Optimistic concurrency covers the race: if
163
- * the page changed since, the act fails with STALE_TOKEN, the retry
164
- * loop refreshes, and we re-resolve.
490
+ * Focus the element, then type with trusted per-character key events
491
+ * (isTrusted=true), for editors that ignore fill().
165
492
  */
166
- async resolveForAction() {
167
- const snap = await this.page.actionSnapshot();
168
- return this.pickOne(preferVisible(snap, findMatches(snap, this.query)));
493
+ async pressSequentially(text, options = {}) {
494
+ await this.waitOne('locator.pressSequentially', 'focus', {}, options.timeout);
495
+ await this.owner.typeTrusted(text);
169
496
  }
170
- /** Wait until the locator resolves to one node, then run the action, retrying on staleness. */
171
- async withResolved(actionName, action, timeout) {
172
- const budget = timeout ?? this.page.timeouts.action;
173
- const deadline = Date.now() + budget;
174
- let lastNote = 'no matching element';
497
+ /** Same as pressSequentially(). */
498
+ async type(text, options = {}) {
499
+ await this.pressSequentially(text, options);
500
+ }
501
+ /** Focus the element and press a key or chord, e.g. `Enter` or `Control+A`. */
502
+ async press(key, options = {}) {
503
+ await this.waitOne('locator.press', 'press', { key }, options.timeout);
504
+ }
505
+ async focus(options = {}) {
506
+ await this.waitOne('locator.focus', 'focus', {}, options.timeout);
507
+ }
508
+ async blur(options = {}) {
509
+ await this.waitOne('locator.blur', 'blur', {}, options.timeout);
510
+ }
511
+ async setChecked(checked, options = {}) {
512
+ const state = await this.waitOne('locator.setChecked', 'checked', {}, options.timeout);
513
+ if (state === checked)
514
+ return;
515
+ await this.click(options);
516
+ if (options.trial)
517
+ return;
518
+ // The click's events can still be on their way to the page (WebKitGTK
519
+ // sends a mouse event once the last one is acknowledged), so give
520
+ // the state a moment to change before calling the click a failure.
521
+ const deadline = Date.now() + 1000;
175
522
  for (;;) {
176
- let stale = false;
177
- try {
178
- const node = await this.resolveForAction();
179
- if (node)
180
- return await action(node);
181
- }
182
- catch (e) {
183
- if (e instanceof WireError && (e.code === 'STALE_TOKEN' || e.code === 'NOT_FOUND')) {
184
- lastNote = `retrying after ${e.code}`;
185
- stale = true;
186
- }
187
- else {
188
- throw e;
189
- }
190
- }
523
+ const after = await this.peek('locator.setChecked', 'checked');
524
+ if (!after.found || after.v === checked)
525
+ return;
526
+ if (Date.now() >= deadline)
527
+ throw new Error('Clicking the checkbox did not change its state');
528
+ await sleep(10);
529
+ }
530
+ }
531
+ async check(options = {}) {
532
+ await this.setChecked(true, options);
533
+ }
534
+ async uncheck(options = {}) {
535
+ await this.setChecked(false, options);
536
+ }
537
+ /** Select options by value or label (or `{ value, label, index }`). Returns the selected values. */
538
+ async selectOption(values, options = {}) {
539
+ const list = values === null ? [] : Array.isArray(values) ? values : [values];
540
+ const wanted = list.map((v) => (typeof v === 'string' ? { valueOrLabel: v } : v));
541
+ const budget = options.timeout ?? this.owner.timeouts.action;
542
+ const deadline = Date.now() + budget;
543
+ for (let i = 0;; i++) {
544
+ const r = await this.waitOne('locator.selectOption', 'selectOption', { values: wanted }, Math.max(1, deadline - Date.now()));
545
+ if (r.values)
546
+ return r.values;
191
547
  if (Date.now() >= deadline) {
192
- throw new TimeoutError(`${actionName} on ${this.toString()} timed out after ${budget}ms (${lastNote})`);
548
+ throw new TimeoutError(`locator.selectOption: Timeout ${budget}ms exceeded.\n - did not find some options`);
193
549
  }
194
- // A staleness rejection means the page just changed; retry
195
- // immediately against a fresh view. Only a missing element earns
196
- // a poll-tick sleep.
197
- if (!stale)
198
- await sleep(POLL_MS);
550
+ await sleep(BACKOFF[Math.min(i, BACKOFF.length - 1)]);
199
551
  }
200
552
  }
553
+ async selectText(options = {}) {
554
+ await this.waitOne('locator.selectText', 'selectText', {}, options.timeout);
555
+ }
556
+ /** Set the files of an `<input type=file>`: paths, or `{ name, mimeType, buffer }`. */
557
+ async setInputFiles(files, options = {}) {
558
+ const fs = await import('node:fs/promises');
559
+ const nodePath = await import('node:path');
560
+ const list = Array.isArray(files) ? files : [files];
561
+ const payload = await Promise.all(list.map(async (f) => {
562
+ if (typeof f === 'string') {
563
+ const buf = await fs.readFile(f);
564
+ return {
565
+ name: nodePath.basename(f),
566
+ mimeType: MIME[nodePath.extname(f).toLowerCase()] ?? 'application/octet-stream',
567
+ b64: buf.toString('base64'),
568
+ };
569
+ }
570
+ return { name: f.name, mimeType: f.mimeType, b64: f.buffer.toString('base64') };
571
+ }));
572
+ await this.waitOne('locator.setInputFiles', 'setFiles', { files: payload }, options.timeout);
573
+ }
574
+ async dispatchEvent(type, eventInit = {}, options = {}) {
575
+ await this.waitOne('locator.dispatchEvent', 'dispatch', { type, init: eventInit }, options.timeout);
576
+ }
577
+ async scrollIntoViewIfNeeded(options = {}) {
578
+ await this.waitOne('locator.scrollIntoViewIfNeeded', 'scroll', {}, options.timeout);
579
+ }
580
+ /** Accepted for compatibility; there is no headed browser to highlight in. */
581
+ async highlight() { }
201
582
  /**
202
- * Click the element. Visible targets get a trusted native click at
203
- * their rect center via vs_click_at, which honors the page's input
204
- * mode (robotic by default; the humanized path behind plain
205
- * `vs_act click` costs seconds per click). Zero-size or hidden
206
- * targets cannot be hit by coordinates and fall back to vs_act,
207
- * whose JS path dispatches regardless of geometry.
583
+ * Drag this element onto `target` with a trusted press, move and
584
+ * release from center to center. vibesurfer also fires the HTML5
585
+ * drag events, so native draggable and react-dnd lists see the drop.
208
586
  */
209
- async click(options) {
210
- await this.withResolved('click', async (n) => {
211
- if (this.page.clickVia === 'act') {
212
- await this.page.act(n.ref, 'click', undefined, { mode: this.page.inputMode });
213
- return;
214
- }
215
- const rects = await this.page.layout([n.ref]);
216
- const r = rects.get(n.ref);
217
- if (r && r.visible && r.w > 1 && r.h > 1) {
218
- await this.page.clickAt(r.x + r.w / 2, r.y + r.h / 2);
587
+ async dragTo(target, options = {}) {
588
+ const from = await this.boundingBox(options);
589
+ if (!from)
590
+ throw new TimeoutError(`locator.dragTo: ${this.toString()} is not rendered`);
591
+ const to = await target.boundingBox(options);
592
+ if (!to)
593
+ throw new TimeoutError(`locator.dragTo: ${target.toString()} is not rendered`);
594
+ await this.owner.mouse.drag(from.x + from.width / 2, from.y + from.height / 2, to.x + to.width / 2, to.y + to.height / 2);
595
+ }
596
+ /** Wait for the locator to reach a state: attached, detached, visible (default) or hidden. */
597
+ async waitFor(options = {}) {
598
+ const state = options.state ?? 'visible';
599
+ const budget = options.timeout ?? this.owner.timeouts.action;
600
+ const deadline = Date.now() + budget;
601
+ for (let i = 0;; i++) {
602
+ let ok;
603
+ if (state === 'attached' || state === 'detached') {
604
+ const n = await this.count();
605
+ ok = state === 'attached' ? n > 0 : n === 0;
219
606
  }
220
607
  else {
221
- await this.page.act(n.ref, 'click');
608
+ const r = await this.peek('locator.waitFor', 'visible');
609
+ const visible = r.found && r.v === true;
610
+ ok = state === 'visible' ? visible : !visible;
611
+ }
612
+ if (ok)
613
+ return;
614
+ if (Date.now() >= deadline) {
615
+ throw new TimeoutError(`locator.waitFor: Timeout ${budget}ms exceeded.\nCall log:\n - waiting for ${this.toString()} to be ${state}`);
222
616
  }
223
- }, options?.timeout);
617
+ await sleep(BACKOFF[Math.min(i, BACKOFF.length - 1)]);
618
+ }
224
619
  }
225
- /** Replace the field's text via the engine's fill path. */
226
- async fill(value, options) {
227
- await this.withResolved('fill', (n) => this.page.act(n.ref, 'fill', value), options?.timeout);
620
+ // --- reading --------------------------------------------------------
621
+ async textContent(options = {}) {
622
+ return this.waitOne('locator.textContent', 'text', {}, options.timeout);
228
623
  }
229
- /**
230
- * Focus the element, then send real per-character key events
231
- * (isTrusted=true), for rich-text editors and inputs that ignore a
232
- * programmatic fill. Use fill() for plain inputs.
233
- */
234
- async type(text, options) {
235
- await this.withResolved('type', async (n) => {
236
- await this.page.act(n.ref, 'focus');
237
- await this.page.typeTrusted(text);
238
- }, options?.timeout);
624
+ async innerText(options = {}) {
625
+ return this.waitOne('locator.innerText', 'innerText', {}, options.timeout);
626
+ }
627
+ async innerHTML(options = {}) {
628
+ return this.waitOne('locator.innerHTML', 'innerHTML', {}, options.timeout);
239
629
  }
240
- /** Send a key chord to the element, e.g. `Enter` or `Ctrl+K`. */
241
- async press(key, options) {
242
- await this.withResolved('press', (n) => this.page.act(n.ref, 'key', key), options?.timeout);
630
+ /** An attribute's value, or null when absent. */
631
+ async getAttribute(name, options = {}) {
632
+ return this.waitOne('locator.getAttribute', 'attr', { name }, options.timeout);
243
633
  }
244
- async hover(options) {
245
- await this.withResolved('hover', (n) => this.page.act(n.ref, 'hover'), options?.timeout);
634
+ /** Current value of an input, textarea or select. */
635
+ async inputValue(options = {}) {
636
+ return this.waitOne('locator.inputValue', 'value', {}, options.timeout);
246
637
  }
247
- async focus(options) {
248
- await this.withResolved('focus', (n) => this.page.act(n.ref, 'focus'), options?.timeout);
638
+ async isChecked(options = {}) {
639
+ return this.waitOne('locator.isChecked', 'checked', {}, options.timeout);
249
640
  }
250
- /** Full text content of the element via vs_read. */
251
- async textContent(options) {
252
- return this.withResolved('textContent', (n) => this.page.readRef(n.ref), options?.timeout);
641
+ /** Disabled natively (`disabled`, a disabled fieldset) or with `aria-disabled="true"`. */
642
+ async isDisabled(options = {}) {
643
+ return this.waitOne('locator.isDisabled', 'disabled', {}, options.timeout);
253
644
  }
254
- /** Number of current matches (no waiting). */
255
- async count() {
256
- return (await this.resolveAll()).length;
645
+ async isEnabled(options = {}) {
646
+ return !(await this.isDisabled(options));
257
647
  }
258
- /** True if the locator has a visible match right now (no waiting). */
648
+ async isEditable(options = {}) {
649
+ return this.waitOne('locator.isEditable', 'editable', {}, options.timeout);
650
+ }
651
+ async isFocused(options = {}) {
652
+ return this.waitOne('locator.isFocused', 'focused', {}, options.timeout);
653
+ }
654
+ /** True if the locator's element is visible right now (no waiting). */
259
655
  async isVisible() {
260
- const visible = await this.resolveVisible();
261
- return this.index === null ? visible.length > 0 : visible[this.index] !== undefined;
656
+ const r = await this.peek('locator.isVisible', 'visible');
657
+ return r.found && r.v === true;
262
658
  }
263
- /** Checked state of a checkbox or radio, from the tree (vibesurfer 0.2.12+). */
264
- async isChecked(options) {
265
- return this.withResolved('isChecked', async (n) => n.attrs['checked'] === '1', options?.timeout);
659
+ async isHidden() {
660
+ return !(await this.isVisible());
266
661
  }
267
- /** Click a checkbox or radio unless it is already checked. */
268
- async check(options) {
269
- if (!(await this.isChecked(options)))
270
- await this.click(options);
662
+ /** Number of current matches (no waiting). A navigation mid-query counts as no matches. */
663
+ async count(options = {}) {
664
+ // The query belongs to the document it started in; if a navigation
665
+ // replaces that document before the result is read, nothing matched.
666
+ const hookFn = options.__testHookBeforeQuery;
667
+ const doc = hookFn ? await this.owner.engineCall('E.doc').catch(() => null) : null;
668
+ const hook = hookFn ? hookFn().catch(() => { }) : null;
669
+ try {
670
+ if (hook)
671
+ await hook;
672
+ const n = (await this.run('count', {}, { many: true })).n ?? 0;
673
+ if (!hookFn)
674
+ return n;
675
+ const after = await this.owner.engineCall('E.doc').catch(() => null);
676
+ return doc !== null && after !== doc ? 0 : n;
677
+ }
678
+ catch (e) {
679
+ if (e instanceof Error && /Execution context was destroyed/.test(e.message))
680
+ return 0;
681
+ throw e;
682
+ }
683
+ finally {
684
+ await hook;
685
+ }
271
686
  }
272
- /** Click a checkbox unless it is already unchecked. */
273
- async uncheck(options) {
274
- if (await this.isChecked(options))
275
- await this.click(options);
687
+ /** One locator per current match, in document order (no waiting). */
688
+ async all() {
689
+ const n = await this.count();
690
+ return Array.from({ length: n }, (_, i) => this.nth(i));
276
691
  }
277
- /**
278
- * Current value of a text field or select. The tree labels a field
279
- * with its value; a password field reads `***` once filled.
280
- */
281
- async inputValue(options) {
282
- return this.withResolved('inputValue', async (n) => n.label, options?.timeout);
692
+ async allTextContents() {
693
+ return this.many('texts');
694
+ }
695
+ async allInnerTexts() {
696
+ return this.many('innerTexts');
697
+ }
698
+ /** Rect in CSS px relative to the main frame's viewport, or null when not rendered. */
699
+ async boundingBox(options = {}) {
700
+ return this.waitOne('locator.boundingBox', 'box', {}, options.timeout);
701
+ }
702
+ /** Call `fn(element, arg)` in the page and return its result. */
703
+ async evaluate(fn, arg, options = {}) {
704
+ return this.waitOne('locator.evaluate', 'eval', { arg: serializeValue(arg) }, options.timeout, fn.toString());
705
+ }
706
+ /** Call `fn(elements, arg)` with every match and return its result. */
707
+ async evaluateAll(fn, arg) {
708
+ return this.many('evalAll', { arg: serializeValue(arg) }, fn.toString());
709
+ }
710
+ /** PNG of the element. Returns the bytes; with `path`, also writes the file. */
711
+ async screenshot(options = {}) {
712
+ await this.scrollIntoViewIfNeeded(options);
713
+ const box = await this.boundingBox(options);
714
+ if (!box)
715
+ throw new Error(`locator.screenshot: ${this.toString()} is not visible`);
716
+ return this.owner.screenshotClip(box, options.path);
717
+ }
718
+ /** The matched element's accessibility subtree as template text (see toMatchAriaSnapshot). */
719
+ async ariaSnapshot(options = {}) {
720
+ const { snap, refs } = await this.resolveScope(options.timeout);
721
+ return renderSnapshot(snap, refs);
722
+ }
723
+ /** Tree refs of the strict-mode match, for scoping a snapshot match. */
724
+ async resolveScope(timeout) {
725
+ const refs = await this.waitOne('locator.ariaSnapshot', 'refs', {}, timeout);
726
+ const snap = await this.owner.view();
727
+ return { snap, refs };
728
+ }
729
+ }
730
+ /** Locators inside an iframe (Playwright's FrameLocator). */
731
+ export class FrameLocator {
732
+ frame;
733
+ constructor(frame) {
734
+ this.frame = frame;
735
+ }
736
+ /** The iframe element itself. */
737
+ owner() {
738
+ return this.frame;
739
+ }
740
+ inside() {
741
+ return this.frame.extendWith([step({ kind: 'frame' })]);
742
+ }
743
+ first() {
744
+ return new FrameLocator(this.frame.first());
745
+ }
746
+ last() {
747
+ return new FrameLocator(this.frame.last());
748
+ }
749
+ nth(index) {
750
+ return new FrameLocator(this.frame.nth(index));
751
+ }
752
+ locator(selector, options) {
753
+ return this.inside().locator(selector, options);
754
+ }
755
+ frameLocator(selector) {
756
+ return new FrameLocator(this.inside().locator(selector));
757
+ }
758
+ getByRole(role, options = {}) {
759
+ return this.inside().getByRole(role, options);
283
760
  }
284
- /** Viewport rect in CSS px, or null when the element is not rendered. */
285
- async boundingBox(options) {
286
- return this.withResolved('boundingBox', async (n) => {
287
- const r = (await this.page.layout([n.ref])).get(n.ref);
288
- return r && r.w > 0 && r.h > 0 ? r : null;
289
- }, options?.timeout);
761
+ getByText(text, options = {}) {
762
+ return this.inside().getByText(text, options);
763
+ }
764
+ getByLabel(text, options = {}) {
765
+ return this.inside().getByLabel(text, options);
766
+ }
767
+ getByTestId(id) {
768
+ return this.inside().getByTestId(id);
769
+ }
770
+ getByPlaceholder(text, options = {}) {
771
+ return this.inside().getByPlaceholder(text, options);
772
+ }
773
+ getByAltText(text, options = {}) {
774
+ return this.inside().getByAltText(text, options);
775
+ }
776
+ getByTitle(text, options = {}) {
777
+ return this.inside().getByTitle(text, options);
778
+ }
779
+ }
780
+ /** A page value held by the test (Playwright's JSHandle). */
781
+ export class JSHandle {
782
+ handleId;
783
+ ownerPage;
784
+ constructor(page, id) {
785
+ this.ownerPage = page;
786
+ this.handleId = id;
787
+ }
788
+ /** Call `fn(value, arg)` in the page. */
789
+ async evaluate(fn, arg) {
790
+ return (await this.ownerPage.engineCall(`(${fn.toString()})(E.h(${this.handleId}),E.des(${JSON.stringify(serializeValue(arg))}))`));
791
+ }
792
+ async evaluateHandle(fn, arg) {
793
+ return this.ownerPage.adoptResult(`(${fn.toString()})(E.h(${this.handleId}),E.des(${JSON.stringify(serializeValue(arg))}))`);
794
+ }
795
+ /** The value, serialized back. */
796
+ async jsonValue() {
797
+ return (await this.ownerPage.engineCall(`E.h(${this.handleId})`));
798
+ }
799
+ async getProperty(name) {
800
+ return this.ownerPage.adoptResult(`(function(v){return v==null?undefined:v[${JSON.stringify(name)}];})(E.h(${this.handleId}))`);
801
+ }
802
+ async getProperties() {
803
+ const rows = (await this.ownerPage.engineCall(`E.props(${this.handleId})`));
804
+ return new Map(rows.map(([k, id, el]) => [k, el ? new ElementHandle(this.ownerPage, id) : new JSHandle(this.ownerPage, id)]));
805
+ }
806
+ asElement() {
807
+ return null;
808
+ }
809
+ async dispose() {
810
+ await this.ownerPage.engineCall(`E.drop(${this.handleId})`).catch(() => { });
811
+ }
812
+ /** @internal What the page showed for the value when it was adopted. */
813
+ previewText = '';
814
+ toString() {
815
+ return `JSHandle@${this.previewText}`;
816
+ }
817
+ }
818
+ /**
819
+ * An element held by the test (Playwright's ElementHandle). It is a
820
+ * locator pinned to that one element, so every locator method works on
821
+ * it; selectors on it search inside the element.
822
+ */
823
+ export class ElementHandle extends Locator {
824
+ handleId;
825
+ ownerPage;
826
+ constructor(page, id) {
827
+ super(page, { kind: 'handle', id });
828
+ this.handleId = id;
829
+ this.ownerPage = page;
830
+ }
831
+ asElement() {
832
+ return this;
290
833
  }
291
834
  /**
292
- * Drag this element onto `target` with a trusted press, move and
293
- * release from center to center. vibesurfer also fires the HTML5
294
- * drag events, so native draggable and react-dnd lists see the drop.
835
+ * The frame this <iframe> element hosts. Playwright gives handles an
836
+ * async contentFrame() returning a Frame, unlike Locator's, which
837
+ * returns a FrameLocator; the override is deliberately incompatible.
295
838
  */
296
- async dragTo(target, options) {
297
- const from = await this.boundingBox(options);
298
- if (!from)
299
- throw new TimeoutError(`dragTo: ${this.toString()} is not rendered`);
300
- const to = await target.boundingBox(options);
301
- if (!to)
302
- throw new TimeoutError(`dragTo: ${target.toString()} is not rendered`);
303
- await this.page.mouse.drag(from.x + from.w / 2, from.y + from.h / 2, to.x + to.w / 2, to.y + to.h / 2);
304
- }
305
- /** The matched element's subtree as template text (see toMatchAriaSnapshot). */
306
- async ariaSnapshot(options) {
307
- return this.withResolved('ariaSnapshot', async (n) => renderSnapshot(await this.page.actionSnapshot(), [n.ref]), options?.timeout);
308
- }
309
- /** Refs of the strict-mode match, for scoping a snapshot match. */
310
- async resolveScope() {
311
- const snap = await this.page.view();
312
- const node = this.pickOne(preferVisible(snap, findMatches(snap, this.query)));
313
- return { snap, refs: node ? [node.ref] : [] };
839
+ // @ts-expect-error see above
840
+ async contentFrame() {
841
+ const isFrame = await this.evaluate((e) => e.nodeName === 'IFRAME' || e.nodeName === 'FRAME');
842
+ if (!isFrame)
843
+ return null;
844
+ const { Frame } = await import("./frame.js");
845
+ return new Frame(this.page(), this, this.page().mainFrame());
846
+ }
847
+ /** The frame the element is in (the main frame for top-level elements). */
848
+ async ownerFrame() {
849
+ return this.page().mainFrame();
850
+ }
851
+ /** The first element matching `selector` inside this one, or null. */
852
+ async $(selector) {
853
+ return this.locator(selector).firstHandle();
854
+ }
855
+ async $$(selector) {
856
+ return this.locator(selector).elementHandles();
857
+ }
858
+ async $eval(selector, fn, arg) {
859
+ const r = await this.page().engineRun({ steps: this.locator(selector).wire(), op: 'eval', args: { arg: serializeValue(arg) }, first: true }, fn.toString());
860
+ if (r.none)
861
+ throw new Error(`elementHandle.$eval: Error: failed to find element matching selector "${selector}"`);
862
+ return r.v;
863
+ }
864
+ async $$eval(selector, fn, arg) {
865
+ return this.locator(selector).evaluateAll(fn, arg);
866
+ }
867
+ async evaluateHandle(fn, arg) {
868
+ return new JSHandle(this.page(), this.handleId).evaluateHandle(fn, arg);
869
+ }
870
+ async jsonValue() {
871
+ return {};
872
+ }
873
+ /** @internal Set when the handle came from evaluateHandle. */
874
+ previewText = '';
875
+ async getProperty(name) {
876
+ return new JSHandle(this.page(), this.handleId).getProperty(name);
877
+ }
878
+ async getProperties() {
879
+ return new JSHandle(this.page(), this.handleId).getProperties();
880
+ }
881
+ async dispose() {
882
+ await new JSHandle(this.page(), this.handleId).dispose();
883
+ }
884
+ /** The element matching `selector` inside this one, once it reaches `state` (visible by default). */
885
+ async waitForSelector(selector, options = {}) {
886
+ const l = this.locator(selector).first();
887
+ await l.waitFor(options);
888
+ return options.state === 'detached' || options.state === 'hidden' ? null : l.firstHandle();
889
+ }
890
+ /** Wait for the element to be visible, hidden, stable, enabled, disabled or editable. */
891
+ async waitForElementState(state, options = {}) {
892
+ const budget = options.timeout ?? this.page().timeouts.action;
893
+ const deadline = Date.now() + budget;
894
+ for (let i = 0;; i++) {
895
+ let ok = true;
896
+ if (state === 'visible')
897
+ ok = await this.isVisible();
898
+ else if (state === 'hidden')
899
+ ok = !(await this.isVisible());
900
+ else if (state === 'enabled')
901
+ ok = await this.isEnabled({ timeout: budget });
902
+ else if (state === 'disabled')
903
+ ok = await this.isDisabled({ timeout: budget });
904
+ else if (state === 'editable')
905
+ ok = await this.isEditable({ timeout: budget });
906
+ if (ok)
907
+ return;
908
+ if (Date.now() >= deadline)
909
+ throw new TimeoutError(`elementHandle.waitForElementState: Timeout ${budget}ms exceeded.`);
910
+ await sleep(BACKOFF[Math.min(i, BACKOFF.length - 1)]);
911
+ }
912
+ }
913
+ toString() {
914
+ return 'ElementHandle';
314
915
  }
315
916
  }
316
917
  //# sourceMappingURL=locator.js.map