@piwitests/reporter 0.19.0 → 0.21.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.
package/dist/index.js CHANGED
@@ -2766,1322 +2766,1775 @@ var PiwiDashboardReporter = class {
2766
2766
  // src/internal/capture/capture-fixtures.ts
2767
2767
  var import_node_zlib = require("zlib");
2768
2768
 
2769
- // src/internal/capture/locator-healing.ts
2770
- var path15 = __toESM(require("path"));
2771
-
2772
- // ../packages/core/src/locator-fingerprint.ts
2773
- var PRESENT_SIMILARITY = 0.8;
2774
- var MATCH_SIMILARITY = 0.2;
2775
- function parseAriaCandidates(ariaSnapshot) {
2776
- if (!ariaSnapshot) return [];
2777
- const out = [];
2778
- for (const line of ariaSnapshot.split("\n")) {
2779
- const m = line.match(/^\s*-\s+([a-z]+)(?:\s+"((?:[^"\\]|\\.)*)")?/i);
2780
- if (!m) continue;
2781
- const role = m[1];
2782
- const name = m[2] != null ? m[2].replace(/\\(.)/g, "$1") : null;
2783
- if (!name && (role === "generic" || role === "group" || role === "list" || role === "paragraph")) continue;
2784
- const levelMatch = line.slice(m[0].length).match(/\[level=(\d+)\]/);
2785
- const level = levelMatch ? Number(levelMatch[1]) : null;
2786
- out.push({ role, name, level });
2787
- }
2788
- return out;
2789
- }
2790
- function textSimilarity(a, b) {
2791
- const tok = (s) => new Set(
2792
- (s ?? "").toLowerCase().split(/[^a-z0-9]+/i).filter(Boolean)
2793
- );
2794
- const sa = tok(a);
2795
- const sb = tok(b);
2796
- if (sa.size === 0 && sb.size === 0) return 1;
2797
- if (sa.size === 0 || sb.size === 0) return 0;
2798
- let common = 0;
2799
- for (const t of sa) if (sb.has(t)) common++;
2800
- return 2 * common / (sa.size + sb.size);
2801
- }
2802
- function fingerprintPresent(fp, candidates) {
2803
- if (!fp.name) return false;
2804
- return candidates.some(
2805
- (c) => (!fp.role || c.role === fp.role) && textSimilarity(c.name, fp.name) >= PRESENT_SIMILARITY
2806
- );
2807
- }
2808
- function matchRenamedElement(fp, candidates) {
2809
- if (candidates.length === 0) return null;
2810
- const sameRole = fp.role ? candidates.filter((c) => c.role === fp.role) : candidates;
2811
- if (sameRole.length === 0) return null;
2812
- let pool = sameRole;
2813
- if (fp.level != null) {
2814
- const sameLevel = sameRole.filter((c) => c.level === fp.level);
2815
- if (sameLevel.length > 0) pool = sameLevel;
2816
- }
2817
- if (pool.length === 1) {
2818
- return { candidate: pool[0], confidence: 0.7 };
2769
+ // ../packages/picker-dom/src/probe.ts
2770
+ function probeElementAttrs(el, arg) {
2771
+ const { keep, tagRoles, inputRoles, roleSources, includeStructural, includeLabelText } = arg;
2772
+ const attrMap = {};
2773
+ for (const key of keep) {
2774
+ const v = el.getAttribute(key) ?? el[key];
2775
+ attrMap[key] = typeof v === "string" ? v.slice(0, 200) : v ? String(v).slice(0, 200) : null;
2819
2776
  }
2820
- let best = null;
2821
- let bestScore = -1;
2822
- for (const c of pool) {
2823
- const s = textSimilarity(c.name, fp.name);
2824
- if (s > bestScore) {
2825
- bestScore = s;
2826
- best = c;
2777
+ const r = el.getBoundingClientRect();
2778
+ const selectorCounts = {};
2779
+ try {
2780
+ const doc = el.ownerDocument;
2781
+ const cssEsc = (s) => doc.defaultView.CSS.escape(s);
2782
+ const count = (sel) => {
2783
+ try {
2784
+ return doc.querySelectorAll(sel).length;
2785
+ } catch {
2786
+ return void 0;
2787
+ }
2788
+ };
2789
+ if (attrMap["data-testid"]) {
2790
+ selectorCounts.testId = count(`[data-testid=${JSON.stringify(attrMap["data-testid"])}]`);
2791
+ }
2792
+ if (attrMap["id"]) selectorCounts.id = count(`#${cssEsc(attrMap["id"])}`);
2793
+ if (attrMap["name"]) selectorCounts.name = count(`[name=${JSON.stringify(attrMap["name"])}]`);
2794
+ if (attrMap["placeholder"]) {
2795
+ selectorCounts.placeholder = count(`[placeholder=${JSON.stringify(attrMap["placeholder"])}]`);
2796
+ }
2797
+ if (attrMap["alt"]) selectorCounts.alt = count(`[alt=${JSON.stringify(attrMap["alt"])}]`);
2798
+ if (attrMap["title"]) selectorCounts.title = count(`[title=${JSON.stringify(attrMap["title"])}]`);
2799
+ const classList = (attrMap["class"] || "").split(/\s+/).filter((c) => c.length > 1).slice(0, 10);
2800
+ if (classList.length > 0) {
2801
+ const classCounts = {};
2802
+ for (const cls of classList) {
2803
+ const n = count(`.${cssEsc(cls)}`);
2804
+ if (n !== void 0) classCounts[cls] = n;
2805
+ }
2806
+ selectorCounts.classes = classCounts;
2827
2807
  }
2808
+ } catch {
2828
2809
  }
2829
- if (best && bestScore >= MATCH_SIMILARITY) return { candidate: best, confidence: bestScore };
2830
- const pos = fp.rolePosition;
2831
- if (pos && fp.role && pos.role === fp.role && sameRole.length >= 2 && sameRole.length === pos.count) {
2832
- const byIndex = sameRole[pos.index];
2833
- if (byIndex) return { candidate: byIndex, confidence: 0.5 };
2810
+ let rolePosition = null;
2811
+ const ancestors = [];
2812
+ if (includeStructural && tagRoles && inputRoles && roleSources) {
2813
+ try {
2814
+ const doc = el.ownerDocument;
2815
+ const cssEsc = (s) => doc.defaultView.CSS.escape(s);
2816
+ const count = (sel) => {
2817
+ try {
2818
+ return doc.querySelectorAll(sel).length;
2819
+ } catch {
2820
+ return void 0;
2821
+ }
2822
+ };
2823
+ const roleMemo = /* @__PURE__ */ new Map();
2824
+ const textMemo = /* @__PURE__ */ new Map();
2825
+ const roleOf = (n) => {
2826
+ const cached = roleMemo.get(n);
2827
+ if (cached !== void 0) return cached;
2828
+ let role;
2829
+ const explicit = n.getAttribute("role");
2830
+ if (explicit) {
2831
+ role = explicit;
2832
+ } else {
2833
+ const tag = (n.tagName || "").toLowerCase();
2834
+ if (tag === "input") role = inputRoles[(n.getAttribute("type") || "text").toLowerCase()] ?? "textbox";
2835
+ else if (tag === "select") role = n.getAttribute("multiple") != null ? "listbox" : "combobox";
2836
+ else if (tag === "a") role = n.getAttribute("href") != null ? "link" : null;
2837
+ else role = tagRoles[tag] ?? null;
2838
+ }
2839
+ roleMemo.set(n, role);
2840
+ return role;
2841
+ };
2842
+ const levelOf = (n) => {
2843
+ const m = /^h([1-6])$/.exec((n.tagName || "").toLowerCase());
2844
+ if (m) return Number(m[1]);
2845
+ const al = n.getAttribute("aria-level");
2846
+ return al && /^\d+$/.test(al) ? Number(al) : null;
2847
+ };
2848
+ const targetRole = roleOf(el);
2849
+ const targetLevel = targetRole === "heading" ? levelOf(el) : null;
2850
+ const nameOf = (n) => {
2851
+ const al = n.getAttribute("aria-label");
2852
+ if (al) return al;
2853
+ const txt = (n.textContent || "").replace(/\s+/g, " ").trim();
2854
+ if (txt) return txt;
2855
+ return n.getAttribute("title") || n.getAttribute("placeholder") || null;
2856
+ };
2857
+ const targetName = nameOf(el);
2858
+ const targetText = (el.textContent || "").replace(/\s+/g, " ").trim();
2859
+ const textNeedle = targetText ? targetText.toLowerCase() : null;
2860
+ const normText = (n) => {
2861
+ const cached = textMemo.get(n);
2862
+ if (cached !== void 0) return cached;
2863
+ const text = (n.textContent || "").replace(/\s+/g, " ").trim().toLowerCase();
2864
+ textMemo.set(n, text);
2865
+ return text;
2866
+ };
2867
+ const TEXT_COUNT_CAP = 2;
2868
+ const countTextOwners = (root, cap) => {
2869
+ if (!textNeedle) return -1;
2870
+ const els = root.querySelectorAll("*");
2871
+ if (els.length > cap) return -1;
2872
+ let total = 0;
2873
+ for (let i = 0; i < els.length; i++) {
2874
+ const n = els[i];
2875
+ if (normText(n).indexOf(textNeedle) === -1) continue;
2876
+ let deeper = false;
2877
+ const kids = n.children;
2878
+ for (let j = 0; j < kids.length; j++) {
2879
+ if (normText(kids[j]).indexOf(textNeedle) !== -1) {
2880
+ deeper = true;
2881
+ break;
2882
+ }
2883
+ }
2884
+ if (!deeper) total++;
2885
+ if (total >= TEXT_COUNT_CAP) return total;
2886
+ }
2887
+ return total;
2888
+ };
2889
+ const nodes = doc.querySelectorAll(roleSources);
2890
+ const nodesUsable = nodes.length <= 4e3;
2891
+ const rolesUsable = !!targetRole && nodesUsable;
2892
+ if (rolesUsable) {
2893
+ let roleCountAll = 0;
2894
+ let index = -1;
2895
+ let levelCount = 0;
2896
+ let roleNameCount = 0;
2897
+ for (let i = 0; i < nodes.length; i++) {
2898
+ const n = nodes[i];
2899
+ if (roleOf(n) !== targetRole) continue;
2900
+ if (n === el) index = roleCountAll;
2901
+ roleCountAll++;
2902
+ if (targetLevel != null && levelOf(n) === targetLevel) levelCount++;
2903
+ if (targetName != null && nameOf(n) === targetName) roleNameCount++;
2904
+ }
2905
+ if (targetName != null) selectorCounts.roleName = roleNameCount;
2906
+ if (index !== -1) {
2907
+ rolePosition = {
2908
+ role: targetRole,
2909
+ count: roleCountAll,
2910
+ index,
2911
+ ...targetLevel != null ? { levelCount } : {}
2912
+ };
2913
+ }
2914
+ }
2915
+ if (textNeedle) {
2916
+ const textCount = countTextOwners(doc.body || doc.documentElement, 4e3);
2917
+ if (textCount >= 0) selectorCounts.text = textCount;
2918
+ }
2919
+ if (rolesUsable || textNeedle) {
2920
+ const CONTAINER_TAGS = ["form", "nav", "main", "article", "section", "dialog", "table", "li", "tr"];
2921
+ const NOISY_DATA_ATTR = /^data-(v-[0-9a-f]+|reactid|react-checksum|svelte-\w+|ng-\w+|ember\w*)$/i;
2922
+ const POSITIONAL_DATA_ATTR = /^data-(index|idx|i|key|row|rownum|col|column|position|pos|order|sort|offset|page)$/i;
2923
+ const TEST_DATA_ATTRS2 = ["data-test", "data-test-id", "data-qa", "data-qa-id", "data-cy", "data-e2e"];
2924
+ const usableDataAttr = (name, value) => {
2925
+ if (!name || name.slice(0, 5) !== "data-" || name === "data-testid") return false;
2926
+ if (NOISY_DATA_ATTR.test(name) || POSITIONAL_DATA_ATTR.test(name)) return false;
2927
+ return !!value && value.length <= 120;
2928
+ };
2929
+ const stableDataAttr = (n) => {
2930
+ const attrs = n.attributes;
2931
+ if (!attrs) return null;
2932
+ let fallback = null;
2933
+ for (let i = 0; i < attrs.length; i++) {
2934
+ const name = attrs[i].name;
2935
+ const value = attrs[i].value;
2936
+ if (!usableDataAttr(name, value)) continue;
2937
+ if (TEST_DATA_ATTRS2.indexOf(name.toLowerCase()) !== -1) return { name, value };
2938
+ if (!fallback) fallback = { name, value };
2939
+ }
2940
+ return fallback;
2941
+ };
2942
+ const docRoleCount = (role) => {
2943
+ let c = 0;
2944
+ for (let i = 0; i < nodes.length; i++) if (roleOf(nodes[i]) === role) c++;
2945
+ return c;
2946
+ };
2947
+ const rawText = (n) => (n.textContent || "").replace(/\s+/g, " ").trim();
2948
+ const namesRatherThanReports = (t) => {
2949
+ const letters = t.replace(/[^A-Za-z]/g, "").length;
2950
+ if (letters < 2) return false;
2951
+ const digits = t.replace(/[^0-9]/g, "").length;
2952
+ return digits <= letters;
2953
+ };
2954
+ const usableDiscriminator = (t) => !!t && t.length <= 60 && t !== targetText && namesRatherThanReports(t);
2955
+ const discriminatingText = (anc) => {
2956
+ const heading = anc.querySelector('h1,h2,h3,h4,h5,h6,[role="heading"]');
2957
+ if (heading) {
2958
+ const t = rawText(heading);
2959
+ if (usableDiscriminator(t)) return t;
2960
+ }
2961
+ const els = anc.querySelectorAll("*");
2962
+ if (els.length > 200) return null;
2963
+ for (let i = 0; i < els.length; i++) {
2964
+ const n = els[i];
2965
+ if (n === el || n.children.length > 0) continue;
2966
+ const t = rawText(n);
2967
+ if (!usableDiscriminator(t)) continue;
2968
+ return t;
2969
+ }
2970
+ return null;
2971
+ };
2972
+ const filterMatchCount = (role, text) => {
2973
+ const needle = text.toLowerCase();
2974
+ let c = 0;
2975
+ for (let i = 0; i < nodes.length; i++) {
2976
+ if (roleOf(nodes[i]) !== role) continue;
2977
+ if (normText(nodes[i]).indexOf(needle) !== -1) c++;
2978
+ }
2979
+ return c;
2980
+ };
2981
+ let node = el.parentElement;
2982
+ let depth = 0;
2983
+ while (node && depth < 12 && ancestors.length < 4) {
2984
+ depth++;
2985
+ const tag = (node.tagName || "").toLowerCase();
2986
+ if (tag === "body" || tag === "html") break;
2987
+ const testId = node.getAttribute("data-testid");
2988
+ const id = node.getAttribute("id");
2989
+ const explicitRole = node.getAttribute("role");
2990
+ const ariaLabel = node.getAttribute("aria-label");
2991
+ const anchorRole = explicitRole || (CONTAINER_TAGS.includes(tag) ? tagRoles[tag] : null) || null;
2992
+ const dataAttr = stableDataAttr(node);
2993
+ if (testId || id || anchorRole || ariaLabel || dataAttr) {
2994
+ let scopedRoleCount = -1;
2995
+ if (rolesUsable) {
2996
+ const scoped = node.querySelectorAll(roleSources);
2997
+ if (scoped.length <= 2e3) {
2998
+ scopedRoleCount = 0;
2999
+ for (let i = 0; i < scoped.length; i++) {
3000
+ const n = scoped[i];
3001
+ if (roleOf(n) !== targetRole) continue;
3002
+ if (targetLevel != null && levelOf(n) !== targetLevel) continue;
3003
+ scopedRoleCount++;
3004
+ }
3005
+ }
3006
+ }
3007
+ const scopedTextCount = countTextOwners(node, 2e3);
3008
+ let filterText = null;
3009
+ try {
3010
+ if (anchorRole && nodesUsable) filterText = discriminatingText(node);
3011
+ } catch {
3012
+ filterText = null;
3013
+ }
3014
+ ancestors.push({
3015
+ tag,
3016
+ depth,
3017
+ testId: testId || null,
3018
+ id: id || null,
3019
+ role: explicitRole || null,
3020
+ ariaLabel: ariaLabel || null,
3021
+ ...scopedRoleCount >= 0 ? { scopedRoleCount } : {},
3022
+ ...scopedTextCount >= 0 ? { scopedTextCount } : {},
3023
+ ...testId ? { testIdCount: count(`[data-testid=${JSON.stringify(testId)}]`) } : {},
3024
+ ...id ? { idCount: count(`#${cssEsc(id)}`) } : {},
3025
+ ...anchorRole && nodesUsable ? { roleCount: docRoleCount(anchorRole) } : {},
3026
+ ...filterText ? { filterText, filterRoleCount: filterMatchCount(anchorRole, filterText) } : {},
3027
+ ...dataAttr ? { dataAttr, dataAttrCount: count(`[${dataAttr.name}=${JSON.stringify(dataAttr.value)}]`) } : {}
3028
+ });
3029
+ }
3030
+ node = node.parentElement;
3031
+ }
3032
+ }
3033
+ } catch {
3034
+ }
2834
3035
  }
2835
- return null;
3036
+ const hasLabel = !!(el.labels && el.labels.length > 0);
3037
+ const labelText = includeLabelText ? hasLabel ? (el.labels[0].textContent || "").replace(/\s+/g, " ").trim().slice(0, 120) || null : null : void 0;
3038
+ return {
3039
+ tagName: el.tagName?.toLowerCase?.() ?? "unknown",
3040
+ attributes: attrMap,
3041
+ // Collapse whitespace so multi-line text can't produce a getByText
3042
+ // suggestion with literal newlines in it.
3043
+ textContent: (el.textContent || "").replace(/\s+/g, " ").trim().slice(0, 80),
3044
+ center: {
3045
+ x: Math.round(r.x + r.width / 2),
3046
+ y: Math.round(r.y + r.height / 2)
3047
+ },
3048
+ hasLabel,
3049
+ ...includeLabelText ? { labelText } : {},
3050
+ selectorCounts,
3051
+ ...includeStructural ? { rolePosition, ancestors } : {}
3052
+ };
2836
3053
  }
2837
3054
 
2838
- // ../packages/core/src/locator-methods.ts
2839
- var LOCATOR_BUILDER_METHODS = [
2840
- "getByRole",
2841
- "getByTestId",
2842
- "getByText",
2843
- "getByLabel",
2844
- "getByPlaceholder",
2845
- "getByAltText",
2846
- "getByTitle",
2847
- "locator"
2848
- ];
2849
-
2850
- // ../packages/core/src/locator-generation.ts
2851
- var TAG_TO_ROLE = {
2852
- a: "link",
2853
- button: "button",
2854
- nav: "navigation",
2855
- main: "main",
2856
- article: "article",
2857
- section: "region",
2858
- form: "form",
2859
- img: "img",
2860
- figure: "figure",
2861
- figcaption: "caption",
2862
- blockquote: "blockquote",
2863
- table: "table",
2864
- ul: "list",
2865
- ol: "list",
2866
- li: "listitem",
2867
- dialog: "dialog",
2868
- output: "status",
2869
- progress: "progressbar",
2870
- meter: "meter",
2871
- textarea: "textbox",
2872
- h1: "heading",
2873
- h2: "heading",
2874
- h3: "heading",
2875
- h4: "heading",
2876
- h5: "heading",
2877
- h6: "heading",
2878
- details: "group",
2879
- summary: "button",
2880
- search: "search"
2881
- };
2882
- var INPUT_TYPE_TO_ROLE = {
2883
- button: "button",
2884
- submit: "button",
2885
- reset: "button",
2886
- image: "button",
2887
- checkbox: "checkbox",
2888
- radio: "radio",
2889
- range: "slider",
2890
- search: "searchbox",
2891
- number: "spinbutton",
2892
- text: "textbox",
2893
- email: "textbox",
2894
- tel: "textbox",
2895
- url: "textbox",
2896
- password: "textbox"
2897
- };
2898
- var CAPTURED_ATTRIBUTES = [
2899
- "id",
2900
- "class",
2901
- "name",
2902
- "data-testid",
2903
- "placeholder",
2904
- "alt",
2905
- "title",
2906
- "aria-label",
2907
- "aria-level",
2908
- "role",
2909
- "type",
2910
- "href",
2911
- "multiple"
2912
- ];
2913
- function resolveAriaRole(attrs) {
2914
- const explicit = attrs.attributes["role"];
2915
- if (explicit) return explicit;
2916
- const tag = attrs.tagName;
2917
- if (!tag) return null;
2918
- if (tag === "input") {
2919
- const type = (attrs.attributes["type"] ?? "text").toLowerCase();
2920
- return INPUT_TYPE_TO_ROLE[type] ?? "textbox";
2921
- }
2922
- if (tag === "select") {
2923
- return attrs.attributes["multiple"] != null ? "listbox" : "combobox";
2924
- }
2925
- if (tag === "a") {
2926
- return attrs.attributes["href"] != null ? "link" : null;
3055
+ // ../packages/picker-dom/src/overlay-element.ts
3056
+ function installPickerOverlay(arg) {
3057
+ const g = globalThis;
3058
+ const doc = g.document;
3059
+ if (!doc || !doc.body) {
3060
+ if (arg.transport === "postMessage") g.parent.postMessage({ type: "pickerClosed" }, "*");
3061
+ else g.__piwiPickState = "skipped";
3062
+ return;
2927
3063
  }
2928
- return TAG_TO_ROLE[tag] ?? null;
2929
- }
2930
- function headingLevel(attrs, role) {
2931
- if (role !== "heading") return null;
2932
- const tagMatch = attrs.tagName.match(/^h([1-6])$/);
2933
- if (tagMatch) return Number(tagMatch[1]);
2934
- const ariaLevel = attrs.attributes["aria-level"];
2935
- if (ariaLevel && /^\d+$/.test(ariaLevel)) return Number(ariaLevel);
2936
- return null;
2937
- }
2938
- var attr = (a, key) => a.attributes[key] || null;
2939
- var esc = (s) => s.replace(/\\/g, "\\\\").replace(/'/g, "\\'");
2940
- var escCssAttrValue = (s) => s.replace(/\\/g, "\\\\").replace(/"/g, '\\"');
2941
- var isCssSafeId = (id) => /^[A-Za-z][A-Za-z0-9_-]*$/.test(id);
2942
- function classifyCssStability(className) {
2943
- if (/[a-f0-9]{8,}/i.test(className)) return 10;
2944
- if (/^(?:css|sc|emotion|styled)-/i.test(className)) return 15;
2945
- 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(
2946
- className
2947
- ))
2948
- return 25;
2949
- if (/__/.test(className) || /--/.test(className)) return 35;
2950
- if (/^[a-z]+(-[a-z]+)+$/.test(className)) return 40;
2951
- if (/^[a-z]+[A-Z][a-zA-Z]+$/.test(className)) return 40;
2952
- if (className.includes("_")) return 15;
2953
- if (/^[a-z]+-[a-z0-9]{5,}$/.test(className) && /[0-9]/.test(className)) return 15;
2954
- return 15;
2955
- }
2956
- function isAutoGenerated(value) {
2957
- if (/^[a-f0-9]{8}-([a-f0-9]{4}-){3}[a-f0-9]{12}$/i.test(value)) return true;
2958
- if (/^[a-f0-9]{8,}$/i.test(value)) return true;
2959
- if (/^[a-z]+-\d+$/.test(value)) return true;
2960
- if (/^(emotion-|styled-|css-|sc-)/.test(value)) return true;
2961
- if (value.startsWith("ng-")) return true;
2962
- if (/^(radix-|headlessui-|mui-|mantine-|chakra-)/i.test(value)) return true;
2963
- if (/^:r[0-9a-z]+:$/i.test(value) || /^«r[0-9a-z]+»$/i.test(value)) return true;
2964
- return false;
2965
- }
2966
- function generateAlternatives(attrs) {
2967
- const alts = [];
2968
- const seen = /* @__PURE__ */ new Set();
2969
- const add = (loc) => {
2970
- if (!seen.has(loc.locator)) {
2971
- seen.add(loc.locator);
2972
- alts.push(loc);
3064
+ const Z = 2147483600;
3065
+ const highlight = doc.createElement("div");
3066
+ highlight.id = "__piwi_picker_highlight";
3067
+ 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);`;
3068
+ const banner = doc.createElement("div");
3069
+ banner.id = "__piwi_picker_banner";
3070
+ 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);`;
3071
+ const hlTokens = (expr) => {
3072
+ const escHtml = (s) => s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
3073
+ const re = /('(?:\\.|[^'])*'|"(?:\\.|[^"])*")|([A-Za-z_$][\w$]*)(?=\s*\()|([A-Za-z_$][\w$]*)(?=\s*:)|(true|false|null|\d+)|([{}(),.])/g;
3074
+ let html = "";
3075
+ let last = 0;
3076
+ let m;
3077
+ while ((m = re.exec(expr)) !== null) {
3078
+ if (m.index > last) html += escHtml(expr.slice(last, m.index));
3079
+ const color = m[1] ? "#86efac" : m[2] ? "#d8b4fe" : m[3] ? "#93c5fd" : m[4] ? "#fcd34d" : "#9ca3af";
3080
+ html += `<span style="color:${color}">${escHtml(m[0])}</span>`;
3081
+ last = re.lastIndex;
2973
3082
  }
3083
+ if (last < expr.length) html += escHtml(expr.slice(last));
3084
+ return html;
2974
3085
  };
2975
- const { accessibleName } = attrs;
2976
- const tag = attrs.tagName;
2977
- const role = resolveAriaRole(attrs);
2978
- const counts = attrs.selectorCounts;
2979
- const isUnique = (n) => n == null || n <= 1;
2980
- const text = attrs.textContent ? attrs.textContent.replace(/\s+/g, " ").trim() : null;
2981
- const testId = attr(attrs, "data-testid");
2982
- if (testId && isUnique(counts?.testId)) {
2983
- add({
2984
- locator: `getByTestId('${esc(testId)}')`,
2985
- method: "getByTestId",
2986
- args: { testId },
2987
- score: 100
2988
- });
2989
- }
2990
- const level = headingLevel(attrs, role);
2991
- const levelPart = level != null ? `, level: ${level}` : "";
2992
- const withLevel = (base) => level != null ? { ...base, level } : base;
2993
- if (role && accessibleName) {
2994
- add({
2995
- locator: `getByRole('${role}', { name: '${esc(accessibleName)}'${levelPart} })`,
2996
- method: "getByRole",
2997
- args: withLevel({ role, name: accessibleName }),
2998
- score: 90
2999
- });
3000
- }
3001
- const ariaLabel = attr(attrs, "aria-label");
3002
- if (role && ariaLabel && ariaLabel !== accessibleName) {
3003
- add({
3004
- locator: `getByRole('${role}', { name: '${esc(ariaLabel)}'${levelPart} })`,
3005
- method: "getByRole",
3006
- args: withLevel({ role, name: ariaLabel }),
3007
- score: 85
3008
- });
3009
- }
3010
- if (accessibleName && ["input", "select", "textarea"].includes(tag)) {
3011
- const label = attr(attrs, "aria-label");
3012
- const labelBacked = attrs.hasLabel === void 0 ? true : attrs.hasLabel === true || label === accessibleName;
3013
- if (labelBacked) {
3014
- add({
3015
- locator: `getByLabel('${esc(accessibleName)}')`,
3016
- method: "getByLabel",
3017
- args: { label: accessibleName },
3018
- score: 85
3019
- });
3020
- }
3021
- }
3022
- const placeholder = attr(attrs, "placeholder");
3023
- if (placeholder) {
3024
- add({
3025
- locator: `getByPlaceholder('${esc(placeholder)}')`,
3026
- method: "getByPlaceholder",
3027
- args: { placeholder },
3028
- score: 80
3029
- });
3030
- }
3031
- if (text && text.length < 80) {
3032
- add({
3033
- locator: `getByText('${esc(text)}')`,
3034
- method: "getByText",
3035
- args: { text },
3036
- score: 75
3037
- });
3038
- }
3039
- const id = attr(attrs, "id");
3040
- if (id && !isAutoGenerated(id) && isUnique(counts?.id)) {
3041
- const selector = isCssSafeId(id) ? `#${id}` : `[id="${escCssAttrValue(id)}"]`;
3042
- add({
3043
- locator: `locator('${esc(selector)}')`,
3044
- method: "locator",
3045
- args: { selector },
3046
- score: 65
3047
- });
3048
- }
3049
- const name = attr(attrs, "name");
3050
- if (name && isUnique(counts?.name)) {
3051
- const selector = `[name="${escCssAttrValue(name)}"]`;
3052
- add({
3053
- locator: `locator('${esc(selector)}')`,
3054
- method: "locator",
3055
- args: { selector },
3056
- score: 60
3057
- });
3058
- }
3059
- const alt = attr(attrs, "alt");
3060
- if (alt) {
3061
- add({
3062
- locator: `getByAltText('${esc(alt)}')`,
3063
- method: "getByAltText",
3064
- args: { text: alt },
3065
- score: 60
3066
- });
3067
- }
3068
- const title = attr(attrs, "title");
3069
- if (title) {
3070
- add({
3071
- locator: `getByTitle('${esc(title)}')`,
3072
- method: "getByTitle",
3073
- args: { title },
3074
- score: 50
3075
- });
3076
- }
3077
- const hasOwnTestId = !!(testId && isUnique(counts?.testId));
3078
- if (role && !hasOwnTestId) {
3079
- const rolePart = level != null ? `'${role}', { level: ${level} }` : `'${role}'`;
3080
- const leafArgs = withLevel({ role });
3081
- let testIdAnchorDone = false;
3082
- let idAnchorDone = false;
3083
- let roleAnchorDone = false;
3084
- for (const anc of attrs.ancestors ?? []) {
3085
- if (anc.scopedRoleCount !== 1) continue;
3086
- if (!testIdAnchorDone && anc.testId && anc.testIdCount === 1) {
3087
- testIdAnchorDone = true;
3088
- add({
3089
- locator: `getByTestId('${esc(anc.testId)}').getByRole(${rolePart})`,
3090
- method: "getByRole",
3091
- args: { ...leafArgs, anchorTestId: anc.testId },
3092
- score: 72
3093
- });
3094
- }
3095
- if (!idAnchorDone && anc.id && !isAutoGenerated(anc.id) && anc.idCount === 1) {
3096
- idAnchorDone = true;
3097
- const anchorSelector = isCssSafeId(anc.id) ? `#${anc.id}` : `[id="${escCssAttrValue(anc.id)}"]`;
3098
- add({
3099
- locator: `locator('${esc(anchorSelector)}').getByRole(${rolePart})`,
3100
- method: "getByRole",
3101
- args: { ...leafArgs, anchorSelector },
3102
- score: 64
3103
- });
3104
- }
3105
- const ancestorRole = anc.role || TAG_TO_ROLE[anc.tag] || null;
3106
- if (!roleAnchorDone && ancestorRole && ancestorRole !== role && anc.roleCount === 1) {
3107
- roleAnchorDone = true;
3108
- add({
3109
- locator: `getByRole('${esc(ancestorRole)}').getByRole(${rolePart})`,
3110
- method: "getByRole",
3111
- args: { ...leafArgs, anchorRole: ancestorRole },
3112
- score: 55
3113
- });
3114
- }
3086
+ const MONO = "ui-monospace,SFMono-Regular,Menlo,Consolas,monospace";
3087
+ const hlLocator = (expr) => `<code style="font-family:${MONO}">${hlTokens(expr)}</code>`;
3088
+ const head = doc.createElement("div");
3089
+ head.innerHTML = arg.transport === "postMessage" ? "Click an element to generate locators" : arg.failing ? `Piwi locator picker \u2014 click the element that should replace ${hlLocator(arg.failing)}` : "Piwi inspector \u2014 click any element to generate locators for it";
3090
+ const locatorLine = doc.createElement("div");
3091
+ locatorLine.id = "__piwi_picker_locator";
3092
+ 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;`;
3093
+ const foot = doc.createElement("div");
3094
+ foot.id = "__piwi_picker_foot";
3095
+ foot.style.cssText = "color:#9ca3af;margin-top:6px;font-size:12px;";
3096
+ foot.textContent = "\u2191 parent \xB7 \u2193 child \xB7 Esc skip";
3097
+ banner.appendChild(head);
3098
+ banner.appendChild(locatorLine);
3099
+ banner.appendChild(foot);
3100
+ const label = doc.createElement("div");
3101
+ label.id = "__piwi_picker_label";
3102
+ 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);`;
3103
+ doc.body.appendChild(highlight);
3104
+ doc.body.appendChild(label);
3105
+ doc.body.appendChild(banner);
3106
+ const escJs = (s) => s.replace(/\\/g, "\\\\").replace(/'/g, "\\'");
3107
+ const describe = (el) => {
3108
+ const tag = (el.tagName || "?").toLowerCase();
3109
+ const testId = el.getAttribute && el.getAttribute("data-testid");
3110
+ if (testId) return `getByTestId('${escJs(testId)}')`;
3111
+ if (el.labels && el.labels.length > 0) {
3112
+ const labelText = (el.labels[0].textContent || "").replace(/\s+/g, " ").trim().slice(0, 80);
3113
+ if (labelText) return `getByLabel('${escJs(labelText)}')`;
3115
3114
  }
3116
- const pos = attrs.rolePosition;
3117
- if (pos && pos.role === role && (pos.count === 1 || level != null && pos.levelCount === 1)) {
3118
- add({
3119
- locator: `getByRole(${rolePart})`,
3120
- method: "getByRole",
3121
- args: leafArgs,
3122
- score: 58
3123
- });
3115
+ const ariaLabel = el.getAttribute && el.getAttribute("aria-label");
3116
+ if (ariaLabel) return `getByLabel('${escJs(ariaLabel)}')`;
3117
+ const placeholder = el.getAttribute && el.getAttribute("placeholder");
3118
+ if (placeholder) return `getByPlaceholder('${escJs(placeholder)}')`;
3119
+ const alt = el.getAttribute && el.getAttribute("alt");
3120
+ if (alt) return `getByAltText('${escJs(alt)}')`;
3121
+ const titleAttr = el.getAttribute && el.getAttribute("title");
3122
+ if (titleAttr) return `getByTitle('${escJs(titleAttr)}')`;
3123
+ if (el.id) return `locator('#${escJs(el.id)}')`;
3124
+ const cls = (el.getAttribute && el.getAttribute("class") || "").split(/\s+/).find((c) => c.length > 1);
3125
+ return cls ? `locator('.${escJs(cls)}')` : tag;
3126
+ };
3127
+ const buildChain = (raw) => {
3128
+ const chain2 = [];
3129
+ let node = raw;
3130
+ while (node && chain2.length < 15) {
3131
+ const tag = (node.tagName || "").toLowerCase();
3132
+ if (tag === "body" || tag === "html") break;
3133
+ chain2.push(node);
3134
+ node = node.parentElement;
3124
3135
  }
3125
- }
3126
- const clsStr = attr(attrs, "class");
3127
- if (clsStr) {
3128
- const countsClasses = counts?.classes;
3129
- 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);
3130
- for (const { cls, score } of classes) {
3131
- add({
3132
- locator: `locator('.${esc(cls)}')`,
3133
- method: "locator",
3134
- args: { selector: `.${cls}` },
3135
- score
3136
- });
3136
+ return chain2.length ? chain2 : [raw];
3137
+ };
3138
+ const ACTIONABLE_TAGS = ["button", "a", "input", "select", "textarea", "summary", "option"];
3139
+ const snapIndex = (chain2) => {
3140
+ for (let i = 0; i < Math.min(chain2.length, 4); i++) {
3141
+ const el = chain2[i];
3142
+ const tag = (el.tagName || "").toLowerCase();
3143
+ if (ACTIONABLE_TAGS.includes(tag)) return i;
3144
+ if (el.getAttribute && (el.getAttribute("role") || el.getAttribute("data-testid"))) return i;
3137
3145
  }
3138
- }
3139
- return alts.sort((a, b) => b.score - a.score);
3140
- }
3141
- function approximateAccessibleName(attrs) {
3142
- const a = attrs.attributes;
3143
- const ariaLabel = a["aria-label"];
3144
- if (ariaLabel) return ariaLabel;
3145
- if (attrs.textContent) return attrs.textContent;
3146
- const title = a["title"];
3147
- if (title) return title;
3148
- const placeholder = a["placeholder"];
3149
- if (placeholder) return placeholder;
3150
- return null;
3151
- }
3152
-
3153
- // src/internal/capture/locator-healing.ts
3154
- function dedupeSnapshotsByLocation(snaps) {
3155
- const lastWithElement = /* @__PURE__ */ new Map();
3156
- const lastAny = /* @__PURE__ */ new Map();
3157
- snaps.forEach((s, i) => {
3158
- if (!s.location) return;
3159
- lastAny.set(s.location, i);
3160
- if (s.element) lastWithElement.set(s.location, i);
3161
- });
3162
- return snaps.filter((s, i) => {
3163
- if (!s.location) return true;
3164
- return (lastWithElement.get(s.location) ?? lastAny.get(s.location)) === i;
3165
- });
3166
- }
3167
- var LOCATOR_METHODS = [...LOCATOR_BUILDER_METHODS];
3168
- var CHAIN_METHODS = [
3169
- "first",
3170
- "nth",
3171
- "last",
3172
- "filter",
3173
- "and",
3174
- "or",
3175
- "locator",
3176
- "getByRole",
3177
- "getByTestId",
3178
- "getByText",
3179
- "getByLabel",
3180
- "getByPlaceholder",
3181
- "getByAltText",
3182
- "getByTitle"
3183
- ];
3184
- var ACTION_METHODS = [
3185
- "click",
3186
- "fill",
3187
- "check",
3188
- "uncheck",
3189
- "selectOption",
3190
- "dblclick",
3191
- "tap",
3192
- "hover",
3193
- "press",
3194
- "type",
3195
- "pressSequentially",
3196
- "clear",
3197
- "setInputFiles",
3198
- "dragTo",
3199
- "focus",
3200
- "blur",
3201
- "scrollIntoViewIfNeeded",
3202
- "dispatchEvent",
3203
- "selectText",
3204
- // Not an action, but a successful waitFor proves the element resolved — the
3205
- // closest capture hook available for assertion-style usage of a locator.
3206
- "waitFor"
3207
- ];
3208
- var LOCATOR_CREATING_CHAINS = new Set(LOCATOR_METHODS);
3209
- var EXPECT_METHOD = "_expect";
3210
- var EXPECT_CAPTURE_EXPRESSIONS = /* @__PURE__ */ new Set([
3211
- "to.be.attached",
3212
- "to.be.checked",
3213
- "to.be.disabled",
3214
- "to.be.editable",
3215
- "to.be.empty",
3216
- "to.be.enabled",
3217
- "to.be.focused",
3218
- "to.be.in.viewport",
3219
- "to.be.readonly",
3220
- "to.be.visible",
3221
- "to.contain.class",
3222
- "to.contain.text",
3223
- "to.have.accessible.description",
3224
- "to.have.accessible.error.message",
3225
- "to.have.accessible.name",
3226
- "to.have.attribute",
3227
- "to.have.attribute.value",
3228
- "to.have.class",
3229
- "to.have.css",
3230
- "to.have.id",
3231
- "to.have.js.property",
3232
- "to.have.role",
3233
- "to.have.text",
3234
- "to.have.value",
3235
- "to.match.aria"
3236
- ]);
3237
- function extractAccessibleName(ariaSnapshot) {
3238
- if (!ariaSnapshot) return null;
3239
- const match = ariaSnapshot.match(/- \w+ "([^"]+)"/);
3240
- if (match) return match[1];
3241
- return null;
3242
- }
3243
- var NAME_BASED_METHODS = /* @__PURE__ */ new Set([
3244
- "getByText",
3245
- "getByRole",
3246
- "getByLabel",
3247
- "getByPlaceholder",
3248
- "getByTitle",
3249
- "getByAltText"
3250
- ]);
3251
- var escAttr = (s) => s.replaceAll("\\", "\\\\").replaceAll("'", "\\'");
3252
- var SUGG_TEXT_ROLES = /* @__PURE__ */ new Set([
3253
- "button",
3254
- "link",
3255
- "heading",
3256
- "menuitem",
3257
- "tab",
3258
- "option",
3259
- "cell",
3260
- "columnheader",
3261
- "rowheader",
3262
- "gridcell",
3263
- "treeitem",
3264
- "listitem",
3265
- "checkbox",
3266
- "radio",
3267
- "switch"
3268
- ]);
3269
- var SUGG_FIELD_ROLES = /* @__PURE__ */ new Set(["textbox", "combobox", "searchbox", "spinbutton", "slider"]);
3270
- function failedNameAndRole(failed) {
3271
- if (failed.method === "getByRole") {
3272
- const role = typeof failed.args[0] === "string" ? failed.args[0] : null;
3273
- const opts = failed.args[1];
3274
- const name = opts && typeof opts.name === "string" ? opts.name : null;
3275
- const level = opts && typeof opts.level === "number" ? opts.level : null;
3276
- return { role, name, level };
3277
- }
3278
- const first = failed.args.find((a) => typeof a === "string");
3279
- return { role: null, name: typeof first === "string" ? first : null, level: null };
3280
- }
3281
- function renderFailing(failed) {
3282
- const { role, name } = failedNameAndRole(failed);
3283
- if (failed.method === "getByRole") {
3284
- return name ? `getByRole('${escAttr(role ?? "")}', { name: '${escAttr(name)}' })` : `getByRole('${escAttr(role ?? "")}')`;
3285
- }
3286
- return `${failed.method}('${escAttr(name ?? "")}')`;
3287
- }
3288
- function freshSuggestions(candidate, failedMethod) {
3289
- const out = [];
3290
- const role = candidate.role;
3291
- const name = candidate.name;
3292
- const push = (s) => {
3293
- if (!out.includes(s)) out.push(s);
3146
+ return 0;
3294
3147
  };
3295
- const levelPart = candidate.level != null ? `, level: ${candidate.level}` : "";
3296
- const roleLoc = `getByRole('${escAttr(role)}', { name: '${escAttr(name)}'${levelPart} })`;
3297
- const textLoc = `getByText('${escAttr(name)}')`;
3298
- const labelLoc = `getByLabel('${escAttr(name)}')`;
3299
- if (failedMethod === "getByText" && SUGG_TEXT_ROLES.has(role)) push(textLoc);
3300
- if (failedMethod === "getByLabel" && SUGG_FIELD_ROLES.has(role)) push(labelLoc);
3301
- push(roleLoc);
3302
- if (SUGG_TEXT_ROLES.has(role)) push(textLoc);
3303
- else if (SUGG_FIELD_ROLES.has(role)) push(labelLoc);
3304
- return out;
3305
- }
3306
- function suggestLocatorsFromAria(failed, ariaSnapshot) {
3307
- if (!ariaSnapshot || !NAME_BASED_METHODS.has(failed.method)) return null;
3308
- const { role, name, level } = failedNameAndRole(failed);
3309
- if (!name) return null;
3310
- const candidates = parseAriaCandidates(ariaSnapshot);
3311
- if (candidates.length === 0) return null;
3312
- const fingerprint = { role, name, level };
3313
- if (fingerprintPresent(fingerprint, candidates)) return null;
3314
- const best = matchRenamedElement(fingerprint, candidates)?.candidate;
3315
- if (!best || !best.name) return null;
3316
- const suggestions = freshSuggestions({ role: best.role, name: best.name, level: best.level }, failed.method);
3317
- if (suggestions.length === 0) return null;
3318
- return { failing: renderFailing(failed), suggestions };
3319
- }
3320
- function captureCallerLocation(stack = new Error().stack ?? "") {
3321
- const lines = stack.split("\n");
3322
- let prevWasCaptureModule = false;
3323
- let selfFile = null;
3324
- for (let i = 1; i < lines.length; i++) {
3325
- const line = lines[i].trim();
3326
- if (!line.startsWith("at")) continue;
3327
- const m = line.match(/^at\s+(?:(.+?)\s+\()?(.+?):(\d+):(\d+)\)?$/);
3328
- if (!m) {
3329
- prevWasCaptureModule = false;
3330
- continue;
3148
+ const locatorOf = (el) => {
3149
+ const hook = g.__piwiDescribeElement;
3150
+ if (typeof hook === "function") {
3151
+ try {
3152
+ const derived = hook(el);
3153
+ if (typeof derived === "string" && derived) return derived;
3154
+ } catch {
3155
+ }
3331
3156
  }
3332
- let file = m[2];
3333
- if (!file || file.startsWith("node:")) {
3334
- prevWasCaptureModule = false;
3335
- continue;
3157
+ return describe(el);
3158
+ };
3159
+ let chain = [];
3160
+ let idx = 0;
3161
+ let lastRaw = null;
3162
+ let labeled = null;
3163
+ const placeLabel = (r) => {
3164
+ label.style.display = "block";
3165
+ const lr = label.getBoundingClientRect();
3166
+ const vw = g.innerWidth || doc.documentElement.clientWidth || 0;
3167
+ const vh = g.innerHeight || doc.documentElement.clientHeight || 0;
3168
+ let top = r.top - lr.height - 6;
3169
+ if (top < 4) top = r.bottom + 6;
3170
+ if (top + lr.height > vh - 4) top = Math.max(4, vh - lr.height - 4);
3171
+ let left = r.left;
3172
+ if (left + lr.width > vw - 6) left = vw - lr.width - 6;
3173
+ if (left < 6) left = 6;
3174
+ label.style.left = left + "px";
3175
+ label.style.top = top + "px";
3176
+ };
3177
+ const current = () => chain[idx] ?? null;
3178
+ const refresh = () => {
3179
+ const el = current();
3180
+ if (!el) {
3181
+ highlight.style.display = "none";
3182
+ label.style.display = "none";
3183
+ return;
3336
3184
  }
3337
- file = file.replace(/^file:\/\/\/?/, "");
3338
- if (!/\.[a-z]+$/i.test(file)) {
3339
- prevWasCaptureModule = false;
3340
- continue;
3185
+ const r = el.getBoundingClientRect();
3186
+ highlight.style.display = "block";
3187
+ highlight.style.left = r.left + "px";
3188
+ highlight.style.top = r.top + "px";
3189
+ highlight.style.width = r.width + "px";
3190
+ highlight.style.height = r.height + "px";
3191
+ if (el !== labeled) {
3192
+ labeled = el;
3193
+ const tag = (el.tagName || "?").toLowerCase();
3194
+ const locatorHtml = hlTokens(locatorOf(el));
3195
+ label.innerHTML = `<span style="color:#c4b5fd">&lt;${tag}&gt;</span> ${locatorHtml}`;
3196
+ locatorLine.innerHTML = locatorHtml;
3197
+ locatorLine.style.display = "block";
3198
+ }
3199
+ placeLabel(r);
3200
+ foot.textContent = "click to pick \xB7 \u2191 parent \xB7 \u2193 child \xB7 Esc skip";
3201
+ };
3202
+ const stop = (e) => {
3203
+ e.preventDefault();
3204
+ e.stopImmediatePropagation();
3205
+ };
3206
+ const isOwn = (el) => el === banner || el === highlight || el === label || banner.contains && banner.contains(el) || !!(el && el.__piwiHint);
3207
+ let bannerDocked = "top";
3208
+ const dockBanner = (side) => {
3209
+ if (bannerDocked === side) return;
3210
+ bannerDocked = side;
3211
+ if (side === "bottom") {
3212
+ banner.style.top = "auto";
3213
+ banner.style.bottom = "12px";
3214
+ } else {
3215
+ banner.style.top = "12px";
3216
+ banner.style.bottom = "auto";
3341
3217
  }
3342
- if (selfFile === null || file === selfFile) {
3343
- selfFile ??= file;
3344
- prevWasCaptureModule = /[\\/]locator-healing\.[a-z]+$/i.test(file);
3345
- continue;
3218
+ };
3219
+ const onMove = (e) => {
3220
+ const raw = e.target;
3221
+ if (!raw || isOwn(raw)) {
3222
+ highlight.style.display = "none";
3223
+ label.style.display = "none";
3224
+ return;
3346
3225
  }
3347
- if (/[\\/]locator-healing\.[a-z]+$/i.test(file)) {
3348
- prevWasCaptureModule = true;
3349
- continue;
3226
+ if (raw !== lastRaw) {
3227
+ lastRaw = raw;
3228
+ chain = buildChain(raw);
3229
+ idx = snapIndex(chain);
3350
3230
  }
3351
- if (prevWasCaptureModule && /[\\/](?:capture-)?fixtures\.[a-z]+$/i.test(file)) {
3352
- prevWasCaptureModule = false;
3353
- continue;
3231
+ refresh();
3232
+ const el = current();
3233
+ if (el) {
3234
+ const r = el.getBoundingClientRect();
3235
+ const br = banner.getBoundingClientRect();
3236
+ const margin = 8;
3237
+ if (r.left < br.right + margin && r.right > br.left - margin && r.top < br.bottom + margin && r.bottom > br.top - margin) {
3238
+ dockBanner(bannerDocked === "top" ? "bottom" : "top");
3239
+ }
3354
3240
  }
3355
- if (/[\\/]node_modules[\\/]/.test(file)) {
3356
- prevWasCaptureModule = false;
3357
- continue;
3241
+ };
3242
+ const suppressed = ["mousedown", "mouseup", "pointerdown", "pointerup", "auxclick", "dblclick"];
3243
+ const removePickingListeners = () => {
3244
+ doc.removeEventListener("mousemove", onMove, true);
3245
+ doc.removeEventListener("click", onClick, true);
3246
+ doc.removeEventListener("keydown", onKey, true);
3247
+ if (arg.transport === "postMessage") g.removeEventListener("message", onParentMsg, false);
3248
+ };
3249
+ const removeSuppressed = () => {
3250
+ for (const t of suppressed) doc.removeEventListener(t, stop, true);
3251
+ };
3252
+ const cleanup = () => {
3253
+ highlight.remove();
3254
+ label.remove();
3255
+ banner.remove();
3256
+ };
3257
+ const reportPicked = (el) => {
3258
+ removePickingListeners();
3259
+ highlight.style.display = "none";
3260
+ label.style.display = "none";
3261
+ if (arg.transport === "postMessage") {
3262
+ const probeFn = g.__piwiProbe;
3263
+ const attrs = typeof probeFn === "function" ? probeFn(el, arg.probeArg) : null;
3264
+ g.__piwiSnapshotExtras?.onPick?.();
3265
+ doc.addEventListener("click", stop, true);
3266
+ doc.addEventListener("keydown", stop, true);
3267
+ foot.textContent = "Analyzing element\u2026";
3268
+ g.parent.postMessage({ type: "elementPicked", attrs }, "*");
3269
+ } else {
3270
+ removeSuppressed();
3271
+ g.__piwiPickedElement = el;
3272
+ g.__piwiPickState = "picked";
3273
+ foot.textContent = "Analyzing element\u2026";
3358
3274
  }
3359
- let rel = file;
3360
- try {
3361
- rel = path15.relative(process.cwd(), file);
3362
- } catch {
3275
+ };
3276
+ const reportSkipped = () => {
3277
+ removePickingListeners();
3278
+ if (arg.transport === "postMessage") {
3279
+ doc.removeEventListener("click", stop, true);
3280
+ doc.removeEventListener("keydown", stop, true);
3281
+ removeSuppressed();
3282
+ g.__piwiSnapshotExtras?.onClose?.();
3283
+ cleanup();
3284
+ g.parent.postMessage({ type: "pickerClosed" }, "*");
3285
+ } else {
3286
+ removeSuppressed();
3287
+ g.__piwiPickState = "skipped";
3288
+ cleanup();
3363
3289
  }
3364
- rel = rel.split(path15.sep).join("/");
3365
- if (rel.startsWith("./")) rel = rel.slice(2);
3366
- return `${rel}:${m[3]}:${m[4]}`;
3290
+ };
3291
+ const onClick = (e) => {
3292
+ stop(e);
3293
+ const el = current();
3294
+ if (!el || isOwn(e.target)) return;
3295
+ reportPicked(el);
3296
+ };
3297
+ const onKey = (e) => {
3298
+ if (e.key === "Escape") {
3299
+ stop(e);
3300
+ reportSkipped();
3301
+ return;
3302
+ }
3303
+ if (e.key === "ArrowUp" || e.key === "ArrowDown") {
3304
+ stop(e);
3305
+ if (e.key === "ArrowUp") idx = Math.min(idx + 1, chain.length - 1);
3306
+ else idx = Math.max(idx - 1, 0);
3307
+ refresh();
3308
+ }
3309
+ };
3310
+ const onParentMsg = (e) => {
3311
+ const d = e.data;
3312
+ if (!d || typeof d.type !== "string" || d.type !== "piwiPickerKey" || typeof d.key !== "string") return;
3313
+ onKey({
3314
+ key: d.key,
3315
+ preventDefault() {
3316
+ },
3317
+ stopImmediatePropagation() {
3318
+ }
3319
+ });
3320
+ };
3321
+ g.__piwiPickCleanup = cleanup;
3322
+ doc.addEventListener("mousemove", onMove, true);
3323
+ doc.addEventListener("click", onClick, true);
3324
+ doc.addEventListener("keydown", onKey, true);
3325
+ for (const t of suppressed) doc.addEventListener(t, stop, true);
3326
+ if (arg.transport === "postMessage") {
3327
+ g.addEventListener("message", onParentMsg, false);
3328
+ g.parent.postMessage({ type: "pickerReady" }, "*");
3367
3329
  }
3368
- return null;
3369
3330
  }
3370
3331
 
3371
- // src/internal/capture/inspect-on-failure.ts
3372
- function isCi(ci) {
3373
- return ci !== void 0 && ci !== "" && ci !== "false";
3374
- }
3375
- function shouldInspectOnFailure(gate) {
3376
- if (gate.enabled !== "true") return false;
3377
- if (isCi(gate.ci)) return false;
3378
- if (gate.headless !== false) return false;
3379
- if (gate.status !== "failed" && gate.status !== "timedOut") return false;
3380
- if (gate.status === gate.expectedStatus) return false;
3381
- return gate.retry >= gate.retries;
3382
- }
3383
- function environmentalSkipReason(gate) {
3384
- if (gate.enabled !== "true") return null;
3385
- if (gate.status !== "failed" && gate.status !== "timedOut") return null;
3386
- if (gate.status === gate.expectedStatus) return null;
3387
- if (isCi(gate.ci)) return "running under CI \u2014 this is a headed, local-only feature";
3388
- if (gate.headless !== false) {
3389
- return "the browser is headless \u2014 re-run with --headed (or set use: { headless: false })";
3332
+ // ../packages/picker-dom/src/overlay-anchors.ts
3333
+ function showAnchorPicker(arg) {
3334
+ const g = globalThis;
3335
+ const doc = g.document;
3336
+ const el = g.__piwiPickedElement;
3337
+ if (!doc || !doc.body || !el) {
3338
+ g.__piwiAnchorState = "skipped";
3339
+ return;
3390
3340
  }
3391
- return null;
3392
- }
3393
- function inspectionGateFromTestInfo(testInfo, enabled = process.env.PIWI_INSPECT_ON_FAIL) {
3394
- const use = testInfo.project?.use ?? {};
3395
- return {
3396
- enabled,
3397
- ci: process.env.CI,
3398
- status: testInfo.status,
3399
- expectedStatus: testInfo.expectedStatus,
3400
- headless: use.headless,
3401
- retry: testInfo.retry,
3402
- retries: testInfo.project?.retries ?? 0
3341
+ const Z = 2147483600;
3342
+ const { tagRoles, inputRoles, roleSources, leafRole, leafLevel, leafTestId } = arg;
3343
+ const roleOf = (n) => {
3344
+ const explicit = n.getAttribute && n.getAttribute("role");
3345
+ if (explicit) return explicit;
3346
+ const tag = (n.tagName || "").toLowerCase();
3347
+ if (tag === "input") return inputRoles[(n.getAttribute("type") || "text").toLowerCase()] ?? "textbox";
3348
+ if (tag === "select") return n.getAttribute("multiple") != null ? "listbox" : "combobox";
3349
+ if (tag === "a") return n.getAttribute("href") != null ? "link" : null;
3350
+ return tagRoles[tag] ?? null;
3403
3351
  };
3404
- }
3405
-
3406
- // src/internal/capture/pick-on-failure.ts
3407
- var path16 = __toESM(require("path"));
3408
- var ANSI_RE = /\[[0-9;]*m/g;
3409
- function endOfString(s, start) {
3410
- const q = s[start];
3411
- for (let i = start + 1; i < s.length; i++) {
3412
- if (s[i] === "\\") {
3413
- i++;
3414
- continue;
3352
+ const levelOf = (n) => {
3353
+ const m = /^h([1-6])$/.exec((n.tagName || "").toLowerCase());
3354
+ if (m) return Number(m[1]);
3355
+ const al = n.getAttribute && n.getAttribute("aria-level");
3356
+ return al && /^\d+$/.test(al) ? Number(al) : null;
3357
+ };
3358
+ const leafMatches = (scope) => {
3359
+ try {
3360
+ if (leafTestId) return scope.querySelectorAll(`[data-testid=${JSON.stringify(leafTestId)}]`).length;
3361
+ const nodes = scope.querySelectorAll(roleSources);
3362
+ if (nodes.length > 2e3) return -1;
3363
+ let matched = 0;
3364
+ for (let i = 0; i < nodes.length; i++) {
3365
+ const n = nodes[i];
3366
+ if (roleOf(n) !== leafRole) continue;
3367
+ if (leafLevel != null && levelOf(n) !== leafLevel) continue;
3368
+ matched++;
3369
+ }
3370
+ return matched;
3371
+ } catch {
3372
+ return -1;
3415
3373
  }
3416
- if (s[i] === q) return i;
3417
- }
3418
- return s.length - 1;
3419
- }
3420
- function matchBrace(s, start) {
3421
- let depth = 0;
3422
- for (let i = start; i < s.length; i++) {
3423
- if (s[i] === "{") depth++;
3424
- else if (s[i] === "}" && --depth === 0) return i;
3425
- }
3426
- return s.length - 1;
3427
- }
3428
- function parseOptions(src) {
3429
- const obj = {};
3430
- const re = /(\w+)\s*:\s*('(?:\\.|[^'])*'|"(?:\\.|[^"])*"|true|false|-?\d+)/g;
3431
- let m;
3432
- while ((m = re.exec(src)) !== null) {
3433
- const key = m[1];
3434
- const raw = m[2];
3435
- if (raw === "true") obj[key] = true;
3436
- else if (raw === "false") obj[key] = false;
3437
- else if (/^-?\d+$/.test(raw)) obj[key] = Number(raw);
3438
- else obj[key] = raw.slice(1, -1).replace(/\\(.)/g, "$1");
3374
+ };
3375
+ let roleNodes = [];
3376
+ try {
3377
+ const all = doc.querySelectorAll(roleSources);
3378
+ if (all.length <= 4e3) roleNodes = Array.from(all);
3379
+ } catch {
3380
+ roleNodes = [];
3439
3381
  }
3440
- return obj;
3441
- }
3442
- function parseArgs(inner) {
3443
- const args = [];
3444
- let i = 0;
3445
- while (i < inner.length) {
3446
- const c = inner[i];
3447
- if (c === " " || c === ",") {
3448
- i++;
3449
- continue;
3450
- }
3451
- if (c === "'" || c === '"') {
3452
- const end = endOfString(inner, i);
3453
- args.push(inner.slice(i + 1, end).replace(/\\(.)/g, "$1"));
3454
- i = end + 1;
3455
- continue;
3456
- }
3457
- if (c === "{") {
3458
- const end = matchBrace(inner, i);
3459
- args.push(parseOptions(inner.slice(i, end + 1)));
3460
- i = end + 1;
3461
- continue;
3382
+ const count = (sel) => {
3383
+ try {
3384
+ return doc.querySelectorAll(sel).length;
3385
+ } catch {
3386
+ return void 0;
3462
3387
  }
3463
- i++;
3464
- }
3465
- return args;
3466
- }
3467
- function leafExpression(expr) {
3388
+ };
3389
+ const rows = [];
3390
+ let node = el.parentElement;
3468
3391
  let depth = 0;
3469
- let leafStart = 0;
3470
- for (let i = 0; i < expr.length - 1; i++) {
3471
- const c = expr[i];
3472
- if (c === "'" || c === '"') {
3473
- i = endOfString(expr, i);
3474
- continue;
3475
- }
3476
- if (c === "(") depth++;
3477
- else if (c === ")") {
3478
- depth--;
3479
- if (depth === 0 && expr[i + 1] === ".") leafStart = i + 2;
3392
+ while (node && depth < 12) {
3393
+ depth++;
3394
+ const tag = (node.tagName || "").toLowerCase();
3395
+ if (tag === "body" || tag === "html") break;
3396
+ const testId = node.getAttribute("data-testid");
3397
+ const id = node.getAttribute("id");
3398
+ const ariaLabel = node.getAttribute("aria-label");
3399
+ const role = roleOf(node);
3400
+ const info = { tag, depth, testId: testId || null, id: id || null, ariaLabel: ariaLabel || null, role };
3401
+ if (testId) info.testIdCount = count(`[data-testid=${JSON.stringify(testId)}]`);
3402
+ if (id) {
3403
+ try {
3404
+ info.idCount = count(`#${doc.defaultView.CSS.escape(id)}`);
3405
+ } catch {
3406
+ }
3480
3407
  }
3481
- }
3482
- return expr.slice(leafStart);
3483
- }
3484
- function parseLeafLocatorExpression(rawExpr) {
3485
- const expr = leafExpression(rawExpr.trim());
3486
- const m = /^([A-Za-z]+)\((.*)\)$/s.exec(expr);
3487
- if (!m) return null;
3488
- return { method: m[1], args: parseArgs(m[2].trim()) };
3489
- }
3490
- function deriveFailedLocator(testInfo) {
3491
- const info = testInfo;
3492
- const errors = info.errors && info.errors.length > 0 ? info.errors : info.error ? [info.error] : [];
3493
- for (const err of errors) {
3494
- const text = `${err.message ?? ""}
3495
- ${err.stack ?? ""}`.replace(ANSI_RE, "");
3496
- const line = /^\s*Locator:\s*(.+)$/m.exec(text);
3497
- if (!line) continue;
3498
- const parsed = parseLeafLocatorExpression(line[1].trim());
3499
- if (!parsed) continue;
3500
- const loc = err.location;
3501
- const location = loc ? `${path16.relative(process.cwd(), loc.file).split(path16.sep).join("/")}:${loc.line}:${loc.column}` : null;
3502
- return { method: parsed.method, args: parsed.args, location };
3503
- }
3504
- return null;
3505
- }
3506
- var escStr = (s) => s.replaceAll("\\", "\\\\").replaceAll("'", "\\'");
3507
- var cssIdSelector = (id) => /^[A-Za-z_][A-Za-z0-9_-]*$/.test(id) ? `#${id}` : `[id="${id.replaceAll("\\", "\\\\").replaceAll('"', '\\"')}"]`;
3508
- var ANCHOR_KIND_SCORES = { testid: 80, id: 74, labeledRole: 68, role: 62 };
3509
- function anchorSegment(a) {
3510
- if (a.testId && a.testIdCount === 1) {
3511
- return { code: `getByTestId('${escStr(a.testId)}')`, kind: "testid", flatArgs: { anchorTestId: a.testId } };
3512
- }
3513
- if (a.id && !isAutoGenerated(a.id) && a.idCount === 1) {
3514
- const anchorSelector = cssIdSelector(a.id);
3515
- return { code: `locator('${escStr(anchorSelector)}')`, kind: "id", flatArgs: { anchorSelector } };
3516
- }
3517
- if (a.role && a.ariaLabel && a.labeledRoleCount === 1) {
3518
- return {
3519
- code: `getByRole('${escStr(a.role)}', { name: '${escStr(a.ariaLabel)}' })`,
3520
- kind: "labeledRole",
3521
- flatArgs: { anchorRole: a.role, anchorName: a.ariaLabel }
3522
- };
3523
- }
3524
- if (a.role && a.roleCount === 1) {
3525
- return { code: `getByRole('${escStr(a.role)}')`, kind: "role", flatArgs: { anchorRole: a.role } };
3526
- }
3527
- return null;
3528
- }
3529
- function generateAnchoredAlternatives(leaf, anchors, chainLeafCount) {
3530
- if (!leaf.role || anchors.length === 0) return [];
3531
- const out = [];
3532
- const seen = /* @__PURE__ */ new Set();
3533
- const rolePart = leaf.level != null ? `'${leaf.role}', { level: ${leaf.level} }` : `'${leaf.role}'`;
3534
- const leafArgs = leaf.level != null ? { role: leaf.role, level: leaf.level } : { role: leaf.role };
3535
- const add = (l) => {
3536
- if (!seen.has(l.locator)) {
3537
- seen.add(l.locator);
3538
- out.push(l);
3408
+ if (role) {
3409
+ let roleCount = 0;
3410
+ let labeledCount = 0;
3411
+ for (const n of roleNodes) {
3412
+ if (roleOf(n) !== role) continue;
3413
+ roleCount++;
3414
+ if (ariaLabel && n.getAttribute && n.getAttribute("aria-label") === ariaLabel) labeledCount++;
3415
+ }
3416
+ info.roleCount = roleCount;
3417
+ if (ariaLabel) info.labeledRoleCount = labeledCount;
3539
3418
  }
3540
- };
3541
- for (const anchor of anchors) {
3542
- if (anchor.scopedLeafCount !== 1) continue;
3543
- const seg = anchorSegment(anchor);
3544
- if (!seg) continue;
3545
- add({
3546
- locator: `${seg.code}.getByRole(${rolePart})`,
3547
- method: "getByRole",
3548
- args: { ...leafArgs, ...seg.flatArgs },
3549
- score: ANCHOR_KIND_SCORES[seg.kind]
3419
+ info.scopedLeafCount = leafMatches(node);
3420
+ const hookLabel = testId ? `data-testid="${testId}"` : id ? `#${id}` : ariaLabel && role ? `${role} "${ariaLabel}"` : role ? `role ${role}` : "no stable hook";
3421
+ rows.push({
3422
+ node,
3423
+ info,
3424
+ hookLabel,
3425
+ selectable: !!(testId || id || role && (ariaLabel || info.roleCount === 1))
3550
3426
  });
3427
+ node = node.parentElement;
3551
3428
  }
3552
- if (anchors.length >= 2 && chainLeafCount === 1) {
3553
- const ordered = [...anchors].sort((a, b) => b.depth - a.depth);
3554
- const segments = ordered.map(anchorSegment);
3555
- if (segments.every((s) => s !== null)) {
3556
- const innermost = segments[segments.length - 1];
3557
- const score = Math.min(...segments.map((s) => ANCHOR_KIND_SCORES[s.kind]));
3558
- add({
3559
- locator: `${segments.map((s) => s.code).join(".")}.getByRole(${rolePart})`,
3560
- method: "getByRole",
3561
- // Flat args describe the innermost anchor (what the healing fingerprint
3562
- // logic understands); the full chain rides along for transparency.
3563
- args: { ...leafArgs, ...innermost.flatArgs, anchorChain: segments.map((s) => s.code) },
3564
- score
3565
- });
3566
- }
3567
- }
3568
- return out.sort((a, b) => b.score - a.score);
3569
- }
3570
- function mergeCandidates(base, extra) {
3571
- const seen = new Set(base.map((b) => b.locator));
3572
- const merged = [...base];
3573
- for (const e of extra) {
3574
- if (seen.has(e.locator)) continue;
3575
- seen.add(e.locator);
3576
- merged.push(e);
3577
- }
3578
- return merged.sort((a, b) => b.score - a.score);
3579
- }
3580
- function installPickerOverlay(arg) {
3581
- const g = globalThis;
3582
- const doc = g.document;
3583
- if (!doc || !doc.body) {
3584
- g.__piwiPickState = "skipped";
3429
+ if (rows.length === 0) {
3430
+ g.__piwiAnchorState = "skipped";
3585
3431
  return;
3586
3432
  }
3587
- const Z = 2147483600;
3588
- const highlight = doc.createElement("div");
3589
- highlight.style.cssText = `position:fixed;pointer-events:none;z-index:${Z};display:none;box-sizing:border-box;border:2px solid #7c3aed;background:rgba(124,58,237,.12);border-radius:3px;`;
3590
- const banner = doc.createElement("div");
3591
- 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;padding:10px 16px;border-radius:8px;box-shadow:0 4px 24px rgba(0,0,0,.4);max-width:80vw;`;
3592
- const hlLocator = (expr) => {
3593
- const escHtml = (s) => s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
3594
- const re = /('(?:\\.|[^'])*'|"(?:\\.|[^"])*")|([A-Za-z_$][\w$]*)(?=\s*\()|([A-Za-z_$][\w$]*)(?=\s*:)|(true|false|null|\d+)|([{}(),.])/g;
3595
- let html = "";
3596
- let last = 0;
3597
- let m;
3598
- while ((m = re.exec(expr)) !== null) {
3599
- if (m.index > last) html += escHtml(expr.slice(last, m.index));
3600
- const color = m[1] ? "#4ade80" : m[2] ? "#c084fc" : m[3] ? "#93c5fd" : m[4] ? "#fbbf24" : "#9ca3af";
3601
- html += `<span style="color:${color}">${escHtml(m[0])}</span>`;
3602
- last = re.lastIndex;
3603
- }
3604
- if (last < expr.length) html += escHtml(expr.slice(last));
3605
- return `<code style="font-family:ui-monospace,SFMono-Regular,Menlo,monospace">${html}</code>`;
3606
- };
3607
- const head = doc.createElement("div");
3608
- head.innerHTML = arg.failing ? `Piwi locator picker \u2014 click the element that should replace ${hlLocator(arg.failing)}` : "Piwi inspector \u2014 click any element to generate locators for it";
3609
- const foot = doc.createElement("div");
3610
- foot.style.cssText = "color:#9ca3af;margin-top:3px;";
3611
- foot.textContent = "\u2191 parent \xB7 \u2193 child \xB7 Esc skip";
3612
- banner.appendChild(head);
3613
- banner.appendChild(foot);
3614
- doc.body.appendChild(highlight);
3615
- doc.body.appendChild(banner);
3616
- const escJs = (s) => s.replace(/\\/g, "\\\\").replace(/'/g, "\\'");
3617
- const describe = (el) => {
3618
- const tag = (el.tagName || "?").toLowerCase();
3619
- const testId = el.getAttribute && el.getAttribute("data-testid");
3620
- if (testId) return `getByTestId('${escJs(testId)}')`;
3621
- if (el.labels && el.labels.length > 0) {
3622
- const labelText = (el.labels[0].textContent || "").replace(/\s+/g, " ").trim().slice(0, 80);
3623
- if (labelText) return `getByLabel('${escJs(labelText)}')`;
3433
+ const MONO = "ui-monospace,SFMono-Regular,Menlo,Consolas,monospace";
3434
+ const outline = doc.createElement("div");
3435
+ 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);`;
3436
+ const outlineLabel = doc.createElement("div");
3437
+ 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);`;
3438
+ const pickedOutline = doc.createElement("div");
3439
+ const pr = el.getBoundingClientRect();
3440
+ 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;`;
3441
+ const panel = doc.createElement("div");
3442
+ panel.style.cssText = `position:fixed;top:12px;right:12px;z-index:${Z + 3};width:340px;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);`;
3443
+ const title = doc.createElement("div");
3444
+ title.style.cssText = "font-weight:600;font-size:13px;margin-bottom:2px;";
3445
+ title.textContent = "Scope to stable parents (optional)";
3446
+ const sub = doc.createElement("div");
3447
+ sub.style.cssText = "color:#9ca3af;margin-bottom:10px;";
3448
+ sub.textContent = "Pick one or more parents to anchor the locator to. Hover a row to see the parent.";
3449
+ panel.appendChild(title);
3450
+ panel.appendChild(sub);
3451
+ const selected = /* @__PURE__ */ new Set();
3452
+ const footer = doc.createElement("div");
3453
+ footer.style.cssText = "margin:10px 0;font-weight:600;";
3454
+ const segMatches = (scope, info) => {
3455
+ try {
3456
+ if (info.testId) return Array.from(scope.querySelectorAll(`[data-testid=${JSON.stringify(info.testId)}]`));
3457
+ if (info.id) return Array.from(scope.querySelectorAll(`#${doc.defaultView.CSS.escape(info.id)}`));
3458
+ const nodes = Array.from(scope.querySelectorAll(roleSources));
3459
+ if (nodes.length > 2e3) return [];
3460
+ return nodes.filter(
3461
+ (n) => roleOf(n) === info.role && (!info.ariaLabel || n.getAttribute && n.getAttribute("aria-label") === info.ariaLabel)
3462
+ );
3463
+ } catch {
3464
+ return [];
3624
3465
  }
3625
- const ariaLabel = el.getAttribute && el.getAttribute("aria-label");
3626
- if (ariaLabel) return `getByLabel('${escJs(ariaLabel)}')`;
3627
- const placeholder = el.getAttribute && el.getAttribute("placeholder");
3628
- if (placeholder) return `getByPlaceholder('${escJs(placeholder)}')`;
3629
- const alt = el.getAttribute && el.getAttribute("alt");
3630
- if (alt) return `getByAltText('${escJs(alt)}')`;
3631
- const titleAttr = el.getAttribute && el.getAttribute("title");
3632
- if (titleAttr) return `getByTitle('${escJs(titleAttr)}')`;
3633
- if (el.id) return `locator('#${escJs(el.id)}')`;
3634
- const cls = (el.getAttribute && el.getAttribute("class") || "").split(/\s+/).find((c) => c.length > 1);
3635
- return cls ? `locator('.${escJs(cls)}')` : tag;
3636
3466
  };
3637
- const buildChain = (raw) => {
3638
- const chain2 = [];
3639
- let node = raw;
3640
- while (node && chain2.length < 15) {
3641
- const tag = (node.tagName || "").toLowerCase();
3642
- if (tag === "body" || tag === "html") break;
3643
- chain2.push(node);
3644
- node = node.parentElement;
3467
+ const chainCount = () => {
3468
+ const chosen = rows.filter((_, i) => selected.has(i)).sort((a, b) => b.info.depth - a.info.depth);
3469
+ if (chosen.length === 0) return -1;
3470
+ let scopes = [doc];
3471
+ for (const row of chosen) {
3472
+ const next = [];
3473
+ for (const s of scopes) next.push(...segMatches(s, row.info));
3474
+ scopes = next.slice(0, 200);
3475
+ if (scopes.length === 0) return 0;
3645
3476
  }
3646
- return chain2.length ? chain2 : [raw];
3647
- };
3648
- const ACTIONABLE_TAGS = ["button", "a", "input", "select", "textarea", "summary", "option"];
3649
- const snapIndex = (chain2) => {
3650
- for (let i = 0; i < Math.min(chain2.length, 4); i++) {
3651
- const el = chain2[i];
3652
- const tag = (el.tagName || "").toLowerCase();
3653
- if (ACTIONABLE_TAGS.includes(tag)) return i;
3654
- if (el.getAttribute && (el.getAttribute("role") || el.getAttribute("data-testid"))) return i;
3477
+ let total = 0;
3478
+ for (const s of scopes) {
3479
+ const c = leafMatches(s);
3480
+ if (c > 0) total += c;
3481
+ if (total > 50) return total;
3655
3482
  }
3656
- return 0;
3483
+ return total;
3657
3484
  };
3658
- let chain = [];
3659
- let idx = 0;
3660
- let lastRaw = null;
3661
- const current = () => chain[idx] ?? null;
3662
- const refresh = () => {
3663
- const el = current();
3664
- if (!el) {
3665
- highlight.style.display = "none";
3485
+ const refreshFooter = () => {
3486
+ if (selected.size === 0) {
3487
+ footer.textContent = "No parents selected \u2014 standard alternatives only.";
3488
+ footer.style.color = "#9ca3af";
3489
+ g.__piwiPickChainCount = void 0;
3666
3490
  return;
3667
3491
  }
3668
- const r = el.getBoundingClientRect();
3669
- highlight.style.display = "block";
3670
- highlight.style.left = r.left + "px";
3671
- highlight.style.top = r.top + "px";
3672
- highlight.style.width = r.width + "px";
3673
- highlight.style.height = r.height + "px";
3674
- foot.textContent = `${describe(el)} \u2014 click to pick \xB7 \u2191 parent \xB7 \u2193 child \xB7 Esc skip`;
3675
- };
3676
- const stop = (e) => {
3677
- e.preventDefault();
3678
- e.stopImmediatePropagation();
3492
+ const c = chainCount();
3493
+ g.__piwiPickChainCount = c;
3494
+ if (c === 1) {
3495
+ footer.textContent = "\u2713 Selection matches exactly 1 element";
3496
+ footer.style.color = "#4ade80";
3497
+ } else {
3498
+ footer.textContent = c < 0 ? "Match count unavailable" : `\u2717 Selection matches ${c} elements`;
3499
+ footer.style.color = "#fbbf24";
3500
+ }
3679
3501
  };
3680
- const isOwn = (el) => el === banner || el === highlight || banner.contains && banner.contains(el);
3681
- let bannerDocked = "top";
3682
- const dockBanner = (side) => {
3683
- if (bannerDocked === side) return;
3684
- bannerDocked = side;
3685
- if (side === "bottom") {
3686
- banner.style.top = "auto";
3687
- banner.style.bottom = "12px";
3688
- } else {
3689
- banner.style.top = "12px";
3690
- banner.style.bottom = "auto";
3691
- }
3692
- };
3693
- const onMove = (e) => {
3694
- const raw = e.target;
3695
- if (!raw || isOwn(raw)) {
3696
- highlight.style.display = "none";
3697
- return;
3698
- }
3699
- if (raw !== lastRaw) {
3700
- lastRaw = raw;
3701
- chain = buildChain(raw);
3702
- idx = snapIndex(chain);
3703
- }
3704
- refresh();
3705
- const el = current();
3706
- if (el) {
3707
- const r = el.getBoundingClientRect();
3708
- const br = banner.getBoundingClientRect();
3709
- const margin = 8;
3710
- if (r.left < br.right + margin && r.right > br.left - margin && r.top < br.bottom + margin && r.bottom > br.top - margin) {
3711
- dockBanner(bannerDocked === "top" ? "bottom" : "top");
3712
- }
3713
- }
3502
+ rows.forEach((row, i) => {
3503
+ const line = doc.createElement("label");
3504
+ 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"};`;
3505
+ const box = doc.createElement("input");
3506
+ box.type = "checkbox";
3507
+ box.disabled = !row.selectable;
3508
+ const text = doc.createElement("span");
3509
+ text.style.cssText = "flex:1;min-width:0;";
3510
+ const code = doc.createElement("code");
3511
+ code.style.cssText = `display:block;font:12px ${MONO};color:#f3f4f6;word-break:break-all;`;
3512
+ code.textContent = `<${row.info.tag}> ${row.hookLabel}`;
3513
+ const hint = doc.createElement("span");
3514
+ hint.style.cssText = "color:#9ca3af;";
3515
+ hint.textContent = row.selectable ? row.info.scopedLeafCount === 1 ? "contains exactly 1 matching element" : `contains ${row.info.scopedLeafCount ?? "?"} matching elements` : "add a data-testid to make this usable";
3516
+ text.appendChild(code);
3517
+ text.appendChild(hint);
3518
+ line.appendChild(box);
3519
+ line.appendChild(text);
3520
+ line.addEventListener("mouseenter", () => {
3521
+ const r = row.node.getBoundingClientRect();
3522
+ outline.style.display = "block";
3523
+ outline.style.left = r.left + "px";
3524
+ outline.style.top = r.top + "px";
3525
+ outline.style.width = r.width + "px";
3526
+ outline.style.height = r.height + "px";
3527
+ outlineLabel.textContent = `<${row.info.tag}> ${row.hookLabel}`;
3528
+ outlineLabel.style.display = "block";
3529
+ const lr = outlineLabel.getBoundingClientRect();
3530
+ const vw = g.innerWidth || doc.documentElement.clientWidth || 0;
3531
+ const top = r.top - lr.height - 6 < 4 ? r.bottom + 6 : r.top - lr.height - 6;
3532
+ outlineLabel.style.left = Math.max(6, Math.min(r.left, vw - lr.width - 6)) + "px";
3533
+ outlineLabel.style.top = top + "px";
3534
+ });
3535
+ line.addEventListener("mouseleave", () => {
3536
+ outline.style.display = "none";
3537
+ outlineLabel.style.display = "none";
3538
+ });
3539
+ box.addEventListener("change", () => {
3540
+ if (box.checked) selected.add(i);
3541
+ else selected.delete(i);
3542
+ refreshFooter();
3543
+ });
3544
+ panel.appendChild(line);
3545
+ });
3546
+ panel.appendChild(footer);
3547
+ const cleanup = () => {
3548
+ doc.removeEventListener("keydown", onKey, true);
3549
+ panel.remove();
3550
+ outline.remove();
3551
+ outlineLabel.remove();
3552
+ pickedOutline.remove();
3714
3553
  };
3715
- const onClick = (e) => {
3716
- stop(e);
3717
- const el = current();
3718
- if (!el || isOwn(e.target)) return;
3719
- g.__piwiPickedElement = el;
3720
- g.__piwiPickState = "picked";
3721
- removeListeners();
3722
- highlight.style.display = "none";
3723
- foot.textContent = "Analyzing element\u2026";
3554
+ const done = (state) => {
3555
+ g.__piwiPickAnchors = state === "done" ? rows.filter((_, i) => selected.has(i)).map((r) => r.info) : [];
3556
+ g.__piwiAnchorState = state;
3557
+ cleanup();
3724
3558
  };
3725
3559
  const onKey = (e) => {
3726
- if (e.key === "Escape") {
3727
- stop(e);
3728
- g.__piwiPickState = "skipped";
3729
- cleanup();
3730
- return;
3731
- }
3732
- if (e.key === "ArrowUp" || e.key === "ArrowDown") {
3733
- stop(e);
3734
- if (e.key === "ArrowUp") idx = Math.min(idx + 1, chain.length - 1);
3735
- else idx = Math.max(idx - 1, 0);
3736
- refresh();
3737
- }
3738
- };
3739
- const suppressed = ["mousedown", "mouseup", "pointerdown", "pointerup", "auxclick", "dblclick"];
3740
- const removeListeners = () => {
3741
- doc.removeEventListener("mousemove", onMove, true);
3742
- doc.removeEventListener("click", onClick, true);
3743
- doc.removeEventListener("keydown", onKey, true);
3744
- for (const t of suppressed) doc.removeEventListener(t, stop, true);
3745
- };
3746
- const cleanup = () => {
3747
- removeListeners();
3748
- highlight.remove();
3749
- banner.remove();
3560
+ if (e.key !== "Escape") return;
3561
+ e.preventDefault();
3562
+ e.stopImmediatePropagation();
3563
+ done("skipped");
3750
3564
  };
3751
- g.__piwiPickCleanup = cleanup;
3752
- doc.addEventListener("mousemove", onMove, true);
3753
- doc.addEventListener("click", onClick, true);
3565
+ const buttonRow = doc.createElement("div");
3566
+ buttonRow.style.cssText = "display:flex;gap:8px;margin-top:4px;";
3567
+ const useBtn = doc.createElement("button");
3568
+ useBtn.style.cssText = "flex:1;background:#7c3aed;color:#fff;border:none;border-radius:6px;padding:8px;cursor:pointer;font:600 12px system-ui;";
3569
+ useBtn.textContent = "Use selected parents";
3570
+ useBtn.addEventListener("click", (e) => {
3571
+ e.preventDefault();
3572
+ e.stopImmediatePropagation();
3573
+ done(selected.size > 0 ? "done" : "skipped");
3574
+ });
3575
+ const skipBtn = doc.createElement("button");
3576
+ skipBtn.style.cssText = "background:none;border:1px solid #374151;color:#9ca3af;border-radius:6px;padding:8px 10px;cursor:pointer;font:12px system-ui;";
3577
+ skipBtn.textContent = "Skip (Esc)";
3578
+ skipBtn.addEventListener("click", (e) => {
3579
+ e.preventDefault();
3580
+ e.stopImmediatePropagation();
3581
+ done("skipped");
3582
+ });
3583
+ buttonRow.appendChild(useBtn);
3584
+ buttonRow.appendChild(skipBtn);
3585
+ panel.appendChild(buttonRow);
3586
+ refreshFooter();
3587
+ g.__piwiAnchorCleanup = cleanup;
3754
3588
  doc.addEventListener("keydown", onKey, true);
3755
- for (const t of suppressed) doc.addEventListener(t, stop, true);
3589
+ doc.body.appendChild(pickedOutline);
3590
+ doc.body.appendChild(outline);
3591
+ doc.body.appendChild(outlineLabel);
3592
+ doc.body.appendChild(panel);
3756
3593
  }
3757
- function showAnchorPicker(arg) {
3594
+
3595
+ // ../packages/picker-dom/src/overlay-confirm.ts
3596
+ function showPickerChoices(arg) {
3758
3597
  const g = globalThis;
3759
3598
  const doc = g.document;
3760
- const el = g.__piwiPickedElement;
3761
- if (!doc || !doc.body || !el) {
3762
- g.__piwiAnchorState = "skipped";
3599
+ if (!doc || !doc.body) {
3600
+ g.__piwiPickChoice = -1;
3763
3601
  return;
3764
3602
  }
3765
3603
  const Z = 2147483600;
3766
- const { tagRoles, inputRoles, roleSources, leafRole, leafLevel, leafTestId } = arg;
3767
- const roleOf = (n) => {
3768
- const explicit = n.getAttribute && n.getAttribute("role");
3769
- if (explicit) return explicit;
3770
- const tag = (n.tagName || "").toLowerCase();
3771
- if (tag === "input") return inputRoles[(n.getAttribute("type") || "text").toLowerCase()] ?? "textbox";
3772
- if (tag === "select") return n.getAttribute("multiple") != null ? "listbox" : "combobox";
3773
- if (tag === "a") return n.getAttribute("href") != null ? "link" : null;
3774
- return tagRoles[tag] ?? null;
3775
- };
3776
- const levelOf = (n) => {
3777
- const m = /^h([1-6])$/.exec((n.tagName || "").toLowerCase());
3778
- if (m) return Number(m[1]);
3779
- const al = n.getAttribute && n.getAttribute("aria-level");
3780
- return al && /^\d+$/.test(al) ? Number(al) : null;
3781
- };
3782
- const leafMatches = (scope) => {
3783
- try {
3784
- if (leafTestId) return scope.querySelectorAll(`[data-testid=${JSON.stringify(leafTestId)}]`).length;
3785
- const nodes = scope.querySelectorAll(roleSources);
3786
- if (nodes.length > 2e3) return -1;
3787
- let matched = 0;
3788
- for (let i = 0; i < nodes.length; i++) {
3789
- const n = nodes[i];
3790
- if (roleOf(n) !== leafRole) continue;
3791
- if (leafLevel != null && levelOf(n) !== leafLevel) continue;
3792
- matched++;
3793
- }
3794
- return matched;
3795
- } catch {
3796
- return -1;
3604
+ const wrap = doc.createElement("div");
3605
+ 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;`;
3606
+ const panel = doc.createElement("div");
3607
+ 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);";
3608
+ const hlLocator = (expr) => {
3609
+ const escHtml = (s) => s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
3610
+ const re = /('(?:\\.|[^'])*'|"(?:\\.|[^"])*")|([A-Za-z_$][\w$]*)(?=\s*\()|([A-Za-z_$][\w$]*)(?=\s*:)|(true|false|null|\d+)|([{}(),.])/g;
3611
+ let html = "";
3612
+ let last = 0;
3613
+ let m;
3614
+ while ((m = re.exec(expr)) !== null) {
3615
+ if (m.index > last) html += escHtml(expr.slice(last, m.index));
3616
+ const color = m[1] ? "#86efac" : m[2] ? "#d8b4fe" : m[3] ? "#93c5fd" : m[4] ? "#fcd34d" : "#9ca3af";
3617
+ html += `<span style="color:${color}">${escHtml(m[0])}</span>`;
3618
+ last = re.lastIndex;
3797
3619
  }
3620
+ if (last < expr.length) html += escHtml(expr.slice(last));
3621
+ return html;
3798
3622
  };
3799
- let roleNodes = [];
3800
- try {
3801
- const all = doc.querySelectorAll(roleSources);
3802
- if (all.length <= 4e3) roleNodes = Array.from(all);
3803
- } catch {
3804
- roleNodes = [];
3623
+ const title = doc.createElement("div");
3624
+ title.style.cssText = "font-weight:600;margin-bottom:4px;";
3625
+ title.textContent = arg.failing ? "Pick a replacement locator" : "Pick a locator";
3626
+ const sub = doc.createElement("div");
3627
+ sub.style.cssText = "color:#9ca3af;margin-bottom:12px;";
3628
+ if (arg.failing) {
3629
+ sub.innerHTML = `Replaces <code style="font-family:ui-monospace,Menlo,monospace">${hlLocator(arg.failing)}</code> \u2014 ranked by stability score.`;
3630
+ } else {
3631
+ sub.textContent = "For the element you picked \u2014 ranked by stability score.";
3805
3632
  }
3806
- const count = (sel) => {
3807
- try {
3808
- return doc.querySelectorAll(sel).length;
3809
- } catch {
3810
- return void 0;
3811
- }
3633
+ panel.appendChild(title);
3634
+ panel.appendChild(sub);
3635
+ const done = (choice) => {
3636
+ g.__piwiPickChoice = choice;
3637
+ doc.removeEventListener("keydown", onKey, true);
3638
+ wrap.remove();
3812
3639
  };
3813
- const rows = [];
3814
- let node = el.parentElement;
3815
- let depth = 0;
3816
- while (node && depth < 12) {
3817
- depth++;
3818
- const tag = (node.tagName || "").toLowerCase();
3819
- if (tag === "body" || tag === "html") break;
3820
- const testId = node.getAttribute("data-testid");
3821
- const id = node.getAttribute("id");
3822
- const ariaLabel = node.getAttribute("aria-label");
3823
- const role = roleOf(node);
3824
- const info = { tag, depth, testId: testId || null, id: id || null, ariaLabel: ariaLabel || null, role };
3825
- if (testId) info.testIdCount = count(`[data-testid=${JSON.stringify(testId)}]`);
3826
- if (id) {
3827
- try {
3828
- info.idCount = count(`#${doc.defaultView.CSS.escape(id)}`);
3829
- } catch {
3830
- }
3640
+ const onKey = (e) => {
3641
+ if (e.key !== "Escape") return;
3642
+ e.preventDefault();
3643
+ e.stopImmediatePropagation();
3644
+ done(-1);
3645
+ };
3646
+ arg.choices.forEach((c, i) => {
3647
+ const btn = doc.createElement("button");
3648
+ 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;";
3649
+ const code = doc.createElement("span");
3650
+ code.innerHTML = hlLocator(c.locator);
3651
+ code.style.cssText = "word-break:break-all;";
3652
+ const score = doc.createElement("span");
3653
+ score.textContent = String(c.score);
3654
+ score.style.cssText = "color:#c4b5fd;flex-shrink:0;font-variant-numeric:tabular-nums;";
3655
+ btn.appendChild(code);
3656
+ btn.appendChild(score);
3657
+ btn.addEventListener("click", (e) => {
3658
+ e.preventDefault();
3659
+ e.stopImmediatePropagation();
3660
+ done(i);
3661
+ });
3662
+ panel.appendChild(btn);
3663
+ });
3664
+ const skip = doc.createElement("button");
3665
+ skip.style.cssText = "background:none;border:none;color:#9ca3af;cursor:pointer;padding:6px 0 0;font:12px system-ui,sans-serif;";
3666
+ skip.textContent = "Skip \u2014 keep the failure as-is (Esc)";
3667
+ skip.addEventListener("click", (e) => {
3668
+ e.preventDefault();
3669
+ e.stopImmediatePropagation();
3670
+ done(-1);
3671
+ });
3672
+ panel.appendChild(skip);
3673
+ doc.addEventListener("keydown", onKey, true);
3674
+ wrap.appendChild(panel);
3675
+ doc.body.appendChild(wrap);
3676
+ }
3677
+
3678
+ // ../packages/core/src/locator-generation.ts
3679
+ var TAG_TO_ROLE = {
3680
+ a: "link",
3681
+ button: "button",
3682
+ nav: "navigation",
3683
+ main: "main",
3684
+ article: "article",
3685
+ section: "region",
3686
+ form: "form",
3687
+ img: "img",
3688
+ figure: "figure",
3689
+ figcaption: "caption",
3690
+ blockquote: "blockquote",
3691
+ table: "table",
3692
+ caption: "caption",
3693
+ thead: "rowgroup",
3694
+ tbody: "rowgroup",
3695
+ tfoot: "rowgroup",
3696
+ tr: "row",
3697
+ td: "cell",
3698
+ ul: "list",
3699
+ ol: "list",
3700
+ li: "listitem",
3701
+ dialog: "dialog",
3702
+ output: "status",
3703
+ progress: "progressbar",
3704
+ meter: "meter",
3705
+ textarea: "textbox",
3706
+ h1: "heading",
3707
+ h2: "heading",
3708
+ h3: "heading",
3709
+ h4: "heading",
3710
+ h5: "heading",
3711
+ h6: "heading",
3712
+ details: "group",
3713
+ summary: "button",
3714
+ search: "search"
3715
+ };
3716
+ var INPUT_TYPE_TO_ROLE = {
3717
+ button: "button",
3718
+ submit: "button",
3719
+ reset: "button",
3720
+ image: "button",
3721
+ checkbox: "checkbox",
3722
+ radio: "radio",
3723
+ range: "slider",
3724
+ search: "searchbox",
3725
+ number: "spinbutton",
3726
+ text: "textbox",
3727
+ email: "textbox",
3728
+ tel: "textbox",
3729
+ url: "textbox",
3730
+ password: "textbox"
3731
+ };
3732
+ var CAPTURED_ATTRIBUTES = [
3733
+ "id",
3734
+ "class",
3735
+ "name",
3736
+ "data-testid",
3737
+ "placeholder",
3738
+ "alt",
3739
+ "title",
3740
+ "aria-label",
3741
+ "aria-level",
3742
+ "role",
3743
+ "type",
3744
+ "href",
3745
+ "multiple"
3746
+ ];
3747
+ function resolveAriaRole(attrs) {
3748
+ const explicit = attrs.attributes["role"];
3749
+ if (explicit) return explicit;
3750
+ const tag = attrs.tagName;
3751
+ if (!tag) return null;
3752
+ if (tag === "input") {
3753
+ const type = (attrs.attributes["type"] ?? "text").toLowerCase();
3754
+ return INPUT_TYPE_TO_ROLE[type] ?? "textbox";
3755
+ }
3756
+ if (tag === "select") {
3757
+ return attrs.attributes["multiple"] != null ? "listbox" : "combobox";
3758
+ }
3759
+ if (tag === "a") {
3760
+ return attrs.attributes["href"] != null ? "link" : null;
3761
+ }
3762
+ return TAG_TO_ROLE[tag] ?? null;
3763
+ }
3764
+ function headingLevel(attrs, role) {
3765
+ if (role !== "heading") return null;
3766
+ const tagMatch = attrs.tagName.match(/^h([1-6])$/);
3767
+ if (tagMatch) return Number(tagMatch[1]);
3768
+ const ariaLevel = attrs.attributes["aria-level"];
3769
+ if (ariaLevel && /^\d+$/.test(ariaLevel)) return Number(ariaLevel);
3770
+ return null;
3771
+ }
3772
+ var attr = (a, key) => a.attributes[key] || null;
3773
+ var esc = (s) => s.replace(/\\/g, "\\\\").replace(/'/g, "\\'");
3774
+ var escCssAttrValue = (s) => s.replace(/\\/g, "\\\\").replace(/"/g, '\\"');
3775
+ var isCssSafeId = (id) => /^[A-Za-z][A-Za-z0-9_-]*$/.test(id);
3776
+ function classifyCssStability(className) {
3777
+ if (/[a-f0-9]{8,}/i.test(className)) return 10;
3778
+ if (/^(?:css|sc|emotion|styled)-/i.test(className)) return 15;
3779
+ 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(
3780
+ className
3781
+ ))
3782
+ return 25;
3783
+ if (/__/.test(className) || /--/.test(className)) return 35;
3784
+ if (/^[a-z]+(-[a-z]+)+$/.test(className)) return 40;
3785
+ if (/^[a-z]+[A-Z][a-zA-Z]+$/.test(className)) return 40;
3786
+ if (className.includes("_")) return 15;
3787
+ if (/^[a-z]+-[a-z0-9]{5,}$/.test(className) && /[0-9]/.test(className)) return 15;
3788
+ return 15;
3789
+ }
3790
+ function isAutoGenerated(value) {
3791
+ if (/^[a-f0-9]{8}-([a-f0-9]{4}-){3}[a-f0-9]{12}$/i.test(value)) return true;
3792
+ if (/^[a-f0-9]{8,}$/i.test(value)) return true;
3793
+ if (/^[a-z]+-\d{4,}$/.test(value)) return true;
3794
+ 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(
3795
+ value
3796
+ )) {
3797
+ return true;
3798
+ }
3799
+ if (/^(emotion-|styled-|css-|sc-)/.test(value)) return true;
3800
+ if (value.startsWith("ng-")) return true;
3801
+ if (/^(radix-|headlessui-|mui-|mantine-|chakra-)/i.test(value)) return true;
3802
+ if (/^:r[0-9a-z]+:$/i.test(value) || /^«r[0-9a-z]+»$/i.test(value)) return true;
3803
+ return false;
3804
+ }
3805
+ var TEST_DATA_ATTRS = /* @__PURE__ */ new Set(["data-test", "data-test-id", "data-qa", "data-qa-id", "data-cy", "data-e2e"]);
3806
+ function generateAlternatives(attrs) {
3807
+ const alts = [];
3808
+ const seen = /* @__PURE__ */ new Set();
3809
+ const add = (loc) => {
3810
+ if (!seen.has(loc.locator)) {
3811
+ seen.add(loc.locator);
3812
+ alts.push(loc);
3813
+ }
3814
+ };
3815
+ const { accessibleName } = attrs;
3816
+ const tag = attrs.tagName;
3817
+ const role = resolveAriaRole(attrs);
3818
+ const counts = attrs.selectorCounts;
3819
+ const isUnique = (n) => n == null || n <= 1;
3820
+ const ambiguityPenalty = (n) => n != null && n > 1 ? 45 : 0;
3821
+ const text = attrs.textContent ? attrs.textContent.replace(/\s+/g, " ").trim() : null;
3822
+ const testId = attr(attrs, "data-testid");
3823
+ if (testId && isUnique(counts?.testId)) {
3824
+ add({
3825
+ locator: `getByTestId('${esc(testId)}')`,
3826
+ method: "getByTestId",
3827
+ args: { testId },
3828
+ score: 100
3829
+ });
3830
+ }
3831
+ const level = headingLevel(attrs, role);
3832
+ const levelPart = level != null ? `, level: ${level}` : "";
3833
+ const withLevel = (base) => level != null ? { ...base, level } : base;
3834
+ if (role && accessibleName) {
3835
+ add({
3836
+ locator: `getByRole('${role}', { name: '${esc(accessibleName)}'${levelPart} })`,
3837
+ method: "getByRole",
3838
+ args: withLevel({ role, name: accessibleName }),
3839
+ score: 90 - ambiguityPenalty(counts?.roleName)
3840
+ });
3841
+ }
3842
+ const ariaLabel = attr(attrs, "aria-label");
3843
+ if (role && ariaLabel && ariaLabel !== accessibleName) {
3844
+ add({
3845
+ locator: `getByRole('${role}', { name: '${esc(ariaLabel)}'${levelPart} })`,
3846
+ method: "getByRole",
3847
+ args: withLevel({ role, name: ariaLabel }),
3848
+ score: 85 - ambiguityPenalty(counts?.roleName)
3849
+ });
3850
+ }
3851
+ if (accessibleName && ["input", "select", "textarea"].includes(tag)) {
3852
+ const label = attr(attrs, "aria-label");
3853
+ const labelBacked = attrs.hasLabel === void 0 ? true : attrs.hasLabel === true || label === accessibleName;
3854
+ if (labelBacked) {
3855
+ add({
3856
+ locator: `getByLabel('${esc(accessibleName)}')`,
3857
+ method: "getByLabel",
3858
+ args: { label: accessibleName },
3859
+ score: 85
3860
+ });
3861
+ }
3862
+ }
3863
+ const placeholder = attr(attrs, "placeholder");
3864
+ if (placeholder) {
3865
+ add({
3866
+ locator: `getByPlaceholder('${esc(placeholder)}')`,
3867
+ method: "getByPlaceholder",
3868
+ args: { placeholder },
3869
+ score: 80 - ambiguityPenalty(counts?.placeholder)
3870
+ });
3871
+ }
3872
+ if (text && text.length < 80) {
3873
+ add({
3874
+ locator: `getByText('${esc(text)}')`,
3875
+ method: "getByText",
3876
+ args: { text },
3877
+ score: 75 - ambiguityPenalty(counts?.text)
3878
+ });
3879
+ }
3880
+ const id = attr(attrs, "id");
3881
+ if (id && !isAutoGenerated(id) && isUnique(counts?.id)) {
3882
+ const selector = isCssSafeId(id) ? `#${id}` : `[id="${escCssAttrValue(id)}"]`;
3883
+ add({
3884
+ locator: `locator('${esc(selector)}')`,
3885
+ method: "locator",
3886
+ args: { selector },
3887
+ score: 65
3888
+ });
3889
+ }
3890
+ const name = attr(attrs, "name");
3891
+ if (name && isUnique(counts?.name)) {
3892
+ const selector = `[name="${escCssAttrValue(name)}"]`;
3893
+ add({
3894
+ locator: `locator('${esc(selector)}')`,
3895
+ method: "locator",
3896
+ args: { selector },
3897
+ score: 60
3898
+ });
3899
+ }
3900
+ const alt = attr(attrs, "alt");
3901
+ if (alt) {
3902
+ add({
3903
+ locator: `getByAltText('${esc(alt)}')`,
3904
+ method: "getByAltText",
3905
+ args: { text: alt },
3906
+ score: 60 - ambiguityPenalty(counts?.alt)
3907
+ });
3908
+ }
3909
+ const title = attr(attrs, "title");
3910
+ if (title) {
3911
+ add({
3912
+ locator: `getByTitle('${esc(title)}')`,
3913
+ method: "getByTitle",
3914
+ args: { title },
3915
+ score: 50 - ambiguityPenalty(counts?.title)
3916
+ });
3917
+ }
3918
+ const hasOwnTestId = !!(testId && isUnique(counts?.testId));
3919
+ const addAnchoredChains = (leaf, scopedCount, scores) => {
3920
+ let testIdAnchorDone = false;
3921
+ let idAnchorDone = false;
3922
+ let roleAnchorDone = false;
3923
+ let dataAnchorDone = false;
3924
+ let filterAnchorDone = false;
3925
+ for (const anc of attrs.ancestors ?? []) {
3926
+ if (scopedCount(anc) !== 1) continue;
3927
+ if (!testIdAnchorDone && anc.testId && anc.testIdCount === 1) {
3928
+ testIdAnchorDone = true;
3929
+ add({
3930
+ locator: `getByTestId('${esc(anc.testId)}').${leaf.expr}`,
3931
+ method: leaf.method,
3932
+ args: { ...leaf.args, anchorTestId: anc.testId },
3933
+ score: scores.testId
3934
+ });
3935
+ }
3936
+ if (!idAnchorDone && anc.id && !isAutoGenerated(anc.id) && anc.idCount === 1) {
3937
+ idAnchorDone = true;
3938
+ const anchorSelector = isCssSafeId(anc.id) ? `#${anc.id}` : `[id="${escCssAttrValue(anc.id)}"]`;
3939
+ add({
3940
+ locator: `locator('${esc(anchorSelector)}').${leaf.expr}`,
3941
+ method: leaf.method,
3942
+ args: { ...leaf.args, anchorSelector },
3943
+ score: scores.id
3944
+ });
3945
+ }
3946
+ if (!dataAnchorDone && anc.dataAttr && anc.dataAttrCount === 1) {
3947
+ dataAnchorDone = true;
3948
+ const { name: name2, value } = anc.dataAttr;
3949
+ const anchorSelector = `[${name2}="${escCssAttrValue(value)}"]`;
3950
+ add({
3951
+ locator: `locator('${esc(anchorSelector)}').${leaf.expr}`,
3952
+ method: leaf.method,
3953
+ args: { ...leaf.args, anchorSelector },
3954
+ score: TEST_DATA_ATTRS.has(name2) ? scores.testData : scores.data
3955
+ });
3956
+ }
3957
+ const ancestorRole = anc.role || TAG_TO_ROLE[anc.tag] || null;
3958
+ if (!roleAnchorDone && ancestorRole && ancestorRole !== leaf.role && anc.roleCount === 1) {
3959
+ roleAnchorDone = true;
3960
+ add({
3961
+ locator: `getByRole('${esc(ancestorRole)}').${leaf.expr}`,
3962
+ method: leaf.method,
3963
+ args: { ...leaf.args, anchorRole: ancestorRole },
3964
+ score: scores.role
3965
+ });
3966
+ }
3967
+ if (!filterAnchorDone && ancestorRole && anc.filterText && anc.filterRoleCount === 1) {
3968
+ filterAnchorDone = true;
3969
+ add({
3970
+ locator: `getByRole('${esc(ancestorRole)}').filter({ hasText: '${esc(anc.filterText)}' }).${leaf.expr}`,
3971
+ method: leaf.method,
3972
+ args: { ...leaf.args, anchorRole: ancestorRole, anchorHasText: anc.filterText },
3973
+ score: scores.filter
3974
+ });
3975
+ }
3976
+ }
3977
+ };
3978
+ if (role && !hasOwnTestId) {
3979
+ const rolePart = level != null ? `'${role}', { level: ${level} }` : `'${role}'`;
3980
+ const leafArgs = withLevel({ role });
3981
+ addAnchoredChains(
3982
+ { expr: `getByRole(${rolePart})`, method: "getByRole", args: leafArgs, role },
3983
+ (anc) => anc.scopedRoleCount,
3984
+ { testId: 72, testData: 70, id: 64, data: 60, role: 55, filter: 53 }
3985
+ );
3986
+ const pos = attrs.rolePosition;
3987
+ if (pos && pos.role === role && (pos.count === 1 || level != null && pos.levelCount === 1)) {
3988
+ add({
3989
+ locator: `getByRole(${rolePart})`,
3990
+ method: "getByRole",
3991
+ args: leafArgs,
3992
+ score: 58
3993
+ });
3994
+ }
3995
+ } else if (!role && text && text.length < 80 && !hasOwnTestId) {
3996
+ addAnchoredChains(
3997
+ { expr: `getByText('${esc(text)}')`, method: "getByText", args: { text }, role: null },
3998
+ (anc) => anc.scopedTextCount,
3999
+ { testId: 68, testData: 66, id: 60, data: 56, role: 51, filter: 49 }
4000
+ );
4001
+ }
4002
+ const clsStr = attr(attrs, "class");
4003
+ if (clsStr) {
4004
+ const countsClasses = counts?.classes;
4005
+ 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);
4006
+ for (const { cls, score } of classes) {
4007
+ add({
4008
+ locator: `locator('.${esc(cls)}')`,
4009
+ method: "locator",
4010
+ args: { selector: `.${cls}` },
4011
+ score
4012
+ });
4013
+ }
4014
+ }
4015
+ return alts.sort((a, b) => b.score - a.score);
4016
+ }
4017
+ function approximateAccessibleName(attrs) {
4018
+ const a = attrs.attributes;
4019
+ const ariaLabel = a["aria-label"];
4020
+ if (ariaLabel) return ariaLabel;
4021
+ if (attrs.textContent) return attrs.textContent;
4022
+ const title = a["title"];
4023
+ if (title) return title;
4024
+ const placeholder = a["placeholder"];
4025
+ if (placeholder) return placeholder;
4026
+ return null;
4027
+ }
4028
+
4029
+ // ../packages/picker-dom/src/anchor-alternatives.ts
4030
+ var escStr = (s) => s.replaceAll("\\", "\\\\").replaceAll("'", "\\'");
4031
+ var cssIdSelector = (id) => /^[A-Za-z_][A-Za-z0-9_-]*$/.test(id) ? `#${id}` : `[id="${id.replaceAll("\\", "\\\\").replaceAll('"', '\\"')}"]`;
4032
+ var ANCHOR_KIND_SCORES = { testid: 80, id: 74, labeledRole: 68, role: 62 };
4033
+ function anchorSegment(a) {
4034
+ if (a.testId && a.testIdCount === 1) {
4035
+ return { code: `getByTestId('${escStr(a.testId)}')`, kind: "testid", flatArgs: { anchorTestId: a.testId } };
4036
+ }
4037
+ if (a.id && !isAutoGenerated(a.id) && a.idCount === 1) {
4038
+ const anchorSelector = cssIdSelector(a.id);
4039
+ return { code: `locator('${escStr(anchorSelector)}')`, kind: "id", flatArgs: { anchorSelector } };
4040
+ }
4041
+ if (a.role && a.ariaLabel && a.labeledRoleCount === 1) {
4042
+ return {
4043
+ code: `getByRole('${escStr(a.role)}', { name: '${escStr(a.ariaLabel)}' })`,
4044
+ kind: "labeledRole",
4045
+ flatArgs: { anchorRole: a.role, anchorName: a.ariaLabel }
4046
+ };
4047
+ }
4048
+ if (a.role && a.roleCount === 1) {
4049
+ return { code: `getByRole('${escStr(a.role)}')`, kind: "role", flatArgs: { anchorRole: a.role } };
4050
+ }
4051
+ return null;
4052
+ }
4053
+ function generateAnchoredAlternatives(leaf, anchors, chainLeafCount) {
4054
+ if (!leaf.role || anchors.length === 0) return [];
4055
+ const out = [];
4056
+ const seen = /* @__PURE__ */ new Set();
4057
+ const rolePart = leaf.level != null ? `'${leaf.role}', { level: ${leaf.level} }` : `'${leaf.role}'`;
4058
+ const leafArgs = leaf.level != null ? { role: leaf.role, level: leaf.level } : { role: leaf.role };
4059
+ const add = (l) => {
4060
+ if (!seen.has(l.locator)) {
4061
+ seen.add(l.locator);
4062
+ out.push(l);
4063
+ }
4064
+ };
4065
+ for (const anchor of anchors) {
4066
+ if (anchor.scopedLeafCount !== 1) continue;
4067
+ const seg = anchorSegment(anchor);
4068
+ if (!seg) continue;
4069
+ add({
4070
+ locator: `${seg.code}.getByRole(${rolePart})`,
4071
+ method: "getByRole",
4072
+ args: { ...leafArgs, ...seg.flatArgs },
4073
+ score: ANCHOR_KIND_SCORES[seg.kind]
4074
+ });
4075
+ }
4076
+ if (anchors.length >= 2 && chainLeafCount === 1) {
4077
+ const ordered = [...anchors].sort((a, b) => b.depth - a.depth);
4078
+ const segments = ordered.map(anchorSegment);
4079
+ if (segments.every((s) => s !== null)) {
4080
+ const innermost = segments[segments.length - 1];
4081
+ const score = Math.min(...segments.map((s) => ANCHOR_KIND_SCORES[s.kind]));
4082
+ add({
4083
+ locator: `${segments.map((s) => s.code).join(".")}.getByRole(${rolePart})`,
4084
+ method: "getByRole",
4085
+ // Flat args describe the innermost anchor (what the healing fingerprint
4086
+ // logic understands); the full chain rides along for transparency.
4087
+ args: { ...leafArgs, ...innermost.flatArgs, anchorChain: segments.map((s) => s.code) },
4088
+ score
4089
+ });
4090
+ }
4091
+ }
4092
+ return out.sort((a, b) => b.score - a.score);
4093
+ }
4094
+ function mergeCandidates(base, extra) {
4095
+ const seen = new Set(base.map((b) => b.locator));
4096
+ const merged = [...base];
4097
+ for (const e of extra) {
4098
+ if (seen.has(e.locator)) continue;
4099
+ seen.add(e.locator);
4100
+ merged.push(e);
4101
+ }
4102
+ return merged.sort((a, b) => b.score - a.score);
4103
+ }
4104
+
4105
+ // src/internal/capture/locator-healing.ts
4106
+ var path15 = __toESM(require("path"));
4107
+
4108
+ // ../packages/core/src/locator-fingerprint.ts
4109
+ var PRESENT_SIMILARITY = 0.8;
4110
+ var MATCH_SIMILARITY = 0.2;
4111
+ function parseAriaCandidates(ariaSnapshot) {
4112
+ if (!ariaSnapshot) return [];
4113
+ const out = [];
4114
+ for (const line of ariaSnapshot.split("\n")) {
4115
+ const m = line.match(/^\s*-\s+([a-z]+)(?:\s+"((?:[^"\\]|\\.)*)")?/i);
4116
+ if (!m) continue;
4117
+ const role = m[1];
4118
+ const name = m[2] != null ? m[2].replace(/\\(.)/g, "$1") : null;
4119
+ if (!name && (role === "generic" || role === "group" || role === "list" || role === "paragraph")) continue;
4120
+ const levelMatch = line.slice(m[0].length).match(/\[level=(\d+)\]/);
4121
+ const level = levelMatch ? Number(levelMatch[1]) : null;
4122
+ out.push({ role, name, level });
4123
+ }
4124
+ return out;
4125
+ }
4126
+ function textSimilarity(a, b) {
4127
+ const tok = (s) => new Set(
4128
+ (s ?? "").toLowerCase().split(/[^a-z0-9]+/i).filter(Boolean)
4129
+ );
4130
+ const sa = tok(a);
4131
+ const sb = tok(b);
4132
+ if (sa.size === 0 && sb.size === 0) return 1;
4133
+ if (sa.size === 0 || sb.size === 0) return 0;
4134
+ let common = 0;
4135
+ for (const t of sa) if (sb.has(t)) common++;
4136
+ return 2 * common / (sa.size + sb.size);
4137
+ }
4138
+ function fingerprintPresent(fp, candidates) {
4139
+ if (!fp.name) return false;
4140
+ return candidates.some(
4141
+ (c) => (!fp.role || c.role === fp.role) && textSimilarity(c.name, fp.name) >= PRESENT_SIMILARITY
4142
+ );
4143
+ }
4144
+ function matchRenamedElement(fp, candidates) {
4145
+ if (candidates.length === 0) return null;
4146
+ const sameRole = fp.role ? candidates.filter((c) => c.role === fp.role) : candidates;
4147
+ if (sameRole.length === 0) return null;
4148
+ let pool = sameRole;
4149
+ if (fp.level != null) {
4150
+ const sameLevel = sameRole.filter((c) => c.level === fp.level);
4151
+ if (sameLevel.length > 0) pool = sameLevel;
4152
+ }
4153
+ if (pool.length === 1) {
4154
+ return { candidate: pool[0], confidence: 0.7 };
4155
+ }
4156
+ let best = null;
4157
+ let bestScore = -1;
4158
+ for (const c of pool) {
4159
+ const s = textSimilarity(c.name, fp.name);
4160
+ if (s > bestScore) {
4161
+ bestScore = s;
4162
+ best = c;
4163
+ }
4164
+ }
4165
+ if (best && bestScore >= MATCH_SIMILARITY) return { candidate: best, confidence: bestScore };
4166
+ const pos = fp.rolePosition;
4167
+ if (pos && fp.role && pos.role === fp.role && sameRole.length >= 2 && sameRole.length === pos.count) {
4168
+ const byIndex = sameRole[pos.index];
4169
+ if (byIndex) return { candidate: byIndex, confidence: 0.5 };
4170
+ }
4171
+ return null;
4172
+ }
4173
+
4174
+ // ../packages/core/src/locator-methods.ts
4175
+ var LOCATOR_BUILDER_METHODS = [
4176
+ "getByRole",
4177
+ "getByTestId",
4178
+ "getByText",
4179
+ "getByLabel",
4180
+ "getByPlaceholder",
4181
+ "getByAltText",
4182
+ "getByTitle",
4183
+ "locator"
4184
+ ];
4185
+
4186
+ // src/internal/capture/locator-healing.ts
4187
+ function dedupeSnapshotsByLocation(snaps) {
4188
+ const lastWithElement = /* @__PURE__ */ new Map();
4189
+ const lastAny = /* @__PURE__ */ new Map();
4190
+ snaps.forEach((s, i) => {
4191
+ if (!s.location) return;
4192
+ lastAny.set(s.location, i);
4193
+ if (s.element) lastWithElement.set(s.location, i);
4194
+ });
4195
+ return snaps.filter((s, i) => {
4196
+ if (!s.location) return true;
4197
+ return (lastWithElement.get(s.location) ?? lastAny.get(s.location)) === i;
4198
+ });
4199
+ }
4200
+ var LOCATOR_METHODS = [...LOCATOR_BUILDER_METHODS];
4201
+ var CHAIN_METHODS = [
4202
+ "first",
4203
+ "nth",
4204
+ "last",
4205
+ "filter",
4206
+ "and",
4207
+ "or",
4208
+ "locator",
4209
+ "getByRole",
4210
+ "getByTestId",
4211
+ "getByText",
4212
+ "getByLabel",
4213
+ "getByPlaceholder",
4214
+ "getByAltText",
4215
+ "getByTitle"
4216
+ ];
4217
+ var ACTION_METHODS = [
4218
+ "click",
4219
+ "fill",
4220
+ "check",
4221
+ "uncheck",
4222
+ "selectOption",
4223
+ "dblclick",
4224
+ "tap",
4225
+ "hover",
4226
+ "press",
4227
+ "type",
4228
+ "pressSequentially",
4229
+ "clear",
4230
+ "setInputFiles",
4231
+ "dragTo",
4232
+ "focus",
4233
+ "blur",
4234
+ "scrollIntoViewIfNeeded",
4235
+ "dispatchEvent",
4236
+ "selectText",
4237
+ // Not an action, but a successful waitFor proves the element resolved — the
4238
+ // closest capture hook available for assertion-style usage of a locator.
4239
+ "waitFor"
4240
+ ];
4241
+ var LOCATOR_CREATING_CHAINS = new Set(LOCATOR_METHODS);
4242
+ var EXPECT_METHOD = "_expect";
4243
+ var EXPECT_CAPTURE_EXPRESSIONS = /* @__PURE__ */ new Set([
4244
+ "to.be.attached",
4245
+ "to.be.checked",
4246
+ "to.be.disabled",
4247
+ "to.be.editable",
4248
+ "to.be.empty",
4249
+ "to.be.enabled",
4250
+ "to.be.focused",
4251
+ "to.be.in.viewport",
4252
+ "to.be.readonly",
4253
+ "to.be.visible",
4254
+ "to.contain.class",
4255
+ "to.contain.text",
4256
+ "to.have.accessible.description",
4257
+ "to.have.accessible.error.message",
4258
+ "to.have.accessible.name",
4259
+ "to.have.attribute",
4260
+ "to.have.attribute.value",
4261
+ "to.have.class",
4262
+ "to.have.css",
4263
+ "to.have.id",
4264
+ "to.have.js.property",
4265
+ "to.have.role",
4266
+ "to.have.text",
4267
+ "to.have.value",
4268
+ "to.match.aria"
4269
+ ]);
4270
+ function extractAccessibleName(ariaSnapshot) {
4271
+ if (!ariaSnapshot) return null;
4272
+ const match = ariaSnapshot.match(/- \w+ "([^"]+)"/);
4273
+ if (match) return match[1];
4274
+ return null;
4275
+ }
4276
+ var NAME_BASED_METHODS = /* @__PURE__ */ new Set([
4277
+ "getByText",
4278
+ "getByRole",
4279
+ "getByLabel",
4280
+ "getByPlaceholder",
4281
+ "getByTitle",
4282
+ "getByAltText"
4283
+ ]);
4284
+ var escAttr = (s) => s.replaceAll("\\", "\\\\").replaceAll("'", "\\'");
4285
+ var SUGG_TEXT_ROLES = /* @__PURE__ */ new Set([
4286
+ "button",
4287
+ "link",
4288
+ "heading",
4289
+ "menuitem",
4290
+ "tab",
4291
+ "option",
4292
+ "cell",
4293
+ "columnheader",
4294
+ "rowheader",
4295
+ "gridcell",
4296
+ "treeitem",
4297
+ "listitem",
4298
+ "checkbox",
4299
+ "radio",
4300
+ "switch"
4301
+ ]);
4302
+ var SUGG_FIELD_ROLES = /* @__PURE__ */ new Set(["textbox", "combobox", "searchbox", "spinbutton", "slider"]);
4303
+ function failedNameAndRole(failed) {
4304
+ if (failed.method === "getByRole") {
4305
+ const role = typeof failed.args[0] === "string" ? failed.args[0] : null;
4306
+ const opts = failed.args[1];
4307
+ const name = opts && typeof opts.name === "string" ? opts.name : null;
4308
+ const level = opts && typeof opts.level === "number" ? opts.level : null;
4309
+ return { role, name, level };
4310
+ }
4311
+ const first = failed.args.find((a) => typeof a === "string");
4312
+ return { role: null, name: typeof first === "string" ? first : null, level: null };
4313
+ }
4314
+ function renderFailing(failed) {
4315
+ const { role, name } = failedNameAndRole(failed);
4316
+ if (failed.method === "getByRole") {
4317
+ return name ? `getByRole('${escAttr(role ?? "")}', { name: '${escAttr(name)}' })` : `getByRole('${escAttr(role ?? "")}')`;
4318
+ }
4319
+ return `${failed.method}('${escAttr(name ?? "")}')`;
4320
+ }
4321
+ function freshSuggestions(candidate, failedMethod) {
4322
+ const out = [];
4323
+ const role = candidate.role;
4324
+ const name = candidate.name;
4325
+ const push = (s) => {
4326
+ if (!out.includes(s)) out.push(s);
4327
+ };
4328
+ const levelPart = candidate.level != null ? `, level: ${candidate.level}` : "";
4329
+ const roleLoc = `getByRole('${escAttr(role)}', { name: '${escAttr(name)}'${levelPart} })`;
4330
+ const textLoc = `getByText('${escAttr(name)}')`;
4331
+ const labelLoc = `getByLabel('${escAttr(name)}')`;
4332
+ if (failedMethod === "getByText" && SUGG_TEXT_ROLES.has(role)) push(textLoc);
4333
+ if (failedMethod === "getByLabel" && SUGG_FIELD_ROLES.has(role)) push(labelLoc);
4334
+ push(roleLoc);
4335
+ if (SUGG_TEXT_ROLES.has(role)) push(textLoc);
4336
+ else if (SUGG_FIELD_ROLES.has(role)) push(labelLoc);
4337
+ return out;
4338
+ }
4339
+ function suggestLocatorsFromAria(failed, ariaSnapshot) {
4340
+ if (!ariaSnapshot || !NAME_BASED_METHODS.has(failed.method)) return null;
4341
+ const { role, name, level } = failedNameAndRole(failed);
4342
+ if (!name) return null;
4343
+ const candidates = parseAriaCandidates(ariaSnapshot);
4344
+ if (candidates.length === 0) return null;
4345
+ const fingerprint = { role, name, level };
4346
+ if (fingerprintPresent(fingerprint, candidates)) return null;
4347
+ const best = matchRenamedElement(fingerprint, candidates)?.candidate;
4348
+ if (!best || !best.name) return null;
4349
+ const suggestions = freshSuggestions({ role: best.role, name: best.name, level: best.level }, failed.method);
4350
+ if (suggestions.length === 0) return null;
4351
+ return { failing: renderFailing(failed), suggestions };
4352
+ }
4353
+ function captureCallerLocation(stack = new Error().stack ?? "") {
4354
+ const lines = stack.split("\n");
4355
+ let prevWasCaptureModule = false;
4356
+ let selfFile = null;
4357
+ for (let i = 1; i < lines.length; i++) {
4358
+ const line = lines[i].trim();
4359
+ if (!line.startsWith("at")) continue;
4360
+ const m = line.match(/^at\s+(?:(.+?)\s+\()?(.+?):(\d+):(\d+)\)?$/);
4361
+ if (!m) {
4362
+ prevWasCaptureModule = false;
4363
+ continue;
4364
+ }
4365
+ let file = m[2];
4366
+ if (!file || file.startsWith("node:")) {
4367
+ prevWasCaptureModule = false;
4368
+ continue;
3831
4369
  }
3832
- if (role) {
3833
- let roleCount = 0;
3834
- let labeledCount = 0;
3835
- for (const n of roleNodes) {
3836
- if (roleOf(n) !== role) continue;
3837
- roleCount++;
3838
- if (ariaLabel && n.getAttribute && n.getAttribute("aria-label") === ariaLabel) labeledCount++;
3839
- }
3840
- info.roleCount = roleCount;
3841
- if (ariaLabel) info.labeledRoleCount = labeledCount;
4370
+ file = file.replace(/^file:\/\/\/?/, "");
4371
+ if (!/\.[a-z]+$/i.test(file)) {
4372
+ prevWasCaptureModule = false;
4373
+ continue;
3842
4374
  }
3843
- info.scopedLeafCount = leafMatches(node);
3844
- const hookLabel = testId ? `data-testid="${testId}"` : id ? `#${id}` : ariaLabel && role ? `${role} "${ariaLabel}"` : role ? `role ${role}` : "no stable hook";
3845
- rows.push({
3846
- node,
3847
- info,
3848
- hookLabel,
3849
- selectable: !!(testId || id || role && (ariaLabel || info.roleCount === 1))
3850
- });
3851
- node = node.parentElement;
3852
- }
3853
- if (rows.length === 0) {
3854
- g.__piwiAnchorState = "skipped";
3855
- return;
3856
- }
3857
- const outline = doc.createElement("div");
3858
- outline.style.cssText = `position:fixed;pointer-events:none;z-index:${Z};box-sizing:border-box;border:2px solid #22c55e;border-radius:3px;display:none;`;
3859
- const pickedOutline = doc.createElement("div");
3860
- const pr = el.getBoundingClientRect();
3861
- pickedOutline.style.cssText = `position:fixed;pointer-events:none;z-index:${Z};box-sizing:border-box;border:2px solid #7c3aed;background:rgba(124,58,237,.10);border-radius:3px;left:${pr.left}px;top:${pr.top}px;width:${pr.width}px;height:${pr.height}px;`;
3862
- const panel = doc.createElement("div");
3863
- panel.style.cssText = `position:fixed;top:12px;right:12px;z-index:${Z + 3};width:340px;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);`;
3864
- const title = doc.createElement("div");
3865
- title.style.cssText = "font-weight:600;font-size:13px;margin-bottom:2px;";
3866
- title.textContent = "Scope to stable parents (optional)";
3867
- const sub = doc.createElement("div");
3868
- sub.style.cssText = "color:#9ca3af;margin-bottom:10px;";
3869
- sub.textContent = "Pick one or more parents to anchor the locator to. Hover a row to see the parent.";
3870
- panel.appendChild(title);
3871
- panel.appendChild(sub);
3872
- const selected = /* @__PURE__ */ new Set();
3873
- const footer = doc.createElement("div");
3874
- footer.style.cssText = "margin:10px 0;font-weight:600;";
3875
- const segMatches = (scope, info) => {
3876
- try {
3877
- if (info.testId) return Array.from(scope.querySelectorAll(`[data-testid=${JSON.stringify(info.testId)}]`));
3878
- if (info.id) return Array.from(scope.querySelectorAll(`#${doc.defaultView.CSS.escape(info.id)}`));
3879
- const nodes = Array.from(scope.querySelectorAll(roleSources));
3880
- if (nodes.length > 2e3) return [];
3881
- return nodes.filter(
3882
- (n) => roleOf(n) === info.role && (!info.ariaLabel || n.getAttribute && n.getAttribute("aria-label") === info.ariaLabel)
3883
- );
3884
- } catch {
3885
- return [];
4375
+ if (selfFile === null || file === selfFile) {
4376
+ selfFile ??= file;
4377
+ prevWasCaptureModule = /[\\/]locator-healing\.[a-z]+$/i.test(file);
4378
+ continue;
3886
4379
  }
3887
- };
3888
- const chainCount = () => {
3889
- const chosen = rows.filter((_, i) => selected.has(i)).sort((a, b) => b.info.depth - a.info.depth);
3890
- if (chosen.length === 0) return -1;
3891
- let scopes = [doc];
3892
- for (const row of chosen) {
3893
- const next = [];
3894
- for (const s of scopes) next.push(...segMatches(s, row.info));
3895
- scopes = next.slice(0, 200);
3896
- if (scopes.length === 0) return 0;
4380
+ if (/[\\/]locator-healing\.[a-z]+$/i.test(file)) {
4381
+ prevWasCaptureModule = true;
4382
+ continue;
3897
4383
  }
3898
- let total = 0;
3899
- for (const s of scopes) {
3900
- const c = leafMatches(s);
3901
- if (c > 0) total += c;
3902
- if (total > 50) return total;
4384
+ if (prevWasCaptureModule && /[\\/](?:capture-)?fixtures\.[a-z]+$/i.test(file)) {
4385
+ prevWasCaptureModule = false;
4386
+ continue;
3903
4387
  }
3904
- return total;
3905
- };
3906
- const refreshFooter = () => {
3907
- if (selected.size === 0) {
3908
- footer.textContent = "No parents selected \u2014 standard alternatives only.";
3909
- footer.style.color = "#9ca3af";
3910
- g.__piwiPickChainCount = void 0;
3911
- return;
4388
+ if (/[\\/]node_modules[\\/]/.test(file)) {
4389
+ prevWasCaptureModule = false;
4390
+ continue;
3912
4391
  }
3913
- const c = chainCount();
3914
- g.__piwiPickChainCount = c;
3915
- if (c === 1) {
3916
- footer.textContent = "\u2713 Selection matches exactly 1 element";
3917
- footer.style.color = "#4ade80";
3918
- } else {
3919
- footer.textContent = c < 0 ? "Match count unavailable" : `\u2717 Selection matches ${c} elements`;
3920
- footer.style.color = "#fbbf24";
4392
+ let rel = file;
4393
+ try {
4394
+ rel = path15.relative(process.cwd(), file);
4395
+ } catch {
3921
4396
  }
4397
+ rel = rel.split(path15.sep).join("/");
4398
+ if (rel.startsWith("./")) rel = rel.slice(2);
4399
+ return `${rel}:${m[3]}:${m[4]}`;
4400
+ }
4401
+ return null;
4402
+ }
4403
+
4404
+ // src/internal/capture/inspect-on-failure.ts
4405
+ function isCi(ci) {
4406
+ return ci !== void 0 && ci !== "" && ci !== "false";
4407
+ }
4408
+ function shouldInspectOnFailure(gate) {
4409
+ if (gate.enabled !== "true") return false;
4410
+ if (isCi(gate.ci)) return false;
4411
+ if (gate.headless !== false) return false;
4412
+ if (gate.status !== "failed" && gate.status !== "timedOut") return false;
4413
+ if (gate.status === gate.expectedStatus) return false;
4414
+ return gate.retry >= gate.retries;
4415
+ }
4416
+ function environmentalSkipReason(gate) {
4417
+ if (gate.enabled !== "true") return null;
4418
+ if (gate.status !== "failed" && gate.status !== "timedOut") return null;
4419
+ if (gate.status === gate.expectedStatus) return null;
4420
+ if (isCi(gate.ci)) return "running under CI \u2014 this is a headed, local-only feature";
4421
+ if (gate.headless !== false) {
4422
+ return "the browser is headless \u2014 re-run with --headed (or set use: { headless: false })";
4423
+ }
4424
+ return null;
4425
+ }
4426
+ function inspectionGateFromTestInfo(testInfo, enabled = process.env.PIWI_INSPECT_ON_FAIL) {
4427
+ const use = testInfo.project?.use ?? {};
4428
+ return {
4429
+ enabled,
4430
+ ci: process.env.CI,
4431
+ status: testInfo.status,
4432
+ expectedStatus: testInfo.expectedStatus,
4433
+ headless: use.headless,
4434
+ retry: testInfo.retry,
4435
+ retries: testInfo.project?.retries ?? 0
3922
4436
  };
3923
- rows.forEach((row, i) => {
3924
- const line = doc.createElement("label");
3925
- 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"};`;
3926
- const box = doc.createElement("input");
3927
- box.type = "checkbox";
3928
- box.disabled = !row.selectable;
3929
- const text = doc.createElement("span");
3930
- text.style.cssText = "flex:1;min-width:0;";
3931
- const code = doc.createElement("code");
3932
- code.style.cssText = "display:block;font:11px ui-monospace,monospace;color:#e5e7eb;word-break:break-all;";
3933
- code.textContent = `<${row.info.tag}> ${row.hookLabel}`;
3934
- const hint = doc.createElement("span");
3935
- hint.style.cssText = "color:#9ca3af;";
3936
- hint.textContent = row.selectable ? row.info.scopedLeafCount === 1 ? "contains exactly 1 matching element" : `contains ${row.info.scopedLeafCount ?? "?"} matching elements` : "add a data-testid to make this usable";
3937
- text.appendChild(code);
3938
- text.appendChild(hint);
3939
- line.appendChild(box);
3940
- line.appendChild(text);
3941
- line.addEventListener("mouseenter", () => {
3942
- const r = row.node.getBoundingClientRect();
3943
- outline.style.display = "block";
3944
- outline.style.left = r.left + "px";
3945
- outline.style.top = r.top + "px";
3946
- outline.style.width = r.width + "px";
3947
- outline.style.height = r.height + "px";
3948
- });
3949
- line.addEventListener("mouseleave", () => {
3950
- outline.style.display = "none";
3951
- });
3952
- box.addEventListener("change", () => {
3953
- if (box.checked) selected.add(i);
3954
- else selected.delete(i);
3955
- refreshFooter();
3956
- });
3957
- panel.appendChild(line);
3958
- });
3959
- panel.appendChild(footer);
3960
- const cleanup = () => {
3961
- doc.removeEventListener("keydown", onKey, true);
3962
- panel.remove();
3963
- outline.remove();
3964
- pickedOutline.remove();
3965
- };
3966
- const done = (state) => {
3967
- g.__piwiPickAnchors = state === "done" ? rows.filter((_, i) => selected.has(i)).map((r) => r.info) : [];
3968
- g.__piwiAnchorState = state;
3969
- cleanup();
3970
- };
3971
- const onKey = (e) => {
3972
- if (e.key !== "Escape") return;
3973
- e.preventDefault();
3974
- e.stopImmediatePropagation();
3975
- done("skipped");
3976
- };
3977
- const buttonRow = doc.createElement("div");
3978
- buttonRow.style.cssText = "display:flex;gap:8px;margin-top:4px;";
3979
- const useBtn = doc.createElement("button");
3980
- useBtn.style.cssText = "flex:1;background:#7c3aed;color:#fff;border:none;border-radius:6px;padding:8px;cursor:pointer;font:600 12px system-ui;";
3981
- useBtn.textContent = "Use selected parents";
3982
- useBtn.addEventListener("click", (e) => {
3983
- e.preventDefault();
3984
- e.stopImmediatePropagation();
3985
- done(selected.size > 0 ? "done" : "skipped");
3986
- });
3987
- const skipBtn = doc.createElement("button");
3988
- skipBtn.style.cssText = "background:none;border:1px solid #374151;color:#9ca3af;border-radius:6px;padding:8px 10px;cursor:pointer;font:12px system-ui;";
3989
- skipBtn.textContent = "Skip (Esc)";
3990
- skipBtn.addEventListener("click", (e) => {
3991
- e.preventDefault();
3992
- e.stopImmediatePropagation();
3993
- done("skipped");
3994
- });
3995
- buttonRow.appendChild(useBtn);
3996
- buttonRow.appendChild(skipBtn);
3997
- panel.appendChild(buttonRow);
3998
- refreshFooter();
3999
- g.__piwiAnchorCleanup = cleanup;
4000
- doc.addEventListener("keydown", onKey, true);
4001
- doc.body.appendChild(pickedOutline);
4002
- doc.body.appendChild(outline);
4003
- doc.body.appendChild(panel);
4004
4437
  }
4005
- function showPickerChoices(arg) {
4006
- const g = globalThis;
4007
- const doc = g.document;
4008
- if (!doc || !doc.body) {
4009
- g.__piwiPickChoice = -1;
4010
- return;
4438
+
4439
+ // src/internal/capture/pick-on-failure.ts
4440
+ var path16 = __toESM(require("path"));
4441
+ var ANSI_RE = /\[[0-9;]*m/g;
4442
+ function endOfString(s, start) {
4443
+ const q = s[start];
4444
+ for (let i = start + 1; i < s.length; i++) {
4445
+ if (s[i] === "\\") {
4446
+ i++;
4447
+ continue;
4448
+ }
4449
+ if (s[i] === q) return i;
4450
+ }
4451
+ return s.length - 1;
4452
+ }
4453
+ function matchBrace(s, start) {
4454
+ let depth = 0;
4455
+ for (let i = start; i < s.length; i++) {
4456
+ if (s[i] === "{") depth++;
4457
+ else if (s[i] === "}" && --depth === 0) return i;
4458
+ }
4459
+ return s.length - 1;
4460
+ }
4461
+ function parseOptions(src) {
4462
+ const obj = {};
4463
+ const re = /(\w+)\s*:\s*('(?:\\.|[^'])*'|"(?:\\.|[^"])*"|true|false|-?\d+)/g;
4464
+ let m;
4465
+ while ((m = re.exec(src)) !== null) {
4466
+ const key = m[1];
4467
+ const raw = m[2];
4468
+ if (raw === "true") obj[key] = true;
4469
+ else if (raw === "false") obj[key] = false;
4470
+ else if (/^-?\d+$/.test(raw)) obj[key] = Number(raw);
4471
+ else obj[key] = raw.slice(1, -1).replace(/\\(.)/g, "$1");
4472
+ }
4473
+ return obj;
4474
+ }
4475
+ function parseArgs(inner) {
4476
+ const args = [];
4477
+ let i = 0;
4478
+ while (i < inner.length) {
4479
+ const c = inner[i];
4480
+ if (c === " " || c === ",") {
4481
+ i++;
4482
+ continue;
4483
+ }
4484
+ if (c === "'" || c === '"') {
4485
+ const end = endOfString(inner, i);
4486
+ args.push(inner.slice(i + 1, end).replace(/\\(.)/g, "$1"));
4487
+ i = end + 1;
4488
+ continue;
4489
+ }
4490
+ if (c === "{") {
4491
+ const end = matchBrace(inner, i);
4492
+ args.push(parseOptions(inner.slice(i, end + 1)));
4493
+ i = end + 1;
4494
+ continue;
4495
+ }
4496
+ i++;
4011
4497
  }
4012
- const Z = 2147483600;
4013
- const wrap = doc.createElement("div");
4014
- 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;`;
4015
- const panel = doc.createElement("div");
4016
- 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);";
4017
- const hlLocator = (expr) => {
4018
- const escHtml = (s) => s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
4019
- const re = /('(?:\\.|[^'])*'|"(?:\\.|[^"])*")|([A-Za-z_$][\w$]*)(?=\s*\()|([A-Za-z_$][\w$]*)(?=\s*:)|(true|false|null|\d+)|([{}(),.])/g;
4020
- let html = "";
4021
- let last = 0;
4022
- let m;
4023
- while ((m = re.exec(expr)) !== null) {
4024
- if (m.index > last) html += escHtml(expr.slice(last, m.index));
4025
- const color = m[1] ? "#4ade80" : m[2] ? "#c084fc" : m[3] ? "#93c5fd" : m[4] ? "#fbbf24" : "#9ca3af";
4026
- html += `<span style="color:${color}">${escHtml(m[0])}</span>`;
4027
- last = re.lastIndex;
4498
+ return args;
4499
+ }
4500
+ function leafExpression(expr) {
4501
+ let depth = 0;
4502
+ let leafStart = 0;
4503
+ for (let i = 0; i < expr.length - 1; i++) {
4504
+ const c = expr[i];
4505
+ if (c === "'" || c === '"') {
4506
+ i = endOfString(expr, i);
4507
+ continue;
4508
+ }
4509
+ if (c === "(") depth++;
4510
+ else if (c === ")") {
4511
+ depth--;
4512
+ if (depth === 0 && expr[i + 1] === ".") leafStart = i + 2;
4028
4513
  }
4029
- if (last < expr.length) html += escHtml(expr.slice(last));
4030
- return html;
4031
- };
4032
- const title = doc.createElement("div");
4033
- title.style.cssText = "font-weight:600;margin-bottom:4px;";
4034
- title.textContent = arg.failing ? "Pick a replacement locator" : "Pick a locator";
4035
- const sub = doc.createElement("div");
4036
- sub.style.cssText = "color:#9ca3af;margin-bottom:12px;";
4037
- if (arg.failing) {
4038
- sub.innerHTML = `Replaces <code style="font-family:ui-monospace,Menlo,monospace">${hlLocator(arg.failing)}</code> \u2014 ranked by stability score.`;
4039
- } else {
4040
- sub.textContent = "For the element you picked \u2014 ranked by stability score.";
4041
4514
  }
4042
- panel.appendChild(title);
4043
- panel.appendChild(sub);
4044
- const done = (choice) => {
4045
- g.__piwiPickChoice = choice;
4046
- doc.removeEventListener("keydown", onKey, true);
4047
- wrap.remove();
4048
- };
4049
- const onKey = (e) => {
4050
- if (e.key !== "Escape") return;
4051
- e.preventDefault();
4052
- e.stopImmediatePropagation();
4053
- done(-1);
4054
- };
4055
- arg.choices.forEach((c, i) => {
4056
- const btn = doc.createElement("button");
4057
- btn.style.cssText = "display:flex;justify-content:space-between;align-items:center;gap:12px;width:100%;text-align:left;background:#1f2937;color:#e5e7eb;border:1px solid #374151;border-radius:6px;padding:8px 12px;margin:0 0 8px;cursor:pointer;font:12px/1.5 ui-monospace,SFMono-Regular,Menlo,monospace;";
4058
- const code = doc.createElement("span");
4059
- code.innerHTML = hlLocator(c.locator);
4060
- code.style.cssText = "word-break:break-all;";
4061
- const score = doc.createElement("span");
4062
- score.textContent = String(c.score);
4063
- score.style.cssText = "color:#a78bfa;flex-shrink:0;";
4064
- btn.appendChild(code);
4065
- btn.appendChild(score);
4066
- btn.addEventListener("click", (e) => {
4067
- e.preventDefault();
4068
- e.stopImmediatePropagation();
4069
- done(i);
4070
- });
4071
- panel.appendChild(btn);
4072
- });
4073
- const skip = doc.createElement("button");
4074
- skip.style.cssText = "background:none;border:none;color:#9ca3af;cursor:pointer;padding:6px 0 0;font:12px system-ui,sans-serif;";
4075
- skip.textContent = "Skip \u2014 keep the failure as-is (Esc)";
4076
- skip.addEventListener("click", (e) => {
4077
- e.preventDefault();
4078
- e.stopImmediatePropagation();
4079
- done(-1);
4080
- });
4081
- panel.appendChild(skip);
4082
- doc.addEventListener("keydown", onKey, true);
4083
- wrap.appendChild(panel);
4084
- doc.body.appendChild(wrap);
4515
+ return expr.slice(leafStart);
4516
+ }
4517
+ function parseLeafLocatorExpression(rawExpr) {
4518
+ const expr = leafExpression(rawExpr.trim());
4519
+ const m = /^([A-Za-z]+)\((.*)\)$/s.exec(expr);
4520
+ if (!m) return null;
4521
+ return { method: m[1], args: parseArgs(m[2].trim()) };
4522
+ }
4523
+ function deriveFailedLocator(testInfo) {
4524
+ const info = testInfo;
4525
+ const errors = info.errors && info.errors.length > 0 ? info.errors : info.error ? [info.error] : [];
4526
+ for (const err of errors) {
4527
+ const text = `${err.message ?? ""}
4528
+ ${err.stack ?? ""}`.replace(ANSI_RE, "");
4529
+ const line = /^\s*Locator:\s*(.+)$/m.exec(text);
4530
+ if (!line) continue;
4531
+ const parsed = parseLeafLocatorExpression(line[1].trim());
4532
+ if (!parsed) continue;
4533
+ const loc = err.location;
4534
+ const location = loc ? `${path16.relative(process.cwd(), loc.file).split(path16.sep).join("/")}:${loc.line}:${loc.column}` : null;
4535
+ return { method: parsed.method, args: parsed.args, location };
4536
+ }
4537
+ return null;
4085
4538
  }
4086
4539
  async function cleanupPicker(page) {
4087
4540
  try {
@@ -4109,7 +4562,8 @@ async function runLocatorPicker(page, testInfo, failed, probe) {
4109
4562
  `
4110
4563
  [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).`
4111
4564
  );
4112
- await page.evaluate(installPickerOverlay, { failing: rendered });
4565
+ const overlayArg = { transport: "global", failing: rendered };
4566
+ await page.evaluate(installPickerOverlay, overlayArg);
4113
4567
  await page.waitForFunction(() => globalThis.__piwiPickState !== void 0, void 0, {
4114
4568
  timeout: 0,
4115
4569
  polling: 250
@@ -4130,9 +4584,9 @@ async function runLocatorPicker(page, testInfo, failed, probe) {
4130
4584
  if (role) {
4131
4585
  const probeArg = probe.arg;
4132
4586
  await page.evaluate(showAnchorPicker, {
4133
- tagRoles: probeArg.tagRoles,
4134
- inputRoles: probeArg.inputRoles,
4135
- roleSources: probeArg.roleSources,
4587
+ tagRoles: probeArg.tagRoles ?? {},
4588
+ inputRoles: probeArg.inputRoles ?? {},
4589
+ roleSources: probeArg.roleSources ?? "",
4136
4590
  leafRole: role,
4137
4591
  leafLevel: level,
4138
4592
  leafTestId: attrs.attributes["data-testid"] ?? null
@@ -4497,7 +4951,12 @@ var CAPTURED_ATTRS_ARG = {
4497
4951
  inputRoles: INPUT_TYPE_TO_ROLE,
4498
4952
  // '[role]' plus every tag the maps can resolve (input/select are handled by
4499
4953
  // special-cased logic in the probe, so add them explicitly).
4500
- roleSources: [.../* @__PURE__ */ new Set(["[role]", "input", "select", ...Object.keys(TAG_TO_ROLE)])].join(",")
4954
+ roleSources: [.../* @__PURE__ */ new Set(["[role]", "input", "select", ...Object.keys(TAG_TO_ROLE)])].join(","),
4955
+ // The reporter always wants ancestor-anchored alternatives (the picker's
4956
+ // anchors step and generateAnchoredAlternatives both need them); it derives
4957
+ // the accessible name itself, so the probe's own labelText is unneeded.
4958
+ includeStructural: true,
4959
+ includeLabelText: false
4501
4960
  };
4502
4961
  async function ariaSnapshotBestEffort(target, timeout) {
4503
4962
  if (typeof target.ariaSnapshot !== "function") return null;
@@ -4517,156 +4976,6 @@ async function ariaSnapshotBestEffort(target, timeout) {
4517
4976
  }
4518
4977
  }
4519
4978
  }
4520
- function probeElementAttrs(el, arg) {
4521
- const { keep, tagRoles, inputRoles, roleSources } = arg;
4522
- const attrMap = {};
4523
- for (const key of keep) {
4524
- const v = el.getAttribute(key) ?? el[key];
4525
- attrMap[key] = typeof v === "string" ? v.slice(0, 200) : v ? String(v).slice(0, 200) : null;
4526
- }
4527
- const r = el.getBoundingClientRect();
4528
- const selectorCounts = {};
4529
- try {
4530
- const doc = el.ownerDocument;
4531
- const cssEsc = (s) => doc.defaultView.CSS.escape(s);
4532
- const count = (sel) => {
4533
- try {
4534
- return doc.querySelectorAll(sel).length;
4535
- } catch {
4536
- return void 0;
4537
- }
4538
- };
4539
- if (attrMap["data-testid"]) {
4540
- selectorCounts.testId = count(`[data-testid=${JSON.stringify(attrMap["data-testid"])}]`);
4541
- }
4542
- if (attrMap["id"]) selectorCounts.id = count(`#${cssEsc(attrMap["id"])}`);
4543
- if (attrMap["name"]) selectorCounts.name = count(`[name=${JSON.stringify(attrMap["name"])}]`);
4544
- const classList = (attrMap["class"] || "").split(/\s+/).filter((c) => c.length > 1).slice(0, 10);
4545
- if (classList.length > 0) {
4546
- const classCounts = {};
4547
- for (const cls of classList) {
4548
- const n = count(`.${cssEsc(cls)}`);
4549
- if (n !== void 0) classCounts[cls] = n;
4550
- }
4551
- selectorCounts.classes = classCounts;
4552
- }
4553
- } catch {
4554
- }
4555
- let rolePosition = null;
4556
- const ancestors = [];
4557
- try {
4558
- const doc = el.ownerDocument;
4559
- const cssEsc = (s) => doc.defaultView.CSS.escape(s);
4560
- const count = (sel) => {
4561
- try {
4562
- return doc.querySelectorAll(sel).length;
4563
- } catch {
4564
- return void 0;
4565
- }
4566
- };
4567
- const roleOf = (n) => {
4568
- const explicit = n.getAttribute("role");
4569
- if (explicit) return explicit;
4570
- const tag = (n.tagName || "").toLowerCase();
4571
- if (tag === "input") return inputRoles[(n.getAttribute("type") || "text").toLowerCase()] ?? "textbox";
4572
- if (tag === "select") return n.getAttribute("multiple") != null ? "listbox" : "combobox";
4573
- if (tag === "a") return n.getAttribute("href") != null ? "link" : null;
4574
- return tagRoles[tag] ?? null;
4575
- };
4576
- const levelOf = (n) => {
4577
- const m = /^h([1-6])$/.exec((n.tagName || "").toLowerCase());
4578
- if (m) return Number(m[1]);
4579
- const al = n.getAttribute("aria-level");
4580
- return al && /^\d+$/.test(al) ? Number(al) : null;
4581
- };
4582
- const targetRole = roleOf(el);
4583
- const targetLevel = targetRole === "heading" ? levelOf(el) : null;
4584
- if (targetRole) {
4585
- const nodes = doc.querySelectorAll(roleSources);
4586
- if (nodes.length <= 4e3) {
4587
- let roleCountAll = 0;
4588
- let index = -1;
4589
- let levelCount = 0;
4590
- for (let i = 0; i < nodes.length; i++) {
4591
- const n = nodes[i];
4592
- if (roleOf(n) !== targetRole) continue;
4593
- if (n === el) index = roleCountAll;
4594
- roleCountAll++;
4595
- if (targetLevel != null && levelOf(n) === targetLevel) levelCount++;
4596
- }
4597
- if (index !== -1) {
4598
- rolePosition = {
4599
- role: targetRole,
4600
- count: roleCountAll,
4601
- index,
4602
- ...targetLevel != null ? { levelCount } : {}
4603
- };
4604
- }
4605
- const CONTAINER_TAGS = ["form", "nav", "main", "article", "section", "dialog", "table"];
4606
- const docRoleCount = (role) => {
4607
- let c = 0;
4608
- for (let i = 0; i < nodes.length; i++) if (roleOf(nodes[i]) === role) c++;
4609
- return c;
4610
- };
4611
- let node = el.parentElement;
4612
- let depth = 0;
4613
- while (node && depth < 12 && ancestors.length < 4) {
4614
- depth++;
4615
- const tag = (node.tagName || "").toLowerCase();
4616
- if (tag === "body" || tag === "html") break;
4617
- const testId = node.getAttribute("data-testid");
4618
- const id = node.getAttribute("id");
4619
- const explicitRole = node.getAttribute("role");
4620
- const ariaLabel = node.getAttribute("aria-label");
4621
- const anchorRole = explicitRole || (CONTAINER_TAGS.includes(tag) ? tagRoles[tag] : null) || null;
4622
- if (testId || id || anchorRole || ariaLabel) {
4623
- const scoped = node.querySelectorAll(roleSources);
4624
- let scopedRoleCount = 0;
4625
- if (scoped.length <= 2e3) {
4626
- for (let i = 0; i < scoped.length; i++) {
4627
- const n = scoped[i];
4628
- if (roleOf(n) !== targetRole) continue;
4629
- if (targetLevel != null && levelOf(n) !== targetLevel) continue;
4630
- scopedRoleCount++;
4631
- }
4632
- } else {
4633
- scopedRoleCount = -1;
4634
- }
4635
- ancestors.push({
4636
- tag,
4637
- depth,
4638
- testId: testId || null,
4639
- id: id || null,
4640
- role: explicitRole || null,
4641
- ariaLabel: ariaLabel || null,
4642
- ...scopedRoleCount >= 0 ? { scopedRoleCount } : {},
4643
- ...testId ? { testIdCount: count(`[data-testid=${JSON.stringify(testId)}]`) } : {},
4644
- ...id ? { idCount: count(`#${cssEsc(id)}`) } : {},
4645
- ...anchorRole ? { roleCount: docRoleCount(anchorRole) } : {}
4646
- });
4647
- }
4648
- node = node.parentElement;
4649
- }
4650
- }
4651
- }
4652
- } catch {
4653
- }
4654
- return {
4655
- tagName: el.tagName?.toLowerCase?.() ?? "unknown",
4656
- attributes: attrMap,
4657
- // Collapse whitespace so multi-line text can't produce a getByText
4658
- // suggestion with literal newlines in it.
4659
- textContent: (el.textContent || "").replace(/\s+/g, " ").trim().slice(0, 80),
4660
- center: {
4661
- x: Math.round(r.x + r.width / 2),
4662
- y: Math.round(r.y + r.height / 2)
4663
- },
4664
- hasLabel: !!(el.labels && el.labels.length > 0),
4665
- selectorCounts,
4666
- rolePosition,
4667
- ancestors
4668
- };
4669
- }
4670
4979
  function startElementCapture(sink, target, seq, callerLocation, used) {
4671
4980
  const probe = target.evaluate(probeElementAttrs, CAPTURED_ATTRS_ARG);
4672
4981
  const settledProbe = probe.then(