e2e-web 0.1.0__py3-none-any.whl

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.
e2e_web/semantic.js ADDED
@@ -0,0 +1,329 @@
1
+ (() => {
2
+ const key = Symbol.for('e2e.web.semantic.v1');
3
+ if (globalThis[key]) return;
4
+ const roots = new WeakMap(), ids = new WeakMap(), elements = new Map(), search = new Map();
5
+ const documentId = crypto.randomUUID ? crypto.randomUUID() : `${Date.now()}-${Math.random()}`;
6
+ let next = 0;
7
+ const original = Element.prototype.attachShadow;
8
+ Element.prototype.attachShadow = function(init) {
9
+ const root = original.call(this, init);
10
+ if (root.mode === 'closed') roots.set(this, root);
11
+ return root;
12
+ };
13
+ const clean = value => String(value ?? '').replace(/\s+/g, ' ').trim().slice(0, 512);
14
+ const buttonInput = type => ['button', 'submit', 'reset', 'image'].includes(type);
15
+ const structure = {
16
+ article:'article', aside:'complementary', details:'group', dialog:'dialog',
17
+ fieldset:'group', form:'form', main:'main', nav:'navigation', section:'group',
18
+ ol:'list', ul:'list', li:'listitem',
19
+ table:'table', thead:'rowgroup', tbody:'rowgroup', tfoot:'rowgroup', tr:'row', td:'cell',
20
+ };
21
+ const parentOf = el => el.parentElement || el.getRootNode()?.host || null;
22
+ const flatParentOf = el => {
23
+ if (el.assignedSlot) return el.assignedSlot;
24
+ const root = roots.get(el.parentElement);
25
+ if (root) {
26
+ for (const slot of root.querySelectorAll('slot')) {
27
+ if (slot.assignedElements().includes(el)) return slot;
28
+ }
29
+ }
30
+ return parentOf(el);
31
+ };
32
+ const inside = (el, ancestor, parent = flatParentOf) => {
33
+ for (let node = el; node; node = parent(node)) if (node === ancestor) return true;
34
+ return false;
35
+ };
36
+ const scrollable = (el, style = getComputedStyle(el)) => {
37
+ let axes = '';
38
+ if (/^(auto|scroll|overlay)$/.test(style.overflowX) && el.scrollWidth > el.clientWidth) axes += 'x';
39
+ if (/^(auto|scroll|overlay)$/.test(style.overflowY) && el.scrollHeight > el.clientHeight) axes += 'y';
40
+ return axes;
41
+ };
42
+ const role = (el, axes) => {
43
+ const explicit = (el.getAttribute('role') || '').trim();
44
+ if (explicit && !/^(none|presentation)(\s|$)/.test(explicit)) return explicit.split(/\s+/)[0].slice(0, 64);
45
+ const tag = el.tagName.toLowerCase();
46
+ if (!explicit) {
47
+ if (tag === 'th') return el.scope === 'row' ? 'rowheader' : 'columnheader';
48
+ if (structure[tag]) return structure[tag];
49
+ }
50
+ if (/^h[1-6]$/.test(tag)) return 'heading';
51
+ if (tag === 'input') {
52
+ if (buttonInput(el.type)) return 'button';
53
+ if (el.list && ['text', 'search', 'email', 'tel', 'url'].includes(el.type)) return 'combobox';
54
+ return ({checkbox:'checkbox',radio:'radio',range:'slider',number:'spinbutton',search:'searchbox',hidden:'none'})[el.type] || 'textbox';
55
+ }
56
+ if (tag === 'select') return el.multiple || el.size > 1 ? 'listbox' : 'combobox';
57
+ const native = ({button:'button',a:el.hasAttribute('href')?'link':'',textarea:'textbox',
58
+ option:'option',img:'img',summary:'button',canvas:'canvas',iframe:'iframe'})[tag];
59
+ if (native && !explicit) return native;
60
+ if (el.isContentEditable && !parentOf(el)?.isContentEditable) return 'textbox';
61
+ if (axes || el.hasAttribute('data-testid') || el.hasAttribute('aria-label') ||
62
+ el.hasAttribute('aria-labelledby') || el.hasAttribute('tabindex') ||
63
+ el.hasAttribute('onclick') || typeof el.onclick === 'function') return 'generic';
64
+ return !el.children.length && clean(el.textContent) ? 'text' : '';
65
+ };
66
+ const labelText = (label, control) => {
67
+ if (!label.contains(control)) return clean(label.textContent);
68
+ const walker = document.createTreeWalker(label, NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_TEXT,
69
+ node => node === control ? NodeFilter.FILTER_REJECT :
70
+ node.nodeType === Node.TEXT_NODE ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_SKIP);
71
+ let text = '';
72
+ for (let node = walker.nextNode(); node && text.length < 1024; node = walker.nextNode()) text += node.textContent;
73
+ return clean(text);
74
+ };
75
+ const contentRoles = new Set(['button','cell','checkbox','columnheader','gridcell','heading','link',
76
+ 'menuitem','menuitemcheckbox','menuitemradio','option','radio','rowheader','switch','tab','tooltip','treeitem']);
77
+ const textRoles = new Set(['caption','code','contentinfo','definition','deletion','emphasis','generic',
78
+ 'insertion','list','listitem','mark','none','paragraph','presentation','region','row','rowgroup',
79
+ 'section','strong','subscript','superscript','table','term','text','time']);
80
+ const captionTags = {FIELDSET:'legend', FIGURE:'figcaption', TABLE:'caption'};
81
+ const nameFromContent = el => {
82
+ let text = '', visited = 0;
83
+ const append = value => { text += String(value ?? '').slice(0, 1024 - text.length); };
84
+ const walk = (node, depth) => {
85
+ if (++visited > 512 || text.length >= 1024 || depth > 32) return;
86
+ if (node.nodeType === Node.TEXT_NODE) { append(node.textContent); return; }
87
+ if (node.nodeType !== Node.ELEMENT_NODE || node.matches('script,style,template,[inert]')) return;
88
+ const style = getComputedStyle(node);
89
+ if (hidesSubtree(node, style)) return;
90
+ const spaced = node.tagName === 'BR' || !['inline','contents','inline-block','inline-flex','inline-grid'].includes(style.display);
91
+ if (spaced) append(' ');
92
+ const explicit = node.getAttribute('role')?.trim().split(/\s+/)[0];
93
+ const r = explicit || role(node, '');
94
+ const refs = (node.getAttribute('aria-labelledby') || '').split(/\s+/);
95
+ const labelled = refs.map(id => node.getRootNode().getElementById?.(id)?.textContent || '').join(' ');
96
+ const alternative = clean(labelled) || clean(node.getAttribute('aria-label')) ||
97
+ clean(node.getAttribute('alt')) || (node.tagName.toLowerCase() === 'svg' ? clean(node.querySelector('title')?.textContent) : '');
98
+ if (alternative) append(alternative);
99
+ else if (!r || contentRoles.has(r) || textRoles.has(r)) {
100
+ children(node, depth);
101
+ } else {
102
+ const caption = captionTags[node.tagName];
103
+ append((caption && node.querySelector(`:scope > ${caption}`)?.textContent) || node.getAttribute('title'));
104
+ }
105
+ if (spaced) append(' ');
106
+ };
107
+ const children = (node, depth) => {
108
+ const assigned = node.tagName === 'SLOT' ? node.assignedNodes() : null;
109
+ const children = assigned?.length ? assigned : (node.shadowRoot || roots.get(node) || node).childNodes;
110
+ for (const child of children) {
111
+ if (visited >= 512 || text.length >= 1024) break;
112
+ walk(child, depth + 1);
113
+ }
114
+ };
115
+ children(el, 0);
116
+ return clean(text);
117
+ };
118
+ const name = (el, r) => {
119
+ const labelled = el.getAttribute('aria-labelledby');
120
+ if (labelled) {
121
+ const root = el.getRootNode();
122
+ const text = labelled.split(/\s+/).map(id => root.getElementById?.(id)?.textContent || '').join(' ');
123
+ if (clean(text)) return clean(text);
124
+ }
125
+ const label = clean(el.getAttribute('aria-label')) || Array.from(el.labels || [], l => labelText(l, el)).filter(Boolean).join(' ');
126
+ if (label) return clean(label);
127
+ if (el.tagName === 'INPUT' && buttonInput(el.type)) {
128
+ const fallback = {submit:'Submit',reset:'Reset',image:'Submit'}[el.type];
129
+ const caption = el.type === 'image' ? el.getAttribute('alt') : el.value;
130
+ return clean(caption || el.getAttribute('title') || fallback);
131
+ }
132
+ if (el.tagName === 'OPTION') return clean(el.label);
133
+ if (el.tagName === 'FIELDSET') return clean(el.querySelector(':scope > legend')?.textContent);
134
+ if (el.tagName === 'TABLE') return clean(el.caption?.textContent || el.title);
135
+ if (el.tagName === 'TR') {
136
+ return clean(Array.prototype.slice.call(el.cells, 0, 32).map(cell => cell.textContent).join(' '));
137
+ }
138
+ const title = el.getAttribute('title');
139
+ if (['INPUT','TEXTAREA','SELECT','IFRAME'].includes(el.tagName) || el.isContentEditable) {
140
+ return clean(title || el.getAttribute('placeholder'));
141
+ }
142
+ if (['group','form','list','rowgroup','navigation','main','complementary','article','dialog'].includes(r)) {
143
+ return clean(title);
144
+ }
145
+ if (contentRoles.has(r)) return clean(el.getAttribute('alt')) || nameFromContent(el) || clean(title);
146
+ return clean(el.getAttribute('alt') || el.textContent || title) || clean(title);
147
+ };
148
+ const selectOptions = el => {
149
+ const limit = 32;
150
+ const options = new Set(Array.prototype.slice.call(el.selectedOptions, 0, limit));
151
+ for (let i = 0; i < el.options.length && options.size < limit; i++) options.add(el.options[i]);
152
+ return {options: [...options].sort((a, b) => a.index - b.index).map(option => ({
153
+ name: clean(option.label), index: option.index, selected: option.selected, disabled: option.matches(':disabled'),
154
+ })), multiple: el.multiple, options_truncated: el.options.length > options.size};
155
+ };
156
+ const focusedElement = () => {
157
+ let active = document.activeElement;
158
+ while (active) {
159
+ const inner = (active.shadowRoot || roots.get(active))?.activeElement;
160
+ if (!inner) break;
161
+ active = inner;
162
+ }
163
+ return active;
164
+ };
165
+ const modalOrder = new WeakMap(), modalRefs = new WeakMap(), trackedModals = new Set();
166
+ let opening = 0;
167
+ const isModal = el => {
168
+ try { return el.matches('dialog:modal'); } catch { return false; }
169
+ };
170
+ if (typeof HTMLDialogElement !== 'undefined' && typeof HTMLDialogElement.prototype.showModal === 'function') {
171
+ const showModal = HTMLDialogElement.prototype.showModal;
172
+ HTMLDialogElement.prototype.showModal = function(...args) {
173
+ const wasOpen = this.open;
174
+ const result = showModal.apply(this, args);
175
+ if (!wasOpen && isModal(this)) {
176
+ if (!modalOrder.has(this)) {
177
+ modalRefs.set(this, new WeakRef(this));
178
+ this.addEventListener('beforetoggle', event => {
179
+ if (event.newState === 'open') {
180
+ modalOrder.set(this, ++opening);
181
+ trackedModals.add(modalRefs.get(this));
182
+ }
183
+ });
184
+ }
185
+ modalOrder.set(this, ++opening);
186
+ trackedModals.add(modalRefs.get(this));
187
+ }
188
+ return result;
189
+ };
190
+ }
191
+ const activeModal = () => {
192
+ for (let node = focusedElement(); node; node = flatParentOf(node)) {
193
+ if (isModal(node)) return node;
194
+ }
195
+ let open;
196
+ try { open = new Set(document.querySelectorAll('dialog:modal')); } catch { return null; }
197
+ for (const ref of trackedModals) {
198
+ const el = ref.deref();
199
+ if (el && isModal(el)) open.add(el);
200
+ else trackedModals.delete(ref);
201
+ }
202
+ if (open.size < 2) return open.values().next().value || null;
203
+ let newest = null, order = 0;
204
+ for (const el of open) {
205
+ const current = modalOrder.get(el);
206
+ if (current === undefined) return null;
207
+ if (current > order) { newest = el; order = current; }
208
+ }
209
+ return newest;
210
+ };
211
+ const selectionOf = el => {
212
+ if (el.type === 'password' || el.matches('[autocomplete~="one-time-code" i]')) return '';
213
+ if (typeof el.selectionStart === 'number') return clean(el.value.slice(el.selectionStart, el.selectionEnd));
214
+ if (!el.isContentEditable) return '';
215
+ const root = el.getRootNode();
216
+ const selected = root.getSelection?.() || document.getSelection();
217
+ return selected?.anchorNode && selected?.focusNode && el.contains(selected.anchorNode) && el.contains(selected.focusNode)
218
+ ? clean(selected.toString()) : '';
219
+ };
220
+ const describe = (el, axes = scrollable(el), r = role(el, axes)) => {
221
+ const rect = el.getBoundingClientRect();
222
+ const nativeCheck = el.matches('input[type=checkbox],input[type=radio]');
223
+ const ariaChecked = el.getAttribute('aria-checked');
224
+ const disabled = el.matches(':disabled') || el.closest('[aria-disabled]')?.getAttribute('aria-disabled') === 'true';
225
+ const readonly = el.readOnly === true || el.getAttribute('aria-readonly') === 'true';
226
+ const editable = el.isContentEditable || el.matches('textarea') ||
227
+ (el.matches('input') && !['button','submit','reset','image','checkbox','radio','file','range','hidden'].includes(el.type));
228
+ const expanded = el.getAttribute('aria-expanded');
229
+ const pressed = el.getAttribute('aria-pressed');
230
+ const details = el.tagName === 'SUMMARY' && el.parentElement?.tagName === 'DETAILS' ? el.parentElement : null;
231
+ const activeId = el.getAttribute('aria-activedescendant');
232
+ const active = activeId ? el.getRootNode().getElementById?.(activeId) : null;
233
+ const focused = el.getRootNode().activeElement === el && !(el.shadowRoot || roots.get(el))?.activeElement;
234
+ const selection = focused ? selectionOf(el) : '';
235
+ return {role:r,name:name(el, r),test_id:clean(el.getAttribute('data-testid')),
236
+ disabled, readonly, editable:editable && !readonly && !disabled,
237
+ checked:nativeCheck ? el.checked : ariaChecked === 'true',
238
+ indeterminate:nativeCheck ? el.indeterminate : ariaChecked === 'mixed',
239
+ selected:el.selected === true || el.getAttribute('aria-selected') === 'true',
240
+ expanded:expanded === null ? (details ? details.open : null) : expanded === 'true',
241
+ pressed:pressed === 'mixed' ? 'mixed' : (pressed === null ? null : pressed === 'true'),
242
+ focused,
243
+ ...(selection ? {selection} : {}),
244
+ ...(active ? {active_descendant: name(active, active.getAttribute('role'))} : {}),
245
+ ...(el.getAttribute('aria-multiselectable') === 'true' ? {multiselectable:true} : {}),
246
+ scrollable:axes,
247
+ input_type:typeof el.type === 'string' ? el.type : '',
248
+ value:el.type === 'password' || el.matches('[autocomplete~="one-time-code" i]') ? '<masked>' : clean(el.value),
249
+ bounds:{x:rect.x,y:rect.y,width:rect.width,height:rect.height},
250
+ in_viewport:rect.bottom>0 && rect.right>0 && rect.top<innerHeight && rect.left<innerWidth};
251
+ };
252
+ // A form control named "hidden" can shadow the form's DOM property.
253
+ const hidesSubtree = (el, style) => el.getAttribute('aria-hidden') === 'true' || el.hasAttribute('hidden') ||
254
+ style.display === 'none' || ['hidden','collapse'].includes(style.visibility);
255
+ const hiddenAncestor = el => {
256
+ for (let p=el; p; p=parentOf(p)) {
257
+ if (hidesSubtree(p, getComputedStyle(p))) return true;
258
+ }
259
+ return false;
260
+ };
261
+ const inActiveModal = el => {
262
+ const modal = activeModal();
263
+ return !modal || inside(el, modal);
264
+ };
265
+ const elementAt = ({x, y}) => {
266
+ let el = document.elementFromPoint(x, y);
267
+ while (el) {
268
+ const inner = (el.shadowRoot || roots.get(el))?.elementFromPoint(x, y);
269
+ if (!inner || inner === el || !inside(inner, el)) break;
270
+ el = inner;
271
+ }
272
+ return el && inActiveModal(el) ? el : null;
273
+ };
274
+ const visible = el => el.isConnected && el.getClientRects().length > 0 && !hiddenAncestor(el) && inActiveModal(el);
275
+ const matchesContext = (el, context) => {
276
+ const parent = elements.get(context.id)?.deref();
277
+ for (let p = parentOf(el); p; p = parentOf(p)) {
278
+ if (p === parent) {
279
+ return clean(p.getAttribute('data-testid')) === context.test_id && name(p, context.role) === context.name;
280
+ }
281
+ }
282
+ return false;
283
+ };
284
+ const scan = ({maxNodes=200,maxElements=10000,root=null,replace=true}={}) => {
285
+ const lookup = replace ? elements : search;
286
+ lookup.clear();
287
+ const modal = activeModal();
288
+ const start = modal && (!root || inside(modal, root)) ? modal : root || document.documentElement;
289
+ const nodes = [], seen = new Set();
290
+ const stack = start && (!modal || inside(start, modal)) && !hiddenAncestor(parentOf(start)) ? [[start, null, false]] : [];
291
+ let visited=0;
292
+ while(stack.length && visited < maxElements && nodes.length < maxNodes) {
293
+ const [el, parent_id, siblings]=stack.pop(); visited++;
294
+ // Iterate lazily: even a root with millions of children is bounded.
295
+ if (siblings && el.nextElementSibling) stack.push([el.nextElementSibling, parent_id, true]);
296
+ if (seen.has(el)) continue;
297
+ seen.add(el);
298
+ const style = getComputedStyle(el);
299
+ if (hidesSubtree(el, style)) continue;
300
+ let childParent = parent_id;
301
+ if (el.getClientRects().length) {
302
+ const axes = scrollable(el, style);
303
+ const r = role(el, axes);
304
+ if (r) {
305
+ let id=ids.get(el);
306
+ if (!id) {id=`${documentId}:${++next}`; ids.set(el,id);}
307
+ lookup.set(id,new WeakRef(el));
308
+ nodes.push({id,parent_id,...describe(el, axes, r),
309
+ ...(el.tagName === 'SELECT' ? selectOptions(el) : {}),
310
+ ...(el.tagName === 'OPTION' && el.closest('select') ? {native_option:true} : {})});
311
+ childParent = id;
312
+ }
313
+ }
314
+ const shadow=el.shadowRoot || roots.get(el);
315
+ const assigned = modal && el.tagName === 'SLOT' ? el.assignedElements() : [];
316
+ if (assigned.length) {
317
+ for (let index = Math.min(assigned.length, maxElements); index > 0; index--) {
318
+ stack.push([assigned[index - 1], childParent, false]);
319
+ }
320
+ } else if ((!modal || !shadow) && el.firstElementChild) stack.push([el.firstElementChild, childParent, true]);
321
+ if (shadow?.firstElementChild) stack.push([shadow.firstElementChild, childParent, true]);
322
+ }
323
+ return {nodes,truncated:stack.length>0,visited,document:documentId,modal:!!modal,root_id:root ? ids.get(root) || null : null};
324
+ };
325
+ Object.defineProperty(globalThis,key,{value:{
326
+ scan, describe, visible, matchesContext, focusedElement, activeModal, inside, inActiveModal, elementAt,
327
+ resolve:(id, searched) => (searched ? search : elements).get(id)?.deref() || null,
328
+ },configurable:false});
329
+ })();
e2e_web/semantics.py ADDED
@@ -0,0 +1,135 @@
1
+ """Bounded structured observations and main-world closed shadow tracking."""
2
+
3
+ from pathlib import Path
4
+ import time
5
+
6
+ from .errors import StepTimeout
7
+
8
+ SEMANTIC_INIT = Path(__file__).with_name("semantic.js").read_text(encoding="utf-8")
9
+ DESCRIBE = "el => globalThis[Symbol.for('e2e.web.semantic.v1')].describe(el)"
10
+ FRAME_IDENTITY = "el => Object.fromEntries(['id','name','src','title'].map(k=>[k,el.getAttribute(k)||'']))"
11
+ VISIBLE = "el => globalThis[Symbol.for('e2e.web.semantic.v1')].visible(el)"
12
+ IN_ACTIVE_MODAL = "el => globalThis[Symbol.for('e2e.web.semantic.v1')]?.inActiveModal(el) ?? true"
13
+ MODAL_FRAME_INDICES = """frames => {
14
+ const semantics = globalThis[Symbol.for('e2e.web.semantic.v1')];
15
+ const modal = semantics.activeModal();
16
+ return frames.flatMap((el, index) => !modal || semantics.inside(el, modal) ? [index] : []);
17
+ }"""
18
+ ELEMENT_AT = "point => globalThis[Symbol.for('e2e.web.semantic.v1')].elementAt(point)"
19
+ FRAME_POINT = """(el, point) => {
20
+ const rect = el.getBoundingClientRect();
21
+ if (!rect.width || !rect.height || !el.offsetWidth || !el.offsetHeight) return null;
22
+ const x = (point.x - rect.left) * el.offsetWidth / rect.width - el.clientLeft;
23
+ const y = (point.y - rect.top) * el.offsetHeight / rect.height - el.clientTop;
24
+ return x >= 0 && y >= 0 && x < el.clientWidth && y < el.clientHeight ? {x, y} : null;
25
+ }"""
26
+ MATCHES_CONTEXT = "(el, context) => globalThis[Symbol.for('e2e.web.semantic.v1')].matchesContext(el, context)"
27
+ FOCUSED_ELEMENT = """() => globalThis[Symbol.for('e2e.web.semantic.v1')]?.focusedElement?.() ??
28
+ document.activeElement"""
29
+ FOCUSED_INPUT = """el => {
30
+ if (!el.isConnected || el.matches(':disabled') ||
31
+ el.closest('[aria-disabled="true"], [aria-readonly="true"], [inert]')) return null;
32
+ if (el instanceof HTMLInputElement) {
33
+ return !el.readOnly && ['text','search','tel','url','email','password','number'].includes(el.type)
34
+ ? 'editable' : null;
35
+ }
36
+ if (el instanceof HTMLTextAreaElement) return el.readOnly ? null : 'editable';
37
+ if (el.isContentEditable) return 'editable';
38
+ return el.hasAttribute('tabindex') && !el.matches('html,body,a,button,select,iframe,frame')
39
+ ? 'keyboard' : null;
40
+ }"""
41
+ CONTAINS = """(node, container) => {
42
+ for (let p = node.parentElement || node.getRootNode().host; p;
43
+ p = p.parentElement || p.getRootNode().host) {
44
+ if (p === container) return true;
45
+ }
46
+ return false;
47
+ }"""
48
+ SCROLL_STATE = """element => {
49
+ const el = element || document.scrollingElement;
50
+ return [el.scrollLeft, el.scrollTop, el.scrollWidth, el.scrollHeight];
51
+ }"""
52
+ DESCENDANTS = f"(nodes, container) => nodes.flatMap((node, index) => ({CONTAINS})(node, container) ? [index] : [])"
53
+ SCROLL = """(el, {x, y, page}) => {
54
+ const style = getComputedStyle(el);
55
+ const acceptsScroll = overflow => /^(auto|scroll|overlay)$/.test(overflow);
56
+ const dx = acceptsScroll(style.overflowX) ? x : 0;
57
+ const dy = acceptsScroll(style.overflowY) ? y : 0;
58
+ el.scrollBy({
59
+ left: page ? dx * Math.max(1, Math.floor(el.clientWidth * 0.8)) : dx,
60
+ top: page ? dy * Math.max(1, Math.floor(el.clientHeight * 0.8)) : dy,
61
+ behavior: 'instant',
62
+ });
63
+ }"""
64
+ SELECT_OPTIONS = """(el, {choices, batch}) => {
65
+ const select = el.matches('select') ? el : el.closest('label')?.control;
66
+ if (!(select instanceof HTMLSelectElement)) return {problem: 'not-select'};
67
+ if (batch && !select.multiple) return {problem: 'not-multiple'};
68
+ const options = Array.from(select.options);
69
+ const selected = new Set();
70
+ for (const choice of choices) {
71
+ const [field, value] = Object.entries(choice)[0];
72
+ const matches = field === 'index' ? options.slice(value, value + 1) :
73
+ options.filter(option => option[field] === value);
74
+ if (!matches.length) return {problem: 'missing'};
75
+ if (matches.length > 1) return {problem: 'ambiguous'};
76
+ if (matches[0].matches(':disabled')) return {problem: 'disabled'};
77
+ selected.add(matches[0]);
78
+ }
79
+ return {select, options: [...selected]};
80
+ }"""
81
+ CHECK_STATE = """el => {
82
+ const control = el.matches('input') ? el : el.closest('label')?.control || el;
83
+ const native = control.matches('input[type=checkbox],input[type=radio]');
84
+ return {
85
+ connected: el.isConnected,
86
+ type: native ? control.type : null,
87
+ mixed: native ? control.indeterminate : el.getAttribute('aria-checked') === 'mixed',
88
+ };
89
+ }"""
90
+
91
+
92
+ def install(scope, *, timeout):
93
+ """Also install into a borrowed document; existing closed roots stay inaccessible."""
94
+ scope.locator('html').evaluate('(el) => {' + SEMANTIC_INIT + '}', timeout=timeout * 1000)
95
+
96
+
97
+ def scan(scope, *, max_nodes, max_elements, timeout, root=None, replace=True):
98
+ end = time.monotonic() + timeout
99
+ install(scope, timeout=timeout)
100
+ remaining = end - time.monotonic()
101
+ if remaining <= 0:
102
+ raise StepTimeout('STEP_TIMEOUT', 'semantic observation deadline elapsed')
103
+ return scope.locator('html').evaluate(
104
+ '(el, options) => globalThis[Symbol.for("e2e.web.semantic.v1")].scan(options)',
105
+ dict(maxNodes=max_nodes, maxElements=max_elements, root=root, replace=replace), timeout=remaining * 1000)
106
+
107
+
108
+ def ancestors(node, nodes):
109
+ """Walk the listed parents of a node in its document."""
110
+ while parent := nodes.get(node.get('parent_id')):
111
+ yield parent
112
+ node = parent
113
+
114
+
115
+ def resolve(scope, node_id, *, timeout, searched=False):
116
+ handle = scope.locator('html').evaluate_handle(
117
+ '(el, {id, searched}) => globalThis[Symbol.for("e2e.web.semantic.v1")]?.resolve(id, searched) || null',
118
+ dict(id=node_id, searched=searched), timeout=timeout * 1000).as_element()
119
+ return ElementTarget(handle) if handle else None
120
+
121
+
122
+ class ElementTarget:
123
+ """Expose Locator-compatible calls on a resolved closed-root ElementHandle."""
124
+
125
+ def __init__(self, handle):
126
+ self.handle = handle
127
+
128
+ def __getattr__(self, name):
129
+ method = getattr(self.handle, 'type' if name == 'press_sequentially' else name)
130
+ if name in {'evaluate', 'get_attribute', 'is_enabled', 'is_editable', 'is_visible'}:
131
+ def call(*args, **kwargs):
132
+ kwargs.pop('timeout', None)
133
+ return method(*args, **kwargs)
134
+ return call
135
+ return method