@whenessel/seql-js 1.0.1 → 1.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,2 +1,2 @@
1
- (function(m,q){typeof exports=="object"&&typeof module<"u"?q(exports):typeof define=="function"&&define.amd?define(["exports"],q):(m=typeof globalThis<"u"?globalThis:m||self,q(m.SeqlJS={}))})(this,(function(m){"use strict";const F={ANCHOR:.4,PATH:.3,TARGET:.2,UNIQUENESS:.1},v={SEMANTIC_TAG:.5,ROLE:.3,ARIA_LABEL:.1,STABLE_ID:.1,TEST_MARKER:.05,DEPTH_PENALTY_THRESHOLD:5,DEPTH_PENALTY_FACTOR:.05,DEGRADED_SCORE:.3},Tt={MIN_CONFIDENCE_FOR_SKIP:.7},B=["form","main","nav","section","article","footer","header"],G=["form","navigation","main","region","contentinfo","complementary","banner","search"],tt=["article","aside","details","figcaption","figure","footer","header","main","mark","nav","section","summary","time","button","datalist","fieldset","form","input","label","legend","meter","optgroup","option","output","progress","select","textarea","a","audio","video","canvas","dialog","menu","blockquote","dd","dl","dt","hr","li","ol","ul","p","pre","h1","h2","h3","h4","h5","h6","caption","col","colgroup","table","tbody","td","tfoot","th","thead","tr","svg","path","circle","rect","line","polyline","polygon","ellipse","g","text","use"],wt=["rect","path","circle","line","polyline","polygon","ellipse","g","text","use","defs","clipPath","mask"],vt=["aria-label","aria-labelledby","aria-describedby","name","type","data-testid","data-qa","data-test","href","title","placeholder","alt"],T={"data-testid":100,"data-qa":99,"data-cy":98,"data-test":97,"data-test-id":96,"aria-label":90,"aria-labelledby":85,"aria-describedby":80,name:75,href:70,src:70,type:65,role:60,alt:55,title:50,for:45,placeholder:40,"data-*":30,"aria-*":25},et=new Set(["id","class","style","xmlns","tabindex","contenteditable"]),st={maxPathDepth:10,enableSvgFingerprint:!0,confidenceThreshold:.1,fallbackToBody:!0,includeUtilityClasses:!1,source:"dom-dsl"},rt={strictMode:!1,enableFallback:!0,maxCandidates:20};function O(n){return!!(/^[a-z]+-\d+$/i.test(n)||/^\d+$/.test(n)||/^:[a-z0-9]+:$/i.test(n)||/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i.test(n)||/^[a-z]{1,3}[A-Za-z0-9]{8,}$/.test(n)&&(/\d/.test(n)||/[A-Z]/.test(n))||/^radix-/.test(n)||/^mui-\d+$/.test(n))}class nt{constructor(t,e){this.maxDepth=t.maxPathDepth??10,this.cache=e}findAnchor(t){if(this.cache){const a=this.cache.getAnchor(t);if(a!==void 0)return a}let e=t.parentElement,s=0,r=null;for(;e&&s<this.maxDepth;){if(e.tagName.toLowerCase()==="body")return r||{element:e,score:v.DEGRADED_SCORE,tier:"C",depth:s};const a=this.scoreAnchor(e);if(a>0){const o=this.applyDepthPenalty(a,s),l=this.getTier(e),h={element:e,score:o,tier:l,depth:s};if(l==="A")return h;(!r||o>r.score)&&(r=h)}e=e.parentElement,s++}const i=r;return this.cache&&this.cache.setAnchor(t,i),i}scoreAnchor(t){let e=0;const s=t.tagName.toLowerCase();B.includes(s)&&(e+=v.SEMANTIC_TAG);const r=t.getAttribute("role");r&&G.includes(r)&&(e+=v.ROLE),(t.hasAttribute("aria-label")||t.hasAttribute("aria-labelledby"))&&(e+=v.ARIA_LABEL);const i=t.id;return i&&!O(i)&&(e+=v.STABLE_ID),(t.hasAttribute("data-testid")||t.hasAttribute("data-qa")||t.hasAttribute("data-test"))&&(e+=v.TEST_MARKER),Math.min(e,1)}applyDepthPenalty(t,e){if(e<=v.DEPTH_PENALTY_THRESHOLD)return t;const s=(e-v.DEPTH_PENALTY_THRESHOLD)*v.DEPTH_PENALTY_FACTOR;return Math.max(0,t-s)}getTier(t){const e=t.tagName.toLowerCase();if(B.includes(e))return"A";const s=t.getAttribute("role");return s&&G.includes(s)?"B":"C"}}const $t=[/^css-[a-z0-9]+$/i,/^sc-[a-z0-9]+-\d+$/i,/^[a-z]{5,8}$/i,/^Mui[A-Z]\w+-\w+-\w+/,/^makeStyles-\w+-\d+$/,/^jss\d+$/,/^(emotion|linaria)-[a-z0-9]+/i,/^(chakra|tw-|ant-)[a-z0-9]+-\w+/i,/-[a-f0-9]{6,}$/i,/^_[a-z0-9]{5,}$/i,/\d{5,}/],Mt=[/^\[/,/^(first|last|odd|even|only|first-of-type|last-of-type|only-of-type):/,/^(hover|focus|active|disabled|enabled|checked|indeterminate|default|required|valid|invalid|in-range|out-of-range|placeholder-shown|autofill|read-only):/,/^(focus-within|focus-visible|visited|target|open):/,/^(sm|md|lg|xl|2xl|3xl|4xl|5xl|6xl|7xl):/,/^dark:/,/^(rtl|ltr):/,/^(group|peer)(-hover|-focus|-active)?:/,/\/([\d.]+|full|auto|screen)$/,/^(inset|top|right|bottom|left)(-|$)/,/^(flex|inline-flex|grid|block|inline|inline-block|hidden|visible)$/,/^(absolute|relative|fixed|sticky|static)$/,/^(items|justify|content|self|place)-/,/^flex-(row|col|wrap|nowrap|1|auto|initial|none)/,/^grid-(cols|rows|flow)/,/^(gap|space)-/,/^[mp][trblxy]?-(\d+|auto|px)$/,/^(w|h|min-w|min-h|max-w|max-h|size)-/,/^text-(center|left|right|justify|start|end|xs|sm|base|lg|xl|2xl|3xl|4xl|5xl|6xl|7xl|8xl|9xl)$/,/^text-(uppercase|lowercase|capitalize|normal-case|underline|line-through|no-underline)$/,/^text-(truncate|ellipsis|clip)$/,/^(bg|border|ring|shadow|outline)-/,/^rounded(-|$)/,/^(font|leading|tracking|whitespace|break|truncate)-/,/^(uppercase|lowercase|capitalize|normal-case)$/,/^(transform|transition|duration|delay|ease|animate)-/,/^(scale|rotate|translate|skew)-/,/^transform$/,/^backdrop-blur-/,/^motion-/,/^(fade|slide|zoom|bounce|pulse|spin|ping)-/,/^(overflow|overscroll|scroll)-/,/^(cursor|pointer-events|select|resize)-/,/^(opacity|z)-/,/^(visible|invisible|collapse)$/,/^d-(none|inline|inline-block|block|grid|table|flex)$/,/^(float|clearfix|text)-(left|right|center|justify|start|end)$/,/^(m|p)[trblxy]?-[0-5]$/,/^(w|h)-(25|50|75|100|auto)$/,/^btn-(sm|lg|block)$/,/^text-(muted|primary|success|danger|warning|info|light|dark|white)$/,/^bg-(primary|secondary|success|danger|warning|info|light|dark|white|transparent)$/,/^border(-top|-bottom|-left|-right)?(-0)?$/,/^rounded(-top|-bottom|-left|-right|-circle|-pill|-0)?$/,/^shadow(-sm|-lg|-none)?$/,/^(align|justify|order|flex)-(start|end|center|between|around|fill|grow|shrink)$/,/^col(-sm|-md|-lg|-xl)?(-\d+|-auto)?$/,/^row(-cols)?(-\d+)?$/,/^g[xy]?-[0-5]$/,/^(show|hide|invisible|visible)$/,/^(position|top|bottom|start|end)-(static|relative|absolute|fixed|sticky|-\d+)$/,/^(row|col)$/,/^clearfix$/,/^pull-(left|right)$/,/^float-(left|right|none)$/],It=[/^(nav|menu|header|footer|sidebar|topbar|navbar|breadcrumb)/,/(navigation|dropdown|megamenu)$/,/^(btn|button|link|card|modal|dialog|popup|tooltip|alert|badge|chip)/,/^(form|input|select|checkbox|radio|textarea|label|fieldset)/,/^(table|list|item|row|cell|column)/,/^(accordion|tab|carousel|slider|gallery)/,/^(content|main|article|post|comment|title|subtitle|description|caption)/,/^(hero|banner|jumbotron|section|wrapper|box)/,/^(user|profile|avatar|account|auth)/,/^(product|item|price|cart|checkout|order)/,/^(page|layout|panel|widget|block)/,/-(primary|secondary|tertiary|success|error|warning|info|danger)$/,/-(active|inactive|disabled|enabled|selected|highlighted|focused)$/,/-(open|closed|expanded|collapsed|visible|hidden)$/,/-(large|medium|small|tiny|xs|sm|md|lg|xl)$/,/^(submit|cancel|close|delete|edit|save|back|next|prev|search)/,/^(loading|pending|complete|failed|draft|published)/];function L(n){return $t.some(t=>t.test(n))}function _(n){return n.length<=2||/^\d/.test(n)?!0:Mt.some(t=>t.test(n))}function Nt(n){return L(n)||_(n)?!1:It.some(t=>t.test(n))}function Dt(n){return!L(n)&&!_(n)}function N(n){return n.filter(t=>Dt(t))}function Rt(n){if(L(n)||_(n))return 0;let t=.5;return Nt(n)&&(t=.8),n.length<3?t*=.3:n.length<5&&(t*=.6),/\d/.test(n)&&(t*=.7),Math.min(t,1)}function it(n){const t=[],e=[];for(const s of n)_(s)||L(s)?e.push(s):t.push(s);return{semantic:t,utility:e}}function V(n){return _(n)||L(n)}function Ht(n){return Rt(n)}const at=n=>n.replace(/([#:.[\]@])/g,"\\$1");class ot{constructor(t,e){this.maxDepth=t.maxPathDepth??10,this.cache=e}buildPath(t,e,s){const r=[];let i=e.parentElement;for(;i&&i!==t&&r.length<this.maxDepth;)r.unshift(i),i=i.parentElement;const a=r.length>=this.maxDepth&&i!==t;let o=this.filterNoise(r);return o=this.ensureUniqueness(r,o,t,e,s),{path:o.map(h=>{const c=h.parentElement;let u;if(c){const g=Array.from(c.children).indexOf(h);g!==-1&&(u=g+1)}return{tag:h.tagName.toLowerCase(),semantics:s.extract(h),score:s.scoreElement(h),nthChild:u}}),degraded:a,degradationReason:a?"path-depth-overflow":void 0}}buildPathNodes(t,e,s){return this.buildPath(t,e,s).path}ensureUniqueness(t,e,s,r,i){const a=this.buildTestSelector(s,e,r);try{const o=r.ownerDocument;if(!o)return e;let l;if(this.cache){const c=this.cache.getSelectorResults(a);c!==void 0?l=c:(l=Array.from(o.querySelectorAll(a)),this.cache.setSelectorResults(a,l))}else l=o.querySelectorAll(a);if(l.length<=1)return e;const h=t.filter(c=>!e.includes(c));for(const c of h){if(i.scoreElement(c)<Tt.MIN_CONFIDENCE_FOR_SKIP)continue;const f=this.insertNodeInOrder(e,c,t),g=this.buildTestSelector(s,f,r);try{let d;if(this.cache){const p=this.cache.getSelectorResults(g);p!==void 0?d=p:(d=Array.from(o.querySelectorAll(g)),this.cache.setSelectorResults(g,d))}else d=o.querySelectorAll(g);if(d.length===1)return f;d.length<l.length&&(e=f)}catch{}}return e}catch{return e}}insertNodeInOrder(t,e,s){const r=s.indexOf(e),i=[...t];let a=0;for(let o=0;o<i.length&&!(s.indexOf(i[o])>r);o++)a=o+1;return i.splice(a,0,e),i}buildTestSelector(t,e,s){const r=[];r.push(this.elementToSelector(t));for(const i of e)r.push(this.elementToSelector(i));return r.push(this.elementToSelector(s)),r.join(" ")}elementToSelector(t){let e=t.tagName.toLowerCase();t.id&&!O(t.id)&&(e+=`#${at(t.id)}`);for(const s of Array.from(t.classList))V(s)||(e+=`.${at(s)}`);return e}filterNoise(t){return t.filter(e=>this.shouldInclude(e))}shouldInclude(t){const e=t.tagName.toLowerCase();return tt.includes(e)?!0:e==="div"||e==="span"?this.hasSemanticFeatures(t):!1}hasSemanticFeatures(t){if(t.hasAttribute("role"))return!0;for(const s of Array.from(t.attributes))if(s.name.startsWith("aria-"))return!0;if(t.classList.length>0){for(const s of Array.from(t.classList))if(!V(s))return!0}if(t.hasAttribute("data-testid")||t.hasAttribute("data-qa")||t.hasAttribute("data-test"))return!0;const e=t.id;return!!(e&&!O(e))}}function z(n){return n?n.trim().replace(/[\n\t\r]/g," ").replace(/\s+/g," "):""}const Pt={preserveQueryForAbsolute:!0,removeDynamicHashes:!0};function Ot(n){return n?[/\d{5,}/,/[a-f0-9]{8,}/i,/(session|token|temp|random|timestamp|nonce|cache)/i,/^\d+$/,/^[a-f0-9-]{32,}$/i].some(e=>e.test(n)):!1}function Lt(n,t){if(!n)return n;const e=n.startsWith("http://")||n.startsWith("https://");let[s,r]=n.split("#");const[i,a]=s.split("?");let o=i;return e&&t.preserveQueryForAbsolute&&a&&(o+=`?${a}`),r&&(t.removeDynamicHashes&&Ot(r)||(o+=`#${r}`)),o}function H(n,t,e={}){if(!t)return t;const s={...Pt,...e};return n==="href"||n==="src"?Lt(t,s):t}class ct{constructor(t,e){this.includeUtilityClasses=t.includeUtilityClasses??!1,this.cache=e}extract(t){if(this.cache){const a=this.cache.getSemantics(t);if(a!==void 0)return a}const e={},s=t.id;if(s&&!O(s)&&(e.id=s),t.classList.length>0){const a=Array.from(t.classList);if(this.includeUtilityClasses)e.classes=a;else{const{semantic:o}=it(a);o.length>0&&(e.classes=o)}}const r=this.extractAttributes(t);Object.keys(r).length>0&&(e.attributes=r);const i=t.getAttribute("role");if(i&&(e.role=i),this.shouldExtractText(t)){const a=this.extractText(t);a&&(e.text=a)}return this.cache&&this.cache.setSemantics(t,e),e}scoreElement(t){let e=.5;const s=this.extract(t);return s.id&&(e+=.15),s.classes&&s.classes.length>0&&(e+=.1),s.attributes&&Object.keys(s.attributes).length>0&&(e+=.1),s.role&&(e+=.1),s.text&&(e+=.05),Math.min(e,1)}shouldIgnoreAttribute(t){return!!(et.has(t)||t.startsWith("on")||t.startsWith("ng-")||t.startsWith("_ng")||t.startsWith("data-reactid")||t.startsWith("data-react")||t.startsWith("data-v-"))}getAttributePriority(t){return T[t]!==void 0?T[t]:t.startsWith("data-")?T["data-*"]:t.startsWith("aria-")?T["aria-*"]:0}isDynamicValue(t){return[/^[a-f0-9]{32,}$/i,/^\d{10,}$/,/^(undefined|null|\[object)/,/^{{.*}}$/].some(s=>s.test(t))}extractAttributes(t){const e={};for(const s of Array.from(t.attributes)){const r=s.name;if(this.shouldIgnoreAttribute(r)||this.getAttributePriority(r)===0)continue;const a=r==="href"||r==="src"?H(r,s.value):s.value;!a||a.trim()===""||this.isDynamicValue(a)||(e[r]=a)}return e}extractText(t){const e=this.getDirectTextContent(t);if(!e)return null;const s=z(e);if(!s)return null;const r=100,i=e.length>r?e.slice(0,r)+"...":e,a=s.length>r?s.slice(0,r)+"...":s;return{raw:i,normalized:a}}getDirectTextContent(t){const e=[];for(const s of Array.from(t.childNodes))if(s.nodeType===Node.TEXT_NODE&&s.textContent){const r=s.textContent.trim();r&&e.push(r)}return e.length>0?e.join(" "):t.textContent??null}shouldExtractText(t){const e=t.tagName.toLowerCase();return["button","a","label","h1","h2","h3","h4","h5","h6","p","span","li","th","td","dt","dd","legend","figcaption","summary"].includes(e)}}class lt{fingerprint(t){const e=t.tagName.toLowerCase(),s=this.getShape(e),r={shape:s,hasAnimation:this.hasAnimation(t)};if(s==="path"){const o=t.getAttribute("d");o&&(r.dHash=this.computePathHash(o))}else["circle","rect","ellipse","line"].includes(s)&&(r.geomHash=this.computeGeomHash(t,s));const i=t.getAttribute("role");i&&(r.role=i);const a=t.querySelector("title");return a?.textContent&&(r.titleText=a.textContent.trim()),r}computePathHash(t){const e=this.normalizePathData(t);return this.simpleHash(e)}getShape(t){return["path","circle","rect","line","polyline","polygon","ellipse","g","text","use","svg"].find(s=>s===t)??"path"}normalizePathData(t){return(t.match(/[MLHVCSQTAZ][^MLHVCSQTAZ]*/gi)??[]).slice(0,5).map(r=>r.trim().replace(/(-?\d+\.?\d*)/g,i=>parseFloat(i).toFixed(1))).join(" ")}computeGeomHash(t,e){const s=[];switch(e){case"circle":s.push(`r=${t.getAttribute("r")??"0"}`);break;case"rect":{const r=parseFloat(t.getAttribute("width")??"0"),i=parseFloat(t.getAttribute("height")??"0");r>0&&i>0&&s.push(`ratio=${(r/i).toFixed(2)}`)}break;case"ellipse":{const r=parseFloat(t.getAttribute("rx")??"0"),i=parseFloat(t.getAttribute("ry")??"0");r>0&&i>0&&s.push(`ratio=${(r/i).toFixed(2)}`)}break;case"line":{const r=parseFloat(t.getAttribute("x1")??"0"),i=parseFloat(t.getAttribute("y1")??"0"),a=parseFloat(t.getAttribute("x2")??"0"),o=parseFloat(t.getAttribute("y2")??"0"),l=Math.atan2(o-i,a-r);s.push(`angle=${l.toFixed(2)}`)}break}return this.simpleHash(s.join(";"))}hasAnimation(t){if(t.querySelector("animate, animateTransform, animateMotion"))return!0;const e=t.ownerDocument;if(e?.defaultView)try{const s=e.defaultView.getComputedStyle(t);if(s.animationName!=="none"||s.transitionProperty!=="all"&&s.transitionProperty!=="none")return!0}catch{}return!1}simpleHash(t){let e=0;for(let s=0;s<t.length;s++){const r=t.charCodeAt(s);e=(e<<5)-e+r,e=e&e}return Math.abs(e).toString(16).padStart(8,"0")}}function ht(n,t=0){const e=n.anchor.score,s=n.path.length>0?n.path.reduce((o,l)=>o+l.score,0)/n.path.length:.5,r=n.target.score,i=e*F.ANCHOR+s*F.PATH+r*F.TARGET+t*F.UNIQUENESS,a=n.anchor.degraded?.2:0;return Math.max(0,Math.min(1,i-a))}function _t(n,t,e){let s=.5;return t&&(s+=.2),e&&(s+=.15),s+=Math.min(n*.05,.15),Math.min(s,1)}class kt{constructor(t){this.cache=new Map,this.maxSize=t}get(t){if(!this.cache.has(t))return;const e=this.cache.get(t);return this.cache.delete(t),this.cache.set(t,e),e}set(t,e){if(this.cache.has(t))this.cache.delete(t);else if(this.cache.size>=this.maxSize){const s=this.cache.keys().next().value;s!==void 0&&this.cache.delete(s)}this.cache.set(t,e)}has(t){return this.cache.has(t)}delete(t){this.cache.delete(t)}clear(){this.cache.clear()}get size(){return this.cache.size}}class ut{constructor(t={}){this.eidCache=new WeakMap,this.selectorResultCache=new kt(t.maxSelectorCacheSize??1e3),this.anchorCache=new WeakMap,this.semanticsCache=new WeakMap,this.stats={eidHits:0,eidMisses:0,selectorHits:0,selectorMisses:0,anchorHits:0,anchorMisses:0,semanticsHits:0,semanticsMisses:0,selectorCacheSize:0,maxSelectorCacheSize:t.maxSelectorCacheSize??1e3}}getEID(t){const e=this.eidCache.get(t);if(e!==void 0)return this.stats.eidHits++,e;this.stats.eidMisses++}setEID(t,e){this.eidCache.set(t,e)}getSelectorResults(t){const e=this.selectorResultCache.get(t);if(e!==void 0)return this.stats.selectorHits++,this.stats.selectorCacheSize=this.selectorResultCache.size,e;this.stats.selectorMisses++,this.stats.selectorCacheSize=this.selectorResultCache.size}setSelectorResults(t,e){this.selectorResultCache.set(t,e),this.stats.selectorCacheSize=this.selectorResultCache.size}getAnchor(t){if(this.anchorCache.has(t))return this.stats.anchorHits++,this.anchorCache.get(t);this.stats.anchorMisses++}setAnchor(t,e){this.anchorCache.set(t,e)}getSemantics(t){const e=this.semanticsCache.get(t);if(e!==void 0)return this.stats.semanticsHits++,e;this.stats.semanticsMisses++}setSemantics(t,e){this.semanticsCache.set(t,e)}clear(){this.selectorResultCache.clear(),this.stats.selectorCacheSize=0,this.stats={eidHits:0,eidMisses:0,selectorHits:0,selectorMisses:0,anchorHits:0,anchorMisses:0,semanticsHits:0,semanticsMisses:0,selectorCacheSize:0,maxSelectorCacheSize:this.stats.maxSelectorCacheSize}}invalidateElement(t){}invalidateSelector(t){this.selectorResultCache.delete(t),this.stats.selectorCacheSize=this.selectorResultCache.size}getStats(){return{...this.stats,selectorCacheSize:this.selectorResultCache.size}}getEIDHitRate(){const t=this.stats.eidHits+this.stats.eidMisses;return t>0?this.stats.eidHits/t:0}getSelectorHitRate(){const t=this.stats.selectorHits+this.stats.selectorMisses;return t>0?this.stats.selectorHits/t:0}getAnchorHitRate(){const t=this.stats.anchorHits+this.stats.anchorMisses;return t>0?this.stats.anchorHits/t:0}getSemanticsHitRate(){const t=this.stats.semanticsHits+this.stats.semanticsMisses;return t>0?this.stats.semanticsHits/t:0}getOverallHitRate(){const t=this.stats.eidHits+this.stats.selectorHits+this.stats.anchorHits+this.stats.semanticsHits,e=this.stats.eidMisses+this.stats.selectorMisses+this.stats.anchorMisses+this.stats.semanticsMisses,s=t+e;return s>0?t/s:0}}function ft(n){return new ut(n)}let U=null;function j(){return U||(U=ft()),U}function qt(){U=null}function W(n,t={}){if(!n||!n.ownerDocument||!n.isConnected)return null;const e={...st,...t},s=e.cache??j(),r=s.getEID(n);if(r!==void 0)return r;const i=new nt(e,s),a=new ot(e,s),o=new ct(e,s),l=new lt,h=i.findAnchor(n);if(!h&&!e.fallbackToBody)return null;const c=h?.element??n.ownerDocument?.body??null;if(!c)return null;const u=!h||h.tier==="C",f=o.extract(c),g={tag:c.tagName.toLowerCase(),semantics:f,score:h?.score??v.DEGRADED_SCORE,degraded:u},d=a.buildPath(c,n,o),p=o.extract(n);e.enableSvgFingerprint&&Ft(n)&&(p.svg=l.fingerprint(n));const b=n.parentElement;let y;if(b){const x=Array.from(b.children).indexOf(n);x!==-1&&(y=x+1)}const A={tag:n.tagName.toLowerCase(),semantics:p,score:o.scoreElement(n),nthChild:y},$=[],C={onMultiple:"best-score",onMissing:"anchor-only",maxDepth:3},S=g.degraded||d.degraded,M=zt(g.degraded,d),E={version:"1.0",anchor:g,path:d.path,target:A,constraints:$,fallback:C,meta:{confidence:0,generatedAt:new Date().toISOString(),generator:"dom-eid@1.0",source:e.source,degraded:S,degradationReason:M}};return E.meta.confidence=ht(E),E.meta.confidence<e.confidenceThreshold?null:(s.setEID(n,E),E)}function Ft(n){return n.namespaceURI==="http://www.w3.org/2000/svg"||n.tagName.toLowerCase()==="svg"||n instanceof SVGElement}function zt(n,t){if(n&&t.degraded)return"anchor-and-path-degraded";if(n)return"no-semantic-anchor";if(t.degraded)return t.degradationReason}class Q{buildSelector(t,e){if(t.path.length===0&&t.anchor.tag===t.target.tag&&JSON.stringify(t.anchor.semantics)===JSON.stringify(t.target.semantics)){const u=this.buildNodeSelector(t.target.tag,t.target.semantics,{excludeClasses:!1});return e?.ensureUnique?this.ensureUniqueSelector(u,t,e):u}const r=[],i=e?.ensureUnique?this.ensureUniqueAnchor(t,e.root??document):this.buildNodeSelector(t.anchor.tag,t.anchor.semantics);r.push(i);for(const u of t.path){let f=this.buildNodeSelector(u.tag,u.semantics);u.nthChild!==void 0&&(["tr","td","th","thead","tbody","tfoot"].includes(u.tag)?f+=`:nth-child(${u.nthChild})`:f+=`:nth-child(${u.nthChild})`),r.push(f)}let a=this.buildNodeSelector(t.target.tag,t.target.semantics,{excludeClasses:e?.ensureUnique});t.target.nthChild!==void 0&&(["tr","td","th","thead","tbody","tfoot"].includes(t.target.tag)?a+=`:nth-child(${t.target.nthChild})`:a+=`:nth-child(${t.target.nthChild})`),r.push(a);const o=this.isSvgChildElement(t.target.tag),l=t.path.some(u=>u.tag==="svg");let h;if(o&&l){const u=t.path.findIndex(f=>f.tag==="svg");if(u!==-1){const f=u+1,g=r.slice(0,f+1),d=r.slice(f+1,-1),p=r[r.length-1];d.length>0?h=g.join(" ")+" > "+d.join(" > ")+" > "+p:h=g.join(" ")+" > "+p}else h=r.join(" ")}else h=r.join(" ");if(!e?.ensureUnique)return h;const c=this.querySelectorSafe(h,e.root??document);if(c.length===1)return{selector:h,isUnique:!0,usedNthOfType:h.includes(":nth-"),extraClassesAdded:0};if(c.length===0||c.length>1){const u=this.buildFullDomPathSelector(t,t.target.semantics,e.root??document);if(u&&this.isUnique(u,e.root??document))return{selector:u,isUnique:!0,usedNthOfType:u.includes(":nth-"),extraClassesAdded:0}}return this.ensureUniqueSelector(h,t,e)}buildAnchorSelector(t){return this.buildNodeSelector(t.anchor.tag,t.anchor.semantics)}ensureUniqueSelector(t,e,s){const r=s.root??document,i=s.maxClasses??4,a=e.target.tag,o=e.target.semantics;let l=t,h=0,c=!1;if(this.querySelectorSafe(l,r).length===0){const d=this.buildFullDomPathSelector(e,o,r);if(d&&(l=d,this.isUnique(l,r)))return{selector:l,isUnique:!0,usedNthOfType:!1,extraClassesAdded:0}}if(this.isUnique(l,r))return{selector:l,isUnique:!0,usedNthOfType:!1,extraClassesAdded:0};const f=N(o.classes??[]);for(let d=0;d<Math.min(f.length,i);d++){const p=f[d];if(l+=`.${this.escapeCSS(p)}`,h++,this.isUnique(l,r))return{selector:l,isUnique:!0,usedNthOfType:!1,extraClassesAdded:h}}if(!this.isUnique(l,r)){const d=this.buildFullDomPathSelector(e,o,r);if(d&&this.isUnique(d,r))return{selector:d,isUnique:!0,usedNthOfType:d.includes(":nth-of-type("),extraClassesAdded:h}}const g=this.findNthElementByText(l,o,r);return g&&(l+=this.getNthSelector(g,a),c=!0),{selector:l,isUnique:this.isUnique(l,r),usedNthOfType:c,extraClassesAdded:h}}buildFullDomPathSelector(t,e,s){const r=this.buildNodeSelector(t.anchor.tag,t.anchor.semantics),i=this.querySelectorSafe(r,s);if(i.length===0)return null;for(const a of i){const o=this.findTargetWithinAnchor(a,t.target.tag,e);if(o.length===0)continue;const l=o.map(h=>{const c=this.scorePathMatch(h,a,t.path);return{element:h,score:c}});l.sort((h,c)=>c.score-h.score);for(const{element:h}of l){const c=this.buildPathFromAnchorToTarget(a,h,t,s);if(c&&this.isUnique(c,s))return c}}return null}scorePathMatch(t,e,s){const r=[];let i=t.parentElement;for(;i&&i!==e;)r.unshift(i),i=i.parentElement;let a=0;const o=Math.min(r.length,s.length);for(let h=0;h<o;h++){const c=r[h],u=s[h];if(c.tagName.toLowerCase()===u.tag){if(a+=10,u.nthChild!==void 0){const f=c.parentElement;f&&(Array.from(f.children).indexOf(c)+1===u.nthChild?a+=20:a-=10)}}else a-=5;if(u.semantics.classes&&u.semantics.classes.length>0){const f=u.semantics.classes.filter(g=>c.classList.contains(g));a+=f.length*2}if(u.semantics.attributes){const f=Object.entries(u.semantics.attributes).filter(([g,d])=>c.getAttribute(g)===d);a+=f.length*3}}const l=Math.abs(r.length-s.length);return a-=l*2,a}findTargetWithinAnchor(t,e,s){return Array.from(t.querySelectorAll(e)).filter(i=>{if(s.text){const a=i.textContent?.trim()||"",o=s.text.normalized;if(!a.includes(o)&&!o.includes(a))return!1}return!!(s.classes&&s.classes.length>0&&s.classes.every(o=>i.classList.contains(o))||s.attributes&&Object.entries(s.attributes).every(([o,l])=>{const h=i.getAttribute(o);return o==="href"||o==="src"?H(o,h||"")===H(o,l):h===l})||s.text)})}disambiguateParent(t,e,s,r,i){if(s?.semantics?.attributes){const o=this.buildNodeSelector(e,s.semantics,{excludeClasses:!0}),l=[...r,e].join(" > "),h=this.querySelectorSafe(l,i),c=[...r,o].join(" > "),u=this.querySelectorSafe(c,i);if(u.length>0&&u.length<h.length)return o}if(s?.semantics?.classes){const o=N(s.semantics.classes);if(o.length>0){const l=`${e}.${this.escapeCSS(o[0])}`,h=[...r,e].join(" > "),c=this.querySelectorSafe(h,i),u=[...r,l].join(" > "),f=this.querySelectorSafe(u,i);if(f.length>0&&f.length<c.length)return l}}const a=t.parentElement;return a&&Array.from(a.children).filter(l=>l.tagName.toLowerCase()===e).length>1?`${e}${this.getNthSelector(t,e)}`:e}buildPathFromAnchorToTarget(t,e,s,r){const i=[];let a=e;for(;a&&a!==t;)i.unshift(a),a=a.parentElement;if(a!==t)return null;const o=[()=>{const l=this.buildNodeSelector(s.anchor.tag,s.anchor.semantics),h=s.target.tag,c=s.target.semantics,u=[];for(const b of s.path)u.push(b.tag);const g=[l,...u,h].filter(Boolean).join(" ");if(this.isUnique(g,r))return g;const d=this.buildNodeSelector(h,c,{excludeClasses:!0}),p=[l,...u.slice(0,-1),d].join(" ");return this.isUnique(p,r)?p:null},()=>{const l=[this.buildNodeSelector(s.anchor.tag,s.anchor.semantics)],h=new Map;let c=0;for(let f=0;f<i.length-1;f++){const g=i[f],d=g.tagName.toLowerCase();c<s.path.length&&s.path[c].tag===d?(h.set(g,s.path[c]),c++):h.set(g,null)}for(let f=0;f<i.length;f++){const g=i[f],d=g.tagName.toLowerCase();if(f<i.length-1){const y=h.get(g)||null,A=this.disambiguateParent(g,d,y,l,r);l.push(A);continue}const p=this.buildNodeSelector(s.target.tag,s.target.semantics,{excludeClasses:!0}),b=g.parentElement;b&&["td","th","tr","thead","tbody","tfoot"].includes(d)&&Array.from(b.children).filter(A=>A.tagName.toLowerCase()===d).length>1?l.push(`${p}${this.getNthSelector(g,d)}`):l.push(p)}const u=l.join(" > ");return this.isUnique(u,r)?u:null},()=>{const h=[this.buildNodeSelector(s.anchor.tag,s.anchor.semantics)];for(let f=0;f<i.length-1;f++){const d=i[f].tagName.toLowerCase(),p=s.path[f]||null,b=h.join(" ")+" "+d;if(this.querySelectorSafe(b,r).length>1){if(p?.semantics?.attributes){const C=this.buildNodeSelector(d,p.semantics,{excludeClasses:!0}),S=h.join(" ")+" "+C;if(this.querySelectorSafe(S,r).length===1||this.querySelectorSafe(S+" "+s.target.tag,r).length===1){h.push(C);continue}}if(p?.semantics?.classes){const C=N(p.semantics.classes);if(C.length>0){const S=`${d}.${this.escapeCSS(C[0])}`,M=h.join(" ")+" "+S;if(this.querySelectorSafe(M,r).length===1||this.querySelectorSafe(M+" "+s.target.tag,r).length===1){h.push(S);continue}}}const A=i[f],$=A.parentElement;if($&&Array.from($.children).filter(S=>S.tagName.toLowerCase()===d).length>1){h.push(`${d}${this.getNthSelector(A,d)}`);continue}}h.push(d)}const c=this.buildNodeSelector(s.target.tag,s.target.semantics,{excludeClasses:!0});h.push(c);const u=h.join(" ");return this.isUnique(u,r)?u:null},()=>{const l=this.buildNodeSelector(s.anchor.tag,s.anchor.semantics),h=[];for(const g of s.path)h.push(g.tag);if(N(s.target.semantics.classes??[]).length===0)return null;const u=this.buildNodeSelector(s.target.tag,s.target.semantics,{maxClasses:1}),f=[l,...h.slice(0,-1),u].join(" ");return this.isUnique(f,r)?f:null},()=>{const l=this.buildNodeSelector(s.anchor.tag,s.anchor.semantics),h=[];for(const p of s.path)h.push(p.tag);const c=i[i.length-1],u=c.parentElement;if(!u||Array.from(u.children).filter(p=>p.tagName.toLowerCase()===s.target.tag).length<=1)return null;const g=this.buildNodeSelector(s.target.tag,s.target.semantics,{excludeClasses:!0})+this.getNthSelector(c,s.target.tag),d=[l,...h.slice(0,-1),g].join(" ");return this.isUnique(d,r)?d:null}];for(const l of o){const h=l();if(h)return h}return null}buildElementSelector(t){const e=t.tagName.toLowerCase();let s=e;if(t.id&&!this.isDynamicId(t.id))return`${e}#${this.escapeCSS(t.id)}`;const r=Array.from(t.classList),i=N(r);i.length>0&&(s+=i.slice(0,2).map(o=>`.${this.escapeCSS(o)}`).join(""));const a=t.getAttribute("role");return a&&(s+=`[role="${this.escapeAttr(a)}"]`),s}isDynamicId(t){return[/^[a-f0-9]{8,}$/i,/^\d{5,}$/,/^(r|react|ember|vue)[\d_]/i,/:r\d+:$/].some(s=>s.test(t))}querySelectorSafe(t,e){try{return Array.from(e.querySelectorAll(t))}catch{return[]}}findNthElementByText(t,e,s){const r=this.querySelectorSafe(t,s);if(r.length<=1)return null;if(e.text){const i=e.text.normalized;for(const a of r){const o=a.textContent?.trim()||"";if(o===i||o.includes(i)||i.includes(o))return a}}return null}isUnique(t,e){try{return e.querySelectorAll(t).length===1}catch{return!1}}getNthOfTypeIndex(t,e){const s=t.parentElement;if(!s)return null;const i=Array.from(s.children).filter(a=>a.tagName.toLowerCase()===e).indexOf(t);return i!==-1?i+1:null}ensureUniqueAnchor(t,e){const s=t.anchor.tag,r=t.anchor.semantics;if(this.isUnique(s,e))return s;if(r.classes&&r.classes.length>0){const a=N(r.classes);if(a.length>0){const o=`${s}.${this.escapeCSS(a[0])}`;if(this.isUnique(o,e))return o}}if(r.attributes){const a=this.getSortedAttributes(r.attributes);for(const{name:o,value:l}of a){const h=o==="href"||o==="src"?H(o,l):l;if(h){const c=`${s}[${o}="${this.escapeAttr(h)}"]`;if(this.isUnique(c,e))return c}}}const i=Array.from(e.querySelectorAll(s));if(i.length>1){const a=this.findElementBySemantics(i,r);if(a){const o=this.getNthOfTypeIndex(a,s);if(o)return`${s}:nth-of-type(${o})`}}return s}findElementBySemantics(t,e){return e.classes&&e.classes.length>0||e.attributes&&Object.keys(e.attributes).length>0||e.text?t.find(r=>{if(e.classes&&e.classes.length>0&&e.classes.every(a=>r.classList.contains(a))||e.attributes&&Object.entries(e.attributes).every(([a,o])=>r.getAttribute(a)===o))return!0;if(e.text){const i=r.textContent?.trim()||"",a=e.text.normalized;if(i.includes(a)||a.includes(i))return!0}return!1})||null:t.length>0?t[0]:null}getNthSelector(t,e){const s=t.parentElement;if(!s)return"";const r=Array.from(s.children),i=r.indexOf(t)+1;return["tr","td","th","thead","tbody","tfoot"].includes(e)?`:nth-child(${i})`:`:nth-of-type(${r.filter(l=>l.tagName.toLowerCase()===e).indexOf(t)+1})`}getAttributePriority(t){return T[t]!==void 0?T[t]:t.startsWith("data-")?T["data-*"]:t.startsWith("aria-")?T["aria-*"]:0}shouldIgnoreAttribute(t){return!!(et.has(t)||t.startsWith("on")||t.startsWith("ng-")||t.startsWith("_ng")||t.startsWith("data-reactid")||t.startsWith("data-react")||t.startsWith("data-v-"))}getSortedAttributes(t){return Object.entries(t).filter(([e])=>!this.shouldIgnoreAttribute(e)).map(([e,s])=>({name:e,value:s,priority:this.getAttributePriority(e)})).filter(e=>e.priority>0).sort((e,s)=>s.priority-e.priority)}buildNodeSelector(t,e,s){let r=t;if(e.id)return r+=`#${this.escapeCSS(e.id)}`,r;if(e.attributes){const i=this.getSortedAttributes(e.attributes);for(const{name:a,value:o}of i){const l=a==="href"||a==="src"?H(a,o):o;l&&(r+=`[${a}="${this.escapeAttr(l)}"]`)}}if(e.role&&!e.attributes?.role&&(r+=`[role="${this.escapeAttr(e.role)}"]`),!s?.excludeClasses&&e.classes&&e.classes.length>0){const i=N(e.classes),a=s?.maxClasses!==void 0?i.slice(0,s.maxClasses):i;r+=a.map(o=>`.${this.escapeCSS(o)}`).join("")}return r}escapeCSS(t){return t.replace(/([!"#$%&'()*+,./:;<=>?@[\\\]^`{|}~])/g,"\\$1")}escapeAttr(t){return t.replace(/"/g,'\\"').replace(/\\/g,"\\\\")}isSvgChildElement(t){return wt.includes(t)}}class dt{match(t,e){return t.filter(s=>this.matchElement(s,e))}matchElement(t,e){return!(e.text&&!this.matchText(t,e.text)||e.attributes&&!this.matchAttributes(t,e.attributes)||e.svg&&!this.matchSvgFingerprint(t,e.svg))}matchText(t,e){const i=Array.from(t.childNodes).filter(o=>o.nodeType===Node.TEXT_NODE).map(o=>o.textContent?.trim()??"").join(" ")||(t.textContent?.trim()??"");if(!i)return!1;const a=z(i);return e.matchMode==="partial"?a.includes(e.normalized):a===e.normalized}matchAttributes(t,e){for(const[s,r]of Object.entries(e))if(t.getAttribute(s)!==r)return!1;return!0}matchSvgFingerprint(t,e){if(t.tagName.toLowerCase()!==e.shape)return!1;if(e.dHash&&e.shape==="path"){const s=t.getAttribute("d");if(s&&this.computePathHash(s)!==e.dHash)return!1}return!(e.geomHash&&["circle","rect","ellipse","line"].includes(e.shape)&&this.computeGeomHash(t,e.shape)!==e.geomHash||e.titleText&&t.querySelector("title")?.textContent?.trim()!==e.titleText)}computePathHash(t){const r=(t.match(/[MLHVCSQTAZ][^MLHVCSQTAZ]*/gi)??[]).slice(0,5).map(i=>i.trim().replace(/(-?\d+\.?\d*)/g,a=>parseFloat(a).toFixed(1))).join(" ");return this.simpleHash(r)}computeGeomHash(t,e){const s=[];switch(e){case"circle":s.push(`r=${t.getAttribute("r")??"0"}`);break;case"rect":{const r=parseFloat(t.getAttribute("width")??"0"),i=parseFloat(t.getAttribute("height")??"0");r>0&&i>0&&s.push(`ratio=${(r/i).toFixed(2)}`);break}case"ellipse":{const r=parseFloat(t.getAttribute("rx")??"0"),i=parseFloat(t.getAttribute("ry")??"0");r>0&&i>0&&s.push(`ratio=${(r/i).toFixed(2)}`);break}case"line":{const r=parseFloat(t.getAttribute("x1")??"0"),i=parseFloat(t.getAttribute("y1")??"0"),a=parseFloat(t.getAttribute("x2")??"0"),o=parseFloat(t.getAttribute("y2")??"0"),l=Math.atan2(o-i,a-r);s.push(`angle=${l.toFixed(2)}`);break}}return this.simpleHash(s.join(";"))}simpleHash(t){let e=0;for(let s=0;s<t.length;s++){const r=t.charCodeAt(s);e=(e<<5)-e+r,e=e&e}return Math.abs(e).toString(16).padStart(8,"0")}}class gt{applyConstraint(t,e){switch(e.type){case"text-proximity":return this.applyTextProximity(t,e.params);case"position":return this.applyPosition(t,e.params);default:return t}}applyTextProximity(t,e){return t.filter(s=>{const r=s.textContent?.trim()??"";return this.levenshteinDistance(r,e.reference)<=e.maxDistance})}applyPosition(t,e){if(t.length<=1)return t;switch(e.strategy){case"first-in-dom":return[t[0]];case"top-most":return[this.getTopMost(t)];case"left-most":return[this.getLeftMost(t)];default:return[t[0]]}}getTopMost(t){return t.reduce((e,s)=>{try{const r=e.getBoundingClientRect();return s.getBoundingClientRect().top<r.top?s:e}catch{return e}})}getLeftMost(t){return t.reduce((e,s)=>{try{const r=e.getBoundingClientRect();return s.getBoundingClientRect().left<r.left?s:e}catch{return e}})}levenshteinDistance(t,e){if(t===e)return 0;if(t.length===0)return e.length;if(e.length===0)return t.length;const s=Array.from({length:e.length+1},(r,i)=>i);for(let r=1;r<=t.length;r++){let i=r;for(let a=1;a<=e.length;a++){const o=t[r-1]===e[a-1]?s[a-1]:Math.min(s[a-1],i,s[a])+1;s[a-1]=i,i=o}s[e.length]=i}return s[e.length]}}class mt{constructor(){this.cssGenerator=new Q}handleFallback(t,e){const{onMissing:s}=t.fallback;switch(s){case"anchor-only":return this.fallbackToAnchor(t,e);case"strict":return{status:"error",elements:[],warnings:["Element not found (strict mode)"],confidence:0,meta:{degraded:!0,degradationReason:"strict-not-found"}};default:return{status:"error",elements:[],warnings:["Element not found"],confidence:0,meta:{degraded:!0,degradationReason:"not-found"}}}}fallbackToAnchor(t,e){const s=this.cssGenerator.buildAnchorSelector(t),r=e instanceof Document?e:e.ownerDocument??e;try{const i=r.querySelector(s);if(i)return{status:"degraded-fallback",elements:[i],warnings:["Target not found, returning anchor"],confidence:t.meta.confidence*.3,meta:{degraded:!0,degradationReason:"anchor-fallback"}}}catch(i){const a=i instanceof Error?i.message:"Unknown selector error";return{status:"error",elements:[],warnings:[`Invalid anchor selector: ${a}`],confidence:0,meta:{degraded:!0,degradationReason:"invalid-anchor-selector"}}}return{status:"error",elements:[],warnings:["Anchor also not found"],confidence:0,meta:{degraded:!0,degradationReason:"anchor-not-found"}}}handleAmbiguous(t,e){const{onMultiple:s}=e.fallback;switch(s){case"first":return{status:"success",elements:[t[0]],warnings:["Multiple matches, returning first"],confidence:e.meta.confidence*.7,meta:{degraded:!0,degradationReason:"first-of-multiple"}};case"best-score":return this.selectBestScoring(t,e);default:return{status:"ambiguous",elements:t,warnings:[`Multiple matches: ${t.length}`],confidence:e.meta.confidence*.5,meta:{degraded:!0,degradationReason:"multiple-matches"}}}}selectBestScoring(t,e){const s=e.target.semantics;let r=t[0],i=-1;for(const a of t){const o=this.scoreElementMatch(a,s);o>i&&(i=o,r=a)}return{status:"success",elements:[r],warnings:[`Multiple matches (${t.length}), selected best-scoring element`],confidence:e.meta.confidence*(.7+i*.2),meta:{degraded:!0,degradationReason:"best-of-multiple"}}}scoreElementMatch(t,e){let s=0,r=0;if(e.id&&(r+=.3,t.id===e.id&&(s+=.3)),e.classes&&e.classes.length>0){r+=.25;const i=Array.from(t.classList),a=e.classes.filter(o=>i.includes(o)).length;s+=a/e.classes.length*.25}if(e.attributes){const i=Object.entries(e.attributes);if(i.length>0){r+=.2;let a=0;for(const[o,l]of i)t.getAttribute(o)===l&&a++;s+=a/i.length*.2}}if(e.role&&(r+=.15,t.getAttribute("role")===e.role&&(s+=.15)),e.text){r+=.1;const i=z(t.textContent);i===e.text.normalized?s+=.1:i.includes(e.text.normalized)&&(s+=.05)}return r>0?s/r:0}}function pt(n,t,e={}){const s={...rt,...e},r=new Q,i=new dt,a=new gt,o=new mt,l=t instanceof Document?t:t.ownerDocument??t,h=r.buildSelector(n,{ensureUnique:!1,root:l});let c;try{c=Array.from(l.querySelectorAll(h))}catch(d){const p=d instanceof Error?d.message:"Unknown selector error";return{status:"error",elements:[],warnings:[`Invalid CSS selector: ${h}`,`Error: ${p}`],confidence:0,meta:{degraded:!0,degradationReason:"invalid-selector"}}}c.length>s.maxCandidates&&(c=c.slice(0,s.maxCandidates));const u=i.match(c,n.target.semantics);if(u.length===1)return{status:"success",elements:u,warnings:[],confidence:n.meta.confidence,meta:{degraded:!1}};if(u.length===0)return s.enableFallback?o.handleFallback(n,l):{status:"error",elements:[],warnings:["No matching elements found"],confidence:0,meta:{degraded:!0,degradationReason:"not-found"}};let f=u;const g=Ut(n.constraints);for(const d of g){if(f=a.applyConstraint(f,d),f.length===1)return{status:"success",elements:f,warnings:[],confidence:n.meta.confidence*.9,meta:{degraded:!1}};if(f.length===0)return s.enableFallback?o.handleFallback(n,l):{status:"error",elements:[],warnings:["Constraints eliminated all candidates"],confidence:0,meta:{degraded:!0,degradationReason:"over-constrained"}}}return s.strictMode?{status:"ambiguous",elements:f,warnings:[`Non-unique resolution: ${f.length} matches`],confidence:n.meta.confidence*.7,meta:{degraded:!0,degradationReason:"ambiguous"}}:o.handleAmbiguous(f,n)}function Ut(n){return[...n].sort((t,e)=>e.priority-t.priority)}function jt(n){const t=[],e=[];if(n.version?n.version!=="1.0"&&e.push(`Unknown version: ${n.version}`):t.push("Missing version field"),n.anchor?(n.anchor.tag||t.push("Anchor missing tag"),typeof n.anchor.score!="number"&&t.push("Anchor missing score"),n.anchor.semantics||t.push("Anchor missing semantics")):t.push("Missing anchor field"),n.target?(n.target.tag||t.push("Target missing tag"),typeof n.target.score!="number"&&t.push("Target missing score"),n.target.semantics||t.push("Target missing semantics")):t.push("Missing target field"),!Array.isArray(n.path))t.push("Path must be an array");else for(let s=0;s<n.path.length;s++){const r=n.path[s];r.tag||t.push(`Path node ${s} missing tag`),r.semantics||t.push(`Path node ${s} missing semantics`)}return n.meta?(typeof n.meta.confidence!="number"&&e.push("Missing confidence score"),n.meta.generatedAt||e.push("Missing generatedAt timestamp")):t.push("Missing meta field"),Array.isArray(n.constraints)||e.push("Constraints should be an array"),n.fallback||e.push("Missing fallback rules"),{valid:t.length===0,errors:t,warnings:e}}function Wt(n){if(!n||typeof n!="object")return!1;const t=n;return typeof t.version=="string"&&typeof t.anchor=="object"&&Array.isArray(t.path)&&typeof t.target=="object"}const bt={maxClasses:2,maxAttributes:5,includeText:!0,maxTextLength:50,simplifyTarget:!0,includeConstraints:!0};function St(n){return n==="id"?101:T[n]!==void 0?T[n]:n.startsWith("data-")?T["data-*"]:n.startsWith("aria-")?T["aria-*"]:0}function Bt(n){return["id","data-testid","data-qa","data-cy","href","text","role"].includes(n)}function Gt(n){return!!(/@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/.test(n)||/(\+?\d{1,3}[-.\s]?)?\(?\d{3}\)?[-.\s]?\d{3}[-.\s]?\d{4}/.test(n)||/\d{4}[-\s]?\d{4}[-\s]?\d{4}[-\s]?\d{4}/.test(n))}function yt(n,t){const e={...bt,...t},s=`v${n.version}`,r=Z(n.anchor,!1,e),i=n.path.length>0?n.path.map(l=>Z(l,!1,e)).join(" > ")+" > ":"",a=Z(n.target,!0,e),o=e.includeConstraints?Vt(n):"";return`${s}: ${r} :: ${i}${a}${o}`}function At(n){n=n.trim();const t=n.match(/^v(\d+(?:\.\d+)?)\s*:\s*/);if(!t)throw new Error('Invalid SEQL Selector: missing version prefix (expected "v1:")');const e=t[1];if(e!=="1.0"&&e!=="1")throw new Error(`Unsupported SEQL Selector version: v${e} (only v1.0 is supported)`);let s=n.slice(t[0].length);const r=s.match(/^(.+?)\s*::\s*/);if(!r)throw new Error('Invalid SEQL Selector: missing anchor separator "::"');const i=r[1].trim();s=s.slice(r[0].length);const a=s.match(/\s*\{([^}]+)\}\s*$/);let o="";a&&(o=a[1],s=s.slice(0,a.index));const l=s.split(/\s*>\s*/).map(b=>b.trim()).filter(b=>b);if(l.length===0)throw new Error("Invalid SEQL Selector: missing target node");const h=l[l.length-1],c=l.slice(0,-1),u=Y(i,!0),f=c.map(b=>Y(b,!1)),g=Y(h,!1),d=Qt(o);return{version:"1.0",anchor:u,path:f,target:g,constraints:d,fallback:{onMultiple:"best-score",onMissing:"anchor-only",maxDepth:10},meta:{confidence:.7,generatedAt:new Date().toISOString(),generator:"seql-parser@1.0",source:"seql-string",degraded:!1}}}function Z(n,t=!1,e=bt){const{tag:s,semantics:r}=n;let i=s;const a=[],o={...r.attributes};r.id&&(o.id=r.id),r.role&&!o.role&&(o.role=r.role);const l=Object.entries(o).map(([c,u])=>{const f=St(c),g=c==="href"||c==="src"?H(c,u):u;return{name:c,value:g,priority:f}}).filter(c=>["style","xmlns","tabindex","contenteditable"].includes(c.name)?!1:c.priority>0||c.name==="role"||c.name==="id");l.sort((c,u)=>u.priority-c.priority);const h=l.slice(0,e.maxAttributes);h.sort((c,u)=>c.name.localeCompare(u.name));for(const{name:c,value:u}of h)a.push(`${c}="${X(u)}"`);if(e.includeText&&r.text&&!Gt(r.text.normalized)){const c=r.text.normalized;c.length>0&&c.length<=e.maxTextLength&&a.push(`text="${X(c)}"`)}if(a.length>0){let c=a;t&&e.simplifyTarget&&r.id&&(c=a.filter(u=>{const f=u.split("=")[0];return St(f)>=60||f==="text"||f==="id"||f==="role"})),c.length>0&&(c.sort((u,f)=>u.localeCompare(f)),i+=`[${c.join(",")}]`)}if(r.classes&&r.classes.length>0){const c=N(r.classes),u=!!r.id||a.some(g=>g.startsWith("href=")||g.startsWith("data-testid=")||g.startsWith("text=")||g.startsWith("role="));if(!(t&&e.simplifyTarget&&u)&&c.length>0){const g=c.sort().slice(0,e.maxClasses);i+=g.map(d=>`.${d}`).join("")}}if("nthChild"in n&&n.nthChild){const c=!!r.id||r.attributes&&Object.keys(r.attributes).some(Bt);t&&e.simplifyTarget&&c||(i+=`#${n.nthChild}`)}return i}function Vt(n){if(!n.constraints||n.constraints.length===0)return"";const t=[];for(const e of n.constraints)switch(e.type){case"uniqueness":t.push("unique=true");break;case"position":e.params&&e.params.strategy&&t.push(`pos=${e.params.strategy}`);break;case"text-proximity":if(e.params&&e.params.reference){const s=X(String(e.params.reference));t.push(`text="${s}"`)}break}return t.length===0?"":` {${t.join(",")}}`}function Y(n,t){let e=n;const s={},r=e.match(/^([a-z][a-z0-9-]*)/);if(!r)throw new Error(`Invalid node: missing tag name in "${n}"`);const i=r[1];e=e.slice(i.length);const a=[];let o;for(;o=e.match(/^\.([a-zA-Z][a-zA-Z0-9-_]*)/);)a.push(o[1]),e=e.slice(o[0].length);a.length>0&&(s.classes=a);const l=e.match(/^\[([^\]]+)\]/);if(l){const u=l[1],f={},g=Zt(u);for(const d of g){const p=d.match(/^([a-z][a-z0-9-]*)(?:=|~=)"((?:[^"\\]|\\.)*)"/);if(p){const[,b,y]=p;f[b]=Ct(y)}}Object.keys(f).length>0&&(f.text&&(s.text={raw:f.text,normalized:f.text},delete f.text),f.id&&(s.id=f.id,delete f.id),f.role&&(s.role=f.role,delete f.role),Object.keys(f).length>0&&(s.attributes=f)),e=e.slice(l[0].length)}let h;const c=e.match(/^#(\d+)/);if(c&&(h=parseInt(c[1],10),e=e.slice(c[0].length)),e.trim())throw new Error(`Invalid node: unexpected content "${e}" in "${n}"`);return t?{tag:i,semantics:s,score:.7,degraded:!1}:{tag:i,semantics:s,score:.7,nthChild:h}}function Qt(n){if(!n.trim())return[];const t=[],e=n.split(",").map(s=>s.trim());for(const s of e){const[r,i]=s.split("=").map(a=>a.trim());switch(r){case"unique":i==="true"&&t.push({type:"uniqueness",params:{mode:"strict"},priority:90});break;case"pos":t.push({type:"position",params:{strategy:i},priority:70});break;case"text":const a=i.replace(/^"(.*)"$/,"$1");t.push({type:"text-proximity",params:{reference:Ct(a),maxDistance:5},priority:60});break}}return t}function Zt(n){const t=[];let e="",s=!1;for(let r=0;r<n.length;r++){const i=n[r];i==='"'&&(r===0||n[r-1]!=="\\")?(s=!s,e+=i):i===","&&!s?(e.trim()&&t.push(e.trim()),e=""):e+=i}return e.trim()&&t.push(e.trim()),t}function X(n){return n.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/>/g,"\\>").replace(/:/g,"\\:")}function Ct(n){return n.replace(/\\\\/g,"\0").replace(/\\"/g,'"').replace(/\\>/g,">").replace(/\\:/g,":").replace(/\x00/g,"\\")}function Yt(n,t,e){const s=W(n,t);return s?yt(s,e):null}function Xt(n,t,e){try{const s=At(n);return pt(s,t,e).elements||[]}catch(s){return console.error("Failed to resolve SEQL Selector:",s),[]}}const Kt=new Set(["script","style","noscript","meta","link","head","title"]);function K(n){return n.id&&!O(n.id)?3:n.hasAttribute("role")||n.hasAttribute("aria-label")||n.hasAttribute("aria-labelledby")||n.hasAttribute("data-testid")||n.hasAttribute("data-qa")||n.hasAttribute("data-test")?2:1}function Et(n,t){const e=n.tagName.toLowerCase();return!!(Kt.has(e)||t&&K(n)===1&&!["form","main","nav","section","article","footer","header","button","a","input","label","select","textarea"].includes(e))}function xt(n){return[...n].sort((t,e)=>{const s=K(t);return K(e)-s})}function Jt(n={}){const t=performance.now(),{root:e=typeof document<"u"?document.body:void 0,filter:s="*",limit:r=1/0,onProgress:i,progressInterval:a=100,skipNonSemantic:o=!0,generatorOptions:l={},cache:h,signal:c}=n;if(!e)throw new Error("Root element or document is required");const u=h??j(),f={...l,cache:u};let g;try{e instanceof Document,g=Array.from(e.querySelectorAll(s))}catch{return{results:[],failed:[],stats:{totalElements:0,successful:0,failed:0,skipped:0,totalTimeMs:0,avgTimePerElementMs:0,cacheHitRate:0}}}const d=g.filter(w=>!Et(w,o)),b=xt(d).slice(0,r),y=[],A=[];let $=0;const C=b.length;let S=0;for(let w=0;w<b.length&&!c?.aborted;w++){const R=b[w],I=u.getEID(R);if(I)y.push({element:R,eid:I,generationTimeMs:0});else{const J=performance.now();try{const P=W(R,f),ee=performance.now()-J;P?y.push({element:R,eid:P,generationTimeMs:ee}):$++}catch(P){A.push({element:R,error:P instanceof Error?P.message:String(P)})}}i&&w-S>=a&&(i(w+1,C),S=w)}i&&i(C,C);const M=performance.now()-t,E=u.getStats(),k=E.eidHits+E.eidMisses+E.selectorHits+E.selectorMisses,x=E.eidHits+E.selectorHits,D=k>0?x/k:0;return{results:y,failed:A,stats:{totalElements:C,successful:y.length,failed:A.length,skipped:$,totalTimeMs:M,avgTimePerElementMs:y.length>0?M/y.length:0,cacheHitRate:D}}}function te(n,t={}){const e=performance.now(),{limit:s=1/0,onProgress:r,progressInterval:i=100,skipNonSemantic:a=!0,generatorOptions:o={},cache:l,signal:h}=t,c=l??j(),u={...o,cache:c},f=n.filter(x=>!Et(x,a)),d=xt(f).slice(0,s),p=[],b=[];let y=0;const A=d.length;let $=0;for(let x=0;x<d.length&&!h?.aborted;x++){const D=d[x],w=c.getEID(D);if(w)p.push({element:D,eid:w,generationTimeMs:0});else{const R=performance.now();try{const I=W(D,u),J=performance.now()-R;I?p.push({element:D,eid:I,generationTimeMs:J}):y++}catch(I){b.push({element:D,error:I instanceof Error?I.message:String(I)})}}r&&x-$>=i&&(r(x+1,A),$=x)}r&&r(A,A);const C=performance.now()-e,S=c.getStats(),M=S.eidHits+S.eidMisses+S.selectorHits+S.selectorMisses,E=S.eidHits+S.selectorHits,k=M>0?E/M:0;return{results:p,failed:b,stats:{totalElements:A,successful:p.length,failed:b.length,skipped:y,totalTimeMs:C,avgTimePerElementMs:p.length>0?C/p.length:0,cacheHitRate:k}}}m.AnchorFinder=nt,m.ConstraintsEvaluator=gt,m.CssGenerator=Q,m.DEFAULT_GENERATOR_OPTIONS=st,m.DEFAULT_RESOLVER_OPTIONS=rt,m.EIDCache=ut,m.EID_VERSION="1.0",m.FallbackHandler=mt,m.MAX_PATH_DEPTH=10,m.PathBuilder=ot,m.ROLE_ANCHOR_VALUES=G,m.SEMANTIC_ANCHOR_TAGS=B,m.SEMANTIC_ATTRIBUTES=vt,m.SEMANTIC_TAGS=tt,m.SemanticExtractor=ct,m.SemanticsMatcher=dt,m.SvgFingerprinter=lt,m.calculateConfidence=ht,m.calculateElementScore=_t,m.createEIDCache=ft,m.filterClasses=it,m.generateEID=W,m.generateEIDBatch=Jt,m.generateEIDForElements=te,m.generateSEQL=Yt,m.getClassScore=Ht,m.getGlobalCache=j,m.isEID=Wt,m.isUtilityClass=V,m.normalizeText=z,m.parseSEQL=At,m.resetGlobalCache=qt,m.resolve=pt,m.resolveSEQL=Xt,m.stringifySEQL=yt,m.validateEID=jt,Object.defineProperty(m,Symbol.toStringTag,{value:"Module"})}));
1
+ (function(m,q){typeof exports=="object"&&typeof module<"u"?q(exports):typeof define=="function"&&define.amd?define(["exports"],q):(m=typeof globalThis<"u"?globalThis:m||self,q(m.SeqlJS={}))})(this,(function(m){"use strict";const z={ANCHOR:.4,PATH:.3,TARGET:.2,UNIQUENESS:.1},v={SEMANTIC_TAG:.5,ROLE:.3,ARIA_LABEL:.1,STABLE_ID:.1,TEST_MARKER:.05,DEPTH_PENALTY_THRESHOLD:5,DEPTH_PENALTY_FACTOR:.05,DEGRADED_SCORE:.3},vt={MIN_CONFIDENCE_FOR_SKIP:.7},B=["form","main","nav","section","article","footer","header"],G=["form","navigation","main","region","contentinfo","complementary","banner","search"],st=["article","aside","details","figcaption","figure","footer","header","main","mark","nav","section","summary","time","button","datalist","fieldset","form","input","label","legend","meter","optgroup","option","output","progress","select","textarea","a","audio","video","canvas","dialog","menu","blockquote","dd","dl","dt","hr","li","ol","ul","p","pre","h1","h2","h3","h4","h5","h6","caption","col","colgroup","table","tbody","td","tfoot","th","thead","tr","svg","path","circle","rect","line","polyline","polygon","ellipse","g","text","use"],$t=["rect","path","circle","line","polyline","polygon","ellipse","g","text","use","defs","clipPath","mask"],It=["aria-label","aria-labelledby","aria-describedby","name","type","data-testid","data-qa","data-test","href","title","placeholder","alt"],T={"data-testid":100,"data-qa":99,"data-cy":98,"data-test":97,"data-test-id":96,"aria-label":90,"aria-labelledby":85,"aria-describedby":80,name:75,href:70,src:70,type:65,role:60,alt:55,title:50,for:45,placeholder:40,"data-*":30,"aria-*":25},rt=new Set(["id","class","style","xmlns","tabindex","contenteditable"]),nt={maxPathDepth:10,enableSvgFingerprint:!0,confidenceThreshold:.1,fallbackToBody:!0,includeUtilityClasses:!1,source:"dom-dsl"},it={strictMode:!1,enableFallback:!0,maxCandidates:20};function R(n){return!!(/^[a-z]+-\d+$/i.test(n)||/^[a-z]+(-[a-z]+)+-\d+$/i.test(n)||/^[a-z]+(_[a-z]+)*_\d+$/i.test(n)||/^\d+$/.test(n)||/^:[a-z0-9]+:$/i.test(n)||/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i.test(n)||/^[a-z]{1,3}[A-Za-z0-9]{8,}$/.test(n)&&(/\d/.test(n)||/[A-Z]/.test(n))||/^radix-/.test(n)||/^mui-\d+$/.test(n))}const V=new Set(["aria-labelledby","aria-describedby","aria-controls","aria-owns","aria-activedescendant","for","form","list","headers","aria-details","aria-errormessage","aria-flowto"]);function Q(n){return n.trim().split(/\s+/).some(e=>R(e))}class at{constructor(t,e){this.maxDepth=t.maxPathDepth??10,this.cache=e}findAnchor(t){if(this.cache){const a=this.cache.getAnchor(t);if(a!==void 0)return a}let e=t.parentElement,s=0,r=null;for(;e&&s<this.maxDepth;){if(e.tagName.toLowerCase()==="body")return r||{element:e,score:v.DEGRADED_SCORE,tier:"C",depth:s};const a=this.scoreAnchor(e);if(a>0){const o=this.applyDepthPenalty(a,s),l=this.getTier(e),h={element:e,score:o,tier:l,depth:s};if(l==="A")return h;(!r||o>r.score)&&(r=h)}e=e.parentElement,s++}const i=r;return this.cache&&this.cache.setAnchor(t,i),i}scoreAnchor(t){let e=0;const s=t.tagName.toLowerCase();B.includes(s)&&(e+=v.SEMANTIC_TAG);const r=t.getAttribute("role");r&&G.includes(r)&&(e+=v.ROLE),(t.hasAttribute("aria-label")||t.hasAttribute("aria-labelledby"))&&(e+=v.ARIA_LABEL);const i=t.id;return i&&!R(i)&&(e+=v.STABLE_ID),(t.hasAttribute("data-testid")||t.hasAttribute("data-qa")||t.hasAttribute("data-test"))&&(e+=v.TEST_MARKER),Math.min(e,1)}applyDepthPenalty(t,e){if(e<=v.DEPTH_PENALTY_THRESHOLD)return t;const s=(e-v.DEPTH_PENALTY_THRESHOLD)*v.DEPTH_PENALTY_FACTOR;return Math.max(0,t-s)}getTier(t){const e=t.tagName.toLowerCase();if(B.includes(e))return"A";const s=t.getAttribute("role");return s&&G.includes(s)?"B":"C"}}const Mt=[/^css-[a-z0-9]+$/i,/^sc-[a-z0-9]+-\d+$/i,/^[a-z]{5,8}$/i,/^Mui[A-Z]\w+-\w+-\w+/,/^makeStyles-\w+-\d+$/,/^jss\d+$/,/^(emotion|linaria)-[a-z0-9]+/i,/^(chakra|tw-|ant-)[a-z0-9]+-\w+/i,/-[a-f0-9]{6,}$/i,/^_[a-z0-9]{5,}$/i,/\d{5,}/],Nt=[/^\[/,/^(first|last|odd|even|only|first-of-type|last-of-type|only-of-type):/,/^(hover|focus|active|disabled|enabled|checked|indeterminate|default|required|valid|invalid|in-range|out-of-range|placeholder-shown|autofill|read-only):/,/^(focus-within|focus-visible|visited|target|open):/,/^(sm|md|lg|xl|2xl|3xl|4xl|5xl|6xl|7xl):/,/^dark:/,/^(rtl|ltr):/,/^(group|peer)(-hover|-focus|-active)?:/,/\/([\d.]+|full|auto|screen)$/,/^(inset|top|right|bottom|left)(-|$)/,/^(flex|inline-flex|grid|block|inline|inline-block|hidden|visible)$/,/^(absolute|relative|fixed|sticky|static)$/,/^(items|justify|content|self|place)-/,/^flex-(row|col|wrap|nowrap|1|auto|initial|none)/,/^grid-(cols|rows|flow)/,/^(gap|space)-/,/^[mp][trblxy]?-(\d+|auto|px)$/,/^(w|h|min-w|min-h|max-w|max-h|size)-/,/^text-(center|left|right|justify|start|end|xs|sm|base|lg|xl|2xl|3xl|4xl|5xl|6xl|7xl|8xl|9xl)$/,/^text-(uppercase|lowercase|capitalize|normal-case|underline|line-through|no-underline)$/,/^text-(truncate|ellipsis|clip)$/,/^(bg|border|ring|shadow|outline)-/,/^rounded(-|$)/,/^(font|leading|tracking|whitespace|break|truncate)-/,/^(uppercase|lowercase|capitalize|normal-case)$/,/^(transform|transition|duration|delay|ease|animate)-/,/^(scale|rotate|translate|skew)-/,/^transform$/,/^backdrop-blur-/,/^motion-/,/^(fade|slide|zoom|bounce|pulse|spin|ping)-/,/^(overflow|overscroll|scroll)-/,/^(cursor|pointer-events|select|resize)-/,/^(opacity|z)-/,/^(visible|invisible|collapse)$/,/^d-(none|inline|inline-block|block|grid|table|flex)$/,/^(float|clearfix|text)-(left|right|center|justify|start|end)$/,/^(m|p)[trblxy]?-[0-5]$/,/^(w|h)-(25|50|75|100|auto)$/,/^btn-(sm|lg|block)$/,/^text-(muted|primary|success|danger|warning|info|light|dark|white)$/,/^bg-(primary|secondary|success|danger|warning|info|light|dark|white|transparent)$/,/^border(-top|-bottom|-left|-right)?(-0)?$/,/^rounded(-top|-bottom|-left|-right|-circle|-pill|-0)?$/,/^shadow(-sm|-lg|-none)?$/,/^(align|justify|order|flex)-(start|end|center|between|around|fill|grow|shrink)$/,/^col(-sm|-md|-lg|-xl)?(-\d+|-auto)?$/,/^row(-cols)?(-\d+)?$/,/^g[xy]?-[0-5]$/,/^(show|hide|invisible|visible)$/,/^(position|top|bottom|start|end)-(static|relative|absolute|fixed|sticky|-\d+)$/,/^(row|col)$/,/^clearfix$/,/^pull-(left|right)$/,/^float-(left|right|none)$/],Rt=[/^(nav|menu|header|footer|sidebar|topbar|navbar|breadcrumb)/,/(navigation|dropdown|megamenu)$/,/^(btn|button|link|card|modal|dialog|popup|tooltip|alert|badge|chip)/,/^(form|input|select|checkbox|radio|textarea|label|fieldset)/,/^(table|list|item|row|cell|column)/,/^(accordion|tab|carousel|slider|gallery)/,/^(content|main|article|post|comment|title|subtitle|description|caption)/,/^(hero|banner|jumbotron|section|wrapper|box)/,/^(user|profile|avatar|account|auth)/,/^(product|item|price|cart|checkout|order)/,/^(page|layout|panel|widget|block)/,/-(primary|secondary|tertiary|success|error|warning|info|danger)$/,/-(active|inactive|disabled|enabled|selected|highlighted|focused)$/,/-(open|closed|expanded|collapsed|visible|hidden)$/,/-(large|medium|small|tiny|xs|sm|md|lg|xl)$/,/^(submit|cancel|close|delete|edit|save|back|next|prev|search)/,/^(loading|pending|complete|failed|draft|published)/];function _(n){return Mt.some(t=>t.test(n))}function L(n){return n.length<=2||/^\d/.test(n)?!0:Nt.some(t=>t.test(n))}function Dt(n){return _(n)||L(n)?!1:Rt.some(t=>t.test(n))}function Ht(n){return!_(n)&&!L(n)}function N(n){return n.filter(t=>Ht(t))}function Pt(n){if(_(n)||L(n))return 0;let t=.5;return Dt(n)&&(t=.8),n.length<3?t*=.3:n.length<5&&(t*=.6),/\d/.test(n)&&(t*=.7),Math.min(t,1)}function ot(n){const t=[],e=[];for(const s of n)L(s)||_(s)?e.push(s):t.push(s);return{semantic:t,utility:e}}function Z(n){return L(n)||_(n)}function Ot(n){return Pt(n)}const ct=n=>n.replace(/([#:.[\]@])/g,"\\$1");class lt{constructor(t,e){this.maxDepth=t.maxPathDepth??10,this.cache=e}buildPath(t,e,s){const r=[];let i=e.parentElement;for(;i&&i!==t&&r.length<this.maxDepth;)r.unshift(i),i=i.parentElement;const a=r.length>=this.maxDepth&&i!==t;let o=this.filterNoise(r);return o=this.ensureUniqueness(r,o,t,e,s),{path:o.map(h=>{const c=h.parentElement;let u;if(c){const g=Array.from(c.children).indexOf(h);g!==-1&&(u=g+1)}return{tag:h.tagName.toLowerCase(),semantics:s.extract(h),score:s.scoreElement(h),nthChild:u}}),degraded:a,degradationReason:a?"path-depth-overflow":void 0}}buildPathNodes(t,e,s){return this.buildPath(t,e,s).path}ensureUniqueness(t,e,s,r,i){const a=this.buildTestSelector(s,e,r);try{const o=r.ownerDocument;if(!o)return e;let l;if(this.cache){const c=this.cache.getSelectorResults(a);c!==void 0?l=c:(l=Array.from(o.querySelectorAll(a)),this.cache.setSelectorResults(a,l))}else l=o.querySelectorAll(a);if(l.length<=1)return e;const h=t.filter(c=>!e.includes(c));for(const c of h){if(i.scoreElement(c)<vt.MIN_CONFIDENCE_FOR_SKIP)continue;const f=this.insertNodeInOrder(e,c,t),g=this.buildTestSelector(s,f,r);try{let d;if(this.cache){const p=this.cache.getSelectorResults(g);p!==void 0?d=p:(d=Array.from(o.querySelectorAll(g)),this.cache.setSelectorResults(g,d))}else d=o.querySelectorAll(g);if(d.length===1)return f;d.length<l.length&&(e=f)}catch{}}return e}catch{return e}}insertNodeInOrder(t,e,s){const r=s.indexOf(e),i=[...t];let a=0;for(let o=0;o<i.length&&!(s.indexOf(i[o])>r);o++)a=o+1;return i.splice(a,0,e),i}buildTestSelector(t,e,s){const r=[];r.push(this.elementToSelector(t));for(const i of e)r.push(this.elementToSelector(i));return r.push(this.elementToSelector(s)),r.join(" ")}elementToSelector(t){let e=t.tagName.toLowerCase();t.id&&!R(t.id)&&(e+=`#${ct(t.id)}`);for(const s of Array.from(t.classList))Z(s)||(e+=`.${ct(s)}`);return e}filterNoise(t){return t.filter(e=>this.shouldInclude(e))}shouldInclude(t){const e=t.tagName.toLowerCase();return st.includes(e)?!0:e==="div"||e==="span"?this.hasSemanticFeatures(t):!1}hasSemanticFeatures(t){if(t.hasAttribute("role"))return!0;for(const s of Array.from(t.attributes))if(s.name.startsWith("aria-"))return!0;if(t.classList.length>0){for(const s of Array.from(t.classList))if(!Z(s))return!0}if(t.hasAttribute("data-testid")||t.hasAttribute("data-qa")||t.hasAttribute("data-test"))return!0;const e=t.id;return!!(e&&!R(e))}}function F(n){return n?n.trim().replace(/[\n\t\r]/g," ").replace(/\s+/g," "):""}const _t={preserveQueryForAbsolute:!0,removeDynamicHashes:!0};function Lt(n){return n?[/\d{5,}/,/[a-f0-9]{8,}/i,/(session|token|temp|random|timestamp|nonce|cache)/i,/^\d+$/,/^[a-f0-9-]{32,}$/i].some(e=>e.test(n)):!1}function kt(n,t){if(!n)return n;const e=n.startsWith("http://")||n.startsWith("https://");let[s,r]=n.split("#");const[i,a]=s.split("?");let o=i;return e&&t.preserveQueryForAbsolute&&a&&(o+=`?${a}`),r&&(t.removeDynamicHashes&&Lt(r)||(o+=`#${r}`)),o}function P(n,t,e={}){if(!t)return t;const s={..._t,...e};return n==="href"||n==="src"?kt(t,s):t}class ht{constructor(t,e){this.includeUtilityClasses=t.includeUtilityClasses??!1,this.cache=e}extract(t){if(this.cache){const a=this.cache.getSemantics(t);if(a!==void 0)return a}const e={},s=t.id;if(s&&!R(s)&&(e.id=s),t.classList.length>0){const a=Array.from(t.classList);if(this.includeUtilityClasses)e.classes=a;else{const{semantic:o}=ot(a);o.length>0&&(e.classes=o)}}const r=this.extractAttributes(t);Object.keys(r).length>0&&(e.attributes=r);const i=t.getAttribute("role");if(i&&(e.role=i),this.shouldExtractText(t)){const a=this.extractText(t);a&&(e.text=a)}return this.cache&&this.cache.setSemantics(t,e),e}scoreElement(t){let e=.5;const s=this.extract(t);return s.id&&(e+=.15),s.classes&&s.classes.length>0&&(e+=.1),s.attributes&&Object.keys(s.attributes).length>0&&(e+=.1),s.role&&(e+=.1),s.text&&(e+=.05),Math.min(e,1)}shouldIgnoreAttribute(t){return!!(rt.has(t)||t.startsWith("on")||t.startsWith("ng-")||t.startsWith("_ng")||t.startsWith("data-reactid")||t.startsWith("data-react")||t.startsWith("data-v-"))}getAttributePriority(t){return T[t]!==void 0?T[t]:t.startsWith("data-")?T["data-*"]:t.startsWith("aria-")?T["aria-*"]:0}isDynamicValue(t){return[/^[a-f0-9]{32,}$/i,/^\d{10,}$/,/^(undefined|null|\[object)/,/^{{.*}}$/].some(s=>s.test(t))}extractAttributes(t){const e={};for(const s of Array.from(t.attributes)){const r=s.name;if(this.shouldIgnoreAttribute(r)||V.has(r)&&Q(s.value)||this.getAttributePriority(r)===0)continue;const a=r==="href"||r==="src"?P(r,s.value):s.value;!a||a.trim()===""||this.isDynamicValue(a)||(e[r]=a)}return e}extractText(t){const e=this.getDirectTextContent(t);if(!e)return null;const s=F(e);if(!s)return null;const r=100,i=e.length>r?e.slice(0,r)+"...":e,a=s.length>r?s.slice(0,r)+"...":s;return{raw:i,normalized:a}}getDirectTextContent(t){const e=[];for(const s of Array.from(t.childNodes))if(s.nodeType===Node.TEXT_NODE&&s.textContent){const r=s.textContent.trim();r&&e.push(r)}return e.length>0?e.join(" "):t.textContent??null}shouldExtractText(t){const e=t.tagName.toLowerCase();return["button","a","label","h1","h2","h3","h4","h5","h6","p","span","li","th","td","dt","dd","legend","figcaption","summary"].includes(e)}}class ut{fingerprint(t){const e=t.tagName.toLowerCase(),s=this.getShape(e),r={shape:s,hasAnimation:this.hasAnimation(t)};if(s==="path"){const o=t.getAttribute("d");o&&(r.dHash=this.computePathHash(o))}else["circle","rect","ellipse","line"].includes(s)&&(r.geomHash=this.computeGeomHash(t,s));const i=t.getAttribute("role");i&&(r.role=i);const a=t.querySelector("title");return a?.textContent&&(r.titleText=a.textContent.trim()),r}computePathHash(t){const e=this.normalizePathData(t);return this.simpleHash(e)}getShape(t){return["path","circle","rect","line","polyline","polygon","ellipse","g","text","use","svg"].find(s=>s===t)??"path"}normalizePathData(t){return(t.match(/[MLHVCSQTAZ][^MLHVCSQTAZ]*/gi)??[]).slice(0,5).map(r=>r.trim().replace(/(-?\d+\.?\d*)/g,i=>parseFloat(i).toFixed(1))).join(" ")}computeGeomHash(t,e){const s=[];switch(e){case"circle":s.push(`r=${t.getAttribute("r")??"0"}`);break;case"rect":{const r=parseFloat(t.getAttribute("width")??"0"),i=parseFloat(t.getAttribute("height")??"0");r>0&&i>0&&s.push(`ratio=${(r/i).toFixed(2)}`)}break;case"ellipse":{const r=parseFloat(t.getAttribute("rx")??"0"),i=parseFloat(t.getAttribute("ry")??"0");r>0&&i>0&&s.push(`ratio=${(r/i).toFixed(2)}`)}break;case"line":{const r=parseFloat(t.getAttribute("x1")??"0"),i=parseFloat(t.getAttribute("y1")??"0"),a=parseFloat(t.getAttribute("x2")??"0"),o=parseFloat(t.getAttribute("y2")??"0"),l=Math.atan2(o-i,a-r);s.push(`angle=${l.toFixed(2)}`)}break}return this.simpleHash(s.join(";"))}hasAnimation(t){if(t.querySelector("animate, animateTransform, animateMotion"))return!0;const e=t.ownerDocument;if(e?.defaultView)try{const s=e.defaultView.getComputedStyle(t);if(s.animationName!=="none"||s.transitionProperty!=="all"&&s.transitionProperty!=="none")return!0}catch{}return!1}simpleHash(t){let e=0;for(let s=0;s<t.length;s++){const r=t.charCodeAt(s);e=(e<<5)-e+r,e=e&e}return Math.abs(e).toString(16).padStart(8,"0")}}function ft(n,t=0){const e=n.anchor.score,s=n.path.length>0?n.path.reduce((o,l)=>o+l.score,0)/n.path.length:.5,r=n.target.score,i=e*z.ANCHOR+s*z.PATH+r*z.TARGET+t*z.UNIQUENESS,a=n.anchor.degraded?.2:0;return Math.max(0,Math.min(1,i-a))}function qt(n,t,e){let s=.5;return t&&(s+=.2),e&&(s+=.15),s+=Math.min(n*.05,.15),Math.min(s,1)}class zt{constructor(t){this.cache=new Map,this.maxSize=t}get(t){if(!this.cache.has(t))return;const e=this.cache.get(t);return this.cache.delete(t),this.cache.set(t,e),e}set(t,e){if(this.cache.has(t))this.cache.delete(t);else if(this.cache.size>=this.maxSize){const s=this.cache.keys().next().value;s!==void 0&&this.cache.delete(s)}this.cache.set(t,e)}has(t){return this.cache.has(t)}delete(t){this.cache.delete(t)}clear(){this.cache.clear()}get size(){return this.cache.size}}class dt{constructor(t={}){this.eidCache=new WeakMap,this.selectorResultCache=new zt(t.maxSelectorCacheSize??1e3),this.anchorCache=new WeakMap,this.semanticsCache=new WeakMap,this.stats={eidHits:0,eidMisses:0,selectorHits:0,selectorMisses:0,anchorHits:0,anchorMisses:0,semanticsHits:0,semanticsMisses:0,selectorCacheSize:0,maxSelectorCacheSize:t.maxSelectorCacheSize??1e3}}getEID(t){const e=this.eidCache.get(t);if(e!==void 0)return this.stats.eidHits++,e;this.stats.eidMisses++}setEID(t,e){this.eidCache.set(t,e)}getSelectorResults(t){const e=this.selectorResultCache.get(t);if(e!==void 0)return this.stats.selectorHits++,this.stats.selectorCacheSize=this.selectorResultCache.size,e;this.stats.selectorMisses++,this.stats.selectorCacheSize=this.selectorResultCache.size}setSelectorResults(t,e){this.selectorResultCache.set(t,e),this.stats.selectorCacheSize=this.selectorResultCache.size}getAnchor(t){if(this.anchorCache.has(t))return this.stats.anchorHits++,this.anchorCache.get(t);this.stats.anchorMisses++}setAnchor(t,e){this.anchorCache.set(t,e)}getSemantics(t){const e=this.semanticsCache.get(t);if(e!==void 0)return this.stats.semanticsHits++,e;this.stats.semanticsMisses++}setSemantics(t,e){this.semanticsCache.set(t,e)}clear(){this.selectorResultCache.clear(),this.stats.selectorCacheSize=0,this.stats={eidHits:0,eidMisses:0,selectorHits:0,selectorMisses:0,anchorHits:0,anchorMisses:0,semanticsHits:0,semanticsMisses:0,selectorCacheSize:0,maxSelectorCacheSize:this.stats.maxSelectorCacheSize}}invalidateElement(t){}invalidateSelector(t){this.selectorResultCache.delete(t),this.stats.selectorCacheSize=this.selectorResultCache.size}getStats(){return{...this.stats,selectorCacheSize:this.selectorResultCache.size}}getEIDHitRate(){const t=this.stats.eidHits+this.stats.eidMisses;return t>0?this.stats.eidHits/t:0}getSelectorHitRate(){const t=this.stats.selectorHits+this.stats.selectorMisses;return t>0?this.stats.selectorHits/t:0}getAnchorHitRate(){const t=this.stats.anchorHits+this.stats.anchorMisses;return t>0?this.stats.anchorHits/t:0}getSemanticsHitRate(){const t=this.stats.semanticsHits+this.stats.semanticsMisses;return t>0?this.stats.semanticsHits/t:0}getOverallHitRate(){const t=this.stats.eidHits+this.stats.selectorHits+this.stats.anchorHits+this.stats.semanticsHits,e=this.stats.eidMisses+this.stats.selectorMisses+this.stats.anchorMisses+this.stats.semanticsMisses,s=t+e;return s>0?t/s:0}}function gt(n){return new dt(n)}let U=null;function j(){return U||(U=gt()),U}function Ft(){U=null}function W(n,t={}){if(!n||!n.ownerDocument||!n.isConnected)return null;const e={...nt,...t},s=e.cache??j(),r=s.getEID(n);if(r!==void 0)return r;const i=new at(e,s),a=new lt(e,s),o=new ht(e,s),l=new ut,h=i.findAnchor(n);if(!h&&!e.fallbackToBody)return null;const c=h?.element??n.ownerDocument?.body??null;if(!c)return null;const u=!h||h.tier==="C",f=o.extract(c),g={tag:c.tagName.toLowerCase(),semantics:f,score:h?.score??v.DEGRADED_SCORE,degraded:u},d=a.buildPath(c,n,o),p=o.extract(n);e.enableSvgFingerprint&&Ut(n)&&(p.svg=l.fingerprint(n));const b=n.parentElement;let y;if(b){const x=Array.from(b.children).indexOf(n);x!==-1&&(y=x+1)}const A={tag:n.tagName.toLowerCase(),semantics:p,score:o.scoreElement(n),nthChild:y},$=[],C={onMultiple:"best-score",onMissing:"anchor-only",maxDepth:3},S=g.degraded||d.degraded,I=jt(g.degraded,d),E={version:"1.0",anchor:g,path:d.path,target:A,constraints:$,fallback:C,meta:{confidence:0,generatedAt:new Date().toISOString(),generator:"dom-eid@1.0",source:e.source,degraded:S,degradationReason:I}};return E.meta.confidence=ft(E),E.meta.confidence<e.confidenceThreshold?null:(s.setEID(n,E),E)}function Ut(n){return n.namespaceURI==="http://www.w3.org/2000/svg"||n.tagName.toLowerCase()==="svg"||n instanceof SVGElement}function jt(n,t){if(n&&t.degraded)return"anchor-and-path-degraded";if(n)return"no-semantic-anchor";if(t.degraded)return t.degradationReason}class Y{buildSelector(t,e){if(t.path.length===0&&t.anchor.tag===t.target.tag&&JSON.stringify(t.anchor.semantics)===JSON.stringify(t.target.semantics)){const u=this.buildNodeSelector(t.target.tag,t.target.semantics,{excludeClasses:!1});return e?.ensureUnique?this.ensureUniqueSelector(u,t,e):u}const r=[],i=e?.ensureUnique?this.ensureUniqueAnchor(t,e.root??document):this.buildNodeSelector(t.anchor.tag,t.anchor.semantics);r.push(i);for(const u of t.path){let f=this.buildNodeSelector(u.tag,u.semantics);u.nthChild!==void 0&&(["tr","td","th","thead","tbody","tfoot"].includes(u.tag)?f+=`:nth-child(${u.nthChild})`:f+=`:nth-child(${u.nthChild})`),r.push(f)}let a=this.buildNodeSelector(t.target.tag,t.target.semantics,{excludeClasses:e?.ensureUnique});t.target.nthChild!==void 0&&(["tr","td","th","thead","tbody","tfoot"].includes(t.target.tag)?a+=`:nth-child(${t.target.nthChild})`:a+=`:nth-child(${t.target.nthChild})`),r.push(a);const o=this.isSvgChildElement(t.target.tag),l=t.path.some(u=>u.tag==="svg");let h;if(o&&l){const u=t.path.findIndex(f=>f.tag==="svg");if(u!==-1){const f=u+1,g=r.slice(0,f+1),d=r.slice(f+1,-1),p=r[r.length-1];d.length>0?h=g.join(" ")+" > "+d.join(" > ")+" > "+p:h=g.join(" ")+" > "+p}else h=r.join(" ")}else h=r.join(" ");if(!e?.ensureUnique)return h;const c=this.querySelectorSafe(h,e.root??document);if(c.length===1)return{selector:h,isUnique:!0,usedNthOfType:h.includes(":nth-"),extraClassesAdded:0};if(c.length===0||c.length>1){const u=this.buildFullDomPathSelector(t,t.target.semantics,e.root??document);if(u&&this.isUnique(u,e.root??document))return{selector:u,isUnique:!0,usedNthOfType:u.includes(":nth-"),extraClassesAdded:0}}return this.ensureUniqueSelector(h,t,e)}buildAnchorSelector(t){return this.buildNodeSelector(t.anchor.tag,t.anchor.semantics)}ensureUniqueSelector(t,e,s){const r=s.root??document,i=s.maxClasses??4,a=e.target.tag,o=e.target.semantics;let l=t,h=0,c=!1;if(this.querySelectorSafe(l,r).length===0){const d=this.buildFullDomPathSelector(e,o,r);if(d&&(l=d,this.isUnique(l,r)))return{selector:l,isUnique:!0,usedNthOfType:!1,extraClassesAdded:0}}if(this.isUnique(l,r))return{selector:l,isUnique:!0,usedNthOfType:!1,extraClassesAdded:0};const f=N(o.classes??[]);for(let d=0;d<Math.min(f.length,i);d++){const p=f[d];if(l+=`.${this.escapeCSS(p)}`,h++,this.isUnique(l,r))return{selector:l,isUnique:!0,usedNthOfType:!1,extraClassesAdded:h}}if(!this.isUnique(l,r)){const d=this.buildFullDomPathSelector(e,o,r);if(d&&this.isUnique(d,r))return{selector:d,isUnique:!0,usedNthOfType:d.includes(":nth-of-type("),extraClassesAdded:h}}const g=this.findNthElementByText(l,o,r);return g&&(l+=this.getNthSelector(g,a),c=!0),{selector:l,isUnique:this.isUnique(l,r),usedNthOfType:c,extraClassesAdded:h}}buildFullDomPathSelector(t,e,s){const r=this.buildNodeSelector(t.anchor.tag,t.anchor.semantics),i=this.querySelectorSafe(r,s);if(i.length===0)return null;for(const a of i){const o=this.findTargetWithinAnchor(a,t.target.tag,e);if(o.length===0)continue;const l=o.map(h=>{const c=this.scorePathMatch(h,a,t.path);return{element:h,score:c}});l.sort((h,c)=>c.score-h.score);for(const{element:h}of l){const c=this.buildPathFromAnchorToTarget(a,h,t,s);if(c&&this.isUnique(c,s))return c}}return null}scorePathMatch(t,e,s){const r=[];let i=t.parentElement;for(;i&&i!==e;)r.unshift(i),i=i.parentElement;let a=0;const o=Math.min(r.length,s.length);for(let h=0;h<o;h++){const c=r[h],u=s[h];if(c.tagName.toLowerCase()===u.tag){if(a+=10,u.nthChild!==void 0){const f=c.parentElement;f&&(Array.from(f.children).indexOf(c)+1===u.nthChild?a+=20:a-=10)}}else a-=5;if(u.semantics.classes&&u.semantics.classes.length>0){const f=u.semantics.classes.filter(g=>c.classList.contains(g));a+=f.length*2}if(u.semantics.attributes){const f=Object.entries(u.semantics.attributes).filter(([g,d])=>c.getAttribute(g)===d);a+=f.length*3}}const l=Math.abs(r.length-s.length);return a-=l*2,a}findTargetWithinAnchor(t,e,s){return Array.from(t.querySelectorAll(e)).filter(i=>{if(s.text){const a=i.textContent?.trim()||"",o=s.text.normalized;if(!a.includes(o)&&!o.includes(a))return!1}return!!(s.classes&&s.classes.length>0&&s.classes.every(o=>i.classList.contains(o))||s.attributes&&Object.entries(s.attributes).every(([o,l])=>{const h=i.getAttribute(o);return o==="href"||o==="src"?P(o,h||"")===P(o,l):h===l})||s.text)})}disambiguateParent(t,e,s,r,i){if(s?.semantics?.attributes){const o=this.buildNodeSelector(e,s.semantics,{excludeClasses:!0}),l=[...r,e].join(" > "),h=this.querySelectorSafe(l,i),c=[...r,o].join(" > "),u=this.querySelectorSafe(c,i);if(u.length>0&&u.length<h.length)return o}if(s?.semantics?.classes){const o=N(s.semantics.classes);if(o.length>0){const l=`${e}.${this.escapeCSS(o[0])}`,h=[...r,e].join(" > "),c=this.querySelectorSafe(h,i),u=[...r,l].join(" > "),f=this.querySelectorSafe(u,i);if(f.length>0&&f.length<c.length)return l}}const a=t.parentElement;return a&&Array.from(a.children).filter(l=>l.tagName.toLowerCase()===e).length>1?`${e}${this.getNthSelector(t,e)}`:e}buildPathFromAnchorToTarget(t,e,s,r){const i=[];let a=e;for(;a&&a!==t;)i.unshift(a),a=a.parentElement;if(a!==t)return null;const o=[()=>{const l=this.buildNodeSelector(s.anchor.tag,s.anchor.semantics),h=s.target.tag,c=s.target.semantics,u=[];for(const b of s.path)u.push(b.tag);const g=[l,...u,h].filter(Boolean).join(" ");if(this.isUnique(g,r))return g;const d=this.buildNodeSelector(h,c,{excludeClasses:!0}),p=[l,...u.slice(0,-1),d].join(" ");return this.isUnique(p,r)?p:null},()=>{const l=[this.buildNodeSelector(s.anchor.tag,s.anchor.semantics)],h=new Map;let c=0;for(let f=0;f<i.length-1;f++){const g=i[f],d=g.tagName.toLowerCase();c<s.path.length&&s.path[c].tag===d?(h.set(g,s.path[c]),c++):h.set(g,null)}for(let f=0;f<i.length;f++){const g=i[f],d=g.tagName.toLowerCase();if(f<i.length-1){const y=h.get(g)||null,A=this.disambiguateParent(g,d,y,l,r);l.push(A);continue}const p=this.buildNodeSelector(s.target.tag,s.target.semantics,{excludeClasses:!0}),b=g.parentElement;b&&["td","th","tr","thead","tbody","tfoot"].includes(d)&&Array.from(b.children).filter(A=>A.tagName.toLowerCase()===d).length>1?l.push(`${p}${this.getNthSelector(g,d)}`):l.push(p)}const u=l.join(" > ");return this.isUnique(u,r)?u:null},()=>{const h=[this.buildNodeSelector(s.anchor.tag,s.anchor.semantics)];for(let f=0;f<i.length-1;f++){const d=i[f].tagName.toLowerCase(),p=s.path[f]||null,b=h.join(" ")+" "+d;if(this.querySelectorSafe(b,r).length>1){if(p?.semantics?.attributes){const C=this.buildNodeSelector(d,p.semantics,{excludeClasses:!0}),S=h.join(" ")+" "+C;if(this.querySelectorSafe(S,r).length===1||this.querySelectorSafe(S+" "+s.target.tag,r).length===1){h.push(C);continue}}if(p?.semantics?.classes){const C=N(p.semantics.classes);if(C.length>0){const S=`${d}.${this.escapeCSS(C[0])}`,I=h.join(" ")+" "+S;if(this.querySelectorSafe(I,r).length===1||this.querySelectorSafe(I+" "+s.target.tag,r).length===1){h.push(S);continue}}}const A=i[f],$=A.parentElement;if($&&Array.from($.children).filter(S=>S.tagName.toLowerCase()===d).length>1){h.push(`${d}${this.getNthSelector(A,d)}`);continue}}h.push(d)}const c=this.buildNodeSelector(s.target.tag,s.target.semantics,{excludeClasses:!0});h.push(c);const u=h.join(" ");return this.isUnique(u,r)?u:null},()=>{const l=this.buildNodeSelector(s.anchor.tag,s.anchor.semantics),h=[];for(const g of s.path)h.push(g.tag);if(N(s.target.semantics.classes??[]).length===0)return null;const u=this.buildNodeSelector(s.target.tag,s.target.semantics,{maxClasses:1}),f=[l,...h.slice(0,-1),u].join(" ");return this.isUnique(f,r)?f:null},()=>{const l=this.buildNodeSelector(s.anchor.tag,s.anchor.semantics),h=[];for(const p of s.path)h.push(p.tag);const c=i[i.length-1],u=c.parentElement;if(!u||Array.from(u.children).filter(p=>p.tagName.toLowerCase()===s.target.tag).length<=1)return null;const g=this.buildNodeSelector(s.target.tag,s.target.semantics,{excludeClasses:!0})+this.getNthSelector(c,s.target.tag),d=[l,...h.slice(0,-1),g].join(" ");return this.isUnique(d,r)?d:null}];for(const l of o){const h=l();if(h)return h}return null}buildElementSelector(t){const e=t.tagName.toLowerCase();let s=e;if(t.id&&!R(t.id))return`${e}#${this.escapeCSS(t.id)}`;const r=Array.from(t.classList),i=N(r);i.length>0&&(s+=i.slice(0,2).map(o=>`.${this.escapeCSS(o)}`).join(""));const a=t.getAttribute("role");return a&&(s+=`[role="${this.escapeAttr(a)}"]`),s}querySelectorSafe(t,e){try{return Array.from(e.querySelectorAll(t))}catch{return[]}}findNthElementByText(t,e,s){const r=this.querySelectorSafe(t,s);if(r.length<=1)return null;if(e.text){const i=e.text.normalized;for(const a of r){const o=a.textContent?.trim()||"";if(o===i||o.includes(i)||i.includes(o))return a}}return null}isUnique(t,e){try{return e.querySelectorAll(t).length===1}catch{return!1}}getNthOfTypeIndex(t,e){const s=t.parentElement;if(!s)return null;const i=Array.from(s.children).filter(a=>a.tagName.toLowerCase()===e).indexOf(t);return i!==-1?i+1:null}ensureUniqueAnchor(t,e){const s=t.anchor.tag,r=t.anchor.semantics;if(this.isUnique(s,e))return s;if(r.classes&&r.classes.length>0){const a=N(r.classes);if(a.length>0){const o=`${s}.${this.escapeCSS(a[0])}`;if(this.isUnique(o,e))return o}}if(r.attributes){const a=this.getSortedAttributes(r.attributes);for(const{name:o,value:l}of a){const h=o==="href"||o==="src"?P(o,l):l;if(h){const c=`${s}[${o}="${this.escapeAttr(h)}"]`;if(this.isUnique(c,e))return c}}}const i=Array.from(e.querySelectorAll(s));if(i.length>1){const a=this.findElementBySemantics(i,r);if(a){const o=this.getNthOfTypeIndex(a,s);if(o)return`${s}:nth-of-type(${o})`}}return s}findElementBySemantics(t,e){return e.classes&&e.classes.length>0||e.attributes&&Object.keys(e.attributes).length>0||e.text?t.find(r=>{if(e.classes&&e.classes.length>0&&e.classes.every(a=>r.classList.contains(a))||e.attributes&&Object.entries(e.attributes).every(([a,o])=>r.getAttribute(a)===o))return!0;if(e.text){const i=r.textContent?.trim()||"",a=e.text.normalized;if(i.includes(a)||a.includes(i))return!0}return!1})||null:t.length>0?t[0]:null}getNthSelector(t,e){const s=t.parentElement;if(!s)return"";const r=Array.from(s.children),i=r.indexOf(t)+1;return["tr","td","th","thead","tbody","tfoot"].includes(e)?`:nth-child(${i})`:`:nth-of-type(${r.filter(l=>l.tagName.toLowerCase()===e).indexOf(t)+1})`}getAttributePriority(t){return T[t]!==void 0?T[t]:t.startsWith("data-")?T["data-*"]:t.startsWith("aria-")?T["aria-*"]:0}shouldIgnoreAttribute(t){return!!(rt.has(t)||t.startsWith("on")||t.startsWith("ng-")||t.startsWith("_ng")||t.startsWith("data-reactid")||t.startsWith("data-react")||t.startsWith("data-v-"))}getSortedAttributes(t){return Object.entries(t).filter(([e])=>!this.shouldIgnoreAttribute(e)).filter(([e,s])=>!V.has(e)||!Q(s)).map(([e,s])=>({name:e,value:s,priority:this.getAttributePriority(e)})).filter(e=>e.priority>0).sort((e,s)=>s.priority-e.priority)}buildNodeSelector(t,e,s){let r=t;if(e.id)return r+=`#${this.escapeCSS(e.id)}`,r;if(e.attributes){const i=this.getSortedAttributes(e.attributes);for(const{name:a,value:o}of i){const l=a==="href"||a==="src"?P(a,o):o;l&&(r+=`[${a}="${this.escapeAttr(l)}"]`)}}if(e.role&&!e.attributes?.role&&(r+=`[role="${this.escapeAttr(e.role)}"]`),!s?.excludeClasses&&e.classes&&e.classes.length>0){const i=N(e.classes),a=s?.maxClasses!==void 0?i.slice(0,s.maxClasses):i;r+=a.map(o=>`.${this.escapeCSS(o)}`).join("")}return r}escapeCSS(t){return t.replace(/([!"#$%&'()*+,./:;<=>?@[\\\]^`{|}~])/g,"\\$1")}escapeAttr(t){return t.replace(/"/g,'\\"').replace(/\\/g,"\\\\")}isSvgChildElement(t){return $t.includes(t)}}class mt{match(t,e){return t.filter(s=>this.matchElement(s,e))}matchElement(t,e){return!(e.text&&!this.matchText(t,e.text)||e.attributes&&!this.matchAttributes(t,e.attributes)||e.svg&&!this.matchSvgFingerprint(t,e.svg))}matchText(t,e){const i=Array.from(t.childNodes).filter(o=>o.nodeType===Node.TEXT_NODE).map(o=>o.textContent?.trim()??"").join(" ")||(t.textContent?.trim()??"");if(!i)return!1;const a=F(i);return e.matchMode==="partial"?a.includes(e.normalized):a===e.normalized}matchAttributes(t,e){for(const[s,r]of Object.entries(e))if(t.getAttribute(s)!==r)return!1;return!0}matchSvgFingerprint(t,e){if(t.tagName.toLowerCase()!==e.shape)return!1;if(e.dHash&&e.shape==="path"){const s=t.getAttribute("d");if(s&&this.computePathHash(s)!==e.dHash)return!1}return!(e.geomHash&&["circle","rect","ellipse","line"].includes(e.shape)&&this.computeGeomHash(t,e.shape)!==e.geomHash||e.titleText&&t.querySelector("title")?.textContent?.trim()!==e.titleText)}computePathHash(t){const r=(t.match(/[MLHVCSQTAZ][^MLHVCSQTAZ]*/gi)??[]).slice(0,5).map(i=>i.trim().replace(/(-?\d+\.?\d*)/g,a=>parseFloat(a).toFixed(1))).join(" ");return this.simpleHash(r)}computeGeomHash(t,e){const s=[];switch(e){case"circle":s.push(`r=${t.getAttribute("r")??"0"}`);break;case"rect":{const r=parseFloat(t.getAttribute("width")??"0"),i=parseFloat(t.getAttribute("height")??"0");r>0&&i>0&&s.push(`ratio=${(r/i).toFixed(2)}`);break}case"ellipse":{const r=parseFloat(t.getAttribute("rx")??"0"),i=parseFloat(t.getAttribute("ry")??"0");r>0&&i>0&&s.push(`ratio=${(r/i).toFixed(2)}`);break}case"line":{const r=parseFloat(t.getAttribute("x1")??"0"),i=parseFloat(t.getAttribute("y1")??"0"),a=parseFloat(t.getAttribute("x2")??"0"),o=parseFloat(t.getAttribute("y2")??"0"),l=Math.atan2(o-i,a-r);s.push(`angle=${l.toFixed(2)}`);break}}return this.simpleHash(s.join(";"))}simpleHash(t){let e=0;for(let s=0;s<t.length;s++){const r=t.charCodeAt(s);e=(e<<5)-e+r,e=e&e}return Math.abs(e).toString(16).padStart(8,"0")}}class pt{applyConstraint(t,e){switch(e.type){case"text-proximity":return this.applyTextProximity(t,e.params);case"position":return this.applyPosition(t,e.params);default:return t}}applyTextProximity(t,e){return t.filter(s=>{const r=s.textContent?.trim()??"";return this.levenshteinDistance(r,e.reference)<=e.maxDistance})}applyPosition(t,e){if(t.length<=1)return t;switch(e.strategy){case"first-in-dom":return[t[0]];case"top-most":return[this.getTopMost(t)];case"left-most":return[this.getLeftMost(t)];default:return[t[0]]}}getTopMost(t){return t.reduce((e,s)=>{try{const r=e.getBoundingClientRect();return s.getBoundingClientRect().top<r.top?s:e}catch{return e}})}getLeftMost(t){return t.reduce((e,s)=>{try{const r=e.getBoundingClientRect();return s.getBoundingClientRect().left<r.left?s:e}catch{return e}})}levenshteinDistance(t,e){if(t===e)return 0;if(t.length===0)return e.length;if(e.length===0)return t.length;const s=Array.from({length:e.length+1},(r,i)=>i);for(let r=1;r<=t.length;r++){let i=r;for(let a=1;a<=e.length;a++){const o=t[r-1]===e[a-1]?s[a-1]:Math.min(s[a-1],i,s[a])+1;s[a-1]=i,i=o}s[e.length]=i}return s[e.length]}}class bt{constructor(){this.cssGenerator=new Y}handleFallback(t,e){const{onMissing:s}=t.fallback;switch(s){case"anchor-only":return this.fallbackToAnchor(t,e);case"strict":return{status:"error",elements:[],warnings:["Element not found (strict mode)"],confidence:0,meta:{degraded:!0,degradationReason:"strict-not-found"}};default:return{status:"error",elements:[],warnings:["Element not found"],confidence:0,meta:{degraded:!0,degradationReason:"not-found"}}}}fallbackToAnchor(t,e){const s=this.cssGenerator.buildAnchorSelector(t),r=e instanceof Document?e:e.ownerDocument??e;try{const i=r.querySelector(s);if(i)return{status:"degraded-fallback",elements:[i],warnings:["Target not found, returning anchor"],confidence:t.meta.confidence*.3,meta:{degraded:!0,degradationReason:"anchor-fallback"}}}catch(i){const a=i instanceof Error?i.message:"Unknown selector error";return{status:"error",elements:[],warnings:[`Invalid anchor selector: ${a}`],confidence:0,meta:{degraded:!0,degradationReason:"invalid-anchor-selector"}}}return{status:"error",elements:[],warnings:["Anchor also not found"],confidence:0,meta:{degraded:!0,degradationReason:"anchor-not-found"}}}handleAmbiguous(t,e){const{onMultiple:s}=e.fallback;switch(s){case"first":return{status:"success",elements:[t[0]],warnings:["Multiple matches, returning first"],confidence:e.meta.confidence*.7,meta:{degraded:!0,degradationReason:"first-of-multiple"}};case"best-score":return this.selectBestScoring(t,e);default:return{status:"ambiguous",elements:t,warnings:[`Multiple matches: ${t.length}`],confidence:e.meta.confidence*.5,meta:{degraded:!0,degradationReason:"multiple-matches"}}}}selectBestScoring(t,e){const s=e.target.semantics;let r=t[0],i=-1;for(const a of t){const o=this.scoreElementMatch(a,s);o>i&&(i=o,r=a)}return{status:"success",elements:[r],warnings:[`Multiple matches (${t.length}), selected best-scoring element`],confidence:e.meta.confidence*(.7+i*.2),meta:{degraded:!0,degradationReason:"best-of-multiple"}}}scoreElementMatch(t,e){let s=0,r=0;if(e.id&&(r+=.3,t.id===e.id&&(s+=.3)),e.classes&&e.classes.length>0){r+=.25;const i=Array.from(t.classList),a=e.classes.filter(o=>i.includes(o)).length;s+=a/e.classes.length*.25}if(e.attributes){const i=Object.entries(e.attributes);if(i.length>0){r+=.2;let a=0;for(const[o,l]of i)t.getAttribute(o)===l&&a++;s+=a/i.length*.2}}if(e.role&&(r+=.15,t.getAttribute("role")===e.role&&(s+=.15)),e.text){r+=.1;const i=F(t.textContent);i===e.text.normalized?s+=.1:i.includes(e.text.normalized)&&(s+=.05)}return r>0?s/r:0}}function St(n,t,e={}){const s={...it,...e},r=new Y,i=new mt,a=new pt,o=new bt,l=t instanceof Document?t:t.ownerDocument??t,h=r.buildSelector(n,{ensureUnique:!1,root:l});let c;try{c=Array.from(l.querySelectorAll(h))}catch(d){const p=d instanceof Error?d.message:"Unknown selector error";return{status:"error",elements:[],warnings:[`Invalid CSS selector: ${h}`,`Error: ${p}`],confidence:0,meta:{degraded:!0,degradationReason:"invalid-selector"}}}c.length>s.maxCandidates&&(c=c.slice(0,s.maxCandidates));const u=i.match(c,n.target.semantics);if(u.length===1)return{status:"success",elements:u,warnings:[],confidence:n.meta.confidence,meta:{degraded:!1}};if(u.length===0)return s.enableFallback?o.handleFallback(n,l):{status:"error",elements:[],warnings:["No matching elements found"],confidence:0,meta:{degraded:!0,degradationReason:"not-found"}};let f=u;const g=Wt(n.constraints);for(const d of g){if(f=a.applyConstraint(f,d),f.length===1)return{status:"success",elements:f,warnings:[],confidence:n.meta.confidence*.9,meta:{degraded:!1}};if(f.length===0)return s.enableFallback?o.handleFallback(n,l):{status:"error",elements:[],warnings:["Constraints eliminated all candidates"],confidence:0,meta:{degraded:!0,degradationReason:"over-constrained"}}}return s.strictMode?{status:"ambiguous",elements:f,warnings:[`Non-unique resolution: ${f.length} matches`],confidence:n.meta.confidence*.7,meta:{degraded:!0,degradationReason:"ambiguous"}}:o.handleAmbiguous(f,n)}function Wt(n){return[...n].sort((t,e)=>e.priority-t.priority)}function Bt(n){const t=[],e=[];if(n.version?n.version!=="1.0"&&e.push(`Unknown version: ${n.version}`):t.push("Missing version field"),n.anchor?(n.anchor.tag||t.push("Anchor missing tag"),typeof n.anchor.score!="number"&&t.push("Anchor missing score"),n.anchor.semantics||t.push("Anchor missing semantics")):t.push("Missing anchor field"),n.target?(n.target.tag||t.push("Target missing tag"),typeof n.target.score!="number"&&t.push("Target missing score"),n.target.semantics||t.push("Target missing semantics")):t.push("Missing target field"),!Array.isArray(n.path))t.push("Path must be an array");else for(let s=0;s<n.path.length;s++){const r=n.path[s];r.tag||t.push(`Path node ${s} missing tag`),r.semantics||t.push(`Path node ${s} missing semantics`)}return n.meta?(typeof n.meta.confidence!="number"&&e.push("Missing confidence score"),n.meta.generatedAt||e.push("Missing generatedAt timestamp")):t.push("Missing meta field"),Array.isArray(n.constraints)||e.push("Constraints should be an array"),n.fallback||e.push("Missing fallback rules"),{valid:t.length===0,errors:t,warnings:e}}function Gt(n){if(!n||typeof n!="object")return!1;const t=n;return typeof t.version=="string"&&typeof t.anchor=="object"&&Array.isArray(t.path)&&typeof t.target=="object"}const yt={maxClasses:2,maxAttributes:5,includeText:!0,maxTextLength:50,simplifyTarget:!0,includeConstraints:!0};function At(n){return n==="id"?101:T[n]!==void 0?T[n]:n.startsWith("data-")?T["data-*"]:n.startsWith("aria-")?T["aria-*"]:0}function Vt(n){return["id","data-testid","data-qa","data-cy","href","text","role"].includes(n)}function Qt(n){return!!(/@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/.test(n)||/(\+?\d{1,3}[-.\s]?)?\(?\d{3}\)?[-.\s]?\d{3}[-.\s]?\d{4}/.test(n)||/\d{4}[-\s]?\d{4}[-\s]?\d{4}[-\s]?\d{4}/.test(n))}function Ct(n,t){const e={...yt,...t},s=`v${n.version}`,r=X(n.anchor,!1,e),i=n.path.length>0?n.path.map(l=>X(l,!1,e)).join(" > ")+" > ":"",a=X(n.target,!0,e),o=e.includeConstraints?Zt(n):"";return`${s}: ${r} :: ${i}${a}${o}`}function Et(n){n=n.trim();const t=n.match(/^v(\d+(?:\.\d+)?)\s*:\s*/);if(!t)throw new Error('Invalid SEQL Selector: missing version prefix (expected "v1:")');const e=t[1];if(e!=="1.0"&&e!=="1")throw new Error(`Unsupported SEQL Selector version: v${e} (only v1.0 is supported)`);let s=n.slice(t[0].length);const r=s.match(/^(.+?)\s*::\s*/);if(!r)throw new Error('Invalid SEQL Selector: missing anchor separator "::"');const i=r[1].trim();s=s.slice(r[0].length);const a=s.match(/\s*\{([^}]+)\}\s*$/);let o="";a&&(o=a[1],s=s.slice(0,a.index));const l=s.split(/\s*>\s*/).map(b=>b.trim()).filter(b=>b);if(l.length===0)throw new Error("Invalid SEQL Selector: missing target node");const h=l[l.length-1],c=l.slice(0,-1),u=K(i,!0),f=c.map(b=>K(b,!1)),g=K(h,!1),d=Yt(o);return{version:"1.0",anchor:u,path:f,target:g,constraints:d,fallback:{onMultiple:"best-score",onMissing:"anchor-only",maxDepth:10},meta:{confidence:.7,generatedAt:new Date().toISOString(),generator:"seql-parser@1.0",source:"seql-string",degraded:!1}}}function X(n,t=!1,e=yt){const{tag:s,semantics:r}=n;let i=s;const a=[],o={...r.attributes};r.id&&(o.id=r.id),r.role&&!o.role&&(o.role=r.role);const l=Object.entries(o).map(([c,u])=>{const f=At(c),g=c==="href"||c==="src"?P(c,u):u;return{name:c,value:g,priority:f}}).filter(c=>["style","xmlns","tabindex","contenteditable"].includes(c.name)||V.has(c.name)&&Q(c.value)?!1:c.priority>0||c.name==="role"||c.name==="id");l.sort((c,u)=>u.priority-c.priority);const h=l.slice(0,e.maxAttributes);h.sort((c,u)=>c.name.localeCompare(u.name));for(const{name:c,value:u}of h)a.push(`${c}="${J(u)}"`);if(e.includeText&&r.text&&!Qt(r.text.normalized)){const c=r.text.normalized;c.length>0&&c.length<=e.maxTextLength&&a.push(`text="${J(c)}"`)}if(a.length>0){let c=a;t&&e.simplifyTarget&&r.id&&(c=a.filter(u=>{const f=u.split("=")[0];return At(f)>=60||f==="text"||f==="id"||f==="role"})),c.length>0&&(c.sort((u,f)=>u.localeCompare(f)),i+=`[${c.join(",")}]`)}if(r.classes&&r.classes.length>0){const c=N(r.classes),u=!!r.id||a.some(g=>g.startsWith("href=")||g.startsWith("data-testid=")||g.startsWith("text=")||g.startsWith("role="));if(!(t&&e.simplifyTarget&&u)&&c.length>0){const g=c.sort().slice(0,e.maxClasses);i+=g.map(d=>`.${d}`).join("")}}if("nthChild"in n&&n.nthChild){const c=!!r.id||r.attributes&&Object.keys(r.attributes).some(Vt);t&&e.simplifyTarget&&c||(i+=`#${n.nthChild}`)}return i}function Zt(n){if(!n.constraints||n.constraints.length===0)return"";const t=[];for(const e of n.constraints)switch(e.type){case"uniqueness":t.push("unique=true");break;case"position":e.params&&e.params.strategy&&t.push(`pos=${e.params.strategy}`);break;case"text-proximity":if(e.params&&e.params.reference){const s=J(String(e.params.reference));t.push(`text="${s}"`)}break}return t.length===0?"":` {${t.join(",")}}`}function K(n,t){let e=n;const s={},r=e.match(/^([a-z][a-z0-9-]*)/);if(!r)throw new Error(`Invalid node: missing tag name in "${n}"`);const i=r[1];e=e.slice(i.length);const a=[];let o;for(;o=e.match(/^\.([a-zA-Z][a-zA-Z0-9-_]*)/);)a.push(o[1]),e=e.slice(o[0].length);a.length>0&&(s.classes=a);const l=e.match(/^\[([^\]]+)\]/);if(l){const u=l[1],f={},g=Xt(u);for(const d of g){const p=d.match(/^([a-z][a-z0-9-]*)(?:=|~=)"((?:[^"\\]|\\.)*)"/);if(p){const[,b,y]=p;f[b]=xt(y)}}Object.keys(f).length>0&&(f.text&&(s.text={raw:f.text,normalized:f.text},delete f.text),f.id&&(s.id=f.id,delete f.id),f.role&&(s.role=f.role,delete f.role),Object.keys(f).length>0&&(s.attributes=f)),e=e.slice(l[0].length)}let h;const c=e.match(/^#(\d+)/);if(c&&(h=parseInt(c[1],10),e=e.slice(c[0].length)),e.trim())throw new Error(`Invalid node: unexpected content "${e}" in "${n}"`);return t?{tag:i,semantics:s,score:.7,degraded:!1}:{tag:i,semantics:s,score:.7,nthChild:h}}function Yt(n){if(!n.trim())return[];const t=[],e=n.split(",").map(s=>s.trim());for(const s of e){const[r,i]=s.split("=").map(a=>a.trim());switch(r){case"unique":i==="true"&&t.push({type:"uniqueness",params:{mode:"strict"},priority:90});break;case"pos":t.push({type:"position",params:{strategy:i},priority:70});break;case"text":const a=i.replace(/^"(.*)"$/,"$1");t.push({type:"text-proximity",params:{reference:xt(a),maxDistance:5},priority:60});break}}return t}function Xt(n){const t=[];let e="",s=!1;for(let r=0;r<n.length;r++){const i=n[r];i==='"'&&(r===0||n[r-1]!=="\\")?(s=!s,e+=i):i===","&&!s?(e.trim()&&t.push(e.trim()),e=""):e+=i}return e.trim()&&t.push(e.trim()),t}function J(n){return n.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/>/g,"\\>").replace(/:/g,"\\:")}function xt(n){return n.replace(/\\\\/g,"\0").replace(/\\"/g,'"').replace(/\\>/g,">").replace(/\\:/g,":").replace(/\x00/g,"\\")}function Kt(n,t,e){const s=W(n,t);return s?Ct(s,e):null}function Jt(n,t,e){try{const s=Et(n);return St(s,t,e).elements||[]}catch(s){return console.error("Failed to resolve SEQL Selector:",s),[]}}const te=new Set(["script","style","noscript","meta","link","head","title"]);function tt(n){return n.id&&!R(n.id)?3:n.hasAttribute("role")||n.hasAttribute("aria-label")||n.hasAttribute("aria-labelledby")||n.hasAttribute("data-testid")||n.hasAttribute("data-qa")||n.hasAttribute("data-test")?2:1}function Tt(n,t){const e=n.tagName.toLowerCase();return!!(te.has(e)||t&&tt(n)===1&&!["form","main","nav","section","article","footer","header","button","a","input","label","select","textarea"].includes(e))}function wt(n){return[...n].sort((t,e)=>{const s=tt(t);return tt(e)-s})}function ee(n={}){const t=performance.now(),{root:e=typeof document<"u"?document.body:void 0,filter:s="*",limit:r=1/0,onProgress:i,progressInterval:a=100,skipNonSemantic:o=!0,generatorOptions:l={},cache:h,signal:c}=n;if(!e)throw new Error("Root element or document is required");const u=h??j(),f={...l,cache:u};let g;try{e instanceof Document,g=Array.from(e.querySelectorAll(s))}catch{return{results:[],failed:[],stats:{totalElements:0,successful:0,failed:0,skipped:0,totalTimeMs:0,avgTimePerElementMs:0,cacheHitRate:0}}}const d=g.filter(w=>!Tt(w,o)),b=wt(d).slice(0,r),y=[],A=[];let $=0;const C=b.length;let S=0;for(let w=0;w<b.length&&!c?.aborted;w++){const H=b[w],M=u.getEID(H);if(M)y.push({element:H,eid:M,generationTimeMs:0});else{const et=performance.now();try{const O=W(H,f),re=performance.now()-et;O?y.push({element:H,eid:O,generationTimeMs:re}):$++}catch(O){A.push({element:H,error:O instanceof Error?O.message:String(O)})}}i&&w-S>=a&&(i(w+1,C),S=w)}i&&i(C,C);const I=performance.now()-t,E=u.getStats(),k=E.eidHits+E.eidMisses+E.selectorHits+E.selectorMisses,x=E.eidHits+E.selectorHits,D=k>0?x/k:0;return{results:y,failed:A,stats:{totalElements:C,successful:y.length,failed:A.length,skipped:$,totalTimeMs:I,avgTimePerElementMs:y.length>0?I/y.length:0,cacheHitRate:D}}}function se(n,t={}){const e=performance.now(),{limit:s=1/0,onProgress:r,progressInterval:i=100,skipNonSemantic:a=!0,generatorOptions:o={},cache:l,signal:h}=t,c=l??j(),u={...o,cache:c},f=n.filter(x=>!Tt(x,a)),d=wt(f).slice(0,s),p=[],b=[];let y=0;const A=d.length;let $=0;for(let x=0;x<d.length&&!h?.aborted;x++){const D=d[x],w=c.getEID(D);if(w)p.push({element:D,eid:w,generationTimeMs:0});else{const H=performance.now();try{const M=W(D,u),et=performance.now()-H;M?p.push({element:D,eid:M,generationTimeMs:et}):y++}catch(M){b.push({element:D,error:M instanceof Error?M.message:String(M)})}}r&&x-$>=i&&(r(x+1,A),$=x)}r&&r(A,A);const C=performance.now()-e,S=c.getStats(),I=S.eidHits+S.eidMisses+S.selectorHits+S.selectorMisses,E=S.eidHits+S.selectorHits,k=I>0?E/I:0;return{results:p,failed:b,stats:{totalElements:A,successful:p.length,failed:b.length,skipped:y,totalTimeMs:C,avgTimePerElementMs:p.length>0?C/p.length:0,cacheHitRate:k}}}m.AnchorFinder=at,m.ConstraintsEvaluator=pt,m.CssGenerator=Y,m.DEFAULT_GENERATOR_OPTIONS=nt,m.DEFAULT_RESOLVER_OPTIONS=it,m.EIDCache=dt,m.EID_VERSION="1.0",m.FallbackHandler=bt,m.MAX_PATH_DEPTH=10,m.PathBuilder=lt,m.ROLE_ANCHOR_VALUES=G,m.SEMANTIC_ANCHOR_TAGS=B,m.SEMANTIC_ATTRIBUTES=It,m.SEMANTIC_TAGS=st,m.SemanticExtractor=ht,m.SemanticsMatcher=mt,m.SvgFingerprinter=ut,m.calculateConfidence=ft,m.calculateElementScore=qt,m.createEIDCache=gt,m.filterClasses=ot,m.generateEID=W,m.generateEIDBatch=ee,m.generateEIDForElements=se,m.generateSEQL=Kt,m.getClassScore=Ot,m.getGlobalCache=j,m.isEID=Gt,m.isUtilityClass=Z,m.normalizeText=F,m.parseSEQL=Et,m.resetGlobalCache=Ft,m.resolve=St,m.resolveSEQL=Jt,m.stringifySEQL=Ct,m.validateEID=Bt,Object.defineProperty(m,Symbol.toStringTag,{value:"Module"})}));
2
2
  //# sourceMappingURL=seql-js.umd.cjs.map