@runtypelabs/persona 3.22.0 → 3.24.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.
@@ -1,1848 +1,23 @@
1
- var __defProp = Object.defineProperty;
2
- var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
3
- var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
1
+ var Q=Object.defineProperty;var Z=(s,e,t)=>e in s?Q(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t;var M=(s,e,t)=>Z(s,typeof e!="symbol"?e+"":e,t);var D=Object.defineProperty,tt=Object.getOwnPropertyDescriptor,et=Object.getOwnPropertyNames,U=Object.prototype.hasOwnProperty,T=(s,e)=>()=>(s&&(e=s(s=0)),e),nt=(s,e)=>{let t={};for(var n in s)D(t,n,{get:s[n],enumerable:!0});return e||D(t,Symbol.toStringTag,{value:"Module"}),t},rt=(s,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(var r=et(e),i=0,a=r.length,o;i<a;i++)o=r[i],!U.call(s,o)&&o!==t&&D(s,o,{get:(c=>e[c]).bind(null,o),enumerable:!(n=tt(e,o))||n.enumerable});return s},st=s=>U.call(s,"module.exports")?s["module.exports"]:rt(D({},"__esModule",{value:!0}),s),ot=void 0,w,W=T((()=>{w=class v{static findMainContent(e){let t=e.querySelector('main, [role="main"]');return t||(e.body?v.detectMainContent(e.body):e.documentElement)}static detectMainContent(e){let t=[];if(v.collectCandidates(e,t,15),t.length===0)return e;t.sort((r,i)=>v.calculateContentScore(i)-v.calculateContentScore(r));let n=t[0];for(let r=1;r<t.length;r++){let i=t[r];!t.some((a,o)=>o!==r&&a.contains(i))&&v.calculateContentScore(i)>v.calculateContentScore(n)&&(n=i)}return n}static collectCandidates(e,t,n){v.calculateContentScore(e)>=n&&t.push(e),Array.from(e.children).forEach(r=>{v.collectCandidates(r,t,n)})}static calculateContentScore(e){var d;let t=0,n=["article","content","main-container","main","main-content","post","entry"],r=["content","main","article","post","entry"];n.forEach(f=>{e.classList.contains(f)&&(t+=10)}),r.forEach(f=>{var h;(h=e.id)!=null&&h.toLowerCase().includes(f)&&(t+=10)});let i=e.tagName.toLowerCase();["article","main","section"].includes(i)&&(t+=8);let a=e.getElementsByTagName("p").length;t+=Math.min(a*2,10);let o=e.querySelectorAll("h1, h2, h3").length;t+=Math.min(o*3,9);let c=((d=e.textContent)==null?void 0:d.trim().length)||0;c>300&&(t+=Math.min(Math.floor(c/300)*2,10));let l=v.calculateLinkDensity(e);l<.3?t+=5:l>.5&&(t-=5),(e.hasAttribute("data-main")||e.hasAttribute("data-content")||e.hasAttribute("itemprop"))&&(t+=8);let u=e.getAttribute("role");return(u==="main"||u==="article")&&(t+=10),e.matches("aside, nav, header, footer, .sidebar, .navigation, .menu, .ad, .advertisement")&&(t-=10),e.getElementsByTagName("form").length>2&&(t-=5),Math.max(0,t)}static calculateLinkDensity(e){var i,a;let t=e.getElementsByTagName("a"),n=0;for(let o of Array.from(t))n+=((i=o.textContent)==null?void 0:i.length)||0;let r=((a=e.textContent)==null?void 0:a.length)||1;return n/r}static isNavigation(e){if(e.tagName.toLowerCase()==="nav"||e.getAttribute("role")==="navigation")return!0;let t=[/nav/i,/menu/i,/sidebar/i,/toolbar/i],n=`${e.className} ${e.id}`.toLowerCase();return t.some(r=>r.test(n))}static isSupplementary(e){if(e.tagName.toLowerCase()==="aside"||e.getAttribute("role")==="complementary")return!0;let t=[/sidebar/i,/widget/i,/related/i,/advertisement/i,/social/i],n=`${e.className} ${e.id}`.toLowerCase();return t.some(r=>r.test(n))}static detectLandmarks(e){let t={navigation:[],main:[],complementary:[],contentinfo:[],banner:[],search:[],form:[],region:[]};for(let[n,r]of Object.entries({navigation:'nav, [role="navigation"]',main:'main, [role="main"]',complementary:'aside, [role="complementary"]',contentinfo:'footer, [role="contentinfo"]',banner:'header, [role="banner"]',search:'[role="search"]',form:'form[aria-label], form[aria-labelledby], [role="form"]',region:'section[aria-label], section[aria-labelledby], [role="region"]'})){let i=e.querySelectorAll(r);t[n]=Array.from(i)}return t}}})),E,N=T((()=>{E=class S{static generateSelectors(e){var p;let t=e.ownerDocument||document,n=[];e.id&&S.isUniqueId(e.id,t)&&n.push({type:"id",value:`#${CSS.escape(e.id)}`,score:100});let r=S.getDataTestId(e);if(r){let m=`[data-testid="${CSS.escape(r)}"]`;n.push({type:"data-testid",value:m,score:90+(S.isUniqueSelectorSafe(m,t)?5:0)})}let i=e.getAttribute("role"),a=e.getAttribute("aria-label");if(i&&a){let m=`[role="${CSS.escape(i)}"][aria-label="${CSS.escape(a)}"]`;n.push({type:"role-aria",value:m,score:85+(S.isUniqueSelectorSafe(m,t)?5:0)})}let o=e.getAttribute("name");if(o){let m=`[name="${CSS.escape(o)}"]`;n.push({type:"name",value:m,score:78+(S.isUniqueSelectorSafe(m,t)?5:0)})}let c=S.generateCSSSelector(e,t),l=(c.match(/:nth-child\(/g)||[]).length*10,u=c.includes(".")?8:0,d=Math.max(0,70+u-l);n.push({type:"class-path",value:c,score:d});let f=S.generateXPath(e,t);n.push({type:"xpath",value:f,score:40});let h=S.generateTextBasedSelector(e);h&&n.push({type:"text",value:h,score:30}),n.sort((m,x)=>x.score-m.score);let g={css:((p=n.find(m=>m.type!=="xpath"&&m.type!=="text"))==null?void 0:p.value)||c,xpath:f,candidates:n};return h&&(g.textBased=h),r&&(g.dataTestId=r),a&&(g.ariaLabel=a),g}static generateCSSSelector(e,t){var a;if(e.id&&S.isUniqueId(e.id,t))return`#${CSS.escape(e.id)}`;let n=S.getDataTestId(e);if(n)return`[data-testid="${CSS.escape(n)}"]`;let r=[],i=e;for(;i&&i.nodeType===Node.ELEMENT_NODE;){let o=i.nodeName.toLowerCase();if(i.id&&S.isUniqueId(i.id,t)){o=`#${CSS.escape(i.id)}`,r.unshift(o);break}let c=S.getMeaningfulClasses(i);c.length>0&&(o+=`.${c.map(u=>CSS.escape(u)).join(".")}`);let l=(a=i.parentElement)==null?void 0:a.children;if(l&&l.length>1){let u=Array.from(l).indexOf(i);(u>0||!S.isUniqueSelector(o,i.parentElement))&&(o+=`:nth-child(${u+1})`)}r.unshift(o),i=i.parentElement}return S.optimizePath(r,e,t)}static generateXPath(e,t){var i;if(e.id&&S.isUniqueId(e.id,t))return`//*[@id="${e.id}"]`;let n=[],r=e;for(;r&&r.nodeType===Node.ELEMENT_NODE;){let a=r.nodeName.toLowerCase();if(r.id&&S.isUniqueId(r.id,t)){n.unshift(`//*[@id="${r.id}"]`);break}let o=a,c=(i=r.parentElement)==null?void 0:i.children;if(c){let l=Array.from(c).filter(u=>u.nodeName.toLowerCase()===a);if(l.length>1){let u=l.indexOf(r)+1;o+=`[${u}]`}}n.unshift(o),r=r.parentElement}return`//${n.join("/")}`}static generateTextBasedSelector(e){var r;let t=(r=e.textContent)==null?void 0:r.trim();if(!t||t.length>50)return;let n=e.nodeName.toLowerCase();if(["button","a","label"].includes(n))return`${n}:contains("${t.replace(/['"\\]/g,"\\$&")}")`}static getDataTestId(e){return e.getAttribute("data-testid")||e.getAttribute("data-test-id")||e.getAttribute("data-test")||e.getAttribute("data-cy")||void 0}static isUniqueId(e,t){return t.querySelectorAll(`#${CSS.escape(e)}`).length===1}static isUniqueSelector(e,t){try{return t.querySelectorAll(e).length===1}catch{return!1}}static isUniqueSelectorSafe(e,t){try{return t.querySelectorAll(e).length===1}catch{return!1}}static getMeaningfulClasses(e){let t=Array.from(e.classList),n=[/^(p|m|w|h|text|bg|border|flex|grid|col|row)-/,/^(xs|sm|md|lg|xl|2xl):/,/^(hover|focus|active|disabled|checked):/,/^js-/,/^is-/,/^has-/];return t.filter(r=>r.length<3?!1:!n.some(i=>i.test(r))).slice(0,2)}static optimizePath(e,t,n){for(let r=0;r<e.length-1;r++){let i=e.slice(r).join(" > ");try{let a=n.querySelectorAll(i);if(a.length===1&&a[0]===t)return i}catch{}}return e.join(" > ")}static getContextPath(e){var a;let t=[],n=e,r=0,i=5;for(;n&&n!==((a=e.ownerDocument)==null?void 0:a.body)&&r<i;){let o=n.nodeName.toLowerCase(),c=o;if(n.id)c=`${o}#${n.id}`;else if(n.className&&typeof n.className=="string"){let u=n.className.split(" ")[0];u&&(c=`${o}.${u}`)}let l=n.getAttribute("role");l&&(c+=`[role="${l}"]`),t.unshift(c),n=n.parentElement,r++}return t}}})),b,B=T((()=>{var s;N(),b=(s=class{static isVisible(t,n){var a,o;let r=t.getBoundingClientRect(),i=n||((o=(a=t.ownerDocument)==null?void 0:a.defaultView)==null?void 0:o.getComputedStyle(t));return i?r.width>0&&r.height>0&&i.display!=="none"&&i.visibility!=="hidden"&&i.opacity!=="0"&&t.offsetParent!==null:!1}static isInViewport(t,n){var a,o,c,l;let r=t.getBoundingClientRect(),i=n||{width:((o=(a=t.ownerDocument)==null?void 0:a.defaultView)==null?void 0:o.innerWidth)||0,height:((l=(c=t.ownerDocument)==null?void 0:c.defaultView)==null?void 0:l.innerHeight)||0};return r.top<i.height&&r.bottom>0&&r.left<i.width&&r.right>0}static passesFilter(t,n){var a,o,c,l,u,d,f,h,g,p;if(!n)return!0;let r=t;if((a=n.excludeSelectors)!=null&&a.length){for(let m of n.excludeSelectors)if(t.matches(m))return!1}if((o=n.includeSelectors)!=null&&o.length){let m=!1;for(let x of n.includeSelectors)if(t.matches(x)){m=!0;break}if(!m)return!1}if((c=n.tags)!=null&&c.length&&!n.tags.includes(t.tagName.toLowerCase()))return!1;let i=((l=r.textContent)==null?void 0:l.toLowerCase())||"";if((u=n.textContains)!=null&&u.length){let m=!1;for(let x of n.textContains)if(i.includes(x.toLowerCase())){m=!0;break}if(!m)return!1}if((d=n.textMatches)!=null&&d.length){let m=!1;for(let x of n.textMatches)if(x.test(i)){m=!0;break}if(!m)return!1}if((f=n.hasAttributes)!=null&&f.length){for(let m of n.hasAttributes)if(!t.hasAttribute(m))return!1}if(n.attributeValues)for(let[m,x]of Object.entries(n.attributeValues)){let C=t.getAttribute(m);if(!C)return!1;if(typeof x=="string"){if(C!==x)return!1}else if(x instanceof RegExp&&!x.test(C))return!1}if((h=n.withinSelectors)!=null&&h.length){let m=!1;for(let x of n.withinSelectors)if(t.closest(x)){m=!0;break}if(!m)return!1}if((g=n.interactionTypes)!=null&&g.length){let m=s.getInteractionInfo(t),x=!1;for(let C of n.interactionTypes)if(m[C]){x=!0;break}if(!x)return!1}if(n.nearText){let m=t.parentElement;if(!m||!((p=m.textContent)!=null&&p.toLowerCase().includes(n.nearText.toLowerCase())))return!1}return!0}static extractElement(t,n,r=0){if(n.maxDepth&&r>n.maxDepth||!n.includeHidden&&!s.isVisible(t)||n.viewportOnly&&!s.isInViewport(t)||!s.passesFilter(t,n.filter))return null;let i=t,a={tag:t.tagName.toLowerCase(),text:s.getElementText(t,n),selector:E.generateSelectors(t),attributes:s.getRelevantAttributes(t,n),context:s.getElementContext(t),interaction:s.getInteractionInfo(t)};if(n.mode==="full"&&s.isSemanticContainer(t)){let o=[];if(n.includeShadowDOM&&i.shadowRoot){let l=s.extractChildren(i.shadowRoot,n,r+1);o.push(...l)}let c=s.extractChildren(t,n,r+1);o.push(...c),o.length>0&&(a.children=o)}return a}static extractChildren(t,n,r){let i=[],a=t.querySelectorAll("*");for(let o of Array.from(a)){if(s.hasExtractedAncestor(o,a))continue;let c=s.extractElement(o,n,r);c&&i.push(c)}return i}static hasExtractedAncestor(t,n){let r=t.parentElement;for(;r;){if(Array.from(n).includes(r))return!0;r=r.parentElement}return!1}static getRelevantAttributes(t,n){var c,l;let r=["id","class","name","type","value","placeholder","href","src","alt","title","action","method","aria-label","aria-describedby","aria-controls","role","disabled","readonly","required","checked","min","max","pattern","step","autocomplete","data-testid","data-test","data-cy"],i={},a=(c=n.attributeTruncateLength)!=null?c:100,o=(l=n.dataAttributeTruncateLength)!=null?l:50;for(let u of r){let d=t.getAttribute(u);d&&(i[u]=d.length>a?`${d.substring(0,a)}...`:d)}for(let u of t.attributes)u.name.startsWith("data-")&&!r.includes(u.name)&&(i[u.name]=u.value.length>o?`${u.value.substring(0,o)}...`:u.value);return i}static getElementContext(t){let n={parentChain:E.getContextPath(t)},r=t.closest("form");r&&(n.nearestForm=E.generateSelectors(r).css);let i=t.closest('section, [role="region"]');i&&(n.nearestSection=E.generateSelectors(i).css);let a=t.closest('main, [role="main"]');a&&(n.nearestMain=E.generateSelectors(a).css);let o=t.closest('nav, [role="navigation"]');return o&&(n.nearestNav=E.generateSelectors(o).css),n}static getInteractionInfo(t){let n=t,r={};(n.onclick||t.getAttribute("onclick")||t.matches('button, a[href], [role="button"], [tabindex]:not([tabindex="-1"])'))&&(r.click=!0),(n.onchange||t.getAttribute("onchange")||t.matches("input, select, textarea"))&&(r.change=!0),(n.onsubmit||t.getAttribute("onsubmit")||t.matches("form"))&&(r.submit=!0),t.matches('a[href], button[type="submit"]')&&(r.nav=!0),(n.hasAttribute("disabled")||n.getAttribute("aria-disabled")==="true")&&(r.disabled=!0),s.isVisible(t)||(r.hidden=!0);let i=t.getAttribute("role");if(i&&(r.role=i),t.matches("input, textarea, select, button")){let a=t.form||t.closest("form");a&&(r.form=E.generateSelectors(a).css)}return r}static getElementText(t,n){var a;if(t.matches("input, textarea")){let o=t;return o.value||o.placeholder||""}if(t.matches("img"))return t.alt||"";let r=((a=t.textContent)==null?void 0:a.trim())||"",i=n==null?void 0:n.textTruncateLength;return i&&r.length>i?`${r.substring(0,i)}...`:r}static isSemanticContainer(t){return t.matches('article, section, nav, aside, main, header, footer, form, table, ul, ol, dl, figure, details, dialog, [role="region"], [role="navigation"], [role="main"], [role="complementary"]')}static getInteractiveElements(t,n){let r=[],i=s.INTERACTIVE_SELECTORS.join(", "),a=t.querySelectorAll(i);for(let o of Array.from(a)){let c=s.extractElement(o,n);c&&r.push(c)}if(n.customSelectors)for(let o of n.customSelectors)try{let c=t.querySelectorAll(o);for(let l of Array.from(c)){let u=s.extractElement(l,n);u&&r.push(u)}}catch{console.warn(`Invalid custom selector: ${o}`)}return r}static getSemanticElements(t,n){let r=[],i=s.SEMANTIC_SELECTORS.join(", "),a=t.querySelectorAll(i);for(let o of Array.from(a)){let c=s.extractElement(o,n);c&&r.push(c)}return r}},M(s,"INTERACTIVE_SELECTORS",["button","a[href]",'input:not([type="hidden"])',"textarea","select",'[role="button"]',"[onclick]",'[contenteditable="true"]',"summary",'[tabindex]:not([tabindex="-1"])']),M(s,"SEMANTIC_SELECTORS",["h1","h2","h3","h4","h5","h6","article","section","nav","aside","main","header","footer","form","table","ul","ol","img[alt]","figure","video","audio",'[role="navigation"]','[role="main"]','[role="complementary"]','[role="contentinfo"]']),s)}));function $(s,e){let t=(s!=null?s:"").trim();if(!e||t.length<=e)return t;let n=["login","log in","sign in","sign up","submit","search","filter","add to cart","next","continue"],r=t.toLowerCase(),i=n.map(l=>({k:l,i:r.indexOf(l)})).find(l=>l.i>-1),a=Math.max(0,Math.floor(e*.66));if(i&&i.i>a){let l=Math.max(12,e-a-5),u=Math.max(0,i.i-Math.floor(l/2)),d=Math.min(t.length,u+l);return`${t.slice(0,a).trimEnd()} \u2026 ${t.slice(u,d).trim()}\u2026`}let o=t.slice(0,e),c=o.lastIndexOf(" ");return`${c>32?o.slice(0,c):o}\u2026`}function it(s){var e;return((e=s.selector)==null?void 0:e.css)||""}function at(s){let e=5381;for(let t=0;t<s.length;t++)e=e*33^s.charCodeAt(t);return`sec-${(e>>>0).toString(36)}`}function z(s){switch(s){case"header":return"\u{1F9ED}";case"navigation":return"\u{1F4D1}";case"main":return"\u{1F4C4}";case"sections":return"\u{1F5C2}\uFE0F";case"sidebar":return"\u{1F4DA}";case"footer":return"\u{1F53B}";case"modals":return"\u{1F4AC}";default:return"\u{1F539}"}}function R(s,e){var o,c,l,u,d;let t=$(s.text||((o=s.attributes)==null?void 0:o.ariaLabel),(c=e==null?void 0:e.maxTextLength)!=null?c:80),n=it(s),r=s.tag.toLowerCase(),i=(l=s.interaction)!=null&&l.submit?"submit":(u=s.interaction)!=null&&u.click?"click":(d=s.interaction)!=null&&d.change?"change":void 0,a=i?` (${i})`:"";return`- ${r.toUpperCase()}: ${t||"(no text)"} \u2192 \`${n}\`${a}`}function ct(s){let e=[];e.push(...s.buttons.map(o=>{var c;return((c=o.selector)==null?void 0:c.css)||""})),e.push(...s.links.map(o=>{var c;return((c=o.selector)==null?void 0:c.css)||""})),e.push(...s.inputs.map(o=>{var c;return((c=o.selector)==null?void 0:c.css)||""})),e.push(...s.clickable.map(o=>{var c;return((c=o.selector)==null?void 0:c.css)||""}));let t=e.length||1,n=e.filter(o=>o.startsWith("#")).length,r=e.filter(o=>/\[data-testid=/.test(o)).length,i=e.filter(o=>/:nth-child\(/.test(o)).length,a=n+r;return`Selector quality: ${Math.round(a/t*100)}% stable (ID/data-testid), ${Math.round(i/t*100)}% structural (:nth-child)`}function lt(s,e){var r,i;let t=[],n=a=>typeof(e==null?void 0:e.maxElements)=="number"?a.slice(0,e.maxElements):a;if(s.buttons.length){t.push("Buttons:");for(let a of n(s.buttons))t.push(R(a,e))}if(s.links.length){t.push("Links:");for(let a of n(s.links))t.push(R(a,e))}if(s.inputs.length){t.push("Inputs:");for(let a of n(s.inputs))t.push(R(a,e))}if(s.clickable.length){t.push("Other Clickable:");for(let a of n(s.clickable))t.push(R(a,e))}if(s.forms.length){t.push("Forms:");for(let a of n(s.forms))t.push(`- FORM: action=${(r=a.action)!=null?r:"-"} method=${(i=a.method)!=null?i:"-"} \u2192 \`${a.selector}\``)}return t.join(`
2
+ `)}function j(s){var a,o;let e=z("region"),t=at(`${s.selector}|${(a=s.label)!=null?a:""}|${(o=s.role)!=null?o:""}`),n=s.label?` ${s.label}`:"",r=[];s.buttonCount&&r.push(`${s.buttonCount} buttons`),s.linkCount&&r.push(`${s.linkCount} links`),s.inputCount&&r.push(`${s.inputCount} inputs`),s.textPreview&&r.push(`\u201C${$(s.textPreview,80)}\u201D`);let i=r.length?` \u2014 ${r.join(", ")}`:"";return`${e} ${n} \u2192 \`${s.selector}\` [${t}]${i}`}function I(s,e,t="section"){return`<page ${[e!=null&&e.title?`title="${F(e==null?void 0:e.title)}"`:null,e!=null&&e.url?`url="${F(e==null?void 0:e.url)}"`:null].filter(Boolean).join(" ")}>
3
+ <${t}><![CDATA[
4
+ ${s}
5
+ ]]></${t}>
6
+ </page>`}function F(s){return s.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function V(s){return s.charAt(0).toUpperCase()+s.slice(1)}var _,ut=T((()=>{_=class{static structure(s,e={},t){var a,o,c;let n=[];n.push("# Page Outline"),(t!=null&&t.title||t!=null&&t.url)&&(n.push(`Title: ${(a=t==null?void 0:t.title)!=null?a:""}`.trim()),n.push(`URL: ${(o=t==null?void 0:t.url)!=null?o:""}`.trim())),n.push("");let r=s.regions,i=[["header",r.header],["navigation",r.navigation],["main",r.main],["sections",r.sections],["sidebar",r.sidebar],["footer",r.footer],["modals",r.modals]];for(let[l,u]of i){if(!u)continue;let d=z(l);if(Array.isArray(u)){if(!u.length)continue;n.push(`## ${d} ${V(l)}`);for(let f of u)n.push(j(f))}else n.push(`## ${d} ${V(l)}`),n.push(j(u));n.push("")}if((c=s.suggestions)!=null&&c.length){n.push("## Suggestions");for(let l of s.suggestions)n.push(`- ${l}`);n.push("")}return n.push("Next: choose a region (by selector or [sectionId]) and call dom_extract_region for actionable details."),I(n.join(`
7
+ `),t,"outline")}static region(s,e={},t){var o,c,l;let n=[];n.push("# Region Details"),(t!=null&&t.title||t!=null&&t.url)&&(n.push(`Title: ${(o=t==null?void 0:t.title)!=null?o:""}`.trim()),n.push(`URL: ${(c=t==null?void 0:t.url)!=null?c:""}`.trim())),n.push("");let r=s.interactive;if(s.page){let u=[s.page.hasErrors?"errors: yes":"errors: no",s.page.isLoading?"loading: yes":"loading: no",s.page.hasModals?"modals: yes":"modals: no"];n.push(`Page state: ${u.join(", ")}`)}let i=[],a=u=>u?u.length:0;return i.push(`${a(r.buttons)} buttons`),i.push(`${a(r.links)} links`),i.push(`${a(r.inputs)} inputs`),(l=r.forms)!=null&&l.length&&i.push(`${a(r.forms)} forms`),n.push(`Summary: ${i.join(", ")}`),n.push(ct(r)),n.push(""),n.push(lt(r,e)),n.push(""),n.push("Next: write a script using the most stable selectors above. If selectors look unstable, rerun dom_extract_region with higher detail or call dom_extract_content for text context."),I(n.join(`
8
+ `),t,"section")}static content(s,e={},t){var r,i,a,o,c,l,u,d,f;let n=[];if(n.push("# Content"),n.push(`Selector: \`${s.selector}\``),n.push(""),(r=s.text.headings)!=null&&r.length){n.push("Headings:");for(let h of s.text.headings)n.push(`- H${h.level}: ${$(h.text,(i=e.maxTextLength)!=null?i:120)}`);n.push("")}if((a=s.text.paragraphs)!=null&&a.length){let h=typeof e.maxElements=="number"?e.maxElements:s.text.paragraphs.length;n.push("Paragraphs:");for(let g of s.text.paragraphs.slice(0,h))n.push(`- ${$(g,(o=e.maxTextLength)!=null?o:200)}`);n.push("")}if((c=s.text.lists)!=null&&c.length){n.push("Lists:");for(let h of s.text.lists){n.push(`- ${h.type.toUpperCase()}:`);let g=typeof e.maxElements=="number"?e.maxElements:h.items.length;for(let p of h.items.slice(0,g))n.push(` - ${$(p,(l=e.maxTextLength)!=null?l:120)}`)}n.push("")}if((u=s.tables)!=null&&u.length){n.push("Tables:");for(let h of s.tables){n.push(`- Headers: ${h.headers.join(" | ")}`);let g=typeof e.maxElements=="number"?e.maxElements:h.rows.length;for(let p of h.rows.slice(0,g))n.push(` - ${p.join(" | ")}`)}n.push("")}if((d=s.media)!=null&&d.length){n.push("Media:");let h=typeof e.maxElements=="number"?e.maxElements:s.media.length;for(let g of s.media.slice(0,h))n.push(`- ${g.type.toUpperCase()}: ${(f=g.alt)!=null?f:""} ${g.src?`\u2192 ${g.src}`:""}`.trim());n.push("")}return n.push("Next: if text is insufficient for targeting, call dom_extract_region for interactive selectors."),I(n.join(`
9
+ `),t,"content")}}}));function dt(){if(typeof window!="undefined"){let s=window,e=s.SmartDOMReader;if(typeof e=="function")return e;let t=s.SmartDOMReaderNamespace;if(t&&typeof t.SmartDOMReader=="function")return t.SmartDOMReader}try{if(typeof ot=="function"){let s=(G(),st(mt));if(s&&typeof s.SmartDOMReader=="function")return s.SmartDOMReader;if(s&&typeof s.default=="function")return s.default}}catch{}}var X,ft=T((()=>{W(),N(),B(),X=class y{static extractStructure(e){let t={},n=e.querySelector('header, [role="banner"], .header, #header');n&&(t.header=y.analyzeRegion(n));let r=e.querySelectorAll('nav, [role="navigation"], .nav, .navigation');if(r.length>0&&(t.navigation=Array.from(r).map(d=>y.analyzeRegion(d))),e instanceof Document){let d=w.findMainContent(e);if(d){t.main=y.analyzeRegion(d);let f=d.querySelectorAll('section, article, [role="region"]');f.length>0&&(t.sections=Array.from(f).filter(h=>!h.closest("nav, header, footer")).map(h=>y.analyzeRegion(h)))}}else{t.main=y.analyzeRegion(e);let d=e.querySelectorAll('section, article, [role="region"]');d.length>0&&(t.sections=Array.from(d).filter(f=>!f.closest("nav, header, footer")).map(f=>y.analyzeRegion(f)))}let i=e.querySelectorAll('aside, [role="complementary"], .sidebar, #sidebar');i.length>0&&(t.sidebar=Array.from(i).map(d=>y.analyzeRegion(d)));let a=e.querySelector('footer, [role="contentinfo"], .footer, #footer');a&&(t.footer=y.analyzeRegion(a));let o=e.querySelectorAll('[role="dialog"], .modal, .popup, .overlay'),c=Array.from(o).filter(d=>b.isVisible(d));c.length>0&&(t.modals=c.map(d=>y.analyzeRegion(d)));let l=y.extractFormOverview(e),u=y.calculateSummary(e,t,l);return{regions:t,forms:l,summary:u,suggestions:y.generateSuggestions(t,u)}}static extractRegion(e,t,n={},r){let i=t.querySelector(e);if(!i)return null;let a=r!=null?r:dt();if(!a)throw new Error("SmartDOMReader is unavailable. Ensure the Smart DOM Reader module is loaded before calling extractRegion.");return new a(n).extract(i,n)}static extractContent(e,t,n={}){let r=t.querySelector(e);if(!r)return null;let i={selector:e,text:{},metadata:{wordCount:0,hasInteractive:!1}};if(n.includeHeadings!==!1){let c=r.querySelectorAll("h1, h2, h3, h4, h5, h6");i.text.headings=Array.from(c).map(l=>({level:Number.parseInt(l.tagName[1],10),text:y.getTextContent(l,n.maxTextLength)}))}let a=r.querySelectorAll("p");if(a.length>0&&(i.text.paragraphs=Array.from(a).map(c=>y.getTextContent(c,n.maxTextLength)).filter(c=>c.length>0)),n.includeLists!==!1){let c=r.querySelectorAll("ul, ol");i.text.lists=Array.from(c).map(l=>({type:l.tagName.toLowerCase(),items:Array.from(l.querySelectorAll("li")).map(u=>y.getTextContent(u,n.maxTextLength))}))}if(n.includeTables!==!1){let c=r.querySelectorAll("table");i.tables=Array.from(c).map(l=>({headers:Array.from(l.querySelectorAll("th")).map(u=>y.getTextContent(u)),rows:Array.from(l.querySelectorAll("tr")).filter(u=>u.querySelector("td")).map(u=>Array.from(u.querySelectorAll("td")).map(d=>y.getTextContent(d)))}))}if(n.includeMedia!==!1){let c=r.querySelectorAll("img"),l=r.querySelectorAll("video"),u=r.querySelectorAll("audio");i.media=[...Array.from(c).map(d=>{let f={type:"img"},h=d.getAttribute("alt"),g=d.getAttribute("src");return h&&(f.alt=h),g&&(f.src=g),f}),...Array.from(l).map(d=>{let f={type:"video"},h=d.getAttribute("src");return h&&(f.src=h),f}),...Array.from(u).map(d=>{let f={type:"audio"},h=d.getAttribute("src");return h&&(f.src=h),f})]}let o=r.textContent||"";return i.metadata.wordCount=o.trim().split(/\s+/).length,i.metadata.hasInteractive=r.querySelectorAll("button, a, input, textarea, select").length>0,i}static analyzeRegion(e){var x,C,P,k;let t=E.generateSelectors(e).css,n=e.querySelectorAll('button, [role="button"]'),r=e.querySelectorAll("a[href]"),i=e.querySelectorAll("input, textarea, select"),a=e.querySelectorAll("form"),o=e.querySelectorAll("ul, ol"),c=e.querySelectorAll("table"),l=e.querySelectorAll("img, video, audio"),u=n.length+r.length+i.length,d,f=e.getAttribute("aria-label");if(f)d=f;else if(e.getAttribute("aria-labelledby")){let L=e.getAttribute("aria-labelledby");if(L){let H=(x=e.ownerDocument)==null?void 0:x.getElementById(L);H&&(d=(C=H.textContent)==null?void 0:C.trim())}}else{let L=e.querySelector("h1, h2, h3");L&&(d=(P=L.textContent)==null?void 0:P.trim())}let h=((k=e.textContent)==null?void 0:k.trim())||"",g=h.length>50?`${h.substring(0,50)}...`:h,p={selector:t,interactiveCount:u,hasForm:a.length>0,hasList:o.length>0,hasTable:c.length>0,hasMedia:l.length>0};d&&(p.label=d);let m=e.getAttribute("role");return m&&(p.role=m),n.length>0&&(p.buttonCount=n.length),r.length>0&&(p.linkCount=r.length),i.length>0&&(p.inputCount=i.length),g.length>0&&(p.textPreview=g),p}static extractFormOverview(e){let t=e.querySelectorAll("form");return Array.from(t).map(n=>{var g,p,m;let r=n.querySelectorAll("input, textarea, select"),i=E.generateSelectors(n).css,a="unknown";n.closest('header, [role="banner"]')?a="header":n.closest('nav, [role="navigation"]')?a="navigation":n.closest('main, [role="main"]')?a="main":n.closest('aside, [role="complementary"]')?a="sidebar":n.closest('footer, [role="contentinfo"]')&&(a="footer");let o,c=(g=n.getAttribute("id"))==null?void 0:g.toLowerCase(),l=(p=n.getAttribute("class"))==null?void 0:p.toLowerCase(),u=(m=n.getAttribute("action"))==null?void 0:m.toLowerCase(),d=n.querySelector('input[type="email"]'),f=n.querySelector('input[type="password"]');n.querySelector('input[type="search"]')||c!=null&&c.includes("search")||l!=null&&l.includes("search")?o="search":f&&d?o="login":f?o="authentication":c!=null&&c.includes("contact")||l!=null&&l.includes("contact")?o="contact":c!=null&&c.includes("subscribe")||l!=null&&l.includes("subscribe")?o="subscription":(u!=null&&u.includes("checkout")||l!=null&&l.includes("checkout"))&&(o="checkout");let h={selector:i,location:a,inputCount:r.length};return o&&(h.purpose=o),h})}static calculateSummary(e,t,n){var d,f;let r=e.querySelectorAll("button, a[href], input, textarea, select"),i=e.querySelectorAll('section, article, [role="region"]'),a=(((d=t.modals)==null?void 0:d.length)||0)>0,o=[".error",".alert-danger",'[role="alert"]'].some(h=>{let g=e.querySelector(h);return g?b.isVisible(g):!1}),c=[".loading",".spinner",'[aria-busy="true"]'].some(h=>{let g=e.querySelector(h);return g?b.isVisible(g):!1}),l={totalInteractive:r.length,totalForms:n.length,totalSections:i.length,hasModals:a,hasErrors:o,isLoading:c},u=(f=t.main)==null?void 0:f.selector;return u&&(l.mainContentSelector=u),l}static generateSuggestions(e,t){let n=[];return t.hasErrors&&n.push("Page has error indicators - check error messages before interacting"),t.isLoading&&n.push("Page appears to be loading - wait or check loading state"),t.hasModals&&n.push("Modal/dialog is open - may need to interact with or close it first"),e.main&&e.main.interactiveCount>10&&n.push(`Main content has ${e.main.interactiveCount} interactive elements - consider filtering`),t.totalForms>0&&n.push(`Found ${t.totalForms} form(s) on the page`),e.main||n.push("No clear main content area detected - may need to explore regions"),n}static getTextContent(e,t){var r;let n=((r=e.textContent)==null?void 0:r.trim())||"";return t&&n.length>t?`${n.substring(0,t)}...`:n}}})),ht=T((()=>{})),mt=nt({ContentDetection:()=>w,MarkdownFormatter:()=>_,ProgressiveExtractor:()=>X,SelectorGenerator:()=>E,SmartDOMReader:()=>A,default:()=>A}),A,G=T((()=>{W(),N(),B(),ut(),ft(),ht(),A=class O{constructor(e={}){M(this,"options");var t;this.options={mode:e.mode||"interactive",maxDepth:e.maxDepth||5,includeHidden:e.includeHidden||!1,includeShadowDOM:(t=e.includeShadowDOM)!=null?t:!0,includeIframes:e.includeIframes||!1,viewportOnly:e.viewportOnly||!1,mainContentOnly:e.mainContentOnly||!1,customSelectors:e.customSelectors||[],...e.attributeTruncateLength!==void 0&&{attributeTruncateLength:e.attributeTruncateLength},...e.dataAttributeTruncateLength!==void 0&&{dataAttributeTruncateLength:e.dataAttributeTruncateLength},...e.textTruncateLength!==void 0&&{textTruncateLength:e.textTruncateLength},...e.filter!==void 0&&{filter:e.filter}}}extract(e=document,t){let n=Date.now(),r=e instanceof Document?e:e.ownerDocument,i={...this.options,...t},a=e instanceof Document?r:e;i.mainContentOnly&&e instanceof Document&&(a=w.findMainContent(r));let o=this.extractPageState(r),c=this.extractLandmarks(r),l=this.extractInteractiveElements(a,i),u={mode:i.mode,timestamp:n,page:o,landmarks:c,interactive:l};if(i.mode==="full"){let d=this.extractSemanticElements(a,i),f=this.extractMetadata(r,a,i);return{...u,semantic:d,metadata:f}}return u}extractPageState(e){var n;let t=this.getFocusedElement(e);return{url:((n=e.location)==null?void 0:n.href)||"",title:e.title||"",hasErrors:this.detectErrors(e),isLoading:this.detectLoading(e),hasModals:this.detectModals(e),...t!==void 0&&{hasFocus:t}}}extractLandmarks(e){let t=w.detectLandmarks(e);return{navigation:this.elementsToSelectors(t.navigation||[]),main:this.elementsToSelectors(t.main||[]),forms:this.elementsToSelectors(t.form||[]),headers:this.elementsToSelectors(t.banner||[]),footers:this.elementsToSelectors(t.contentinfo||[]),articles:this.elementsToSelectors(t.region||[]),sections:this.elementsToSelectors(t.region||[])}}elementsToSelectors(e){return e.map(t=>E.generateSelectors(t).css)}extractInteractiveElements(e,t){let n=[],r=[],i=[],a=[];return e.querySelectorAll('button, [role="button"], input[type="button"], input[type="submit"]').forEach(o=>{if(this.shouldIncludeElement(o,t)){let c=b.extractElement(o,t);c&&n.push(c)}}),e.querySelectorAll("a[href]").forEach(o=>{if(this.shouldIncludeElement(o,t)){let c=b.extractElement(o,t);c&&r.push(c)}}),e.querySelectorAll('input:not([type="button"]):not([type="submit"]), textarea, select').forEach(o=>{if(this.shouldIncludeElement(o,t)){let c=b.extractElement(o,t);c&&i.push(c)}}),t.customSelectors&&t.customSelectors.forEach(o=>{e.querySelectorAll(o).forEach(c=>{if(this.shouldIncludeElement(c,t)){let l=b.extractElement(c,t);l&&a.push(l)}})}),{buttons:n,links:r,inputs:i,forms:this.extractForms(e,t),clickable:a}}extractForms(e,t){let n=[];return e.querySelectorAll("form").forEach(r=>{if(!this.shouldIncludeElement(r,t))return;let i=[],a=[];r.querySelectorAll('input:not([type="button"]):not([type="submit"]), textarea, select').forEach(u=>{let d=b.extractElement(u,t);d&&i.push(d)}),r.querySelectorAll('button, input[type="button"], input[type="submit"]').forEach(u=>{let d=b.extractElement(u,t);d&&a.push(d)});let o=r.getAttribute("action"),c=r.getAttribute("method"),l={selector:E.generateSelectors(r).css,inputs:i,buttons:a};o&&(l.action=o),c&&(l.method=c),n.push(l)}),n}extractSemanticElements(e,t){let n=[],r=[],i=[],a=[],o=[];return e.querySelectorAll("h1, h2, h3, h4, h5, h6").forEach(c=>{if(this.shouldIncludeElement(c,t)){let l=b.extractElement(c,t);l&&n.push(l)}}),e.querySelectorAll("img").forEach(c=>{if(this.shouldIncludeElement(c,t)){let l=b.extractElement(c,t);l&&r.push(l)}}),e.querySelectorAll("table").forEach(c=>{if(this.shouldIncludeElement(c,t)){let l=b.extractElement(c,t);l&&i.push(l)}}),e.querySelectorAll("ul, ol").forEach(c=>{if(this.shouldIncludeElement(c,t)){let l=b.extractElement(c,t);l&&a.push(l)}}),e.querySelectorAll('article, [role="article"]').forEach(c=>{if(this.shouldIncludeElement(c,t)){let l=b.extractElement(c,t);l&&o.push(l)}}),{headings:n,images:r,tables:i,lists:a,articles:o}}extractMetadata(e,t,n){let r=t.querySelectorAll("*"),i=t.querySelectorAll("button, a, input, textarea, select, h1, h2, h3, h4, h5, h6, img, table, ul, ol, article").length,a={totalElements:r.length,extractedElements:i};n.mainContentOnly&&t instanceof Element&&(a.mainContent=E.generateSelectors(t).css);let o=e.documentElement.getAttribute("lang");return o&&(a.language=o),a}shouldIncludeElement(e,t){return!(!t.includeHidden&&!b.isVisible(e)||t.viewportOnly&&!b.isInViewport(e)||t.filter&&!b.passesFilter(e,t.filter))}detectErrors(e){return[".error",".alert-danger",'[role="alert"]',".error-message"].some(t=>{let n=e.querySelector(t);return n?b.isVisible(n):!1})}detectLoading(e){return[".loading",".spinner",'[aria-busy="true"]',".loader"].some(t=>{let n=e.querySelector(t);return n?b.isVisible(n):!1})}detectModals(e){return['[role="dialog"]',".modal",".popup",".overlay"].some(t=>{let n=e.querySelector(t);return n?b.isVisible(n):!1})}getFocusedElement(e){let t=e.activeElement;if(t&&t!==e.body)return E.generateSelectors(t).css}static extractInteractive(e,t={}){return new O({...t,mode:"interactive"}).extract(e)}static extractFull(e,t={}){return new O({...t,mode:"full"}).extract(e)}static extractFromElement(e,t="interactive",n={}){return new O({...n,mode:t}).extract(e)}}}));G();var gt=new Set(["id","data-testid","role-aria","name","class-path","css-path"]);function K(s){let e=s.trim();return e.startsWith("/")||e.startsWith("(")||e.startsWith("./")}function pt(s){let e=s.selector.candidates;if(e&&e.length>0){let n=null;for(let r of e)gt.has(r.type)&&(!r.value||K(r.value)||(!n||r.score>n.score)&&(n=r));if(n)return n.value}let t=s.selector.css;return t&&!K(t)?t:null}function xt(s){var n;let e=s.tag.toLowerCase(),t=(n=s.interaction.role)!=null?n:s.attributes.role;return e==="a"&&(s.interaction.nav||s.attributes.href!=null)?"navigable":e==="input"||e==="select"||e==="textarea"||t==="textbox"||t==="combobox"||t==="listbox"||t==="spinbutton"||s.interaction.change&&!s.interaction.click?"input":e==="button"||t==="button"||s.interaction.click||s.interaction.submit?"clickable":"static"}function bt(s){let e={...s.attributes},t=s.interaction.role;return t&&!e.role&&(e.role=t),e}function yt(s,e){var n,r;return e?[s.selector.css,s.selector.xpath,s.context.nearestForm,s.context.nearestSection,s.context.nearestMain,s.context.nearestNav,...(r=(n=s.selector.candidates)==null?void 0:n.map(i=>i.value))!=null?r:[],...s.context.parentChain].some(i=>!!i&&i.includes(e)):!1}function Y(s,e={}){var l,u,d;let t=(l=e.includeSemantic)!=null?l:!0,n=(u=e.excludeSelector)!=null?u:".persona-host",r=(d=e.maxTextLength)!=null?d:200,i=[s.interactive.buttons,s.interactive.links,s.interactive.inputs,s.interactive.clickable];t&&s.semantic&&i.push(s.semantic.headings,s.semantic.images,s.semantic.tables,s.semantic.lists,s.semantic.articles);let a=[],o=new Set,c=f=>{var g,p,m;if(yt(f,n))return!0;let h=pt(f);if(h&&!o.has(h)&&(o.add(h),a.push({selector:h,tagName:f.tag.toLowerCase(),text:((g=f.text)!=null?g:"").trim().substring(0,r),role:(m=(p=f.interaction.role)!=null?p:f.attributes.role)!=null?m:null,interactivity:xt(f),attributes:bt(f)}),e.maxElements&&a.length>=e.maxElements))return!1;if(f.children){for(let x of f.children)if(!c(x))return!1}return!0};for(let f of i)if(f){for(let h of f)if(!c(h))return a}return a}var q=100;function J(s,e={}){var i;if(s.length===0)return"No page elements found.";let t=(i=e.mode)!=null?i:"structured",n=[];if(t==="structured"){let a=s.map(o=>o.formattedSummary).filter(o=>!!o&&o.length>0);a.length>0&&n.push(`Structured summaries:
10
+ ${a.map(o=>`- ${o.split(`
11
+ `).join(`
12
+ `)}`).join(`
13
+ `)}`)}let r={clickable:[],navigable:[],input:[],static:[]};for(let a of s)t==="structured"&&a.formattedSummary||r[a.interactivity].push(a);if(r.clickable.length>0){let a=r.clickable.map(o=>`- ${o.selector}: "${o.text.substring(0,q)}" (clickable)`);n.push(`Interactive elements:
14
+ ${a.join(`
15
+ `)}`)}if(r.navigable.length>0){let a=r.navigable.map(o=>`- ${o.selector}${o.attributes.href?`[href="${o.attributes.href}"]`:""}: "${o.text.substring(0,q)}" (navigable)`);n.push(`Navigation links:
16
+ ${a.join(`
17
+ `)}`)}if(r.input.length>0){let a=r.input.map(o=>`- ${o.selector}${o.attributes.type?`[type="${o.attributes.type}"]`:""}: "${o.text.substring(0,q)}" (input)`);n.push(`Form inputs:
18
+ ${a.join(`
19
+ `)}`)}if(r.static.length>0){let a=r.static.map(o=>`- ${o.selector}: "${o.text.substring(0,q)}"`);n.push(`Content:
20
+ ${a.join(`
21
+ `)}`)}return n.join(`
4
22
 
5
- // src/vendor/smart-dom-reader/index.js
6
- var __defProp2 = Object.defineProperty;
7
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
8
- var __getOwnPropNames = Object.getOwnPropertyNames;
9
- var __hasOwnProp = Object.prototype.hasOwnProperty;
10
- var __esmMin = (fn, res) => () => (fn && (res = fn(fn = 0)), res);
11
- var __exportAll = (all, no_symbols) => {
12
- let target = {};
13
- for (var name in all) __defProp2(target, name, {
14
- get: all[name],
15
- enumerable: true
16
- });
17
- if (!no_symbols) __defProp2(target, Symbol.toStringTag, { value: "Module" });
18
- return target;
19
- };
20
- var __copyProps = (to, from, except, desc) => {
21
- if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
22
- key = keys[i];
23
- if (!__hasOwnProp.call(to, key) && key !== except) __defProp2(to, key, {
24
- get: ((k) => from[k]).bind(null, key),
25
- enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
26
- });
27
- }
28
- return to;
29
- };
30
- var __toCommonJS = (mod) => __hasOwnProp.call(mod, "module.exports") ? mod["module.exports"] : __copyProps(__defProp2({}, "__esModule", { value: true }), mod);
31
- var __require = void 0;
32
- var ContentDetection;
33
- var init_content_detection = __esmMin((() => {
34
- ContentDetection = class ContentDetection2 {
35
- /**
36
- * Find the main content area of a page
37
- * Inspired by dom-to-semantic-markdown's approach
38
- */
39
- static findMainContent(doc) {
40
- const mainElement = doc.querySelector('main, [role="main"]');
41
- if (mainElement) return mainElement;
42
- if (!doc.body) return doc.documentElement;
43
- return ContentDetection2.detectMainContent(doc.body);
44
- }
45
- /**
46
- * Detect main content using scoring algorithm
47
- */
48
- static detectMainContent(rootElement) {
49
- const candidates = [];
50
- ContentDetection2.collectCandidates(rootElement, candidates, 15);
51
- if (candidates.length === 0) return rootElement;
52
- candidates.sort((a, b) => ContentDetection2.calculateContentScore(b) - ContentDetection2.calculateContentScore(a));
53
- let bestCandidate = candidates[0];
54
- for (let i = 1; i < candidates.length; i++) {
55
- const candidate = candidates[i];
56
- if (!candidates.some((other, j) => j !== i && other.contains(candidate)) && ContentDetection2.calculateContentScore(candidate) > ContentDetection2.calculateContentScore(bestCandidate)) bestCandidate = candidate;
57
- }
58
- return bestCandidate;
59
- }
60
- /**
61
- * Collect content candidates
62
- */
63
- static collectCandidates(element, candidates, minScore) {
64
- if (ContentDetection2.calculateContentScore(element) >= minScore) candidates.push(element);
65
- Array.from(element.children).forEach((child) => {
66
- ContentDetection2.collectCandidates(child, candidates, minScore);
67
- });
68
- }
69
- /**
70
- * Calculate content score for an element
71
- */
72
- static calculateContentScore(element) {
73
- var _a;
74
- let score = 0;
75
- const semanticClasses = [
76
- "article",
77
- "content",
78
- "main-container",
79
- "main",
80
- "main-content",
81
- "post",
82
- "entry"
83
- ];
84
- const semanticIds = [
85
- "content",
86
- "main",
87
- "article",
88
- "post",
89
- "entry"
90
- ];
91
- semanticClasses.forEach((cls) => {
92
- if (element.classList.contains(cls)) score += 10;
93
- });
94
- semanticIds.forEach((id) => {
95
- var _a2;
96
- if ((_a2 = element.id) == null ? void 0 : _a2.toLowerCase().includes(id)) score += 10;
97
- });
98
- const tag = element.tagName.toLowerCase();
99
- if ([
100
- "article",
101
- "main",
102
- "section"
103
- ].includes(tag)) score += 8;
104
- const paragraphs = element.getElementsByTagName("p").length;
105
- score += Math.min(paragraphs * 2, 10);
106
- const headings = element.querySelectorAll("h1, h2, h3").length;
107
- score += Math.min(headings * 3, 9);
108
- const textLength = ((_a = element.textContent) == null ? void 0 : _a.trim().length) || 0;
109
- if (textLength > 300) score += Math.min(Math.floor(textLength / 300) * 2, 10);
110
- const linkDensity = ContentDetection2.calculateLinkDensity(element);
111
- if (linkDensity < 0.3) score += 5;
112
- else if (linkDensity > 0.5) score -= 5;
113
- if (element.hasAttribute("data-main") || element.hasAttribute("data-content") || element.hasAttribute("itemprop")) score += 8;
114
- const role = element.getAttribute("role");
115
- if (role === "main" || role === "article") score += 10;
116
- if (element.matches("aside, nav, header, footer, .sidebar, .navigation, .menu, .ad, .advertisement")) score -= 10;
117
- if (element.getElementsByTagName("form").length > 2) score -= 5;
118
- return Math.max(0, score);
119
- }
120
- /**
121
- * Calculate link density in an element
122
- */
123
- static calculateLinkDensity(element) {
124
- var _a, _b;
125
- const links = element.getElementsByTagName("a");
126
- let linkTextLength = 0;
127
- for (const link of Array.from(links)) linkTextLength += ((_a = link.textContent) == null ? void 0 : _a.length) || 0;
128
- const totalTextLength = ((_b = element.textContent) == null ? void 0 : _b.length) || 1;
129
- return linkTextLength / totalTextLength;
130
- }
131
- /**
132
- * Check if an element is likely navigation
133
- */
134
- static isNavigation(element) {
135
- if (element.tagName.toLowerCase() === "nav" || element.getAttribute("role") === "navigation") return true;
136
- const navPatterns = [
137
- /nav/i,
138
- /menu/i,
139
- /sidebar/i,
140
- /toolbar/i
141
- ];
142
- const classesAndId = `${element.className} ${element.id}`.toLowerCase();
143
- return navPatterns.some((pattern) => pattern.test(classesAndId));
144
- }
145
- /**
146
- * Check if element is likely supplementary content
147
- */
148
- static isSupplementary(element) {
149
- if (element.tagName.toLowerCase() === "aside" || element.getAttribute("role") === "complementary") return true;
150
- const supplementaryPatterns = [
151
- /sidebar/i,
152
- /widget/i,
153
- /related/i,
154
- /advertisement/i,
155
- /social/i
156
- ];
157
- const classesAndId = `${element.className} ${element.id}`.toLowerCase();
158
- return supplementaryPatterns.some((pattern) => pattern.test(classesAndId));
159
- }
160
- /**
161
- * Detect page landmarks
162
- */
163
- static detectLandmarks(doc) {
164
- const landmarks = {
165
- navigation: [],
166
- main: [],
167
- complementary: [],
168
- contentinfo: [],
169
- banner: [],
170
- search: [],
171
- form: [],
172
- region: []
173
- };
174
- for (const [landmark, selector] of Object.entries({
175
- navigation: 'nav, [role="navigation"]',
176
- main: 'main, [role="main"]',
177
- complementary: 'aside, [role="complementary"]',
178
- contentinfo: 'footer, [role="contentinfo"]',
179
- banner: 'header, [role="banner"]',
180
- search: '[role="search"]',
181
- form: 'form[aria-label], form[aria-labelledby], [role="form"]',
182
- region: 'section[aria-label], section[aria-labelledby], [role="region"]'
183
- })) {
184
- const elements = doc.querySelectorAll(selector);
185
- landmarks[landmark] = Array.from(elements);
186
- }
187
- return landmarks;
188
- }
189
- };
190
- }));
191
- var SelectorGenerator;
192
- var init_selectors = __esmMin((() => {
193
- SelectorGenerator = class SelectorGenerator2 {
194
- /**
195
- * Generate multiple selector strategies for an element
196
- */
197
- static generateSelectors(element) {
198
- var _a;
199
- const doc = element.ownerDocument || document;
200
- const candidates = [];
201
- if (element.id && SelectorGenerator2.isUniqueId(element.id, doc)) candidates.push({
202
- type: "id",
203
- value: `#${CSS.escape(element.id)}`,
204
- score: 100
205
- });
206
- const testId = SelectorGenerator2.getDataTestId(element);
207
- if (testId) {
208
- const v = `[data-testid="${CSS.escape(testId)}"]`;
209
- candidates.push({
210
- type: "data-testid",
211
- value: v,
212
- score: 90 + (SelectorGenerator2.isUniqueSelectorSafe(v, doc) ? 5 : 0)
213
- });
214
- }
215
- const role = element.getAttribute("role");
216
- const aria = element.getAttribute("aria-label");
217
- if (role && aria) {
218
- const v = `[role="${CSS.escape(role)}"][aria-label="${CSS.escape(aria)}"]`;
219
- candidates.push({
220
- type: "role-aria",
221
- value: v,
222
- score: 85 + (SelectorGenerator2.isUniqueSelectorSafe(v, doc) ? 5 : 0)
223
- });
224
- }
225
- const nameAttr = element.getAttribute("name");
226
- if (nameAttr) {
227
- const v = `[name="${CSS.escape(nameAttr)}"]`;
228
- candidates.push({
229
- type: "name",
230
- value: v,
231
- score: 78 + (SelectorGenerator2.isUniqueSelectorSafe(v, doc) ? 5 : 0)
232
- });
233
- }
234
- const pathCss = SelectorGenerator2.generateCSSSelector(element, doc);
235
- const structuralPenalty = (pathCss.match(/:nth-child\(/g) || []).length * 10;
236
- const classBonus = pathCss.includes(".") ? 8 : 0;
237
- const pathScore = Math.max(0, 70 + classBonus - structuralPenalty);
238
- candidates.push({
239
- type: "class-path",
240
- value: pathCss,
241
- score: pathScore
242
- });
243
- const xpath = SelectorGenerator2.generateXPath(element, doc);
244
- candidates.push({
245
- type: "xpath",
246
- value: xpath,
247
- score: 40
248
- });
249
- const textBased = SelectorGenerator2.generateTextBasedSelector(element);
250
- if (textBased) candidates.push({
251
- type: "text",
252
- value: textBased,
253
- score: 30
254
- });
255
- candidates.sort((a, b) => b.score - a.score);
256
- const selector = {
257
- css: ((_a = candidates.find((c) => c.type !== "xpath" && c.type !== "text")) == null ? void 0 : _a.value) || pathCss,
258
- xpath,
259
- candidates
260
- };
261
- if (textBased) selector.textBased = textBased;
262
- if (testId) selector.dataTestId = testId;
263
- if (aria) selector.ariaLabel = aria;
264
- return selector;
265
- }
266
- /**
267
- * Generate a unique CSS selector for an element
268
- */
269
- static generateCSSSelector(element, doc) {
270
- var _a;
271
- if (element.id && SelectorGenerator2.isUniqueId(element.id, doc)) return `#${CSS.escape(element.id)}`;
272
- const testId = SelectorGenerator2.getDataTestId(element);
273
- if (testId) return `[data-testid="${CSS.escape(testId)}"]`;
274
- const path = [];
275
- let current = element;
276
- while (current && current.nodeType === Node.ELEMENT_NODE) {
277
- let selector = current.nodeName.toLowerCase();
278
- if (current.id && SelectorGenerator2.isUniqueId(current.id, doc)) {
279
- selector = `#${CSS.escape(current.id)}`;
280
- path.unshift(selector);
281
- break;
282
- }
283
- const classes = SelectorGenerator2.getMeaningfulClasses(current);
284
- if (classes.length > 0) selector += `.${classes.map((c) => CSS.escape(c)).join(".")}`;
285
- const siblings = (_a = current.parentElement) == null ? void 0 : _a.children;
286
- if (siblings && siblings.length > 1) {
287
- const index = Array.from(siblings).indexOf(current);
288
- if (index > 0 || !SelectorGenerator2.isUniqueSelector(selector, current.parentElement)) selector += `:nth-child(${index + 1})`;
289
- }
290
- path.unshift(selector);
291
- current = current.parentElement;
292
- }
293
- return SelectorGenerator2.optimizePath(path, element, doc);
294
- }
295
- /**
296
- * Generate XPath for an element
297
- */
298
- static generateXPath(element, doc) {
299
- var _a;
300
- if (element.id && SelectorGenerator2.isUniqueId(element.id, doc)) return `//*[@id="${element.id}"]`;
301
- const path = [];
302
- let current = element;
303
- while (current && current.nodeType === Node.ELEMENT_NODE) {
304
- const tagName = current.nodeName.toLowerCase();
305
- if (current.id && SelectorGenerator2.isUniqueId(current.id, doc)) {
306
- path.unshift(`//*[@id="${current.id}"]`);
307
- break;
308
- }
309
- let xpath = tagName;
310
- const siblings = (_a = current.parentElement) == null ? void 0 : _a.children;
311
- if (siblings) {
312
- const sameTagSiblings = Array.from(siblings).filter((s) => s.nodeName.toLowerCase() === tagName);
313
- if (sameTagSiblings.length > 1) {
314
- const index = sameTagSiblings.indexOf(current) + 1;
315
- xpath += `[${index}]`;
316
- }
317
- }
318
- path.unshift(xpath);
319
- current = current.parentElement;
320
- }
321
- return `//${path.join("/")}`;
322
- }
323
- /**
324
- * Generate a text-based selector for buttons and links
325
- */
326
- static generateTextBasedSelector(element) {
327
- var _a;
328
- const text = (_a = element.textContent) == null ? void 0 : _a.trim();
329
- if (!text || text.length > 50) return void 0;
330
- const tag = element.nodeName.toLowerCase();
331
- if ([
332
- "button",
333
- "a",
334
- "label"
335
- ].includes(tag)) return `${tag}:contains("${text.replace(/['"\\]/g, "\\$&")}")`;
336
- }
337
- /**
338
- * Get data-testid or similar attributes
339
- */
340
- static getDataTestId(element) {
341
- return element.getAttribute("data-testid") || element.getAttribute("data-test-id") || element.getAttribute("data-test") || element.getAttribute("data-cy") || void 0;
342
- }
343
- /**
344
- * Check if an ID is unique in the document
345
- */
346
- static isUniqueId(id, doc) {
347
- return doc.querySelectorAll(`#${CSS.escape(id)}`).length === 1;
348
- }
349
- /**
350
- * Check if a selector is unique within a container
351
- */
352
- static isUniqueSelector(selector, container) {
353
- try {
354
- return container.querySelectorAll(selector).length === 1;
355
- } catch {
356
- return false;
357
- }
358
- }
359
- static isUniqueSelectorSafe(selector, doc) {
360
- try {
361
- return doc.querySelectorAll(selector).length === 1;
362
- } catch {
363
- return false;
364
- }
365
- }
366
- /**
367
- * Get meaningful classes (filtering out utility classes)
368
- */
369
- static getMeaningfulClasses(element) {
370
- const classes = Array.from(element.classList);
371
- const utilityPatterns = [
372
- /^(p|m|w|h|text|bg|border|flex|grid|col|row)-/,
373
- /^(xs|sm|md|lg|xl|2xl):/,
374
- /^(hover|focus|active|disabled|checked):/,
375
- /^js-/,
376
- /^is-/,
377
- /^has-/
378
- ];
379
- return classes.filter((cls) => {
380
- if (cls.length < 3) return false;
381
- return !utilityPatterns.some((pattern) => pattern.test(cls));
382
- }).slice(0, 2);
383
- }
384
- /**
385
- * Optimize the selector path by removing unnecessary parts
386
- */
387
- static optimizePath(path, element, doc) {
388
- for (let i = 0; i < path.length - 1; i++) {
389
- const shortPath = path.slice(i).join(" > ");
390
- try {
391
- const matches = doc.querySelectorAll(shortPath);
392
- if (matches.length === 1 && matches[0] === element) return shortPath;
393
- } catch {
394
- }
395
- }
396
- return path.join(" > ");
397
- }
398
- /**
399
- * Get a human-readable path description
400
- */
401
- static getContextPath(element) {
402
- var _a;
403
- const path = [];
404
- let current = element;
405
- let depth = 0;
406
- const maxDepth = 5;
407
- while (current && current !== ((_a = element.ownerDocument) == null ? void 0 : _a.body) && depth < maxDepth) {
408
- const tag = current.nodeName.toLowerCase();
409
- let descriptor = tag;
410
- if (current.id) descriptor = `${tag}#${current.id}`;
411
- else if (current.className && typeof current.className === "string") {
412
- const firstClass = current.className.split(" ")[0];
413
- if (firstClass) descriptor = `${tag}.${firstClass}`;
414
- }
415
- const role = current.getAttribute("role");
416
- if (role) descriptor += `[role="${role}"]`;
417
- path.unshift(descriptor);
418
- current = current.parentElement;
419
- depth++;
420
- }
421
- return path;
422
- }
423
- };
424
- }));
425
- var DOMTraversal;
426
- var init_traversal = __esmMin((() => {
427
- var _a;
428
- init_selectors();
429
- DOMTraversal = (_a = class {
430
- /**
431
- * Check if element is visible
432
- */
433
- static isVisible(element, computedStyle) {
434
- var _a2, _b;
435
- const rect = element.getBoundingClientRect();
436
- const style = computedStyle || ((_b = (_a2 = element.ownerDocument) == null ? void 0 : _a2.defaultView) == null ? void 0 : _b.getComputedStyle(element));
437
- if (!style) return false;
438
- return !!(rect.width > 0 && rect.height > 0 && style.display !== "none" && style.visibility !== "hidden" && style.opacity !== "0" && element.offsetParent !== null);
439
- }
440
- /**
441
- * Check if element is in viewport
442
- */
443
- static isInViewport(element, viewport) {
444
- var _a2, _b, _c, _d;
445
- const rect = element.getBoundingClientRect();
446
- const view = viewport || {
447
- width: ((_b = (_a2 = element.ownerDocument) == null ? void 0 : _a2.defaultView) == null ? void 0 : _b.innerWidth) || 0,
448
- height: ((_d = (_c = element.ownerDocument) == null ? void 0 : _c.defaultView) == null ? void 0 : _d.innerHeight) || 0
449
- };
450
- return rect.top < view.height && rect.bottom > 0 && rect.left < view.width && rect.right > 0;
451
- }
452
- /**
453
- * Check if element passes filter criteria
454
- */
455
- static passesFilter(element, filter) {
456
- var _a2, _b, _c, _d, _e, _f, _g, _h, _i, _j;
457
- if (!filter) return true;
458
- const htmlElement = element;
459
- if ((_a2 = filter.excludeSelectors) == null ? void 0 : _a2.length) {
460
- for (const selector of filter.excludeSelectors) if (element.matches(selector)) return false;
461
- }
462
- if ((_b = filter.includeSelectors) == null ? void 0 : _b.length) {
463
- let matches = false;
464
- for (const selector of filter.includeSelectors) if (element.matches(selector)) {
465
- matches = true;
466
- break;
467
- }
468
- if (!matches) return false;
469
- }
470
- if (((_c = filter.tags) == null ? void 0 : _c.length) && !filter.tags.includes(element.tagName.toLowerCase())) return false;
471
- const textContent = ((_d = htmlElement.textContent) == null ? void 0 : _d.toLowerCase()) || "";
472
- if ((_e = filter.textContains) == null ? void 0 : _e.length) {
473
- let hasText = false;
474
- for (const text of filter.textContains) if (textContent.includes(text.toLowerCase())) {
475
- hasText = true;
476
- break;
477
- }
478
- if (!hasText) return false;
479
- }
480
- if ((_f = filter.textMatches) == null ? void 0 : _f.length) {
481
- let matches = false;
482
- for (const pattern of filter.textMatches) if (pattern.test(textContent)) {
483
- matches = true;
484
- break;
485
- }
486
- if (!matches) return false;
487
- }
488
- if ((_g = filter.hasAttributes) == null ? void 0 : _g.length) {
489
- for (const attr of filter.hasAttributes) if (!element.hasAttribute(attr)) return false;
490
- }
491
- if (filter.attributeValues) for (const [attr, value] of Object.entries(filter.attributeValues)) {
492
- const attrValue = element.getAttribute(attr);
493
- if (!attrValue) return false;
494
- if (typeof value === "string") {
495
- if (attrValue !== value) return false;
496
- } else if (value instanceof RegExp) {
497
- if (!value.test(attrValue)) return false;
498
- }
499
- }
500
- if ((_h = filter.withinSelectors) == null ? void 0 : _h.length) {
501
- let isWithin = false;
502
- for (const selector of filter.withinSelectors) if (element.closest(selector)) {
503
- isWithin = true;
504
- break;
505
- }
506
- if (!isWithin) return false;
507
- }
508
- if ((_i = filter.interactionTypes) == null ? void 0 : _i.length) {
509
- const interaction = _a.getInteractionInfo(element);
510
- let hasInteraction = false;
511
- for (const type of filter.interactionTypes) if (interaction[type]) {
512
- hasInteraction = true;
513
- break;
514
- }
515
- if (!hasInteraction) return false;
516
- }
517
- if (filter.nearText) {
518
- const parent = element.parentElement;
519
- if (!parent || !((_j = parent.textContent) == null ? void 0 : _j.toLowerCase().includes(filter.nearText.toLowerCase()))) return false;
520
- }
521
- return true;
522
- }
523
- /**
524
- * Extract element information
525
- */
526
- static extractElement(element, options, depth = 0) {
527
- if (options.maxDepth && depth > options.maxDepth) return null;
528
- if (!options.includeHidden && !_a.isVisible(element)) return null;
529
- if (options.viewportOnly && !_a.isInViewport(element)) return null;
530
- if (!_a.passesFilter(element, options.filter)) return null;
531
- const htmlElement = element;
532
- const extracted = {
533
- tag: element.tagName.toLowerCase(),
534
- text: _a.getElementText(element, options),
535
- selector: SelectorGenerator.generateSelectors(element),
536
- attributes: _a.getRelevantAttributes(element, options),
537
- context: _a.getElementContext(element),
538
- interaction: _a.getInteractionInfo(element)
539
- };
540
- if (options.mode === "full" && _a.isSemanticContainer(element)) {
541
- const children = [];
542
- if (options.includeShadowDOM && htmlElement.shadowRoot) {
543
- const shadowChildren = _a.extractChildren(htmlElement.shadowRoot, options, depth + 1);
544
- children.push(...shadowChildren);
545
- }
546
- const regularChildren = _a.extractChildren(element, options, depth + 1);
547
- children.push(...regularChildren);
548
- if (children.length > 0) extracted.children = children;
549
- }
550
- return extracted;
551
- }
552
- /**
553
- * Extract children elements
554
- */
555
- static extractChildren(container, options, depth) {
556
- const children = [];
557
- const elements = container.querySelectorAll("*");
558
- for (const child of Array.from(elements)) {
559
- if (_a.hasExtractedAncestor(child, elements)) continue;
560
- const extracted = _a.extractElement(child, options, depth);
561
- if (extracted) children.push(extracted);
562
- }
563
- return children;
564
- }
565
- /**
566
- * Check if element has an ancestor that was already extracted
567
- */
568
- static hasExtractedAncestor(element, extractedElements) {
569
- let parent = element.parentElement;
570
- while (parent) {
571
- if (Array.from(extractedElements).includes(parent)) return true;
572
- parent = parent.parentElement;
573
- }
574
- return false;
575
- }
576
- /**
577
- * Get relevant attributes for an element
578
- */
579
- static getRelevantAttributes(element, options) {
580
- var _a2, _b;
581
- const relevant = [
582
- "id",
583
- "class",
584
- "name",
585
- "type",
586
- "value",
587
- "placeholder",
588
- "href",
589
- "src",
590
- "alt",
591
- "title",
592
- "action",
593
- "method",
594
- "aria-label",
595
- "aria-describedby",
596
- "aria-controls",
597
- "role",
598
- "disabled",
599
- "readonly",
600
- "required",
601
- "checked",
602
- "min",
603
- "max",
604
- "pattern",
605
- "step",
606
- "autocomplete",
607
- "data-testid",
608
- "data-test",
609
- "data-cy"
610
- ];
611
- const attributes = {};
612
- const attrTruncate = (_a2 = options.attributeTruncateLength) != null ? _a2 : 100;
613
- const dataAttrTruncate = (_b = options.dataAttributeTruncateLength) != null ? _b : 50;
614
- for (const attr of relevant) {
615
- const value = element.getAttribute(attr);
616
- if (value) attributes[attr] = value.length > attrTruncate ? `${value.substring(0, attrTruncate)}...` : value;
617
- }
618
- for (const attr of element.attributes) if (attr.name.startsWith("data-") && !relevant.includes(attr.name)) attributes[attr.name] = attr.value.length > dataAttrTruncate ? `${attr.value.substring(0, dataAttrTruncate)}...` : attr.value;
619
- return attributes;
620
- }
621
- /**
622
- * Get element context information
623
- */
624
- static getElementContext(element) {
625
- const context = { parentChain: SelectorGenerator.getContextPath(element) };
626
- const form = element.closest("form");
627
- if (form) context.nearestForm = SelectorGenerator.generateSelectors(form).css;
628
- const section = element.closest('section, [role="region"]');
629
- if (section) context.nearestSection = SelectorGenerator.generateSelectors(section).css;
630
- const main = element.closest('main, [role="main"]');
631
- if (main) context.nearestMain = SelectorGenerator.generateSelectors(main).css;
632
- const nav = element.closest('nav, [role="navigation"]');
633
- if (nav) context.nearestNav = SelectorGenerator.generateSelectors(nav).css;
634
- return context;
635
- }
636
- /**
637
- * Get interaction information for an element (compact format)
638
- */
639
- static getInteractionInfo(element) {
640
- const htmlElement = element;
641
- const interaction = {};
642
- if (!!(htmlElement.onclick || element.getAttribute("onclick") || element.matches('button, a[href], [role="button"], [tabindex]:not([tabindex="-1"])'))) interaction.click = true;
643
- if (!!(htmlElement.onchange || element.getAttribute("onchange") || element.matches("input, select, textarea"))) interaction.change = true;
644
- if (!!(htmlElement.onsubmit || element.getAttribute("onsubmit") || element.matches("form"))) interaction.submit = true;
645
- if (element.matches('a[href], button[type="submit"]')) interaction.nav = true;
646
- if (htmlElement.hasAttribute("disabled") || htmlElement.getAttribute("aria-disabled") === "true") interaction.disabled = true;
647
- if (!_a.isVisible(element)) interaction.hidden = true;
648
- const ariaRole = element.getAttribute("role");
649
- if (ariaRole) interaction.role = ariaRole;
650
- if (element.matches("input, textarea, select, button")) {
651
- const form = element.form || element.closest("form");
652
- if (form) interaction.form = SelectorGenerator.generateSelectors(form).css;
653
- }
654
- return interaction;
655
- }
656
- /**
657
- * Get text content of an element (limited length)
658
- */
659
- static getElementText(element, options) {
660
- var _a2;
661
- if (element.matches("input, textarea")) {
662
- const input = element;
663
- return input.value || input.placeholder || "";
664
- }
665
- if (element.matches("img")) return element.alt || "";
666
- const text = ((_a2 = element.textContent) == null ? void 0 : _a2.trim()) || "";
667
- const maxLength = options == null ? void 0 : options.textTruncateLength;
668
- if (maxLength && text.length > maxLength) return `${text.substring(0, maxLength)}...`;
669
- return text;
670
- }
671
- /**
672
- * Check if element is a semantic container
673
- */
674
- static isSemanticContainer(element) {
675
- return element.matches('article, section, nav, aside, main, header, footer, form, table, ul, ol, dl, figure, details, dialog, [role="region"], [role="navigation"], [role="main"], [role="complementary"]');
676
- }
677
- /**
678
- * Get interactive elements
679
- */
680
- static getInteractiveElements(container, options) {
681
- const elements = [];
682
- const selector = _a.INTERACTIVE_SELECTORS.join(", ");
683
- const found = container.querySelectorAll(selector);
684
- for (const element of Array.from(found)) {
685
- const extracted = _a.extractElement(element, options);
686
- if (extracted) elements.push(extracted);
687
- }
688
- if (options.customSelectors) for (const customSelector of options.customSelectors) try {
689
- const customFound = container.querySelectorAll(customSelector);
690
- for (const element of Array.from(customFound)) {
691
- const extracted = _a.extractElement(element, options);
692
- if (extracted) elements.push(extracted);
693
- }
694
- } catch (_e) {
695
- console.warn(`Invalid custom selector: ${customSelector}`);
696
- }
697
- return elements;
698
- }
699
- /**
700
- * Get semantic elements (for full mode)
701
- */
702
- static getSemanticElements(container, options) {
703
- const elements = [];
704
- const selector = _a.SEMANTIC_SELECTORS.join(", ");
705
- const found = container.querySelectorAll(selector);
706
- for (const element of Array.from(found)) {
707
- const extracted = _a.extractElement(element, options);
708
- if (extracted) elements.push(extracted);
709
- }
710
- return elements;
711
- }
712
- }, __publicField(_a, "INTERACTIVE_SELECTORS", [
713
- "button",
714
- "a[href]",
715
- 'input:not([type="hidden"])',
716
- "textarea",
717
- "select",
718
- '[role="button"]',
719
- "[onclick]",
720
- '[contenteditable="true"]',
721
- "summary",
722
- '[tabindex]:not([tabindex="-1"])'
723
- ]), __publicField(_a, "SEMANTIC_SELECTORS", [
724
- "h1",
725
- "h2",
726
- "h3",
727
- "h4",
728
- "h5",
729
- "h6",
730
- "article",
731
- "section",
732
- "nav",
733
- "aside",
734
- "main",
735
- "header",
736
- "footer",
737
- "form",
738
- "table",
739
- "ul",
740
- "ol",
741
- "img[alt]",
742
- "figure",
743
- "video",
744
- "audio",
745
- '[role="navigation"]',
746
- '[role="main"]',
747
- '[role="complementary"]',
748
- '[role="contentinfo"]'
749
- ]), _a);
750
- }));
751
- function truncate(text, len) {
752
- const t = (text != null ? text : "").trim();
753
- if (!len || t.length <= len) return t;
754
- const keywords = [
755
- "login",
756
- "log in",
757
- "sign in",
758
- "sign up",
759
- "submit",
760
- "search",
761
- "filter",
762
- "add to cart",
763
- "next",
764
- "continue"
765
- ];
766
- const lower = t.toLowerCase();
767
- const hit = keywords.map((k) => ({
768
- k,
769
- i: lower.indexOf(k)
770
- })).find((x) => x.i > -1);
771
- const head = Math.max(0, Math.floor(len * 0.66));
772
- if (hit && hit.i > head) {
773
- const tailWindow = Math.max(12, len - head - 5);
774
- const start = Math.max(0, hit.i - Math.floor(tailWindow / 2));
775
- const end = Math.min(t.length, start + tailWindow);
776
- return `${t.slice(0, head).trimEnd()} \u2026 ${t.slice(start, end).trim()}\u2026`;
777
- }
778
- const slice = t.slice(0, len);
779
- const lastSpace = slice.lastIndexOf(" ");
780
- return `${lastSpace > 32 ? slice.slice(0, lastSpace) : slice}\u2026`;
781
- }
782
- function bestSelector(el) {
783
- var _a;
784
- return ((_a = el.selector) == null ? void 0 : _a.css) || "";
785
- }
786
- function hashId(input) {
787
- let h = 5381;
788
- for (let i = 0; i < input.length; i++) h = h * 33 ^ input.charCodeAt(i);
789
- return `sec-${(h >>> 0).toString(36)}`;
790
- }
791
- function iconForRegion(key) {
792
- switch (key) {
793
- case "header":
794
- return "\u{1F9ED}";
795
- case "navigation":
796
- return "\u{1F4D1}";
797
- case "main":
798
- return "\u{1F4C4}";
799
- case "sections":
800
- return "\u{1F5C2}\uFE0F";
801
- case "sidebar":
802
- return "\u{1F4DA}";
803
- case "footer":
804
- return "\u{1F53B}";
805
- case "modals":
806
- return "\u{1F4AC}";
807
- default:
808
- return "\u{1F539}";
809
- }
810
- }
811
- function elementLine(el, opts) {
812
- var _a, _b, _c, _d, _e;
813
- const txt = truncate(el.text || ((_a = el.attributes) == null ? void 0 : _a.ariaLabel), (_b = opts == null ? void 0 : opts.maxTextLength) != null ? _b : 80);
814
- const sel = bestSelector(el);
815
- const tag = el.tag.toLowerCase();
816
- const action = ((_c = el.interaction) == null ? void 0 : _c.submit) ? "submit" : ((_d = el.interaction) == null ? void 0 : _d.click) ? "click" : ((_e = el.interaction) == null ? void 0 : _e.change) ? "change" : void 0;
817
- const actionText = action ? ` (${action})` : "";
818
- return `- ${tag.toUpperCase()}: ${txt || "(no text)"} \u2192 \`${sel}\`${actionText}`;
819
- }
820
- function selectorQualitySummary(inter) {
821
- const all = [];
822
- all.push(...inter.buttons.map((e) => {
823
- var _a;
824
- return ((_a = e.selector) == null ? void 0 : _a.css) || "";
825
- }));
826
- all.push(...inter.links.map((e) => {
827
- var _a;
828
- return ((_a = e.selector) == null ? void 0 : _a.css) || "";
829
- }));
830
- all.push(...inter.inputs.map((e) => {
831
- var _a;
832
- return ((_a = e.selector) == null ? void 0 : _a.css) || "";
833
- }));
834
- all.push(...inter.clickable.map((e) => {
835
- var _a;
836
- return ((_a = e.selector) == null ? void 0 : _a.css) || "";
837
- }));
838
- const total = all.length || 1;
839
- const idCount = all.filter((s) => s.startsWith("#")).length;
840
- const testIdCount = all.filter((s) => /\[data-testid=/.test(s)).length;
841
- const nthCount = all.filter((s) => /:nth-child\(/.test(s)).length;
842
- const stable = idCount + testIdCount;
843
- return `Selector quality: ${Math.round(stable / total * 100)}% stable (ID/data-testid), ${Math.round(nthCount / total * 100)}% structural (:nth-child)`;
844
- }
845
- function renderInteractive(inter, opts) {
846
- var _a, _b;
847
- const parts = [];
848
- const limit = (arr) => typeof (opts == null ? void 0 : opts.maxElements) === "number" ? arr.slice(0, opts.maxElements) : arr;
849
- if (inter.buttons.length) {
850
- parts.push("Buttons:");
851
- for (const el of limit(inter.buttons)) parts.push(elementLine(el, opts));
852
- }
853
- if (inter.links.length) {
854
- parts.push("Links:");
855
- for (const el of limit(inter.links)) parts.push(elementLine(el, opts));
856
- }
857
- if (inter.inputs.length) {
858
- parts.push("Inputs:");
859
- for (const el of limit(inter.inputs)) parts.push(elementLine(el, opts));
860
- }
861
- if (inter.clickable.length) {
862
- parts.push("Other Clickable:");
863
- for (const el of limit(inter.clickable)) parts.push(elementLine(el, opts));
864
- }
865
- if (inter.forms.length) {
866
- parts.push("Forms:");
867
- for (const f of limit(inter.forms)) parts.push(`- FORM: action=${(_a = f.action) != null ? _a : "-"} method=${(_b = f.method) != null ? _b : "-"} \u2192 \`${f.selector}\``);
868
- }
869
- return parts.join("\n");
870
- }
871
- function renderRegionInfo(region) {
872
- var _a, _b;
873
- const icon = iconForRegion("region");
874
- const id = hashId(`${region.selector}|${(_a = region.label) != null ? _a : ""}|${(_b = region.role) != null ? _b : ""}`);
875
- const label = region.label ? ` ${region.label}` : "";
876
- const stats = [];
877
- if (region.buttonCount) stats.push(`${region.buttonCount} buttons`);
878
- if (region.linkCount) stats.push(`${region.linkCount} links`);
879
- if (region.inputCount) stats.push(`${region.inputCount} inputs`);
880
- if (region.textPreview) stats.push(`\u201C${truncate(region.textPreview, 80)}\u201D`);
881
- const statsLine = stats.length ? ` \u2014 ${stats.join(", ")}` : "";
882
- return `${icon} ${label} \u2192 \`${region.selector}\` [${id}]${statsLine}`;
883
- }
884
- function wrapXml(body, meta, type = "section") {
885
- return `<page ${[(meta == null ? void 0 : meta.title) ? `title="${escapeXml(meta == null ? void 0 : meta.title)}"` : null, (meta == null ? void 0 : meta.url) ? `url="${escapeXml(meta == null ? void 0 : meta.url)}"` : null].filter(Boolean).join(" ")}>
886
- <${type}><![CDATA[
887
- ${body}
888
- ]]></${type}>
889
- </page>`;
890
- }
891
- function escapeXml(s) {
892
- return s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
893
- }
894
- function capitalize(s) {
895
- return s.charAt(0).toUpperCase() + s.slice(1);
896
- }
897
- var MarkdownFormatter;
898
- var init_markdown_formatter = __esmMin((() => {
899
- MarkdownFormatter = class {
900
- static structure(overview, _opts = {}, meta) {
901
- var _a, _b, _c;
902
- const lines = [];
903
- lines.push("# Page Outline");
904
- if ((meta == null ? void 0 : meta.title) || (meta == null ? void 0 : meta.url)) {
905
- lines.push(`Title: ${(_a = meta == null ? void 0 : meta.title) != null ? _a : ""}`.trim());
906
- lines.push(`URL: ${(_b = meta == null ? void 0 : meta.url) != null ? _b : ""}`.trim());
907
- }
908
- lines.push("");
909
- const regions = overview.regions;
910
- const entries = [
911
- ["header", regions.header],
912
- ["navigation", regions.navigation],
913
- ["main", regions.main],
914
- ["sections", regions.sections],
915
- ["sidebar", regions.sidebar],
916
- ["footer", regions.footer],
917
- ["modals", regions.modals]
918
- ];
919
- for (const [key, value] of entries) {
920
- if (!value) continue;
921
- const icon = iconForRegion(key);
922
- if (Array.isArray(value)) {
923
- if (!value.length) continue;
924
- lines.push(`## ${icon} ${capitalize(key)}`);
925
- for (const region of value) lines.push(renderRegionInfo(region));
926
- } else {
927
- lines.push(`## ${icon} ${capitalize(key)}`);
928
- lines.push(renderRegionInfo(value));
929
- }
930
- lines.push("");
931
- }
932
- if ((_c = overview.suggestions) == null ? void 0 : _c.length) {
933
- lines.push("## Suggestions");
934
- for (const s of overview.suggestions) lines.push(`- ${s}`);
935
- lines.push("");
936
- }
937
- lines.push("Next: choose a region (by selector or [sectionId]) and call dom_extract_region for actionable details.");
938
- return wrapXml(lines.join("\n"), meta, "outline");
939
- }
940
- static region(result, opts = {}, meta) {
941
- var _a, _b, _c;
942
- const lines = [];
943
- lines.push("# Region Details");
944
- if ((meta == null ? void 0 : meta.title) || (meta == null ? void 0 : meta.url)) {
945
- lines.push(`Title: ${(_a = meta == null ? void 0 : meta.title) != null ? _a : ""}`.trim());
946
- lines.push(`URL: ${(_b = meta == null ? void 0 : meta.url) != null ? _b : ""}`.trim());
947
- }
948
- lines.push("");
949
- const inter = result.interactive;
950
- if (result.page) {
951
- const ps = [
952
- result.page.hasErrors ? "errors: yes" : "errors: no",
953
- result.page.isLoading ? "loading: yes" : "loading: no",
954
- result.page.hasModals ? "modals: yes" : "modals: no"
955
- ];
956
- lines.push(`Page state: ${ps.join(", ")}`);
957
- }
958
- const summary = [];
959
- const count = (arr) => arr ? arr.length : 0;
960
- summary.push(`${count(inter.buttons)} buttons`);
961
- summary.push(`${count(inter.links)} links`);
962
- summary.push(`${count(inter.inputs)} inputs`);
963
- if ((_c = inter.forms) == null ? void 0 : _c.length) summary.push(`${count(inter.forms)} forms`);
964
- lines.push(`Summary: ${summary.join(", ")}`);
965
- lines.push(selectorQualitySummary(inter));
966
- lines.push("");
967
- lines.push(renderInteractive(inter, opts));
968
- lines.push("");
969
- lines.push("Next: write a script using the most stable selectors above. If selectors look unstable, rerun dom_extract_region with higher detail or call dom_extract_content for text context.");
970
- return wrapXml(lines.join("\n"), meta, "section");
971
- }
972
- static content(content, opts = {}, meta) {
973
- var _a, _b, _c, _d, _e, _f, _g, _h, _i;
974
- const lines = [];
975
- lines.push("# Content");
976
- lines.push(`Selector: \`${content.selector}\``);
977
- lines.push("");
978
- if ((_a = content.text.headings) == null ? void 0 : _a.length) {
979
- lines.push("Headings:");
980
- for (const h of content.text.headings) lines.push(`- H${h.level}: ${truncate(h.text, (_b = opts.maxTextLength) != null ? _b : 120)}`);
981
- lines.push("");
982
- }
983
- if ((_c = content.text.paragraphs) == null ? void 0 : _c.length) {
984
- const limit = typeof opts.maxElements === "number" ? opts.maxElements : content.text.paragraphs.length;
985
- lines.push("Paragraphs:");
986
- for (const p of content.text.paragraphs.slice(0, limit)) lines.push(`- ${truncate(p, (_d = opts.maxTextLength) != null ? _d : 200)}`);
987
- lines.push("");
988
- }
989
- if ((_e = content.text.lists) == null ? void 0 : _e.length) {
990
- lines.push("Lists:");
991
- for (const list of content.text.lists) {
992
- lines.push(`- ${list.type.toUpperCase()}:`);
993
- const limit = typeof opts.maxElements === "number" ? opts.maxElements : list.items.length;
994
- for (const item of list.items.slice(0, limit)) lines.push(` - ${truncate(item, (_f = opts.maxTextLength) != null ? _f : 120)}`);
995
- }
996
- lines.push("");
997
- }
998
- if ((_g = content.tables) == null ? void 0 : _g.length) {
999
- lines.push("Tables:");
1000
- for (const t of content.tables) {
1001
- lines.push(`- Headers: ${t.headers.join(" | ")}`);
1002
- const limit = typeof opts.maxElements === "number" ? opts.maxElements : t.rows.length;
1003
- for (const row of t.rows.slice(0, limit)) lines.push(` - ${row.join(" | ")}`);
1004
- }
1005
- lines.push("");
1006
- }
1007
- if ((_h = content.media) == null ? void 0 : _h.length) {
1008
- lines.push("Media:");
1009
- const limit = typeof opts.maxElements === "number" ? opts.maxElements : content.media.length;
1010
- for (const m of content.media.slice(0, limit)) lines.push(`- ${m.type.toUpperCase()}: ${(_i = m.alt) != null ? _i : ""} ${m.src ? `\u2192 ${m.src}` : ""}`.trim());
1011
- lines.push("");
1012
- }
1013
- lines.push("Next: if text is insufficient for targeting, call dom_extract_region for interactive selectors.");
1014
- return wrapXml(lines.join("\n"), meta, "content");
1015
- }
1016
- };
1017
- }));
1018
- function resolveSmartDomReader() {
1019
- if (typeof window !== "undefined") {
1020
- const globalWindow = window;
1021
- const direct = globalWindow.SmartDOMReader;
1022
- if (typeof direct === "function") return direct;
1023
- const namespace = globalWindow.SmartDOMReaderNamespace;
1024
- if (namespace && typeof namespace.SmartDOMReader === "function") return namespace.SmartDOMReader;
1025
- }
1026
- try {
1027
- if (typeof __require === "function") {
1028
- const moduleExports = (init_src(), __toCommonJS(src_exports));
1029
- if (moduleExports && typeof moduleExports.SmartDOMReader === "function") return moduleExports.SmartDOMReader;
1030
- if (moduleExports && typeof moduleExports.default === "function") return moduleExports.default;
1031
- }
1032
- } catch {
1033
- }
1034
- }
1035
- var ProgressiveExtractor;
1036
- var init_progressive = __esmMin((() => {
1037
- init_content_detection();
1038
- init_selectors();
1039
- init_traversal();
1040
- ProgressiveExtractor = class ProgressiveExtractor2 {
1041
- /**
1042
- * Step 1: Extract high-level structural overview
1043
- * This provides a "map" of the page for the AI to understand structure
1044
- */
1045
- static extractStructure(root) {
1046
- const regions = {};
1047
- const header = root.querySelector('header, [role="banner"], .header, #header');
1048
- if (header) regions.header = ProgressiveExtractor2.analyzeRegion(header);
1049
- const navs = root.querySelectorAll('nav, [role="navigation"], .nav, .navigation');
1050
- if (navs.length > 0) regions.navigation = Array.from(navs).map((nav) => ProgressiveExtractor2.analyzeRegion(nav));
1051
- if (root instanceof Document) {
1052
- const main = ContentDetection.findMainContent(root);
1053
- if (main) {
1054
- regions.main = ProgressiveExtractor2.analyzeRegion(main);
1055
- const sections = main.querySelectorAll('section, article, [role="region"]');
1056
- if (sections.length > 0) regions.sections = Array.from(sections).filter((section) => !section.closest("nav, header, footer")).map((section) => ProgressiveExtractor2.analyzeRegion(section));
1057
- }
1058
- } else {
1059
- regions.main = ProgressiveExtractor2.analyzeRegion(root);
1060
- const sections = root.querySelectorAll('section, article, [role="region"]');
1061
- if (sections.length > 0) regions.sections = Array.from(sections).filter((section) => !section.closest("nav, header, footer")).map((section) => ProgressiveExtractor2.analyzeRegion(section));
1062
- }
1063
- const sidebars = root.querySelectorAll('aside, [role="complementary"], .sidebar, #sidebar');
1064
- if (sidebars.length > 0) regions.sidebar = Array.from(sidebars).map((sidebar) => ProgressiveExtractor2.analyzeRegion(sidebar));
1065
- const footer = root.querySelector('footer, [role="contentinfo"], .footer, #footer');
1066
- if (footer) regions.footer = ProgressiveExtractor2.analyzeRegion(footer);
1067
- const modals = root.querySelectorAll('[role="dialog"], .modal, .popup, .overlay');
1068
- const visibleModals = Array.from(modals).filter((modal) => DOMTraversal.isVisible(modal));
1069
- if (visibleModals.length > 0) regions.modals = visibleModals.map((modal) => ProgressiveExtractor2.analyzeRegion(modal));
1070
- const forms = ProgressiveExtractor2.extractFormOverview(root);
1071
- const summary = ProgressiveExtractor2.calculateSummary(root, regions, forms);
1072
- return {
1073
- regions,
1074
- forms,
1075
- summary,
1076
- suggestions: ProgressiveExtractor2.generateSuggestions(regions, summary)
1077
- };
1078
- }
1079
- /**
1080
- * Step 2: Extract detailed information from a specific region
1081
- */
1082
- static extractRegion(selector, doc, options = {}, smartDomReaderCtor) {
1083
- const element = doc.querySelector(selector);
1084
- if (!element) return null;
1085
- const SmartDOMReaderCtor = smartDomReaderCtor != null ? smartDomReaderCtor : resolveSmartDomReader();
1086
- if (!SmartDOMReaderCtor) throw new Error("SmartDOMReader is unavailable. Ensure the Smart DOM Reader module is loaded before calling extractRegion.");
1087
- return new SmartDOMReaderCtor(options).extract(element, options);
1088
- }
1089
- /**
1090
- * Step 3: Extract readable content from a region
1091
- */
1092
- static extractContent(selector, doc, options = {}) {
1093
- const element = doc.querySelector(selector);
1094
- if (!element) return null;
1095
- const result = {
1096
- selector,
1097
- text: {},
1098
- metadata: {
1099
- wordCount: 0,
1100
- hasInteractive: false
1101
- }
1102
- };
1103
- if (options.includeHeadings !== false) {
1104
- const headings = element.querySelectorAll("h1, h2, h3, h4, h5, h6");
1105
- result.text.headings = Array.from(headings).map((h) => ({
1106
- level: Number.parseInt(h.tagName[1], 10),
1107
- text: ProgressiveExtractor2.getTextContent(h, options.maxTextLength)
1108
- }));
1109
- }
1110
- const paragraphs = element.querySelectorAll("p");
1111
- if (paragraphs.length > 0) result.text.paragraphs = Array.from(paragraphs).map((p) => ProgressiveExtractor2.getTextContent(p, options.maxTextLength)).filter((text) => text.length > 0);
1112
- if (options.includeLists !== false) {
1113
- const lists = element.querySelectorAll("ul, ol");
1114
- result.text.lists = Array.from(lists).map((list) => ({
1115
- type: list.tagName.toLowerCase(),
1116
- items: Array.from(list.querySelectorAll("li")).map((li) => ProgressiveExtractor2.getTextContent(li, options.maxTextLength))
1117
- }));
1118
- }
1119
- if (options.includeTables !== false) {
1120
- const tables = element.querySelectorAll("table");
1121
- result.tables = Array.from(tables).map((table) => {
1122
- return {
1123
- headers: Array.from(table.querySelectorAll("th")).map((th) => ProgressiveExtractor2.getTextContent(th)),
1124
- rows: Array.from(table.querySelectorAll("tr")).filter((tr) => tr.querySelector("td")).map((tr) => Array.from(tr.querySelectorAll("td")).map((td) => ProgressiveExtractor2.getTextContent(td)))
1125
- };
1126
- });
1127
- }
1128
- if (options.includeMedia !== false) {
1129
- const images = element.querySelectorAll("img");
1130
- const videos = element.querySelectorAll("video");
1131
- const audios = element.querySelectorAll("audio");
1132
- result.media = [
1133
- ...Array.from(images).map((img) => {
1134
- const item = { type: "img" };
1135
- const alt = img.getAttribute("alt");
1136
- const src = img.getAttribute("src");
1137
- if (alt) item.alt = alt;
1138
- if (src) item.src = src;
1139
- return item;
1140
- }),
1141
- ...Array.from(videos).map((video) => {
1142
- const item = { type: "video" };
1143
- const src = video.getAttribute("src");
1144
- if (src) item.src = src;
1145
- return item;
1146
- }),
1147
- ...Array.from(audios).map((audio) => {
1148
- const item = { type: "audio" };
1149
- const src = audio.getAttribute("src");
1150
- if (src) item.src = src;
1151
- return item;
1152
- })
1153
- ];
1154
- }
1155
- const allText = element.textContent || "";
1156
- result.metadata.wordCount = allText.trim().split(/\s+/).length;
1157
- result.metadata.hasInteractive = element.querySelectorAll("button, a, input, textarea, select").length > 0;
1158
- return result;
1159
- }
1160
- /**
1161
- * Analyze a region and extract summary information
1162
- */
1163
- static analyzeRegion(element) {
1164
- var _a, _b, _c, _d;
1165
- const selector = SelectorGenerator.generateSelectors(element).css;
1166
- const buttons = element.querySelectorAll('button, [role="button"]');
1167
- const links = element.querySelectorAll("a[href]");
1168
- const inputs = element.querySelectorAll("input, textarea, select");
1169
- const forms = element.querySelectorAll("form");
1170
- const lists = element.querySelectorAll("ul, ol");
1171
- const tables = element.querySelectorAll("table");
1172
- const media = element.querySelectorAll("img, video, audio");
1173
- const interactiveCount = buttons.length + links.length + inputs.length;
1174
- let label;
1175
- const ariaLabel = element.getAttribute("aria-label");
1176
- if (ariaLabel) label = ariaLabel;
1177
- else if (element.getAttribute("aria-labelledby")) {
1178
- const labelId = element.getAttribute("aria-labelledby");
1179
- if (labelId) {
1180
- const labelElement = (_a = element.ownerDocument) == null ? void 0 : _a.getElementById(labelId);
1181
- if (labelElement) label = (_b = labelElement.textContent) == null ? void 0 : _b.trim();
1182
- }
1183
- } else {
1184
- const heading = element.querySelector("h1, h2, h3");
1185
- if (heading) label = (_c = heading.textContent) == null ? void 0 : _c.trim();
1186
- }
1187
- const textContent = ((_d = element.textContent) == null ? void 0 : _d.trim()) || "";
1188
- const textPreview = textContent.length > 50 ? `${textContent.substring(0, 50)}...` : textContent;
1189
- const regionInfo = {
1190
- selector,
1191
- interactiveCount,
1192
- hasForm: forms.length > 0,
1193
- hasList: lists.length > 0,
1194
- hasTable: tables.length > 0,
1195
- hasMedia: media.length > 0
1196
- };
1197
- if (label) regionInfo.label = label;
1198
- const role = element.getAttribute("role");
1199
- if (role) regionInfo.role = role;
1200
- if (buttons.length > 0) regionInfo.buttonCount = buttons.length;
1201
- if (links.length > 0) regionInfo.linkCount = links.length;
1202
- if (inputs.length > 0) regionInfo.inputCount = inputs.length;
1203
- if (textPreview.length > 0) regionInfo.textPreview = textPreview;
1204
- return regionInfo;
1205
- }
1206
- /**
1207
- * Extract overview of forms on the page
1208
- */
1209
- static extractFormOverview(root) {
1210
- const forms = root.querySelectorAll("form");
1211
- return Array.from(forms).map((form) => {
1212
- var _a, _b, _c;
1213
- const inputs = form.querySelectorAll("input, textarea, select");
1214
- const selector = SelectorGenerator.generateSelectors(form).css;
1215
- let location = "unknown";
1216
- if (form.closest('header, [role="banner"]')) location = "header";
1217
- else if (form.closest('nav, [role="navigation"]')) location = "navigation";
1218
- else if (form.closest('main, [role="main"]')) location = "main";
1219
- else if (form.closest('aside, [role="complementary"]')) location = "sidebar";
1220
- else if (form.closest('footer, [role="contentinfo"]')) location = "footer";
1221
- let purpose;
1222
- const formId = (_a = form.getAttribute("id")) == null ? void 0 : _a.toLowerCase();
1223
- const formClass = (_b = form.getAttribute("class")) == null ? void 0 : _b.toLowerCase();
1224
- const formAction = (_c = form.getAttribute("action")) == null ? void 0 : _c.toLowerCase();
1225
- const hasEmail = form.querySelector('input[type="email"]');
1226
- const hasPassword = form.querySelector('input[type="password"]');
1227
- if (form.querySelector('input[type="search"]') || (formId == null ? void 0 : formId.includes("search")) || (formClass == null ? void 0 : formClass.includes("search"))) purpose = "search";
1228
- else if (hasPassword && hasEmail) purpose = "login";
1229
- else if (hasPassword) purpose = "authentication";
1230
- else if ((formId == null ? void 0 : formId.includes("contact")) || (formClass == null ? void 0 : formClass.includes("contact"))) purpose = "contact";
1231
- else if ((formId == null ? void 0 : formId.includes("subscribe")) || (formClass == null ? void 0 : formClass.includes("subscribe"))) purpose = "subscription";
1232
- else if ((formAction == null ? void 0 : formAction.includes("checkout")) || (formClass == null ? void 0 : formClass.includes("checkout"))) purpose = "checkout";
1233
- const formOverview = {
1234
- selector,
1235
- location,
1236
- inputCount: inputs.length
1237
- };
1238
- if (purpose) formOverview.purpose = purpose;
1239
- return formOverview;
1240
- });
1241
- }
1242
- /**
1243
- * Calculate summary statistics
1244
- */
1245
- static calculateSummary(root, regions, forms) {
1246
- var _a, _b;
1247
- const allInteractive = root.querySelectorAll("button, a[href], input, textarea, select");
1248
- const allSections = root.querySelectorAll('section, article, [role="region"]');
1249
- const hasModals = (((_a = regions.modals) == null ? void 0 : _a.length) || 0) > 0;
1250
- const hasErrors = [
1251
- ".error",
1252
- ".alert-danger",
1253
- '[role="alert"]'
1254
- ].some((sel) => {
1255
- const element = root.querySelector(sel);
1256
- return element ? DOMTraversal.isVisible(element) : false;
1257
- });
1258
- const isLoading = [
1259
- ".loading",
1260
- ".spinner",
1261
- '[aria-busy="true"]'
1262
- ].some((sel) => {
1263
- const element = root.querySelector(sel);
1264
- return element ? DOMTraversal.isVisible(element) : false;
1265
- });
1266
- const summary = {
1267
- totalInteractive: allInteractive.length,
1268
- totalForms: forms.length,
1269
- totalSections: allSections.length,
1270
- hasModals,
1271
- hasErrors,
1272
- isLoading
1273
- };
1274
- const mainContentSelector = (_b = regions.main) == null ? void 0 : _b.selector;
1275
- if (mainContentSelector) summary.mainContentSelector = mainContentSelector;
1276
- return summary;
1277
- }
1278
- /**
1279
- * Generate AI-friendly suggestions
1280
- */
1281
- static generateSuggestions(regions, summary) {
1282
- const suggestions = [];
1283
- if (summary.hasErrors) suggestions.push("Page has error indicators - check error messages before interacting");
1284
- if (summary.isLoading) suggestions.push("Page appears to be loading - wait or check loading state");
1285
- if (summary.hasModals) suggestions.push("Modal/dialog is open - may need to interact with or close it first");
1286
- if (regions.main && regions.main.interactiveCount > 10) suggestions.push(`Main content has ${regions.main.interactiveCount} interactive elements - consider filtering`);
1287
- if (summary.totalForms > 0) suggestions.push(`Found ${summary.totalForms} form(s) on the page`);
1288
- if (!regions.main) suggestions.push("No clear main content area detected - may need to explore regions");
1289
- return suggestions;
1290
- }
1291
- /**
1292
- * Get text content with optional truncation
1293
- */
1294
- static getTextContent(element, maxLength) {
1295
- var _a;
1296
- const text = ((_a = element.textContent) == null ? void 0 : _a.trim()) || "";
1297
- if (maxLength && text.length > maxLength) return `${text.substring(0, maxLength)}...`;
1298
- return text;
1299
- }
1300
- };
1301
- }));
1302
- var init_types = __esmMin((() => {
1303
- }));
1304
- var src_exports = /* @__PURE__ */ __exportAll({
1305
- ContentDetection: () => ContentDetection,
1306
- MarkdownFormatter: () => MarkdownFormatter,
1307
- ProgressiveExtractor: () => ProgressiveExtractor,
1308
- SelectorGenerator: () => SelectorGenerator,
1309
- SmartDOMReader: () => SmartDOMReader,
1310
- default: () => SmartDOMReader
1311
- });
1312
- var SmartDOMReader;
1313
- var init_src = __esmMin((() => {
1314
- init_content_detection();
1315
- init_selectors();
1316
- init_traversal();
1317
- init_markdown_formatter();
1318
- init_progressive();
1319
- init_types();
1320
- SmartDOMReader = class SmartDOMReader2 {
1321
- constructor(options = {}) {
1322
- __publicField(this, "options");
1323
- var _a;
1324
- this.options = {
1325
- mode: options.mode || "interactive",
1326
- maxDepth: options.maxDepth || 5,
1327
- includeHidden: options.includeHidden || false,
1328
- includeShadowDOM: (_a = options.includeShadowDOM) != null ? _a : true,
1329
- includeIframes: options.includeIframes || false,
1330
- viewportOnly: options.viewportOnly || false,
1331
- mainContentOnly: options.mainContentOnly || false,
1332
- customSelectors: options.customSelectors || [],
1333
- ...options.attributeTruncateLength !== void 0 && { attributeTruncateLength: options.attributeTruncateLength },
1334
- ...options.dataAttributeTruncateLength !== void 0 && { dataAttributeTruncateLength: options.dataAttributeTruncateLength },
1335
- ...options.textTruncateLength !== void 0 && { textTruncateLength: options.textTruncateLength },
1336
- ...options.filter !== void 0 && { filter: options.filter }
1337
- };
1338
- }
1339
- /**
1340
- * Main extraction method - extracts all data in one pass
1341
- * @param rootElement The document or element to extract from
1342
- * @param runtimeOptions Options to override constructor options
1343
- */
1344
- extract(rootElement = document, runtimeOptions) {
1345
- const startTime = Date.now();
1346
- const doc = rootElement instanceof Document ? rootElement : rootElement.ownerDocument;
1347
- const options = {
1348
- ...this.options,
1349
- ...runtimeOptions
1350
- };
1351
- let container = rootElement instanceof Document ? doc : rootElement;
1352
- if (options.mainContentOnly && rootElement instanceof Document) container = ContentDetection.findMainContent(doc);
1353
- const pageState = this.extractPageState(doc);
1354
- const landmarks = this.extractLandmarks(doc);
1355
- const interactive = this.extractInteractiveElements(container, options);
1356
- const result = {
1357
- mode: options.mode,
1358
- timestamp: startTime,
1359
- page: pageState,
1360
- landmarks,
1361
- interactive
1362
- };
1363
- if (options.mode === "full") {
1364
- const semantic = this.extractSemanticElements(container, options);
1365
- const metadata = this.extractMetadata(doc, container, options);
1366
- return {
1367
- ...result,
1368
- semantic,
1369
- metadata
1370
- };
1371
- }
1372
- return result;
1373
- }
1374
- /**
1375
- * Extract page state information
1376
- */
1377
- extractPageState(doc) {
1378
- var _a;
1379
- const hasFocus = this.getFocusedElement(doc);
1380
- return {
1381
- url: ((_a = doc.location) == null ? void 0 : _a.href) || "",
1382
- title: doc.title || "",
1383
- hasErrors: this.detectErrors(doc),
1384
- isLoading: this.detectLoading(doc),
1385
- hasModals: this.detectModals(doc),
1386
- ...hasFocus !== void 0 && { hasFocus }
1387
- };
1388
- }
1389
- /**
1390
- * Extract page landmarks
1391
- */
1392
- extractLandmarks(doc) {
1393
- const detected = ContentDetection.detectLandmarks(doc);
1394
- return {
1395
- navigation: this.elementsToSelectors(detected.navigation || []),
1396
- main: this.elementsToSelectors(detected.main || []),
1397
- forms: this.elementsToSelectors(detected.form || []),
1398
- headers: this.elementsToSelectors(detected.banner || []),
1399
- footers: this.elementsToSelectors(detected.contentinfo || []),
1400
- articles: this.elementsToSelectors(detected.region || []),
1401
- sections: this.elementsToSelectors(detected.region || [])
1402
- };
1403
- }
1404
- /**
1405
- * Convert elements to selector strings
1406
- */
1407
- elementsToSelectors(elements) {
1408
- return elements.map((el) => SelectorGenerator.generateSelectors(el).css);
1409
- }
1410
- /**
1411
- * Extract interactive elements
1412
- */
1413
- extractInteractiveElements(container, options) {
1414
- const buttons = [];
1415
- const links = [];
1416
- const inputs = [];
1417
- const clickable = [];
1418
- container.querySelectorAll('button, [role="button"], input[type="button"], input[type="submit"]').forEach((el) => {
1419
- if (this.shouldIncludeElement(el, options)) {
1420
- const extracted = DOMTraversal.extractElement(el, options);
1421
- if (extracted) buttons.push(extracted);
1422
- }
1423
- });
1424
- container.querySelectorAll("a[href]").forEach((el) => {
1425
- if (this.shouldIncludeElement(el, options)) {
1426
- const extracted = DOMTraversal.extractElement(el, options);
1427
- if (extracted) links.push(extracted);
1428
- }
1429
- });
1430
- container.querySelectorAll('input:not([type="button"]):not([type="submit"]), textarea, select').forEach((el) => {
1431
- if (this.shouldIncludeElement(el, options)) {
1432
- const extracted = DOMTraversal.extractElement(el, options);
1433
- if (extracted) inputs.push(extracted);
1434
- }
1435
- });
1436
- if (options.customSelectors) options.customSelectors.forEach((selector) => {
1437
- container.querySelectorAll(selector).forEach((el) => {
1438
- if (this.shouldIncludeElement(el, options)) {
1439
- const extracted = DOMTraversal.extractElement(el, options);
1440
- if (extracted) clickable.push(extracted);
1441
- }
1442
- });
1443
- });
1444
- return {
1445
- buttons,
1446
- links,
1447
- inputs,
1448
- forms: this.extractForms(container, options),
1449
- clickable
1450
- };
1451
- }
1452
- /**
1453
- * Extract form information
1454
- */
1455
- extractForms(container, options) {
1456
- const forms = [];
1457
- container.querySelectorAll("form").forEach((form) => {
1458
- if (!this.shouldIncludeElement(form, options)) return;
1459
- const formInputs = [];
1460
- const formButtons = [];
1461
- form.querySelectorAll('input:not([type="button"]):not([type="submit"]), textarea, select').forEach((input) => {
1462
- const extracted = DOMTraversal.extractElement(input, options);
1463
- if (extracted) formInputs.push(extracted);
1464
- });
1465
- form.querySelectorAll('button, input[type="button"], input[type="submit"]').forEach((button) => {
1466
- const extracted = DOMTraversal.extractElement(button, options);
1467
- if (extracted) formButtons.push(extracted);
1468
- });
1469
- const action = form.getAttribute("action");
1470
- const method = form.getAttribute("method");
1471
- const formInfo = {
1472
- selector: SelectorGenerator.generateSelectors(form).css,
1473
- inputs: formInputs,
1474
- buttons: formButtons
1475
- };
1476
- if (action) formInfo.action = action;
1477
- if (method) formInfo.method = method;
1478
- forms.push(formInfo);
1479
- });
1480
- return forms;
1481
- }
1482
- /**
1483
- * Extract semantic elements (full mode only)
1484
- */
1485
- extractSemanticElements(container, options) {
1486
- const headings = [];
1487
- const images = [];
1488
- const tables = [];
1489
- const lists = [];
1490
- const articles = [];
1491
- container.querySelectorAll("h1, h2, h3, h4, h5, h6").forEach((el) => {
1492
- if (this.shouldIncludeElement(el, options)) {
1493
- const extracted = DOMTraversal.extractElement(el, options);
1494
- if (extracted) headings.push(extracted);
1495
- }
1496
- });
1497
- container.querySelectorAll("img").forEach((el) => {
1498
- if (this.shouldIncludeElement(el, options)) {
1499
- const extracted = DOMTraversal.extractElement(el, options);
1500
- if (extracted) images.push(extracted);
1501
- }
1502
- });
1503
- container.querySelectorAll("table").forEach((el) => {
1504
- if (this.shouldIncludeElement(el, options)) {
1505
- const extracted = DOMTraversal.extractElement(el, options);
1506
- if (extracted) tables.push(extracted);
1507
- }
1508
- });
1509
- container.querySelectorAll("ul, ol").forEach((el) => {
1510
- if (this.shouldIncludeElement(el, options)) {
1511
- const extracted = DOMTraversal.extractElement(el, options);
1512
- if (extracted) lists.push(extracted);
1513
- }
1514
- });
1515
- container.querySelectorAll('article, [role="article"]').forEach((el) => {
1516
- if (this.shouldIncludeElement(el, options)) {
1517
- const extracted = DOMTraversal.extractElement(el, options);
1518
- if (extracted) articles.push(extracted);
1519
- }
1520
- });
1521
- return {
1522
- headings,
1523
- images,
1524
- tables,
1525
- lists,
1526
- articles
1527
- };
1528
- }
1529
- /**
1530
- * Extract metadata
1531
- */
1532
- extractMetadata(doc, container, options) {
1533
- const allElements = container.querySelectorAll("*");
1534
- const extractedElements = container.querySelectorAll("button, a, input, textarea, select, h1, h2, h3, h4, h5, h6, img, table, ul, ol, article").length;
1535
- const metadata = {
1536
- totalElements: allElements.length,
1537
- extractedElements
1538
- };
1539
- if (options.mainContentOnly && container instanceof Element) metadata.mainContent = SelectorGenerator.generateSelectors(container).css;
1540
- const language = doc.documentElement.getAttribute("lang");
1541
- if (language) metadata.language = language;
1542
- return metadata;
1543
- }
1544
- /**
1545
- * Check if element should be included based on options
1546
- */
1547
- shouldIncludeElement(element, options) {
1548
- if (!options.includeHidden && !DOMTraversal.isVisible(element)) return false;
1549
- if (options.viewportOnly && !DOMTraversal.isInViewport(element)) return false;
1550
- if (options.filter && !DOMTraversal.passesFilter(element, options.filter)) return false;
1551
- return true;
1552
- }
1553
- /**
1554
- * Detect errors on the page
1555
- */
1556
- detectErrors(doc) {
1557
- return [
1558
- ".error",
1559
- ".alert-danger",
1560
- '[role="alert"]',
1561
- ".error-message"
1562
- ].some((sel) => {
1563
- const element = doc.querySelector(sel);
1564
- return element ? DOMTraversal.isVisible(element) : false;
1565
- });
1566
- }
1567
- /**
1568
- * Detect if page is loading
1569
- */
1570
- detectLoading(doc) {
1571
- return [
1572
- ".loading",
1573
- ".spinner",
1574
- '[aria-busy="true"]',
1575
- ".loader"
1576
- ].some((sel) => {
1577
- const element = doc.querySelector(sel);
1578
- return element ? DOMTraversal.isVisible(element) : false;
1579
- });
1580
- }
1581
- /**
1582
- * Detect modal dialogs
1583
- */
1584
- detectModals(doc) {
1585
- return [
1586
- '[role="dialog"]',
1587
- ".modal",
1588
- ".popup",
1589
- ".overlay"
1590
- ].some((sel) => {
1591
- const element = doc.querySelector(sel);
1592
- return element ? DOMTraversal.isVisible(element) : false;
1593
- });
1594
- }
1595
- /**
1596
- * Get currently focused element
1597
- */
1598
- getFocusedElement(doc) {
1599
- const focused = doc.activeElement;
1600
- if (focused && focused !== doc.body) return SelectorGenerator.generateSelectors(focused).css;
1601
- }
1602
- /**
1603
- * Quick extraction for interactive elements only
1604
- * @param doc The document to extract from
1605
- * @param options Extraction options
1606
- */
1607
- static extractInteractive(doc, options = {}) {
1608
- return new SmartDOMReader2({
1609
- ...options,
1610
- mode: "interactive"
1611
- }).extract(doc);
1612
- }
1613
- /**
1614
- * Quick extraction for full content
1615
- * @param doc The document to extract from
1616
- * @param options Extraction options
1617
- */
1618
- static extractFull(doc, options = {}) {
1619
- return new SmartDOMReader2({
1620
- ...options,
1621
- mode: "full"
1622
- }).extract(doc);
1623
- }
1624
- /**
1625
- * Extract from a specific element
1626
- * @param element The element to extract from
1627
- * @param mode The extraction mode
1628
- * @param options Additional options
1629
- */
1630
- static extractFromElement(element, mode = "interactive", options = {}) {
1631
- return new SmartDOMReader2({
1632
- ...options,
1633
- mode
1634
- }).extract(element);
1635
- }
1636
- };
1637
- }));
1638
- init_src();
1639
-
1640
- // src/utils/smart-dom-adapter.ts
1641
- var PLAIN_CSS_CANDIDATE_TYPES = /* @__PURE__ */ new Set(["id", "data-testid", "role-aria", "name", "class-path", "css-path"]);
1642
- function looksLikeXPath(value) {
1643
- const v = value.trim();
1644
- return v.startsWith("/") || v.startsWith("(") || v.startsWith("./");
1645
- }
1646
- function bestPlainCssSelector(el) {
1647
- const candidates = el.selector.candidates;
1648
- if (candidates && candidates.length > 0) {
1649
- let best = null;
1650
- for (const c of candidates) {
1651
- if (!PLAIN_CSS_CANDIDATE_TYPES.has(c.type)) continue;
1652
- if (!c.value || looksLikeXPath(c.value)) continue;
1653
- if (!best || c.score > best.score) best = c;
1654
- }
1655
- if (best) return best.value;
1656
- }
1657
- const css = el.selector.css;
1658
- if (css && !looksLikeXPath(css)) return css;
1659
- return null;
1660
- }
1661
- function classifyInteractivity(el) {
1662
- var _a;
1663
- const tag = el.tag.toLowerCase();
1664
- const role = (_a = el.interaction.role) != null ? _a : el.attributes.role;
1665
- if (tag === "a" && (el.interaction.nav || el.attributes.href != null)) {
1666
- return "navigable";
1667
- }
1668
- if (tag === "input" || tag === "select" || tag === "textarea") return "input";
1669
- if (role === "textbox" || role === "combobox" || role === "listbox" || role === "spinbutton") {
1670
- return "input";
1671
- }
1672
- if (el.interaction.change && !el.interaction.click) return "input";
1673
- if (tag === "button" || role === "button" || el.interaction.click || el.interaction.submit) {
1674
- return "clickable";
1675
- }
1676
- return "static";
1677
- }
1678
- function collectAttributes(el) {
1679
- const attrs = { ...el.attributes };
1680
- const role = el.interaction.role;
1681
- if (role && !attrs.role) attrs.role = role;
1682
- return attrs;
1683
- }
1684
- function isExcluded(el, excludeSelector) {
1685
- var _a, _b;
1686
- if (!excludeSelector) return false;
1687
- const haystacks = [
1688
- el.selector.css,
1689
- el.selector.xpath,
1690
- el.context.nearestForm,
1691
- el.context.nearestSection,
1692
- el.context.nearestMain,
1693
- el.context.nearestNav,
1694
- ...(_b = (_a = el.selector.candidates) == null ? void 0 : _a.map((c) => c.value)) != null ? _b : [],
1695
- ...el.context.parentChain
1696
- ];
1697
- return haystacks.some((h) => !!h && h.includes(excludeSelector));
1698
- }
1699
- function smartDomResultToEnriched(result, opts = {}) {
1700
- var _a, _b, _c;
1701
- const includeSemantic = (_a = opts.includeSemantic) != null ? _a : true;
1702
- const excludeSelector = (_b = opts.excludeSelector) != null ? _b : ".persona-host";
1703
- const maxTextLength = (_c = opts.maxTextLength) != null ? _c : 200;
1704
- const groups = [
1705
- result.interactive.buttons,
1706
- result.interactive.links,
1707
- result.interactive.inputs,
1708
- result.interactive.clickable
1709
- ];
1710
- if (includeSemantic && result.semantic) {
1711
- groups.push(
1712
- result.semantic.headings,
1713
- result.semantic.images,
1714
- result.semantic.tables,
1715
- result.semantic.lists,
1716
- result.semantic.articles
1717
- );
1718
- }
1719
- const out = [];
1720
- const seen = /* @__PURE__ */ new Set();
1721
- const visit = (el) => {
1722
- var _a2, _b2, _c2;
1723
- if (isExcluded(el, excludeSelector)) return true;
1724
- const selector = bestPlainCssSelector(el);
1725
- if (selector && !seen.has(selector)) {
1726
- seen.add(selector);
1727
- out.push({
1728
- selector,
1729
- tagName: el.tag.toLowerCase(),
1730
- text: ((_a2 = el.text) != null ? _a2 : "").trim().substring(0, maxTextLength),
1731
- role: (_c2 = (_b2 = el.interaction.role) != null ? _b2 : el.attributes.role) != null ? _c2 : null,
1732
- interactivity: classifyInteractivity(el),
1733
- attributes: collectAttributes(el)
1734
- });
1735
- if (opts.maxElements && out.length >= opts.maxElements) return false;
1736
- }
1737
- if (el.children) {
1738
- for (const child of el.children) {
1739
- if (!visit(child)) return false;
1740
- }
1741
- }
1742
- return true;
1743
- };
1744
- for (const group of groups) {
1745
- if (!group) continue;
1746
- for (const el of group) {
1747
- if (!visit(el)) return out;
1748
- }
1749
- }
1750
- return out;
1751
- }
1752
-
1753
- // src/utils/dom-context.ts
1754
- var TEXT_PREVIEW_LEN = 100;
1755
- function formatEnrichedContext(elements, options = {}) {
1756
- var _a;
1757
- if (elements.length === 0) {
1758
- return "No page elements found.";
1759
- }
1760
- const mode = (_a = options.mode) != null ? _a : "structured";
1761
- const sections = [];
1762
- if (mode === "structured") {
1763
- const summaries = elements.map((el) => el.formattedSummary).filter((s) => !!s && s.length > 0);
1764
- if (summaries.length > 0) {
1765
- sections.push(
1766
- `Structured summaries:
1767
- ${summaries.map((s) => `- ${s.split("\n").join("\n ")}`).join("\n")}`
1768
- );
1769
- }
1770
- }
1771
- const groups = {
1772
- clickable: [],
1773
- navigable: [],
1774
- input: [],
1775
- static: []
1776
- };
1777
- for (const el of elements) {
1778
- if (mode === "structured" && el.formattedSummary) continue;
1779
- groups[el.interactivity].push(el);
1780
- }
1781
- if (groups.clickable.length > 0) {
1782
- const lines = groups.clickable.map(
1783
- (el) => `- ${el.selector}: "${el.text.substring(0, TEXT_PREVIEW_LEN)}" (clickable)`
1784
- );
1785
- sections.push(`Interactive elements:
1786
- ${lines.join("\n")}`);
1787
- }
1788
- if (groups.navigable.length > 0) {
1789
- const lines = groups.navigable.map(
1790
- (el) => `- ${el.selector}${el.attributes.href ? `[href="${el.attributes.href}"]` : ""}: "${el.text.substring(0, TEXT_PREVIEW_LEN)}" (navigable)`
1791
- );
1792
- sections.push(`Navigation links:
1793
- ${lines.join("\n")}`);
1794
- }
1795
- if (groups.input.length > 0) {
1796
- const lines = groups.input.map(
1797
- (el) => `- ${el.selector}${el.attributes.type ? `[type="${el.attributes.type}"]` : ""}: "${el.text.substring(0, TEXT_PREVIEW_LEN)}" (input)`
1798
- );
1799
- sections.push(`Form inputs:
1800
- ${lines.join("\n")}`);
1801
- }
1802
- if (groups.static.length > 0) {
1803
- const lines = groups.static.map(
1804
- (el) => `- ${el.selector}: "${el.text.substring(0, TEXT_PREVIEW_LEN)}"`
1805
- );
1806
- sections.push(`Content:
1807
- ${lines.join("\n")}`);
1808
- }
1809
- return sections.join("\n\n");
1810
- }
1811
-
1812
- // src/smart-dom-reader.ts
1813
- function collectSmartDomContext(opts = {}) {
1814
- var _a, _b, _c;
1815
- const mode = (_a = opts.mode) != null ? _a : "interactive";
1816
- let result;
1817
- if (opts.root) {
1818
- result = SmartDOMReader.extractFromElement(
1819
- opts.root,
1820
- mode,
1821
- opts.extractionOptions
1822
- );
1823
- } else {
1824
- const doc = (_b = opts.document) != null ? _b : typeof document !== "undefined" ? document : void 0;
1825
- if (!doc) return [];
1826
- result = mode === "full" ? SmartDOMReader.extractFull(doc, opts.extractionOptions) : SmartDOMReader.extractInteractive(doc, opts.extractionOptions);
1827
- }
1828
- return smartDomResultToEnriched(result, {
1829
- includeSemantic: (_c = opts.includeSemantic) != null ? _c : mode === "full",
1830
- excludeSelector: opts.excludeSelector,
1831
- maxTextLength: opts.maxTextLength,
1832
- maxElements: opts.maxElements
1833
- });
1834
- }
1835
- function createSmartDomReaderContextProvider(opts = {}) {
1836
- var _a;
1837
- const contextKey = (_a = opts.contextKey) != null ? _a : "pageContext";
1838
- return () => {
1839
- const elements = collectSmartDomContext(opts);
1840
- if (elements.length === 0) return {};
1841
- return { [contextKey]: formatEnrichedContext(elements) };
1842
- };
1843
- }
1844
- export {
1845
- collectSmartDomContext,
1846
- createSmartDomReaderContextProvider,
1847
- smartDomResultToEnriched
1848
- };
23
+ `)}function St(s={}){var n,r,i;let e=(n=s.mode)!=null?n:"interactive",t;if(s.root)t=A.extractFromElement(s.root,e,s.extractionOptions);else{let a=(r=s.document)!=null?r:typeof document!="undefined"?document:void 0;if(!a)return[];t=e==="full"?A.extractFull(a,s.extractionOptions):A.extractInteractive(a,s.extractionOptions)}return Y(t,{includeSemantic:(i=s.includeSemantic)!=null?i:e==="full",excludeSelector:s.excludeSelector,maxTextLength:s.maxTextLength,maxElements:s.maxElements})}function Rt(s={}){var t;let e=(t=s.contextKey)!=null?t:"pageContext";return()=>{let n=St(s);return n.length===0?{}:{[e]:J(n)}}}export{St as collectSmartDomContext,Rt as createSmartDomReaderContextProvider,Y as smartDomResultToEnriched};