@piwitests/reporter 0.68.0 → 0.70.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.
@@ -1,1820 +0,0 @@
1
- "use strict";
2
- var __create = Object.create;
3
- var __defProp = Object.defineProperty;
4
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
- var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __getProtoOf = Object.getPrototypeOf;
7
- var __hasOwnProp = Object.prototype.hasOwnProperty;
8
- var __export = (target, all) => {
9
- for (var name in all)
10
- __defProp(target, name, { get: all[name], enumerable: true });
11
- };
12
- var __copyProps = (to, from, except, desc) => {
13
- if (from && typeof from === "object" || typeof from === "function") {
14
- for (let key of __getOwnPropNames(from))
15
- if (!__hasOwnProp.call(to, key) && key !== except)
16
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
- }
18
- return to;
19
- };
20
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
- // If the importer is in node compatibility mode or this is not an ESM
22
- // file that has been converted to a CommonJS file using a Babel-
23
- // compatible transform (i.e. "__esModule" has not been set), then set
24
- // "default" to the CommonJS "module.exports" for node compatibility.
25
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
- mod
27
- ));
28
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
-
30
- // src/internal/capture/pick-on-failure.ts
31
- var pick_on_failure_exports = {};
32
- __export(pick_on_failure_exports, {
33
- applyPickToSnapshots: () => applyPickToSnapshots,
34
- deriveFailedLocator: () => deriveFailedLocator,
35
- generateAnchoredAlternatives: () => generateAnchoredAlternatives,
36
- installPickerOverlay: () => installPickerOverlay,
37
- mergeCandidates: () => mergeCandidates,
38
- parseLeafLocatorExpression: () => parseLeafLocatorExpression,
39
- pickLocator: () => pickLocator,
40
- runLocatorPicker: () => runLocatorPicker,
41
- showAnchorPicker: () => showAnchorPicker,
42
- showPickerChoices: () => showPickerChoices,
43
- unlessEnded: () => unlessEnded
44
- });
45
- module.exports = __toCommonJS(pick_on_failure_exports);
46
- var path2 = __toESM(require("path"));
47
-
48
- // ../core/src/locator-chain.ts
49
- var LOCATING_METHODS = /* @__PURE__ */ new Set([
50
- "getByRole",
51
- "getByTestId",
52
- "getByText",
53
- "getByLabel",
54
- "getByPlaceholder",
55
- "getByAltText",
56
- "getByTitle",
57
- "locator",
58
- "frameLocator"
59
- ]);
60
- var NARROWING_METHODS = /* @__PURE__ */ new Set([
61
- "filter",
62
- "first",
63
- "last",
64
- "nth",
65
- "and",
66
- "or",
67
- "visible",
68
- "contentFrame",
69
- "owner"
70
- ]);
71
- var LOCATOR_CHAIN_METHODS = /* @__PURE__ */ new Set([...LOCATING_METHODS, ...NARROWING_METHODS]);
72
- var LocatorParseError = class extends Error {
73
- constructor(message) {
74
- super(message);
75
- this.name = "LocatorParseError";
76
- }
77
- };
78
- var SIMPLE_ESCAPES = {
79
- n: "\n",
80
- t: " ",
81
- r: "\r",
82
- b: "\b",
83
- f: "\f",
84
- v: "\v",
85
- "0": "\0"
86
- };
87
- var Parser = class {
88
- constructor(src) {
89
- this.src = src;
90
- this.i = 0;
91
- }
92
- parseTopLevel() {
93
- const chain = this.parseChain();
94
- this.skipSpace();
95
- if (this.i < this.src.length) this.fail("unexpected text");
96
- return chain;
97
- }
98
- fail(message) {
99
- throw new LocatorParseError(`${message} at "${this.src.slice(this.i, this.i + 20)}"`);
100
- }
101
- skipSpace() {
102
- while (this.i < this.src.length && /\s/.test(this.src[this.i])) this.i++;
103
- }
104
- peek() {
105
- return this.src[this.i];
106
- }
107
- expect(ch) {
108
- this.skipSpace();
109
- if (this.src[this.i] !== ch) this.fail(`expected "${ch}"`);
110
- this.i++;
111
- }
112
- identifier() {
113
- const m = /^[A-Za-z_$][\w$]*/.exec(this.src.slice(this.i));
114
- if (!m) this.fail("expected a name");
115
- this.i += m[0].length;
116
- return m[0];
117
- }
118
- /**
119
- * A chain of calls joined by `.`. With `lenient`, parsing stops before the
120
- * first link that doesn't parse instead of failing, so a chain followed by
121
- * other text (an error message) is read up to where it ends. `spans` receives
122
- * where each top-level call starts and ends.
123
- */
124
- parseChain(opts = {}) {
125
- this.skipSpace();
126
- const calls = [];
127
- for (; ; ) {
128
- const before = this.i;
129
- if (calls.length > 0) this.i++;
130
- this.skipSpace();
131
- const start = this.i;
132
- try {
133
- calls.push(this.parseCall(calls.length === 0));
134
- } catch (error) {
135
- if (!opts.lenient || calls.length === 0) throw error;
136
- this.i = before;
137
- break;
138
- }
139
- opts.spans?.push({ start, end: this.i });
140
- const end = this.i;
141
- this.skipSpace();
142
- if (this.peek() !== ".") {
143
- this.i = end;
144
- break;
145
- }
146
- }
147
- return { calls };
148
- }
149
- /** Where the parser stopped. */
150
- get position() {
151
- return this.i;
152
- }
153
- parseCall(first) {
154
- this.skipSpace();
155
- const method = this.identifier();
156
- if (!LOCATOR_CHAIN_METHODS.has(method)) this.fail(`unsupported method ${method}()`);
157
- if (first && !LOCATING_METHODS.has(method)) this.fail(`${method}() needs a locator before it`);
158
- this.expect("(");
159
- const args = [];
160
- this.skipSpace();
161
- if (this.peek() === ")") {
162
- this.i++;
163
- return { method, args };
164
- }
165
- for (; ; ) {
166
- args.push(this.parseValue());
167
- this.skipSpace();
168
- if (this.peek() === ",") {
169
- this.i++;
170
- this.skipSpace();
171
- if (this.peek() === ")") {
172
- this.i++;
173
- break;
174
- }
175
- continue;
176
- }
177
- this.expect(")");
178
- break;
179
- }
180
- return { method, args };
181
- }
182
- parseValue() {
183
- this.skipSpace();
184
- const ch = this.peek();
185
- if (ch === "'" || ch === '"' || ch === "`") return { type: "string", value: this.parseString() };
186
- if (ch === "/") return this.parseRegex();
187
- if (ch === "{") return this.parseObject();
188
- if (ch !== void 0 && /[-\d]/.test(ch)) {
189
- const m = /^-?\d+(?:\.\d+)?/.exec(this.src.slice(this.i));
190
- if (!m) this.fail("expected a number");
191
- this.i += m[0].length;
192
- return { type: "number", value: Number(m[0]) };
193
- }
194
- const rest = this.src.slice(this.i);
195
- if (/^true\b/.test(rest)) {
196
- this.i += 4;
197
- return { type: "boolean", value: true };
198
- }
199
- if (/^false\b/.test(rest)) {
200
- this.i += 5;
201
- return { type: "boolean", value: false };
202
- }
203
- if (/^[A-Za-z_$]/.test(rest)) return { type: "chain", chain: this.parseChain() };
204
- return this.fail("expected a value");
205
- }
206
- /** A quoted string, decoding the escapes `JSON.stringify` and JavaScript produce. */
207
- parseString() {
208
- const quote = this.src[this.i];
209
- let out = "";
210
- this.i++;
211
- while (this.i < this.src.length) {
212
- const c = this.src[this.i];
213
- if (c === quote) {
214
- this.i++;
215
- return out;
216
- }
217
- if (c !== "\\") {
218
- out += c;
219
- this.i++;
220
- continue;
221
- }
222
- const next = this.src[this.i + 1];
223
- if (next === void 0) break;
224
- const simple = SIMPLE_ESCAPES[next];
225
- if (simple !== void 0) {
226
- out += simple;
227
- this.i += 2;
228
- continue;
229
- }
230
- const hex = next === "u" && this.src[this.i + 2] === "{" ? /^u\{([0-9a-fA-F]{1,6})\}/.exec(this.src.slice(this.i + 1)) : next === "u" ? /^u([0-9a-fA-F]{4})/.exec(this.src.slice(this.i + 1)) : next === "x" ? /^x([0-9a-fA-F]{2})/.exec(this.src.slice(this.i + 1)) : null;
231
- if (hex) {
232
- out += String.fromCodePoint(parseInt(hex[1], 16));
233
- this.i += 1 + hex[0].length;
234
- continue;
235
- }
236
- if (next === "u" || next === "x") this.fail("malformed escape");
237
- out += next;
238
- this.i += 2;
239
- }
240
- return this.fail("unterminated string");
241
- }
242
- parseRegex() {
243
- let j = this.i + 1;
244
- let inClass = false;
245
- while (j < this.src.length) {
246
- const c = this.src[j];
247
- if (c === "\\") {
248
- j += 2;
249
- continue;
250
- }
251
- if (c === "[") inClass = true;
252
- else if (c === "]") inClass = false;
253
- else if (c === "/" && !inClass) break;
254
- j++;
255
- }
256
- if (j >= this.src.length) this.fail("unterminated regex");
257
- const source = this.src.slice(this.i + 1, j);
258
- const flags = /^[a-z]*/.exec(this.src.slice(j + 1))[0];
259
- this.i = j + 1 + flags.length;
260
- return { type: "regex", source, flags };
261
- }
262
- parseObject() {
263
- this.expect("{");
264
- const entries = [];
265
- for (; ; ) {
266
- this.skipSpace();
267
- if (this.peek() === "}") {
268
- this.i++;
269
- break;
270
- }
271
- const ch = this.peek();
272
- const key = ch === "'" || ch === '"' ? this.parseString() : this.identifier();
273
- this.expect(":");
274
- entries.push([key, this.parseValue()]);
275
- this.skipSpace();
276
- if (this.peek() === ",") {
277
- this.i++;
278
- continue;
279
- }
280
- this.expect("}");
281
- break;
282
- }
283
- return { type: "object", entries };
284
- }
285
- };
286
- function parseLocatorChain(expr) {
287
- const trimmed = expr.trim().replace(/^(?:await\s+)?(?:this\.)?page\./, "");
288
- if (!trimmed) throw new LocatorParseError("empty expression");
289
- return new Parser(trimmed).parseTopLevel();
290
- }
291
- function tryParseLocatorChain(expr) {
292
- try {
293
- return parseLocatorChain(expr);
294
- } catch {
295
- return null;
296
- }
297
- }
298
- function quoteJsString(value) {
299
- const json = JSON.stringify(value).slice(1, -1);
300
- return `'${json.replace(/\\"/g, '"').replace(/'/g, "\\'").replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029")}'`;
301
- }
302
- function parseLeafLocatorCall(expr) {
303
- const chain = tryParseLocatorChain(expr);
304
- if (!chain) return null;
305
- for (let i = chain.calls.length - 1; i >= 0; i--) {
306
- if (LOCATING_METHODS.has(chain.calls[i].method)) return chain.calls[i];
307
- }
308
- return null;
309
- }
310
- function locatorCallValues(call, opts = {}) {
311
- const value = (arg) => {
312
- switch (arg.type) {
313
- case "string":
314
- case "number":
315
- case "boolean":
316
- return arg.value;
317
- case "regex":
318
- return opts.regexAsText ? `/${arg.source}/${arg.flags}` : void 0;
319
- case "object": {
320
- const out = {};
321
- for (const [key, v] of arg.entries) {
322
- const plain = value(v);
323
- if (plain !== void 0) out[key] = plain;
324
- }
325
- return out;
326
- }
327
- case "chain":
328
- return void 0;
329
- }
330
- };
331
- return call.args.map(value).filter((v) => v !== void 0);
332
- }
333
-
334
- // ../core/src/locator-methods.ts
335
- var LOCATOR_BUILDER_METHODS = [
336
- "getByRole",
337
- "getByTestId",
338
- "getByText",
339
- "getByLabel",
340
- "getByPlaceholder",
341
- "getByAltText",
342
- "getByTitle",
343
- "locator"
344
- ];
345
-
346
- // ../core/src/error-parse.ts
347
- var ANSI_RE = new RegExp("\\u001B\\[[0-9;]*m", "g");
348
- function stripAnsi(text) {
349
- return text.replace(ANSI_RE, "");
350
- }
351
- var CHAIN_LINK_METHODS = /* @__PURE__ */ new Set([
352
- ...LOCATOR_BUILDER_METHODS,
353
- "frameLocator",
354
- "contentFrame",
355
- "filter",
356
- "first",
357
- "last",
358
- "nth",
359
- "and",
360
- "or",
361
- "describe"
362
- ]);
363
- var LEAF_METHODS = new Set(LOCATOR_BUILDER_METHODS);
364
- var SUBJECTS = "locator|page|frame|frameLocator|elementHandle|mouse|keyboard|touchscreen|browserContext|browser|apiRequestContext|request|response|route|download|dialog|fileChooser|expect|worker|jsHandle|clock|tracing|video";
365
- var CALL_RE = new RegExp(`\\b(${SUBJECTS})\\.(\\w+): `);
366
- function readLocatorHeader(text) {
367
- const header = /^[ \t]*Locator:[ \t]*(.+)$/m.exec(text);
368
- return header ? header[1].trim() : null;
369
- }
370
- var MAX_PARSED_ERROR_CHARS = 64 * 1024;
371
-
372
- // ../picker-dom/src/overlay-element.ts
373
- function installPickerOverlay(arg) {
374
- const g = globalThis;
375
- const doc = g.document;
376
- if (!doc || !doc.body) {
377
- if (arg.transport === "postMessage") g.parent.postMessage({ type: "pickerClosed" }, "*");
378
- else g.__piwiPickState = "skipped";
379
- return;
380
- }
381
- const Z = 2147483600;
382
- const testIdAttr = arg.testIdAttribute || "data-testid";
383
- const enterReaches = arg.transport === "global";
384
- const words = {
385
- banner: "Piwi inspector \u2014 click any element to generate locators for it",
386
- keys: enterReaches ? "Enter picks the focused element \xB7 \u2191 parent \xB7 \u2193 child \xB7 Esc skip" : "\u2191 parent \xB7 \u2193 child \xB7 Esc skip",
387
- keysHovering: enterReaches ? "click or Enter to pick \xB7 \u2191 parent \xB7 \u2193 child \xB7 Esc skip" : "click to pick \xB7 \u2191 parent \xB7 \u2193 child \xB7 Esc skip",
388
- analyzing: "Analyzing element\u2026"
389
- };
390
- for (const key of Object.keys(words)) {
391
- const given = arg.strings?.[key];
392
- if (typeof given === "string" && given) words[key] = given;
393
- }
394
- const highlight = doc.createElement("div");
395
- highlight.id = "__piwi_picker_highlight";
396
- highlight.style.cssText = `position:fixed;pointer-events:none;z-index:${Z};display:none;box-sizing:border-box;border:2px solid #a855f7;background:rgba(168,85,247,.14);border-radius:4px;box-shadow:0 0 0 1px rgba(255,255,255,.9),0 0 0 3px rgba(59,7,100,.55),inset 0 0 0 1px rgba(255,255,255,.5);`;
397
- const banner = doc.createElement("div");
398
- banner.id = "__piwi_picker_banner";
399
- banner.style.cssText = `position:fixed;top:12px;left:50%;transform:translateX(-50%);z-index:${Z + 2};background:#111827;color:#f9fafb;font:13px/1.5 system-ui,sans-serif;border:1px solid #312e81;padding:10px 16px;border-radius:10px;box-shadow:0 4px 24px rgba(0,0,0,.5);max-width:min(680px,86vw);`;
400
- const hlTokens = (expr) => {
401
- const escHtml = (s) => s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
402
- const re = /('(?:\\.|[^'\\])*'|"(?:\\.|[^"\\])*")|([A-Za-z_$][\w$]*)(?=\s*\()|([A-Za-z_$][\w$]*)(?=\s*:)|(true|false|null|\d+)|([{}(),.])/g;
403
- let html = "";
404
- let last = 0;
405
- let m;
406
- while ((m = re.exec(expr)) !== null) {
407
- if (m.index > last) html += escHtml(expr.slice(last, m.index));
408
- const color = m[1] ? "#86efac" : m[2] ? "#d8b4fe" : m[3] ? "#93c5fd" : m[4] ? "#fcd34d" : "#9ca3af";
409
- html += `<span style="color:${color}">${escHtml(m[0])}</span>`;
410
- last = re.lastIndex;
411
- }
412
- if (last < expr.length) html += escHtml(expr.slice(last));
413
- return html;
414
- };
415
- const MONO = "ui-monospace,SFMono-Regular,Menlo,Consolas,monospace";
416
- const hlLocator = (expr) => `<code style="font-family:${MONO}">${hlTokens(expr)}</code>`;
417
- const head = doc.createElement("div");
418
- if (arg.transport === "postMessage") head.textContent = "Click an element to generate locators";
419
- else if (arg.failing)
420
- head.innerHTML = `Piwi locator picker \u2014 click the element that should replace ${hlLocator(arg.failing)}`;
421
- else head.textContent = words.banner;
422
- const locatorLine = doc.createElement("div");
423
- locatorLine.id = "__piwi_picker_locator";
424
- locatorLine.style.cssText = `display:none;margin-top:7px;padding:5px 9px;border-radius:7px;background:#0b1120;border:1px solid #4c1d95;font:13.5px/1.55 ${MONO};word-break:break-word;overflow-wrap:anywhere;`;
425
- const foot = doc.createElement("div");
426
- foot.id = "__piwi_picker_foot";
427
- foot.style.cssText = "color:#9ca3af;margin-top:6px;font-size:12px;";
428
- foot.textContent = words.keys;
429
- banner.appendChild(head);
430
- banner.appendChild(locatorLine);
431
- banner.appendChild(foot);
432
- const label = doc.createElement("div");
433
- label.id = "__piwi_picker_label";
434
- label.style.cssText = `position:fixed;pointer-events:none;z-index:${Z + 1};display:none;box-sizing:border-box;max-width:min(620px,92vw);background:#0b1120;color:#f9fafb;border:1px solid #7c3aed;border-radius:7px;padding:4px 8px;font:12.5px/1.45 ${MONO};white-space:nowrap;overflow:hidden;text-overflow:ellipsis;box-shadow:0 4px 18px rgba(0,0,0,.5);`;
435
- const mountParent = () => {
436
- let modal = null;
437
- try {
438
- modal = doc.querySelector("dialog:modal");
439
- } catch {
440
- modal = null;
441
- }
442
- if (!modal) return doc.body;
443
- const s = g.getComputedStyle(modal);
444
- const holdsFixed = s.transform !== "none" || s.perspective !== "none" || s.filter !== "none" || /\b(paint|layout|strict|content)\b/.test(s.contain) || /\b(transform|perspective|filter)\b/.test(s.willChange);
445
- return holdsFixed ? doc.body : modal;
446
- };
447
- const mount = (...nodes) => {
448
- const parent = mountParent();
449
- for (const node of nodes) parent.appendChild(node);
450
- if (parent !== doc.body) {
451
- parent.addEventListener(
452
- "close",
453
- () => {
454
- for (const node of nodes) if (node.parentNode === parent) doc.body.appendChild(node);
455
- },
456
- { once: true }
457
- );
458
- }
459
- };
460
- mount(highlight, label, banner);
461
- const quoteJs = (s) => `'${JSON.stringify(s).slice(1, -1).replace(/\\"/g, '"').replace(/'/g, "\\'").replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029")}'`;
462
- const describe = (el) => {
463
- const tag = (el.tagName || "?").toLowerCase();
464
- const testId = el.getAttribute && el.getAttribute(testIdAttr);
465
- if (testId) return `getByTestId(${quoteJs(testId)})`;
466
- if (el.labels && el.labels.length > 0) {
467
- const labelText = (el.labels[0].textContent || "").replace(/\s+/g, " ").trim().slice(0, 80);
468
- if (labelText) return `getByLabel(${quoteJs(labelText)})`;
469
- }
470
- const ariaLabel = el.getAttribute && el.getAttribute("aria-label");
471
- if (ariaLabel) return `getByLabel(${quoteJs(ariaLabel)})`;
472
- const placeholder = el.getAttribute && el.getAttribute("placeholder");
473
- if (placeholder) return `getByPlaceholder(${quoteJs(placeholder)})`;
474
- const alt = el.getAttribute && el.getAttribute("alt");
475
- if (alt) return `getByAltText(${quoteJs(alt)})`;
476
- const titleAttr = el.getAttribute && el.getAttribute("title");
477
- if (titleAttr) return `getByTitle(${quoteJs(titleAttr)})`;
478
- if (el.id) return `locator(${quoteJs(`#${el.id}`)})`;
479
- const cls = (el.getAttribute && el.getAttribute("class") || "").split(/\s+/).find((c) => c.length > 1);
480
- return cls ? `locator(${quoteJs(`.${cls}`)})` : tag;
481
- };
482
- const parentOf = (node) => {
483
- if (node.parentElement) return node.parentElement;
484
- const root = node.getRootNode ? node.getRootNode() : null;
485
- return root && root !== doc && root.host ? root.host : null;
486
- };
487
- const targetOf = (e) => {
488
- const path3 = typeof e.composedPath === "function" ? e.composedPath() : null;
489
- const first = path3 && path3.length ? path3[0] : null;
490
- return first && first.nodeType === 1 ? first : e.target;
491
- };
492
- const buildChain = (raw) => {
493
- const chain2 = [];
494
- let node = raw;
495
- while (node && chain2.length < 15) {
496
- const tag = (node.tagName || "").toLowerCase();
497
- if (tag === "body" || tag === "html") break;
498
- chain2.push(node);
499
- node = parentOf(node);
500
- }
501
- return chain2.length ? chain2 : [raw];
502
- };
503
- const ACTIONABLE_TAGS = ["button", "a", "input", "select", "textarea", "summary", "option"];
504
- const snapIndex = (chain2) => {
505
- for (let i = 0; i < Math.min(chain2.length, 4); i++) {
506
- const el = chain2[i];
507
- const tag = (el.tagName || "").toLowerCase();
508
- if (ACTIONABLE_TAGS.includes(tag)) return i;
509
- if (el.getAttribute && (el.getAttribute("role") || el.getAttribute(testIdAttr))) return i;
510
- }
511
- return 0;
512
- };
513
- const locatorOf = (el) => {
514
- const hook = g.__piwiDescribeElement;
515
- if (typeof hook === "function") {
516
- try {
517
- const derived = hook(el);
518
- if (typeof derived === "string" && derived) return derived;
519
- } catch {
520
- }
521
- }
522
- return describe(el);
523
- };
524
- let chain = [];
525
- let idx = 0;
526
- let lastRaw = null;
527
- let labeled = null;
528
- const placeLabel = (r) => {
529
- label.style.display = "block";
530
- const lr = label.getBoundingClientRect();
531
- const vw = g.innerWidth || doc.documentElement.clientWidth || 0;
532
- const vh = g.innerHeight || doc.documentElement.clientHeight || 0;
533
- let top = r.top - lr.height - 6;
534
- if (top < 4) top = r.bottom + 6;
535
- if (top + lr.height > vh - 4) top = Math.max(4, vh - lr.height - 4);
536
- let left = r.left;
537
- if (left + lr.width > vw - 6) left = vw - lr.width - 6;
538
- if (left < 6) left = 6;
539
- label.style.left = left + "px";
540
- label.style.top = top + "px";
541
- };
542
- const current = () => chain[idx] ?? null;
543
- const refresh = () => {
544
- const el = current();
545
- if (!el) {
546
- highlight.style.display = "none";
547
- label.style.display = "none";
548
- return;
549
- }
550
- const r = el.getBoundingClientRect();
551
- highlight.style.display = "block";
552
- highlight.style.left = r.left + "px";
553
- highlight.style.top = r.top + "px";
554
- highlight.style.width = r.width + "px";
555
- highlight.style.height = r.height + "px";
556
- if (el !== labeled) {
557
- labeled = el;
558
- const tag = (el.tagName || "?").toLowerCase();
559
- const locatorHtml = hlTokens(locatorOf(el));
560
- label.innerHTML = `<span style="color:#c4b5fd">&lt;${tag}&gt;</span> ${locatorHtml}`;
561
- locatorLine.innerHTML = locatorHtml;
562
- locatorLine.style.display = "block";
563
- }
564
- placeLabel(r);
565
- foot.textContent = words.keysHovering;
566
- };
567
- const redescribe = () => {
568
- labeled = null;
569
- if (current()) refresh();
570
- };
571
- g.__piwiRedescribe = redescribe;
572
- const stop = (e) => {
573
- e.preventDefault();
574
- e.stopImmediatePropagation();
575
- };
576
- const isOwn = (el) => el === banner || el === highlight || el === label || banner.contains && banner.contains(el) || !!(el && el.__piwiHint);
577
- let bannerDocked = "top";
578
- const dockBanner = (side) => {
579
- if (bannerDocked === side) return;
580
- bannerDocked = side;
581
- if (side === "bottom") {
582
- banner.style.top = "auto";
583
- banner.style.bottom = "12px";
584
- } else {
585
- banner.style.top = "12px";
586
- banner.style.bottom = "auto";
587
- }
588
- };
589
- const onMove = (e) => {
590
- const raw = targetOf(e);
591
- if (!raw || isOwn(raw)) {
592
- chain = [];
593
- idx = 0;
594
- lastRaw = null;
595
- highlight.style.display = "none";
596
- label.style.display = "none";
597
- foot.textContent = words.keys;
598
- return;
599
- }
600
- if (raw !== lastRaw) {
601
- lastRaw = raw;
602
- chain = buildChain(raw);
603
- idx = snapIndex(chain);
604
- }
605
- refresh();
606
- const el = current();
607
- if (el) {
608
- const r = el.getBoundingClientRect();
609
- const br = banner.getBoundingClientRect();
610
- const margin = 8;
611
- if (r.left < br.right + margin && r.right > br.left - margin && r.top < br.bottom + margin && r.bottom > br.top - margin) {
612
- dockBanner(bannerDocked === "top" ? "bottom" : "top");
613
- }
614
- }
615
- };
616
- const suppressed = ["mousedown", "mouseup", "pointerdown", "pointerup", "auxclick", "dblclick"];
617
- const removePickingListeners = () => {
618
- doc.removeEventListener("mousemove", onMove, true);
619
- doc.removeEventListener("click", onClick, true);
620
- doc.removeEventListener("keydown", onKey, true);
621
- if (arg.transport === "postMessage") g.removeEventListener("message", onParentMsg, false);
622
- };
623
- const removeSuppressed = () => {
624
- for (const t of suppressed) doc.removeEventListener(t, stop, true);
625
- };
626
- const cleanup = () => {
627
- highlight.remove();
628
- label.remove();
629
- banner.remove();
630
- if (g.__piwiRedescribe === redescribe) delete g.__piwiRedescribe;
631
- };
632
- const teardown = () => {
633
- removePickingListeners();
634
- removeSuppressed();
635
- doc.removeEventListener("click", stop, true);
636
- doc.removeEventListener("keydown", stop, true);
637
- cleanup();
638
- };
639
- const reportPicked = (el) => {
640
- removePickingListeners();
641
- highlight.style.display = "none";
642
- label.style.display = "none";
643
- if (arg.transport === "postMessage") {
644
- const probeFn = g.__piwiProbe;
645
- const attrs = typeof probeFn === "function" ? probeFn(el, arg.probeArg) : null;
646
- g.__piwiSnapshotExtras?.onPick?.();
647
- doc.addEventListener("click", stop, true);
648
- doc.addEventListener("keydown", stop, true);
649
- foot.textContent = words.analyzing;
650
- g.parent.postMessage({ type: "elementPicked", attrs }, "*");
651
- } else {
652
- removeSuppressed();
653
- g.__piwiPickedElement = el;
654
- g.__piwiPickState = "picked";
655
- foot.textContent = words.analyzing;
656
- }
657
- };
658
- const reportSkipped = () => {
659
- removePickingListeners();
660
- if (arg.transport === "postMessage") {
661
- doc.removeEventListener("click", stop, true);
662
- doc.removeEventListener("keydown", stop, true);
663
- removeSuppressed();
664
- g.__piwiSnapshotExtras?.onClose?.();
665
- cleanup();
666
- g.parent.postMessage({ type: "pickerClosed" }, "*");
667
- } else {
668
- removeSuppressed();
669
- g.__piwiPickState = "skipped";
670
- cleanup();
671
- }
672
- };
673
- const onClick = (e) => {
674
- stop(e);
675
- const el = current();
676
- if (!el || isOwn(targetOf(e))) return;
677
- reportPicked(el);
678
- };
679
- const focused = () => {
680
- let el = doc.activeElement;
681
- while (el && el.shadowRoot && el.shadowRoot.activeElement) el = el.shadowRoot.activeElement;
682
- const tag = (el && el.tagName || "").toLowerCase();
683
- return !el || tag === "body" || tag === "html" || isOwn(el) ? null : el;
684
- };
685
- const onKey = (e) => {
686
- if (e.key === "Escape") {
687
- stop(e);
688
- reportSkipped();
689
- return;
690
- }
691
- if (e.key === "Enter" && !e.isComposing) {
692
- stop(e);
693
- const el = current() || focused();
694
- if (el) reportPicked(el);
695
- return;
696
- }
697
- if (e.key === "ArrowUp" || e.key === "ArrowDown") {
698
- stop(e);
699
- if (!chain.length) return;
700
- if (e.key === "ArrowUp") idx = Math.min(idx + 1, chain.length - 1);
701
- else idx = Math.max(idx - 1, 0);
702
- refresh();
703
- }
704
- };
705
- const onParentMsg = (e) => {
706
- const d = e.data;
707
- if (!d || typeof d.type !== "string" || d.type !== "piwiPickerKey" || typeof d.key !== "string") return;
708
- onKey({
709
- key: d.key,
710
- preventDefault() {
711
- },
712
- stopImmediatePropagation() {
713
- }
714
- });
715
- };
716
- g.__piwiPickCleanup = teardown;
717
- doc.addEventListener("mousemove", onMove, true);
718
- doc.addEventListener("click", onClick, true);
719
- doc.addEventListener("keydown", onKey, true);
720
- for (const t of suppressed) doc.addEventListener(t, stop, true);
721
- if (arg.transport === "postMessage") {
722
- g.addEventListener("message", onParentMsg, false);
723
- g.parent.postMessage({ type: "pickerReady" }, "*");
724
- }
725
- }
726
-
727
- // ../picker-dom/src/overlay-anchors.ts
728
- function showAnchorPicker(arg) {
729
- const g = globalThis;
730
- const doc = g.document;
731
- const el = g.__piwiPickedElement;
732
- if (!doc || !doc.body || !el) {
733
- g.__piwiAnchorState = "skipped";
734
- return;
735
- }
736
- const Z = 2147483600;
737
- const { tagRoles, inputRoles, roleSources, leafRole, leafLevel, leafTestId } = arg;
738
- const testIdAttr = arg.testIdAttribute || "data-testid";
739
- const words = {
740
- title: "Scope to stable parents (optional)",
741
- hint: "Pick one or more parents to anchor the locator to. Hover a row to see the parent.",
742
- noneSelected: "No parents selected \u2014 standard alternatives only.",
743
- matchesOne: "\u2713 Selection matches exactly 1 element",
744
- matchesMany: "\u2717 Selection matches {count} elements",
745
- countUnavailable: "Match count unavailable",
746
- containsOne: "contains exactly 1 matching element",
747
- containsMany: "contains {count} matching elements",
748
- needsTestId: `add a ${testIdAttr} to make this usable`,
749
- noHook: "no stable hook",
750
- use: "Use selected parents",
751
- skip: "Skip (Esc)"
752
- };
753
- for (const key of Object.keys(words)) {
754
- const given = arg.strings?.[key];
755
- if (typeof given === "string" && given) words[key] = given;
756
- }
757
- const counted = (template, n) => template.replace("{count}", String(n));
758
- const roleOf = (n) => {
759
- const explicit = n.getAttribute && n.getAttribute("role");
760
- if (explicit) return explicit;
761
- const tag = (n.tagName || "").toLowerCase();
762
- if (tag === "input") return inputRoles[(n.getAttribute("type") || "text").toLowerCase()] ?? "textbox";
763
- if (tag === "select") return n.getAttribute("multiple") != null ? "listbox" : "combobox";
764
- if (tag === "a") return n.getAttribute("href") != null ? "link" : null;
765
- return tagRoles[tag] ?? null;
766
- };
767
- const levelOf = (n) => {
768
- const m = /^h([1-6])$/.exec((n.tagName || "").toLowerCase());
769
- if (m) return Number(m[1]);
770
- const al = n.getAttribute && n.getAttribute("aria-level");
771
- return al && /^\d+$/.test(al) ? Number(al) : null;
772
- };
773
- const parentOf = (n) => {
774
- if (n.parentElement) return n.parentElement;
775
- const root = n.getRootNode ? n.getRootNode() : null;
776
- return root && root !== doc && root.host ? root.host : null;
777
- };
778
- const shadowRoots = [];
779
- const collectRoots = (root) => {
780
- const all = root.querySelectorAll("*");
781
- for (let i = 0; i < all.length; i++) {
782
- const sr = all[i].shadowRoot;
783
- if (sr) {
784
- shadowRoots.push(sr);
785
- collectRoots(sr);
786
- }
787
- }
788
- };
789
- try {
790
- collectRoots(doc);
791
- } catch {
792
- shadowRoots.length = 0;
793
- }
794
- const within = (node2, scope) => {
795
- if (scope === doc) return true;
796
- for (let n = node2; n; n = parentOf(n)) if (n === scope) return true;
797
- return false;
798
- };
799
- const queryAll = (scope, sel) => {
800
- const found = Array.from(scope.querySelectorAll(sel));
801
- for (const sr of shadowRoots) if (within(sr.host, scope)) found.push(...Array.from(sr.querySelectorAll(sel)));
802
- return found;
803
- };
804
- const leafCountable = !!leafTestId || roleOf(el) === leafRole;
805
- const leafMatches = (scope) => {
806
- try {
807
- if (leafTestId) return queryAll(scope, `[${testIdAttr}=${JSON.stringify(leafTestId)}]`).length;
808
- if (!leafCountable) return -1;
809
- const nodes = queryAll(scope, roleSources);
810
- if (nodes.length > 2e3) return -1;
811
- let matched = 0;
812
- for (let i = 0; i < nodes.length; i++) {
813
- const n = nodes[i];
814
- if (roleOf(n) !== leafRole) continue;
815
- if (leafLevel != null && levelOf(n) !== leafLevel) continue;
816
- matched++;
817
- }
818
- return matched;
819
- } catch {
820
- return -1;
821
- }
822
- };
823
- let roleNodes = [];
824
- try {
825
- const all = queryAll(doc, roleSources);
826
- if (all.length <= 4e3) roleNodes = all;
827
- } catch {
828
- roleNodes = [];
829
- }
830
- const count = (sel) => {
831
- try {
832
- return queryAll(doc, sel).length;
833
- } catch {
834
- return void 0;
835
- }
836
- };
837
- const rows = [];
838
- let node = parentOf(el);
839
- let depth = 0;
840
- while (node && depth < 12) {
841
- depth++;
842
- const tag = (node.tagName || "").toLowerCase();
843
- if (tag === "body" || tag === "html") break;
844
- const testId = node.getAttribute(testIdAttr);
845
- const id = node.getAttribute("id");
846
- const ariaLabel = node.getAttribute("aria-label");
847
- const role = roleOf(node);
848
- const info = { tag, depth, testId: testId || null, id: id || null, ariaLabel: ariaLabel || null, role };
849
- if (testId) info.testIdCount = count(`[${testIdAttr}=${JSON.stringify(testId)}]`);
850
- if (id) {
851
- try {
852
- info.idCount = count(`#${doc.defaultView.CSS.escape(id)}`);
853
- } catch {
854
- }
855
- }
856
- if (role) {
857
- let roleCount = 0;
858
- let labeledCount = 0;
859
- for (const n of roleNodes) {
860
- if (roleOf(n) !== role) continue;
861
- roleCount++;
862
- if (ariaLabel && n.getAttribute && n.getAttribute("aria-label") === ariaLabel) labeledCount++;
863
- }
864
- info.roleCount = roleCount;
865
- if (ariaLabel) info.labeledRoleCount = labeledCount;
866
- }
867
- info.scopedLeafCount = leafMatches(node);
868
- const hookLabel = testId ? `${testIdAttr}="${testId}"` : id ? `#${id}` : ariaLabel && role ? `${role} "${ariaLabel}"` : role ? `role ${role}` : words.noHook;
869
- rows.push({
870
- node,
871
- info,
872
- hookLabel,
873
- selectable: !!(testId || id || role && (ariaLabel || info.roleCount === 1))
874
- });
875
- node = parentOf(node);
876
- }
877
- if (rows.length === 0) {
878
- g.__piwiAnchorState = "skipped";
879
- return;
880
- }
881
- const MONO = "ui-monospace,SFMono-Regular,Menlo,Consolas,monospace";
882
- const outline = doc.createElement("div");
883
- outline.id = "__piwi_anchor_outline";
884
- outline.style.cssText = `position:fixed;pointer-events:none;z-index:${Z};box-sizing:border-box;border:2px solid #22c55e;background:rgba(34,197,94,.10);border-radius:4px;display:none;box-shadow:0 0 0 1px rgba(255,255,255,.9),0 0 0 3px rgba(5,46,22,.5);`;
885
- const outlineLabel = doc.createElement("div");
886
- outlineLabel.id = "__piwi_anchor_label";
887
- outlineLabel.style.cssText = `position:fixed;pointer-events:none;z-index:${Z + 1};display:none;box-sizing:border-box;max-width:min(420px,90vw);background:#0b1120;color:#f9fafb;border:1px solid #22c55e;border-radius:6px;padding:3px 7px;font:12px/1.45 ${MONO};white-space:nowrap;overflow:hidden;text-overflow:ellipsis;box-shadow:0 4px 18px rgba(0,0,0,.5);`;
888
- const pickedOutline = doc.createElement("div");
889
- pickedOutline.id = "__piwi_anchor_picked";
890
- const pr = el.getBoundingClientRect();
891
- pickedOutline.style.cssText = `position:fixed;pointer-events:none;z-index:${Z};box-sizing:border-box;border:2px solid #a855f7;background:rgba(168,85,247,.14);border-radius:4px;box-shadow:0 0 0 1px rgba(255,255,255,.9),0 0 0 3px rgba(59,7,100,.55);left:${pr.left}px;top:${pr.top}px;width:${pr.width}px;height:${pr.height}px;`;
892
- const panel = doc.createElement("div");
893
- panel.id = "__piwi_anchor_panel";
894
- panel.style.cssText = `position:fixed;top:12px;right:12px;z-index:${Z + 3};width:min(340px,calc(100vw - 56px));max-height:82vh;overflow:auto;background:#111827;color:#f9fafb;border-radius:10px;padding:16px;font:12px/1.5 system-ui,sans-serif;box-shadow:0 8px 40px rgba(0,0,0,.5);`;
895
- const title = doc.createElement("div");
896
- title.style.cssText = "font-weight:600;font-size:13px;margin-bottom:2px;";
897
- title.textContent = words.title;
898
- const sub = doc.createElement("div");
899
- sub.style.cssText = "color:#9ca3af;margin-bottom:10px;";
900
- sub.textContent = words.hint;
901
- panel.appendChild(title);
902
- panel.appendChild(sub);
903
- const selected = /* @__PURE__ */ new Set();
904
- const footer = doc.createElement("div");
905
- footer.style.cssText = "margin:10px 0;font-weight:600;";
906
- const segMatches = (scope, info) => {
907
- try {
908
- if (info.testId) return queryAll(scope, `[${testIdAttr}=${JSON.stringify(info.testId)}]`);
909
- if (info.id) return queryAll(scope, `#${doc.defaultView.CSS.escape(info.id)}`);
910
- const nodes = queryAll(scope, roleSources);
911
- if (nodes.length > 2e3) return [];
912
- return nodes.filter(
913
- (n) => roleOf(n) === info.role && (!info.ariaLabel || n.getAttribute && n.getAttribute("aria-label") === info.ariaLabel)
914
- );
915
- } catch {
916
- return [];
917
- }
918
- };
919
- const chainCount = () => {
920
- const chosen = rows.filter((_, i) => selected.has(i)).sort((a, b) => b.info.depth - a.info.depth);
921
- if (chosen.length === 0) return -1;
922
- let scopes = [doc];
923
- for (const row of chosen) {
924
- const next = [];
925
- for (const s of scopes) next.push(...segMatches(s, row.info));
926
- scopes = next.slice(0, 200);
927
- if (scopes.length === 0) return 0;
928
- }
929
- let total = 0;
930
- for (const s of scopes) {
931
- const c = leafMatches(s);
932
- if (c < 0) return -1;
933
- total += c;
934
- if (total > 50) return total;
935
- }
936
- return total;
937
- };
938
- const refreshFooter = () => {
939
- if (selected.size === 0) {
940
- footer.textContent = words.noneSelected;
941
- footer.style.color = "#9ca3af";
942
- g.__piwiPickChainCount = void 0;
943
- return;
944
- }
945
- const c = chainCount();
946
- g.__piwiPickChainCount = c;
947
- if (c === 1) {
948
- footer.textContent = words.matchesOne;
949
- footer.style.color = "#4ade80";
950
- } else {
951
- footer.textContent = c < 0 ? words.countUnavailable : counted(words.matchesMany, c);
952
- footer.style.color = "#fbbf24";
953
- }
954
- };
955
- rows.forEach((row, i) => {
956
- const line = doc.createElement("label");
957
- line.style.cssText = `display:flex;align-items:center;gap:8px;padding:6px 8px;border:1px solid #374151;border-radius:6px;margin-bottom:6px;cursor:${row.selectable ? "pointer" : "default"};opacity:${row.selectable ? "1" : ".45"};`;
958
- const box = doc.createElement("input");
959
- box.type = "checkbox";
960
- box.disabled = !row.selectable;
961
- const text = doc.createElement("span");
962
- text.style.cssText = "flex:1;min-width:0;";
963
- const code = doc.createElement("code");
964
- code.style.cssText = `display:block;font:12px ${MONO};color:#f3f4f6;word-break:break-all;`;
965
- code.textContent = `<${row.info.tag}> ${row.hookLabel}`;
966
- const hint = doc.createElement("span");
967
- hint.style.cssText = "color:#9ca3af;";
968
- const inside = row.info.scopedLeafCount ?? -1;
969
- hint.textContent = row.selectable ? inside === 1 ? words.containsOne : inside < 0 ? words.countUnavailable : counted(words.containsMany, inside) : words.needsTestId;
970
- text.appendChild(code);
971
- text.appendChild(hint);
972
- line.appendChild(box);
973
- line.appendChild(text);
974
- line.addEventListener("mouseenter", () => {
975
- const r = row.node.getBoundingClientRect();
976
- outline.style.display = "block";
977
- outline.style.left = r.left + "px";
978
- outline.style.top = r.top + "px";
979
- outline.style.width = r.width + "px";
980
- outline.style.height = r.height + "px";
981
- outlineLabel.textContent = `<${row.info.tag}> ${row.hookLabel}`;
982
- outlineLabel.style.display = "block";
983
- const lr = outlineLabel.getBoundingClientRect();
984
- const vw = g.innerWidth || doc.documentElement.clientWidth || 0;
985
- const top = r.top - lr.height - 6 < 4 ? r.bottom + 6 : r.top - lr.height - 6;
986
- outlineLabel.style.left = Math.max(6, Math.min(r.left, vw - lr.width - 6)) + "px";
987
- outlineLabel.style.top = top + "px";
988
- });
989
- line.addEventListener("mouseleave", () => {
990
- outline.style.display = "none";
991
- outlineLabel.style.display = "none";
992
- });
993
- box.addEventListener("change", () => {
994
- if (box.checked) selected.add(i);
995
- else selected.delete(i);
996
- refreshFooter();
997
- });
998
- panel.appendChild(line);
999
- });
1000
- panel.appendChild(footer);
1001
- const cleanup = () => {
1002
- doc.removeEventListener("keydown", onKey, true);
1003
- panel.remove();
1004
- outline.remove();
1005
- outlineLabel.remove();
1006
- pickedOutline.remove();
1007
- if (g.__piwiAnchorCleanup === cleanup) delete g.__piwiAnchorCleanup;
1008
- };
1009
- const done = (state) => {
1010
- g.__piwiPickAnchors = state === "done" ? rows.filter((_, i) => selected.has(i)).map((r) => r.info) : [];
1011
- g.__piwiAnchorState = state;
1012
- cleanup();
1013
- };
1014
- const onKey = (e) => {
1015
- if (e.key !== "Escape") return;
1016
- e.preventDefault();
1017
- e.stopImmediatePropagation();
1018
- done("skipped");
1019
- };
1020
- const buttonRow = doc.createElement("div");
1021
- buttonRow.style.cssText = "display:flex;gap:8px;margin-top:4px;";
1022
- const useBtn = doc.createElement("button");
1023
- useBtn.style.cssText = "flex:1;background:#7c3aed;color:#fff;border:none;border-radius:6px;padding:8px;cursor:pointer;font:600 12px system-ui;";
1024
- useBtn.textContent = words.use;
1025
- useBtn.addEventListener("click", (e) => {
1026
- e.preventDefault();
1027
- e.stopImmediatePropagation();
1028
- done(selected.size > 0 ? "done" : "skipped");
1029
- });
1030
- const skipBtn = doc.createElement("button");
1031
- skipBtn.style.cssText = "background:none;border:1px solid #374151;color:#9ca3af;border-radius:6px;padding:8px 10px;cursor:pointer;font:12px system-ui;";
1032
- skipBtn.textContent = words.skip;
1033
- skipBtn.addEventListener("click", (e) => {
1034
- e.preventDefault();
1035
- e.stopImmediatePropagation();
1036
- done("skipped");
1037
- });
1038
- buttonRow.appendChild(useBtn);
1039
- buttonRow.appendChild(skipBtn);
1040
- panel.appendChild(buttonRow);
1041
- refreshFooter();
1042
- g.__piwiAnchorCleanup = cleanup;
1043
- doc.addEventListener("keydown", onKey, true);
1044
- const mountParent = () => {
1045
- let modal = null;
1046
- try {
1047
- modal = doc.querySelector("dialog:modal");
1048
- } catch {
1049
- modal = null;
1050
- }
1051
- if (!modal) return doc.body;
1052
- const s = g.getComputedStyle(modal);
1053
- const holdsFixed = s.transform !== "none" || s.perspective !== "none" || s.filter !== "none" || /\b(paint|layout|strict|content)\b/.test(s.contain) || /\b(transform|perspective|filter)\b/.test(s.willChange);
1054
- return holdsFixed ? doc.body : modal;
1055
- };
1056
- const mount = (...nodes) => {
1057
- const parent = mountParent();
1058
- for (const node2 of nodes) parent.appendChild(node2);
1059
- if (parent !== doc.body) {
1060
- parent.addEventListener(
1061
- "close",
1062
- () => {
1063
- for (const node2 of nodes) if (node2.parentNode === parent) doc.body.appendChild(node2);
1064
- },
1065
- { once: true }
1066
- );
1067
- }
1068
- };
1069
- mount(pickedOutline, outline, outlineLabel, panel);
1070
- }
1071
-
1072
- // ../picker-dom/src/overlay-confirm.ts
1073
- function showPickerChoices(arg) {
1074
- const g = globalThis;
1075
- const doc = g.document;
1076
- if (!doc || !doc.body) {
1077
- g.__piwiPickChoice = -1;
1078
- return;
1079
- }
1080
- const Z = 2147483600;
1081
- const wrap = doc.createElement("div");
1082
- wrap.id = "__piwi_picker_choices";
1083
- wrap.style.cssText = `position:fixed;inset:0;z-index:${Z + 3};background:rgba(0,0,0,.45);display:flex;align-items:center;justify-content:center;font:13px/1.5 system-ui,sans-serif;`;
1084
- const panel = doc.createElement("div");
1085
- panel.style.cssText = "background:#111827;color:#f9fafb;border-radius:10px;padding:20px;max-width:640px;width:90vw;max-height:70vh;overflow:auto;box-shadow:0 8px 40px rgba(0,0,0,.5);";
1086
- const hlLocator = (expr) => {
1087
- const escHtml = (s) => s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
1088
- const re = /('(?:\\.|[^'\\])*'|"(?:\\.|[^"\\])*")|([A-Za-z_$][\w$]*)(?=\s*\()|([A-Za-z_$][\w$]*)(?=\s*:)|(true|false|null|\d+)|([{}(),.])/g;
1089
- let html = "";
1090
- let last = 0;
1091
- let m;
1092
- while ((m = re.exec(expr)) !== null) {
1093
- if (m.index > last) html += escHtml(expr.slice(last, m.index));
1094
- const color = m[1] ? "#86efac" : m[2] ? "#d8b4fe" : m[3] ? "#93c5fd" : m[4] ? "#fcd34d" : "#9ca3af";
1095
- html += `<span style="color:${color}">${escHtml(m[0])}</span>`;
1096
- last = re.lastIndex;
1097
- }
1098
- if (last < expr.length) html += escHtml(expr.slice(last));
1099
- return html;
1100
- };
1101
- const title = doc.createElement("div");
1102
- title.style.cssText = "font-weight:600;margin-bottom:4px;";
1103
- title.textContent = arg.failing ? "Pick a replacement locator" : "Pick a locator";
1104
- const sub = doc.createElement("div");
1105
- sub.style.cssText = "color:#9ca3af;margin-bottom:12px;";
1106
- if (arg.failing) {
1107
- sub.innerHTML = `Replaces <code style="font-family:ui-monospace,Menlo,monospace">${hlLocator(arg.failing)}</code> \u2014 ranked by stability score.`;
1108
- } else {
1109
- sub.textContent = "For the element you picked \u2014 ranked by stability score.";
1110
- }
1111
- panel.appendChild(title);
1112
- panel.appendChild(sub);
1113
- const cleanup = () => {
1114
- doc.removeEventListener("keydown", onKey, true);
1115
- wrap.remove();
1116
- if (g.__piwiChoiceCleanup === cleanup) delete g.__piwiChoiceCleanup;
1117
- };
1118
- const done = (choice) => {
1119
- g.__piwiPickChoice = choice;
1120
- cleanup();
1121
- };
1122
- const onKey = (e) => {
1123
- if (e.key !== "Escape") return;
1124
- e.preventDefault();
1125
- e.stopImmediatePropagation();
1126
- done(-1);
1127
- };
1128
- arg.choices.forEach((c, i) => {
1129
- const btn = doc.createElement("button");
1130
- btn.style.cssText = "display:flex;justify-content:space-between;align-items:center;gap:12px;width:100%;text-align:left;background:#0b1120;color:#f3f4f6;border:1px solid #374151;border-radius:6px;padding:8px 12px;margin:0 0 8px;cursor:pointer;font:13px/1.55 ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;";
1131
- const code = doc.createElement("span");
1132
- code.innerHTML = hlLocator(c.locator);
1133
- code.style.cssText = "word-break:break-all;";
1134
- const score = doc.createElement("span");
1135
- score.textContent = String(c.score);
1136
- score.style.cssText = "color:#c4b5fd;flex-shrink:0;font-variant-numeric:tabular-nums;";
1137
- btn.appendChild(code);
1138
- btn.appendChild(score);
1139
- btn.addEventListener("click", (e) => {
1140
- e.preventDefault();
1141
- e.stopImmediatePropagation();
1142
- done(i);
1143
- });
1144
- panel.appendChild(btn);
1145
- });
1146
- const skip = doc.createElement("button");
1147
- skip.style.cssText = "background:none;border:none;color:#9ca3af;cursor:pointer;padding:6px 0 0;font:12px system-ui,sans-serif;";
1148
- skip.textContent = "Skip \u2014 keep the failure as-is (Esc)";
1149
- skip.addEventListener("click", (e) => {
1150
- e.preventDefault();
1151
- e.stopImmediatePropagation();
1152
- done(-1);
1153
- });
1154
- panel.appendChild(skip);
1155
- doc.addEventListener("keydown", onKey, true);
1156
- g.__piwiChoiceCleanup = cleanup;
1157
- wrap.appendChild(panel);
1158
- doc.body.appendChild(wrap);
1159
- }
1160
-
1161
- // ../core/src/locator-generation.ts
1162
- var TAG_TO_ROLE = {
1163
- a: "link",
1164
- button: "button",
1165
- nav: "navigation",
1166
- main: "main",
1167
- article: "article",
1168
- section: "region",
1169
- form: "form",
1170
- img: "img",
1171
- figure: "figure",
1172
- figcaption: "caption",
1173
- blockquote: "blockquote",
1174
- table: "table",
1175
- caption: "caption",
1176
- thead: "rowgroup",
1177
- tbody: "rowgroup",
1178
- tfoot: "rowgroup",
1179
- tr: "row",
1180
- td: "cell",
1181
- ul: "list",
1182
- ol: "list",
1183
- li: "listitem",
1184
- dialog: "dialog",
1185
- output: "status",
1186
- progress: "progressbar",
1187
- meter: "meter",
1188
- textarea: "textbox",
1189
- h1: "heading",
1190
- h2: "heading",
1191
- h3: "heading",
1192
- h4: "heading",
1193
- h5: "heading",
1194
- h6: "heading",
1195
- details: "group",
1196
- summary: "button",
1197
- search: "search"
1198
- };
1199
- var INPUT_TYPE_TO_ROLE = {
1200
- button: "button",
1201
- submit: "button",
1202
- reset: "button",
1203
- image: "button",
1204
- checkbox: "checkbox",
1205
- radio: "radio",
1206
- range: "slider",
1207
- search: "searchbox",
1208
- number: "spinbutton",
1209
- text: "textbox",
1210
- email: "textbox",
1211
- tel: "textbox",
1212
- url: "textbox",
1213
- password: "textbox"
1214
- };
1215
- function resolveAriaRole(attrs) {
1216
- const explicit = attrs.attributes["role"];
1217
- if (explicit) return explicit;
1218
- const tag = attrs.tagName;
1219
- if (!tag) return null;
1220
- if (tag === "input") {
1221
- const type = (attrs.attributes["type"] ?? "text").toLowerCase();
1222
- return INPUT_TYPE_TO_ROLE[type] ?? "textbox";
1223
- }
1224
- if (tag === "select") {
1225
- return attrs.attributes["multiple"] != null ? "listbox" : "combobox";
1226
- }
1227
- if (tag === "a") {
1228
- return attrs.attributes["href"] != null ? "link" : null;
1229
- }
1230
- return TAG_TO_ROLE[tag] ?? null;
1231
- }
1232
- function headingLevel(attrs, role) {
1233
- if (role !== "heading") return null;
1234
- const tagMatch = attrs.tagName.match(/^h([1-6])$/);
1235
- if (tagMatch) return Number(tagMatch[1]);
1236
- const ariaLevel = attrs.attributes["aria-level"];
1237
- if (ariaLevel && /^\d+$/.test(ariaLevel)) return Number(ariaLevel);
1238
- return null;
1239
- }
1240
- var attr = (a, key) => a.attributes[key] || null;
1241
- var escCssAttrValue = (s) => s.replace(/\\/g, "\\\\").replace(/"/g, '\\"');
1242
- var isCssSafeId = (id) => /^[A-Za-z][A-Za-z0-9_-]*$/.test(id);
1243
- function classifyCssStability(className) {
1244
- if (/[a-f0-9]{8,}/i.test(className)) return 10;
1245
- if (/^(?:css|sc|emotion|styled)-/i.test(className)) return 15;
1246
- if (/^(bg|text|border|shadow|opacity|font|w-|h-|m[tblrxy]?-|p[tblrxy]?-|flex|grid|gap|rounded|absolute|relative|fixed|sticky|block|inline|hidden|overflow|z-|top-|right-|bottom-|left-|inset-|justify-|items-|self-|content-|order-|col-|row-)/.test(
1247
- className
1248
- ))
1249
- return 25;
1250
- if (/__/.test(className) || /--/.test(className)) return 35;
1251
- if (/^[a-z]+(-[a-z]+)+$/.test(className)) return 40;
1252
- if (/^[a-z]+[A-Z][a-zA-Z]+$/.test(className)) return 40;
1253
- if (className.includes("_")) return 15;
1254
- if (/^[a-z]+-[a-z0-9]{5,}$/.test(className) && /[0-9]/.test(className)) return 15;
1255
- return 15;
1256
- }
1257
- function isAutoGenerated(value) {
1258
- if (/^[a-f0-9]{8}-([a-f0-9]{4}-){3}[a-f0-9]{12}$/i.test(value)) return true;
1259
- if (/^[a-f0-9]{8,}$/i.test(value)) return true;
1260
- if (/^[a-z]+-\d{4,}$/.test(value)) return true;
1261
- if (/^(tab|panel|input|select|option|dialog|modal|popup|tooltip|menu|listbox|combobox|checkbox|radio|textarea|button|field|label|accordion|collapse|step|slider|toggle|switch|dropdown|overlay|portal|layer)-\d+$/i.test(
1262
- value
1263
- )) {
1264
- return true;
1265
- }
1266
- if (/^(emotion-|styled-|css-|sc-)/.test(value)) return true;
1267
- if (value.startsWith("ng-")) return true;
1268
- if (/^(radix-|headlessui-|mui-|mantine-|chakra-|reka-|bits-|downshift-|react-aria|el-id-)/i.test(value)) return true;
1269
- if (/^:r[0-9a-z]+:$/i.test(value) || /^«r[0-9a-z]+»$/i.test(value)) return true;
1270
- if (/(^|[-_:])v-\d+(-\d+)+$/.test(value) || /(^|[-_:])v-\d+(-\d+)+[-_:]/.test(value)) return true;
1271
- return false;
1272
- }
1273
- var TEST_DATA_ATTRS = /* @__PURE__ */ new Set(["data-test", "data-test-id", "data-qa", "data-qa-id", "data-cy", "data-e2e"]);
1274
- function generateAlternatives(attrs, options = {}) {
1275
- const alts = [];
1276
- const seen = /* @__PURE__ */ new Set();
1277
- const add = (loc) => {
1278
- if (!seen.has(loc.locator)) {
1279
- seen.add(loc.locator);
1280
- alts.push(loc);
1281
- }
1282
- };
1283
- const { accessibleName } = attrs;
1284
- const tag = attrs.tagName;
1285
- const role = options.role !== void 0 ? options.role : resolveAriaRole(attrs);
1286
- const counts = attrs.selectorCounts;
1287
- const isUnique = (n) => n == null || n <= 1;
1288
- const ambiguityPenalty = (n) => n != null && n > 1 ? 45 : 0;
1289
- const text = attrs.textContent ? attrs.textContent.replace(/\s+/g, " ").trim() : null;
1290
- const testIdAttribute = options.testIdAttribute || "data-testid";
1291
- const selectable = (name2) => name2.toLowerCase() !== testIdAttribute.toLowerCase();
1292
- const testId = attr(attrs, testIdAttribute);
1293
- if (testId && isUnique(counts?.testId)) {
1294
- add({
1295
- locator: `getByTestId(${quoteJsString(testId)})`,
1296
- method: "getByTestId",
1297
- args: { testId },
1298
- score: 100
1299
- });
1300
- }
1301
- const level = headingLevel(attrs, role);
1302
- const levelPart = level != null ? `, level: ${level}` : "";
1303
- const withLevel = (base) => level != null ? { ...base, level } : base;
1304
- if (role && accessibleName) {
1305
- add({
1306
- locator: `getByRole(${quoteJsString(role)}, { name: ${quoteJsString(accessibleName)}${levelPart} })`,
1307
- method: "getByRole",
1308
- args: withLevel({ role, name: accessibleName }),
1309
- score: 90 - ambiguityPenalty(counts?.roleName)
1310
- });
1311
- }
1312
- const ariaLabel = attr(attrs, "aria-label");
1313
- if (role && ariaLabel && ariaLabel !== accessibleName) {
1314
- add({
1315
- locator: `getByRole(${quoteJsString(role)}, { name: ${quoteJsString(ariaLabel)}${levelPart} })`,
1316
- method: "getByRole",
1317
- args: withLevel({ role, name: ariaLabel }),
1318
- score: 85 - ambiguityPenalty(counts?.roleName)
1319
- });
1320
- }
1321
- if (accessibleName && ["input", "select", "textarea"].includes(tag)) {
1322
- const label = attr(attrs, "aria-label");
1323
- const labelBacked = attrs.hasLabel === void 0 ? true : attrs.hasLabel === true || label === accessibleName;
1324
- if (labelBacked) {
1325
- add({
1326
- locator: `getByLabel(${quoteJsString(accessibleName)})`,
1327
- method: "getByLabel",
1328
- args: { label: accessibleName },
1329
- score: 85
1330
- });
1331
- }
1332
- }
1333
- const placeholder = attr(attrs, "placeholder");
1334
- if (placeholder) {
1335
- add({
1336
- locator: `getByPlaceholder(${quoteJsString(placeholder)})`,
1337
- method: "getByPlaceholder",
1338
- args: { placeholder },
1339
- score: 80 - ambiguityPenalty(counts?.placeholder)
1340
- });
1341
- }
1342
- if (text && text.length < 80) {
1343
- add({
1344
- locator: `getByText(${quoteJsString(text)})`,
1345
- method: "getByText",
1346
- args: { text },
1347
- score: 75 - ambiguityPenalty(counts?.text)
1348
- });
1349
- }
1350
- const id = attr(attrs, "id");
1351
- if (id && selectable("id") && !isAutoGenerated(id) && isUnique(counts?.id)) {
1352
- const selector = isCssSafeId(id) ? `#${id}` : `[id="${escCssAttrValue(id)}"]`;
1353
- add({
1354
- locator: `locator(${quoteJsString(selector)})`,
1355
- method: "locator",
1356
- args: { selector },
1357
- score: 65
1358
- });
1359
- }
1360
- const name = attr(attrs, "name");
1361
- if (name && selectable("name") && isUnique(counts?.name)) {
1362
- const selector = `[name="${escCssAttrValue(name)}"]`;
1363
- add({
1364
- locator: `locator(${quoteJsString(selector)})`,
1365
- method: "locator",
1366
- args: { selector },
1367
- score: 60
1368
- });
1369
- }
1370
- const alt = attr(attrs, "alt");
1371
- if (alt) {
1372
- add({
1373
- locator: `getByAltText(${quoteJsString(alt)})`,
1374
- method: "getByAltText",
1375
- args: { text: alt },
1376
- score: 60 - ambiguityPenalty(counts?.alt)
1377
- });
1378
- }
1379
- const title = attr(attrs, "title");
1380
- if (title) {
1381
- add({
1382
- locator: `getByTitle(${quoteJsString(title)})`,
1383
- method: "getByTitle",
1384
- args: { title },
1385
- score: 50 - ambiguityPenalty(counts?.title)
1386
- });
1387
- }
1388
- const hasOwnTestId = !!(testId && isUnique(counts?.testId));
1389
- const addAnchoredChains = (leaf, scopedCount, scores) => {
1390
- let testIdAnchorDone = false;
1391
- let idAnchorDone = false;
1392
- let roleAnchorDone = false;
1393
- let dataAnchorDone = false;
1394
- let filterAnchorDone = false;
1395
- for (const anc of attrs.ancestors ?? []) {
1396
- if (scopedCount(anc) !== 1) continue;
1397
- if (!testIdAnchorDone && anc.testId && anc.testIdCount === 1) {
1398
- testIdAnchorDone = true;
1399
- add({
1400
- locator: `getByTestId(${quoteJsString(anc.testId)}).${leaf.expr}`,
1401
- method: leaf.method,
1402
- args: { ...leaf.args, anchorTestId: anc.testId },
1403
- score: scores.testId
1404
- });
1405
- }
1406
- if (!idAnchorDone && anc.id && selectable("id") && !isAutoGenerated(anc.id) && anc.idCount === 1) {
1407
- idAnchorDone = true;
1408
- const anchorSelector = isCssSafeId(anc.id) ? `#${anc.id}` : `[id="${escCssAttrValue(anc.id)}"]`;
1409
- add({
1410
- locator: `locator(${quoteJsString(anchorSelector)}).${leaf.expr}`,
1411
- method: leaf.method,
1412
- args: { ...leaf.args, anchorSelector },
1413
- score: scores.id
1414
- });
1415
- }
1416
- if (!dataAnchorDone && anc.dataAttr && selectable(anc.dataAttr.name) && anc.dataAttrCount === 1) {
1417
- dataAnchorDone = true;
1418
- const { name: name2, value } = anc.dataAttr;
1419
- const anchorSelector = `[${name2}="${escCssAttrValue(value)}"]`;
1420
- add({
1421
- locator: `locator(${quoteJsString(anchorSelector)}).${leaf.expr}`,
1422
- method: leaf.method,
1423
- args: { ...leaf.args, anchorSelector },
1424
- score: TEST_DATA_ATTRS.has(name2) ? scores.testData : scores.data
1425
- });
1426
- }
1427
- const ancestorRole = anc.role || TAG_TO_ROLE[anc.tag] || null;
1428
- if (!roleAnchorDone && ancestorRole && ancestorRole !== leaf.role && anc.roleCount === 1) {
1429
- roleAnchorDone = true;
1430
- add({
1431
- locator: `getByRole(${quoteJsString(ancestorRole)}).${leaf.expr}`,
1432
- method: leaf.method,
1433
- args: { ...leaf.args, anchorRole: ancestorRole },
1434
- score: scores.role
1435
- });
1436
- }
1437
- if (!filterAnchorDone && ancestorRole && anc.filterText && anc.filterRoleCount === 1) {
1438
- filterAnchorDone = true;
1439
- add({
1440
- locator: `getByRole(${quoteJsString(ancestorRole)}).filter({ hasText: ${quoteJsString(anc.filterText)} }).${leaf.expr}`,
1441
- method: leaf.method,
1442
- args: { ...leaf.args, anchorRole: ancestorRole, anchorHasText: anc.filterText },
1443
- score: scores.filter
1444
- });
1445
- }
1446
- }
1447
- };
1448
- if (role && !hasOwnTestId) {
1449
- const rolePart = level != null ? `${quoteJsString(role)}, { level: ${level} }` : quoteJsString(role);
1450
- const leafArgs = withLevel({ role });
1451
- addAnchoredChains(
1452
- { expr: `getByRole(${rolePart})`, method: "getByRole", args: leafArgs, role },
1453
- (anc) => anc.scopedRoleCount,
1454
- { testId: 72, testData: 70, id: 64, data: 60, role: 55, filter: 53 }
1455
- );
1456
- const pos = attrs.rolePosition;
1457
- if (pos && pos.role === role && (pos.count === 1 || level != null && pos.levelCount === 1)) {
1458
- add({
1459
- locator: `getByRole(${rolePart})`,
1460
- method: "getByRole",
1461
- args: leafArgs,
1462
- score: 58
1463
- });
1464
- }
1465
- } else if (!role && text && text.length < 80 && !hasOwnTestId) {
1466
- addAnchoredChains(
1467
- { expr: `getByText(${quoteJsString(text)})`, method: "getByText", args: { text }, role: null },
1468
- (anc) => anc.scopedTextCount,
1469
- { testId: 68, testData: 66, id: 60, data: 56, role: 51, filter: 49 }
1470
- );
1471
- }
1472
- const clsStr = attr(attrs, "class");
1473
- if (clsStr) {
1474
- const countsClasses = counts?.classes;
1475
- const classes = clsStr.split(/\s+/).filter((c) => c.length > 1 && /^[A-Za-z_-][A-Za-z0-9_-]*$/.test(c) && isUnique(countsClasses?.[c])).map((cls) => ({ cls, score: classifyCssStability(cls) })).sort((a, b) => b.score - a.score).slice(0, 3);
1476
- for (const { cls, score } of classes) {
1477
- add({
1478
- locator: `locator(${quoteJsString(`.${cls}`)})`,
1479
- method: "locator",
1480
- args: { selector: `.${cls}` },
1481
- score
1482
- });
1483
- }
1484
- }
1485
- return alts.sort((a, b) => b.score - a.score);
1486
- }
1487
- function approximateAccessibleName(attrs) {
1488
- const a = attrs.attributes;
1489
- const labelText = attrs.labelText || null;
1490
- if (a["aria-labelledby"] && labelText) return labelText;
1491
- const ariaLabel = a["aria-label"];
1492
- if (ariaLabel) return ariaLabel;
1493
- if (["input", "select", "textarea"].includes(attrs.tagName)) {
1494
- if (labelText) return labelText;
1495
- } else if (attrs.textContent) {
1496
- return attrs.textContent;
1497
- }
1498
- const title = a["title"];
1499
- if (title) return title;
1500
- const placeholder = a["placeholder"];
1501
- if (placeholder) return placeholder;
1502
- return null;
1503
- }
1504
-
1505
- // ../picker-dom/src/anchor-alternatives.ts
1506
- var cssIdSelector = (id) => /^[A-Za-z_][A-Za-z0-9_-]*$/.test(id) ? `#${id}` : `[id="${id.replaceAll("\\", "\\\\").replaceAll('"', '\\"')}"]`;
1507
- var ANCHOR_KIND_SCORES = { testid: 80, id: 74, labeledRole: 68, role: 62 };
1508
- function anchorSegment(a) {
1509
- if (a.testId && a.testIdCount === 1) {
1510
- return { code: `getByTestId(${quoteJsString(a.testId)})`, kind: "testid", flatArgs: { anchorTestId: a.testId } };
1511
- }
1512
- if (a.id && !isAutoGenerated(a.id) && a.idCount === 1) {
1513
- const anchorSelector = cssIdSelector(a.id);
1514
- return { code: `locator(${quoteJsString(anchorSelector)})`, kind: "id", flatArgs: { anchorSelector } };
1515
- }
1516
- if (a.role && a.ariaLabel && a.labeledRoleCount === 1) {
1517
- return {
1518
- code: `getByRole(${quoteJsString(a.role)}, { name: ${quoteJsString(a.ariaLabel)} })`,
1519
- kind: "labeledRole",
1520
- flatArgs: { anchorRole: a.role, anchorName: a.ariaLabel }
1521
- };
1522
- }
1523
- if (a.role && a.roleCount === 1) {
1524
- return { code: `getByRole(${quoteJsString(a.role)})`, kind: "role", flatArgs: { anchorRole: a.role } };
1525
- }
1526
- return null;
1527
- }
1528
- function generateAnchoredAlternatives(leaf, anchors, chainLeafCount) {
1529
- if (!leaf.role || anchors.length === 0) return [];
1530
- const out = [];
1531
- const seen = /* @__PURE__ */ new Set();
1532
- const rolePart = leaf.level != null ? `${quoteJsString(leaf.role)}, { level: ${leaf.level} }` : quoteJsString(leaf.role);
1533
- const leafArgs = leaf.level != null ? { role: leaf.role, level: leaf.level } : { role: leaf.role };
1534
- const add = (l) => {
1535
- if (!seen.has(l.locator)) {
1536
- seen.add(l.locator);
1537
- out.push(l);
1538
- }
1539
- };
1540
- for (const anchor of anchors) {
1541
- if (anchor.scopedLeafCount !== 1) continue;
1542
- const seg = anchorSegment(anchor);
1543
- if (!seg) continue;
1544
- add({
1545
- locator: `${seg.code}.getByRole(${rolePart})`,
1546
- method: "getByRole",
1547
- args: { ...leafArgs, ...seg.flatArgs },
1548
- score: ANCHOR_KIND_SCORES[seg.kind]
1549
- });
1550
- }
1551
- if (anchors.length >= 2 && chainLeafCount === 1) {
1552
- const ordered = [...anchors].sort((a, b) => b.depth - a.depth);
1553
- const segments = ordered.map(anchorSegment);
1554
- if (segments.every((s) => s !== null)) {
1555
- const innermost = segments[segments.length - 1];
1556
- const score = Math.min(...segments.map((s) => ANCHOR_KIND_SCORES[s.kind]));
1557
- add({
1558
- locator: `${segments.map((s) => s.code).join(".")}.getByRole(${rolePart})`,
1559
- method: "getByRole",
1560
- // Flat args describe the innermost anchor (what the healing fingerprint
1561
- // logic understands); the full chain rides along for transparency.
1562
- args: { ...leafArgs, ...innermost.flatArgs, anchorChain: segments.map((s) => s.code) },
1563
- score
1564
- });
1565
- }
1566
- }
1567
- return out.sort((a, b) => b.score - a.score);
1568
- }
1569
- function mergeCandidates(base, extra) {
1570
- const seen = new Set(base.map((b) => b.locator));
1571
- const merged = [...base];
1572
- for (const e of extra) {
1573
- if (seen.has(e.locator)) continue;
1574
- seen.add(e.locator);
1575
- merged.push(e);
1576
- }
1577
- return merged.sort((a, b) => b.score - a.score);
1578
- }
1579
-
1580
- // src/internal/capture/locator-healing.ts
1581
- var path = __toESM(require("path"));
1582
- var import_node_url = require("url");
1583
-
1584
- // ../core/src/locator-fingerprint.ts
1585
- var FUNCTION_WORDS = new Set(
1586
- "the and for with from your you our this that les des une pour avec par sur aux dans vos votre nos notre".split(" ")
1587
- );
1588
-
1589
- // src/internal/capture/locator-healing.ts
1590
- var LOCATOR_METHODS = [...LOCATOR_BUILDER_METHODS];
1591
- var LOCATOR_CREATING_CHAINS = new Set(LOCATOR_METHODS);
1592
- function failedNameAndRole(failed) {
1593
- if (failed.method === "getByRole") {
1594
- const role = typeof failed.args[0] === "string" ? failed.args[0] : null;
1595
- const opts = failed.args[1];
1596
- const name = opts && typeof opts.name === "string" ? opts.name : null;
1597
- const level = opts && typeof opts.level === "number" ? opts.level : null;
1598
- return { role, name, level };
1599
- }
1600
- const first = failed.args.find((a) => typeof a === "string");
1601
- return { role: null, name: typeof first === "string" ? first : null, level: null };
1602
- }
1603
- function renderFailing(failed) {
1604
- const { role, name } = failedNameAndRole(failed);
1605
- if (failed.method === "getByRole") {
1606
- return name ? `getByRole(${quoteJsString(role ?? "")}, { name: ${quoteJsString(name)} })` : `getByRole(${quoteJsString(role ?? "")})`;
1607
- }
1608
- return `${failed.method}(${quoteJsString(name ?? "")})`;
1609
- }
1610
-
1611
- // src/internal/capture/pick-on-failure.ts
1612
- function parseLeafLocatorExpression(rawExpr) {
1613
- const leaf = parseLeafLocatorCall(rawExpr);
1614
- return leaf ? { method: leaf.method, args: locatorCallValues(leaf) } : null;
1615
- }
1616
- function deriveFailedLocator(testInfo) {
1617
- const info = testInfo;
1618
- const errors = info.errors && info.errors.length > 0 ? info.errors : info.error ? [info.error] : [];
1619
- for (const err of errors) {
1620
- const header = readLocatorHeader(stripAnsi(`${err.message ?? ""}
1621
- ${err.stack ?? ""}`));
1622
- if (!header) continue;
1623
- const parsed = parseLeafLocatorExpression(header);
1624
- if (!parsed) continue;
1625
- const loc = err.location;
1626
- const location = loc ? `${path2.relative(process.cwd(), loc.file).split(path2.sep).join("/")}:${loc.line}:${loc.column}` : null;
1627
- return { method: parsed.method, args: parsed.args, location };
1628
- }
1629
- return null;
1630
- }
1631
- var PICK_ENDED = "__piwiPickEnded";
1632
- async function cleanupPicker(page, ended = false) {
1633
- try {
1634
- await page.evaluate(
1635
- ([endedKey, unanswered]) => {
1636
- const g = globalThis;
1637
- if (typeof g.__piwiPickCleanup === "function") g.__piwiPickCleanup();
1638
- if (typeof g.__piwiAnchorCleanup === "function") g.__piwiAnchorCleanup();
1639
- if (typeof g.__piwiChoiceCleanup === "function") g.__piwiChoiceCleanup();
1640
- delete g.__piwiPickCleanup;
1641
- delete g.__piwiAnchorCleanup;
1642
- delete g.__piwiChoiceCleanup;
1643
- delete g.__piwiPickState;
1644
- delete g.__piwiPickChoice;
1645
- delete g.__piwiPickedElement;
1646
- delete g.__piwiAnchorState;
1647
- delete g.__piwiPickAnchors;
1648
- delete g.__piwiPickChainCount;
1649
- if (unanswered) g[endedKey] = true;
1650
- else delete g[endedKey];
1651
- },
1652
- [PICK_ENDED, ended]
1653
- );
1654
- } catch {
1655
- }
1656
- }
1657
- function unlessEnded(run, ended) {
1658
- if (!ended) return run;
1659
- return Promise.race([
1660
- run,
1661
- new Promise((resolve) => {
1662
- if (ended.aborted) resolve(void 0);
1663
- else ended.addEventListener("abort", () => resolve(void 0), { once: true });
1664
- })
1665
- ]);
1666
- }
1667
- async function pickLocator(page, probe, failing, ended) {
1668
- let polling = false;
1669
- const answered = async (name) => {
1670
- const wait = page.waitForFunction(
1671
- ([key, endedKey]) => {
1672
- const g = globalThis;
1673
- if (g[endedKey] !== true) return g[key] !== void 0;
1674
- delete g[endedKey];
1675
- return true;
1676
- },
1677
- [name, PICK_ENDED],
1678
- { timeout: 0, polling: 250 }
1679
- );
1680
- polling = true;
1681
- const done = await unlessEnded(
1682
- wait.then(() => true),
1683
- ended
1684
- );
1685
- if (done) polling = false;
1686
- return !ended?.aborted;
1687
- };
1688
- try {
1689
- const overlayArg = { transport: "global", failing };
1690
- await page.evaluate((endedKey) => delete globalThis[endedKey], PICK_ENDED);
1691
- await page.evaluate(installPickerOverlay, overlayArg);
1692
- if (!await answered("__piwiPickState")) return null;
1693
- const state = await page.evaluate(() => globalThis.__piwiPickState);
1694
- if (state !== "picked") return null;
1695
- const handle = await page.evaluateHandle(() => globalThis.__piwiPickedElement);
1696
- const attrs = await handle.evaluate(probe.fn, probe.arg);
1697
- await handle.dispose();
1698
- const accessibleName = approximateAccessibleName({ ...attrs, accessibleName: null });
1699
- const role = resolveAriaRole({ ...attrs, accessibleName });
1700
- const level = headingLevel({ ...attrs, accessibleName }, role);
1701
- let anchors = [];
1702
- let chainLeafCount;
1703
- if (role) {
1704
- const probeArg = probe.arg;
1705
- await page.evaluate(showAnchorPicker, {
1706
- tagRoles: probeArg.tagRoles ?? {},
1707
- inputRoles: probeArg.inputRoles ?? {},
1708
- roleSources: probeArg.roleSources ?? "",
1709
- leafRole: role,
1710
- leafLevel: level,
1711
- leafTestId: attrs.attributes["data-testid"] ?? null
1712
- });
1713
- if (!await answered("__piwiAnchorState")) return null;
1714
- const anchorResult = await page.evaluate(() => {
1715
- const g = globalThis;
1716
- return { state: g.__piwiAnchorState, anchors: g.__piwiPickAnchors ?? [], chainCount: g.__piwiPickChainCount };
1717
- });
1718
- if (anchorResult.state === "done" && anchorResult.anchors.length > 0) {
1719
- anchors = anchorResult.anchors;
1720
- chainLeafCount = anchorResult.chainCount;
1721
- }
1722
- }
1723
- const ranked = mergeCandidates(
1724
- generateAlternatives({ ...attrs, accessibleName }),
1725
- generateAnchoredAlternatives({ role, level }, anchors, chainLeafCount)
1726
- );
1727
- if (ranked.length === 0) {
1728
- console.log("[piwi] No stable locator could be generated for the picked element \u2014 nothing recorded.");
1729
- return null;
1730
- }
1731
- await page.evaluate(showPickerChoices, {
1732
- failing,
1733
- choices: ranked.map((r) => ({ locator: r.locator, score: r.score }))
1734
- });
1735
- if (!await answered("__piwiPickChoice")) return null;
1736
- const choice = await page.evaluate(() => globalThis.__piwiPickChoice);
1737
- if (typeof choice !== "number" || choice < 0 || choice >= ranked.length) return null;
1738
- const picked = { ...ranked[choice], pickedByUser: true };
1739
- return {
1740
- picked,
1741
- alternatives: [picked, ...ranked.filter((_, i) => i !== choice)],
1742
- element: {
1743
- tagName: attrs.tagName,
1744
- attributes: attrs.attributes,
1745
- textContent: attrs.textContent,
1746
- accessibleName,
1747
- center: attrs.center,
1748
- ...attrs.rolePosition ? { rolePosition: attrs.rolePosition } : {},
1749
- ...attrs.ancestors && attrs.ancestors.length > 0 ? { ancestors: attrs.ancestors } : {}
1750
- },
1751
- ...anchors.length > 0 ? { anchors } : {}
1752
- };
1753
- } finally {
1754
- await cleanupPicker(page, polling);
1755
- }
1756
- }
1757
- async function runLocatorPicker(page, testInfo, failed, probe) {
1758
- try {
1759
- testInfo.setTimeout(0);
1760
- const rendered = failed ? renderFailing(failed) : null;
1761
- console.log(
1762
- `
1763
- [piwi] "${testInfo.title}" ${testInfo.status} \u2014 ${rendered ? "locator picker" : "inspector"} open in the browser: ${rendered ? `click the element that should replace ${rendered}` : "click any element to generate locators for it"} (\u2191/\u2193 to select a parent/child, Esc to skip).`
1764
- );
1765
- const pick = await pickLocator(page, probe, rendered);
1766
- if (!pick) return null;
1767
- const location = failed?.location ?? null;
1768
- console.log(
1769
- failed ? `[piwi] Replacement picked for ${rendered}${location ? ` at ${location}` : ""}:
1770
- [piwi] ${pick.picked.locator}` : `[piwi] Locator picked while inspecting:
1771
- [piwi] ${pick.picked.locator}`
1772
- );
1773
- return {
1774
- failing: failed ? { method: failed.method, args: failed.args, rendered, location } : null,
1775
- ...pick
1776
- };
1777
- } catch {
1778
- return null;
1779
- }
1780
- }
1781
- function applyPickToSnapshots(snapshots, pick) {
1782
- if (!pick.failing?.location) return false;
1783
- const failing = pick.failing;
1784
- for (let i = snapshots.length - 1; i >= 0; i--) {
1785
- const snap = snapshots[i];
1786
- if (snap.location !== failing.location || snap.element) continue;
1787
- snapshots[i] = {
1788
- location: snap.location,
1789
- used: snap.used,
1790
- element: pick.element,
1791
- alternatives: pick.alternatives.slice(0, 10)
1792
- };
1793
- return true;
1794
- }
1795
- snapshots.push({
1796
- location: failing.location,
1797
- used: {
1798
- method: failing.method,
1799
- args: failing.args,
1800
- raw: `${failing.method}(${JSON.stringify(failing.args)})`
1801
- },
1802
- element: pick.element,
1803
- alternatives: pick.alternatives.slice(0, 10)
1804
- });
1805
- return true;
1806
- }
1807
- // Annotate the CommonJS export names for ESM import in node:
1808
- 0 && (module.exports = {
1809
- applyPickToSnapshots,
1810
- deriveFailedLocator,
1811
- generateAnchoredAlternatives,
1812
- installPickerOverlay,
1813
- mergeCandidates,
1814
- parseLeafLocatorExpression,
1815
- pickLocator,
1816
- runLocatorPicker,
1817
- showAnchorPicker,
1818
- showPickerChoices,
1819
- unlessEnded
1820
- });