@browserbasehq/orca 3.5.0-vertex-test → 3.5.1-preview.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +7 -3
- package/dist/cjs/lib/utils.d.ts +2 -0
- package/dist/cjs/lib/utils.js +20 -0
- package/dist/cjs/lib/utils.js.map +1 -1
- package/dist/cjs/lib/v3/agent/AgentProvider.js +1 -0
- package/dist/cjs/lib/v3/agent/AgentProvider.js.map +1 -1
- package/dist/cjs/lib/v3/agent/AnthropicCUAClient.js +1 -0
- package/dist/cjs/lib/v3/agent/AnthropicCUAClient.js.map +1 -1
- package/dist/cjs/lib/v3/agent/utils/captureAriaTreeProbe.d.ts +35 -0
- package/dist/cjs/lib/v3/agent/utils/captureAriaTreeProbe.js +38 -0
- package/dist/cjs/lib/v3/agent/utils/captureAriaTreeProbe.js.map +1 -0
- package/dist/cjs/lib/v3/agent/utils/postStepProbeEvidence.d.ts +19 -0
- package/dist/cjs/lib/v3/agent/utils/postStepProbeEvidence.js +54 -0
- package/dist/cjs/lib/v3/agent/utils/postStepProbeEvidence.js.map +1 -0
- package/dist/cjs/lib/v3/agent/utils/toolOutputEvidence.d.ts +2 -0
- package/dist/cjs/lib/v3/agent/utils/toolOutputEvidence.js +62 -0
- package/dist/cjs/lib/v3/agent/utils/toolOutputEvidence.js.map +1 -0
- package/dist/cjs/lib/v3/agent/utils/wrapEvidenceCallback.d.ts +3 -0
- package/dist/cjs/lib/v3/agent/utils/wrapEvidenceCallback.js +25 -0
- package/dist/cjs/lib/v3/agent/utils/wrapEvidenceCallback.js.map +1 -0
- package/dist/cjs/lib/v3/api.d.ts +1 -0
- package/dist/cjs/lib/v3/api.js +37 -16
- package/dist/cjs/lib/v3/api.js.map +1 -1
- package/dist/cjs/lib/v3/dom/build/locatorScripts.generated.d.ts +24 -24
- package/dist/cjs/lib/v3/dom/build/locatorScripts.generated.js +24 -24
- package/dist/cjs/lib/v3/dom/build/locatorScripts.generated.js.map +1 -1
- package/dist/cjs/lib/v3/dom/build/selectorRuntime.generated.d.ts +24 -0
- package/dist/cjs/lib/v3/dom/build/selectorRuntime.generated.js +31 -0
- package/dist/cjs/lib/v3/dom/build/selectorRuntime.generated.js.map +1 -0
- package/dist/cjs/lib/v3/dom/locatorScripts/xpathResolver.js +79 -10
- package/dist/cjs/lib/v3/dom/locatorScripts/xpathResolver.js.map +1 -1
- package/dist/cjs/lib/v3/handlers/v3AgentHandler.d.ts +1 -0
- package/dist/cjs/lib/v3/handlers/v3AgentHandler.js +83 -7
- package/dist/cjs/lib/v3/handlers/v3AgentHandler.js.map +1 -1
- package/dist/cjs/lib/v3/handlers/v3CuaAgentHandler.d.ts +11 -0
- package/dist/cjs/lib/v3/handlers/v3CuaAgentHandler.js +119 -5
- package/dist/cjs/lib/v3/handlers/v3CuaAgentHandler.js.map +1 -1
- package/dist/cjs/lib/v3/index.d.ts +13 -1
- package/dist/cjs/lib/v3/index.js +19 -1
- package/dist/cjs/lib/v3/index.js.map +1 -1
- package/dist/cjs/lib/v3/llm/LLMProvider.d.ts +3 -0
- package/dist/cjs/lib/v3/llm/LLMProvider.js +44 -3
- package/dist/cjs/lib/v3/llm/LLMProvider.js.map +1 -1
- package/dist/cjs/lib/v3/types/public/agent.d.ts +8 -2
- package/dist/cjs/lib/v3/types/public/agent.js +1 -0
- package/dist/cjs/lib/v3/types/public/agent.js.map +1 -1
- package/dist/cjs/lib/v3/types/public/agentEvidenceEvents.d.ts +85 -0
- package/dist/cjs/lib/v3/types/public/agentEvidenceEvents.js +15 -0
- package/dist/cjs/lib/v3/types/public/agentEvidenceEvents.js.map +1 -0
- package/dist/cjs/lib/v3/types/public/api.d.ts +925 -182
- package/dist/cjs/lib/v3/types/public/api.js +138 -20
- package/dist/cjs/lib/v3/types/public/api.js.map +1 -1
- package/dist/cjs/lib/v3/types/public/clipboard.d.ts +15 -0
- package/dist/cjs/lib/v3/types/public/clipboard.js +3 -0
- package/dist/cjs/lib/v3/types/public/clipboard.js.map +1 -0
- package/dist/cjs/lib/v3/types/public/index.d.ts +2 -0
- package/dist/cjs/lib/v3/types/public/index.js +2 -0
- package/dist/cjs/lib/v3/types/public/index.js.map +1 -1
- package/dist/cjs/lib/v3/types/public/model.d.ts +30 -6
- package/dist/cjs/lib/v3/types/public/model.js.map +1 -1
- package/dist/cjs/lib/v3/types/public/page.d.ts +29 -0
- package/dist/cjs/lib/v3/types/public/page.js.map +1 -1
- package/dist/cjs/lib/v3/types/public/sdkErrors.d.ts +3 -0
- package/dist/cjs/lib/v3/types/public/sdkErrors.js +8 -2
- package/dist/cjs/lib/v3/types/public/sdkErrors.js.map +1 -1
- package/dist/cjs/lib/v3/understudy/clipboard.d.ts +24 -0
- package/dist/cjs/lib/v3/understudy/clipboard.js +166 -0
- package/dist/cjs/lib/v3/understudy/clipboard.js.map +1 -0
- package/dist/cjs/lib/v3/understudy/context.d.ts +3 -0
- package/dist/cjs/lib/v3/understudy/context.js +15 -0
- package/dist/cjs/lib/v3/understudy/context.js.map +1 -1
- package/dist/cjs/lib/v3/understudy/page.d.ts +23 -1
- package/dist/cjs/lib/v3/understudy/page.js +283 -0
- package/dist/cjs/lib/v3/understudy/page.js.map +1 -1
- package/dist/cjs/lib/v3/v3.js +15 -6
- package/dist/cjs/lib/v3/v3.js.map +1 -1
- package/dist/cjs/lib/v3/verifier/evidenceNormalization.d.ts +7 -0
- package/dist/cjs/lib/v3/verifier/evidenceNormalization.js +100 -0
- package/dist/cjs/lib/v3/verifier/evidenceNormalization.js.map +1 -0
- package/dist/cjs/lib/v3/verifier/index.d.ts +6 -0
- package/dist/cjs/lib/v3/verifier/index.js +16 -0
- package/dist/cjs/lib/v3/verifier/index.js.map +1 -0
- package/dist/cjs/lib/v3/verifier/trajectory.d.ts +50 -0
- package/dist/cjs/lib/v3/verifier/trajectory.js +316 -0
- package/dist/cjs/lib/v3/verifier/trajectory.js.map +1 -0
- package/dist/cjs/lib/v3/verifier/types.d.ts +281 -0
- package/dist/cjs/lib/v3/verifier/types.js +10 -0
- package/dist/cjs/lib/v3/verifier/types.js.map +1 -0
- package/dist/cjs/lib/v3Evaluator.d.ts +9 -4
- package/dist/cjs/lib/v3Evaluator.js +148 -0
- package/dist/cjs/lib/v3Evaluator.js.map +1 -1
- package/dist/cjs/lib/v3LegacyEvaluator.js +5 -1
- package/dist/cjs/lib/v3LegacyEvaluator.js.map +1 -1
- package/dist/cjs/lib/version.d.ts +1 -1
- package/dist/cjs/lib/version.js +1 -1
- package/dist/cjs/lib/version.js.map +1 -1
- package/dist/esm/lib/utils.d.ts +2 -0
- package/dist/esm/lib/utils.js +18 -0
- package/dist/esm/lib/utils.js.map +1 -1
- package/dist/esm/lib/v3/agent/AgentProvider.js +1 -0
- package/dist/esm/lib/v3/agent/AgentProvider.js.map +1 -1
- package/dist/esm/lib/v3/agent/AnthropicCUAClient.js +1 -0
- package/dist/esm/lib/v3/agent/AnthropicCUAClient.js.map +1 -1
- package/dist/esm/lib/v3/agent/utils/captureAriaTreeProbe.d.ts +35 -0
- package/dist/esm/lib/v3/agent/utils/captureAriaTreeProbe.js +35 -0
- package/dist/esm/lib/v3/agent/utils/captureAriaTreeProbe.js.map +1 -0
- package/dist/esm/lib/v3/agent/utils/postStepProbeEvidence.d.ts +19 -0
- package/dist/esm/lib/v3/agent/utils/postStepProbeEvidence.js +50 -0
- package/dist/esm/lib/v3/agent/utils/postStepProbeEvidence.js.map +1 -0
- package/dist/esm/lib/v3/agent/utils/toolOutputEvidence.d.ts +2 -0
- package/dist/esm/lib/v3/agent/utils/toolOutputEvidence.js +59 -0
- package/dist/esm/lib/v3/agent/utils/toolOutputEvidence.js.map +1 -0
- package/dist/esm/lib/v3/agent/utils/wrapEvidenceCallback.d.ts +3 -0
- package/dist/esm/lib/v3/agent/utils/wrapEvidenceCallback.js +22 -0
- package/dist/esm/lib/v3/agent/utils/wrapEvidenceCallback.js.map +1 -0
- package/dist/esm/lib/v3/api.d.ts +1 -0
- package/dist/esm/lib/v3/api.js +38 -17
- package/dist/esm/lib/v3/api.js.map +1 -1
- package/dist/esm/lib/v3/dom/build/locatorScripts.generated.d.ts +24 -24
- package/dist/esm/lib/v3/dom/build/locatorScripts.generated.js +24 -24
- package/dist/esm/lib/v3/dom/build/locatorScripts.generated.js.map +1 -1
- package/dist/esm/lib/v3/dom/build/selectorRuntime.generated.d.ts +24 -0
- package/dist/esm/lib/v3/dom/build/selectorRuntime.generated.js +28 -0
- package/dist/esm/lib/v3/dom/build/selectorRuntime.generated.js.map +1 -0
- package/dist/esm/lib/v3/dom/locatorScripts/xpathResolver.js +79 -10
- package/dist/esm/lib/v3/dom/locatorScripts/xpathResolver.js.map +1 -1
- package/dist/esm/lib/v3/handlers/v3AgentHandler.d.ts +1 -0
- package/dist/esm/lib/v3/handlers/v3AgentHandler.js +83 -7
- package/dist/esm/lib/v3/handlers/v3AgentHandler.js.map +1 -1
- package/dist/esm/lib/v3/handlers/v3CuaAgentHandler.d.ts +11 -0
- package/dist/esm/lib/v3/handlers/v3CuaAgentHandler.js +119 -5
- package/dist/esm/lib/v3/handlers/v3CuaAgentHandler.js.map +1 -1
- package/dist/esm/lib/v3/index.d.ts +13 -1
- package/dist/esm/lib/v3/index.js +10 -0
- package/dist/esm/lib/v3/index.js.map +1 -1
- package/dist/esm/lib/v3/llm/LLMProvider.d.ts +3 -0
- package/dist/esm/lib/v3/llm/LLMProvider.js +43 -3
- package/dist/esm/lib/v3/llm/LLMProvider.js.map +1 -1
- package/dist/esm/lib/v3/types/public/agent.d.ts +8 -2
- package/dist/esm/lib/v3/types/public/agent.js +1 -0
- package/dist/esm/lib/v3/types/public/agent.js.map +1 -1
- package/dist/esm/lib/v3/types/public/agentEvidenceEvents.d.ts +85 -0
- package/dist/esm/lib/v3/types/public/agentEvidenceEvents.js +14 -0
- package/dist/esm/lib/v3/types/public/agentEvidenceEvents.js.map +1 -0
- package/dist/esm/lib/v3/types/public/api.d.ts +925 -182
- package/dist/esm/lib/v3/types/public/api.js +136 -18
- package/dist/esm/lib/v3/types/public/api.js.map +1 -1
- package/dist/esm/lib/v3/types/public/clipboard.d.ts +15 -0
- package/dist/esm/lib/v3/types/public/clipboard.js +2 -0
- package/dist/esm/lib/v3/types/public/clipboard.js.map +1 -0
- package/dist/esm/lib/v3/types/public/index.d.ts +2 -0
- package/dist/esm/lib/v3/types/public/index.js +2 -0
- package/dist/esm/lib/v3/types/public/index.js.map +1 -1
- package/dist/esm/lib/v3/types/public/model.d.ts +30 -6
- package/dist/esm/lib/v3/types/public/model.js.map +1 -1
- package/dist/esm/lib/v3/types/public/page.d.ts +29 -0
- package/dist/esm/lib/v3/types/public/page.js.map +1 -1
- package/dist/esm/lib/v3/types/public/sdkErrors.d.ts +3 -0
- package/dist/esm/lib/v3/types/public/sdkErrors.js +5 -0
- package/dist/esm/lib/v3/types/public/sdkErrors.js.map +1 -1
- package/dist/esm/lib/v3/understudy/clipboard.d.ts +24 -0
- package/dist/esm/lib/v3/understudy/clipboard.js +163 -0
- package/dist/esm/lib/v3/understudy/clipboard.js.map +1 -0
- package/dist/esm/lib/v3/understudy/context.d.ts +3 -0
- package/dist/esm/lib/v3/understudy/context.js +15 -0
- package/dist/esm/lib/v3/understudy/context.js.map +1 -1
- package/dist/esm/lib/v3/understudy/page.d.ts +23 -1
- package/dist/esm/lib/v3/understudy/page.js +284 -1
- package/dist/esm/lib/v3/understudy/page.js.map +1 -1
- package/dist/esm/lib/v3/v3.js +16 -7
- package/dist/esm/lib/v3/v3.js.map +1 -1
- package/dist/esm/lib/v3/verifier/evidenceNormalization.d.ts +7 -0
- package/dist/esm/lib/v3/verifier/evidenceNormalization.js +93 -0
- package/dist/esm/lib/v3/verifier/evidenceNormalization.js.map +1 -0
- package/dist/esm/lib/v3/verifier/index.d.ts +6 -0
- package/dist/esm/lib/v3/verifier/index.js +3 -0
- package/dist/esm/lib/v3/verifier/index.js.map +1 -0
- package/dist/esm/lib/v3/verifier/trajectory.d.ts +50 -0
- package/dist/esm/lib/v3/verifier/trajectory.js +273 -0
- package/dist/esm/lib/v3/verifier/trajectory.js.map +1 -0
- package/dist/esm/lib/v3/verifier/types.d.ts +281 -0
- package/dist/esm/lib/v3/verifier/types.js +9 -0
- package/dist/esm/lib/v3/verifier/types.js.map +1 -0
- package/dist/esm/lib/v3Evaluator.d.ts +9 -4
- package/dist/esm/lib/v3Evaluator.js +148 -0
- package/dist/esm/lib/v3Evaluator.js.map +1 -1
- package/dist/esm/lib/v3LegacyEvaluator.js +5 -1
- package/dist/esm/lib/v3LegacyEvaluator.js.map +1 -1
- package/dist/esm/lib/version.d.ts +1 -1
- package/dist/esm/lib/version.js +1 -1
- package/dist/esm/lib/version.js.map +1 -1
- package/package.json +16 -10
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* AUTO-GENERATED FILE. DO NOT EDIT.
|
|
3
|
+
* Run `pnpm run build-dom-scripts` to regenerate.
|
|
4
|
+
*/
|
|
5
|
+
export const selectorRuntimeBootstrap = "if (!globalThis.__stagehandSelectorRuntime) { var __stagehandSelectorRuntimeFactory=(()=>{var P=Object.defineProperty;var A=Object.getOwnPropertyDescriptor;var N=Object.getOwnPropertyNames;var D=Object.prototype.hasOwnProperty;var $=(t,e)=>{for(var n in e)P(t,n,{get:e[n],enumerable:!0})},C=(t,e,n,r)=>{if(e&&typeof e==\"object\"||typeof e==\"function\")for(let s of N(e))!D.call(t,s)&&s!==n&&P(t,s,{get:()=>e[s],enumerable:!(r=A(e,s))||r.enumerable});return t};var k=t=>C(P({},\"__esModule\",{value:!0}),t);var j={};$(j,{countCssWithRoots:()=>B,countTextWithRoots:()=>Y,countXPathNative:()=>U,countXPathWithRoots:()=>K,hasOpenShadowRoots:()=>V,queryCssWithRoots:()=>X,queryTextWithRoots:()=>M,queryXPathNative:()=>Z,queryXPathWithRoots:()=>z});function R(t){let e=String(t||\"\").trim().replace(/^xpath=/i,\"\");if(!e)return[];let n=[],r=0;for(;r<e.length;){let s=\"child\";e.startsWith(\"//\",r)?(s=\"desc\",r+=2):e[r]===\"/\"&&(s=\"child\",r+=1);let o=r,a=0,i=null;for(;r<e.length;){let l=e[r];if(i)l===i&&(i=null);else if(l===\"'\"||l==='\"')i=l;else if(l===\"[\")a++;else if(l===\"]\")a--;else if(l===\"/\"&&a===0)break;r+=1}let u=e.slice(o,r).trim();if(!u)continue;let{tag:c,predicates:f}=W(u);n.push({axis:s,tag:c,predicates:f})}return n}function q(t){let e=[],n=0;for(;n<t.length;){if(t[n]!==\"[\"){n++;continue}n++;let r=n,s=null;for(;n<t.length;){let o=t[n];if(s)o===s&&(s=null);else if(o===\"'\"||o==='\"')s=o;else if(o===\"]\")break;n++}e.push(t.slice(r,n).trim()),n++}return e}function W(t){let e=t.indexOf(\"[\");if(e===-1)return{tag:t===\"\"?\"*\":t.toLowerCase(),predicates:[]};let n=t.slice(0,e).trim(),r=n===\"\"?\"*\":n.toLowerCase(),s=t.slice(e),o=[];for(let a of q(s)){let i=d(a);i&&o.push(i)}return{tag:r,predicates:o}}function d(t){let e=t.trim();if(!e)return null;let n=y(e,\"or\");if(n.length>1){let o=n.map(a=>d(a)).filter(Boolean);return o.length!==n.length?null:{type:\"or\",predicates:o}}let r=y(e,\"and\");if(r.length>1){let o=r.map(a=>d(a)).filter(Boolean);return o.length!==r.length?null:{type:\"and\",predicates:o}}let s=O(e,\"not\");if(s!=null){let o=d(s);return o?{type:\"not\",predicate:o}:null}return _(e)}function _(t){let e=/^(?:'([^']*)'|\"([^\"]*)\")$/,n=\"[a-zA-Z_][\\\\w.-]*\",r=`(?:'([^']*)'|\"([^\"]*)\")`;if(/^\\d+$/.test(t))return{type:\"index\",index:Math.max(1,Number(t))};let s=t.match(new RegExp(`^normalize-space\\\\(\\\\s*@(${n})\\\\s*\\\\)\\\\s*=\\\\s*${r}$`));if(s)return{type:\"attrEquals\",name:s[1],value:s[2]??s[3]??\"\",normalize:!0};let o=t.match(new RegExp(`^normalize-space\\\\(\\\\s*(?:text\\\\(\\\\)|\\\\.)\\\\s*\\\\)\\\\s*=\\\\s*${r}$`));if(o)return{type:\"textEquals\",value:o[1]??o[2]??\"\",normalize:!0};let a=t.match(new RegExp(`^@(${n})\\\\s*=\\\\s*${r}$`));if(a)return{type:\"attrEquals\",name:a[1],value:a[2]??a[3]??\"\"};let i=t.match(new RegExp(`^@(${n})$`));if(i)return{type:\"attrExists\",name:i[1]};let u=t.match(new RegExp(`^contains\\\\(\\\\s*@(${n})\\\\s*,\\\\s*${r}\\\\s*\\\\)$`));if(u)return{type:\"attrContains\",name:u[1],value:u[2]??u[3]??\"\"};let c=t.match(new RegExp(`^starts-with\\\\(\\\\s*@(${n})\\\\s*,\\\\s*${r}\\\\s*\\\\)$`));if(c)return{type:\"attrStartsWith\",name:c[1],value:c[2]??c[3]??\"\"};let f=t.match(new RegExp(`^(?:text\\\\(\\\\)|\\\\.)\\\\s*=\\\\s*${r}$`));if(f)return{type:\"textEquals\",value:f[1]??f[2]??\"\"};let l=t.match(new RegExp(`^contains\\\\(\\\\s*(?:text\\\\(\\\\)|\\\\.)\\\\s*,\\\\s*${r}\\\\s*\\\\)$`));return l?{type:\"textContains\",value:l[1]??l[2]??\"\"}:(e.test(t),null)}function y(t,e){let n=[],r=0,s=0,o=null,a=0;for(;a<t.length;){let i=t[a];if(o){i===o&&(o=null),a+=1;continue}if(i===\"'\"||i==='\"'){o=i,a+=1;continue}if(i===\"(\"){s+=1,a+=1;continue}if(i===\")\"){s=Math.max(0,s-1),a+=1;continue}if(s===0&&L(t,a,e)){n.push(t.slice(r,a).trim()),a+=e.length,r=a;continue}a+=1}return n.push(t.slice(r).trim()),n.filter(i=>i.length>0)}function L(t,e,n){if(!t.startsWith(n,e))return!1;let r=e>0?t[e-1]:\" \";if(r===\"@\")return!1;let s=e+n.length<t.length?t[e+n.length]:\" \";return S(r)&&S(s)}function S(t){return!/[a-zA-Z0-9_.-]/.test(t)}function O(t,e){let n=`${e}(`;if(!t.startsWith(n)||!t.endsWith(\")\"))return null;let r=t.slice(n.length,-1);return I(r)?r:null}function I(t){let e=0,n=null;for(let r=0;r<t.length;r+=1){let s=t[r];if(n){s===n&&(n=null);continue}if(s===\"'\"||s==='\"'){n=s;continue}if(s===\"(\"?e+=1:s===\")\"&&(e-=1),e<0)return!1}return e===0}var F=t=>t.replace(/\\s+/g,\" \").trim();function b(t){return String(t.textContent??\"\")}function m(t,e){return e?F(t):t}function x(t,e){switch(e.type){case\"and\":return e.predicates.every(n=>x(t,n));case\"or\":return e.predicates.some(n=>x(t,n));case\"not\":return!x(t,e.predicate);case\"attrExists\":return t.getAttribute(e.name)!==null;case\"attrEquals\":{let n=t.getAttribute(e.name);return n===null?!1:m(n,e.normalize)===m(e.value,e.normalize)}case\"attrContains\":{let n=t.getAttribute(e.name);return n===null?!1:m(n,e.normalize).includes(m(e.value,e.normalize))}case\"attrStartsWith\":{let n=t.getAttribute(e.name);return n===null?!1:m(n,e.normalize).startsWith(m(e.value,e.normalize))}case\"textEquals\":return m(b(t),e.normalize)===m(e.value,e.normalize);case\"textContains\":return m(b(t),e.normalize).includes(m(e.value,e.normalize));case\"index\":return!0;default:return!0}}function v(t,e){let n=t;for(let r of e){if(!n.length)return[];if(r.type===\"index\"){let s=r.index-1;n=s>=0&&s<n.length?[n[s]]:[];continue}n=n.filter(s=>x(s,r))}return n}function w(t){let e=new Map;for(let n=0;n<t.length;n+=2){let r=t[n],s=t[n+1];r instanceof Element&&s instanceof ShadowRoot&&e.set(r,s)}return e}function E(t,e){if(!t)return[];if(t instanceof Document)return t.documentElement?[t.documentElement]:[];if(t instanceof ShadowRoot||t instanceof DocumentFragment)return Array.from(t.children||[]);if(!(t instanceof Element))return[];let n=Array.from(t.children||[]);t.shadowRoot&&n.push(...Array.from(t.shadowRoot.children||[]));let r=e.get(t);return r&&n.push(...Array.from(r.children||[])),n}function H(t,e){let n=[],r=new Set,s=[...E(t,e)].reverse();for(;s.length;){let o=s.pop();if(!(o instanceof Element)||r.has(o))continue;r.add(o),n.push(o);let a=E(o,e);for(let i=a.length-1;i>=0;i-=1)s.push(a[i])}return n}function X(t,e,...n){let r=w(n),s=[],o=new Set,a=[...E(this,r)].reverse();for(;a.length&&s.length<e;){let i=a.pop();if(!(i instanceof Element)||o.has(i))continue;o.add(i);try{if(i.matches(t)&&(s.push(i),s.length>=e))break}catch{return[]}let u=E(i,r);for(let c=u.length-1;c>=0;c-=1)a.push(u[c])}return s}function B(t,...e){return X.call(this,t,Number.MAX_SAFE_INTEGER,...e).length}function M(t,e,...n){let r=w(n),s=new Set([\"SCRIPT\",\"STYLE\",\"TEMPLATE\",\"NOSCRIPT\",\"HEAD\",\"TITLE\",\"LINK\",\"META\",\"HTML\",\"BODY\"]),o=String(t||\"\").toLowerCase();if(!o)return[];let a=l=>{let g=l.tagName?l.tagName.toUpperCase():\"\";if(s.has(g))return\"\";try{let p=l.innerText;if(typeof p==\"string\"&&p.trim())return p.trim()}catch{}let h=l.textContent;return typeof h==\"string\"?h.trim():\"\"},i=[],u=new Set,c=[...E(this,r)].reverse();for(;c.length;){let l=c.pop();if(!(l instanceof Element)||u.has(l))continue;u.add(l);let g=a(l);g&&g.toLowerCase().includes(o)&&i.push(l);let h=E(l,r);for(let p=h.length-1;p>=0;p-=1)c.push(h[p])}let f=[];for(let l of i){let g=!1;for(let h of i)if(l!==h)try{if(l.contains(h)){g=!0;break}}catch{}if(!g&&(f.push(l),f.length>=e))break}return f}function Y(t,...e){return M.call(this,t,Number.MAX_SAFE_INTEGER,...e).length}function T(t){let e=String(t||\"\").trim();return e?e.replace(/^xpath=/i,\"\").trim():\"\"}function G(t,e){return e.tag===\"*\"?!0:t.localName===e.tag}function z(t,e,...n){let r=w(n),s=R(t);if(!s.length)return[];let o=[this];for(let a of s){let i=[],u=new Set;for(let c of o){let l=(a.axis===\"child\"?E(c,r):H(c,r)).filter(h=>G(h,a)),g=v(l,a.predicates);for(let h of g)if(!u.has(h)&&(u.add(h),i.push(h),i.length>=e&&a===s[s.length-1]))break}if(!i.length)return[];o=i}return o.slice(0,e)}function K(t,...e){return z.call(this,t,Number.MAX_SAFE_INTEGER,...e).length}function Z(t,e){let n=T(t);if(!n||!Number.isFinite(e)||e<=0)return[];try{let r=this.evaluate(n,this,null,XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,null),s=[],o=Math.min(r.snapshotLength,Math.floor(e));for(let a=0;a<o;a+=1){let i=r.snapshotItem(a);i instanceof Element&&s.push(i)}return s}catch{return[]}}function U(t){let e=T(t);if(!e)return 0;try{let n=this.evaluate(e,this,null,XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,null),r=0;for(let s=0;s<n.snapshotLength;s+=1)n.snapshotItem(s)instanceof Element&&(r+=1);return r}catch{return 0}}function V(){try{let t=this.createTreeWalker(this,NodeFilter.SHOW_ELEMENT);for(;t.nextNode();){let e=t.currentNode;if(e instanceof Element&&e.shadowRoot)return!0}}catch{return!1}return!1}return k(j);})();\n globalThis.__stagehandSelectorRuntime = __stagehandSelectorRuntimeFactory;\n}";
|
|
6
|
+
export const selectorRuntimeSources = {
|
|
7
|
+
"countCssWithRoots": "function O(t,...e){return C.call(this,t,Number.MAX_SAFE_INTEGER,...e).length}",
|
|
8
|
+
"countTextWithRoots": "function I(t,...e){return k.call(this,t,Number.MAX_SAFE_INTEGER,...e).length}",
|
|
9
|
+
"countXPathNative": "function B(t){let e=v(t);if(!e)return 0;try{let n=this.evaluate(e,this,null,XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,null),r=0;for(let s=0;s<n.snapshotLength;s+=1)n.snapshotItem(s)instanceof Element&&(r+=1);return r}catch{return 0}}",
|
|
10
|
+
"countXPathWithRoots": "function F(t,...e){return W.call(this,t,Number.MAX_SAFE_INTEGER,...e).length}",
|
|
11
|
+
"hasOpenShadowRoots": "function Y(){try{let t=this.createTreeWalker(this,NodeFilter.SHOW_ELEMENT);for(;t.nextNode();){let e=t.currentNode;if(e instanceof Element&&e.shadowRoot)return!0}}catch{return!1}return!1}",
|
|
12
|
+
"queryCssWithRoots": "function C(t,e,...n){let r=P(n),s=[],o=new Set,a=[...E(this,r)].reverse();for(;a.length&&s.length<e;){let i=a.pop();if(!(i instanceof Element)||o.has(i))continue;o.add(i);try{if(i.matches(t)&&(s.push(i),s.length>=e))break}catch{return[]}let u=E(i,r);for(let c=u.length-1;c>=0;c-=1)a.push(u[c])}return s}",
|
|
13
|
+
"queryTextWithRoots": "function k(t,e,...n){let r=P(n),s=new Set([\"SCRIPT\",\"STYLE\",\"TEMPLATE\",\"NOSCRIPT\",\"HEAD\",\"TITLE\",\"LINK\",\"META\",\"HTML\",\"BODY\"]),o=String(t||\"\").toLowerCase();if(!o)return[];let a=l=>{let g=l.tagName?l.tagName.toUpperCase():\"\";if(s.has(g))return\"\";try{let p=l.innerText;if(typeof p==\"string\"&&p.trim())return p.trim()}catch{}let h=l.textContent;return typeof h==\"string\"?h.trim():\"\"},i=[],u=new Set,c=[...E(this,r)].reverse();for(;c.length;){let l=c.pop();if(!(l instanceof Element)||u.has(l))continue;u.add(l);let g=a(l);g&&g.toLowerCase().includes(o)&&i.push(l);let h=E(l,r);for(let p=h.length-1;p>=0;p-=1)c.push(h[p])}let f=[];for(let l of i){let g=!1;for(let h of i)if(l!==h)try{if(l.contains(h)){g=!0;break}}catch{}if(!g&&(f.push(l),f.length>=e))break}return f}",
|
|
14
|
+
"queryXPathNative": "function H(t,e){let n=v(t);if(!n||!Number.isFinite(e)||e<=0)return[];try{let r=this.evaluate(n,this,null,XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,null),s=[],o=Math.min(r.snapshotLength,Math.floor(e));for(let a=0;a<o;a+=1){let i=r.snapshotItem(a);i instanceof Element&&s.push(i)}return s}catch{return[]}}",
|
|
15
|
+
"queryXPathWithRoots": "function W(t,e,...n){let r=P(n),s=b(t);if(!s.length)return[];let o=[this];for(let a of s){let i=[],u=new Set;for(let c of o){let l=(a.axis===\"child\"?E(c,r):$(c,r)).filter(h=>q(h,a)),g=R(l,a.predicates);for(let h of g)if(!u.has(h)&&(u.add(h),i.push(h),i.length>=e&&a===s[s.length-1]))break}if(!i.length)return[];o=i}return o.slice(0,e)}"
|
|
16
|
+
};
|
|
17
|
+
export const selectorRuntimeGlobalRefs = {
|
|
18
|
+
"countCssWithRoots": "globalThis.__stagehandSelectorRuntime.countCssWithRoots",
|
|
19
|
+
"countTextWithRoots": "globalThis.__stagehandSelectorRuntime.countTextWithRoots",
|
|
20
|
+
"countXPathNative": "globalThis.__stagehandSelectorRuntime.countXPathNative",
|
|
21
|
+
"countXPathWithRoots": "globalThis.__stagehandSelectorRuntime.countXPathWithRoots",
|
|
22
|
+
"hasOpenShadowRoots": "globalThis.__stagehandSelectorRuntime.hasOpenShadowRoots",
|
|
23
|
+
"queryCssWithRoots": "globalThis.__stagehandSelectorRuntime.queryCssWithRoots",
|
|
24
|
+
"queryTextWithRoots": "globalThis.__stagehandSelectorRuntime.queryTextWithRoots",
|
|
25
|
+
"queryXPathNative": "globalThis.__stagehandSelectorRuntime.queryXPathNative",
|
|
26
|
+
"queryXPathWithRoots": "globalThis.__stagehandSelectorRuntime.queryXPathWithRoots"
|
|
27
|
+
};
|
|
28
|
+
//# sourceMappingURL=selectorRuntime.generated.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"selectorRuntime.generated.js","sourceRoot":"","sources":["../../../../../../lib/v3/dom/build/selectorRuntime.generated.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,MAAM,CAAC,MAAM,wBAAwB,GAAG,0oRAA0oR,CAAC;AACnrR,MAAM,CAAC,MAAM,sBAAsB,GAAG;IACpC,mBAAmB,EAAE,+EAA+E;IACpG,oBAAoB,EAAE,+EAA+E;IACrG,kBAAkB,EAAE,wOAAwO;IAC5P,qBAAqB,EAAE,+EAA+E;IACtG,oBAAoB,EAAE,6LAA6L;IACnN,mBAAmB,EAAE,iTAAiT;IACtU,oBAAoB,EAAE,8xBAA8xB;IACpzB,kBAAkB,EAAE,+SAA+S;IACnU,qBAAqB,EAAE,mVAAmV;CAClW,CAAC;AACX,MAAM,CAAC,MAAM,yBAAyB,GAAG;IACvC,mBAAmB,EAAE,yDAAyD;IAC9E,oBAAoB,EAAE,0DAA0D;IAChF,kBAAkB,EAAE,wDAAwD;IAC5E,qBAAqB,EAAE,2DAA2D;IAClF,oBAAoB,EAAE,0DAA0D;IAChF,mBAAmB,EAAE,yDAAyD;IAC9E,oBAAoB,EAAE,0DAA0D;IAChF,kBAAkB,EAAE,wDAAwD;IAC5E,qBAAqB,EAAE,2DAA2D;CAC1E,CAAC","sourcesContent":["/*\n * AUTO-GENERATED FILE. DO NOT EDIT.\n * Run `pnpm run build-dom-scripts` to regenerate.\n */\nexport const selectorRuntimeBootstrap = \"if (!globalThis.__stagehandSelectorRuntime) { var __stagehandSelectorRuntimeFactory=(()=>{var P=Object.defineProperty;var A=Object.getOwnPropertyDescriptor;var N=Object.getOwnPropertyNames;var D=Object.prototype.hasOwnProperty;var $=(t,e)=>{for(var n in e)P(t,n,{get:e[n],enumerable:!0})},C=(t,e,n,r)=>{if(e&&typeof e==\\\"object\\\"||typeof e==\\\"function\\\")for(let s of N(e))!D.call(t,s)&&s!==n&&P(t,s,{get:()=>e[s],enumerable:!(r=A(e,s))||r.enumerable});return t};var k=t=>C(P({},\\\"__esModule\\\",{value:!0}),t);var j={};$(j,{countCssWithRoots:()=>B,countTextWithRoots:()=>Y,countXPathNative:()=>U,countXPathWithRoots:()=>K,hasOpenShadowRoots:()=>V,queryCssWithRoots:()=>X,queryTextWithRoots:()=>M,queryXPathNative:()=>Z,queryXPathWithRoots:()=>z});function R(t){let e=String(t||\\\"\\\").trim().replace(/^xpath=/i,\\\"\\\");if(!e)return[];let n=[],r=0;for(;r<e.length;){let s=\\\"child\\\";e.startsWith(\\\"//\\\",r)?(s=\\\"desc\\\",r+=2):e[r]===\\\"/\\\"&&(s=\\\"child\\\",r+=1);let o=r,a=0,i=null;for(;r<e.length;){let l=e[r];if(i)l===i&&(i=null);else if(l===\\\"'\\\"||l==='\\\"')i=l;else if(l===\\\"[\\\")a++;else if(l===\\\"]\\\")a--;else if(l===\\\"/\\\"&&a===0)break;r+=1}let u=e.slice(o,r).trim();if(!u)continue;let{tag:c,predicates:f}=W(u);n.push({axis:s,tag:c,predicates:f})}return n}function q(t){let e=[],n=0;for(;n<t.length;){if(t[n]!==\\\"[\\\"){n++;continue}n++;let r=n,s=null;for(;n<t.length;){let o=t[n];if(s)o===s&&(s=null);else if(o===\\\"'\\\"||o==='\\\"')s=o;else if(o===\\\"]\\\")break;n++}e.push(t.slice(r,n).trim()),n++}return e}function W(t){let e=t.indexOf(\\\"[\\\");if(e===-1)return{tag:t===\\\"\\\"?\\\"*\\\":t.toLowerCase(),predicates:[]};let n=t.slice(0,e).trim(),r=n===\\\"\\\"?\\\"*\\\":n.toLowerCase(),s=t.slice(e),o=[];for(let a of q(s)){let i=d(a);i&&o.push(i)}return{tag:r,predicates:o}}function d(t){let e=t.trim();if(!e)return null;let n=y(e,\\\"or\\\");if(n.length>1){let o=n.map(a=>d(a)).filter(Boolean);return o.length!==n.length?null:{type:\\\"or\\\",predicates:o}}let r=y(e,\\\"and\\\");if(r.length>1){let o=r.map(a=>d(a)).filter(Boolean);return o.length!==r.length?null:{type:\\\"and\\\",predicates:o}}let s=O(e,\\\"not\\\");if(s!=null){let o=d(s);return o?{type:\\\"not\\\",predicate:o}:null}return _(e)}function _(t){let e=/^(?:'([^']*)'|\\\"([^\\\"]*)\\\")$/,n=\\\"[a-zA-Z_][\\\\\\\\w.-]*\\\",r=`(?:'([^']*)'|\\\"([^\\\"]*)\\\")`;if(/^\\\\d+$/.test(t))return{type:\\\"index\\\",index:Math.max(1,Number(t))};let s=t.match(new RegExp(`^normalize-space\\\\\\\\(\\\\\\\\s*@(${n})\\\\\\\\s*\\\\\\\\)\\\\\\\\s*=\\\\\\\\s*${r}$`));if(s)return{type:\\\"attrEquals\\\",name:s[1],value:s[2]??s[3]??\\\"\\\",normalize:!0};let o=t.match(new RegExp(`^normalize-space\\\\\\\\(\\\\\\\\s*(?:text\\\\\\\\(\\\\\\\\)|\\\\\\\\.)\\\\\\\\s*\\\\\\\\)\\\\\\\\s*=\\\\\\\\s*${r}$`));if(o)return{type:\\\"textEquals\\\",value:o[1]??o[2]??\\\"\\\",normalize:!0};let a=t.match(new RegExp(`^@(${n})\\\\\\\\s*=\\\\\\\\s*${r}$`));if(a)return{type:\\\"attrEquals\\\",name:a[1],value:a[2]??a[3]??\\\"\\\"};let i=t.match(new RegExp(`^@(${n})$`));if(i)return{type:\\\"attrExists\\\",name:i[1]};let u=t.match(new RegExp(`^contains\\\\\\\\(\\\\\\\\s*@(${n})\\\\\\\\s*,\\\\\\\\s*${r}\\\\\\\\s*\\\\\\\\)$`));if(u)return{type:\\\"attrContains\\\",name:u[1],value:u[2]??u[3]??\\\"\\\"};let c=t.match(new RegExp(`^starts-with\\\\\\\\(\\\\\\\\s*@(${n})\\\\\\\\s*,\\\\\\\\s*${r}\\\\\\\\s*\\\\\\\\)$`));if(c)return{type:\\\"attrStartsWith\\\",name:c[1],value:c[2]??c[3]??\\\"\\\"};let f=t.match(new RegExp(`^(?:text\\\\\\\\(\\\\\\\\)|\\\\\\\\.)\\\\\\\\s*=\\\\\\\\s*${r}$`));if(f)return{type:\\\"textEquals\\\",value:f[1]??f[2]??\\\"\\\"};let l=t.match(new RegExp(`^contains\\\\\\\\(\\\\\\\\s*(?:text\\\\\\\\(\\\\\\\\)|\\\\\\\\.)\\\\\\\\s*,\\\\\\\\s*${r}\\\\\\\\s*\\\\\\\\)$`));return l?{type:\\\"textContains\\\",value:l[1]??l[2]??\\\"\\\"}:(e.test(t),null)}function y(t,e){let n=[],r=0,s=0,o=null,a=0;for(;a<t.length;){let i=t[a];if(o){i===o&&(o=null),a+=1;continue}if(i===\\\"'\\\"||i==='\\\"'){o=i,a+=1;continue}if(i===\\\"(\\\"){s+=1,a+=1;continue}if(i===\\\")\\\"){s=Math.max(0,s-1),a+=1;continue}if(s===0&&L(t,a,e)){n.push(t.slice(r,a).trim()),a+=e.length,r=a;continue}a+=1}return n.push(t.slice(r).trim()),n.filter(i=>i.length>0)}function L(t,e,n){if(!t.startsWith(n,e))return!1;let r=e>0?t[e-1]:\\\" \\\";if(r===\\\"@\\\")return!1;let s=e+n.length<t.length?t[e+n.length]:\\\" \\\";return S(r)&&S(s)}function S(t){return!/[a-zA-Z0-9_.-]/.test(t)}function O(t,e){let n=`${e}(`;if(!t.startsWith(n)||!t.endsWith(\\\")\\\"))return null;let r=t.slice(n.length,-1);return I(r)?r:null}function I(t){let e=0,n=null;for(let r=0;r<t.length;r+=1){let s=t[r];if(n){s===n&&(n=null);continue}if(s===\\\"'\\\"||s==='\\\"'){n=s;continue}if(s===\\\"(\\\"?e+=1:s===\\\")\\\"&&(e-=1),e<0)return!1}return e===0}var F=t=>t.replace(/\\\\s+/g,\\\" \\\").trim();function b(t){return String(t.textContent??\\\"\\\")}function m(t,e){return e?F(t):t}function x(t,e){switch(e.type){case\\\"and\\\":return e.predicates.every(n=>x(t,n));case\\\"or\\\":return e.predicates.some(n=>x(t,n));case\\\"not\\\":return!x(t,e.predicate);case\\\"attrExists\\\":return t.getAttribute(e.name)!==null;case\\\"attrEquals\\\":{let n=t.getAttribute(e.name);return n===null?!1:m(n,e.normalize)===m(e.value,e.normalize)}case\\\"attrContains\\\":{let n=t.getAttribute(e.name);return n===null?!1:m(n,e.normalize).includes(m(e.value,e.normalize))}case\\\"attrStartsWith\\\":{let n=t.getAttribute(e.name);return n===null?!1:m(n,e.normalize).startsWith(m(e.value,e.normalize))}case\\\"textEquals\\\":return m(b(t),e.normalize)===m(e.value,e.normalize);case\\\"textContains\\\":return m(b(t),e.normalize).includes(m(e.value,e.normalize));case\\\"index\\\":return!0;default:return!0}}function v(t,e){let n=t;for(let r of e){if(!n.length)return[];if(r.type===\\\"index\\\"){let s=r.index-1;n=s>=0&&s<n.length?[n[s]]:[];continue}n=n.filter(s=>x(s,r))}return n}function w(t){let e=new Map;for(let n=0;n<t.length;n+=2){let r=t[n],s=t[n+1];r instanceof Element&&s instanceof ShadowRoot&&e.set(r,s)}return e}function E(t,e){if(!t)return[];if(t instanceof Document)return t.documentElement?[t.documentElement]:[];if(t instanceof ShadowRoot||t instanceof DocumentFragment)return Array.from(t.children||[]);if(!(t instanceof Element))return[];let n=Array.from(t.children||[]);t.shadowRoot&&n.push(...Array.from(t.shadowRoot.children||[]));let r=e.get(t);return r&&n.push(...Array.from(r.children||[])),n}function H(t,e){let n=[],r=new Set,s=[...E(t,e)].reverse();for(;s.length;){let o=s.pop();if(!(o instanceof Element)||r.has(o))continue;r.add(o),n.push(o);let a=E(o,e);for(let i=a.length-1;i>=0;i-=1)s.push(a[i])}return n}function X(t,e,...n){let r=w(n),s=[],o=new Set,a=[...E(this,r)].reverse();for(;a.length&&s.length<e;){let i=a.pop();if(!(i instanceof Element)||o.has(i))continue;o.add(i);try{if(i.matches(t)&&(s.push(i),s.length>=e))break}catch{return[]}let u=E(i,r);for(let c=u.length-1;c>=0;c-=1)a.push(u[c])}return s}function B(t,...e){return X.call(this,t,Number.MAX_SAFE_INTEGER,...e).length}function M(t,e,...n){let r=w(n),s=new Set([\\\"SCRIPT\\\",\\\"STYLE\\\",\\\"TEMPLATE\\\",\\\"NOSCRIPT\\\",\\\"HEAD\\\",\\\"TITLE\\\",\\\"LINK\\\",\\\"META\\\",\\\"HTML\\\",\\\"BODY\\\"]),o=String(t||\\\"\\\").toLowerCase();if(!o)return[];let a=l=>{let g=l.tagName?l.tagName.toUpperCase():\\\"\\\";if(s.has(g))return\\\"\\\";try{let p=l.innerText;if(typeof p==\\\"string\\\"&&p.trim())return p.trim()}catch{}let h=l.textContent;return typeof h==\\\"string\\\"?h.trim():\\\"\\\"},i=[],u=new Set,c=[...E(this,r)].reverse();for(;c.length;){let l=c.pop();if(!(l instanceof Element)||u.has(l))continue;u.add(l);let g=a(l);g&&g.toLowerCase().includes(o)&&i.push(l);let h=E(l,r);for(let p=h.length-1;p>=0;p-=1)c.push(h[p])}let f=[];for(let l of i){let g=!1;for(let h of i)if(l!==h)try{if(l.contains(h)){g=!0;break}}catch{}if(!g&&(f.push(l),f.length>=e))break}return f}function Y(t,...e){return M.call(this,t,Number.MAX_SAFE_INTEGER,...e).length}function T(t){let e=String(t||\\\"\\\").trim();return e?e.replace(/^xpath=/i,\\\"\\\").trim():\\\"\\\"}function G(t,e){return e.tag===\\\"*\\\"?!0:t.localName===e.tag}function z(t,e,...n){let r=w(n),s=R(t);if(!s.length)return[];let o=[this];for(let a of s){let i=[],u=new Set;for(let c of o){let l=(a.axis===\\\"child\\\"?E(c,r):H(c,r)).filter(h=>G(h,a)),g=v(l,a.predicates);for(let h of g)if(!u.has(h)&&(u.add(h),i.push(h),i.length>=e&&a===s[s.length-1]))break}if(!i.length)return[];o=i}return o.slice(0,e)}function K(t,...e){return z.call(this,t,Number.MAX_SAFE_INTEGER,...e).length}function Z(t,e){let n=T(t);if(!n||!Number.isFinite(e)||e<=0)return[];try{let r=this.evaluate(n,this,null,XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,null),s=[],o=Math.min(r.snapshotLength,Math.floor(e));for(let a=0;a<o;a+=1){let i=r.snapshotItem(a);i instanceof Element&&s.push(i)}return s}catch{return[]}}function U(t){let e=T(t);if(!e)return 0;try{let n=this.evaluate(e,this,null,XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,null),r=0;for(let s=0;s<n.snapshotLength;s+=1)n.snapshotItem(s)instanceof Element&&(r+=1);return r}catch{return 0}}function V(){try{let t=this.createTreeWalker(this,NodeFilter.SHOW_ELEMENT);for(;t.nextNode();){let e=t.currentNode;if(e instanceof Element&&e.shadowRoot)return!0}}catch{return!1}return!1}return k(j);})();\\n globalThis.__stagehandSelectorRuntime = __stagehandSelectorRuntimeFactory;\\n}\";\nexport const selectorRuntimeSources = {\n \"countCssWithRoots\": \"function O(t,...e){return C.call(this,t,Number.MAX_SAFE_INTEGER,...e).length}\",\n \"countTextWithRoots\": \"function I(t,...e){return k.call(this,t,Number.MAX_SAFE_INTEGER,...e).length}\",\n \"countXPathNative\": \"function B(t){let e=v(t);if(!e)return 0;try{let n=this.evaluate(e,this,null,XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,null),r=0;for(let s=0;s<n.snapshotLength;s+=1)n.snapshotItem(s)instanceof Element&&(r+=1);return r}catch{return 0}}\",\n \"countXPathWithRoots\": \"function F(t,...e){return W.call(this,t,Number.MAX_SAFE_INTEGER,...e).length}\",\n \"hasOpenShadowRoots\": \"function Y(){try{let t=this.createTreeWalker(this,NodeFilter.SHOW_ELEMENT);for(;t.nextNode();){let e=t.currentNode;if(e instanceof Element&&e.shadowRoot)return!0}}catch{return!1}return!1}\",\n \"queryCssWithRoots\": \"function C(t,e,...n){let r=P(n),s=[],o=new Set,a=[...E(this,r)].reverse();for(;a.length&&s.length<e;){let i=a.pop();if(!(i instanceof Element)||o.has(i))continue;o.add(i);try{if(i.matches(t)&&(s.push(i),s.length>=e))break}catch{return[]}let u=E(i,r);for(let c=u.length-1;c>=0;c-=1)a.push(u[c])}return s}\",\n \"queryTextWithRoots\": \"function k(t,e,...n){let r=P(n),s=new Set([\\\"SCRIPT\\\",\\\"STYLE\\\",\\\"TEMPLATE\\\",\\\"NOSCRIPT\\\",\\\"HEAD\\\",\\\"TITLE\\\",\\\"LINK\\\",\\\"META\\\",\\\"HTML\\\",\\\"BODY\\\"]),o=String(t||\\\"\\\").toLowerCase();if(!o)return[];let a=l=>{let g=l.tagName?l.tagName.toUpperCase():\\\"\\\";if(s.has(g))return\\\"\\\";try{let p=l.innerText;if(typeof p==\\\"string\\\"&&p.trim())return p.trim()}catch{}let h=l.textContent;return typeof h==\\\"string\\\"?h.trim():\\\"\\\"},i=[],u=new Set,c=[...E(this,r)].reverse();for(;c.length;){let l=c.pop();if(!(l instanceof Element)||u.has(l))continue;u.add(l);let g=a(l);g&&g.toLowerCase().includes(o)&&i.push(l);let h=E(l,r);for(let p=h.length-1;p>=0;p-=1)c.push(h[p])}let f=[];for(let l of i){let g=!1;for(let h of i)if(l!==h)try{if(l.contains(h)){g=!0;break}}catch{}if(!g&&(f.push(l),f.length>=e))break}return f}\",\n \"queryXPathNative\": \"function H(t,e){let n=v(t);if(!n||!Number.isFinite(e)||e<=0)return[];try{let r=this.evaluate(n,this,null,XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,null),s=[],o=Math.min(r.snapshotLength,Math.floor(e));for(let a=0;a<o;a+=1){let i=r.snapshotItem(a);i instanceof Element&&s.push(i)}return s}catch{return[]}}\",\n \"queryXPathWithRoots\": \"function W(t,e,...n){let r=P(n),s=b(t);if(!s.length)return[];let o=[this];for(let a of s){let i=[],u=new Set;for(let c of o){let l=(a.axis===\\\"child\\\"?E(c,r):$(c,r)).filter(h=>q(h,a)),g=R(l,a.predicates);for(let h of g)if(!u.has(h)&&(u.add(h),i.push(h),i.length>=e&&a===s[s.length-1]))break}if(!i.length)return[];o=i}return o.slice(0,e)}\"\n} as const;\nexport const selectorRuntimeGlobalRefs = {\n \"countCssWithRoots\": \"globalThis.__stagehandSelectorRuntime.countCssWithRoots\",\n \"countTextWithRoots\": \"globalThis.__stagehandSelectorRuntime.countTextWithRoots\",\n \"countXPathNative\": \"globalThis.__stagehandSelectorRuntime.countXPathNative\",\n \"countXPathWithRoots\": \"globalThis.__stagehandSelectorRuntime.countXPathWithRoots\",\n \"hasOpenShadowRoots\": \"globalThis.__stagehandSelectorRuntime.hasOpenShadowRoots\",\n \"queryCssWithRoots\": \"globalThis.__stagehandSelectorRuntime.queryCssWithRoots\",\n \"queryTextWithRoots\": \"globalThis.__stagehandSelectorRuntime.queryTextWithRoots\",\n \"queryXPathNative\": \"globalThis.__stagehandSelectorRuntime.queryXPathNative\",\n \"queryXPathWithRoots\": \"globalThis.__stagehandSelectorRuntime.queryXPathWithRoots\"\n} as const;\nexport type SelectorRuntimeName = keyof typeof selectorRuntimeSources;\n"]}
|
|
@@ -28,7 +28,11 @@ export function resolveXPathAtIndex(rawXp, index, options) {
|
|
|
28
28
|
return composed[targetIndex] ?? null;
|
|
29
29
|
}
|
|
30
30
|
const composed = resolveXPathComposedMatches(xp, shadowCtx.getClosedRoot);
|
|
31
|
-
|
|
31
|
+
if (composed.length > 0) {
|
|
32
|
+
return composed[targetIndex] ?? null;
|
|
33
|
+
}
|
|
34
|
+
const shadowHopMatches = resolveStagehandShadowHopMatches(xp, shadowCtx.getClosedRoot);
|
|
35
|
+
return shadowHopMatches[targetIndex] ?? null;
|
|
32
36
|
}
|
|
33
37
|
export function countXPathMatches(rawXp, options) {
|
|
34
38
|
const xp = normalizeXPath(rawXp);
|
|
@@ -45,7 +49,10 @@ export function countXPathMatches(rawXp, options) {
|
|
|
45
49
|
return count.count;
|
|
46
50
|
return resolveXPathComposedMatches(xp, shadowCtx?.getClosedRoot).length;
|
|
47
51
|
}
|
|
48
|
-
|
|
52
|
+
const composedCount = resolveXPathComposedMatches(xp, shadowCtx.getClosedRoot).length;
|
|
53
|
+
if (composedCount > 0)
|
|
54
|
+
return composedCount;
|
|
55
|
+
return resolveStagehandShadowHopMatches(xp, shadowCtx.getClosedRoot).length;
|
|
49
56
|
}
|
|
50
57
|
export function resolveXPathComposedMatches(rawXp, getClosedRoot) {
|
|
51
58
|
const xp = normalizeXPath(rawXp);
|
|
@@ -55,15 +62,11 @@ export function resolveXPathComposedMatches(rawXp, getClosedRoot) {
|
|
|
55
62
|
if (!steps.length)
|
|
56
63
|
return [];
|
|
57
64
|
const closedRoot = getClosedRoot ?? null;
|
|
58
|
-
let current = [
|
|
59
|
-
document,
|
|
60
|
-
];
|
|
65
|
+
let current = [document];
|
|
61
66
|
for (const step of steps) {
|
|
62
67
|
const next = [];
|
|
63
68
|
const seen = new Set();
|
|
64
69
|
for (const root of current) {
|
|
65
|
-
if (!root)
|
|
66
|
-
continue;
|
|
67
70
|
const pool = step.axis === "child"
|
|
68
71
|
? composedChildren(root, closedRoot)
|
|
69
72
|
: composedDescendants(root, closedRoot);
|
|
@@ -84,6 +87,43 @@ export function resolveXPathComposedMatches(rawXp, getClosedRoot) {
|
|
|
84
87
|
}
|
|
85
88
|
return current;
|
|
86
89
|
}
|
|
90
|
+
function resolveStagehandShadowHopMatches(rawXp, getClosedRoot) {
|
|
91
|
+
const xp = normalizeXPath(rawXp);
|
|
92
|
+
if (!xp)
|
|
93
|
+
return [];
|
|
94
|
+
const steps = parseXPathSteps(xp);
|
|
95
|
+
if (!steps.some((step, index) => step.axis === "desc" && index > 0)) {
|
|
96
|
+
return [];
|
|
97
|
+
}
|
|
98
|
+
const closedRoot = getClosedRoot ?? null;
|
|
99
|
+
let current = [document];
|
|
100
|
+
for (let i = 0; i < steps.length; i += 1) {
|
|
101
|
+
const step = steps[i];
|
|
102
|
+
const next = [];
|
|
103
|
+
const seen = new Set();
|
|
104
|
+
for (const root of current) {
|
|
105
|
+
const pool = step.axis === "child"
|
|
106
|
+
? domChildren(root)
|
|
107
|
+
: i === 0
|
|
108
|
+
? composedDescendants(root, closedRoot)
|
|
109
|
+
: shadowRootChildren(root, closedRoot);
|
|
110
|
+
if (!pool.length)
|
|
111
|
+
continue;
|
|
112
|
+
const tagMatches = pool.filter((candidate) => matchesTag(candidate, step));
|
|
113
|
+
const matches = applyPredicates(tagMatches, step.predicates);
|
|
114
|
+
for (const candidate of matches) {
|
|
115
|
+
if (!seen.has(candidate)) {
|
|
116
|
+
seen.add(candidate);
|
|
117
|
+
next.push(candidate);
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
if (!next.length)
|
|
122
|
+
return [];
|
|
123
|
+
current = next;
|
|
124
|
+
}
|
|
125
|
+
return current;
|
|
126
|
+
}
|
|
87
127
|
function matchesTag(element, step) {
|
|
88
128
|
if (step.tag === "*")
|
|
89
129
|
return true;
|
|
@@ -130,8 +170,6 @@ function getShadowContext() {
|
|
|
130
170
|
}
|
|
131
171
|
function composedChildren(node, getClosedRoot) {
|
|
132
172
|
const out = [];
|
|
133
|
-
if (!node)
|
|
134
|
-
return out;
|
|
135
173
|
if (node instanceof Document) {
|
|
136
174
|
if (node.documentElement)
|
|
137
175
|
out.push(node.documentElement);
|
|
@@ -155,13 +193,44 @@ function composedChildren(node, getClosedRoot) {
|
|
|
155
193
|
}
|
|
156
194
|
return out;
|
|
157
195
|
}
|
|
196
|
+
function domChildren(node) {
|
|
197
|
+
const out = [];
|
|
198
|
+
if (node instanceof Document) {
|
|
199
|
+
if (node.documentElement)
|
|
200
|
+
out.push(node.documentElement);
|
|
201
|
+
return out;
|
|
202
|
+
}
|
|
203
|
+
if (node instanceof ShadowRoot || node instanceof DocumentFragment) {
|
|
204
|
+
out.push(...Array.from(node.children ?? []));
|
|
205
|
+
return out;
|
|
206
|
+
}
|
|
207
|
+
if (node instanceof Element) {
|
|
208
|
+
out.push(...Array.from(node.children ?? []));
|
|
209
|
+
return out;
|
|
210
|
+
}
|
|
211
|
+
return out;
|
|
212
|
+
}
|
|
213
|
+
function shadowRootChildren(node, getClosedRoot) {
|
|
214
|
+
const out = [];
|
|
215
|
+
if (!(node instanceof Element))
|
|
216
|
+
return out;
|
|
217
|
+
const open = node.shadowRoot;
|
|
218
|
+
if (open)
|
|
219
|
+
out.push(...Array.from(open.children ?? []));
|
|
220
|
+
if (getClosedRoot) {
|
|
221
|
+
const closed = getClosedRoot(node);
|
|
222
|
+
if (closed)
|
|
223
|
+
out.push(...Array.from(closed.children ?? []));
|
|
224
|
+
}
|
|
225
|
+
return out;
|
|
226
|
+
}
|
|
158
227
|
function composedDescendants(node, getClosedRoot) {
|
|
159
228
|
const out = [];
|
|
160
229
|
const seen = new Set();
|
|
161
230
|
const stack = [...composedChildren(node, getClosedRoot)].reverse();
|
|
162
231
|
while (stack.length) {
|
|
163
232
|
const next = stack.pop();
|
|
164
|
-
if (
|
|
233
|
+
if (seen.has(next))
|
|
165
234
|
continue;
|
|
166
235
|
seen.add(next);
|
|
167
236
|
out.push(next);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"xpathResolver.js","sourceRoot":"","sources":["../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,CAAC;QACF,OAAO;YACL,KAAK,EAAE,QAAQ,CAAC,YAAY,CAAC,KAAK,CAAmB;YACrD,KAAK,EAAE,KAAK;SACb,CAAC;IACJ,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,EAAE,KAAK,EAAE,IAAI,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC;IACtC,CAAC;AACH,CAAC;AAED,SAAS,2BAA2B,CAAC,EAAU;IAI7C,IAAI,CAAC;QACH,MAAM,QAAQ,GAAG,QAAQ,CAAC,QAAQ,CAChC,EAAE,EACF,QAAQ,EACR,IAAI,EACJ,WAAW,CAAC,0BAA0B,EACtC,IAAI,CACL,CAAC;QACF,OAAO,EAAE,KAAK,EAAE,QAAQ,CAAC,cAAc,EAAE,KAAK,EAAE,KAAK,EAAE,CAAC;IAC1D,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,EAAE,KAAK,EAAE,CAAC,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC;IACnC,CAAC;AACH,CAAC","sourcesContent":["import {\n applyPredicates,\n parseXPathSteps,\n type XPathStep,\n} from \"./xpathParser.js\";\n\ntype ClosedRootGetter = (host: Element) => ShadowRoot | null;\n\nexport type XPathResolveOptions = {\n pierceShadow?: boolean;\n};\n\ntype ShadowContext = {\n getClosedRoot: ClosedRootGetter | null;\n hasShadow: boolean;\n};\n\nconst normalizeXPath = (selector: string): string => {\n const raw = String(selector ?? \"\").trim();\n if (!raw) return \"\";\n return raw.replace(/^xpath=/i, \"\").trim();\n};\n\nexport function resolveXPathFirst(\n rawXp: string,\n options?: XPathResolveOptions,\n): Element | null {\n return resolveXPathAtIndex(rawXp, 0, options);\n}\n\nexport function resolveXPathAtIndex(\n rawXp: string,\n index: number,\n options?: XPathResolveOptions,\n): Element | null {\n if (!Number.isFinite(index) || index < 0) return null;\n const xp = normalizeXPath(rawXp);\n if (!xp) return null;\n\n const targetIndex = Math.floor(index);\n const pierceShadow = options?.pierceShadow !== false;\n const shadowCtx = pierceShadow ? getShadowContext() : null;\n\n if (!pierceShadow) {\n return resolveNativeAtIndexWithError(xp, targetIndex).value;\n }\n\n if (!shadowCtx?.hasShadow) {\n const native = resolveNativeAtIndexWithError(xp, targetIndex);\n if (!native.error) return native.value;\n const composed = resolveXPathComposedMatches(xp, shadowCtx?.getClosedRoot);\n return composed[targetIndex] ?? null;\n }\n\n const composed = resolveXPathComposedMatches(xp, shadowCtx.getClosedRoot);\n return composed[targetIndex] ?? null;\n}\n\nexport function countXPathMatches(\n rawXp: string,\n options?: XPathResolveOptions,\n): number {\n const xp = normalizeXPath(rawXp);\n if (!xp) return 0;\n\n const pierceShadow = options?.pierceShadow !== false;\n const shadowCtx = pierceShadow ? getShadowContext() : null;\n\n if (!pierceShadow) {\n return resolveNativeCountWithError(xp).count;\n }\n\n if (!shadowCtx?.hasShadow) {\n const count = resolveNativeCountWithError(xp);\n if (!count.error) return count.count;\n return resolveXPathComposedMatches(xp, shadowCtx?.getClosedRoot).length;\n }\n\n return resolveXPathComposedMatches(xp, shadowCtx.getClosedRoot).length;\n}\n\nexport function resolveXPathComposedMatches(\n rawXp: string,\n getClosedRoot?: ClosedRootGetter | null,\n): Element[] {\n const xp = normalizeXPath(rawXp);\n if (!xp) return [];\n\n const steps = parseXPathSteps(xp);\n if (!steps.length) return [];\n\n const closedRoot = getClosedRoot ?? null;\n\n let current: Array<Document | Element | ShadowRoot | DocumentFragment> = [\n document,\n ];\n\n for (const step of steps) {\n const next: Element[] = [];\n const seen = new Set<Element>();\n\n for (const root of current) {\n if (!root) continue;\n const pool =\n step.axis === \"child\"\n ? composedChildren(root, closedRoot)\n : composedDescendants(root, closedRoot);\n if (!pool.length) continue;\n\n const tagMatches = pool.filter((candidate) =>\n matchesTag(candidate, step),\n );\n const matches = applyPredicates(tagMatches, step.predicates);\n\n for (const candidate of matches) {\n if (!seen.has(candidate)) {\n seen.add(candidate);\n next.push(candidate);\n }\n }\n }\n\n if (!next.length) return [];\n current = next;\n }\n\n return current as Element[];\n}\n\nfunction matchesTag(element: Element, step: XPathStep): boolean {\n if (step.tag === \"*\") return true;\n return element.localName === step.tag;\n}\n\nfunction getShadowContext(): ShadowContext {\n const backdoor = window.__stagehandV3__;\n const getClosedRoot: ClosedRootGetter | null =\n backdoor && typeof backdoor.getClosedRoot === \"function\"\n ? (host: Element): ShadowRoot | null => {\n try {\n return backdoor.getClosedRoot(host) ?? null;\n } catch {\n return null;\n }\n }\n : null;\n\n let hasShadow = false;\n try {\n if (backdoor && typeof backdoor.stats === \"function\") {\n const stats = backdoor.stats();\n hasShadow = (stats?.open ?? 0) > 0 || (stats?.closed ?? 0) > 0;\n }\n } catch {\n // ignore stats errors\n }\n\n if (!hasShadow) {\n try {\n const walker = document.createTreeWalker(\n document,\n NodeFilter.SHOW_ELEMENT,\n );\n while (walker.nextNode()) {\n const el = walker.currentNode as Element;\n if (el.shadowRoot) {\n hasShadow = true;\n break;\n }\n }\n } catch {\n // ignore scan errors\n }\n }\n\n return { getClosedRoot, hasShadow };\n}\n\nfunction composedChildren(\n node: Node | null | undefined,\n getClosedRoot: ClosedRootGetter | null,\n): Element[] {\n const out: Element[] = [];\n if (!node) return out;\n\n if (node instanceof Document) {\n if (node.documentElement) out.push(node.documentElement);\n return out;\n }\n\n if (node instanceof ShadowRoot || node instanceof DocumentFragment) {\n out.push(...Array.from(node.children ?? []));\n return out;\n }\n\n if (node instanceof Element) {\n out.push(...Array.from(node.children ?? []));\n const open = node.shadowRoot;\n if (open) out.push(...Array.from(open.children ?? []));\n if (getClosedRoot) {\n const closed = getClosedRoot(node);\n if (closed) out.push(...Array.from(closed.children ?? []));\n }\n return out;\n }\n\n return out;\n}\n\nfunction composedDescendants(\n node: Node | null | undefined,\n getClosedRoot: ClosedRootGetter | null,\n): Element[] {\n const out: Element[] = [];\n const seen = new Set<Element>();\n const stack = [...composedChildren(node, getClosedRoot)].reverse();\n\n while (stack.length) {\n const next = stack.pop();\n if (!next || seen.has(next)) continue;\n seen.add(next);\n out.push(next);\n\n const children = composedChildren(next, getClosedRoot);\n for (let i = children.length - 1; i >= 0; i -= 1) {\n stack.push(children[i]!);\n }\n }\n\n return out;\n}\n\nfunction resolveNativeAtIndexWithError(\n xp: string,\n index: number,\n): { value: Element | null; error: boolean } {\n try {\n const snapshot = document.evaluate(\n xp,\n document,\n null,\n XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,\n null,\n );\n return {\n value: snapshot.snapshotItem(index) as Element | null,\n error: false,\n };\n } catch {\n return { value: null, error: true };\n }\n}\n\nfunction resolveNativeCountWithError(xp: string): {\n count: number;\n error: boolean;\n} {\n try {\n const snapshot = document.evaluate(\n xp,\n document,\n null,\n XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,\n null,\n );\n return { count: snapshot.snapshotLength, error: false };\n } catch {\n return { count: 0, error: true };\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"xpathResolver.js","sourceRoot":"","sources":["../../../../../../lib/v3/dom/locatorScripts/xpathResolver.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,eAAe,EACf,eAAe,GAEhB,MAAM,kBAAkB,CAAC;AAc1B,MAAM,cAAc,GAAG,CAAC,QAAgB,EAAU,EAAE;IAClD,MAAM,GAAG,GAAG,MAAM,CAAC,QAAQ,IAAI,EAAE,CAAC,CAAC,IAAI,EAAE,CAAC;IAC1C,IAAI,CAAC,GAAG;QAAE,OAAO,EAAE,CAAC;IACpB,OAAO,GAAG,CAAC,OAAO,CAAC,UAAU,EAAE,EAAE,CAAC,CAAC,IAAI,EAAE,CAAC;AAC5C,CAAC,CAAC;AAEF,MAAM,UAAU,iBAAiB,CAC/B,KAAa,EACb,OAA6B;IAE7B,OAAO,mBAAmB,CAAC,KAAK,EAAE,CAAC,EAAE,OAAO,CAAC,CAAC;AAChD,CAAC;AAED,MAAM,UAAU,mBAAmB,CACjC,KAAa,EACb,KAAa,EACb,OAA6B;IAE7B,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,KAAK,CAAC,IAAI,KAAK,GAAG,CA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EAAE,EACF,QAAQ,EACR,IAAI,EACJ,WAAW,CAAC,0BAA0B,EACtC,IAAI,CACL,CAAC;QACF,OAAO;YACL,KAAK,EAAE,QAAQ,CAAC,YAAY,CAAC,KAAK,CAAmB;YACrD,KAAK,EAAE,KAAK;SACb,CAAC;IACJ,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,EAAE,KAAK,EAAE,IAAI,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC;IACtC,CAAC;AACH,CAAC;AAED,SAAS,2BAA2B,CAAC,EAAU;IAI7C,IAAI,CAAC;QACH,MAAM,QAAQ,GAAG,QAAQ,CAAC,QAAQ,CAChC,EAAE,EACF,QAAQ,EACR,IAAI,EACJ,WAAW,CAAC,0BAA0B,EACtC,IAAI,CACL,CAAC;QACF,OAAO,EAAE,KAAK,EAAE,QAAQ,CAAC,cAAc,EAAE,KAAK,EAAE,KAAK,EAAE,CAAC;IAC1D,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,EAAE,KAAK,EAAE,CAAC,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC;IACnC,CAAC;AACH,CAAC","sourcesContent":["import {\n applyPredicates,\n parseXPathSteps,\n type XPathStep,\n} from \"./xpathParser.js\";\n\ntype ClosedRootGetter = (host: Element) => ShadowRoot | null;\ntype TraversalRoot = Document | Element | ShadowRoot | DocumentFragment;\n\nexport type XPathResolveOptions = {\n pierceShadow?: boolean;\n};\n\ntype ShadowContext = {\n getClosedRoot: ClosedRootGetter | null;\n hasShadow: boolean;\n};\n\nconst normalizeXPath = (selector: string): string => {\n const raw = String(selector ?? \"\").trim();\n if (!raw) return \"\";\n return raw.replace(/^xpath=/i, \"\").trim();\n};\n\nexport function resolveXPathFirst(\n rawXp: string,\n options?: XPathResolveOptions,\n): Element | null {\n return resolveXPathAtIndex(rawXp, 0, options);\n}\n\nexport function resolveXPathAtIndex(\n rawXp: string,\n index: number,\n options?: XPathResolveOptions,\n): Element | null {\n if (!Number.isFinite(index) || index < 0) return null;\n const xp = normalizeXPath(rawXp);\n if (!xp) return null;\n\n const targetIndex = Math.floor(index);\n const pierceShadow = options?.pierceShadow !== false;\n const shadowCtx = pierceShadow ? getShadowContext() : null;\n\n if (!pierceShadow) {\n return resolveNativeAtIndexWithError(xp, targetIndex).value;\n }\n\n if (!shadowCtx?.hasShadow) {\n const native = resolveNativeAtIndexWithError(xp, targetIndex);\n if (!native.error) return native.value;\n const composed = resolveXPathComposedMatches(xp, shadowCtx?.getClosedRoot);\n return composed[targetIndex] ?? null;\n }\n\n const composed = resolveXPathComposedMatches(xp, shadowCtx.getClosedRoot);\n if (composed.length > 0) {\n return composed[targetIndex] ?? null;\n }\n\n const shadowHopMatches = resolveStagehandShadowHopMatches(\n xp,\n shadowCtx.getClosedRoot,\n );\n return shadowHopMatches[targetIndex] ?? null;\n}\n\nexport function countXPathMatches(\n rawXp: string,\n options?: XPathResolveOptions,\n): number {\n const xp = normalizeXPath(rawXp);\n if (!xp) return 0;\n\n const pierceShadow = options?.pierceShadow !== false;\n const shadowCtx = pierceShadow ? getShadowContext() : null;\n\n if (!pierceShadow) {\n return resolveNativeCountWithError(xp).count;\n }\n\n if (!shadowCtx?.hasShadow) {\n const count = resolveNativeCountWithError(xp);\n if (!count.error) return count.count;\n return resolveXPathComposedMatches(xp, shadowCtx?.getClosedRoot).length;\n }\n\n const composedCount = resolveXPathComposedMatches(\n xp,\n shadowCtx.getClosedRoot,\n ).length;\n if (composedCount > 0) return composedCount;\n\n return resolveStagehandShadowHopMatches(xp, shadowCtx.getClosedRoot).length;\n}\n\nexport function resolveXPathComposedMatches(\n rawXp: string,\n getClosedRoot?: ClosedRootGetter | null,\n): Element[] {\n const xp = normalizeXPath(rawXp);\n if (!xp) return [];\n\n const steps = parseXPathSteps(xp);\n if (!steps.length) return [];\n\n const closedRoot = getClosedRoot ?? null;\n\n let current: TraversalRoot[] = [document];\n\n for (const step of steps) {\n const next: Element[] = [];\n const seen = new Set<Element>();\n\n for (const root of current) {\n const pool =\n step.axis === \"child\"\n ? composedChildren(root, closedRoot)\n : composedDescendants(root, closedRoot);\n if (!pool.length) continue;\n\n const tagMatches = pool.filter((candidate) =>\n matchesTag(candidate, step),\n );\n const matches = applyPredicates(tagMatches, step.predicates);\n\n for (const candidate of matches) {\n if (!seen.has(candidate)) {\n seen.add(candidate);\n next.push(candidate);\n }\n }\n }\n\n if (!next.length) return [];\n current = next;\n }\n\n return current as Element[];\n}\n\nfunction resolveStagehandShadowHopMatches(\n rawXp: string,\n getClosedRoot?: ClosedRootGetter | null,\n): Element[] {\n const xp = normalizeXPath(rawXp);\n if (!xp) return [];\n\n const steps = parseXPathSteps(xp);\n if (!steps.some((step, index) => step.axis === \"desc\" && index > 0)) {\n return [];\n }\n\n const closedRoot = getClosedRoot ?? null;\n let current: TraversalRoot[] = [document];\n\n for (let i = 0; i < steps.length; i += 1) {\n const step = steps[i]!;\n const next: Element[] = [];\n const seen = new Set<Element>();\n\n for (const root of current) {\n const pool =\n step.axis === \"child\"\n ? domChildren(root)\n : i === 0\n ? composedDescendants(root, closedRoot)\n : shadowRootChildren(root, closedRoot);\n if (!pool.length) continue;\n\n const tagMatches = pool.filter((candidate) =>\n matchesTag(candidate, step),\n );\n const matches = applyPredicates(tagMatches, step.predicates);\n\n for (const candidate of matches) {\n if (!seen.has(candidate)) {\n seen.add(candidate);\n next.push(candidate);\n }\n }\n }\n\n if (!next.length) return [];\n current = next;\n }\n\n return current as Element[];\n}\n\nfunction matchesTag(element: Element, step: XPathStep): boolean {\n if (step.tag === \"*\") return true;\n return element.localName === step.tag;\n}\n\nfunction getShadowContext(): ShadowContext {\n const backdoor = window.__stagehandV3__;\n const getClosedRoot: ClosedRootGetter | null =\n backdoor && typeof backdoor.getClosedRoot === \"function\"\n ? (host: Element): ShadowRoot | null => {\n try {\n return backdoor.getClosedRoot(host) ?? null;\n } catch {\n return null;\n }\n }\n : null;\n\n let hasShadow = false;\n try {\n if (backdoor && typeof backdoor.stats === \"function\") {\n const stats = backdoor.stats();\n hasShadow = (stats?.open ?? 0) > 0 || (stats?.closed ?? 0) > 0;\n }\n } catch {\n // ignore stats errors\n }\n\n if (!hasShadow) {\n try {\n const walker = document.createTreeWalker(\n document,\n NodeFilter.SHOW_ELEMENT,\n );\n while (walker.nextNode()) {\n const el = walker.currentNode as Element;\n if (el.shadowRoot) {\n hasShadow = true;\n break;\n }\n }\n } catch {\n // ignore scan errors\n }\n }\n\n return { getClosedRoot, hasShadow };\n}\n\nfunction composedChildren(\n node: TraversalRoot,\n getClosedRoot: ClosedRootGetter | null,\n): Element[] {\n const out: Element[] = [];\n\n if (node instanceof Document) {\n if (node.documentElement) out.push(node.documentElement);\n return out;\n }\n\n if (node instanceof ShadowRoot || node instanceof DocumentFragment) {\n out.push(...Array.from(node.children ?? []));\n return out;\n }\n\n if (node instanceof Element) {\n out.push(...Array.from(node.children ?? []));\n const open = node.shadowRoot;\n if (open) out.push(...Array.from(open.children ?? []));\n if (getClosedRoot) {\n const closed = getClosedRoot(node);\n if (closed) out.push(...Array.from(closed.children ?? []));\n }\n return out;\n }\n\n return out;\n}\n\nfunction domChildren(node: TraversalRoot): Element[] {\n const out: Element[] = [];\n\n if (node instanceof Document) {\n if (node.documentElement) out.push(node.documentElement);\n return out;\n }\n\n if (node instanceof ShadowRoot || node instanceof DocumentFragment) {\n out.push(...Array.from(node.children ?? []));\n return out;\n }\n\n if (node instanceof Element) {\n out.push(...Array.from(node.children ?? []));\n return out;\n }\n\n return out;\n}\n\nfunction shadowRootChildren(\n node: TraversalRoot,\n getClosedRoot: ClosedRootGetter | null,\n): Element[] {\n const out: Element[] = [];\n if (!(node instanceof Element)) return out;\n\n const open = node.shadowRoot;\n if (open) out.push(...Array.from(open.children ?? []));\n if (getClosedRoot) {\n const closed = getClosedRoot(node);\n if (closed) out.push(...Array.from(closed.children ?? []));\n }\n\n return out;\n}\n\nfunction composedDescendants(\n node: TraversalRoot,\n getClosedRoot: ClosedRootGetter | null,\n): Element[] {\n const out: Element[] = [];\n const seen = new Set<Element>();\n const stack = [...composedChildren(node, getClosedRoot)].reverse();\n\n while (stack.length) {\n const next = stack.pop()!;\n if (seen.has(next)) continue;\n seen.add(next);\n out.push(next);\n\n const children = composedChildren(next, getClosedRoot);\n for (let i = children.length - 1; i >= 0; i -= 1) {\n stack.push(children[i]!);\n }\n }\n\n return out;\n}\n\nfunction resolveNativeAtIndexWithError(\n xp: string,\n index: number,\n): { value: Element | null; error: boolean } {\n try {\n const snapshot = document.evaluate(\n xp,\n document,\n null,\n XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,\n null,\n );\n return {\n value: snapshot.snapshotItem(index) as Element | null,\n error: false,\n };\n } catch {\n return { value: null, error: true };\n }\n}\n\nfunction resolveNativeCountWithError(xp: string): {\n count: number;\n error: boolean;\n} {\n try {\n const snapshot = document.evaluate(\n xp,\n document,\n null,\n XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,\n null,\n );\n return { count: snapshot.snapshotLength, error: false };\n } catch {\n return { count: 0, error: true };\n }\n}\n"]}
|
|
@@ -18,6 +18,7 @@ export declare class V3AgentHandler {
|
|
|
18
18
|
private createStepHandler;
|
|
19
19
|
execute(instructionOrOptions: string | AgentExecuteOptions): Promise<AgentResult>;
|
|
20
20
|
stream(instructionOrOptions: string | AgentStreamExecuteOptions): Promise<AgentStreamResult>;
|
|
21
|
+
private emitFinalEvidence;
|
|
21
22
|
private consolidateMetricsAndResult;
|
|
22
23
|
private createTools;
|
|
23
24
|
private handleStop;
|
|
@@ -8,6 +8,9 @@ import { V3FunctionName } from "../types/public/methods.js";
|
|
|
8
8
|
import { mapToolResultToActions } from "../agent/utils/actionMapping.js";
|
|
9
9
|
import { MissingLLMConfigurationError, MissingEnvironmentVariableError, StreamingCallbacksInNonStreamingModeError, AgentAbortError, } from "../types/public/sdkErrors.js";
|
|
10
10
|
import { handleDoneToolCall } from "../agent/utils/handleDoneToolCall.js";
|
|
11
|
+
import { captureProbeEvidence, emitPostStepProbeEvidence, } from "../agent/utils/postStepProbeEvidence.js";
|
|
12
|
+
import { wrapEvidenceCallback } from "../agent/utils/wrapEvidenceCallback.js";
|
|
13
|
+
import { inferToolOutput } from "../agent/utils/toolOutputEvidence.js";
|
|
11
14
|
import { CaptchaSolver, CAPTCHA_SOLVED_MSG, CAPTCHA_ERRORED_MSG, } from "../agent/utils/captchaSolver.js";
|
|
12
15
|
function getErrorMessage(error) {
|
|
13
16
|
return error instanceof Error ? error.message : String(error);
|
|
@@ -160,13 +163,14 @@ export class V3AgentHandler {
|
|
|
160
163
|
return options;
|
|
161
164
|
};
|
|
162
165
|
}
|
|
163
|
-
createStepHandler(state, userCallback) {
|
|
166
|
+
createStepHandler(state, { userCallback, evidenceCallback, onFinalAnswer }) {
|
|
164
167
|
return async (event) => {
|
|
165
168
|
this.logger({
|
|
166
169
|
category: "agent",
|
|
167
170
|
message: `Step finished: ${event.finishReason}`,
|
|
168
171
|
level: 2,
|
|
169
172
|
});
|
|
173
|
+
let lastFinalAnswer;
|
|
170
174
|
if (event.toolCalls && event.toolCalls.length > 0) {
|
|
171
175
|
for (let i = 0; i < event.toolCalls.length; i++) {
|
|
172
176
|
const toolCall = event.toolCalls[i];
|
|
@@ -189,6 +193,12 @@ export class V3AgentHandler {
|
|
|
189
193
|
? `${allReasoning} ${doneReasoning}`.trim()
|
|
190
194
|
: allReasoning || "Task completed successfully";
|
|
191
195
|
}
|
|
196
|
+
lastFinalAnswer = {
|
|
197
|
+
message: state.finalMessage,
|
|
198
|
+
output: typeof args?.output === "object" && args?.output !== null
|
|
199
|
+
? args.output
|
|
200
|
+
: undefined,
|
|
201
|
+
};
|
|
192
202
|
}
|
|
193
203
|
const mappedActions = mapToolResultToActions({
|
|
194
204
|
toolCallName: toolCall.toolName,
|
|
@@ -201,8 +211,31 @@ export class V3AgentHandler {
|
|
|
201
211
|
action.timestamp = Date.now();
|
|
202
212
|
state.actions.push(action);
|
|
203
213
|
}
|
|
214
|
+
await evidenceCallback?.({
|
|
215
|
+
type: "step_finished",
|
|
216
|
+
actionName: toolCall.toolName,
|
|
217
|
+
actionArgs: typeof args === "object" && args !== null
|
|
218
|
+
? args
|
|
219
|
+
: {},
|
|
220
|
+
reasoning: event.text ?? "",
|
|
221
|
+
toolOutput: inferToolOutput(toolResult),
|
|
222
|
+
});
|
|
204
223
|
}
|
|
205
224
|
state.currentPageUrl = (await this.v3.context.awaitActivePage()).url();
|
|
225
|
+
// Harness probe — one screenshot / a11y snapshot per AI SDK step.
|
|
226
|
+
// The recorder applies the probe to every step_finished received
|
|
227
|
+
// since the previous probe, so a multi-tool turn shares the same
|
|
228
|
+
// post-turn observation.
|
|
229
|
+
await emitPostStepProbeEvidence({
|
|
230
|
+
v3: this.v3,
|
|
231
|
+
url: state.currentPageUrl,
|
|
232
|
+
evidenceCallback,
|
|
233
|
+
logger: this.logger,
|
|
234
|
+
warningMessage: "Warning: harness probe failed",
|
|
235
|
+
});
|
|
236
|
+
}
|
|
237
|
+
if (lastFinalAnswer) {
|
|
238
|
+
onFinalAnswer?.(lastFinalAnswer);
|
|
206
239
|
}
|
|
207
240
|
if (userCallback) {
|
|
208
241
|
await userCallback(event);
|
|
@@ -222,6 +255,7 @@ export class V3AgentHandler {
|
|
|
222
255
|
completed: false,
|
|
223
256
|
currentPageUrl: "",
|
|
224
257
|
};
|
|
258
|
+
let finalAnswerFromDoneTool;
|
|
225
259
|
let messages = [];
|
|
226
260
|
let captchaSolver;
|
|
227
261
|
try {
|
|
@@ -251,6 +285,7 @@ export class V3AgentHandler {
|
|
|
251
285
|
throw new StreamingCallbacksInNonStreamingModeError(invalidCallbacks);
|
|
252
286
|
}
|
|
253
287
|
}
|
|
288
|
+
const evidenceCallback = wrapEvidenceCallback(callbacks?.onEvidence, this.logger);
|
|
254
289
|
const result = await this.llmClient.generateText({
|
|
255
290
|
model: wrappedModel,
|
|
256
291
|
messages: prependSystemMessage(systemPrompt, messages),
|
|
@@ -258,7 +293,13 @@ export class V3AgentHandler {
|
|
|
258
293
|
stopWhen: (result) => this.handleStop(result, maxSteps),
|
|
259
294
|
toolChoice: "auto",
|
|
260
295
|
prepareStep: this.createPrepareStep(callbacks?.prepareStep, captchaSolver),
|
|
261
|
-
onStepFinish: this.createStepHandler(state,
|
|
296
|
+
onStepFinish: this.createStepHandler(state, {
|
|
297
|
+
userCallback: callbacks?.onStepFinish,
|
|
298
|
+
evidenceCallback,
|
|
299
|
+
onFinalAnswer: (answer) => {
|
|
300
|
+
finalAnswerFromDoneTool = answer;
|
|
301
|
+
},
|
|
302
|
+
}),
|
|
262
303
|
abortSignal: preparedOptions.signal,
|
|
263
304
|
providerOptions: {
|
|
264
305
|
google: { mediaResolution: "MEDIA_RESOLUTION_HIGH" },
|
|
@@ -267,7 +308,12 @@ export class V3AgentHandler {
|
|
|
267
308
|
});
|
|
268
309
|
const allMessages = [...messages, ...(result.response?.messages || [])];
|
|
269
310
|
const doneResult = await this.ensureDone(state, wrappedModel, allMessages, preparedOptions.instruction, preparedOptions.output, this.logger);
|
|
270
|
-
|
|
311
|
+
const output = doneResult.output ?? finalAnswerFromDoneTool?.output;
|
|
312
|
+
await this.emitFinalEvidence(state, {
|
|
313
|
+
message: state.finalMessage,
|
|
314
|
+
output,
|
|
315
|
+
}, evidenceCallback);
|
|
316
|
+
return this.consolidateMetricsAndResult(startTime, state, doneResult.messages, result, maxSteps, output);
|
|
271
317
|
}
|
|
272
318
|
catch (error) {
|
|
273
319
|
// Re-throw validation errors that should propagate to the caller
|
|
@@ -303,6 +349,7 @@ export class V3AgentHandler {
|
|
|
303
349
|
const streamOptions = typeof instructionOrOptions === "object" ? instructionOrOptions : null;
|
|
304
350
|
// Highlight cursor defaults to true for hybrid mode, can be overridden
|
|
305
351
|
const shouldHighlightCursor = streamOptions?.highlightCursor ?? this.mode === "hybrid";
|
|
352
|
+
let finalAnswerFromDoneTool;
|
|
306
353
|
const { options, maxSteps, systemPrompt, allTools, messages, wrappedModel, initialPageUrl, } = await this.prepareAgent(instructionOrOptions);
|
|
307
354
|
// Enable cursor overlay for hybrid mode (coordinate-based interactions)
|
|
308
355
|
if (shouldHighlightCursor && this.mode === "hybrid") {
|
|
@@ -340,6 +387,7 @@ export class V3AgentHandler {
|
|
|
340
387
|
});
|
|
341
388
|
rejectResult(error);
|
|
342
389
|
};
|
|
390
|
+
const evidenceCallback = wrapEvidenceCallback(callbacks?.onEvidence, this.logger);
|
|
343
391
|
let streamResult;
|
|
344
392
|
try {
|
|
345
393
|
streamResult = this.llmClient.streamText({
|
|
@@ -349,7 +397,13 @@ export class V3AgentHandler {
|
|
|
349
397
|
stopWhen: (result) => this.handleStop(result, maxSteps),
|
|
350
398
|
toolChoice: "auto",
|
|
351
399
|
prepareStep: this.createPrepareStep(callbacks?.prepareStep, captchaSolver),
|
|
352
|
-
onStepFinish: this.createStepHandler(state,
|
|
400
|
+
onStepFinish: this.createStepHandler(state, {
|
|
401
|
+
userCallback: callbacks?.onStepFinish,
|
|
402
|
+
evidenceCallback,
|
|
403
|
+
onFinalAnswer: (answer) => {
|
|
404
|
+
finalAnswerFromDoneTool = answer;
|
|
405
|
+
},
|
|
406
|
+
}),
|
|
353
407
|
onError: (event) => {
|
|
354
408
|
captchaSolver?.dispose();
|
|
355
409
|
if (callbacks?.onError) {
|
|
@@ -367,10 +421,17 @@ export class V3AgentHandler {
|
|
|
367
421
|
...messages,
|
|
368
422
|
...(event.response?.messages || []),
|
|
369
423
|
];
|
|
370
|
-
this.ensureDone(state, wrappedModel, allMessages, options.instruction, options.output, this.logger)
|
|
371
|
-
|
|
424
|
+
this.ensureDone(state, wrappedModel, allMessages, options.instruction, options.output, this.logger)
|
|
425
|
+
.then(async (doneResult) => {
|
|
426
|
+
const output = doneResult.output ?? finalAnswerFromDoneTool?.output;
|
|
427
|
+
await this.emitFinalEvidence(state, {
|
|
428
|
+
message: state.finalMessage,
|
|
429
|
+
output,
|
|
430
|
+
}, evidenceCallback);
|
|
431
|
+
const result = this.consolidateMetricsAndResult(startTime, state, doneResult.messages, event, maxSteps, output);
|
|
372
432
|
resolveResult(result);
|
|
373
|
-
})
|
|
433
|
+
})
|
|
434
|
+
.catch(handleError);
|
|
374
435
|
},
|
|
375
436
|
onAbort: (event) => {
|
|
376
437
|
captchaSolver?.dispose();
|
|
@@ -398,6 +459,21 @@ export class V3AgentHandler {
|
|
|
398
459
|
agentStreamResult.result = resultPromise;
|
|
399
460
|
return agentStreamResult;
|
|
400
461
|
}
|
|
462
|
+
async emitFinalEvidence(state, finalAnswer, evidenceCallback) {
|
|
463
|
+
if (!evidenceCallback)
|
|
464
|
+
return;
|
|
465
|
+
const observation = await captureProbeEvidence({
|
|
466
|
+
v3: this.v3,
|
|
467
|
+
url: state.currentPageUrl,
|
|
468
|
+
logger: this.logger,
|
|
469
|
+
warningMessage: "Warning: final harness probe failed",
|
|
470
|
+
});
|
|
471
|
+
await evidenceCallback({
|
|
472
|
+
type: "final_answer",
|
|
473
|
+
...finalAnswer,
|
|
474
|
+
observation,
|
|
475
|
+
});
|
|
476
|
+
}
|
|
401
477
|
consolidateMetricsAndResult(startTime, state, inputMessages, result, maxSteps, output) {
|
|
402
478
|
if (!state.finalMessage) {
|
|
403
479
|
const allReasoning = state.collectedReasoning.join(" ").trim();
|