@whenessel/seql-js 1.1.0 → 1.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +20 -4
- package/dist/seql-js.d.ts +65 -2
- package/dist/seql-js.js +719 -531
- package/dist/seql-js.js.map +1 -1
- package/dist/seql-js.umd.cjs +1 -1
- package/dist/seql-js.umd.cjs.map +1 -1
- package/package.json +26 -6
package/dist/seql-js.umd.cjs
CHANGED
|
@@ -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 U={ANCHOR:.4,PATH:.3,TARGET:.2,UNIQUENESS:.1},I={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"],w={"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"},at={strictMode:!1,enableFallback:!0,maxCandidates:20};function H(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=>H(e))}class it{constructor(t,e){this.maxDepth=t.maxPathDepth??10,this.cache=e}findAnchor(t){if(this.cache){const i=this.cache.getAnchor(t);if(i!==void 0)return i}let e=t.parentElement,s=0,r=null;for(;e&&s<this.maxDepth;){if(e.tagName.toLowerCase()==="body")return r||{element:e,score:I.DEGRADED_SCORE,tier:"C",depth:s};const i=this.scoreAnchor(e);if(i>0){const o=this.applyDepthPenalty(i,s),l=this.getTier(e),u={element:e,score:o,tier:l,depth:s};if(l==="A")return u;(!r||o>r.score)&&(r=u)}e=e.parentElement,s++}const a=r;return this.cache&&this.cache.setAnchor(t,a),a}scoreAnchor(t){let e=0;const s=t.tagName.toLowerCase();B.includes(s)&&(e+=I.SEMANTIC_TAG);const r=t.getAttribute("role");r&&G.includes(r)&&(e+=I.ROLE),(t.hasAttribute("aria-label")||t.hasAttribute("aria-labelledby"))&&(e+=I.ARIA_LABEL);const a=t.id;return a&&!H(a)&&(e+=I.STABLE_ID),(t.hasAttribute("data-testid")||t.hasAttribute("data-qa")||t.hasAttribute("data-test"))&&(e+=I.TEST_MARKER),Math.min(e,1)}applyDepthPenalty(t,e){if(e<=I.DEPTH_PENALTY_THRESHOLD)return t;const s=(e-I.DEPTH_PENALTY_THRESHOLD)*I.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,}/],Rt=[/^\[/,/^(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)$/,/^-[mp][trblxy]?-\d+$/,/^-(top|right|bottom|left|inset)-\d+$/,/^-z-\d+$/,/^-space-[xy]-\d+$/,/^-translate-[xy]-\d+$/,/^-rotate-\d+$/,/^-scale-\d+$/,/^-skew-[xy]-\d+$/,/^(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)-/,/^object-(contain|cover|fill|none|scale-down)$/,/^(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)$/],Nt=[/^(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 O(n){return Mt.some(t=>t.test(n))}function k(n){return n.length<=2||/^\d/.test(n)?!0:Rt.some(t=>t.test(n))}function Dt(n){return O(n)||k(n)?!1:Nt.some(t=>t.test(n))}function Ht(n){return!O(n)&&!k(n)}function D(n){return n.filter(t=>Ht(t))}function Pt(n){if(O(n)||k(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)k(s)||O(s)?e.push(s):t.push(s);return{semantic:t,utility:e}}function Z(n){return k(n)||O(n)}function _t(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 a=e.parentElement;for(;a&&a!==t&&r.length<this.maxDepth;)r.unshift(a),a=a.parentElement;const i=r.length>=this.maxDepth&&a!==t;let o=this.filterNoise(r);return o=this.ensureUniqueness(r,o,t,e,s),{path:o.map(u=>{const d=u.parentElement;let c;if(d){const g=Array.from(d.children).indexOf(u);g!==-1&&(c=g+1)}return{tag:u.tagName.toLowerCase(),semantics:s.extract(u),score:s.scoreElement(u),nthChild:c}}),degraded:i,degradationReason:i?"path-depth-overflow":void 0}}buildPathNodes(t,e,s){return this.buildPath(t,e,s).path}ensureUniqueness(t,e,s,r,a){const i=this.buildTestSelector(s,e,r);try{const o=r.ownerDocument;if(!o)return e;let l;if(this.cache){const d=this.cache.getSelectorResults(i);d!==void 0?l=d:(l=Array.from(o.querySelectorAll(i)),this.cache.setSelectorResults(i,l))}else l=o.querySelectorAll(i);if(l.length<=1)return e;const u=t.filter(d=>!e.includes(d));for(const d of u){if(a.scoreElement(d)<vt.MIN_CONFIDENCE_FOR_SKIP)continue;const h=this.insertNodeInOrder(e,d,t),g=this.buildTestSelector(s,h,r);try{let f;if(this.cache){const p=this.cache.getSelectorResults(g);p!==void 0?f=p:(f=Array.from(o.querySelectorAll(g)),this.cache.setSelectorResults(g,f))}else f=o.querySelectorAll(g);if(f.length===1)return h;f.length<l.length&&(e=h)}catch{}}return e}catch{return e}}insertNodeInOrder(t,e,s){const r=s.indexOf(e),a=[...t];let i=0;for(let o=0;o<a.length&&!(s.indexOf(a[o])>r);o++)i=o+1;return a.splice(i,0,e),a}buildTestSelector(t,e,s){const r=[];r.push(this.elementToSelector(t));for(const a of e)r.push(this.elementToSelector(a));return r.push(this.elementToSelector(s)),r.join(" ")}elementToSelector(t){let e=t.tagName.toLowerCase();t.id&&!H(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&&!H(e))}}function z(n){return n?n.trim().replace(/[\n\t\r]/g," ").replace(/\s+/g," "):""}const Lt={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 kt(n,t){if(!n)return n;const e=n.startsWith("http://")||n.startsWith("https://");let[s,r]=n.split("#");const[a,i]=s.split("?");let o=a;return e&&t.preserveQueryForAbsolute&&i&&(o+=`?${i}`),r&&(t.removeDynamicHashes&&Ot(r)||(o+=`#${r}`)),o}function P(n,t,e={}){if(!t)return t;const s={...Lt,...e};return n==="href"||n==="src"?kt(t,s):t}const qt=["role","aria-label","aria-labelledby","aria-describedby","aria-controls","aria-owns","aria-level","aria-posinset","aria-setsize","aria-haspopup"],Ut=["aria-selected","aria-checked","aria-pressed","aria-expanded","aria-hidden","aria-disabled","aria-current","aria-busy","aria-invalid","aria-grabbed","aria-live","aria-atomic"],zt=["data-state","data-active","data-inactive","data-selected","data-open","data-closed","data-visible","data-hidden","data-disabled","data-enabled","data-loading","data-error","data-success","data-highlighted","data-focused","data-hover","data-orientation","data-theme"],Ft=["data-radix-","data-headlessui-","data-reach-","data-mui-","data-chakra-","data-mantine-","data-tw-"],jt=["data-testid","data-test-id","data-test","data-cy","data-qa","data-automation-id","data-id","data-component","data-entity-id","data-product-id","data-user-id"],Wt=["id","name","type","placeholder","title","for","alt","href"],Bt=["disabled","checked","selected","hidden","readonly","required","value"],Gt=[/^radix-/,/^headlessui-/,/^mui-/,/:\w+:/];function Vt(n,t){return qt.includes(n)?!0:Ut.includes(n)||zt.includes(n)||Ft.some(e=>n.startsWith(e))?!1:jt.includes(n)||n.startsWith("data-")&&n.endsWith("-id")?!0:n==="id"?!Gt.some(e=>e.test(t)):Wt.includes(n)?!0:Bt.includes(n)?!1:!!n.startsWith("data-")}class ht{constructor(t,e){this.includeUtilityClasses=t.includeUtilityClasses??!1,this.cache=e}extract(t){if(this.cache){const i=this.cache.getSemantics(t);if(i!==void 0)return i}const e={},s=t.id;if(s&&!H(s)&&(e.id=s),t.classList.length>0){const i=Array.from(t.classList);if(this.includeUtilityClasses)e.classes=i;else{const{semantic:o}=ot(i);o.length>0&&(e.classes=o)}}const r=this.extractAttributes(t);Object.keys(r).length>0&&(e.attributes=r);const a=t.getAttribute("role");if(a&&(e.role=a),this.shouldExtractText(t)){const i=this.extractText(t);i&&(e.text=i)}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 w[t]!==void 0?w[t]:t.startsWith("data-")?w["data-*"]:t.startsWith("aria-")?w["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)||!Vt(r,s.value)||V.has(r)&&Q(s.value)||this.getAttributePriority(r)===0)continue;const i=r==="href"||r==="src"?P(r,s.value):s.value;!i||i.trim()===""||this.isDynamicValue(i)||(e[r]=i)}return e}extractText(t){const e=this.getDirectTextContent(t);if(!e)return null;const s=z(e);if(!s)return null;const r=100,a=e.length>r?e.slice(0,r)+"...":e,i=s.length>r?s.slice(0,r)+"...":s;return{raw:a,normalized:i}}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 a=t.getAttribute("role");a&&(r.role=a);const i=t.querySelector("title");return i?.textContent&&(r.titleText=i.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,a=>parseFloat(a).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"),a=parseFloat(t.getAttribute("height")??"0");r>0&&a>0&&s.push(`ratio=${(r/a).toFixed(2)}`)}break;case"ellipse":{const r=parseFloat(t.getAttribute("rx")??"0"),a=parseFloat(t.getAttribute("ry")??"0");r>0&&a>0&&s.push(`ratio=${(r/a).toFixed(2)}`)}break;case"line":{const r=parseFloat(t.getAttribute("x1")??"0"),a=parseFloat(t.getAttribute("y1")??"0"),i=parseFloat(t.getAttribute("x2")??"0"),o=parseFloat(t.getAttribute("y2")??"0"),l=Math.atan2(o-a,i-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 dt(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,a=e*U.ANCHOR+s*U.PATH+r*U.TARGET+t*U.UNIQUENESS,i=n.anchor.degraded?.2:0;return Math.max(0,Math.min(1,a-i))}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 ft{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 ft(n)}let F=null;function j(){return F||(F=gt()),F}function Yt(){F=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 a=new it(e,s),i=new lt(e,s),o=new ht(e,s),l=new ut,u=a.findAnchor(n);if(!u&&!e.fallbackToBody)return null;const d=u?.element??n.ownerDocument?.body??null;if(!d)return null;const c=!u||u.tier==="C",h=d.tagName.toLowerCase(),g=d.parentElement;let f;if(g&&h!=="body"&&h!=="html"){const x=Array.from(g.children).indexOf(d);x!==-1&&(f=x+1)}const p=o.extract(d),b={tag:d.tagName.toLowerCase(),semantics:p,score:u?.score??I.DEGRADED_SCORE,degraded:c,nthChild:f},S=i.buildPath(d,n,o),A=o.extract(n);e.enableSvgFingerprint&&Xt(n)&&(A.svg=l.fingerprint(n));const $=n.parentElement;let C;if($){const x=Array.from($.children).indexOf(n);x!==-1&&(C=x+1)}const y={tag:n.tagName.toLowerCase(),semantics:A,score:o.scoreElement(n),nthChild:C},M=[],R={onMultiple:"best-score",onMissing:"anchor-only",maxDepth:3},_=b.degraded||S.degraded,v=Kt(b.degraded,S),T={version:"1.0",anchor:b,path:S.path,target:y,constraints:M,fallback:R,meta:{confidence:0,generatedAt:new Date().toISOString(),generator:"dom-eid@1.0",source:e.source,degraded:_,degradationReason:v}};return T.meta.confidence=dt(T),T.meta.confidence<e.confidenceThreshold?null:(s.setEID(n,T),T)}function Xt(n){return n.namespaceURI==="http://www.w3.org/2000/svg"||n.tagName.toLowerCase()==="svg"||n instanceof SVGElement}function Kt(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 c=this.buildNodeSelector(t.target.tag,t.target.semantics,{excludeClasses:!1});return e?.ensureUnique?this.ensureUniqueSelector(c,t,e):c}const r=[],a=e?.ensureUnique?this.ensureUniqueAnchor(t,e.root??document):this.buildNodeSelector(t.anchor.tag,t.anchor.semantics);r.push(a);for(const c of t.path){let h=this.buildNodeSelector(c.tag,c.semantics);c.nthChild!==void 0&&(["tr","td","th","thead","tbody","tfoot"].includes(c.tag)?h+=`:nth-child(${c.nthChild})`:h+=`:nth-child(${c.nthChild})`),r.push(h)}let i=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)?i+=`:nth-child(${t.target.nthChild})`:i+=`:nth-child(${t.target.nthChild})`),r.push(i);const o=this.isSvgChildElement(t.target.tag),l=t.path.some(c=>c.tag==="svg");let u;if(o&&l){const c=t.path.findIndex(h=>h.tag==="svg");if(c!==-1){const h=c+1,g=r.slice(0,h+1),f=r.slice(h+1,-1),p=r[r.length-1];f.length>0?u=g.join(" ")+" > "+f.join(" > ")+" > "+p:u=g.join(" ")+" > "+p}else u=r.join(" ")}else u=r.join(" ");if(!e?.ensureUnique)return u;const d=this.querySelectorSafe(u,e.root??document);if(d.length===1)return{selector:u,isUnique:!0,usedNthOfType:u.includes(":nth-"),extraClassesAdded:0};if(d.length===0||d.length>1){const c=this.buildFullDomPathSelector(t,t.target.semantics,e.root??document);if(c&&this.isUnique(c,e.root??document))return{selector:c,isUnique:!0,usedNthOfType:c.includes(":nth-"),extraClassesAdded:0}}return this.ensureUniqueSelector(u,t,e)}buildAnchorSelector(t){return this.buildNodeSelector(t.anchor.tag,t.anchor.semantics)}ensureUniqueSelector(t,e,s){const r=s.root??document,a=s.maxClasses??4,i=e.target.tag,o=e.target.semantics;let l=t,u=0,d=!1;if(this.querySelectorSafe(l,r).length===0){const f=this.buildFullDomPathSelector(e,o,r);if(f&&(l=f,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 h=D(o.classes??[]);for(let f=0;f<Math.min(h.length,a);f++){const p=h[f];if(l+=`.${this.escapeCSS(p)}`,u++,this.isUnique(l,r))return{selector:l,isUnique:!0,usedNthOfType:!1,extraClassesAdded:u}}if(!this.isUnique(l,r)){const f=this.buildFullDomPathSelector(e,o,r);if(f&&this.isUnique(f,r))return{selector:f,isUnique:!0,usedNthOfType:f.includes(":nth-of-type("),extraClassesAdded:u}}const g=this.findNthElementByText(l,o,r);return g&&(l+=this.getNthSelector(g,i),d=!0),{selector:l,isUnique:this.isUnique(l,r),usedNthOfType:d,extraClassesAdded:u}}buildFullDomPathSelector(t,e,s){const r=this.buildNodeSelector(t.anchor.tag,t.anchor.semantics),a=this.querySelectorSafe(r,s);if(a.length===0)return null;for(const i of a){const o=this.findTargetWithinAnchor(i,t.target.tag,e);if(o.length===0)continue;const l=o.map(u=>{const d=this.scorePathMatch(u,i,t.path);return{element:u,score:d}});l.sort((u,d)=>d.score-u.score);for(const{element:u}of l){const d=this.buildPathFromAnchorToTarget(i,u,t,s);if(d&&this.isUnique(d,s))return d}}return null}scorePathMatch(t,e,s){const r=[];let a=t.parentElement;for(;a&&a!==e;)r.unshift(a),a=a.parentElement;let i=0;const o=Math.min(r.length,s.length);for(let u=0;u<o;u++){const d=r[u],c=s[u];if(d.tagName.toLowerCase()===c.tag){if(i+=10,c.nthChild!==void 0){const h=d.parentElement;h&&(Array.from(h.children).indexOf(d)+1===c.nthChild?i+=20:i-=10)}}else i-=5;if(c.semantics.classes&&c.semantics.classes.length>0){const h=c.semantics.classes.filter(g=>d.classList.contains(g));i+=h.length*2}if(c.semantics.attributes){const h=Object.entries(c.semantics.attributes).filter(([g,f])=>d.getAttribute(g)===f);i+=h.length*3}}const l=Math.abs(r.length-s.length);return i-=l*2,i}findTargetWithinAnchor(t,e,s){return Array.from(t.querySelectorAll(e)).filter(a=>{if(s.text){const i=a.textContent?.trim()||"",o=s.text.normalized;if(!i.includes(o)&&!o.includes(i))return!1}return!!(s.classes&&s.classes.length>0&&s.classes.every(o=>a.classList.contains(o))||s.attributes&&Object.entries(s.attributes).every(([o,l])=>{const u=a.getAttribute(o);return o==="href"||o==="src"?P(o,u||"")===P(o,l):u===l})||s.text)})}disambiguateParent(t,e,s,r,a){if(s?.semantics?.attributes){const o=this.buildNodeSelector(e,s.semantics,{excludeClasses:!0}),l=[...r,e].join(" > "),u=this.querySelectorSafe(l,a),d=[...r,o].join(" > "),c=this.querySelectorSafe(d,a);if(c.length>0&&c.length<u.length)return o}if(s?.semantics?.classes){const o=D(s.semantics.classes);if(o.length>0){const l=`${e}.${this.escapeCSS(o[0])}`,u=[...r,e].join(" > "),d=this.querySelectorSafe(u,a),c=[...r,l].join(" > "),h=this.querySelectorSafe(c,a);if(h.length>0&&h.length<d.length)return l}}const i=t.parentElement;return i&&Array.from(i.children).filter(l=>l.tagName.toLowerCase()===e).length>1?`${e}${this.getNthSelector(t,e)}`:e}buildPathFromAnchorToTarget(t,e,s,r){const a=[];let i=e;for(;i&&i!==t;)a.unshift(i),i=i.parentElement;if(i!==t)return null;const o=[()=>{const l=this.buildNodeSelector(s.anchor.tag,s.anchor.semantics),u=s.target.tag,d=s.target.semantics,c=[];for(const b of s.path)c.push(b.tag);const g=[l,...c,u].filter(Boolean).join(" ");if(this.isUnique(g,r))return g;const f=this.buildNodeSelector(u,d,{excludeClasses:!0}),p=[l,...c.slice(0,-1),f].join(" ");return this.isUnique(p,r)?p:null},()=>{const l=[this.buildNodeSelector(s.anchor.tag,s.anchor.semantics)],u=new Map;let d=0;for(let h=0;h<a.length-1;h++){const g=a[h],f=g.tagName.toLowerCase();d<s.path.length&&s.path[d].tag===f?(u.set(g,s.path[d]),d++):u.set(g,null)}for(let h=0;h<a.length;h++){const g=a[h],f=g.tagName.toLowerCase();if(h<a.length-1){const S=u.get(g)||null,A=this.disambiguateParent(g,f,S,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(f)&&Array.from(b.children).filter(A=>A.tagName.toLowerCase()===f).length>1?l.push(`${p}${this.getNthSelector(g,f)}`):l.push(p)}const c=l.join(" > ");return this.isUnique(c,r)?c:null},()=>{const u=[this.buildNodeSelector(s.anchor.tag,s.anchor.semantics)];for(let h=0;h<a.length-1;h++){const f=a[h].tagName.toLowerCase(),p=s.path[h]||null,b=u.join(" ")+" "+f;if(this.querySelectorSafe(b,r).length>1){if(p?.semantics?.attributes){const C=this.buildNodeSelector(f,p.semantics,{excludeClasses:!0}),y=u.join(" ")+" "+C;if(this.querySelectorSafe(y,r).length===1||this.querySelectorSafe(y+" "+s.target.tag,r).length===1){u.push(C);continue}}if(p?.semantics?.classes){const C=D(p.semantics.classes);if(C.length>0){const y=`${f}.${this.escapeCSS(C[0])}`,M=u.join(" ")+" "+y;if(this.querySelectorSafe(M,r).length===1||this.querySelectorSafe(M+" "+s.target.tag,r).length===1){u.push(y);continue}}}const A=a[h],$=A.parentElement;if($&&Array.from($.children).filter(y=>y.tagName.toLowerCase()===f).length>1){u.push(`${f}${this.getNthSelector(A,f)}`);continue}}u.push(f)}const d=this.buildNodeSelector(s.target.tag,s.target.semantics,{excludeClasses:!0});u.push(d);const c=u.join(" ");return this.isUnique(c,r)?c:null},()=>{const l=this.buildNodeSelector(s.anchor.tag,s.anchor.semantics),u=[];for(const g of s.path)u.push(g.tag);if(D(s.target.semantics.classes??[]).length===0)return null;const c=this.buildNodeSelector(s.target.tag,s.target.semantics,{maxClasses:1}),h=[l,...u.slice(0,-1),c].join(" ");return this.isUnique(h,r)?h:null},()=>{const l=this.buildNodeSelector(s.anchor.tag,s.anchor.semantics),u=[];for(const p of s.path)u.push(p.tag);const d=a[a.length-1],c=d.parentElement;if(!c||Array.from(c.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(d,s.target.tag),f=[l,...u.slice(0,-1),g].join(" ");return this.isUnique(f,r)?f:null}];for(const l of o){const u=l();if(u)return u}return null}buildElementSelector(t){const e=t.tagName.toLowerCase();let s=e;if(t.id&&!H(t.id))return`${e}#${this.escapeCSS(t.id)}`;const r=Array.from(t.classList),a=D(r);a.length>0&&(s+=a.slice(0,2).map(o=>`.${this.escapeCSS(o)}`).join(""));const i=t.getAttribute("role");return i&&(s+=`[role="${this.escapeAttr(i)}"]`),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 a=e.text.normalized;for(const i of r){const o=i.textContent?.trim()||"";if(o===a||o.includes(a)||a.includes(o))return i}}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 a=Array.from(s.children).filter(i=>i.tagName.toLowerCase()===e).indexOf(t);return a!==-1?a+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 i=D(r.classes);if(i.length>0){const o=`${s}.${this.escapeCSS(i[0])}`;if(this.isUnique(o,e))return o}}if(r.attributes){const i=this.getSortedAttributes(r.attributes);for(const{name:o,value:l}of i){const u=o==="href"||o==="src"?P(o,l):l;if(u){const d=`${s}[${o}="${this.escapeAttr(u)}"]`;if(this.isUnique(d,e))return d}}}if(t.anchor.nthChild!==void 0){const i=`${s}:nth-child(${t.anchor.nthChild})`;if(this.isUnique(i,e))return i}const a=Array.from(e.querySelectorAll(s));if(a.length>1){const i=this.findElementBySemantics(a,r);if(i){const o=this.getNthOfTypeIndex(i,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(i=>r.classList.contains(i))||e.attributes&&Object.entries(e.attributes).every(([i,o])=>r.getAttribute(i)===o))return!0;if(e.text){const a=r.textContent?.trim()||"",i=e.text.normalized;if(a.includes(i)||i.includes(a))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),a=r.indexOf(t)+1;return["tr","td","th","thead","tbody","tfoot"].includes(e)?`:nth-child(${a})`:`:nth-of-type(${r.filter(l=>l.tagName.toLowerCase()===e).indexOf(t)+1})`}getAttributePriority(t){return w[t]!==void 0?w[t]:t.startsWith("data-")?w["data-*"]:t.startsWith("aria-")?w["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 a=this.getSortedAttributes(e.attributes);for(const{name:i,value:o}of a){const l=i==="href"||i==="src"?P(i,o):o;l&&(r+=`[${i}="${this.escapeAttr(l)}"]`)}}if(e.role&&!e.attributes?.role&&(r+=`[role="${this.escapeAttr(e.role)}"]`),!s?.excludeClasses&&e.classes&&e.classes.length>0){const a=D(e.classes),i=s?.maxClasses!==void 0?a.slice(0,s.maxClasses):a;r+=i.map(o=>`.${this.escapeCSS(o)}`).join("")}return r}escapeCSS(t){let e=t;return e.startsWith("-")&&(e="\\-"+e.slice(1)),e=e.replace(/([!"#$%&'()*+,./:;<=>?@[\\\]^`{|}~])/g,"\\$1"),e}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 a=Array.from(t.childNodes).filter(o=>o.nodeType===Node.TEXT_NODE).map(o=>o.textContent?.trim()??"").join(" ")||(t.textContent?.trim()??"");if(!a)return!1;const i=z(a);return e.matchMode==="partial"?i.includes(e.normalized):i===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(a=>a.trim().replace(/(-?\d+\.?\d*)/g,i=>parseFloat(i).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"),a=parseFloat(t.getAttribute("height")??"0");r>0&&a>0&&s.push(`ratio=${(r/a).toFixed(2)}`);break}case"ellipse":{const r=parseFloat(t.getAttribute("rx")??"0"),a=parseFloat(t.getAttribute("ry")??"0");r>0&&a>0&&s.push(`ratio=${(r/a).toFixed(2)}`);break}case"line":{const r=parseFloat(t.getAttribute("x1")??"0"),a=parseFloat(t.getAttribute("y1")??"0"),i=parseFloat(t.getAttribute("x2")??"0"),o=parseFloat(t.getAttribute("y2")??"0"),l=Math.atan2(o-a,i-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,a)=>a);for(let r=1;r<=t.length;r++){let a=r;for(let i=1;i<=e.length;i++){const o=t[r-1]===e[i-1]?s[i-1]:Math.min(s[i-1],a,s[i])+1;s[i-1]=a,a=o}s[e.length]=a}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 a=r.querySelector(s);if(a)return{status:"degraded-fallback",elements:[a],warnings:["Target not found, returning anchor"],confidence:t.meta.confidence*.3,meta:{degraded:!0,degradationReason:"anchor-fallback"}}}catch(a){const i=a instanceof Error?a.message:"Unknown selector error";return{status:"error",elements:[],warnings:[`Invalid anchor selector: ${i}`],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],a=-1;for(const i of t){const o=this.scoreElementMatch(i,s);o>a&&(a=o,r=i)}return{status:"success",elements:[r],warnings:[`Multiple matches (${t.length}), selected best-scoring element`],confidence:e.meta.confidence*(.7+a*.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 a=Array.from(t.classList),i=e.classes.filter(o=>a.includes(o)).length;s+=i/e.classes.length*.25}if(e.attributes){const a=Object.entries(e.attributes);if(a.length>0){r+=.2;let i=0;for(const[o,l]of a)t.getAttribute(o)===l&&i++;s+=i/a.length*.2}}if(e.role&&(r+=.15,t.getAttribute("role")===e.role&&(s+=.15)),e.text){r+=.1;const a=z(t.textContent);a===e.text.normalized?s+=.1:a.includes(e.text.normalized)&&(s+=.05)}return r>0?s/r:0}}function St(n,t,e={}){const s={...at,...e},r=new Y,a=new mt,i=new pt,o=new bt,l=t instanceof Document?t:t.ownerDocument??t,u=r.buildSelector(n,{ensureUnique:!1,root:l});let d;try{d=Array.from(l.querySelectorAll(u))}catch(f){const p=f instanceof Error?f.message:"Unknown selector error";return{status:"error",elements:[],warnings:[`Invalid CSS selector: ${u}`,`Error: ${p}`],confidence:0,meta:{degraded:!0,degradationReason:"invalid-selector"}}}d.length>s.maxCandidates&&(d=d.slice(0,s.maxCandidates));const c=a.match(d,n.target.semantics);if(c.length===1)return{status:"success",elements:c,warnings:[],confidence:n.meta.confidence,meta:{degraded:!1}};if(c.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 h=c;const g=Jt(n.constraints);for(const f of g){if(h=i.applyConstraint(h,f),h.length===1)return{status:"success",elements:h,warnings:[],confidence:n.meta.confidence*.9,meta:{degraded:!1}};if(h.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:h,warnings:[`Non-unique resolution: ${h.length} matches`],confidence:n.meta.confidence*.7,meta:{degraded:!0,degradationReason:"ambiguous"}}:o.handleAmbiguous(h,n)}function Jt(n){return[...n].sort((t,e)=>e.priority-t.priority)}function te(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 ee(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:w[n]!==void 0?w[n]:n.startsWith("data-")?w["data-*"]:n.startsWith("aria-")?w["aria-*"]:0}function se(n){return["id","data-testid","data-qa","data-cy","href","text","role"].includes(n)}function re(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),a=n.path.length>0?n.path.map(l=>X(l,!1,e)).join(" > ")+" > ":"",i=X(n.target,!0,e),o=e.includeConstraints?ne(n):"";return`${s}: ${r} :: ${a}${i}${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 a=r[1].trim();s=s.slice(r[0].length);const i=s.match(/\s*\{([^}]+)\}\s*$/);let o="";i&&(o=i[1],s=s.slice(0,i.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 u=l[l.length-1],d=l.slice(0,-1),c=K(a,!0),h=d.map(b=>K(b,!1)),g=K(u,!1),f=ae(o);return{version:"1.0",anchor:c,path:h,target:g,constraints:f,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 a=s;const i=[],o={...r.attributes};r.id&&(o.id=r.id),r.role&&!o.role&&(o.role=r.role);const l=Object.entries(o).map(([c,h])=>{const g=At(c),f=c==="href"||c==="src"?P(c,h):h;return{name:c,value:f,priority:g}}).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,h)=>h.priority-c.priority);const u=l.slice(0,e.maxAttributes);u.sort((c,h)=>c.name.localeCompare(h.name));for(const{name:c,value:h}of u)i.push(`${c}="${J(h)}"`);if(e.includeText&&r.text&&!re(r.text.normalized)){const c=r.text.normalized;c.length>0&&c.length<=e.maxTextLength&&i.push(`text="${J(c)}"`)}let d=i;if(i.length>0&&(t&&e.simplifyTarget&&r.id&&(d=i.filter(c=>{const h=c.split("=")[0];return At(h)>=60||h==="text"||h==="id"||h==="role"})),d.length>0&&d.sort((c,h)=>c.localeCompare(h))),r.classes&&r.classes.length>0){const c=D(r.classes),h=!!r.id||i.some(f=>f.startsWith("href=")||f.startsWith("data-testid=")||f.startsWith("text=")||f.startsWith("role="));if(!(t&&e.simplifyTarget&&h)&&c.length>0){const f=c.sort().slice(0,e.maxClasses);a+=f.map(p=>`.${p}`).join("")}}if(d.length>0&&(a+=`[${d.join(",")}]`),"nthChild"in n&&n.nthChild){const c=!!r.id||r.attributes&&Object.keys(r.attributes).some(se);t&&e.simplifyTarget&&c||(a+=`#${n.nthChild}`)}return a}function ne(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 a=r[1];e=e.slice(a.length);const i=[];let o;for(;o=e.match(/^\.([a-zA-Z][a-zA-Z0-9-_]*)/);)i.push(o[1]),e=e.slice(o[0].length);i.length>0&&(s.classes=i);const l=e.match(/^\[([^\]]+)\]/);if(l){const c=l[1],h={},g=ie(c);for(const f of g){const p=f.match(/^([a-z][a-z0-9-]*)(?:=|~=)"((?:[^"\\]|\\.)*)"/);if(p){const[,b,S]=p;h[b]=Tt(S)}}Object.keys(h).length>0&&(h.text&&(s.text={raw:h.text,normalized:h.text},delete h.text),h.id&&(s.id=h.id,delete h.id),h.role&&(s.role=h.role,delete h.role),Object.keys(h).length>0&&(s.attributes=h)),e=e.slice(l[0].length)}let u;const d=e.match(/^#(\d+)/);if(d&&(u=parseInt(d[1],10),e=e.slice(d[0].length)),e.trim())throw new Error(`Invalid node: unexpected content "${e}" in "${n}"`);return t?{tag:a,semantics:s,score:.7,degraded:!1}:{tag:a,semantics:s,score:.7,nthChild:u}}function ae(n){if(!n.trim())return[];const t=[],e=n.split(",").map(s=>s.trim());for(const s of e){const[r,a]=s.split("=").map(i=>i.trim());switch(r){case"unique":a==="true"&&t.push({type:"uniqueness",params:{mode:"strict"},priority:90});break;case"pos":t.push({type:"position",params:{strategy:a},priority:70});break;case"text":const i=a.replace(/^"(.*)"$/,"$1");t.push({type:"text-proximity",params:{reference:Tt(i),maxDistance:5},priority:60});break}}return t}function ie(n){const t=[];let e="",s=!1;for(let r=0;r<n.length;r++){const a=n[r];a==='"'&&(r===0||n[r-1]!=="\\")?(s=!s,e+=a):a===","&&!s?(e.trim()&&t.push(e.trim()),e=""):e+=a}return e.trim()&&t.push(e.trim()),t}function J(n){return n.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/>/g,"\\>").replace(/:/g,"\\:")}function Tt(n){return n.replace(/\\\\/g,"\0").replace(/\\"/g,'"').replace(/\\>/g,">").replace(/\\:/g,":").replace(/\x00/g,"\\")}function oe(n,t,e){const s=W(n,t);return s?Ct(s,e):null}function ce(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 le=new Set(["script","style","noscript","meta","link","head","title"]);function tt(n){return n.id&&!H(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 xt(n,t){const e=n.tagName.toLowerCase();return!!(le.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 he(n={}){const t=performance.now(),{root:e=typeof document<"u"?document.body:void 0,filter:s="*",limit:r=1/0,onProgress:a,progressInterval:i=100,skipNonSemantic:o=!0,generatorOptions:l={},cache:u,signal:d}=n;if(!e)throw new Error("Root element or document is required");const c=u??j(),h={...l,cache:c};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 f=g.filter(E=>!xt(E,o)),b=wt(f).slice(0,r),S=[],A=[];let $=0;const C=b.length;let y=0;for(let E=0;E<b.length&&!d?.aborted;E++){const x=b[E],N=c.getEID(x);if(N)S.push({element:x,eid:N,generationTimeMs:0});else{const et=performance.now();try{const L=W(x,h),de=performance.now()-et;L?S.push({element:x,eid:L,generationTimeMs:de}):$++}catch(L){A.push({element:x,error:L instanceof Error?L.message:String(L)})}}a&&E-y>=i&&(a(E+1,C),y=E)}a&&a(C,C);const M=performance.now()-t,R=c.getStats(),_=R.eidHits+R.eidMisses+R.selectorHits+R.selectorMisses,v=R.eidHits+R.selectorHits,T=_>0?v/_:0;return{results:S,failed:A,stats:{totalElements:C,successful:S.length,failed:A.length,skipped:$,totalTimeMs:M,avgTimePerElementMs:S.length>0?M/S.length:0,cacheHitRate:T}}}function ue(n,t={}){const e=performance.now(),{limit:s=1/0,onProgress:r,progressInterval:a=100,skipNonSemantic:i=!0,generatorOptions:o={},cache:l,signal:u}=t,d=l??j(),c={...o,cache:d},h=n.filter(v=>!xt(v,i)),f=wt(h).slice(0,s),p=[],b=[];let S=0;const A=f.length;let $=0;for(let v=0;v<f.length&&!u?.aborted;v++){const T=f[v],E=d.getEID(T);if(E)p.push({element:T,eid:E,generationTimeMs:0});else{const x=performance.now();try{const N=W(T,c),et=performance.now()-x;N?p.push({element:T,eid:N,generationTimeMs:et}):S++}catch(N){b.push({element:T,error:N instanceof Error?N.message:String(N)})}}r&&v-$>=a&&(r(v+1,A),$=v)}r&&r(A,A);const C=performance.now()-e,y=d.getStats(),M=y.eidHits+y.eidMisses+y.selectorHits+y.selectorMisses,R=y.eidHits+y.selectorHits,_=M>0?R/M:0;return{results:p,failed:b,stats:{totalElements:A,successful:p.length,failed:b.length,skipped:S,totalTimeMs:C,avgTimePerElementMs:p.length>0?C/p.length:0,cacheHitRate:_}}}m.AnchorFinder=it,m.ConstraintsEvaluator=pt,m.CssGenerator=Y,m.DEFAULT_GENERATOR_OPTIONS=nt,m.DEFAULT_RESOLVER_OPTIONS=at,m.EIDCache=ft,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=dt,m.calculateElementScore=Qt,m.createEIDCache=gt,m.filterClasses=ot,m.generateEID=W,m.generateEIDBatch=he,m.generateEIDForElements=ue,m.generateSEQL=oe,m.getClassScore=_t,m.getGlobalCache=j,m.isEID=ee,m.isUtilityClass=Z,m.normalizeText=z,m.parseSEQL=Et,m.resetGlobalCache=Yt,m.resolve=St,m.resolveSEQL=ce,m.stringifySEQL=Ct,m.validateEID=te,Object.defineProperty(m,Symbol.toStringTag,{value:"Module"})}));
|
|
1
|
+
(function(p,k){typeof exports=="object"&&typeof module<"u"?k(exports):typeof define=="function"&&define.amd?define(["exports"],k):(p=typeof globalThis<"u"?globalThis:p||self,k(p.SeqlJS={}))})(this,(function(p){"use strict";const U={ANCHOR:.4,PATH:.3,TARGET:.2,UNIQUENESS:.1},$={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"],nt=["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"],It=["rect","path","circle","line","polyline","polygon","ellipse","g","text","use","defs","clipPath","mask"],$t=["aria-label","aria-labelledby","aria-describedby","name","type","data-testid","data-qa","data-test","href","title","placeholder","alt"],x={"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},V=new Set(["id","class","style","xmlns","tabindex","contenteditable"]),at={maxPathDepth:10,enableSvgFingerprint:!0,confidenceThreshold:.1,fallbackToBody:!0,includeUtilityClasses:!1,source:"dom-dsl"},it={strictMode:!1,enableFallback:!0,maxCandidates:20};function H(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 Q=new Set(["aria-labelledby","aria-describedby","aria-controls","aria-owns","aria-activedescendant","for","form","list","headers","aria-details","aria-errormessage","aria-flowto"]);function Z(n){return n.trim().split(/\s+/).some(e=>H(e))}class ot{constructor(t,e){this.maxDepth=t.maxPathDepth??10,this.cache=e}findAnchor(t){if(this.cache){const c=this.cache.getAnchor(t);if(c!==void 0)return c}const e=t.tagName.toLowerCase(),s=t.ownerDocument;if(e==="html"){const c={element:t,score:1,tier:"A",depth:0};return this.cacheResult(t,c),c}if(e==="head"||this.isInsideHead(t)){const c=s?.documentElement;if(c){const u={element:c,score:1,tier:"A",depth:0};return this.cacheResult(t,u),u}}if(e==="body"){const c=s?.documentElement;if(c){const u={element:c,score:1,tier:"A",depth:0};return this.cacheResult(t,u),u}}let r=t.parentElement,a=0,i=null;for(;r&&a<this.maxDepth;){if(r.tagName.toLowerCase()==="body")return i||{element:r,score:$.DEGRADED_SCORE,tier:"C",depth:a};const c=this.scoreAnchor(r);if(c>0){const u=this.applyDepthPenalty(c,a),d=this.getTier(r),l={element:r,score:u,tier:d,depth:a};if(d==="A")return l;(!i||u>i.score)&&(i=l)}r=r.parentElement,a++}const o=i;return this.cache&&this.cache.setAnchor(t,o),o}scoreAnchor(t){let e=0;const s=t.tagName.toLowerCase();B.includes(s)&&(e+=$.SEMANTIC_TAG);const r=t.getAttribute("role");r&&G.includes(r)&&(e+=$.ROLE),(t.hasAttribute("aria-label")||t.hasAttribute("aria-labelledby"))&&(e+=$.ARIA_LABEL);const a=t.id;return a&&!H(a)&&(e+=$.STABLE_ID),(t.hasAttribute("data-testid")||t.hasAttribute("data-qa")||t.hasAttribute("data-test"))&&(e+=$.TEST_MARKER),Math.min(e,1)}applyDepthPenalty(t,e){if(e<=$.DEPTH_PENALTY_THRESHOLD)return t;const s=(e-$.DEPTH_PENALTY_THRESHOLD)*$.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"}isInsideHead(t){let e=t.parentElement;for(;e;){const s=e.tagName.toLowerCase();if(s==="head")return!0;if(s==="body")return!1;e=e.parentElement}return!1}cacheResult(t,e){this.cache&&this.cache.setAnchor(t,e)}}const Nt=[/^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,}/],Rt=[/^\[/,/^(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)$/,/^-[mp][trblxy]?-\d+$/,/^-(top|right|bottom|left|inset)-\d+$/,/^-z-\d+$/,/^-space-[xy]-\d+$/,/^-translate-[xy]-\d+$/,/^-rotate-\d+$/,/^-scale-\d+$/,/^-skew-[xy]-\d+$/,/^(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)-/,/^object-(contain|cover|fill|none|scale-down)$/,/^(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)$/],Mt=[/^(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 O(n){return Nt.some(t=>t.test(n))}function q(n){return n.length<=2||/^\d/.test(n)?!0:Rt.some(t=>t.test(n))}function Dt(n){return O(n)||q(n)?!1:Mt.some(t=>t.test(n))}function Ht(n){return!O(n)&&!q(n)}function D(n){return n.filter(t=>Ht(t))}function Pt(n){if(O(n)||q(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 ct(n){const t=[],e=[];for(const s of n)q(s)||O(s)?e.push(s):t.push(s);return{semantic:t,utility:e}}function Y(n){return q(n)||O(n)}function _t(n){return Pt(n)}const lt=n=>n.replace(/([#:.[\]@])/g,"\\$1");class ht{constructor(t,e){this.maxDepth=t.maxPathDepth??10,this.cache=e}buildPath(t,e,s){const r=t.tagName.toLowerCase(),a=e.tagName.toLowerCase();if(r==="html"&&(a==="head"||a==="body"))return{path:[],degraded:!1};if(r==="html"&&this.isInsideHead(e))return this.buildHeadPath(t,e,s);const i=[];let o=e.parentElement;for(;o&&o!==t&&i.length<this.maxDepth;)i.unshift(o),o=o.parentElement;const c=i.length>=this.maxDepth&&o!==t;if(!c&&o!==t)return console.warn("[PathBuilder] Target is not a descendant of anchor"),{path:[],degraded:!0,degradationReason:"target-not-descendant-of-anchor"};let u=this.filterNoise(i);return u=this.ensureUniqueness(i,u,t,e,s),{path:u.map(l=>{const h=l.parentElement;let g;if(h){const m=Array.from(h.children).indexOf(l);m!==-1&&(g=m+1)}return{tag:l.tagName.toLowerCase(),semantics:s.extract(l),score:s.scoreElement(l),nthChild:g}}),degraded:c,degradationReason:c?"path-depth-overflow":void 0}}buildPathNodes(t,e,s){return this.buildPath(t,e,s).path}ensureUniqueness(t,e,s,r,a){const i=this.buildTestSelector(s,e,r);try{const o=r.ownerDocument;if(!o)return e;let c;if(this.cache){const d=this.cache.getSelectorResults(i);d!==void 0?c=d:(c=Array.from(o.querySelectorAll(i)),this.cache.setSelectorResults(i,c))}else c=o.querySelectorAll(i);if(c.length<=1)return e;const u=t.filter(d=>!e.includes(d));for(const d of u){if(a.scoreElement(d)<vt.MIN_CONFIDENCE_FOR_SKIP)continue;const h=this.insertNodeInOrder(e,d,t),g=this.buildTestSelector(s,h,r);try{let f;if(this.cache){const m=this.cache.getSelectorResults(g);m!==void 0?f=m:(f=Array.from(o.querySelectorAll(g)),this.cache.setSelectorResults(g,f))}else f=o.querySelectorAll(g);if(f.length===1)return h;f.length<c.length&&(e=h)}catch{}}return e}catch{return e}}insertNodeInOrder(t,e,s){const r=s.indexOf(e),a=[...t];let i=0;for(let o=0;o<a.length&&!(s.indexOf(a[o])>r);o++)i=o+1;return a.splice(i,0,e),a}buildTestSelector(t,e,s){const r=[];r.push(this.elementToSelector(t));for(const a of e)r.push(this.elementToSelector(a));return r.push(this.elementToSelector(s)),r.join(" ")}elementToSelector(t){let e=t.tagName.toLowerCase();t.id&&!H(t.id)&&(e+=`#${lt(t.id)}`);for(const s of Array.from(t.classList))Y(s)||(e+=`.${lt(s)}`);return e}filterNoise(t){return t.filter(e=>this.shouldInclude(e))}shouldInclude(t){const e=t.tagName.toLowerCase();return nt.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(!Y(s))return!0}if(t.hasAttribute("data-testid")||t.hasAttribute("data-qa")||t.hasAttribute("data-test"))return!0;const e=t.id;return!!(e&&!H(e))}isInsideHead(t){let e=t.parentElement;for(;e;){const s=e.tagName.toLowerCase();if(s==="head")return!0;if(s==="body")return!1;e=e.parentElement}return!1}buildHeadPath(t,e,s){const r=[];let a=e.parentElement;for(;a&&a!==t;)r.unshift(a),a=a.parentElement;return a!==t?{path:[],degraded:!0,degradationReason:"target-not-descendant-of-html"}:r.findIndex(c=>c.tagName.toLowerCase()==="head")===-1?{path:[],degraded:!0,degradationReason:"head-not-found-in-path"}:{path:r.map(c=>{const u=c.parentElement;let d;if(u){const h=Array.from(u.children).indexOf(c);h!==-1&&(d=h+1)}return{tag:c.tagName.toLowerCase(),semantics:s.extract(c),score:s.scoreElement(c),nthChild:d}}),degraded:!1}}}function z(n){return n?n.trim().replace(/[\n\t\r]/g," ").replace(/\s+/g," "):""}const Lt={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 qt(n,t){if(!n)return n;const e=n.startsWith("http://")||n.startsWith("https://"),[s,r]=n.split("#"),[a,i]=s.split("?");let o=a;return e&&t.preserveQueryForAbsolute&&i&&(o+=`?${i}`),r&&(t.removeDynamicHashes&&Ot(r)||(o+=`#${r}`)),o}function P(n,t,e={}){if(!t)return t;const s={...Lt,...e};return n==="href"||n==="src"?qt(t,s):t}const kt=["role","aria-label","aria-labelledby","aria-describedby","aria-controls","aria-owns","aria-level","aria-posinset","aria-setsize","aria-haspopup"],Ut=["aria-selected","aria-checked","aria-pressed","aria-expanded","aria-hidden","aria-disabled","aria-current","aria-busy","aria-invalid","aria-grabbed","aria-live","aria-atomic"],zt=["data-state","data-active","data-inactive","data-selected","data-open","data-closed","data-visible","data-hidden","data-disabled","data-enabled","data-loading","data-error","data-success","data-highlighted","data-focused","data-hover","data-orientation","data-theme"],Ft=["data-radix-","data-headlessui-","data-reach-","data-mui-","data-chakra-","data-mantine-","data-tw-"],jt=["data-testid","data-test-id","data-test","data-cy","data-qa","data-automation-id","data-id","data-component","data-entity-id","data-product-id","data-user-id"],Wt=["id","name","type","placeholder","title","for","alt","href"],Bt=["disabled","checked","selected","hidden","readonly","required","value"],Gt=[/^radix-/,/^headlessui-/,/^mui-/,/:\w+:/];function Vt(n,t){return kt.includes(n)?!0:Ut.includes(n)||zt.includes(n)||Ft.some(e=>n.startsWith(e))?!1:jt.includes(n)||n.startsWith("data-")&&n.endsWith("-id")?!0:n==="id"?!Gt.some(e=>e.test(t)):Wt.includes(n)?!0:Bt.includes(n)?!1:!!n.startsWith("data-")}class X{constructor(t,e){this.includeUtilityClasses=t.includeUtilityClasses??!1,this.cache=e}extract(t){if(this.cache){const i=this.cache.getSemantics(t);if(i!==void 0)return i}const e={},s=t.id;if(s&&!H(s)&&(e.id=s),t.classList.length>0){const i=Array.from(t.classList);if(this.includeUtilityClasses)e.classes=i;else{const{semantic:o}=ct(i);o.length>0&&(e.classes=o)}}const r=this.extractAttributes(t);Object.keys(r).length>0&&(e.attributes=r);const a=t.getAttribute("role");if(a&&(e.role=a),this.shouldExtractText(t)){const i=this.extractText(t);i&&(e.text=i)}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!!(V.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 x[t]!==void 0?x[t]:t.startsWith("data-")?x["data-*"]:t.startsWith("aria-")?x["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)||!Vt(r,s.value)||Q.has(r)&&Z(s.value)||this.getAttributePriority(r)===0)continue;const i=r==="href"||r==="src"?P(r,s.value):s.value;!i||i.trim()===""||this.isDynamicValue(i)||(e[r]=i)}return e}extractText(t){const e=this.getDirectTextContent(t);if(!e)return null;const s=z(e);if(!s)return null;const r=100,a=e.length>r?e.slice(0,r)+"...":e,i=s.length>r?s.slice(0,r)+"...":s;return{raw:a,normalized:i}}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 a=t.getAttribute("role");a&&(r.role=a);const i=t.querySelector("title");return i?.textContent&&(r.titleText=i.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,a=>parseFloat(a).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"),a=parseFloat(t.getAttribute("height")??"0");r>0&&a>0&&s.push(`ratio=${(r/a).toFixed(2)}`)}break;case"ellipse":{const r=parseFloat(t.getAttribute("rx")??"0"),a=parseFloat(t.getAttribute("ry")??"0");r>0&&a>0&&s.push(`ratio=${(r/a).toFixed(2)}`)}break;case"line":{const r=parseFloat(t.getAttribute("x1")??"0"),a=parseFloat(t.getAttribute("y1")??"0"),i=parseFloat(t.getAttribute("x2")??"0"),o=parseFloat(t.getAttribute("y2")??"0"),c=Math.atan2(o-a,i-r);s.push(`angle=${c.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 dt(n,t=0){const e=n.anchor.score,s=n.path.length>0?n.path.reduce((o,c)=>o+c.score,0)/n.path.length:.5,r=n.target.score,a=e*U.ANCHOR+s*U.PATH+r*U.TARGET+t*U.UNIQUENESS,i=n.anchor.degraded?.2:0;return Math.max(0,Math.min(1,a-i))}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){const e=this.cache.get(t);if(e!==void 0)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 ft{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 ft(n)}let F=null;function j(){return F||(F=gt()),F}function Yt(){F=null}function W(n,t={}){if(!n||!n.ownerDocument||!n.isConnected)return null;const e={...at,...t},s=e.cache??j(),r=s.getEID(n);if(r!==void 0)return r;if(n.tagName.toLowerCase()==="html"){const I=new X(e,s),C=Jt(n,e,I);return s.setEID(n,C),C}const i=new ot(e,s),o=new ht(e,s),c=new X(e,s),u=new ut,d=i.findAnchor(n);if(!d&&!e.fallbackToBody)return null;const l=d?.element??n.ownerDocument?.body??null;if(!l)return null;const h=!d||d.tier==="C",g=l.tagName.toLowerCase(),f=l.parentElement;let m;if(f&&g!=="body"&&g!=="html"){const C=Array.from(f.children).indexOf(l);C!==-1&&(m=C+1)}const b=c.extract(l),y={tag:l.tagName.toLowerCase(),semantics:b,score:d?.score??$.DEGRADED_SCORE,degraded:h,nthChild:m},A=o.buildPath(l,n,c),v=c.extract(n);e.enableSvgFingerprint&&Xt(n)&&(v.svg=u.fingerprint(n));const E=n.parentElement;let S;if(E){const C=Array.from(E.children).indexOf(n);C!==-1&&(S=C+1)}const N={tag:n.tagName.toLowerCase(),semantics:v,score:c.scoreElement(n),nthChild:S},R=[],_={onMultiple:"best-score",onMissing:"anchor-only",maxDepth:3},w=y.degraded||A.degraded,M=Kt(y.degraded,A),T={version:"1.0",anchor:y,path:A.path,target:N,constraints:R,fallback:_,meta:{confidence:0,generatedAt:new Date().toISOString(),generator:"dom-eid@1.0",source:e.source,degraded:w,degradationReason:M}};return T.meta.confidence=dt(T),T.meta.confidence<e.confidenceThreshold?null:(s.setEID(n,T),T)}function Xt(n){return n.namespaceURI==="http://www.w3.org/2000/svg"||n.tagName.toLowerCase()==="svg"||n instanceof SVGElement}function Kt(n,t){if(n&&t.degraded)return"anchor-and-path-degraded";if(n)return"no-semantic-anchor";if(t.degraded)return t.degradationReason}function Jt(n,t,e,s){const a={tag:"html",semantics:e.extract(n),score:1,degraded:!1,nthChild:void 0};return{version:"1.0",anchor:a,path:[],target:a,constraints:[],fallback:{onMultiple:"best-score",onMissing:"anchor-only",maxDepth:3},meta:{confidence:1,generatedAt:new Date().toISOString(),generator:"dom-eid@1.0",source:t.source,degraded:!1,degradationReason:void 0}}}class K{buildSelector(t,e){if(t.target.tag==="html"){const l="html";return e?.ensureUnique?{selector:l,isUnique:!0,usedNthOfType:!1,extraClassesAdded:0}:l}if(t.anchor.tag==="html"&&t.path.length===0){const h=`html > ${this.buildNodeSelector(t.target.tag,t.target.semantics)}`;return e?.ensureUnique?{selector:h,isUnique:this.isUnique(h,e.root??document),usedNthOfType:!1,extraClassesAdded:0}:h}if(t.anchor.tag==="html"&&t.path.length>0&&t.path[0].tag==="head")return this.buildHeadSelector(t,e);if(t.path.length===0&&t.anchor.tag===t.target.tag&&JSON.stringify(t.anchor.semantics)===JSON.stringify(t.target.semantics)){const l=this.buildNodeSelector(t.target.tag,t.target.semantics,{excludeClasses:!1});return e?.ensureUnique?this.ensureUniqueSelector(l,t,e):l}const r=[],a=e?.ensureUnique?this.ensureUniqueAnchor(t,e.root??document):this.buildNodeSelector(t.anchor.tag,t.anchor.semantics);r.push(a);for(const l of t.path){let h=this.buildNodeSelector(l.tag,l.semantics);l.nthChild!==void 0&&(["tr","td","th","thead","tbody","tfoot"].includes(l.tag)?h+=`:nth-child(${l.nthChild})`:h+=`:nth-child(${l.nthChild})`),r.push(h)}let i=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)?i+=`:nth-child(${t.target.nthChild})`:i+=`:nth-child(${t.target.nthChild})`),r.push(i);const o=this.isSvgChildElement(t.target.tag),c=t.path.some(l=>l.tag==="svg");let u;if(o&&c){const l=t.path.findIndex(h=>h.tag==="svg");if(l!==-1){const h=l+1,g=r.slice(0,h+1),f=r.slice(h+1,-1),m=r[r.length-1];f.length>0?u=g.join(" ")+" > "+f.join(" > ")+" > "+m:u=g.join(" ")+" > "+m}else u=r.join(" ")}else u=r.join(" ");if(!e?.ensureUnique)return u;const d=this.querySelectorSafe(u,e.root??document);if(d.length===1)return{selector:u,isUnique:!0,usedNthOfType:u.includes(":nth-"),extraClassesAdded:0};if(d.length===0||d.length>1){const l=this.buildFullDomPathSelector(t,t.target.semantics,e.root??document);if(l&&this.isUnique(l,e.root??document))return{selector:l,isUnique:!0,usedNthOfType:l.includes(":nth-"),extraClassesAdded:0}}return this.ensureUniqueSelector(u,t,e)}buildAnchorSelector(t){return this.buildNodeSelector(t.anchor.tag,t.anchor.semantics)}ensureUniqueSelector(t,e,s){const r=s.root??document,a=s.maxClasses??4,i=e.target.tag,o=e.target.semantics;let c=t,u=0,d=!1;if(this.querySelectorSafe(c,r).length===0){const f=this.buildFullDomPathSelector(e,o,r);if(f&&(c=f,this.isUnique(c,r)))return{selector:c,isUnique:!0,usedNthOfType:!1,extraClassesAdded:0}}if(this.isUnique(c,r))return{selector:c,isUnique:!0,usedNthOfType:!1,extraClassesAdded:0};const h=D(o.classes??[]);for(let f=0;f<Math.min(h.length,a);f++){const m=h[f];if(c+=`.${this.escapeCSS(m)}`,u++,this.isUnique(c,r))return{selector:c,isUnique:!0,usedNthOfType:!1,extraClassesAdded:u}}if(!this.isUnique(c,r)){const f=this.buildFullDomPathSelector(e,o,r);if(f&&this.isUnique(f,r))return{selector:f,isUnique:!0,usedNthOfType:f.includes(":nth-of-type("),extraClassesAdded:u}}const g=this.findNthElementByText(c,o,r);return g&&(c+=this.getNthSelector(g,i),d=!0),{selector:c,isUnique:this.isUnique(c,r),usedNthOfType:d,extraClassesAdded:u}}buildFullDomPathSelector(t,e,s){const r=this.buildNodeSelector(t.anchor.tag,t.anchor.semantics),a=this.querySelectorSafe(r,s);if(a.length===0)return null;for(const i of a){const o=this.findTargetWithinAnchor(i,t.target.tag,e);if(o.length===0)continue;const c=o.map(u=>{const d=this.scorePathMatch(u,i,t.path);return{element:u,score:d}});c.sort((u,d)=>d.score-u.score);for(const{element:u}of c){const d=this.buildPathFromAnchorToTarget(i,u,t,s);if(d&&this.isUnique(d,s))return d}}return null}scorePathMatch(t,e,s){const r=[];let a=t.parentElement;for(;a&&a!==e;)r.unshift(a),a=a.parentElement;let i=0;const o=Math.min(r.length,s.length);for(let u=0;u<o;u++){const d=r[u],l=s[u];if(d.tagName.toLowerCase()===l.tag){if(i+=10,l.nthChild!==void 0){const h=d.parentElement;h&&(Array.from(h.children).indexOf(d)+1===l.nthChild?i+=20:i-=10)}}else i-=5;if(l.semantics.classes&&l.semantics.classes.length>0){const h=l.semantics.classes.filter(g=>d.classList.contains(g));i+=h.length*2}if(l.semantics.attributes){const h=Object.entries(l.semantics.attributes).filter(([g,f])=>d.getAttribute(g)===f);i+=h.length*3}}const c=Math.abs(r.length-s.length);return i-=c*2,i}findTargetWithinAnchor(t,e,s){return Array.from(t.querySelectorAll(e)).filter(a=>{if(s.text){const i=a.textContent?.trim()||"",o=s.text.normalized;if(!i.includes(o)&&!o.includes(i))return!1}return!!(s.classes&&s.classes.length>0&&s.classes.every(o=>a.classList.contains(o))||s.attributes&&Object.entries(s.attributes).every(([o,c])=>{const u=a.getAttribute(o);return o==="href"||o==="src"?P(o,u||"")===P(o,c):u===c})||s.text)})}disambiguateParent(t,e,s,r,a){if(s?.semantics?.attributes){const o=this.buildNodeSelector(e,s.semantics,{excludeClasses:!0}),c=[...r,e].join(" > "),u=this.querySelectorSafe(c,a),d=[...r,o].join(" > "),l=this.querySelectorSafe(d,a);if(l.length>0&&l.length<u.length)return o}if(s?.semantics?.classes){const o=D(s.semantics.classes);if(o.length>0){const c=`${e}.${this.escapeCSS(o[0])}`,u=[...r,e].join(" > "),d=this.querySelectorSafe(u,a),l=[...r,c].join(" > "),h=this.querySelectorSafe(l,a);if(h.length>0&&h.length<d.length)return c}}const i=t.parentElement;return i&&Array.from(i.children).filter(c=>c.tagName.toLowerCase()===e).length>1?`${e}${this.getNthSelector(t,e)}`:e}buildPathFromAnchorToTarget(t,e,s,r){const a=[];let i=e;for(;i&&i!==t;)a.unshift(i),i=i.parentElement;if(i!==t)return null;const o=[()=>{const c=this.buildNodeSelector(s.anchor.tag,s.anchor.semantics),u=s.target.tag,d=s.target.semantics,l=[];for(const b of s.path)l.push(b.tag);const g=[c,...l,u].filter(Boolean).join(" ");if(this.isUnique(g,r))return g;const f=this.buildNodeSelector(u,d,{excludeClasses:!0}),m=[c,...l.slice(0,-1),f].join(" ");return this.isUnique(m,r)?m:null},()=>{const c=[this.buildNodeSelector(s.anchor.tag,s.anchor.semantics)],u=new Map;let d=0;for(let h=0;h<a.length-1;h++){const g=a[h],f=g.tagName.toLowerCase();d<s.path.length&&s.path[d].tag===f?(u.set(g,s.path[d]),d++):u.set(g,null)}for(let h=0;h<a.length;h++){const g=a[h],f=g.tagName.toLowerCase();if(h<a.length-1){const y=u.get(g)||null,A=this.disambiguateParent(g,f,y,c,r);c.push(A);continue}const m=this.buildNodeSelector(s.target.tag,s.target.semantics,{excludeClasses:!0}),b=g.parentElement;b&&["td","th","tr","thead","tbody","tfoot"].includes(f)&&Array.from(b.children).filter(A=>A.tagName.toLowerCase()===f).length>1?c.push(`${m}${this.getNthSelector(g,f)}`):c.push(m)}const l=c.join(" > ");return this.isUnique(l,r)?l:null},()=>{const u=[this.buildNodeSelector(s.anchor.tag,s.anchor.semantics)];for(let h=0;h<a.length-1;h++){const f=a[h].tagName.toLowerCase(),m=s.path[h]||null,b=u.join(" ")+" "+f;if(this.querySelectorSafe(b,r).length>1){if(m?.semantics?.attributes){const E=this.buildNodeSelector(f,m.semantics,{excludeClasses:!0}),S=u.join(" ")+" "+E;if(this.querySelectorSafe(S,r).length===1||this.querySelectorSafe(S+" "+s.target.tag,r).length===1){u.push(E);continue}}if(m?.semantics?.classes){const E=D(m.semantics.classes);if(E.length>0){const S=`${f}.${this.escapeCSS(E[0])}`,N=u.join(" ")+" "+S;if(this.querySelectorSafe(N,r).length===1||this.querySelectorSafe(N+" "+s.target.tag,r).length===1){u.push(S);continue}}}const A=a[h],v=A.parentElement;if(v&&Array.from(v.children).filter(S=>S.tagName.toLowerCase()===f).length>1){u.push(`${f}${this.getNthSelector(A,f)}`);continue}}u.push(f)}const d=this.buildNodeSelector(s.target.tag,s.target.semantics,{excludeClasses:!0});u.push(d);const l=u.join(" ");return this.isUnique(l,r)?l:null},()=>{const c=this.buildNodeSelector(s.anchor.tag,s.anchor.semantics),u=[];for(const g of s.path)u.push(g.tag);if(D(s.target.semantics.classes??[]).length===0)return null;const l=this.buildNodeSelector(s.target.tag,s.target.semantics,{maxClasses:1}),h=[c,...u.slice(0,-1),l].join(" ");return this.isUnique(h,r)?h:null},()=>{const c=this.buildNodeSelector(s.anchor.tag,s.anchor.semantics),u=[];for(const m of s.path)u.push(m.tag);const d=a[a.length-1],l=d.parentElement;if(!l||Array.from(l.children).filter(m=>m.tagName.toLowerCase()===s.target.tag).length<=1)return null;const g=this.buildNodeSelector(s.target.tag,s.target.semantics,{excludeClasses:!0})+this.getNthSelector(d,s.target.tag),f=[c,...u.slice(0,-1),g].join(" ");return this.isUnique(f,r)?f:null}];for(const c of o){const u=c();if(u)return u}return null}buildElementSelector(t){const e=t.tagName.toLowerCase();let s=e;if(t.id&&!H(t.id))return`${e}#${this.escapeCSS(t.id)}`;const r=Array.from(t.classList),a=D(r);a.length>0&&(s+=a.slice(0,2).map(o=>`.${this.escapeCSS(o)}`).join(""));const i=t.getAttribute("role");return i&&(s+=`[role="${this.escapeAttr(i)}"]`),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 a=e.text.normalized;for(const i of r){const o=i.textContent?.trim()||"";if(o===a||o.includes(a)||a.includes(o))return i}}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 a=Array.from(s.children).filter(i=>i.tagName.toLowerCase()===e).indexOf(t);return a!==-1?a+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 i=D(r.classes);if(i.length>0){const o=`${s}.${this.escapeCSS(i[0])}`;if(this.isUnique(o,e))return o}}if(r.attributes){const i=this.getSortedAttributes(r.attributes);for(const{name:o,value:c}of i){const u=o==="href"||o==="src"?P(o,c):c;if(u){const d=`${s}[${o}="${this.escapeAttr(u)}"]`;if(this.isUnique(d,e))return d}}}if(t.anchor.nthChild!==void 0){const i=`${s}:nth-child(${t.anchor.nthChild})`;if(this.isUnique(i,e))return i}const a=Array.from(e.querySelectorAll(s));if(a.length>1){const i=this.findElementBySemantics(a,r);if(i){const o=this.getNthOfTypeIndex(i,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(i=>r.classList.contains(i))||e.attributes&&Object.entries(e.attributes).every(([i,o])=>r.getAttribute(i)===o))return!0;if(e.text){const a=r.textContent?.trim()||"",i=e.text.normalized;if(a.includes(i)||i.includes(a))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),a=r.indexOf(t)+1;return["tr","td","th","thead","tbody","tfoot"].includes(e)?`:nth-child(${a})`:`:nth-of-type(${r.filter(c=>c.tagName.toLowerCase()===e).indexOf(t)+1})`}getAttributePriority(t){return x[t]!==void 0?x[t]:t.startsWith("data-")?x["data-*"]:t.startsWith("aria-")?x["aria-*"]:0}shouldIgnoreAttribute(t){return!!(V.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])=>!Q.has(e)||!Z(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 a=this.getSortedAttributes(e.attributes);for(const{name:i,value:o}of a){const c=i==="href"||i==="src"?P(i,o):o;c&&(r+=`[${i}="${this.escapeAttr(c)}"]`)}}if(e.role&&!e.attributes?.role&&(r+=`[role="${this.escapeAttr(e.role)}"]`),!s?.excludeClasses&&e.classes&&e.classes.length>0){const a=D(e.classes),i=s?.maxClasses!==void 0?a.slice(0,s.maxClasses):a;r+=i.map(o=>`.${this.escapeCSS(o)}`).join("")}return r}escapeCSS(t){let e=t;return e.startsWith("-")&&(e="\\-"+e.slice(1)),e=e.replace(/([!"#$%&'()*+,./:;<=>?@[\\\]^`{|}~])/g,"\\$1"),e}escapeAttr(t){return t.replace(/"/g,'\\"').replace(/\\/g,"\\\\")}isSvgChildElement(t){return It.includes(t)}buildHeadSelector(t,e){const s=["html"];for(const o of t.path){let c=this.buildNodeSelector(o.tag,o.semantics);o.nthChild!==void 0&&(c+=`:nth-child(${o.nthChild})`),s.push(c)}let r=this.buildNodeSelector(t.target.tag,t.target.semantics);t.target.nthChild!==void 0&&(r+=`:nth-child(${t.target.nthChild})`),s.push(r);const a=s.join(" > ");if(!e?.ensureUnique)return a;const i=this.isUnique(a,e.root??document);return{selector:a,isUnique:i,usedNthOfType:a.includes(":nth-"),extraClassesAdded:0}}}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 a=Array.from(t.childNodes).filter(o=>o.nodeType===Node.TEXT_NODE).map(o=>o.textContent?.trim()??"").join(" ")||(t.textContent?.trim()??"");if(!a)return!1;const i=z(a);return e.matchMode==="partial"?i.includes(e.normalized):i===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(a=>a.trim().replace(/(-?\d+\.?\d*)/g,i=>parseFloat(i).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"),a=parseFloat(t.getAttribute("height")??"0");r>0&&a>0&&s.push(`ratio=${(r/a).toFixed(2)}`);break}case"ellipse":{const r=parseFloat(t.getAttribute("rx")??"0"),a=parseFloat(t.getAttribute("ry")??"0");r>0&&a>0&&s.push(`ratio=${(r/a).toFixed(2)}`);break}case"line":{const r=parseFloat(t.getAttribute("x1")??"0"),a=parseFloat(t.getAttribute("y1")??"0"),i=parseFloat(t.getAttribute("x2")??"0"),o=parseFloat(t.getAttribute("y2")??"0"),c=Math.atan2(o-a,i-r);s.push(`angle=${c.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,a)=>a);for(let r=1;r<=t.length;r++){let a=r;for(let i=1;i<=e.length;i++){const o=t[r-1]===e[i-1]?s[i-1]:Math.min(s[i-1],a,s[i])+1;s[i-1]=a,a=o}s[e.length]=a}return s[e.length]}}class bt{constructor(){this.cssGenerator=new K}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 a=r.querySelector(s);if(a)return{status:"degraded-fallback",elements:[a],warnings:["Target not found, returning anchor"],confidence:t.meta.confidence*.3,meta:{degraded:!0,degradationReason:"anchor-fallback"}}}catch(a){const i=a instanceof Error?a.message:"Unknown selector error";return{status:"error",elements:[],warnings:[`Invalid anchor selector: ${i}`],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],a=-1;for(const i of t){const o=this.scoreElementMatch(i,s);o>a&&(a=o,r=i)}return{status:"success",elements:[r],warnings:[`Multiple matches (${t.length}), selected best-scoring element`],confidence:e.meta.confidence*(.7+a*.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 a=Array.from(t.classList),i=e.classes.filter(o=>a.includes(o)).length;s+=i/e.classes.length*.25}if(e.attributes){const a=Object.entries(e.attributes);if(a.length>0){r+=.2;let i=0;for(const[o,c]of a)t.getAttribute(o)===c&&i++;s+=i/a.length*.2}}if(e.role&&(r+=.15,t.getAttribute("role")===e.role&&(s+=.15)),e.text){r+=.1;const a=z(t.textContent);a===e.text.normalized?s+=.1:a.includes(e.text.normalized)&&(s+=.05)}return r>0?s/r:0}}function St(n,t,e={}){const s={...it,...e},r=new K,a=new mt,i=new pt,o=new bt,c=t instanceof Document?t:t.ownerDocument??t,u=r.buildSelector(n,{ensureUnique:!1,root:c});let d;try{d=Array.from(c.querySelectorAll(u))}catch(f){const m=f instanceof Error?f.message:"Unknown selector error";return{status:"error",elements:[],warnings:[`Invalid CSS selector: ${u}`,`Error: ${m}`],confidence:0,meta:{degraded:!0,degradationReason:"invalid-selector"}}}d.length>s.maxCandidates&&(d=d.slice(0,s.maxCandidates));const l=a.match(d,n.target.semantics);if(l.length===1)return{status:"success",elements:l,warnings:[],confidence:n.meta.confidence,meta:{degraded:!1}};if(l.length===0)return s.enableFallback?o.handleFallback(n,c):{status:"error",elements:[],warnings:["No matching elements found"],confidence:0,meta:{degraded:!0,degradationReason:"not-found"}};let h=l;const g=te(n.constraints);for(const f of g){if(h=i.applyConstraint(h,f),h.length===1)return{status:"success",elements:h,warnings:[],confidence:n.meta.confidence*.9,meta:{degraded:!1}};if(h.length===0)return s.enableFallback?o.handleFallback(n,c):{status:"error",elements:[],warnings:["Constraints eliminated all candidates"],confidence:0,meta:{degraded:!0,degradationReason:"over-constrained"}}}return s.strictMode?{status:"ambiguous",elements:h,warnings:[`Non-unique resolution: ${h.length} matches`],confidence:n.meta.confidence*.7,meta:{degraded:!0,degradationReason:"ambiguous"}}:o.handleAmbiguous(h,n)}function te(n){return[...n].sort((t,e)=>e.priority-t.priority)}function ee(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 se(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:x[n]!==void 0?x[n]:n.startsWith("data-")?x["data-*"]:n.startsWith("aria-")?x["aria-*"]:0}function re(n){return["id","data-testid","data-qa","data-cy","href","text","role"].includes(n)}function ne(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=J(n.anchor,!1,e),a=n.path.length>0?n.path.map(c=>J(c,!1,e)).join(" > ")+" > ":"",i=J(n.target,!0,e),o=e.includeConstraints?ae(n):"";return`${s}: ${r} :: ${a}${i}${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 a=r[1].trim();s=s.slice(r[0].length);const i=s.match(/\s*\{([^}]+)\}\s*$/);let o="";i&&(o=i[1],s=s.slice(0,i.index));const c=s.split(/\s*>\s*/).map(b=>b.trim()).filter(b=>b);if(c.length===0)throw new Error("Invalid SEQL Selector: missing target node");const u=c[c.length-1],d=c.slice(0,-1),l=tt(a,!0),h=d.map(b=>tt(b,!1)),g=tt(u,!1),f=ie(o);return{version:"1.0",anchor:l,path:h,target:g,constraints:f,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 J(n,t=!1,e=yt){const{tag:s,semantics:r}=n;let a=s;const i=[],o={...r.attributes};r.id&&(o.id=r.id),r.role&&!o.role&&(o.role=r.role);const c=Object.entries(o).map(([l,h])=>{const g=At(l),f=l==="href"||l==="src"?P(l,h):h;return{name:l,value:f,priority:g}}).filter(l=>l.name!=="id"&&l.name!=="class"&&V.has(l.name)||Q.has(l.name)&&Z(l.value)?!1:l.priority>0||l.name==="role"||l.name==="id");c.sort((l,h)=>h.priority-l.priority);const u=c.slice(0,e.maxAttributes);u.sort((l,h)=>l.name.localeCompare(h.name));for(const{name:l,value:h}of u)i.push(`${l}="${et(h)}"`);if(e.includeText&&r.text&&!ne(r.text.normalized)){const l=r.text.normalized;l.length>0&&l.length<=e.maxTextLength&&i.push(`text="${et(l)}"`)}let d=i;if(i.length>0&&(t&&e.simplifyTarget&&r.id&&(d=i.filter(l=>{const h=l.split("=")[0];return At(h)>=60||h==="text"||h==="id"||h==="role"})),d.length>0&&d.sort((l,h)=>l.localeCompare(h))),r.classes&&r.classes.length>0){const l=D(r.classes),h=!!r.id||i.some(f=>f.startsWith("href=")||f.startsWith("data-testid=")||f.startsWith("text=")||f.startsWith("role="));if(!(t&&e.simplifyTarget&&h)&&l.length>0){const f=l.sort().slice(0,e.maxClasses);a+=f.map(m=>`.${m}`).join("")}}if(d.length>0&&(a+=`[${d.join(",")}]`),"nthChild"in n&&n.nthChild){const l=!!r.id||r.attributes&&Object.keys(r.attributes).some(re);t&&e.simplifyTarget&&l||(a+=`#${n.nthChild}`)}return a}function ae(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=et(String(e.params.reference));t.push(`text="${s}"`)}break}return t.length===0?"":` {${t.join(",")}}`}function tt(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 a=r[1];e=e.slice(a.length);const i=[];let o;for(;o=e.match(/^\.([a-zA-Z][a-zA-Z0-9-_]*)/);)i.push(o[1]),e=e.slice(o[0].length);i.length>0&&(s.classes=i);const c=e.match(/^\[([^\]]+)\]/);if(c){const l=c[1],h={},g=oe(l);for(const f of g){const m=f.match(/^([a-z][a-z0-9-]*)(?:=|~=)"((?:[^"\\]|\\.)*)"/);if(m){const[,b,y]=m;h[b]=Tt(y)}}Object.keys(h).length>0&&(h.text&&(s.text={raw:h.text,normalized:h.text},delete h.text),h.id&&(s.id=h.id,delete h.id),h.role&&(s.role=h.role,delete h.role),Object.keys(h).length>0&&(s.attributes=h)),e=e.slice(c[0].length)}let u;const d=e.match(/^#(\d+)/);if(d&&(u=parseInt(d[1],10),e=e.slice(d[0].length)),e.trim())throw new Error(`Invalid node: unexpected content "${e}" in "${n}"`);return t?{tag:a,semantics:s,score:.7,degraded:!1}:{tag:a,semantics:s,score:.7,nthChild:u}}function ie(n){if(!n.trim())return[];const t=[],e=n.split(",").map(s=>s.trim());for(const s of e){const[r,a]=s.split("=").map(i=>i.trim());switch(r){case"unique":a==="true"&&t.push({type:"uniqueness",params:{mode:"strict"},priority:90});break;case"pos":t.push({type:"position",params:{strategy:a},priority:70});break;case"text":{const i=a.replace(/^"(.*)"$/,"$1");t.push({type:"text-proximity",params:{reference:Tt(i),maxDistance:5},priority:60});break}}}return t}function oe(n){const t=[];let e="",s=!1;for(let r=0;r<n.length;r++){const a=n[r];a==='"'&&(r===0||n[r-1]!=="\\")?(s=!s,e+=a):a===","&&!s?(e.trim()&&t.push(e.trim()),e=""):e+=a}return e.trim()&&t.push(e.trim()),t}function et(n){return n.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/>/g,"\\>").replace(/:/g,"\\:")}function Tt(n){return n.replace(/\\\\/g,"\0").replace(/\\"/g,'"').replace(/\\>/g,">").replace(/\\:/g,":").replace(/\x00/g,"\\")}function ce(n,t,e){const s=W(n,t);return s?Ct(s,e):null}function le(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 he=new Set(["script","style","noscript","meta","link","head","title"]);function st(n){return n.id&&!H(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 xt(n,t){const e=n.tagName.toLowerCase();return!!(he.has(e)||t&&st(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=st(t);return st(e)-s})}function ue(n={}){const t=performance.now(),{root:e=typeof document<"u"?document.body:void 0,filter:s="*",limit:r=1/0,onProgress:a,progressInterval:i=100,skipNonSemantic:o=!0,generatorOptions:c={},cache:u,signal:d}=n;if(!e)throw new Error("Root element or document is required");const l=u??j(),h={...c,cache:l};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 f=g.filter(T=>!xt(T,o)),b=wt(f).slice(0,r),y=[],A=[];let v=0;const E=b.length;let S=0;for(let T=0;T<b.length&&!d?.aborted;T++){const I=b[T],C=l.getEID(I);if(C)y.push({element:I,eid:C,generationTimeMs:0});else{const rt=performance.now();try{const L=W(I,h),fe=performance.now()-rt;L?y.push({element:I,eid:L,generationTimeMs:fe}):v++}catch(L){A.push({element:I,error:L instanceof Error?L.message:String(L)})}}a&&T-S>=i&&(a(T+1,E),S=T)}a&&a(E,E);const N=performance.now()-t,R=l.getStats(),_=R.eidHits+R.eidMisses+R.selectorHits+R.selectorMisses,w=R.eidHits+R.selectorHits,M=_>0?w/_:0;return{results:y,failed:A,stats:{totalElements:E,successful:y.length,failed:A.length,skipped:v,totalTimeMs:N,avgTimePerElementMs:y.length>0?N/y.length:0,cacheHitRate:M}}}function de(n,t={}){const e=performance.now(),{limit:s=1/0,onProgress:r,progressInterval:a=100,skipNonSemantic:i=!0,generatorOptions:o={},cache:c,signal:u}=t,d=c??j(),l={...o,cache:d},h=n.filter(w=>!xt(w,i)),f=wt(h).slice(0,s),m=[],b=[];let y=0;const A=f.length;let v=0;for(let w=0;w<f.length&&!u?.aborted;w++){const M=f[w],T=d.getEID(M);if(T)m.push({element:M,eid:T,generationTimeMs:0});else{const I=performance.now();try{const C=W(M,l),rt=performance.now()-I;C?m.push({element:M,eid:C,generationTimeMs:rt}):y++}catch(C){b.push({element:M,error:C instanceof Error?C.message:String(C)})}}r&&w-v>=a&&(r(w+1,A),v=w)}r&&r(A,A);const E=performance.now()-e,S=d.getStats(),N=S.eidHits+S.eidMisses+S.selectorHits+S.selectorMisses,R=S.eidHits+S.selectorHits,_=N>0?R/N:0;return{results:m,failed:b,stats:{totalElements:A,successful:m.length,failed:b.length,skipped:y,totalTimeMs:E,avgTimePerElementMs:m.length>0?E/m.length:0,cacheHitRate:_}}}p.AnchorFinder=ot,p.ConstraintsEvaluator=pt,p.CssGenerator=K,p.DEFAULT_GENERATOR_OPTIONS=at,p.DEFAULT_RESOLVER_OPTIONS=it,p.EIDCache=ft,p.EID_VERSION="1.0",p.FallbackHandler=bt,p.MAX_PATH_DEPTH=10,p.PathBuilder=ht,p.ROLE_ANCHOR_VALUES=G,p.SEMANTIC_ANCHOR_TAGS=B,p.SEMANTIC_ATTRIBUTES=$t,p.SEMANTIC_TAGS=nt,p.SemanticExtractor=X,p.SemanticsMatcher=mt,p.SvgFingerprinter=ut,p.calculateConfidence=dt,p.calculateElementScore=Qt,p.createEIDCache=gt,p.filterClasses=ct,p.generateEID=W,p.generateEIDBatch=ue,p.generateEIDForElements=de,p.generateSEQL=ce,p.getClassScore=_t,p.getGlobalCache=j,p.isEID=se,p.isUtilityClass=Y,p.normalizeText=z,p.parseSEQL=Et,p.resetGlobalCache=Yt,p.resolve=St,p.resolveSEQL=le,p.stringifySEQL=Ct,p.validateEID=ee,Object.defineProperty(p,Symbol.toStringTag,{value:"Module"})}));
|
|
2
2
|
//# sourceMappingURL=seql-js.umd.cjs.map
|