@scrape-admin/element-picker 0.0.0-stage → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +15 -2
- package/dist/index.cjs +463 -0
- package/dist/index.d.cts +102 -0
- package/dist/index.d.mts +102 -0
- package/dist/index.d.ts +102 -0
- package/dist/index.mjs +448 -0
- package/dist/inject.d.mts +2 -0
- package/dist/inject.d.ts +2 -0
- package/dist/inject.mjs +2 -0
- package/package.json +43 -3
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Hareland
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,16 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @scrape-admin/element-picker
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Framework-agnostic DOM element picking, shared by the profile recorder extension and the web profile playground.
|
|
4
|
+
|
|
5
|
+
- `@scrape-admin/element-picker` (source) — stable selector generation (`buildPickedElement`, `buildCandidates`,
|
|
6
|
+
`suggestName`, `sampleOf`, `describeElement`, `cssEscape`, …), the `PickedElement` / `SelectorCandidate` types, and
|
|
7
|
+
`createPicker(window)` / `installPicker(window)`.
|
|
8
|
+
- `@scrape-admin/element-picker/inject` (built, `dist/inject.mjs`) — `PICKER_SCRIPT: string`, a self-contained IIFE.
|
|
9
|
+
Evaluating it in a page (e.g. puppeteer `page.evaluate` / `evaluateOnNewDocument`) installs
|
|
10
|
+
`window.__scrapeAdminPicker = { version, at(x, y), highlight(selector), describe() }`. Boxes are viewport CSS pixels;
|
|
11
|
+
the page DOM is never modified.
|
|
12
|
+
|
|
13
|
+
```bash
|
|
14
|
+
pnpm --filter @scrape-admin/element-picker build # required before importing ./inject
|
|
15
|
+
pnpm --filter @scrape-admin/element-picker test
|
|
16
|
+
```
|
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,463 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const MAX_CANDIDATES = 3;
|
|
4
|
+
const TEST_ATTRIBUTES = ["data-testid", "data-test", "data-cy", "data-qa"];
|
|
5
|
+
function cssEscape(value) {
|
|
6
|
+
const string = String(value);
|
|
7
|
+
let result = "";
|
|
8
|
+
for (let index = 0; index < string.length; index++) {
|
|
9
|
+
const code = string.charCodeAt(index);
|
|
10
|
+
const char = string.charAt(index);
|
|
11
|
+
if (code === 0) {
|
|
12
|
+
result += "\uFFFD";
|
|
13
|
+
} else if (code >= 1 && code <= 31 || code === 127 || index === 0 && code >= 48 && code <= 57 || index === 1 && code >= 48 && code <= 57 && string.charCodeAt(0) === 45) {
|
|
14
|
+
result += `\\${code.toString(16)} `;
|
|
15
|
+
} else if (index === 0 && code === 45 && string.length === 1) {
|
|
16
|
+
result += `\\${char}`;
|
|
17
|
+
} else if (code >= 128 || code === 45 || code === 95 || code >= 48 && code <= 57 || code >= 65 && code <= 90 || code >= 97 && code <= 122) {
|
|
18
|
+
result += char;
|
|
19
|
+
} else {
|
|
20
|
+
result += `\\${char}`;
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
return result;
|
|
24
|
+
}
|
|
25
|
+
function cssString(value) {
|
|
26
|
+
return `"${value.replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/\n/g, "\\a ").replace(/\r/g, "\\d ")}"`;
|
|
27
|
+
}
|
|
28
|
+
function isGeneratedId(id) {
|
|
29
|
+
if (!id || id.length > 50) return true;
|
|
30
|
+
if (id.startsWith(":")) return true;
|
|
31
|
+
if (/^(?:ember|radix|headlessui|react-aria|reactid|mui|downshift|rc|chakra|__next|yui_|ext-gen)[-_:]?\d*/i.test(id) && /[\d\-_:]/.test(id)) return true;
|
|
32
|
+
if (/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(id)) return true;
|
|
33
|
+
if (/^[0-9a-f]{12,}$/i.test(id)) return true;
|
|
34
|
+
if (/\d{5,}/.test(id)) return true;
|
|
35
|
+
const digits = (id.match(/\d/g) ?? []).length;
|
|
36
|
+
if (id.length >= 4 && digits / id.length >= 0.4) return true;
|
|
37
|
+
return false;
|
|
38
|
+
}
|
|
39
|
+
const TAILWIND_PREFIXES = "(?:[whpmz]|min-w|min-h|max-w|max-h|px|py|pt|pb|pl|pr|mx|my|mt|mb|ml|mr|gap|gap-x|gap-y|space-x|space-y|top|left|right|bottom|inset|text|bg|border|rounded|font|leading|tracking|opacity|shadow|ring|flex|grid|col|row|basis|grow|shrink|size|order|divide|fill|stroke|outline|object|overflow|cursor|duration|ease|aspect|translate|rotate|scale|items|justify|self|content|place)";
|
|
40
|
+
const TAILWIND_VALUE = "(?:[\\d[]|(?:px|auto|full|screen|min|max|fit|none|xs|sm|md|lg|xl|base|center|left|right|justify|start|end|between|around|bold|semibold|medium|light|normal|italic|white|black|transparent|current|inherit)$|[a-z]+-\\d{2,3}$)";
|
|
41
|
+
const TAILWIND_UTILITY = new RegExp(`^-?${TAILWIND_PREFIXES}-${TAILWIND_VALUE}`);
|
|
42
|
+
const TAILWIND_BARE = /* @__PURE__ */ new Set([
|
|
43
|
+
"flex",
|
|
44
|
+
"grid",
|
|
45
|
+
"block",
|
|
46
|
+
"inline",
|
|
47
|
+
"inline-block",
|
|
48
|
+
"inline-flex",
|
|
49
|
+
"hidden",
|
|
50
|
+
"relative",
|
|
51
|
+
"absolute",
|
|
52
|
+
"fixed",
|
|
53
|
+
"sticky",
|
|
54
|
+
"static",
|
|
55
|
+
"truncate",
|
|
56
|
+
"underline",
|
|
57
|
+
"uppercase",
|
|
58
|
+
"lowercase",
|
|
59
|
+
"capitalize",
|
|
60
|
+
"italic",
|
|
61
|
+
"border",
|
|
62
|
+
"rounded",
|
|
63
|
+
"shadow",
|
|
64
|
+
"container",
|
|
65
|
+
"sr-only",
|
|
66
|
+
"transition",
|
|
67
|
+
"grow",
|
|
68
|
+
"shrink",
|
|
69
|
+
"contents",
|
|
70
|
+
"table",
|
|
71
|
+
"visible",
|
|
72
|
+
"invisible",
|
|
73
|
+
"italic"
|
|
74
|
+
]);
|
|
75
|
+
const STATE_CLASSES = /^(?:active|selected|open|opened|closed|show|shown|hide|visible|hover|hovered|focus|focused|disabled|checked|loading|loaded|collapsed|expanded|current|is-[\w-]+|has-[\w-]+|ng-[\w-]+|ember-[\w-]+|v-[\w-]+)$/;
|
|
76
|
+
function isGeneratedClass(name) {
|
|
77
|
+
if (!name || name.length < 2 || name.length > 40) return true;
|
|
78
|
+
if (/[:[\]/%#!@]/.test(name)) return true;
|
|
79
|
+
if (TAILWIND_BARE.has(name) || TAILWIND_UTILITY.test(name)) return true;
|
|
80
|
+
if (/^_[\w-]{4,}$/.test(name)) return true;
|
|
81
|
+
if (/^(?:css|sc|jsx|emotion|styled|svelte|astro|chakra|mui|makeStyles|jss)-/i.test(name)) return true;
|
|
82
|
+
if (/^[a-z]{1,3}-?\d+$/i.test(name) && /\d/.test(name)) return true;
|
|
83
|
+
if (/__[\w-]{5,}$/.test(name) && /[A-Z\d]/.test(name.slice(name.lastIndexOf("__") + 2))) return true;
|
|
84
|
+
if (/^(?=.*\d)(?=.*[a-z])[a-z0-9]{6,}$/i.test(name)) return true;
|
|
85
|
+
if (/^[A-Z0-9]{5,}$/i.test(name) && /[a-z]/.test(name) && /[A-Z]/.test(name) && !/^[A-Z]?[a-z]+(?:[A-Z][a-z]+)*$/.test(name)) return true;
|
|
86
|
+
if (STATE_CLASSES.test(name)) return true;
|
|
87
|
+
return false;
|
|
88
|
+
}
|
|
89
|
+
function stableClasses(el) {
|
|
90
|
+
const raw = el.getAttribute("class");
|
|
91
|
+
if (!raw) return [];
|
|
92
|
+
return raw.split(/\s+/).filter((name) => name && !isGeneratedClass(name));
|
|
93
|
+
}
|
|
94
|
+
function tagOf(el) {
|
|
95
|
+
return el.tagName.toLowerCase();
|
|
96
|
+
}
|
|
97
|
+
function countMatches(doc, selector) {
|
|
98
|
+
try {
|
|
99
|
+
return doc.querySelectorAll(selector).length;
|
|
100
|
+
} catch {
|
|
101
|
+
return 0;
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
function matchesElement(doc, selector, el) {
|
|
105
|
+
try {
|
|
106
|
+
const list = doc.querySelectorAll(selector);
|
|
107
|
+
return { count: list.length, includes: Array.prototype.includes.call(list, el) };
|
|
108
|
+
} catch {
|
|
109
|
+
return { count: 0, includes: false };
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
function safeMatches(el, selector) {
|
|
113
|
+
try {
|
|
114
|
+
return el.matches(selector);
|
|
115
|
+
} catch {
|
|
116
|
+
return false;
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
function testAttributeSelector(el) {
|
|
120
|
+
const out = [];
|
|
121
|
+
for (const attr of TEST_ATTRIBUTES) {
|
|
122
|
+
const value = el.getAttribute(attr);
|
|
123
|
+
if (value && value.length <= 80) out.push({ selector: `[${attr}=${cssString(value)}]`, strategy: attr });
|
|
124
|
+
}
|
|
125
|
+
return out;
|
|
126
|
+
}
|
|
127
|
+
function stableAttributeSelectors(el) {
|
|
128
|
+
const tag = tagOf(el);
|
|
129
|
+
const out = [];
|
|
130
|
+
const label = el.getAttribute("aria-label");
|
|
131
|
+
if (label && label.length <= 80) out.push({ selector: `${tag}[aria-label=${cssString(label)}]`, strategy: "aria-label" });
|
|
132
|
+
const name = el.getAttribute("name");
|
|
133
|
+
if (name && name.length <= 60) out.push({ selector: `${tag}[name=${cssString(name)}]`, strategy: "name" });
|
|
134
|
+
const itemprop = el.getAttribute("itemprop");
|
|
135
|
+
if (itemprop && itemprop.length <= 60) out.push({ selector: `[itemprop=${cssString(itemprop)}]`, strategy: "itemprop" });
|
|
136
|
+
const role = el.getAttribute("role");
|
|
137
|
+
if (role && label && label.length <= 80) {
|
|
138
|
+
out.push({ selector: `[role=${cssString(role)}][aria-label=${cssString(label)}]`, strategy: "role" });
|
|
139
|
+
}
|
|
140
|
+
if (tag === "a") {
|
|
141
|
+
const href = el.getAttribute("href");
|
|
142
|
+
if (href && href.length <= 60 && !href.startsWith("javascript:") && !href.includes("?") && /^(?:[/#.]|[\w-]+\/|https?:\/\/[^/]+\/?$)/.test(href)) {
|
|
143
|
+
out.push({ selector: `a[href=${cssString(href)}]`, strategy: "href" });
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
return out;
|
|
147
|
+
}
|
|
148
|
+
function classSelectors(el) {
|
|
149
|
+
const classes = stableClasses(el);
|
|
150
|
+
if (!classes.length) return [];
|
|
151
|
+
const tag = tagOf(el);
|
|
152
|
+
const out = [];
|
|
153
|
+
const combined = classes.slice(0, 3).map((name) => `.${cssEscape(name)}`).join("");
|
|
154
|
+
out.push({ selector: `${tag}${combined}`, strategy: "class" });
|
|
155
|
+
for (const name of classes.slice(0, 3)) {
|
|
156
|
+
out.push({ selector: `${tag}.${cssEscape(name)}`, strategy: "class" });
|
|
157
|
+
}
|
|
158
|
+
return out;
|
|
159
|
+
}
|
|
160
|
+
function baseSegment(el) {
|
|
161
|
+
const classes = stableClasses(el).slice(0, 2);
|
|
162
|
+
return `${tagOf(el)}${classes.map((name) => `.${cssEscape(name)}`).join("")}`;
|
|
163
|
+
}
|
|
164
|
+
function segment(el) {
|
|
165
|
+
const base = baseSegment(el);
|
|
166
|
+
const parent = el.parentElement;
|
|
167
|
+
if (!parent) return base;
|
|
168
|
+
const siblings = Array.from(parent.children);
|
|
169
|
+
const ambiguous = siblings.some((sibling) => sibling !== el && safeMatches(sibling, base));
|
|
170
|
+
if (!ambiguous) return base;
|
|
171
|
+
const index = siblings.filter((sibling) => sibling.tagName === el.tagName).indexOf(el) + 1;
|
|
172
|
+
return `${base}:nth-of-type(${index})`;
|
|
173
|
+
}
|
|
174
|
+
function anchorSelector(el, doc) {
|
|
175
|
+
for (const candidate of testAttributeSelector(el)) {
|
|
176
|
+
if (countMatches(doc, candidate.selector) === 1) return candidate.selector;
|
|
177
|
+
}
|
|
178
|
+
const id = el.getAttribute("id");
|
|
179
|
+
if (id && !isGeneratedId(id)) {
|
|
180
|
+
const selector = `#${cssEscape(id)}`;
|
|
181
|
+
if (countMatches(doc, selector) === 1) return selector;
|
|
182
|
+
}
|
|
183
|
+
return null;
|
|
184
|
+
}
|
|
185
|
+
function pathSelector(el, doc, full = false) {
|
|
186
|
+
const segments = [];
|
|
187
|
+
let current = el;
|
|
188
|
+
while (current && current !== doc.documentElement) {
|
|
189
|
+
if (current !== el) {
|
|
190
|
+
const anchor = anchorSelector(current, doc);
|
|
191
|
+
if (anchor) {
|
|
192
|
+
segments.unshift(anchor);
|
|
193
|
+
const selector2 = segments.join(" > ");
|
|
194
|
+
if (countMatches(doc, selector2) === 1) return selector2;
|
|
195
|
+
segments.shift();
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
segments.unshift(segment(current));
|
|
199
|
+
const selector = segments.join(" > ");
|
|
200
|
+
const bare = segments.length === 1 && segments[0]?.includes(":nth-of-type");
|
|
201
|
+
if (!full && !bare && countMatches(doc, selector) === 1) return selector;
|
|
202
|
+
if (current === doc.body) break;
|
|
203
|
+
current = current.parentElement;
|
|
204
|
+
}
|
|
205
|
+
return segments.join(" > ");
|
|
206
|
+
}
|
|
207
|
+
function similarSiblingCount(el) {
|
|
208
|
+
const parent = el.parentElement;
|
|
209
|
+
if (!parent) return 0;
|
|
210
|
+
const base = baseSegment(el);
|
|
211
|
+
return Array.from(parent.children).filter((sibling) => safeMatches(sibling, base)).length;
|
|
212
|
+
}
|
|
213
|
+
function isRepeatedItem(el) {
|
|
214
|
+
const hasClasses = stableClasses(el).length > 0;
|
|
215
|
+
return similarSiblingCount(el) >= (hasClasses ? 2 : 3);
|
|
216
|
+
}
|
|
217
|
+
function repeatedRoots(el, doc) {
|
|
218
|
+
const roots = [];
|
|
219
|
+
let current = el;
|
|
220
|
+
for (let depth = 0; current && current !== doc.body && current !== doc.documentElement && depth < 8; depth++) {
|
|
221
|
+
if (isRepeatedItem(current)) roots.push(current);
|
|
222
|
+
current = current.parentElement;
|
|
223
|
+
}
|
|
224
|
+
return roots;
|
|
225
|
+
}
|
|
226
|
+
function uniqueSelectorFor(el, doc) {
|
|
227
|
+
const anchor = anchorSelector(el, doc);
|
|
228
|
+
if (anchor) return anchor;
|
|
229
|
+
for (const candidate of [...stableAttributeSelectors(el), ...classSelectors(el)]) {
|
|
230
|
+
if (countMatches(doc, candidate.selector) === 1) return candidate.selector;
|
|
231
|
+
}
|
|
232
|
+
return pathSelector(el, doc);
|
|
233
|
+
}
|
|
234
|
+
function repeatedParts(el, root, doc) {
|
|
235
|
+
const parent = root.parentElement;
|
|
236
|
+
if (!parent) return null;
|
|
237
|
+
const parentPart = parent === doc.body || parent === doc.documentElement ? "body" : uniqueSelectorFor(parent, doc);
|
|
238
|
+
const parts = [parentPart, baseSegment(root)];
|
|
239
|
+
const relative = [];
|
|
240
|
+
let current = el;
|
|
241
|
+
while (current && current !== root) {
|
|
242
|
+
relative.unshift(segment(current));
|
|
243
|
+
current = current.parentElement;
|
|
244
|
+
}
|
|
245
|
+
return [...parts, ...relative];
|
|
246
|
+
}
|
|
247
|
+
function queryAll(doc, selector) {
|
|
248
|
+
try {
|
|
249
|
+
return Array.from(doc.querySelectorAll(selector));
|
|
250
|
+
} catch {
|
|
251
|
+
return null;
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
const sameSet = (a, b) => a.length === b.length && a.every((el, i) => el === b[i]);
|
|
255
|
+
function listSelector(el, doc, alternatives = []) {
|
|
256
|
+
for (const root of repeatedRoots(el, doc)) {
|
|
257
|
+
const parts = repeatedParts(el, root, doc);
|
|
258
|
+
if (!parts) continue;
|
|
259
|
+
const set = queryAll(doc, parts.join(" > "));
|
|
260
|
+
if (!set || set.length < 2 || !set.includes(el)) continue;
|
|
261
|
+
const options = [...alternatives];
|
|
262
|
+
for (let start = parts.length - 1; start >= 0; start--) options.push(parts.slice(start).join(" > "));
|
|
263
|
+
const best = options.filter((selector) => {
|
|
264
|
+
const found = queryAll(doc, selector);
|
|
265
|
+
return !!found && sameSet(found, set);
|
|
266
|
+
}).sort((a, b) => a.length - b.length)[0];
|
|
267
|
+
return { selector: best ?? parts.join(" > "), count: set.length };
|
|
268
|
+
}
|
|
269
|
+
return null;
|
|
270
|
+
}
|
|
271
|
+
function buildCandidates(el, doc) {
|
|
272
|
+
const ordered = [];
|
|
273
|
+
ordered.push(...testAttributeSelector(el));
|
|
274
|
+
const id = el.getAttribute("id");
|
|
275
|
+
if (id && !isGeneratedId(id)) ordered.push({ selector: `#${cssEscape(id)}`, strategy: "id" });
|
|
276
|
+
ordered.push(...stableAttributeSelectors(el));
|
|
277
|
+
ordered.push(...classSelectors(el));
|
|
278
|
+
ordered.push({ selector: pathSelector(el, doc), strategy: "path" });
|
|
279
|
+
const seen = /* @__PURE__ */ new Set();
|
|
280
|
+
const unique = [];
|
|
281
|
+
const many = [];
|
|
282
|
+
for (const raw of ordered) {
|
|
283
|
+
if (seen.has(raw.selector)) continue;
|
|
284
|
+
seen.add(raw.selector);
|
|
285
|
+
const { count, includes } = matchesElement(doc, raw.selector, el);
|
|
286
|
+
if (!includes) continue;
|
|
287
|
+
if (count === 1) {
|
|
288
|
+
unique.push({ selector: raw.selector, matchCount: 1, strategy: raw.strategy });
|
|
289
|
+
} else if (raw.strategy !== "path") {
|
|
290
|
+
many.push({ selector: raw.selector, matchCount: count, strategy: "repeated" });
|
|
291
|
+
}
|
|
292
|
+
}
|
|
293
|
+
const repeated = [];
|
|
294
|
+
const list = listSelector(el, doc, many.map((candidate) => candidate.selector));
|
|
295
|
+
if (list) {
|
|
296
|
+
repeated.push({ selector: list.selector, matchCount: list.count, strategy: "repeated" });
|
|
297
|
+
repeated.push(...many.filter((candidate) => candidate.selector !== list.selector));
|
|
298
|
+
}
|
|
299
|
+
if (!unique.length) {
|
|
300
|
+
const fallback = pathSelector(el, doc, true);
|
|
301
|
+
const { count } = matchesElement(doc, fallback, el);
|
|
302
|
+
unique.push({ selector: fallback, matchCount: count, strategy: "path" });
|
|
303
|
+
}
|
|
304
|
+
const wantRepeated = repeated.length > 0 ? 1 : 0;
|
|
305
|
+
return [...unique.slice(0, MAX_CANDIDATES - wantRepeated), ...repeated.slice(0, wantRepeated)];
|
|
306
|
+
}
|
|
307
|
+
function toIdentifier(text) {
|
|
308
|
+
const words = text.normalize("NFKD").replace(/\p{M}/gu, "").replace(/([a-z0-9])([A-Z])/g, "$1 $2").split(/[^A-Z0-9]+/i).filter(Boolean).slice(0, 4);
|
|
309
|
+
if (!words.length) return "";
|
|
310
|
+
const [first, ...rest] = words.map((word) => word.toLowerCase());
|
|
311
|
+
const joined = (first ?? "") + rest.map((word) => word.charAt(0).toUpperCase() + word.slice(1)).join("");
|
|
312
|
+
return /^\d/.test(joined) ? `field${joined.charAt(0).toUpperCase()}${joined.slice(1)}` : joined;
|
|
313
|
+
}
|
|
314
|
+
function suggestName(el) {
|
|
315
|
+
const sources = [
|
|
316
|
+
el.getAttribute("aria-label"),
|
|
317
|
+
el.getAttribute("name"),
|
|
318
|
+
el.getAttribute("placeholder"),
|
|
319
|
+
...TEST_ATTRIBUTES.map((attr) => el.getAttribute(attr)),
|
|
320
|
+
el.getAttribute("itemprop"),
|
|
321
|
+
(() => {
|
|
322
|
+
const id = el.getAttribute("id");
|
|
323
|
+
return id && !isGeneratedId(id) ? id : null;
|
|
324
|
+
})(),
|
|
325
|
+
el.getAttribute("title"),
|
|
326
|
+
el.getAttribute("alt"),
|
|
327
|
+
(() => {
|
|
328
|
+
const text = (el.textContent ?? "").replace(/\s+/g, " ").trim();
|
|
329
|
+
return text.length > 0 && text.length <= 40 && /[A-Z]/i.test(text) ? text : null;
|
|
330
|
+
})(),
|
|
331
|
+
stableClasses(el)[0]
|
|
332
|
+
];
|
|
333
|
+
for (const source of sources) {
|
|
334
|
+
if (!source) continue;
|
|
335
|
+
const name = toIdentifier(source);
|
|
336
|
+
if (name) return name;
|
|
337
|
+
}
|
|
338
|
+
return toIdentifier(tagOf(el)) || "element";
|
|
339
|
+
}
|
|
340
|
+
function sampleOf(el) {
|
|
341
|
+
const text = (el.textContent ?? "").replace(/\s+/g, " ").trim().slice(0, 200);
|
|
342
|
+
const sample = { text };
|
|
343
|
+
const attr = (name) => {
|
|
344
|
+
const value = el.getAttribute(name);
|
|
345
|
+
return value ? value.slice(0, 500) : void 0;
|
|
346
|
+
};
|
|
347
|
+
const href = el.href ?? attr("href");
|
|
348
|
+
if (typeof href === "string" && href) sample.href = href.slice(0, 500);
|
|
349
|
+
const src = el.src ?? attr("src");
|
|
350
|
+
if (typeof src === "string" && src) sample.src = src.slice(0, 500);
|
|
351
|
+
const tag = tagOf(el);
|
|
352
|
+
if (tag === "input" || tag === "textarea" || tag === "select") {
|
|
353
|
+
const value = el.value;
|
|
354
|
+
if (typeof value === "string" && value) sample.value = value.slice(0, 200);
|
|
355
|
+
}
|
|
356
|
+
return sample;
|
|
357
|
+
}
|
|
358
|
+
function describeElement(el) {
|
|
359
|
+
const classes = stableClasses(el);
|
|
360
|
+
return `${tagOf(el)}${classes.length ? `.${classes[0]}` : ""}`;
|
|
361
|
+
}
|
|
362
|
+
function buildPickedElement(el, doc) {
|
|
363
|
+
const tagName = tagOf(el);
|
|
364
|
+
return {
|
|
365
|
+
tagName,
|
|
366
|
+
isInput: ["input", "textarea", "select"].includes(tagName),
|
|
367
|
+
candidates: buildCandidates(el, doc),
|
|
368
|
+
suggestedName: suggestName(el),
|
|
369
|
+
sample: sampleOf(el)
|
|
370
|
+
};
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
const PICKER_GLOBAL = "__scrapeAdminPicker";
|
|
374
|
+
const PICKER_VERSION = 1;
|
|
375
|
+
const PICKER_MAX_BOXES = 150;
|
|
376
|
+
|
|
377
|
+
function boxOf(el) {
|
|
378
|
+
const rect = el.getBoundingClientRect();
|
|
379
|
+
return { x: rect.x, y: rect.y, width: rect.width, height: rect.height };
|
|
380
|
+
}
|
|
381
|
+
function errorMessage(error, fallback) {
|
|
382
|
+
return error instanceof Error && error.message ? error.message : fallback;
|
|
383
|
+
}
|
|
384
|
+
function createPicker(win) {
|
|
385
|
+
const doc = win.document;
|
|
386
|
+
function at(x, y) {
|
|
387
|
+
try {
|
|
388
|
+
if (!Number.isFinite(x) || !Number.isFinite(y)) return null;
|
|
389
|
+
const el = doc.elementFromPoint(x, y);
|
|
390
|
+
if (!el || el === doc.documentElement || el === doc.body) return null;
|
|
391
|
+
const picked = buildPickedElement(el, doc);
|
|
392
|
+
const count = picked.candidates[0]?.matchCount ?? 0;
|
|
393
|
+
return {
|
|
394
|
+
box: boxOf(el),
|
|
395
|
+
label: `${describeElement(el)} \xB7 ${count} match${count === 1 ? "" : "es"}`,
|
|
396
|
+
picked
|
|
397
|
+
};
|
|
398
|
+
} catch {
|
|
399
|
+
return null;
|
|
400
|
+
}
|
|
401
|
+
}
|
|
402
|
+
function highlight(selector) {
|
|
403
|
+
if (typeof selector !== "string" || !selector.trim()) return { count: 0, boxes: [], error: "Empty selector" };
|
|
404
|
+
let list;
|
|
405
|
+
try {
|
|
406
|
+
list = doc.querySelectorAll(selector);
|
|
407
|
+
} catch (error) {
|
|
408
|
+
return { count: 0, boxes: [], error: errorMessage(error, "Invalid selector") };
|
|
409
|
+
}
|
|
410
|
+
const boxes = [];
|
|
411
|
+
try {
|
|
412
|
+
for (let index = 0; index < list.length && index < PICKER_MAX_BOXES; index++) {
|
|
413
|
+
const el = list[index];
|
|
414
|
+
if (el) boxes.push(boxOf(el));
|
|
415
|
+
}
|
|
416
|
+
} catch {
|
|
417
|
+
}
|
|
418
|
+
return { count: list.length, boxes };
|
|
419
|
+
}
|
|
420
|
+
function describe() {
|
|
421
|
+
const root = doc.documentElement;
|
|
422
|
+
return {
|
|
423
|
+
url: String(win.location?.href ?? ""),
|
|
424
|
+
title: String(doc.title ?? ""),
|
|
425
|
+
viewport: {
|
|
426
|
+
width: win.innerWidth || root?.clientWidth || 0,
|
|
427
|
+
height: win.innerHeight || root?.clientHeight || 0
|
|
428
|
+
},
|
|
429
|
+
scroll: { x: win.scrollX || 0, y: win.scrollY || 0 },
|
|
430
|
+
devicePixelRatio: win.devicePixelRatio || 1
|
|
431
|
+
};
|
|
432
|
+
}
|
|
433
|
+
return { version: PICKER_VERSION, at, highlight, describe };
|
|
434
|
+
}
|
|
435
|
+
function installPicker(win) {
|
|
436
|
+
try {
|
|
437
|
+
const target = win;
|
|
438
|
+
const existing = target[PICKER_GLOBAL];
|
|
439
|
+
if (existing && typeof existing.at === "function" && (existing.version ?? 0) >= PICKER_VERSION) {
|
|
440
|
+
return existing;
|
|
441
|
+
}
|
|
442
|
+
const api = createPicker(win);
|
|
443
|
+
Object.defineProperty(win, PICKER_GLOBAL, { value: api, configurable: true, enumerable: false, writable: true });
|
|
444
|
+
return api;
|
|
445
|
+
} catch {
|
|
446
|
+
return null;
|
|
447
|
+
}
|
|
448
|
+
}
|
|
449
|
+
|
|
450
|
+
exports.PICKER_GLOBAL = PICKER_GLOBAL;
|
|
451
|
+
exports.PICKER_MAX_BOXES = PICKER_MAX_BOXES;
|
|
452
|
+
exports.PICKER_VERSION = PICKER_VERSION;
|
|
453
|
+
exports.buildCandidates = buildCandidates;
|
|
454
|
+
exports.buildPickedElement = buildPickedElement;
|
|
455
|
+
exports.createPicker = createPicker;
|
|
456
|
+
exports.cssEscape = cssEscape;
|
|
457
|
+
exports.describeElement = describeElement;
|
|
458
|
+
exports.installPicker = installPicker;
|
|
459
|
+
exports.isGeneratedClass = isGeneratedClass;
|
|
460
|
+
exports.isGeneratedId = isGeneratedId;
|
|
461
|
+
exports.listSelector = listSelector;
|
|
462
|
+
exports.sampleOf = sampleOf;
|
|
463
|
+
exports.suggestName = suggestName;
|
package/dist/index.d.cts
ADDED
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
interface SelectorCandidate {
|
|
2
|
+
selector: string;
|
|
3
|
+
/** Number of elements `document.querySelectorAll(selector)` matches. */
|
|
4
|
+
matchCount: number;
|
|
5
|
+
/** Short human label, e.g. "data-testid", "id", "class", "path". */
|
|
6
|
+
strategy: string;
|
|
7
|
+
}
|
|
8
|
+
interface PickedElement {
|
|
9
|
+
tagName: string;
|
|
10
|
+
isInput: boolean;
|
|
11
|
+
/** Ranked best-first. Always has >= 1 entry. */
|
|
12
|
+
candidates: SelectorCandidate[];
|
|
13
|
+
/** Suggested field name (e.g. from aria-label / placeholder / text). */
|
|
14
|
+
suggestedName: string;
|
|
15
|
+
/** Sample values to show in the pick card. */
|
|
16
|
+
sample: {
|
|
17
|
+
text: string;
|
|
18
|
+
href?: string;
|
|
19
|
+
src?: string;
|
|
20
|
+
value?: string;
|
|
21
|
+
};
|
|
22
|
+
}
|
|
23
|
+
/** A rectangle in viewport CSS pixels (as returned by getBoundingClientRect). */
|
|
24
|
+
interface PickerBox {
|
|
25
|
+
x: number;
|
|
26
|
+
y: number;
|
|
27
|
+
width: number;
|
|
28
|
+
height: number;
|
|
29
|
+
}
|
|
30
|
+
interface PickerHit {
|
|
31
|
+
box: PickerBox;
|
|
32
|
+
/** Short chip text, e.g. `div.price · 3 matches`. */
|
|
33
|
+
label: string;
|
|
34
|
+
picked: PickedElement;
|
|
35
|
+
}
|
|
36
|
+
interface PickerHighlight {
|
|
37
|
+
/** Total number of matches (0 for an invalid selector). */
|
|
38
|
+
count: number;
|
|
39
|
+
/** Boxes of the first {@link PICKER_MAX_BOXES} matches. */
|
|
40
|
+
boxes: PickerBox[];
|
|
41
|
+
/** Set when the selector could not be evaluated. */
|
|
42
|
+
error?: string;
|
|
43
|
+
}
|
|
44
|
+
interface PickerPageInfo {
|
|
45
|
+
url: string;
|
|
46
|
+
title: string;
|
|
47
|
+
viewport: {
|
|
48
|
+
width: number;
|
|
49
|
+
height: number;
|
|
50
|
+
};
|
|
51
|
+
scroll: {
|
|
52
|
+
x: number;
|
|
53
|
+
y: number;
|
|
54
|
+
};
|
|
55
|
+
devicePixelRatio: number;
|
|
56
|
+
}
|
|
57
|
+
interface PickerApi {
|
|
58
|
+
/** Version of the injected script, so callers can detect a stale install. */
|
|
59
|
+
version: number;
|
|
60
|
+
/** Element at viewport point (x, y); null over nothing, `<html>` or `<body>`. */
|
|
61
|
+
at: (x: number, y: number) => PickerHit | null;
|
|
62
|
+
/** Count and box every match of a CSS selector. */
|
|
63
|
+
highlight: (selector: string) => PickerHighlight;
|
|
64
|
+
/** Page / viewport facts needed to map canvas coordinates. */
|
|
65
|
+
describe: () => PickerPageInfo;
|
|
66
|
+
}
|
|
67
|
+
/** Name of the global the injected script installs. */
|
|
68
|
+
declare const PICKER_GLOBAL = "__scrapeAdminPicker";
|
|
69
|
+
declare const PICKER_VERSION = 1;
|
|
70
|
+
declare const PICKER_MAX_BOXES = 150;
|
|
71
|
+
|
|
72
|
+
/** Picker bound to one window/document. Pure apart from reading the DOM; never mutates the page. */
|
|
73
|
+
declare function createPicker(win: Window): PickerApi;
|
|
74
|
+
/**
|
|
75
|
+
* Install the picker as `window.__scrapeAdminPicker` (non-enumerable, idempotent: an install of
|
|
76
|
+
* the same or newer version is kept). Returns the installed API, or null if it could not be set.
|
|
77
|
+
*/
|
|
78
|
+
declare function installPicker(win: Window): PickerApi | null;
|
|
79
|
+
|
|
80
|
+
/** Spec-compliant CSS.escape (the global is not available in every runtime). */
|
|
81
|
+
declare function cssEscape(value: string): string;
|
|
82
|
+
declare function isGeneratedId(id: string): boolean;
|
|
83
|
+
declare function isGeneratedClass(name: string): boolean;
|
|
84
|
+
/**
|
|
85
|
+
* A short selector for the list `el` belongs to: walks the repeated ancestors (innermost first)
|
|
86
|
+
* and takes the first whose structural selector matches several elements including `el`, then
|
|
87
|
+
* drops leading parts while the matched set stays the same (`span.titleline > a` instead of
|
|
88
|
+
* `table > tbody > tr.athing > td.title:nth-of-type(3) > span.titleline > a`).
|
|
89
|
+
*/
|
|
90
|
+
declare function listSelector(el: Element, doc: Document, alternatives?: string[]): {
|
|
91
|
+
selector: string;
|
|
92
|
+
count: number;
|
|
93
|
+
} | null;
|
|
94
|
+
declare function buildCandidates(el: Element, doc: Document): SelectorCandidate[];
|
|
95
|
+
declare function suggestName(el: Element): string;
|
|
96
|
+
declare function sampleOf(el: Element): PickedElement['sample'];
|
|
97
|
+
/** Short human description for the hover chip, e.g. `div.price`. */
|
|
98
|
+
declare function describeElement(el: Element): string;
|
|
99
|
+
declare function buildPickedElement(el: Element, doc: Document): PickedElement;
|
|
100
|
+
|
|
101
|
+
export { PICKER_GLOBAL, PICKER_MAX_BOXES, PICKER_VERSION, buildCandidates, buildPickedElement, createPicker, cssEscape, describeElement, installPicker, isGeneratedClass, isGeneratedId, listSelector, sampleOf, suggestName };
|
|
102
|
+
export type { PickedElement, PickerApi, PickerBox, PickerHighlight, PickerHit, PickerPageInfo, SelectorCandidate };
|
package/dist/index.d.mts
ADDED
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
interface SelectorCandidate {
|
|
2
|
+
selector: string;
|
|
3
|
+
/** Number of elements `document.querySelectorAll(selector)` matches. */
|
|
4
|
+
matchCount: number;
|
|
5
|
+
/** Short human label, e.g. "data-testid", "id", "class", "path". */
|
|
6
|
+
strategy: string;
|
|
7
|
+
}
|
|
8
|
+
interface PickedElement {
|
|
9
|
+
tagName: string;
|
|
10
|
+
isInput: boolean;
|
|
11
|
+
/** Ranked best-first. Always has >= 1 entry. */
|
|
12
|
+
candidates: SelectorCandidate[];
|
|
13
|
+
/** Suggested field name (e.g. from aria-label / placeholder / text). */
|
|
14
|
+
suggestedName: string;
|
|
15
|
+
/** Sample values to show in the pick card. */
|
|
16
|
+
sample: {
|
|
17
|
+
text: string;
|
|
18
|
+
href?: string;
|
|
19
|
+
src?: string;
|
|
20
|
+
value?: string;
|
|
21
|
+
};
|
|
22
|
+
}
|
|
23
|
+
/** A rectangle in viewport CSS pixels (as returned by getBoundingClientRect). */
|
|
24
|
+
interface PickerBox {
|
|
25
|
+
x: number;
|
|
26
|
+
y: number;
|
|
27
|
+
width: number;
|
|
28
|
+
height: number;
|
|
29
|
+
}
|
|
30
|
+
interface PickerHit {
|
|
31
|
+
box: PickerBox;
|
|
32
|
+
/** Short chip text, e.g. `div.price · 3 matches`. */
|
|
33
|
+
label: string;
|
|
34
|
+
picked: PickedElement;
|
|
35
|
+
}
|
|
36
|
+
interface PickerHighlight {
|
|
37
|
+
/** Total number of matches (0 for an invalid selector). */
|
|
38
|
+
count: number;
|
|
39
|
+
/** Boxes of the first {@link PICKER_MAX_BOXES} matches. */
|
|
40
|
+
boxes: PickerBox[];
|
|
41
|
+
/** Set when the selector could not be evaluated. */
|
|
42
|
+
error?: string;
|
|
43
|
+
}
|
|
44
|
+
interface PickerPageInfo {
|
|
45
|
+
url: string;
|
|
46
|
+
title: string;
|
|
47
|
+
viewport: {
|
|
48
|
+
width: number;
|
|
49
|
+
height: number;
|
|
50
|
+
};
|
|
51
|
+
scroll: {
|
|
52
|
+
x: number;
|
|
53
|
+
y: number;
|
|
54
|
+
};
|
|
55
|
+
devicePixelRatio: number;
|
|
56
|
+
}
|
|
57
|
+
interface PickerApi {
|
|
58
|
+
/** Version of the injected script, so callers can detect a stale install. */
|
|
59
|
+
version: number;
|
|
60
|
+
/** Element at viewport point (x, y); null over nothing, `<html>` or `<body>`. */
|
|
61
|
+
at: (x: number, y: number) => PickerHit | null;
|
|
62
|
+
/** Count and box every match of a CSS selector. */
|
|
63
|
+
highlight: (selector: string) => PickerHighlight;
|
|
64
|
+
/** Page / viewport facts needed to map canvas coordinates. */
|
|
65
|
+
describe: () => PickerPageInfo;
|
|
66
|
+
}
|
|
67
|
+
/** Name of the global the injected script installs. */
|
|
68
|
+
declare const PICKER_GLOBAL = "__scrapeAdminPicker";
|
|
69
|
+
declare const PICKER_VERSION = 1;
|
|
70
|
+
declare const PICKER_MAX_BOXES = 150;
|
|
71
|
+
|
|
72
|
+
/** Picker bound to one window/document. Pure apart from reading the DOM; never mutates the page. */
|
|
73
|
+
declare function createPicker(win: Window): PickerApi;
|
|
74
|
+
/**
|
|
75
|
+
* Install the picker as `window.__scrapeAdminPicker` (non-enumerable, idempotent: an install of
|
|
76
|
+
* the same or newer version is kept). Returns the installed API, or null if it could not be set.
|
|
77
|
+
*/
|
|
78
|
+
declare function installPicker(win: Window): PickerApi | null;
|
|
79
|
+
|
|
80
|
+
/** Spec-compliant CSS.escape (the global is not available in every runtime). */
|
|
81
|
+
declare function cssEscape(value: string): string;
|
|
82
|
+
declare function isGeneratedId(id: string): boolean;
|
|
83
|
+
declare function isGeneratedClass(name: string): boolean;
|
|
84
|
+
/**
|
|
85
|
+
* A short selector for the list `el` belongs to: walks the repeated ancestors (innermost first)
|
|
86
|
+
* and takes the first whose structural selector matches several elements including `el`, then
|
|
87
|
+
* drops leading parts while the matched set stays the same (`span.titleline > a` instead of
|
|
88
|
+
* `table > tbody > tr.athing > td.title:nth-of-type(3) > span.titleline > a`).
|
|
89
|
+
*/
|
|
90
|
+
declare function listSelector(el: Element, doc: Document, alternatives?: string[]): {
|
|
91
|
+
selector: string;
|
|
92
|
+
count: number;
|
|
93
|
+
} | null;
|
|
94
|
+
declare function buildCandidates(el: Element, doc: Document): SelectorCandidate[];
|
|
95
|
+
declare function suggestName(el: Element): string;
|
|
96
|
+
declare function sampleOf(el: Element): PickedElement['sample'];
|
|
97
|
+
/** Short human description for the hover chip, e.g. `div.price`. */
|
|
98
|
+
declare function describeElement(el: Element): string;
|
|
99
|
+
declare function buildPickedElement(el: Element, doc: Document): PickedElement;
|
|
100
|
+
|
|
101
|
+
export { PICKER_GLOBAL, PICKER_MAX_BOXES, PICKER_VERSION, buildCandidates, buildPickedElement, createPicker, cssEscape, describeElement, installPicker, isGeneratedClass, isGeneratedId, listSelector, sampleOf, suggestName };
|
|
102
|
+
export type { PickedElement, PickerApi, PickerBox, PickerHighlight, PickerHit, PickerPageInfo, SelectorCandidate };
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
interface SelectorCandidate {
|
|
2
|
+
selector: string;
|
|
3
|
+
/** Number of elements `document.querySelectorAll(selector)` matches. */
|
|
4
|
+
matchCount: number;
|
|
5
|
+
/** Short human label, e.g. "data-testid", "id", "class", "path". */
|
|
6
|
+
strategy: string;
|
|
7
|
+
}
|
|
8
|
+
interface PickedElement {
|
|
9
|
+
tagName: string;
|
|
10
|
+
isInput: boolean;
|
|
11
|
+
/** Ranked best-first. Always has >= 1 entry. */
|
|
12
|
+
candidates: SelectorCandidate[];
|
|
13
|
+
/** Suggested field name (e.g. from aria-label / placeholder / text). */
|
|
14
|
+
suggestedName: string;
|
|
15
|
+
/** Sample values to show in the pick card. */
|
|
16
|
+
sample: {
|
|
17
|
+
text: string;
|
|
18
|
+
href?: string;
|
|
19
|
+
src?: string;
|
|
20
|
+
value?: string;
|
|
21
|
+
};
|
|
22
|
+
}
|
|
23
|
+
/** A rectangle in viewport CSS pixels (as returned by getBoundingClientRect). */
|
|
24
|
+
interface PickerBox {
|
|
25
|
+
x: number;
|
|
26
|
+
y: number;
|
|
27
|
+
width: number;
|
|
28
|
+
height: number;
|
|
29
|
+
}
|
|
30
|
+
interface PickerHit {
|
|
31
|
+
box: PickerBox;
|
|
32
|
+
/** Short chip text, e.g. `div.price · 3 matches`. */
|
|
33
|
+
label: string;
|
|
34
|
+
picked: PickedElement;
|
|
35
|
+
}
|
|
36
|
+
interface PickerHighlight {
|
|
37
|
+
/** Total number of matches (0 for an invalid selector). */
|
|
38
|
+
count: number;
|
|
39
|
+
/** Boxes of the first {@link PICKER_MAX_BOXES} matches. */
|
|
40
|
+
boxes: PickerBox[];
|
|
41
|
+
/** Set when the selector could not be evaluated. */
|
|
42
|
+
error?: string;
|
|
43
|
+
}
|
|
44
|
+
interface PickerPageInfo {
|
|
45
|
+
url: string;
|
|
46
|
+
title: string;
|
|
47
|
+
viewport: {
|
|
48
|
+
width: number;
|
|
49
|
+
height: number;
|
|
50
|
+
};
|
|
51
|
+
scroll: {
|
|
52
|
+
x: number;
|
|
53
|
+
y: number;
|
|
54
|
+
};
|
|
55
|
+
devicePixelRatio: number;
|
|
56
|
+
}
|
|
57
|
+
interface PickerApi {
|
|
58
|
+
/** Version of the injected script, so callers can detect a stale install. */
|
|
59
|
+
version: number;
|
|
60
|
+
/** Element at viewport point (x, y); null over nothing, `<html>` or `<body>`. */
|
|
61
|
+
at: (x: number, y: number) => PickerHit | null;
|
|
62
|
+
/** Count and box every match of a CSS selector. */
|
|
63
|
+
highlight: (selector: string) => PickerHighlight;
|
|
64
|
+
/** Page / viewport facts needed to map canvas coordinates. */
|
|
65
|
+
describe: () => PickerPageInfo;
|
|
66
|
+
}
|
|
67
|
+
/** Name of the global the injected script installs. */
|
|
68
|
+
declare const PICKER_GLOBAL = "__scrapeAdminPicker";
|
|
69
|
+
declare const PICKER_VERSION = 1;
|
|
70
|
+
declare const PICKER_MAX_BOXES = 150;
|
|
71
|
+
|
|
72
|
+
/** Picker bound to one window/document. Pure apart from reading the DOM; never mutates the page. */
|
|
73
|
+
declare function createPicker(win: Window): PickerApi;
|
|
74
|
+
/**
|
|
75
|
+
* Install the picker as `window.__scrapeAdminPicker` (non-enumerable, idempotent: an install of
|
|
76
|
+
* the same or newer version is kept). Returns the installed API, or null if it could not be set.
|
|
77
|
+
*/
|
|
78
|
+
declare function installPicker(win: Window): PickerApi | null;
|
|
79
|
+
|
|
80
|
+
/** Spec-compliant CSS.escape (the global is not available in every runtime). */
|
|
81
|
+
declare function cssEscape(value: string): string;
|
|
82
|
+
declare function isGeneratedId(id: string): boolean;
|
|
83
|
+
declare function isGeneratedClass(name: string): boolean;
|
|
84
|
+
/**
|
|
85
|
+
* A short selector for the list `el` belongs to: walks the repeated ancestors (innermost first)
|
|
86
|
+
* and takes the first whose structural selector matches several elements including `el`, then
|
|
87
|
+
* drops leading parts while the matched set stays the same (`span.titleline > a` instead of
|
|
88
|
+
* `table > tbody > tr.athing > td.title:nth-of-type(3) > span.titleline > a`).
|
|
89
|
+
*/
|
|
90
|
+
declare function listSelector(el: Element, doc: Document, alternatives?: string[]): {
|
|
91
|
+
selector: string;
|
|
92
|
+
count: number;
|
|
93
|
+
} | null;
|
|
94
|
+
declare function buildCandidates(el: Element, doc: Document): SelectorCandidate[];
|
|
95
|
+
declare function suggestName(el: Element): string;
|
|
96
|
+
declare function sampleOf(el: Element): PickedElement['sample'];
|
|
97
|
+
/** Short human description for the hover chip, e.g. `div.price`. */
|
|
98
|
+
declare function describeElement(el: Element): string;
|
|
99
|
+
declare function buildPickedElement(el: Element, doc: Document): PickedElement;
|
|
100
|
+
|
|
101
|
+
export { PICKER_GLOBAL, PICKER_MAX_BOXES, PICKER_VERSION, buildCandidates, buildPickedElement, createPicker, cssEscape, describeElement, installPicker, isGeneratedClass, isGeneratedId, listSelector, sampleOf, suggestName };
|
|
102
|
+
export type { PickedElement, PickerApi, PickerBox, PickerHighlight, PickerHit, PickerPageInfo, SelectorCandidate };
|
package/dist/index.mjs
ADDED
|
@@ -0,0 +1,448 @@
|
|
|
1
|
+
const MAX_CANDIDATES = 3;
|
|
2
|
+
const TEST_ATTRIBUTES = ["data-testid", "data-test", "data-cy", "data-qa"];
|
|
3
|
+
function cssEscape(value) {
|
|
4
|
+
const string = String(value);
|
|
5
|
+
let result = "";
|
|
6
|
+
for (let index = 0; index < string.length; index++) {
|
|
7
|
+
const code = string.charCodeAt(index);
|
|
8
|
+
const char = string.charAt(index);
|
|
9
|
+
if (code === 0) {
|
|
10
|
+
result += "\uFFFD";
|
|
11
|
+
} else if (code >= 1 && code <= 31 || code === 127 || index === 0 && code >= 48 && code <= 57 || index === 1 && code >= 48 && code <= 57 && string.charCodeAt(0) === 45) {
|
|
12
|
+
result += `\\${code.toString(16)} `;
|
|
13
|
+
} else if (index === 0 && code === 45 && string.length === 1) {
|
|
14
|
+
result += `\\${char}`;
|
|
15
|
+
} else if (code >= 128 || code === 45 || code === 95 || code >= 48 && code <= 57 || code >= 65 && code <= 90 || code >= 97 && code <= 122) {
|
|
16
|
+
result += char;
|
|
17
|
+
} else {
|
|
18
|
+
result += `\\${char}`;
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
return result;
|
|
22
|
+
}
|
|
23
|
+
function cssString(value) {
|
|
24
|
+
return `"${value.replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/\n/g, "\\a ").replace(/\r/g, "\\d ")}"`;
|
|
25
|
+
}
|
|
26
|
+
function isGeneratedId(id) {
|
|
27
|
+
if (!id || id.length > 50) return true;
|
|
28
|
+
if (id.startsWith(":")) return true;
|
|
29
|
+
if (/^(?:ember|radix|headlessui|react-aria|reactid|mui|downshift|rc|chakra|__next|yui_|ext-gen)[-_:]?\d*/i.test(id) && /[\d\-_:]/.test(id)) return true;
|
|
30
|
+
if (/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(id)) return true;
|
|
31
|
+
if (/^[0-9a-f]{12,}$/i.test(id)) return true;
|
|
32
|
+
if (/\d{5,}/.test(id)) return true;
|
|
33
|
+
const digits = (id.match(/\d/g) ?? []).length;
|
|
34
|
+
if (id.length >= 4 && digits / id.length >= 0.4) return true;
|
|
35
|
+
return false;
|
|
36
|
+
}
|
|
37
|
+
const TAILWIND_PREFIXES = "(?:[whpmz]|min-w|min-h|max-w|max-h|px|py|pt|pb|pl|pr|mx|my|mt|mb|ml|mr|gap|gap-x|gap-y|space-x|space-y|top|left|right|bottom|inset|text|bg|border|rounded|font|leading|tracking|opacity|shadow|ring|flex|grid|col|row|basis|grow|shrink|size|order|divide|fill|stroke|outline|object|overflow|cursor|duration|ease|aspect|translate|rotate|scale|items|justify|self|content|place)";
|
|
38
|
+
const TAILWIND_VALUE = "(?:[\\d[]|(?:px|auto|full|screen|min|max|fit|none|xs|sm|md|lg|xl|base|center|left|right|justify|start|end|between|around|bold|semibold|medium|light|normal|italic|white|black|transparent|current|inherit)$|[a-z]+-\\d{2,3}$)";
|
|
39
|
+
const TAILWIND_UTILITY = new RegExp(`^-?${TAILWIND_PREFIXES}-${TAILWIND_VALUE}`);
|
|
40
|
+
const TAILWIND_BARE = /* @__PURE__ */ new Set([
|
|
41
|
+
"flex",
|
|
42
|
+
"grid",
|
|
43
|
+
"block",
|
|
44
|
+
"inline",
|
|
45
|
+
"inline-block",
|
|
46
|
+
"inline-flex",
|
|
47
|
+
"hidden",
|
|
48
|
+
"relative",
|
|
49
|
+
"absolute",
|
|
50
|
+
"fixed",
|
|
51
|
+
"sticky",
|
|
52
|
+
"static",
|
|
53
|
+
"truncate",
|
|
54
|
+
"underline",
|
|
55
|
+
"uppercase",
|
|
56
|
+
"lowercase",
|
|
57
|
+
"capitalize",
|
|
58
|
+
"italic",
|
|
59
|
+
"border",
|
|
60
|
+
"rounded",
|
|
61
|
+
"shadow",
|
|
62
|
+
"container",
|
|
63
|
+
"sr-only",
|
|
64
|
+
"transition",
|
|
65
|
+
"grow",
|
|
66
|
+
"shrink",
|
|
67
|
+
"contents",
|
|
68
|
+
"table",
|
|
69
|
+
"visible",
|
|
70
|
+
"invisible",
|
|
71
|
+
"italic"
|
|
72
|
+
]);
|
|
73
|
+
const STATE_CLASSES = /^(?:active|selected|open|opened|closed|show|shown|hide|visible|hover|hovered|focus|focused|disabled|checked|loading|loaded|collapsed|expanded|current|is-[\w-]+|has-[\w-]+|ng-[\w-]+|ember-[\w-]+|v-[\w-]+)$/;
|
|
74
|
+
function isGeneratedClass(name) {
|
|
75
|
+
if (!name || name.length < 2 || name.length > 40) return true;
|
|
76
|
+
if (/[:[\]/%#!@]/.test(name)) return true;
|
|
77
|
+
if (TAILWIND_BARE.has(name) || TAILWIND_UTILITY.test(name)) return true;
|
|
78
|
+
if (/^_[\w-]{4,}$/.test(name)) return true;
|
|
79
|
+
if (/^(?:css|sc|jsx|emotion|styled|svelte|astro|chakra|mui|makeStyles|jss)-/i.test(name)) return true;
|
|
80
|
+
if (/^[a-z]{1,3}-?\d+$/i.test(name) && /\d/.test(name)) return true;
|
|
81
|
+
if (/__[\w-]{5,}$/.test(name) && /[A-Z\d]/.test(name.slice(name.lastIndexOf("__") + 2))) return true;
|
|
82
|
+
if (/^(?=.*\d)(?=.*[a-z])[a-z0-9]{6,}$/i.test(name)) return true;
|
|
83
|
+
if (/^[A-Z0-9]{5,}$/i.test(name) && /[a-z]/.test(name) && /[A-Z]/.test(name) && !/^[A-Z]?[a-z]+(?:[A-Z][a-z]+)*$/.test(name)) return true;
|
|
84
|
+
if (STATE_CLASSES.test(name)) return true;
|
|
85
|
+
return false;
|
|
86
|
+
}
|
|
87
|
+
function stableClasses(el) {
|
|
88
|
+
const raw = el.getAttribute("class");
|
|
89
|
+
if (!raw) return [];
|
|
90
|
+
return raw.split(/\s+/).filter((name) => name && !isGeneratedClass(name));
|
|
91
|
+
}
|
|
92
|
+
function tagOf(el) {
|
|
93
|
+
return el.tagName.toLowerCase();
|
|
94
|
+
}
|
|
95
|
+
function countMatches(doc, selector) {
|
|
96
|
+
try {
|
|
97
|
+
return doc.querySelectorAll(selector).length;
|
|
98
|
+
} catch {
|
|
99
|
+
return 0;
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
function matchesElement(doc, selector, el) {
|
|
103
|
+
try {
|
|
104
|
+
const list = doc.querySelectorAll(selector);
|
|
105
|
+
return { count: list.length, includes: Array.prototype.includes.call(list, el) };
|
|
106
|
+
} catch {
|
|
107
|
+
return { count: 0, includes: false };
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
function safeMatches(el, selector) {
|
|
111
|
+
try {
|
|
112
|
+
return el.matches(selector);
|
|
113
|
+
} catch {
|
|
114
|
+
return false;
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
function testAttributeSelector(el) {
|
|
118
|
+
const out = [];
|
|
119
|
+
for (const attr of TEST_ATTRIBUTES) {
|
|
120
|
+
const value = el.getAttribute(attr);
|
|
121
|
+
if (value && value.length <= 80) out.push({ selector: `[${attr}=${cssString(value)}]`, strategy: attr });
|
|
122
|
+
}
|
|
123
|
+
return out;
|
|
124
|
+
}
|
|
125
|
+
function stableAttributeSelectors(el) {
|
|
126
|
+
const tag = tagOf(el);
|
|
127
|
+
const out = [];
|
|
128
|
+
const label = el.getAttribute("aria-label");
|
|
129
|
+
if (label && label.length <= 80) out.push({ selector: `${tag}[aria-label=${cssString(label)}]`, strategy: "aria-label" });
|
|
130
|
+
const name = el.getAttribute("name");
|
|
131
|
+
if (name && name.length <= 60) out.push({ selector: `${tag}[name=${cssString(name)}]`, strategy: "name" });
|
|
132
|
+
const itemprop = el.getAttribute("itemprop");
|
|
133
|
+
if (itemprop && itemprop.length <= 60) out.push({ selector: `[itemprop=${cssString(itemprop)}]`, strategy: "itemprop" });
|
|
134
|
+
const role = el.getAttribute("role");
|
|
135
|
+
if (role && label && label.length <= 80) {
|
|
136
|
+
out.push({ selector: `[role=${cssString(role)}][aria-label=${cssString(label)}]`, strategy: "role" });
|
|
137
|
+
}
|
|
138
|
+
if (tag === "a") {
|
|
139
|
+
const href = el.getAttribute("href");
|
|
140
|
+
if (href && href.length <= 60 && !href.startsWith("javascript:") && !href.includes("?") && /^(?:[/#.]|[\w-]+\/|https?:\/\/[^/]+\/?$)/.test(href)) {
|
|
141
|
+
out.push({ selector: `a[href=${cssString(href)}]`, strategy: "href" });
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
return out;
|
|
145
|
+
}
|
|
146
|
+
function classSelectors(el) {
|
|
147
|
+
const classes = stableClasses(el);
|
|
148
|
+
if (!classes.length) return [];
|
|
149
|
+
const tag = tagOf(el);
|
|
150
|
+
const out = [];
|
|
151
|
+
const combined = classes.slice(0, 3).map((name) => `.${cssEscape(name)}`).join("");
|
|
152
|
+
out.push({ selector: `${tag}${combined}`, strategy: "class" });
|
|
153
|
+
for (const name of classes.slice(0, 3)) {
|
|
154
|
+
out.push({ selector: `${tag}.${cssEscape(name)}`, strategy: "class" });
|
|
155
|
+
}
|
|
156
|
+
return out;
|
|
157
|
+
}
|
|
158
|
+
function baseSegment(el) {
|
|
159
|
+
const classes = stableClasses(el).slice(0, 2);
|
|
160
|
+
return `${tagOf(el)}${classes.map((name) => `.${cssEscape(name)}`).join("")}`;
|
|
161
|
+
}
|
|
162
|
+
function segment(el) {
|
|
163
|
+
const base = baseSegment(el);
|
|
164
|
+
const parent = el.parentElement;
|
|
165
|
+
if (!parent) return base;
|
|
166
|
+
const siblings = Array.from(parent.children);
|
|
167
|
+
const ambiguous = siblings.some((sibling) => sibling !== el && safeMatches(sibling, base));
|
|
168
|
+
if (!ambiguous) return base;
|
|
169
|
+
const index = siblings.filter((sibling) => sibling.tagName === el.tagName).indexOf(el) + 1;
|
|
170
|
+
return `${base}:nth-of-type(${index})`;
|
|
171
|
+
}
|
|
172
|
+
function anchorSelector(el, doc) {
|
|
173
|
+
for (const candidate of testAttributeSelector(el)) {
|
|
174
|
+
if (countMatches(doc, candidate.selector) === 1) return candidate.selector;
|
|
175
|
+
}
|
|
176
|
+
const id = el.getAttribute("id");
|
|
177
|
+
if (id && !isGeneratedId(id)) {
|
|
178
|
+
const selector = `#${cssEscape(id)}`;
|
|
179
|
+
if (countMatches(doc, selector) === 1) return selector;
|
|
180
|
+
}
|
|
181
|
+
return null;
|
|
182
|
+
}
|
|
183
|
+
function pathSelector(el, doc, full = false) {
|
|
184
|
+
const segments = [];
|
|
185
|
+
let current = el;
|
|
186
|
+
while (current && current !== doc.documentElement) {
|
|
187
|
+
if (current !== el) {
|
|
188
|
+
const anchor = anchorSelector(current, doc);
|
|
189
|
+
if (anchor) {
|
|
190
|
+
segments.unshift(anchor);
|
|
191
|
+
const selector2 = segments.join(" > ");
|
|
192
|
+
if (countMatches(doc, selector2) === 1) return selector2;
|
|
193
|
+
segments.shift();
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
segments.unshift(segment(current));
|
|
197
|
+
const selector = segments.join(" > ");
|
|
198
|
+
const bare = segments.length === 1 && segments[0]?.includes(":nth-of-type");
|
|
199
|
+
if (!full && !bare && countMatches(doc, selector) === 1) return selector;
|
|
200
|
+
if (current === doc.body) break;
|
|
201
|
+
current = current.parentElement;
|
|
202
|
+
}
|
|
203
|
+
return segments.join(" > ");
|
|
204
|
+
}
|
|
205
|
+
function similarSiblingCount(el) {
|
|
206
|
+
const parent = el.parentElement;
|
|
207
|
+
if (!parent) return 0;
|
|
208
|
+
const base = baseSegment(el);
|
|
209
|
+
return Array.from(parent.children).filter((sibling) => safeMatches(sibling, base)).length;
|
|
210
|
+
}
|
|
211
|
+
function isRepeatedItem(el) {
|
|
212
|
+
const hasClasses = stableClasses(el).length > 0;
|
|
213
|
+
return similarSiblingCount(el) >= (hasClasses ? 2 : 3);
|
|
214
|
+
}
|
|
215
|
+
function repeatedRoots(el, doc) {
|
|
216
|
+
const roots = [];
|
|
217
|
+
let current = el;
|
|
218
|
+
for (let depth = 0; current && current !== doc.body && current !== doc.documentElement && depth < 8; depth++) {
|
|
219
|
+
if (isRepeatedItem(current)) roots.push(current);
|
|
220
|
+
current = current.parentElement;
|
|
221
|
+
}
|
|
222
|
+
return roots;
|
|
223
|
+
}
|
|
224
|
+
function uniqueSelectorFor(el, doc) {
|
|
225
|
+
const anchor = anchorSelector(el, doc);
|
|
226
|
+
if (anchor) return anchor;
|
|
227
|
+
for (const candidate of [...stableAttributeSelectors(el), ...classSelectors(el)]) {
|
|
228
|
+
if (countMatches(doc, candidate.selector) === 1) return candidate.selector;
|
|
229
|
+
}
|
|
230
|
+
return pathSelector(el, doc);
|
|
231
|
+
}
|
|
232
|
+
function repeatedParts(el, root, doc) {
|
|
233
|
+
const parent = root.parentElement;
|
|
234
|
+
if (!parent) return null;
|
|
235
|
+
const parentPart = parent === doc.body || parent === doc.documentElement ? "body" : uniqueSelectorFor(parent, doc);
|
|
236
|
+
const parts = [parentPart, baseSegment(root)];
|
|
237
|
+
const relative = [];
|
|
238
|
+
let current = el;
|
|
239
|
+
while (current && current !== root) {
|
|
240
|
+
relative.unshift(segment(current));
|
|
241
|
+
current = current.parentElement;
|
|
242
|
+
}
|
|
243
|
+
return [...parts, ...relative];
|
|
244
|
+
}
|
|
245
|
+
function queryAll(doc, selector) {
|
|
246
|
+
try {
|
|
247
|
+
return Array.from(doc.querySelectorAll(selector));
|
|
248
|
+
} catch {
|
|
249
|
+
return null;
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
const sameSet = (a, b) => a.length === b.length && a.every((el, i) => el === b[i]);
|
|
253
|
+
function listSelector(el, doc, alternatives = []) {
|
|
254
|
+
for (const root of repeatedRoots(el, doc)) {
|
|
255
|
+
const parts = repeatedParts(el, root, doc);
|
|
256
|
+
if (!parts) continue;
|
|
257
|
+
const set = queryAll(doc, parts.join(" > "));
|
|
258
|
+
if (!set || set.length < 2 || !set.includes(el)) continue;
|
|
259
|
+
const options = [...alternatives];
|
|
260
|
+
for (let start = parts.length - 1; start >= 0; start--) options.push(parts.slice(start).join(" > "));
|
|
261
|
+
const best = options.filter((selector) => {
|
|
262
|
+
const found = queryAll(doc, selector);
|
|
263
|
+
return !!found && sameSet(found, set);
|
|
264
|
+
}).sort((a, b) => a.length - b.length)[0];
|
|
265
|
+
return { selector: best ?? parts.join(" > "), count: set.length };
|
|
266
|
+
}
|
|
267
|
+
return null;
|
|
268
|
+
}
|
|
269
|
+
function buildCandidates(el, doc) {
|
|
270
|
+
const ordered = [];
|
|
271
|
+
ordered.push(...testAttributeSelector(el));
|
|
272
|
+
const id = el.getAttribute("id");
|
|
273
|
+
if (id && !isGeneratedId(id)) ordered.push({ selector: `#${cssEscape(id)}`, strategy: "id" });
|
|
274
|
+
ordered.push(...stableAttributeSelectors(el));
|
|
275
|
+
ordered.push(...classSelectors(el));
|
|
276
|
+
ordered.push({ selector: pathSelector(el, doc), strategy: "path" });
|
|
277
|
+
const seen = /* @__PURE__ */ new Set();
|
|
278
|
+
const unique = [];
|
|
279
|
+
const many = [];
|
|
280
|
+
for (const raw of ordered) {
|
|
281
|
+
if (seen.has(raw.selector)) continue;
|
|
282
|
+
seen.add(raw.selector);
|
|
283
|
+
const { count, includes } = matchesElement(doc, raw.selector, el);
|
|
284
|
+
if (!includes) continue;
|
|
285
|
+
if (count === 1) {
|
|
286
|
+
unique.push({ selector: raw.selector, matchCount: 1, strategy: raw.strategy });
|
|
287
|
+
} else if (raw.strategy !== "path") {
|
|
288
|
+
many.push({ selector: raw.selector, matchCount: count, strategy: "repeated" });
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
const repeated = [];
|
|
292
|
+
const list = listSelector(el, doc, many.map((candidate) => candidate.selector));
|
|
293
|
+
if (list) {
|
|
294
|
+
repeated.push({ selector: list.selector, matchCount: list.count, strategy: "repeated" });
|
|
295
|
+
repeated.push(...many.filter((candidate) => candidate.selector !== list.selector));
|
|
296
|
+
}
|
|
297
|
+
if (!unique.length) {
|
|
298
|
+
const fallback = pathSelector(el, doc, true);
|
|
299
|
+
const { count } = matchesElement(doc, fallback, el);
|
|
300
|
+
unique.push({ selector: fallback, matchCount: count, strategy: "path" });
|
|
301
|
+
}
|
|
302
|
+
const wantRepeated = repeated.length > 0 ? 1 : 0;
|
|
303
|
+
return [...unique.slice(0, MAX_CANDIDATES - wantRepeated), ...repeated.slice(0, wantRepeated)];
|
|
304
|
+
}
|
|
305
|
+
function toIdentifier(text) {
|
|
306
|
+
const words = text.normalize("NFKD").replace(/\p{M}/gu, "").replace(/([a-z0-9])([A-Z])/g, "$1 $2").split(/[^A-Z0-9]+/i).filter(Boolean).slice(0, 4);
|
|
307
|
+
if (!words.length) return "";
|
|
308
|
+
const [first, ...rest] = words.map((word) => word.toLowerCase());
|
|
309
|
+
const joined = (first ?? "") + rest.map((word) => word.charAt(0).toUpperCase() + word.slice(1)).join("");
|
|
310
|
+
return /^\d/.test(joined) ? `field${joined.charAt(0).toUpperCase()}${joined.slice(1)}` : joined;
|
|
311
|
+
}
|
|
312
|
+
function suggestName(el) {
|
|
313
|
+
const sources = [
|
|
314
|
+
el.getAttribute("aria-label"),
|
|
315
|
+
el.getAttribute("name"),
|
|
316
|
+
el.getAttribute("placeholder"),
|
|
317
|
+
...TEST_ATTRIBUTES.map((attr) => el.getAttribute(attr)),
|
|
318
|
+
el.getAttribute("itemprop"),
|
|
319
|
+
(() => {
|
|
320
|
+
const id = el.getAttribute("id");
|
|
321
|
+
return id && !isGeneratedId(id) ? id : null;
|
|
322
|
+
})(),
|
|
323
|
+
el.getAttribute("title"),
|
|
324
|
+
el.getAttribute("alt"),
|
|
325
|
+
(() => {
|
|
326
|
+
const text = (el.textContent ?? "").replace(/\s+/g, " ").trim();
|
|
327
|
+
return text.length > 0 && text.length <= 40 && /[A-Z]/i.test(text) ? text : null;
|
|
328
|
+
})(),
|
|
329
|
+
stableClasses(el)[0]
|
|
330
|
+
];
|
|
331
|
+
for (const source of sources) {
|
|
332
|
+
if (!source) continue;
|
|
333
|
+
const name = toIdentifier(source);
|
|
334
|
+
if (name) return name;
|
|
335
|
+
}
|
|
336
|
+
return toIdentifier(tagOf(el)) || "element";
|
|
337
|
+
}
|
|
338
|
+
function sampleOf(el) {
|
|
339
|
+
const text = (el.textContent ?? "").replace(/\s+/g, " ").trim().slice(0, 200);
|
|
340
|
+
const sample = { text };
|
|
341
|
+
const attr = (name) => {
|
|
342
|
+
const value = el.getAttribute(name);
|
|
343
|
+
return value ? value.slice(0, 500) : void 0;
|
|
344
|
+
};
|
|
345
|
+
const href = el.href ?? attr("href");
|
|
346
|
+
if (typeof href === "string" && href) sample.href = href.slice(0, 500);
|
|
347
|
+
const src = el.src ?? attr("src");
|
|
348
|
+
if (typeof src === "string" && src) sample.src = src.slice(0, 500);
|
|
349
|
+
const tag = tagOf(el);
|
|
350
|
+
if (tag === "input" || tag === "textarea" || tag === "select") {
|
|
351
|
+
const value = el.value;
|
|
352
|
+
if (typeof value === "string" && value) sample.value = value.slice(0, 200);
|
|
353
|
+
}
|
|
354
|
+
return sample;
|
|
355
|
+
}
|
|
356
|
+
function describeElement(el) {
|
|
357
|
+
const classes = stableClasses(el);
|
|
358
|
+
return `${tagOf(el)}${classes.length ? `.${classes[0]}` : ""}`;
|
|
359
|
+
}
|
|
360
|
+
function buildPickedElement(el, doc) {
|
|
361
|
+
const tagName = tagOf(el);
|
|
362
|
+
return {
|
|
363
|
+
tagName,
|
|
364
|
+
isInput: ["input", "textarea", "select"].includes(tagName),
|
|
365
|
+
candidates: buildCandidates(el, doc),
|
|
366
|
+
suggestedName: suggestName(el),
|
|
367
|
+
sample: sampleOf(el)
|
|
368
|
+
};
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
const PICKER_GLOBAL = "__scrapeAdminPicker";
|
|
372
|
+
const PICKER_VERSION = 1;
|
|
373
|
+
const PICKER_MAX_BOXES = 150;
|
|
374
|
+
|
|
375
|
+
function boxOf(el) {
|
|
376
|
+
const rect = el.getBoundingClientRect();
|
|
377
|
+
return { x: rect.x, y: rect.y, width: rect.width, height: rect.height };
|
|
378
|
+
}
|
|
379
|
+
function errorMessage(error, fallback) {
|
|
380
|
+
return error instanceof Error && error.message ? error.message : fallback;
|
|
381
|
+
}
|
|
382
|
+
function createPicker(win) {
|
|
383
|
+
const doc = win.document;
|
|
384
|
+
function at(x, y) {
|
|
385
|
+
try {
|
|
386
|
+
if (!Number.isFinite(x) || !Number.isFinite(y)) return null;
|
|
387
|
+
const el = doc.elementFromPoint(x, y);
|
|
388
|
+
if (!el || el === doc.documentElement || el === doc.body) return null;
|
|
389
|
+
const picked = buildPickedElement(el, doc);
|
|
390
|
+
const count = picked.candidates[0]?.matchCount ?? 0;
|
|
391
|
+
return {
|
|
392
|
+
box: boxOf(el),
|
|
393
|
+
label: `${describeElement(el)} \xB7 ${count} match${count === 1 ? "" : "es"}`,
|
|
394
|
+
picked
|
|
395
|
+
};
|
|
396
|
+
} catch {
|
|
397
|
+
return null;
|
|
398
|
+
}
|
|
399
|
+
}
|
|
400
|
+
function highlight(selector) {
|
|
401
|
+
if (typeof selector !== "string" || !selector.trim()) return { count: 0, boxes: [], error: "Empty selector" };
|
|
402
|
+
let list;
|
|
403
|
+
try {
|
|
404
|
+
list = doc.querySelectorAll(selector);
|
|
405
|
+
} catch (error) {
|
|
406
|
+
return { count: 0, boxes: [], error: errorMessage(error, "Invalid selector") };
|
|
407
|
+
}
|
|
408
|
+
const boxes = [];
|
|
409
|
+
try {
|
|
410
|
+
for (let index = 0; index < list.length && index < PICKER_MAX_BOXES; index++) {
|
|
411
|
+
const el = list[index];
|
|
412
|
+
if (el) boxes.push(boxOf(el));
|
|
413
|
+
}
|
|
414
|
+
} catch {
|
|
415
|
+
}
|
|
416
|
+
return { count: list.length, boxes };
|
|
417
|
+
}
|
|
418
|
+
function describe() {
|
|
419
|
+
const root = doc.documentElement;
|
|
420
|
+
return {
|
|
421
|
+
url: String(win.location?.href ?? ""),
|
|
422
|
+
title: String(doc.title ?? ""),
|
|
423
|
+
viewport: {
|
|
424
|
+
width: win.innerWidth || root?.clientWidth || 0,
|
|
425
|
+
height: win.innerHeight || root?.clientHeight || 0
|
|
426
|
+
},
|
|
427
|
+
scroll: { x: win.scrollX || 0, y: win.scrollY || 0 },
|
|
428
|
+
devicePixelRatio: win.devicePixelRatio || 1
|
|
429
|
+
};
|
|
430
|
+
}
|
|
431
|
+
return { version: PICKER_VERSION, at, highlight, describe };
|
|
432
|
+
}
|
|
433
|
+
function installPicker(win) {
|
|
434
|
+
try {
|
|
435
|
+
const target = win;
|
|
436
|
+
const existing = target[PICKER_GLOBAL];
|
|
437
|
+
if (existing && typeof existing.at === "function" && (existing.version ?? 0) >= PICKER_VERSION) {
|
|
438
|
+
return existing;
|
|
439
|
+
}
|
|
440
|
+
const api = createPicker(win);
|
|
441
|
+
Object.defineProperty(win, PICKER_GLOBAL, { value: api, configurable: true, enumerable: false, writable: true });
|
|
442
|
+
return api;
|
|
443
|
+
} catch {
|
|
444
|
+
return null;
|
|
445
|
+
}
|
|
446
|
+
}
|
|
447
|
+
|
|
448
|
+
export { PICKER_GLOBAL, PICKER_MAX_BOXES, PICKER_VERSION, buildCandidates, buildPickedElement, createPicker, cssEscape, describeElement, installPicker, isGeneratedClass, isGeneratedId, listSelector, sampleOf, suggestName };
|
package/dist/inject.d.ts
ADDED
package/dist/inject.mjs
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
/** Self-contained IIFE that installs `window.__scrapeAdminPicker` when evaluated in a page. */
|
|
2
|
+
export const PICKER_SCRIPT = "\"use strict\";(()=>{var w=[\"data-testid\",\"data-test\",\"data-cy\",\"data-qa\"];function d(t){let e=String(t),n=\"\";for(let r=0;r<e.length;r++){let i=e.charCodeAt(r),s=e.charAt(r);i===0?n+=\"�\":i>=1&&i<=31||i===127||r===0&&i>=48&&i<=57||r===1&&i>=48&&i<=57&&e.charCodeAt(0)===45?n+=`\\\\${i.toString(16)} `:r===0&&i===45&&e.length===1?n+=`\\\\${s}`:i>=128||i===45||i===95||i>=48&&i<=57||i>=65&&i<=90||i>=97&&i<=122?n+=s:n+=`\\\\${s}`}return n}function f(t){return`\"${t.replace(/\\\\/g,\"\\\\\\\\\").replace(/\"/g,'\\\\\"').replace(/\\n/g,\"\\\\a \").replace(/\\r/g,\"\\\\d \")}\"`}function x(t){if(!t||t.length>50||t.startsWith(\":\")||/^(?:ember|radix|headlessui|react-aria|reactid|mui|downshift|rc|chakra|__next|yui_|ext-gen)[-_:]?\\d*/i.test(t)&&/[\\d\\-_:]/.test(t)||/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(t)||/^[0-9a-f]{12,}$/i.test(t)||/\\d{5,}/.test(t))return!0;let e=(t.match(/\\d/g)??[]).length;return t.length>=4&&e/t.length>=.4}var B=\"(?:[whpmz]|min-w|min-h|max-w|max-h|px|py|pt|pb|pl|pr|mx|my|mt|mb|ml|mr|gap|gap-x|gap-y|space-x|space-y|top|left|right|bottom|inset|text|bg|border|rounded|font|leading|tracking|opacity|shadow|ring|flex|grid|col|row|basis|grow|shrink|size|order|divide|fill|stroke|outline|object|overflow|cursor|duration|ease|aspect|translate|rotate|scale|items|justify|self|content|place)\",H=\"(?:[\\\\d[]|(?:px|auto|full|screen|min|max|fit|none|xs|sm|md|lg|xl|base|center|left|right|justify|start|end|between|around|bold|semibold|medium|light|normal|italic|white|black|transparent|current|inherit)$|[a-z]+-\\\\d{2,3}$)\",O=new RegExp(`^-?${B}-${H}`),z=new Set([\"flex\",\"grid\",\"block\",\"inline\",\"inline-block\",\"inline-flex\",\"hidden\",\"relative\",\"absolute\",\"fixed\",\"sticky\",\"static\",\"truncate\",\"underline\",\"uppercase\",\"lowercase\",\"capitalize\",\"italic\",\"border\",\"rounded\",\"shadow\",\"container\",\"sr-only\",\"transition\",\"grow\",\"shrink\",\"contents\",\"table\",\"visible\",\"invisible\",\"italic\"]),M=/^(?:active|selected|open|opened|closed|show|shown|hide|visible|hover|hovered|focus|focused|disabled|checked|loading|loaded|collapsed|expanded|current|is-[\\w-]+|has-[\\w-]+|ng-[\\w-]+|ember-[\\w-]+|v-[\\w-]+)$/;function W(t){return!!(!t||t.length<2||t.length>40||/[:[\\]/%#!@]/.test(t)||z.has(t)||O.test(t)||/^_[\\w-]{4,}$/.test(t)||/^(?:css|sc|jsx|emotion|styled|svelte|astro|chakra|mui|makeStyles|jss)-/i.test(t)||/^[a-z]{1,3}-?\\d+$/i.test(t)&&/\\d/.test(t)||/__[\\w-]{5,}$/.test(t)&&/[A-Z\\d]/.test(t.slice(t.lastIndexOf(\"__\")+2))||/^(?=.*\\d)(?=.*[a-z])[a-z0-9]{6,}$/i.test(t)||/^[A-Z0-9]{5,}$/i.test(t)&&/[a-z]/.test(t)&&/[A-Z]/.test(t)&&!/^[A-Z]?[a-z]+(?:[A-Z][a-z]+)*$/.test(t)||M.test(t))}function h(t){let e=t.getAttribute(\"class\");return e?e.split(/\\s+/).filter(n=>n&&!W(n)):[]}function g(t){return t.tagName.toLowerCase()}function m(t,e){try{return t.querySelectorAll(e).length}catch{return 0}}function A(t,e,n){try{let r=t.querySelectorAll(e);return{count:r.length,includes:Array.prototype.includes.call(r,n)}}catch{return{count:0,includes:!1}}}function $(t,e){try{return t.matches(e)}catch{return!1}}function C(t){let e=[];for(let n of w){let r=t.getAttribute(n);r&&r.length<=80&&e.push({selector:`[${n}=${f(r)}]`,strategy:n})}return e}function S(t){let e=g(t),n=[],r=t.getAttribute(\"aria-label\");r&&r.length<=80&&n.push({selector:`${e}[aria-label=${f(r)}]`,strategy:\"aria-label\"});let i=t.getAttribute(\"name\");i&&i.length<=60&&n.push({selector:`${e}[name=${f(i)}]`,strategy:\"name\"});let s=t.getAttribute(\"itemprop\");s&&s.length<=60&&n.push({selector:`[itemprop=${f(s)}]`,strategy:\"itemprop\"});let c=t.getAttribute(\"role\");if(c&&r&&r.length<=80&&n.push({selector:`[role=${f(c)}][aria-label=${f(r)}]`,strategy:\"role\"}),e===\"a\"){let o=t.getAttribute(\"href\");o&&o.length<=60&&!o.startsWith(\"javascript:\")&&!o.includes(\"?\")&&/^(?:[/#.]|[\\w-]+\\/|https?:\\/\\/[^/]+\\/?$)/.test(o)&&n.push({selector:`a[href=${f(o)}]`,strategy:\"href\"})}return n}function I(t){let e=h(t);if(!e.length)return[];let n=g(t),r=[],i=e.slice(0,3).map(s=>`.${d(s)}`).join(\"\");r.push({selector:`${n}${i}`,strategy:\"class\"});for(let s of e.slice(0,3))r.push({selector:`${n}.${d(s)}`,strategy:\"class\"});return r}function E(t){let e=h(t).slice(0,2);return`${g(t)}${e.map(n=>`.${d(n)}`).join(\"\")}`}function v(t){let e=E(t),n=t.parentElement;if(!n)return e;let r=Array.from(n.children);if(!r.some(c=>c!==t&&$(c,e)))return e;let s=r.filter(c=>c.tagName===t.tagName).indexOf(t)+1;return`${e}:nth-of-type(${s})`}function R(t,e){for(let r of C(t))if(m(e,r.selector)===1)return r.selector;let n=t.getAttribute(\"id\");if(n&&!x(n)){let r=`#${d(n)}`;if(m(e,r)===1)return r}return null}function b(t,e,n=!1){let r=[],i=t;for(;i&&i!==e.documentElement;){if(i!==t){let o=R(i,e);if(o){r.unshift(o);let l=r.join(\" > \");if(m(e,l)===1)return l;r.shift()}}r.unshift(v(i));let s=r.join(\" > \"),c=r.length===1&&r[0]?.includes(\":nth-of-type\");if(!n&&!c&&m(e,s)===1)return s;if(i===e.body)break;i=i.parentElement}return r.join(\" > \")}function F(t){let e=t.parentElement;if(!e)return 0;let n=E(t);return Array.from(e.children).filter(r=>$(r,n)).length}function q(t){let e=h(t).length>0;return F(t)>=(e?2:3)}function X(t,e){let n=[],r=t;for(let i=0;r&&r!==e.body&&r!==e.documentElement&&i<8;i++)q(r)&&n.push(r),r=r.parentElement;return n}function Z(t,e){let n=R(t,e);if(n)return n;for(let r of[...S(t),...I(t)])if(m(e,r.selector)===1)return r.selector;return b(t,e)}function K(t,e,n){let r=e.parentElement;if(!r)return null;let s=[r===n.body||r===n.documentElement?\"body\":Z(r,n),E(e)],c=[],o=t;for(;o&&o!==e;)c.unshift(v(o)),o=o.parentElement;return[...s,...c]}function P(t,e){try{return Array.from(t.querySelectorAll(e))}catch{return null}}var U=(t,e)=>t.length===e.length&&t.every((n,r)=>n===e[r]);function G(t,e,n=[]){for(let r of X(t,e)){let i=K(t,r,e);if(!i)continue;let s=P(e,i.join(\" > \"));if(!s||s.length<2||!s.includes(t))continue;let c=[...n];for(let l=i.length-1;l>=0;l--)c.push(i.slice(l).join(\" > \"));return{selector:c.filter(l=>{let u=P(e,l);return!!u&&U(u,s)}).sort((l,u)=>l.length-u.length)[0]??i.join(\" > \"),count:s.length}}return null}function V(t,e){let n=[];n.push(...C(t));let r=t.getAttribute(\"id\");r&&!x(r)&&n.push({selector:`#${d(r)}`,strategy:\"id\"}),n.push(...S(t)),n.push(...I(t)),n.push({selector:b(t,e),strategy:\"path\"});let i=new Set,s=[],c=[];for(let a of n){if(i.has(a.selector))continue;i.add(a.selector);let{count:p,includes:L}=A(e,a.selector,t);L&&(p===1?s.push({selector:a.selector,matchCount:1,strategy:a.strategy}):a.strategy!==\"path\"&&c.push({selector:a.selector,matchCount:p,strategy:\"repeated\"}))}let o=[],l=G(t,e,c.map(a=>a.selector));if(l&&(o.push({selector:l.selector,matchCount:l.count,strategy:\"repeated\"}),o.push(...c.filter(a=>a.selector!==l.selector))),!s.length){let a=b(t,e,!0),{count:p}=A(e,a,t);s.push({selector:a,matchCount:p,strategy:\"path\"})}let u=o.length>0?1:0;return[...s.slice(0,3-u),...o.slice(0,u)]}function k(t){let e=t.normalize(\"NFKD\").replace(/\\p{M}/gu,\"\").replace(/([a-z0-9])([A-Z])/g,\"$1 $2\").split(/[^A-Z0-9]+/i).filter(Boolean).slice(0,4);if(!e.length)return\"\";let[n,...r]=e.map(s=>s.toLowerCase()),i=(n??\"\")+r.map(s=>s.charAt(0).toUpperCase()+s.slice(1)).join(\"\");return/^\\d/.test(i)?`field${i.charAt(0).toUpperCase()}${i.slice(1)}`:i}function Y(t){let e=[t.getAttribute(\"aria-label\"),t.getAttribute(\"name\"),t.getAttribute(\"placeholder\"),...w.map(n=>t.getAttribute(n)),t.getAttribute(\"itemprop\"),(()=>{let n=t.getAttribute(\"id\");return n&&!x(n)?n:null})(),t.getAttribute(\"title\"),t.getAttribute(\"alt\"),(()=>{let n=(t.textContent??\"\").replace(/\\s+/g,\" \").trim();return n.length>0&&n.length<=40&&/[A-Z]/i.test(n)?n:null})(),h(t)[0]];for(let n of e){if(!n)continue;let r=k(n);if(r)return r}return k(g(t))||\"element\"}function J(t){let n={text:(t.textContent??\"\").replace(/\\s+/g,\" \").trim().slice(0,200)},r=o=>{let l=t.getAttribute(o);return l?l.slice(0,500):void 0},i=t.href??r(\"href\");typ\u0065of i==\"string\"&&i&&(n.href=i.slice(0,500));let s=t.src??r(\"src\");typ\u0065of s==\"string\"&&s&&(n.src=s.slice(0,500));let c=g(t);if(c===\"input\"||c===\"textarea\"||c===\"select\"){let o=t.value;typ\u0065of o==\"string\"&&o&&(n.value=o.slice(0,200))}return n}function _(t){let e=h(t);return`${g(t)}${e.length?`.${e[0]}`:\"\"}`}function D(t,e){let n=g(t);return{tagName:n,isInput:[\"input\",\"textarea\",\"select\"].includes(n),candidates:V(t,e),suggestedName:Y(t),sample:J(t)}}var y=\"__scrapeAdminPicker\";function N(t){let e=t.getBoundingClientRect();return{x:e.x,y:e.y,width:e.width,height:e.height}}function tt(t,e){return t instanceof Error&&t.message?t.message:e}function et(t){let e=t.document;function n(s,c){try{if(!Number.isFinite(s)||!Number.isFinite(c))return null;let o=e.elementFromPoint(s,c);if(!o||o===e.documentElement||o===e.body)return null;let l=D(o,e),u=l.candidates[0]?.matchCount??0;return{box:N(o),label:`${_(o)} · ${u} match${u===1?\"\":\"es\"}`,picked:l}}catch{return null}}function r(s){if(typ\u0065of s!=\"string\"||!s.trim())return{count:0,boxes:[],error:\"Empty selector\"};let c;try{c=e.querySelectorAll(s)}catch(l){return{count:0,boxes:[],error:tt(l,\"Invalid selector\")}}let o=[];try{for(let l=0;l<c.length&&l<150;l++){let u=c[l];u&&o.push(N(u))}}catch{}return{count:c.length,boxes:o}}function i(){let s=e.documentElement;return{url:String(t.location?.href??\"\"),title:String(e.title??\"\"),viewport:{width:t.innerWidth||s?.clientWidth||0,height:t.innerHeight||s?.clientHeight||0},scroll:{x:t.scrollX||0,y:t.scrollY||0},devicePixelRatio:t.devicePixelRatio||1}}return{version:1,at:n,highlight:r,describe:i}}function j(t){try{let n=t[y];if(n&&typ\u0065of n.at==\"function\"&&(n.version??0)>=1)return n;let r=et(t);return Object.defineProperty(t,y,{value:r,configurable:!0,enumerable:!1,writable:!0}),r}catch{return null}}typ\u0065of window<\"u\"&&j(window);})();"
|
package/package.json
CHANGED
|
@@ -1,6 +1,46 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@scrape-admin/element-picker",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "0.1.1",
|
|
4
|
+
"description": "Framework-agnostic DOM element picker: stable selector generation and an injectable in-page picker.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"license": "MIT",
|
|
7
|
+
"repository": {
|
|
8
|
+
"type": "git",
|
|
9
|
+
"url": "git+https://github.com/hareland-eu/scrape-admin-standalone.git",
|
|
10
|
+
"directory": "packages/element-picker"
|
|
11
|
+
},
|
|
12
|
+
"publishConfig": {
|
|
13
|
+
"access": "public"
|
|
14
|
+
},
|
|
15
|
+
"main": "./dist/index.mjs",
|
|
16
|
+
"exports": {
|
|
17
|
+
".": {
|
|
18
|
+
"import": "./dist/index.mjs",
|
|
19
|
+
"types": "./dist/index.d.ts"
|
|
20
|
+
},
|
|
21
|
+
"./inject": {
|
|
22
|
+
"import": "./dist/inject.mjs",
|
|
23
|
+
"types": "./dist/inject.d.ts"
|
|
24
|
+
}
|
|
25
|
+
},
|
|
26
|
+
"files": [
|
|
27
|
+
"dist",
|
|
28
|
+
"LICENSE"
|
|
29
|
+
],
|
|
30
|
+
"devDependencies": {
|
|
31
|
+
"esbuild": "^0.28.2",
|
|
32
|
+
"eslint": "^10.12.0",
|
|
33
|
+
"happy-dom": "20.14.6",
|
|
34
|
+
"typescript": "^5.8.0",
|
|
35
|
+
"unbuild": "^3.6.1",
|
|
36
|
+
"vitest": "^5.0.3",
|
|
37
|
+
"@scrape-admin/eslint-config": "0.0.0"
|
|
38
|
+
},
|
|
39
|
+
"scripts": {
|
|
40
|
+
"build": "unbuild",
|
|
41
|
+
"test": "vitest run",
|
|
42
|
+
"typecheck": "tsc --noEmit -p tsconfig.json",
|
|
43
|
+
"lint": "eslint . --cache --cache-strategy content --cache-location node_modules/.cache/eslint/",
|
|
44
|
+
"lint:fix": "eslint --fix ."
|
|
45
|
+
}
|
|
6
46
|
}
|