@usecrow/client 0.1.31 → 0.1.32
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/dist/browser.cjs +1 -1
- package/dist/browser.js +1 -1
- package/dist/browserUse-CAnPpcJX.cjs +9 -0
- package/dist/{browserUse-D5NUCzN4.js → browserUse-DHVE_OuS.js} +63 -57
- package/dist/index.cjs +1 -1
- package/dist/index.js +2 -2
- package/package.json +1 -1
- package/dist/browserUse-B-b3zqW1.cjs +0 -9
package/dist/browser.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("./browserUse-
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("./browserUse-CAnPpcJX.cjs");e.setPageController(e.PageController);let r=null;function w(){r&&(console.log("[Crow] Stopping active browser-use automation"),r.stop(),r=null)}function a(t,u){return async n=>{const s=n.instruction||n.instruction;if(!s)return{status:"error",error:"Missing instruction parameter for browser_use tool"};const l=window.__crow_browser_callbacks,o=u||l,i=new e.CrowBrowserUse({productId:t.productId,apiUrl:t.apiUrl,onConfirmation:o==null?void 0:o.onConfirmation,onQuestion:o==null?void 0:o.onQuestion,onProgress:o==null?void 0:o.onProgress});r=i;try{return await i.execute(s)}finally{r=null}}}exports.CrowBrowserUse=e.CrowBrowserUse;exports.PageController=e.PageController;exports.createBrowserUseTool=a;exports.stopActiveBrowserUse=w;
|
package/dist/browser.js
CHANGED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
"use strict";async function waitFor(o){await new Promise(e=>setTimeout(e,o*1e3))}async function movePointerToElement(o){const e=o.getBoundingClientRect(),n=e.left+e.width/2,r=e.top+e.height/2;window.dispatchEvent(new CustomEvent("PageAgent::MovePointerTo",{detail:{x:n,y:r}})),await waitFor(.3)}function getElementByIndex(o,e){const n=o.get(e);if(!n)throw new Error(`No interactive element found at index ${e}`);const r=n.ref;if(!r)throw new Error(`Element at index ${e} does not have a reference`);if(!(r instanceof HTMLElement))throw new Error(`Element at index ${e} is not an HTMLElement`);return r}let lastClickedElement=null;function blurLastClickedElement(){lastClickedElement&&(lastClickedElement.blur(),lastClickedElement.dispatchEvent(new MouseEvent("mouseout",{bubbles:!0,cancelable:!0})),lastClickedElement=null)}async function clickElement(o){blurLastClickedElement(),lastClickedElement=o,await scrollIntoViewIfNeeded(o),await movePointerToElement(o),window.dispatchEvent(new CustomEvent("PageAgent::ClickPointer")),await waitFor(.1),o.dispatchEvent(new MouseEvent("mouseenter",{bubbles:!0,cancelable:!0})),o.dispatchEvent(new MouseEvent("mouseover",{bubbles:!0,cancelable:!0})),o.dispatchEvent(new MouseEvent("mousedown",{bubbles:!0,cancelable:!0})),o.focus(),o.dispatchEvent(new MouseEvent("mouseup",{bubbles:!0,cancelable:!0})),o.dispatchEvent(new MouseEvent("click",{bubbles:!0,cancelable:!0})),await waitFor(.1)}let _nativeInputValueSetter,_nativeTextAreaValueSetter;function getNativeInputValueSetter(){return _nativeInputValueSetter||(_nativeInputValueSetter=Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype,"value").set),_nativeInputValueSetter}function getNativeTextAreaValueSetter(){return _nativeTextAreaValueSetter||(_nativeTextAreaValueSetter=Object.getOwnPropertyDescriptor(window.HTMLTextAreaElement.prototype,"value").set),_nativeTextAreaValueSetter}async function inputTextElement(o,e){if(!(o instanceof HTMLInputElement||o instanceof HTMLTextAreaElement))throw new Error("Element is not an input or textarea");await clickElement(o),o instanceof HTMLTextAreaElement?getNativeTextAreaValueSetter().call(o,e):getNativeInputValueSetter().call(o,e);const n=new Event("input",{bubbles:!0});o.dispatchEvent(n),await waitFor(.1),blurLastClickedElement()}async function selectOptionElement(o,e){if(!(o instanceof HTMLSelectElement))throw new Error("Element is not a select element");const r=Array.from(o.options).find(d=>{var h;return((h=d.textContent)==null?void 0:h.trim())===e.trim()});if(!r)throw new Error(`Option with text "${e}" not found in select element`);o.value=r.value,o.dispatchEvent(new Event("change",{bubbles:!0})),await waitFor(.1)}async function scrollIntoViewIfNeeded(o){const e=o;e.scrollIntoViewIfNeeded?e.scrollIntoViewIfNeeded():e.scrollIntoView({behavior:"auto",block:"center",inline:"nearest"})}async function scrollVertically(o,e,n){if(n){const l=n;console.log("[SCROLL DEBUG] Starting direct container scroll for element:",l.tagName);let f=l,v=!1,m=null,c=0,g=0;const C=e;for(;f&&g<10;){const B=window.getComputedStyle(f),D=/(auto|scroll|overlay)/.test(B.overflowY),S=f.scrollHeight>f.clientHeight;if(console.log("[SCROLL DEBUG] Checking element:",f.tagName,"hasScrollableY:",D,"canScrollVertically:",S,"scrollHeight:",f.scrollHeight,"clientHeight:",f.clientHeight),D&&S){const H=f.scrollTop,U=f.scrollHeight-f.clientHeight;let k=C/3;k>0?k=Math.min(k,U-H):k=Math.max(k,-H),f.scrollTop=H+k;const V=f.scrollTop,$=V-H;if(console.log("[SCROLL DEBUG] Scroll attempt:",f.tagName,"before:",H,"after:",V,"delta:",$),Math.abs($)>.5){v=!0,m=f,c=$,console.log("[SCROLL DEBUG] Successfully scrolled container:",f.tagName,"delta:",$);break}}if(f===document.body||f===document.documentElement)break;f=f.parentElement,g++}return v?`Scrolled container (${m==null?void 0:m.tagName}) by ${c}px`:`No scrollable container found for element (${l.tagName})`}const r=e,d=l=>l.clientHeight>=window.innerHeight*.5,h=l=>l&&/(auto|scroll|overlay)/.test(getComputedStyle(l).overflowY)&&l.scrollHeight>l.clientHeight&&d(l);let s=document.activeElement;for(;s&&!h(s)&&s!==document.body;)s=s.parentElement;if(s=h(s)?s:Array.from(document.querySelectorAll("*")).find(h)||document.scrollingElement||document.documentElement,s===document.scrollingElement||s===document.documentElement||s===document.body){const l=window.scrollY,f=document.documentElement.scrollHeight-window.innerHeight;window.scrollBy(0,r);const v=window.scrollY,m=v-l;if(Math.abs(m)<1)return r>0?"⚠️ Already at the bottom of the page, cannot scroll down further.":"⚠️ Already at the top of the page, cannot scroll up further.";const c=r>0&&v>=f-1,g=r<0&&v<=1;return c?`✅ Scrolled page by ${m}px. Reached the bottom of the page.`:g?`✅ Scrolled page by ${m}px. Reached the top of the page.`:`✅ Scrolled page by ${m}px.`}else{const l=s.scrollTop,f=s.scrollHeight-s.clientHeight;s.scrollBy({top:r,behavior:"smooth"}),await waitFor(.1);const v=s.scrollTop,m=v-l;if(Math.abs(m)<1)return r>0?`⚠️ Already at the bottom of container (${s.tagName}), cannot scroll down further.`:`⚠️ Already at the top of container (${s.tagName}), cannot scroll up further.`;const c=r>0&&v>=f-1,g=r<0&&v<=1;return c?`✅ Scrolled container (${s.tagName}) by ${m}px. Reached the bottom.`:g?`✅ Scrolled container (${s.tagName}) by ${m}px. Reached the top.`:`✅ Scrolled container (${s.tagName}) by ${m}px.`}}async function scrollHorizontally(o,e,n){if(n){const l=n;console.log("[SCROLL DEBUG] Starting direct container scroll for element:",l.tagName);let f=l,v=!1,m=null,c=0,g=0;const C=o?e:-e;for(;f&&g<10;){const B=window.getComputedStyle(f),D=/(auto|scroll|overlay)/.test(B.overflowX),S=f.scrollWidth>f.clientWidth;if(console.log("[SCROLL DEBUG] Checking element:",f.tagName,"hasScrollableX:",D,"canScrollHorizontally:",S,"scrollWidth:",f.scrollWidth,"clientWidth:",f.clientWidth),D&&S){const H=f.scrollLeft,U=f.scrollWidth-f.clientWidth;let k=C/3;k>0?k=Math.min(k,U-H):k=Math.max(k,-H),f.scrollLeft=H+k;const V=f.scrollLeft,$=V-H;if(console.log("[SCROLL DEBUG] Scroll attempt:",f.tagName,"before:",H,"after:",V,"delta:",$),Math.abs($)>.5){v=!0,m=f,c=$,console.log("[SCROLL DEBUG] Successfully scrolled container:",f.tagName,"delta:",$);break}}if(f===document.body||f===document.documentElement)break;f=f.parentElement,g++}return v?`Scrolled container (${m==null?void 0:m.tagName}) horizontally by ${c}px`:`No horizontally scrollable container found for element (${l.tagName})`}const r=o?e:-e,d=l=>l.clientWidth>=window.innerWidth*.5,h=l=>l&&/(auto|scroll|overlay)/.test(getComputedStyle(l).overflowX)&&l.scrollWidth>l.clientWidth&&d(l);let s=document.activeElement;for(;s&&!h(s)&&s!==document.body;)s=s.parentElement;if(s=h(s)?s:Array.from(document.querySelectorAll("*")).find(h)||document.scrollingElement||document.documentElement,s===document.scrollingElement||s===document.documentElement||s===document.body){const l=window.scrollX,f=document.documentElement.scrollWidth-window.innerWidth;window.scrollBy(r,0);const v=window.scrollX,m=v-l;if(Math.abs(m)<1)return r>0?"⚠️ Already at the right edge of the page, cannot scroll right further.":"⚠️ Already at the left edge of the page, cannot scroll left further.";const c=r>0&&v>=f-1,g=r<0&&v<=1;return c?`✅ Scrolled page by ${m}px. Reached the right edge of the page.`:g?`✅ Scrolled page by ${m}px. Reached the left edge of the page.`:`✅ Scrolled page horizontally by ${m}px.`}else{const l=s.scrollLeft,f=s.scrollWidth-s.clientWidth;s.scrollBy({left:r,behavior:"smooth"}),await waitFor(.1);const v=s.scrollLeft,m=v-l;if(Math.abs(m)<1)return r>0?`⚠️ Already at the right edge of container (${s.tagName}), cannot scroll right further.`:`⚠️ Already at the left edge of container (${s.tagName}), cannot scroll left further.`;const c=r>0&&v>=f-1,g=r<0&&v<=1;return c?`✅ Scrolled container (${s.tagName}) by ${m}px. Reached the right edge.`:g?`✅ Scrolled container (${s.tagName}) by ${m}px. Reached the left edge.`:`✅ Scrolled container (${s.tagName}) horizontally by ${m}px.`}}const VIEWPORT_EXPANSION=-1,domTree=(o={doHighlightElements:!0,focusHighlightIndex:-1,viewportExpansion:0,debugMode:!1,interactiveBlacklist:[],interactiveWhitelist:[],highlightOpacity:.1,highlightLabelOpacity:.5})=>{const{interactiveBlacklist:e,interactiveWhitelist:n,highlightOpacity:r,highlightLabelOpacity:d}=o,{doHighlightElements:h,focusHighlightIndex:s,viewportExpansion:l,debugMode:f}=o;let v=0;const m=new WeakMap;function c(t,i){!t||t.nodeType!==Node.ELEMENT_NODE||m.set(t,{...m.get(t),...i})}const g={boundingRects:new WeakMap,clientRects:new WeakMap,computedStyles:new WeakMap,clearCache:()=>{g.boundingRects=new WeakMap,g.clientRects=new WeakMap,g.computedStyles=new WeakMap}};function C(t){if(!t)return null;if(g.boundingRects.has(t))return g.boundingRects.get(t);const i=t.getBoundingClientRect();return i&&g.boundingRects.set(t,i),i}function B(t){if(!t)return null;if(g.computedStyles.has(t))return g.computedStyles.get(t);const i=window.getComputedStyle(t);return i&&g.computedStyles.set(t,i),i}function D(t){if(!t)return null;if(g.clientRects.has(t))return g.clientRects.get(t);const i=t.getClientRects();return i&&g.clientRects.set(t,i),i}const S={},H={current:0},U="playwright-highlight-container";function k(t,i,w=null){if(!t)return i;const u=[];let a=null,x=20,E=16,_=null;try{let b=document.getElementById(U);b||(b=document.createElement("div"),b.id=U,b.style.position="fixed",b.style.pointerEvents="none",b.style.top="0",b.style.left="0",b.style.width="100%",b.style.height="100%",b.style.zIndex="2147483640",b.style.backgroundColor="transparent",document.body.appendChild(b));const P=t.getClientRects();if(!P||P.length===0)return i;const O=["#FF0000","#00FF00","#0000FF","#FFA500","#800080","#008080","#FF69B4","#4B0082","#FF4500","#2E8B57","#DC143C","#4682B4"],p=i%O.length;let y=O[p];const I=y+Math.floor(r*255).toString(16).padStart(2,"0");y=y+Math.floor(d*255).toString(16).padStart(2,"0");let L={x:0,y:0};if(w){const N=w.getBoundingClientRect();L.x=N.left,L.y=N.top}const j=document.createDocumentFragment();for(const N of P){if(N.width===0||N.height===0)continue;const M=document.createElement("div");M.style.position="fixed",M.style.border=`2px solid ${y}`,M.style.backgroundColor=I,M.style.pointerEvents="none",M.style.boxSizing="border-box";const T=N.top+L.y,W=N.left+L.x;M.style.top=`${T}px`,M.style.left=`${W}px`,M.style.width=`${N.width}px`,M.style.height=`${N.height}px`,j.appendChild(M),u.push({element:M,initialRect:N})}const G=P[0];if(d>0){a=document.createElement("div"),a.className="playwright-highlight-label",a.style.position="fixed",a.style.background=y,a.style.color="white",a.style.padding="1px 4px",a.style.borderRadius="4px",a.style.fontSize=`${Math.min(12,Math.max(8,G.height/2))}px`,a.textContent=i.toString(),x=a.offsetWidth>0?a.offsetWidth:x,E=a.offsetHeight>0?a.offsetHeight:E;const N=G.top+L.y,M=G.left+L.x;let T=N+2,W=M+G.width-x-2;(G.width<x+4||G.height<E+4)&&(T=N-E-2,W=M+G.width-x,W<L.x&&(W=M)),T=Math.max(0,Math.min(T,window.innerHeight-E)),W=Math.max(0,Math.min(W,window.innerWidth-x)),a.style.top=`${T}px`,a.style.left=`${W}px`,j.appendChild(a)}const q=((N,M)=>{let T=0;return(...W)=>{const X=performance.now();if(!(X-T<M))return T=X,N(...W)}})(()=>{const N=t.getClientRects();let M={x:0,y:0};if(w){const T=w.getBoundingClientRect();M.x=T.left,M.y=T.top}if(u.forEach((T,W)=>{if(W<N.length){const X=N[W],tt=X.top+M.y,Q=X.left+M.x;T.element.style.top=`${tt}px`,T.element.style.left=`${Q}px`,T.element.style.width=`${X.width}px`,T.element.style.height=`${X.height}px`,T.element.style.display=X.width===0||X.height===0?"none":"block"}else T.element.style.display="none"}),N.length<u.length)for(let T=N.length;T<u.length;T++)u[T].element.style.display="none";if(a&&N.length>0){const T=N[0],W=T.top+M.y,X=T.left+M.x;let tt=W+2,Q=X+T.width-x-2;(T.width<x+4||T.height<E+4)&&(tt=W-E-2,Q=X+T.width-x,Q<M.x&&(Q=X)),tt=Math.max(0,Math.min(tt,window.innerHeight-E)),Q=Math.max(0,Math.min(Q,window.innerWidth-x)),a.style.top=`${tt}px`,a.style.left=`${Q}px`,a.style.display="block"}else a&&(a.style.display="none")},16);return window.addEventListener("scroll",q,!0),window.addEventListener("resize",q),_=()=>{window.removeEventListener("scroll",q,!0),window.removeEventListener("resize",q),u.forEach(N=>N.element.remove()),a&&a.remove()},b.appendChild(j),i+1}finally{_&&(window._highlightCleanupFunctions=window._highlightCleanupFunctions||[]).push(_)}}function V(t){if(!t||t.nodeType!==Node.ELEMENT_NODE)return null;const i=B(t);if(!i)return null;const w=i.display;if(w==="inline"||w==="inline-block")return null;const u=i.overflowX,a=i.overflowY,x=u==="auto"||u==="scroll",E=a==="auto"||a==="scroll";if(!x&&!E)return null;const _=t.scrollWidth-t.clientWidth,b=t.scrollHeight-t.clientHeight,P=4;if(_<P&&b<P||!E&&_<P||!x&&b<P)return null;const O=t.scrollTop,p=t.scrollLeft,y=t.scrollWidth-t.clientWidth-t.scrollLeft,I=t.scrollHeight-t.clientHeight-t.scrollTop,L={top:O,right:y,bottom:I,left:p};return c(t,{scrollable:!0,scrollData:L}),L}function $(t){try{if(l===-1){const E=t.parentElement;if(!E)return!1;try{return E.checkVisibility({checkOpacity:!0,checkVisibilityCSS:!0})}catch{const b=window.getComputedStyle(E);return b.display!=="none"&&b.visibility!=="hidden"&&b.opacity!=="0"}}const i=document.createRange();i.selectNodeContents(t);const w=i.getClientRects();if(!w||w.length===0)return!1;let u=!1,a=!1;for(const E of w)if(E.width>0&&E.height>0&&(u=!0,!(E.bottom<-l||E.top>window.innerHeight+l||E.right<-l||E.left>window.innerWidth+l))){a=!0;break}if(!u||!a)return!1;const x=t.parentElement;if(!x)return!1;try{return x.checkVisibility({checkOpacity:!0,checkVisibilityCSS:!0})}catch{const _=window.getComputedStyle(x);return _.display!=="none"&&_.visibility!=="hidden"&&_.opacity!=="0"}}catch(i){return console.warn("Error checking text node visibility:",i),!1}}function R(t){if(!t||!t.tagName)return!1;const i=new Set(["body","div","main","article","section","nav","header","footer"]),w=t.tagName.toLowerCase();return i.has(w)?!0:!new Set(["svg","script","style","link","meta","noscript","template"]).has(w)}function F(t){const i=B(t);return t.offsetWidth>0&&t.offsetHeight>0&&(i==null?void 0:i.visibility)!=="hidden"&&(i==null?void 0:i.display)!=="none"}function A(t){var I,L;if(!t||t.nodeType!==Node.ELEMENT_NODE||e.includes(t))return!1;if(n.includes(t))return!0;const i=t.tagName.toLowerCase(),w=B(t),u=new Set(["pointer","move","text","grab","grabbing","cell","copy","alias","all-scroll","col-resize","context-menu","crosshair","e-resize","ew-resize","help","n-resize","ne-resize","nesw-resize","ns-resize","nw-resize","nwse-resize","row-resize","s-resize","se-resize","sw-resize","vertical-text","w-resize","zoom-in","zoom-out"]),a=new Set(["not-allowed","no-drop","wait","progress","initial","inherit"]);function x(j){return j.tagName.toLowerCase()==="html"?!1:!!(w!=null&&w.cursor&&u.has(w.cursor))}if(x(t))return!0;const _=new Set(["a","button","input","select","textarea","details","summary","label","option","optgroup","fieldset","legend"]),b=new Set(["disabled","readonly"]);if(_.has(i)){if(w!=null&&w.cursor&&a.has(w.cursor))return!1;for(const j of b)if(t.hasAttribute(j)||t.getAttribute(j)==="true"||t.getAttribute(j)==="")return!1;return!(t.disabled||t.readOnly||t.inert)}const P=t.getAttribute("role"),O=t.getAttribute("aria-role");if(t.getAttribute("contenteditable")==="true"||t.isContentEditable||t.classList&&(t.classList.contains("button")||t.classList.contains("dropdown-toggle")||t.getAttribute("data-index")||t.getAttribute("data-toggle")==="dropdown"||t.getAttribute("aria-haspopup")==="true"))return!0;const p=new Set(["button","menu","menubar","menuitem","menuitemradio","menuitemcheckbox","radio","checkbox","tab","switch","slider","spinbutton","combobox","searchbox","textbox","listbox","option","scrollbar"]);if(_.has(i)||P&&p.has(P)||O&&p.has(O))return!0;try{if(typeof getEventListeners=="function"){const J=getEventListeners(t),nt=["click","mousedown","mouseup","dblclick"];for(const q of nt)if(J[q]&&J[q].length>0)return!0}const j=((L=(I=t==null?void 0:t.ownerDocument)==null?void 0:I.defaultView)==null?void 0:L.getEventListenersForNode)||window.getEventListenersForNode;if(typeof j=="function"){const J=j(t),nt=["click","mousedown","mouseup","keydown","keyup","submit","change","input","focus","blur"];for(const q of nt)for(const N of J)if(N.type===q)return!0}const G=["onclick","onmousedown","onmouseup","ondblclick"];for(const J of G)if(t.hasAttribute(J)||typeof t[J]=="function")return!0}catch{}return!!V(t)}function ot(t){if(l===-1)return!0;const i=D(t);if(!i||i.length===0)return!1;let w=!1;for(const b of i)if(b.width>0&&b.height>0&&!(b.bottom<-l||b.top>window.innerHeight+l||b.right<-l||b.left>window.innerWidth+l)){w=!0;break}if(!w)return!1;if(t.ownerDocument!==window.document)return!0;let a=Array.from(i).find(b=>b.width>0&&b.height>0);if(!a)return!1;const x=t.getRootNode();if(x instanceof ShadowRoot){const b=a.left+a.width/2,P=a.top+a.height/2;try{const O=x.elementFromPoint(b,P);if(!O)return!1;let p=O;for(;p&&p!==x;){if(p===t)return!0;p=p.parentElement}return!1}catch{return!0}}const E=5;return[{x:a.left+a.width/2,y:a.top+a.height/2},{x:a.left+E,y:a.top+E},{x:a.right-E,y:a.bottom-E}].some(({x:b,y:P})=>{try{const O=document.elementFromPoint(b,P);if(!O)return!1;let p=O;for(;p&&p!==document.documentElement;){if(p===t)return!0;p=p.parentElement}return!1}catch{return!0}})}function rt(t,i){if(i===-1)return!0;const w=t.getClientRects();if(!w||w.length===0){const u=C(t);return!u||u.width===0||u.height===0?!1:!(u.bottom<-i||u.top>window.innerHeight+i||u.right<-i||u.left>window.innerWidth+i)}for(const u of w)if(!(u.width===0||u.height===0)&&!(u.bottom<-i||u.top>window.innerHeight+i||u.right<-i||u.left>window.innerWidth+i))return!0;return!1}function z(t){if(!t||t.nodeType!==Node.ELEMENT_NODE)return!1;const i=t.tagName.toLowerCase();return new Set(["a","button","input","select","textarea","details","summary","label"]).has(i)?!0:t.hasAttribute("onclick")||t.hasAttribute("role")||t.hasAttribute("tabindex")||t.hasAttribute("aria-")||t.hasAttribute("data-action")||t.getAttribute("contenteditable")==="true"}const Y=new Set(["a","button","input","select","textarea","summary","details","label","option"]),K=new Set(["button","link","menuitem","menuitemradio","menuitemcheckbox","radio","checkbox","tab","switch","slider","spinbutton","combobox","searchbox","textbox","listbox","option","scrollbar"]);function et(t){if(!t||t.nodeType!==Node.ELEMENT_NODE||!F(t))return!1;const i=t.hasAttribute("role")||t.hasAttribute("tabindex")||t.hasAttribute("onclick")||typeof t.onclick=="function",w=/\b(btn|clickable|menu|item|entry|link)\b/i.test(t.className||""),u=!!t.closest('button,a,[role="button"],.menu,.dropdown,.list,.toolbar'),a=[...t.children].some(F),x=t.parentElement&&t.parentElement.isSameNode(document.body);return(A(t)||i||w)&&a&&u&&!x}function it(t){var u,a;if(!t||t.nodeType!==Node.ELEMENT_NODE)return!1;const i=t.tagName.toLowerCase(),w=t.getAttribute("role");if(i==="iframe"||Y.has(i)||w&&K.has(w)||t.isContentEditable||t.getAttribute("contenteditable")==="true"||t.hasAttribute("data-testid")||t.hasAttribute("data-cy")||t.hasAttribute("data-test")||t.hasAttribute("onclick")||typeof t.onclick=="function")return!0;try{const x=((a=(u=t==null?void 0:t.ownerDocument)==null?void 0:u.defaultView)==null?void 0:a.getEventListenersForNode)||window.getEventListenersForNode;if(typeof x=="function"){const _=x(t),b=["click","mousedown","mouseup","keydown","keyup","submit","change","input","focus","blur"];for(const P of b)for(const O of _)if(O.type===P)return!0}if(["onmousedown","onmouseup","onkeydown","onkeyup","onsubmit","onchange","oninput","onfocus","onblur"].some(_=>t.hasAttribute(_)))return!0}catch{}return!!et(t)}function st(t,i,w,u){if(!t.isInteractive)return!1;let a=!1;return u?it(i)?a=!0:a=!1:a=!0,a&&(t.isInViewport=rt(i,l),(t.isInViewport||l===-1)&&(t.highlightIndex=v++,h))?(s>=0?s===t.highlightIndex&&k(i,t.highlightIndex,w):k(i,t.highlightIndex,w),!0):!1}function Z(t,i=null,w=!1){var E,_,b,P,O;if(!t||t.id===U||t.nodeType!==Node.ELEMENT_NODE&&t.nodeType!==Node.TEXT_NODE||!t||t.id===U||((E=t.dataset)==null?void 0:E.browserUseIgnore)==="true"||t.getAttribute&&t.getAttribute("aria-hidden")==="true")return null;if(t===document.body){const p={tagName:"body",attributes:{},xpath:"/body",children:[]};for(const I of t.childNodes){const L=Z(I,i,!1);L&&p.children.push(L)}const y=`${H.current++}`;return S[y]=p,y}if(t.nodeType!==Node.ELEMENT_NODE&&t.nodeType!==Node.TEXT_NODE)return null;if(t.nodeType===Node.TEXT_NODE){const p=(_=t.textContent)==null?void 0:_.trim();if(!p)return null;const y=t.parentElement;if(!y||y.tagName.toLowerCase()==="script")return null;const I=`${H.current++}`;return S[I]={type:"TEXT_NODE",text:p,isVisible:$(t)},I}if(t.nodeType===Node.ELEMENT_NODE&&!R(t))return null;if(l!==-1&&!t.shadowRoot){const p=C(t),y=B(t),I=y&&(y.position==="fixed"||y.position==="sticky"),L=t.offsetWidth>0||t.offsetHeight>0;if(!p||!I&&!L&&(p.bottom<-l||p.top>window.innerHeight+l||p.right<-l||p.left>window.innerWidth+l))return null}const u={tagName:t.tagName.toLowerCase(),attributes:{},children:[]};if(z(t)||t.tagName.toLowerCase()==="iframe"||t.tagName.toLowerCase()==="body"){const p=((b=t.getAttributeNames)==null?void 0:b.call(t))||[];for(const y of p){const I=t.getAttribute(y);u.attributes[y]=I}t.tagName.toLowerCase()==="input"&&(t.type==="checkbox"||t.type==="radio")&&(u.attributes.checked=t.checked?"true":"false")}let a=!1;if(t.nodeType===Node.ELEMENT_NODE&&(u.isVisible=F(t),u.isVisible)){u.isTopElement=ot(t);const p=t.getAttribute("role"),y=p==="menu"||p==="menubar"||p==="listbox";(u.isTopElement||y)&&(u.isInteractive=A(t),a=st(u,t,i,w),u.ref=t)}if(t.tagName){const p=t.tagName.toLowerCase();if(p==="iframe")try{const y=t.contentDocument||((P=t.contentWindow)==null?void 0:P.document);if(y)for(const I of y.childNodes){const L=Z(I,t,!1);L&&u.children.push(L)}}catch(y){console.warn("Unable to access iframe:",y)}else if(t.isContentEditable||t.getAttribute("contenteditable")==="true"||t.id==="tinymce"||t.classList.contains("mce-content-body")||p==="body"&&((O=t.getAttribute("data-id"))!=null&&O.startsWith("mce_")))for(const y of t.childNodes){const I=Z(y,i,a);I&&u.children.push(I)}else{if(t.shadowRoot){u.shadowRoot=!0;for(const y of t.shadowRoot.childNodes){const I=Z(y,i,a);I&&u.children.push(I)}}for(const y of t.childNodes){const L=Z(y,i,a||w);L&&u.children.push(L)}}}if(u.tagName==="a"&&u.children.length===0&&!u.attributes.href){const p=C(t);if(!(p&&p.width>0&&p.height>0||t.offsetWidth>0||t.offsetHeight>0))return null}u.extra=m.get(t)||null;const x=`${H.current++}`;return S[x]=u,x}const lt=Z(document.body);return g.clearCache(),{rootId:lt,map:S}},newElementsCache=new WeakMap;function getFlatTree(o){const e=[];for(const h of o.interactiveBlacklist||[])typeof h=="function"?e.push(h()):e.push(h);const n=[];for(const h of o.interactiveWhitelist||[])typeof h=="function"?n.push(h()):n.push(h);const r=domTree({doHighlightElements:!0,debugMode:!0,focusHighlightIndex:-1,viewportExpansion:VIEWPORT_EXPANSION,interactiveBlacklist:e,interactiveWhitelist:n,highlightOpacity:o.highlightOpacity??0,highlightLabelOpacity:o.highlightLabelOpacity??.1}),d=window.location.href;for(const h in r.map){const s=r.map[h];if(s.isInteractive&&s.ref){const l=s.ref;newElementsCache.has(l)||(newElementsCache.set(l,d),s.isNew=!0)}}return r}function flatTreeToString(o,e){const n=["title","type","checked","name","role","value","placeholder","data-date-format","alt","aria-label","aria-expanded","data-state","aria-checked","id","for","target","aria-haspopup","aria-controls","aria-owns"],r=[...e||[],...n],d=(c,g)=>c.length>g?c.substring(0,g)+"...":c,h=c=>{const g=o.map[c];if(!g)return null;if(g.type==="TEXT_NODE"){const C=g;return{type:"text",text:C.text,isVisible:C.isVisible,parent:null,children:[]}}else{const C=g,B=[];if(C.children)for(const D of C.children){const S=h(D);S&&(S.parent=null,B.push(S))}return{type:"element",tagName:C.tagName,attributes:C.attributes??{},isVisible:C.isVisible??!1,isInteractive:C.isInteractive??!1,isTopElement:C.isTopElement??!1,isNew:C.isNew??!1,highlightIndex:C.highlightIndex,parent:null,children:B,extra:C.extra??{}}}},s=(c,g=null)=>{c.parent=g;for(const C of c.children)s(C,c)},l=h(o.rootId);if(!l)return"";s(l);const f=c=>{let g=c.parent;for(;g;){if(g.type==="element"&&g.highlightIndex!==void 0)return!0;g=g.parent}return!1},v=(c,g,C)=>{var S,H,U,k;let B=g;const D=" ".repeat(g);if(c.type==="element"){if(c.highlightIndex!==void 0){B+=1;const V=getAllTextTillNextClickableElement(c);let $="";if(r.length>0&&c.attributes){const A={};for(const z of r){const Y=c.attributes[z];Y&&Y.trim()!==""&&(A[z]=Y.trim())}const ot=r.filter(z=>z in A);if(ot.length>1){const z=new Set,Y={};for(const K of ot){const et=A[K];et.length>5&&(et in Y?z.add(K):Y[et]=K)}for(const K of z)delete A[K]}A.role===c.tagName&&delete A.role;const rt=["aria-label","placeholder","title"];for(const z of rt)A[z]&&A[z].toLowerCase().trim()===V.toLowerCase().trim()&&delete A[z];Object.keys(A).length>0&&($=Object.entries(A).map(([z,Y])=>`${z}=${d(Y,20)}`).join(" "))}const R=c.isNew?`*[${c.highlightIndex}]`:`[${c.highlightIndex}]`;let F=`${D}${R}<${c.tagName??""}`;if($&&(F+=` ${$}`),c.extra&&c.extra.scrollable){let A="";(S=c.extra.scrollData)!=null&&S.left&&(A+=`left=${c.extra.scrollData.left}, `),(H=c.extra.scrollData)!=null&&H.top&&(A+=`top=${c.extra.scrollData.top}, `),(U=c.extra.scrollData)!=null&&U.right&&(A+=`right=${c.extra.scrollData.right}, `),(k=c.extra.scrollData)!=null&&k.bottom&&(A+=`bottom=${c.extra.scrollData.bottom}`),F+=` data-scrollable="${A}"`}if(V){const A=V.trim();$||(F+=" "),F+=`>${A}`}else $||(F+=" ");F+=" />",C.push(F)}for(const V of c.children)v(V,B,C)}else if(c.type==="text"){if(f(c))return;c.parent&&c.parent.type==="element"&&c.parent.isVisible&&c.parent.isTopElement&&C.push(`${D}${c.text??""}`)}},m=[];return v(l,0,m),m.join(`
|
|
2
|
+
`)}const getAllTextTillNextClickableElement=(o,e=-1)=>{const n=[],r=(d,h)=>{if(!(e!==-1&&h>e)&&!(d.type==="element"&&d!==o&&d.highlightIndex!==void 0)){if(d.type==="text"&&d.text)n.push(d.text);else if(d.type==="element")for(const s of d.children)r(s,h+1)}};return r(o,0),n.join(`
|
|
3
|
+
`).trim()};function getSelectorMap(o){const e=new Map,n=Object.keys(o.map);for(const r of n){const d=o.map[r];d.isInteractive&&typeof d.highlightIndex=="number"&&e.set(d.highlightIndex,d)}return e}function getElementTextMap(o){const e=o.split(`
|
|
4
|
+
`).map(r=>r.trim()).filter(r=>r.length>0),n=new Map;for(const r of e){const h=/^\[(\d+)\]<[^>]+>([^<]*)/.exec(r);if(h){const s=parseInt(h[1],10);n.set(s,r)}}return n}function cleanUpHighlights(){const o=window._highlightCleanupFunctions||[];for(const e of o)typeof e=="function"&&e();window._highlightCleanupFunctions=[]}window.addEventListener("popstate",()=>{cleanUpHighlights()});window.addEventListener("hashchange",()=>{cleanUpHighlights()});window.addEventListener("beforeunload",()=>{cleanUpHighlights()});const navigation=window.navigation;if(navigation&&typeof navigation.addEventListener=="function")navigation.addEventListener("navigate",()=>{cleanUpHighlights()});else{let o=window.location.href;setInterval(()=>{window.location.href!==o&&(o=window.location.href,cleanUpHighlights())},500)}function getPageInfo(){const o=window.innerWidth,e=window.innerHeight,n=Math.max(document.documentElement.scrollWidth,document.body.scrollWidth||0),r=Math.max(document.documentElement.scrollHeight,document.body.scrollHeight||0),d=window.scrollX||window.pageXOffset||document.documentElement.scrollLeft||0,h=window.scrollY||window.pageYOffset||document.documentElement.scrollTop||0,s=Math.max(0,r-(window.innerHeight+h)),l=Math.max(0,n-(window.innerWidth+d));return{viewport_width:o,viewport_height:e,page_width:n,page_height:r,scroll_x:d,scroll_y:h,pixels_above:h,pixels_below:s,pages_above:e>0?h/e:0,pages_below:e>0?s/e:0,total_pages:e>0?r/e:0,current_page_position:h/Math.max(1,r-e),pixels_left:d,pixels_right:l}}function patchReact(o){const e=document.querySelectorAll('[data-reactroot], [data-reactid], [data-react-checksum], #root, #app, [id^="root-"], [id^="app-"], #adex-wrapper, #adex-root');for(const n of e)n.setAttribute("data-page-agent-not-interactive","true")}class PageController extends EventTarget{constructor(o={}){super(),this.flatTree=null,this.selectorMap=new Map,this.elementTextMap=new Map,this.simplifiedHTML="<EMPTY>",this.lastTimeUpdate=0,this.isIndexed=!1,this.mask=null,this.maskReady=null,this.config=o,patchReact(),o.enableMask&&this.initMask()}initMask(){this.maskReady===null&&(this.maskReady=(async()=>{const{SimulatorMask:o}=await Promise.resolve().then(()=>require("./SimulatorMask-jCkPs2Tt.cjs"));this.mask=new o})())}async getCurrentUrl(){return window.location.href}async getLastUpdateTime(){return this.lastTimeUpdate}async getBrowserState(){const o=window.location.href,e=document.title,n=getPageInfo(),r=this.config.viewportExpansion??VIEWPORT_EXPANSION;await this.updateTree();const d=this.simplifiedHTML,h=`Current Page: [${e}](${o})`,s=`Page info: ${n.viewport_width}x${n.viewport_height}px viewport, ${n.page_width}x${n.page_height}px total page size, ${n.pages_above.toFixed(1)} pages above, ${n.pages_below.toFixed(1)} pages below, ${n.total_pages.toFixed(1)} total pages, at ${(n.current_page_position*100).toFixed(0)}% of page`,l=r===-1?"Interactive elements from top layer of the current page (full page):":"Interactive elements from top layer of the current page inside the viewport:",v=n.pixels_above>4&&r!==-1?`... ${n.pixels_above} pixels above (${n.pages_above.toFixed(1)} pages) - scroll to see more ...`:"[Start of page]",m=`${h}
|
|
5
|
+
${s}
|
|
6
|
+
|
|
7
|
+
${l}
|
|
8
|
+
|
|
9
|
+
${v}`,g=n.pixels_below>4&&r!==-1?`... ${n.pixels_below} pixels below (${n.pages_below.toFixed(1)} pages) - scroll to see more ...`:"[End of page]";return{url:o,title:e,header:m,content:d,footer:g}}async updateTree(){this.dispatchEvent(new Event("beforeUpdate")),this.lastTimeUpdate=Date.now(),this.mask&&(this.mask.wrapper.style.pointerEvents="none"),cleanUpHighlights();const o=[...this.config.interactiveBlacklist||[],...document.querySelectorAll("[data-page-agent-not-interactive]").values()];return this.flatTree=getFlatTree({...this.config,interactiveBlacklist:o}),this.simplifiedHTML=flatTreeToString(this.flatTree,this.config.include_attributes),this.selectorMap.clear(),this.selectorMap=getSelectorMap(this.flatTree),this.elementTextMap.clear(),this.elementTextMap=getElementTextMap(this.simplifiedHTML),this.isIndexed=!0,this.mask&&(this.mask.wrapper.style.pointerEvents="auto"),this.dispatchEvent(new Event("afterUpdate")),this.simplifiedHTML}async cleanUpHighlights(){cleanUpHighlights()}assertIndexed(){if(!this.isIndexed)throw new Error("DOM tree not indexed yet. Can not perform actions on elements.")}async clickElement(o){try{this.assertIndexed();const e=getElementByIndex(this.selectorMap,o),n=this.elementTextMap.get(o);return await clickElement(e),e instanceof HTMLAnchorElement&&e.target==="_blank"?{success:!0,message:`✅ Clicked element (${n??o}). ⚠️ Link opens in a new tab. You are not capable of reading new tabs.`}:{success:!0,message:`✅ Clicked element (${n??o}).`}}catch(e){return{success:!1,message:`❌ Failed to click element: ${e}`}}}async inputText(o,e){try{this.assertIndexed();const n=getElementByIndex(this.selectorMap,o),r=this.elementTextMap.get(o);return await inputTextElement(n,e),{success:!0,message:`✅ Input text (${e}) into element (${r??o}).`}}catch(n){return{success:!1,message:`❌ Failed to input text: ${n}`}}}async selectOption(o,e){try{this.assertIndexed();const n=getElementByIndex(this.selectorMap,o),r=this.elementTextMap.get(o);return await selectOptionElement(n,e),{success:!0,message:`✅ Selected option (${e}) in element (${r??o}).`}}catch(n){return{success:!1,message:`❌ Failed to select option: ${n}`}}}async scroll(o){try{const{down:e,numPages:n,pixels:r,index:d}=o;this.assertIndexed();const h=r??n*(e?1:-1)*window.innerHeight,s=d!==void 0?getElementByIndex(this.selectorMap,d):null;return{success:!0,message:await scrollVertically(e,h,s)}}catch(e){return{success:!1,message:`❌ Failed to scroll: ${e}`}}}async scrollHorizontally(o){try{const{right:e,pixels:n,index:r}=o;this.assertIndexed();const d=n*(e?1:-1),h=r!==void 0?getElementByIndex(this.selectorMap,r):null;return{success:!0,message:await scrollHorizontally(e,d,h)}}catch(e){return{success:!1,message:`❌ Failed to scroll horizontally: ${e}`}}}async executeJavascript(script){try{const asyncFunction=eval(`(async () => { ${script} })`),result=await asyncFunction();return{success:!0,message:`✅ Executed JavaScript. Result: ${result}`}}catch(o){return{success:!1,message:`❌ Error executing JavaScript: ${o}`}}}async showMask(){var o;await this.maskReady,(o=this.mask)==null||o.show()}async hideMask(){var o;await this.maskReady,(o=this.mask)==null||o.hide()}dispose(){var o;cleanUpHighlights(),this.flatTree=null,this.selectorMap.clear(),this.elementTextMap.clear(),this.simplifiedHTML="<EMPTY>",this.isIndexed=!1,(o=this.mask)==null||o.dispose(),this.mask=null}}const PageController$1=Object.freeze(Object.defineProperty({__proto__:null,PageController},Symbol.toStringTag,{value:"Module"}));let injectedPageController=null,PageControllerModule=null;function setPageController(o){injectedPageController=o}async function getPageController(){if(injectedPageController)return injectedPageController;if(!PageControllerModule)try{PageControllerModule=await Promise.resolve().then(()=>PageController$1)}catch{throw new Error('PageController not available. Either import from "@usecrow/client/browser" or use the bundled version.')}return PageControllerModule.PageController}class CrowBrowserUse{constructor(e){this.pageController=null,this.sessionId=null,this.maxSteps=20,this.aborted=!1,this.config=e}async initPageController(){if(this.pageController)return this.pageController;try{const e=await getPageController();this.pageController=new e({enableMask:!0,viewportExpansion:500,highlightLabelOpacity:0,highlightOpacity:0}),await this.pageController.showMask();const n=this.pageController.mask;return n!=null&&n.wrapper&&(n.wrapper.style.pointerEvents="none"),console.log("[CrowBrowserUse] PageController initialized with non-blocking pointer"),this.pageController}catch(e){throw console.error("[CrowBrowserUse] Failed to initialize PageController:",e),new Error("Failed to initialize browser automation. Please import from @usecrow/client/browser.")}}async execute(e){var n,r,d,h,s,l,f,v,m,c,g,C,B,D;if(console.log("[CrowBrowserUse] Starting task:",e),this.config.onConfirmation&&!await this.config.onConfirmation(e))return console.log("[CrowBrowserUse] User declined browser automation"),(r=(n=this.config).onProgress)==null||r.call(n,-1,this.maxSteps),{status:"error",error:"User declined browser automation",data:{declined:!0}};try{const S=await this.initPageController(),H=await this.startSession(e);this.sessionId=H.session_id,this.maxSteps=H.max_steps,console.log("[CrowBrowserUse] Session started:",this.sessionId);let U=0,k;for(;U<this.maxSteps;){if(this.aborted)return console.log("[CrowBrowserUse] Task cancelled by user"),await this.cleanup(),(h=(d=this.config).onProgress)==null||h.call(d,-1,this.maxSteps),{status:"error",error:"Task cancelled by user"};U++;const V=await S.getBrowserState(),$=S.mask;$!=null&&$.wrapper&&($.wrapper.style.pointerEvents="none");const R=await this.processStep(V,k);if(R.needs_user_input&&R.question){if(console.log("[CrowBrowserUse] Asking user:",R.question),!this.config.onQuestion){k="User input not available - no callback provided",console.warn("[CrowBrowserUse] No onQuestion callback provided");continue}try{const F=await this.config.onQuestion(R.question);k=`User answered: ${F}`,console.log("[CrowBrowserUse] User answered:",F)}catch(F){if(k="User cancelled or failed to respond",console.log("[CrowBrowserUse] User cancelled or error:",F),this.aborted)return console.log("[CrowBrowserUse] Aborted after user cancelled"),await this.cleanup(),(l=(s=this.config).onProgress)==null||l.call(s,-1,this.maxSteps),{status:"error",error:"Task cancelled by user"}}continue}if(R.done)return console.log("[CrowBrowserUse] Task completed:",R.message),await this.cleanup(),(v=(f=this.config).onProgress)==null||v.call(f,U,this.maxSteps),{status:R.success?"success":"error",data:{message:R.message,steps:U},error:R.success?void 0:R.message};if(R.error)return console.error("[CrowBrowserUse] Error:",R.error),await this.cleanup(),(c=(m=this.config).onProgress)==null||c.call(m,-1,this.maxSteps),{status:"error",error:R.error};R.action&&(k=await this.executeAction(S,R.action),console.log(`[CrowBrowserUse] Step ${U}:`,k)),R.reflection&&console.log("[CrowBrowserUse] Reflection:",R.reflection.next_goal)}return await this.cleanup(),(C=(g=this.config).onProgress)==null||C.call(g,-1,this.maxSteps),{status:"error",error:`Task incomplete after ${this.maxSteps} steps`}}catch(S){return console.error("[CrowBrowserUse] Error:",S),await this.cleanup(),(D=(B=this.config).onProgress)==null||D.call(B,-1,this.maxSteps),{status:"error",error:S instanceof Error?S.message:String(S)}}}async startSession(e){const n=await fetch(`${this.config.apiUrl}/api/browser-use/start`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({product_id:this.config.productId,task:e})});if(!n.ok){const r=await n.json().catch(()=>({detail:"Unknown error"}));throw new Error(r.detail||`Failed to start session: ${n.status}`)}return n.json()}async processStep(e,n){const r=await fetch(`${this.config.apiUrl}/api/browser-use/step`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({session_id:this.sessionId,product_id:this.config.productId,browser_state:e,action_result:n})});if(!r.ok){const d=await r.json().catch(()=>({detail:"Unknown error"}));throw new Error(d.detail||`Failed to process step: ${r.status}`)}return r.json()}async executeAction(e,n){const r=Object.keys(n)[0],d=n[r];try{switch(r){case"click_element_by_index":return(await e.clickElement(d.index)).message;case"input_text":return(await e.inputText(d.index,d.text)).message;case"select_dropdown_option":return(await e.selectOption(d.index,d.text)).message;case"scroll":return(await e.scroll({down:d.down,numPages:d.num_pages,pixels:d.pixels,index:d.index})).message;case"scroll_horizontally":return(await e.scrollHorizontally({right:d.right,pixels:d.pixels,index:d.index})).message;case"wait":{const h=d.seconds||1;return await new Promise(s=>setTimeout(s,h*1e3)),`Waited ${h} seconds`}case"done":return"Task completed";default:return`Unknown action: ${r}`}}catch(h){return`Action failed: ${h instanceof Error?h.message:String(h)}`}}async cleanup(){if(this.pageController){try{await this.pageController.hideMask(),await this.pageController.cleanUpHighlights(),this.pageController.dispose()}catch(e){console.warn("[CrowBrowserUse] Cleanup error:",e)}this.pageController=null}if(this.sessionId){try{await fetch(`${this.config.apiUrl}/api/browser-use/end`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({session_id:this.sessionId,product_id:this.config.productId})})}catch{}this.sessionId=null}}async stop(){this.aborted=!0,await this.cleanup()}}exports.CrowBrowserUse=CrowBrowserUse;exports.PageController=PageController;exports.setPageController=setPageController;
|
|
@@ -25,17 +25,23 @@ function blurLastClickedElement() {
|
|
|
25
25
|
async function clickElement(o) {
|
|
26
26
|
blurLastClickedElement(), lastClickedElement = o, await scrollIntoViewIfNeeded(o), await movePointerToElement(o), window.dispatchEvent(new CustomEvent("PageAgent::ClickPointer")), await waitFor(0.1), o.dispatchEvent(new MouseEvent("mouseenter", { bubbles: !0, cancelable: !0 })), o.dispatchEvent(new MouseEvent("mouseover", { bubbles: !0, cancelable: !0 })), o.dispatchEvent(new MouseEvent("mousedown", { bubbles: !0, cancelable: !0 })), o.focus(), o.dispatchEvent(new MouseEvent("mouseup", { bubbles: !0, cancelable: !0 })), o.dispatchEvent(new MouseEvent("click", { bubbles: !0, cancelable: !0 })), await waitFor(0.1);
|
|
27
27
|
}
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
28
|
+
let _nativeInputValueSetter, _nativeTextAreaValueSetter;
|
|
29
|
+
function getNativeInputValueSetter() {
|
|
30
|
+
return _nativeInputValueSetter || (_nativeInputValueSetter = Object.getOwnPropertyDescriptor(
|
|
31
|
+
window.HTMLInputElement.prototype,
|
|
32
|
+
"value"
|
|
33
|
+
).set), _nativeInputValueSetter;
|
|
34
|
+
}
|
|
35
|
+
function getNativeTextAreaValueSetter() {
|
|
36
|
+
return _nativeTextAreaValueSetter || (_nativeTextAreaValueSetter = Object.getOwnPropertyDescriptor(
|
|
37
|
+
window.HTMLTextAreaElement.prototype,
|
|
38
|
+
"value"
|
|
39
|
+
).set), _nativeTextAreaValueSetter;
|
|
40
|
+
}
|
|
35
41
|
async function inputTextElement(o, e) {
|
|
36
42
|
if (!(o instanceof HTMLInputElement || o instanceof HTMLTextAreaElement))
|
|
37
43
|
throw new Error("Element is not an input or textarea");
|
|
38
|
-
await clickElement(o), o instanceof HTMLTextAreaElement ?
|
|
44
|
+
await clickElement(o), o instanceof HTMLTextAreaElement ? getNativeTextAreaValueSetter().call(o, e) : getNativeInputValueSetter().call(o, e);
|
|
39
45
|
const n = new Event("input", { bubbles: !0 });
|
|
40
46
|
o.dispatchEvent(n), await waitFor(0.1), blurLastClickedElement();
|
|
41
47
|
}
|
|
@@ -77,15 +83,15 @@ async function scrollVertically(o, e, n) {
|
|
|
77
83
|
"clientHeight:",
|
|
78
84
|
f.clientHeight
|
|
79
85
|
), D && S) {
|
|
80
|
-
const
|
|
86
|
+
const H = f.scrollTop, U = f.scrollHeight - f.clientHeight;
|
|
81
87
|
let k = C / 3;
|
|
82
|
-
k > 0 ? k = Math.min(k, U -
|
|
83
|
-
const V = f.scrollTop, $ = V -
|
|
88
|
+
k > 0 ? k = Math.min(k, U - H) : k = Math.max(k, -H), f.scrollTop = H + k;
|
|
89
|
+
const V = f.scrollTop, $ = V - H;
|
|
84
90
|
if (console.log(
|
|
85
91
|
"[SCROLL DEBUG] Scroll attempt:",
|
|
86
92
|
f.tagName,
|
|
87
93
|
"before:",
|
|
88
|
-
|
|
94
|
+
H,
|
|
89
95
|
"after:",
|
|
90
96
|
V,
|
|
91
97
|
"delta:",
|
|
@@ -150,15 +156,15 @@ async function scrollHorizontally(o, e, n) {
|
|
|
150
156
|
"clientWidth:",
|
|
151
157
|
f.clientWidth
|
|
152
158
|
), D && S) {
|
|
153
|
-
const
|
|
159
|
+
const H = f.scrollLeft, U = f.scrollWidth - f.clientWidth;
|
|
154
160
|
let k = C / 3;
|
|
155
|
-
k > 0 ? k = Math.min(k, U -
|
|
156
|
-
const V = f.scrollLeft, $ = V -
|
|
161
|
+
k > 0 ? k = Math.min(k, U - H) : k = Math.max(k, -H), f.scrollLeft = H + k;
|
|
162
|
+
const V = f.scrollLeft, $ = V - H;
|
|
157
163
|
if (console.log(
|
|
158
164
|
"[SCROLL DEBUG] Scroll attempt:",
|
|
159
165
|
f.tagName,
|
|
160
166
|
"before:",
|
|
161
|
-
|
|
167
|
+
H,
|
|
162
168
|
"after:",
|
|
163
169
|
V,
|
|
164
170
|
"delta:",
|
|
@@ -250,11 +256,11 @@ const VIEWPORT_EXPANSION = -1, domTree = (o = {
|
|
|
250
256
|
const i = t.getClientRects();
|
|
251
257
|
return i && p.clientRects.set(t, i), i;
|
|
252
258
|
}
|
|
253
|
-
const S = {},
|
|
259
|
+
const S = {}, H = { current: 0 }, U = "playwright-highlight-container";
|
|
254
260
|
function k(t, i, w = null) {
|
|
255
261
|
if (!t) return i;
|
|
256
262
|
const u = [];
|
|
257
|
-
let a = null, x = 20, E = 16,
|
|
263
|
+
let a = null, x = 20, E = 16, _ = null;
|
|
258
264
|
try {
|
|
259
265
|
let b = document.getElementById(U);
|
|
260
266
|
b || (b = document.createElement("div"), b.id = U, b.style.position = "fixed", b.style.pointerEvents = "none", b.style.top = "0", b.style.left = "0", b.style.width = "100%", b.style.height = "100%", b.style.zIndex = "2147483640", b.style.backgroundColor = "transparent", document.body.appendChild(b));
|
|
@@ -326,12 +332,12 @@ const VIEWPORT_EXPANSION = -1, domTree = (o = {
|
|
|
326
332
|
(T.width < x + 4 || T.height < E + 4) && (tt = W - E - 2, Q = X + T.width - x, Q < M.x && (Q = X)), tt = Math.max(0, Math.min(tt, window.innerHeight - E)), Q = Math.max(0, Math.min(Q, window.innerWidth - x)), a.style.top = `${tt}px`, a.style.left = `${Q}px`, a.style.display = "block";
|
|
327
333
|
} else a && (a.style.display = "none");
|
|
328
334
|
}, 16);
|
|
329
|
-
return window.addEventListener("scroll", q, !0), window.addEventListener("resize", q),
|
|
335
|
+
return window.addEventListener("scroll", q, !0), window.addEventListener("resize", q), _ = () => {
|
|
330
336
|
window.removeEventListener("scroll", q, !0), window.removeEventListener("resize", q), u.forEach((N) => N.element.remove()), a && a.remove();
|
|
331
337
|
}, b.appendChild(j), i + 1;
|
|
332
338
|
} finally {
|
|
333
|
-
|
|
334
|
-
|
|
339
|
+
_ && (window._highlightCleanupFunctions = window._highlightCleanupFunctions || []).push(
|
|
340
|
+
_
|
|
335
341
|
);
|
|
336
342
|
}
|
|
337
343
|
}
|
|
@@ -346,8 +352,8 @@ const VIEWPORT_EXPANSION = -1, domTree = (o = {
|
|
|
346
352
|
const u = i.overflowX, a = i.overflowY, x = u === "auto" || u === "scroll", E = a === "auto" || a === "scroll";
|
|
347
353
|
if (!x && !E)
|
|
348
354
|
return null;
|
|
349
|
-
const
|
|
350
|
-
if (
|
|
355
|
+
const _ = t.scrollWidth - t.clientWidth, b = t.scrollHeight - t.clientHeight, P = 4;
|
|
356
|
+
if (_ < P && b < P || !E && _ < P || !x && b < P)
|
|
351
357
|
return null;
|
|
352
358
|
const O = t.scrollTop, g = t.scrollLeft, y = t.scrollWidth - t.clientWidth - t.scrollLeft, I = t.scrollHeight - t.clientHeight - t.scrollTop, L = {
|
|
353
359
|
top: O,
|
|
@@ -396,14 +402,14 @@ const VIEWPORT_EXPANSION = -1, domTree = (o = {
|
|
|
396
402
|
checkVisibilityCSS: !0
|
|
397
403
|
});
|
|
398
404
|
} catch {
|
|
399
|
-
const
|
|
400
|
-
return
|
|
405
|
+
const _ = window.getComputedStyle(x);
|
|
406
|
+
return _.display !== "none" && _.visibility !== "hidden" && _.opacity !== "0";
|
|
401
407
|
}
|
|
402
408
|
} catch (i) {
|
|
403
409
|
return console.warn("Error checking text node visibility:", i), !1;
|
|
404
410
|
}
|
|
405
411
|
}
|
|
406
|
-
function
|
|
412
|
+
function R(t) {
|
|
407
413
|
if (!t || !t.tagName) return !1;
|
|
408
414
|
const i = /* @__PURE__ */ new Set([
|
|
409
415
|
"body",
|
|
@@ -517,7 +523,7 @@ const VIEWPORT_EXPANSION = -1, domTree = (o = {
|
|
|
517
523
|
}
|
|
518
524
|
if (x(t))
|
|
519
525
|
return !0;
|
|
520
|
-
const
|
|
526
|
+
const _ = /* @__PURE__ */ new Set([
|
|
521
527
|
"a",
|
|
522
528
|
// Links
|
|
523
529
|
"button",
|
|
@@ -556,7 +562,7 @@ const VIEWPORT_EXPANSION = -1, domTree = (o = {
|
|
|
556
562
|
// 'tabindex="-1"', // Removed from tab order
|
|
557
563
|
// 'aria-hidden="true"' // Hidden from screen readers
|
|
558
564
|
]);
|
|
559
|
-
if (
|
|
565
|
+
if (_.has(i)) {
|
|
560
566
|
if (w != null && w.cursor && a.has(w.cursor))
|
|
561
567
|
return !1;
|
|
562
568
|
for (const j of b)
|
|
@@ -606,7 +612,7 @@ const VIEWPORT_EXPANSION = -1, domTree = (o = {
|
|
|
606
612
|
"scrollbar"
|
|
607
613
|
// Scrollable control
|
|
608
614
|
]);
|
|
609
|
-
if (
|
|
615
|
+
if (_.has(i) || P && g.has(P) || O && g.has(O)) return !0;
|
|
610
616
|
try {
|
|
611
617
|
if (typeof getEventListeners == "function") {
|
|
612
618
|
const J = getEventListeners(t), nt = ["click", "mousedown", "mouseup", "dblclick"];
|
|
@@ -775,7 +781,7 @@ const VIEWPORT_EXPANSION = -1, domTree = (o = {
|
|
|
775
781
|
try {
|
|
776
782
|
const x = ((a = (u = t == null ? void 0 : t.ownerDocument) == null ? void 0 : u.defaultView) == null ? void 0 : a.getEventListenersForNode) || window.getEventListenersForNode;
|
|
777
783
|
if (typeof x == "function") {
|
|
778
|
-
const
|
|
784
|
+
const _ = x(t), b = [
|
|
779
785
|
"click",
|
|
780
786
|
"mousedown",
|
|
781
787
|
"mouseup",
|
|
@@ -788,7 +794,7 @@ const VIEWPORT_EXPANSION = -1, domTree = (o = {
|
|
|
788
794
|
"blur"
|
|
789
795
|
];
|
|
790
796
|
for (const P of b)
|
|
791
|
-
for (const O of
|
|
797
|
+
for (const O of _)
|
|
792
798
|
if (O.type === P)
|
|
793
799
|
return !0;
|
|
794
800
|
}
|
|
@@ -802,7 +808,7 @@ const VIEWPORT_EXPANSION = -1, domTree = (o = {
|
|
|
802
808
|
"oninput",
|
|
803
809
|
"onfocus",
|
|
804
810
|
"onblur"
|
|
805
|
-
].some((
|
|
811
|
+
].some((_) => t.hasAttribute(_)))
|
|
806
812
|
return !0;
|
|
807
813
|
} catch {
|
|
808
814
|
}
|
|
@@ -814,7 +820,7 @@ const VIEWPORT_EXPANSION = -1, domTree = (o = {
|
|
|
814
820
|
return u ? it(i) ? a = !0 : a = !1 : a = !0, a && (t.isInViewport = rt(i, l), (t.isInViewport || l === -1) && (t.highlightIndex = v++, h)) ? (s >= 0 ? s === t.highlightIndex && k(i, t.highlightIndex, w) : k(i, t.highlightIndex, w), !0) : !1;
|
|
815
821
|
}
|
|
816
822
|
function Z(t, i = null, w = !1) {
|
|
817
|
-
var E,
|
|
823
|
+
var E, _, b, P, O;
|
|
818
824
|
if (!t || t.id === U || t.nodeType !== Node.ELEMENT_NODE && t.nodeType !== Node.TEXT_NODE || !t || t.id === U || ((E = t.dataset) == null ? void 0 : E.browserUseIgnore) === "true" || t.getAttribute && t.getAttribute("aria-hidden") === "true")
|
|
819
825
|
return null;
|
|
820
826
|
if (t === document.body) {
|
|
@@ -828,26 +834,26 @@ const VIEWPORT_EXPANSION = -1, domTree = (o = {
|
|
|
828
834
|
const L = Z(I, i, !1);
|
|
829
835
|
L && g.children.push(L);
|
|
830
836
|
}
|
|
831
|
-
const y = `${
|
|
837
|
+
const y = `${H.current++}`;
|
|
832
838
|
return S[y] = g, y;
|
|
833
839
|
}
|
|
834
840
|
if (t.nodeType !== Node.ELEMENT_NODE && t.nodeType !== Node.TEXT_NODE)
|
|
835
841
|
return null;
|
|
836
842
|
if (t.nodeType === Node.TEXT_NODE) {
|
|
837
|
-
const g = (
|
|
843
|
+
const g = (_ = t.textContent) == null ? void 0 : _.trim();
|
|
838
844
|
if (!g)
|
|
839
845
|
return null;
|
|
840
846
|
const y = t.parentElement;
|
|
841
847
|
if (!y || y.tagName.toLowerCase() === "script")
|
|
842
848
|
return null;
|
|
843
|
-
const I = `${
|
|
849
|
+
const I = `${H.current++}`;
|
|
844
850
|
return S[I] = {
|
|
845
851
|
type: "TEXT_NODE",
|
|
846
852
|
text: g,
|
|
847
853
|
isVisible: $(t)
|
|
848
854
|
}, I;
|
|
849
855
|
}
|
|
850
|
-
if (t.nodeType === Node.ELEMENT_NODE && !
|
|
856
|
+
if (t.nodeType === Node.ELEMENT_NODE && !R(t))
|
|
851
857
|
return null;
|
|
852
858
|
if (l !== -1 && !t.shadowRoot) {
|
|
853
859
|
const g = C(t), y = B(t), I = y && (y.position === "fixed" || y.position === "sticky"), L = t.offsetWidth > 0 || t.offsetHeight > 0;
|
|
@@ -915,7 +921,7 @@ const VIEWPORT_EXPANSION = -1, domTree = (o = {
|
|
|
915
921
|
return null;
|
|
916
922
|
}
|
|
917
923
|
u.extra = m.get(t) || null;
|
|
918
|
-
const x = `${
|
|
924
|
+
const x = `${H.current++}`;
|
|
919
925
|
return S[x] = u, x;
|
|
920
926
|
}
|
|
921
927
|
const lt = Z(document.body);
|
|
@@ -1020,7 +1026,7 @@ function flatTreeToString(o, e) {
|
|
|
1020
1026
|
}
|
|
1021
1027
|
return !1;
|
|
1022
1028
|
}, v = (c, p, C) => {
|
|
1023
|
-
var S,
|
|
1029
|
+
var S, H, U, k;
|
|
1024
1030
|
let B = p;
|
|
1025
1031
|
const D = " ".repeat(p);
|
|
1026
1032
|
if (c.type === "element") {
|
|
@@ -1050,11 +1056,11 @@ function flatTreeToString(o, e) {
|
|
|
1050
1056
|
A[z] && A[z].toLowerCase().trim() === V.toLowerCase().trim() && delete A[z];
|
|
1051
1057
|
Object.keys(A).length > 0 && ($ = Object.entries(A).map(([z, Y]) => `${z}=${d(Y, 20)}`).join(" "));
|
|
1052
1058
|
}
|
|
1053
|
-
const
|
|
1054
|
-
let F = `${D}${
|
|
1059
|
+
const R = c.isNew ? `*[${c.highlightIndex}]` : `[${c.highlightIndex}]`;
|
|
1060
|
+
let F = `${D}${R}<${c.tagName ?? ""}`;
|
|
1055
1061
|
if ($ && (F += ` ${$}`), c.extra && c.extra.scrollable) {
|
|
1056
1062
|
let A = "";
|
|
1057
|
-
(S = c.extra.scrollData) != null && S.left && (A += `left=${c.extra.scrollData.left}, `), (
|
|
1063
|
+
(S = c.extra.scrollData) != null && S.left && (A += `left=${c.extra.scrollData.left}, `), (H = c.extra.scrollData) != null && H.top && (A += `top=${c.extra.scrollData.top}, `), (U = c.extra.scrollData) != null && U.right && (A += `right=${c.extra.scrollData.right}, `), (k = c.extra.scrollData) != null && k.bottom && (A += `bottom=${c.extra.scrollData.bottom}`), F += ` data-scrollable="${A}"`;
|
|
1058
1064
|
}
|
|
1059
1065
|
if (V) {
|
|
1060
1066
|
const A = V.trim();
|
|
@@ -1435,8 +1441,8 @@ class CrowBrowserUse {
|
|
|
1435
1441
|
data: { declined: !0 }
|
|
1436
1442
|
};
|
|
1437
1443
|
try {
|
|
1438
|
-
const S = await this.initPageController(),
|
|
1439
|
-
this.sessionId =
|
|
1444
|
+
const S = await this.initPageController(), H = await this.startSession(e);
|
|
1445
|
+
this.sessionId = H.session_id, this.maxSteps = H.max_steps, console.log("[CrowBrowserUse] Session started:", this.sessionId);
|
|
1440
1446
|
let U = 0, k;
|
|
1441
1447
|
for (; U < this.maxSteps; ) {
|
|
1442
1448
|
if (this.aborted)
|
|
@@ -1447,14 +1453,14 @@ class CrowBrowserUse {
|
|
|
1447
1453
|
U++;
|
|
1448
1454
|
const V = await S.getBrowserState(), $ = S.mask;
|
|
1449
1455
|
$ != null && $.wrapper && ($.wrapper.style.pointerEvents = "none");
|
|
1450
|
-
const
|
|
1451
|
-
if (
|
|
1452
|
-
if (console.log("[CrowBrowserUse] Asking user:",
|
|
1456
|
+
const R = await this.processStep(V, k);
|
|
1457
|
+
if (R.needs_user_input && R.question) {
|
|
1458
|
+
if (console.log("[CrowBrowserUse] Asking user:", R.question), !this.config.onQuestion) {
|
|
1453
1459
|
k = "User input not available - no callback provided", console.warn("[CrowBrowserUse] No onQuestion callback provided");
|
|
1454
1460
|
continue;
|
|
1455
1461
|
}
|
|
1456
1462
|
try {
|
|
1457
|
-
const F = await this.config.onQuestion(
|
|
1463
|
+
const F = await this.config.onQuestion(R.question);
|
|
1458
1464
|
k = `User answered: ${F}`, console.log("[CrowBrowserUse] User answered:", F);
|
|
1459
1465
|
} catch (F) {
|
|
1460
1466
|
if (k = "User cancelled or failed to respond", console.log("[CrowBrowserUse] User cancelled or error:", F), this.aborted)
|
|
@@ -1465,21 +1471,21 @@ class CrowBrowserUse {
|
|
|
1465
1471
|
}
|
|
1466
1472
|
continue;
|
|
1467
1473
|
}
|
|
1468
|
-
if (
|
|
1469
|
-
return console.log("[CrowBrowserUse] Task completed:",
|
|
1470
|
-
status:
|
|
1474
|
+
if (R.done)
|
|
1475
|
+
return console.log("[CrowBrowserUse] Task completed:", R.message), await this.cleanup(), (v = (f = this.config).onProgress) == null || v.call(f, U, this.maxSteps), {
|
|
1476
|
+
status: R.success ? "success" : "error",
|
|
1471
1477
|
data: {
|
|
1472
|
-
message:
|
|
1478
|
+
message: R.message,
|
|
1473
1479
|
steps: U
|
|
1474
1480
|
},
|
|
1475
|
-
error:
|
|
1481
|
+
error: R.success ? void 0 : R.message
|
|
1476
1482
|
};
|
|
1477
|
-
if (
|
|
1478
|
-
return console.error("[CrowBrowserUse] Error:",
|
|
1483
|
+
if (R.error)
|
|
1484
|
+
return console.error("[CrowBrowserUse] Error:", R.error), await this.cleanup(), (c = (m = this.config).onProgress) == null || c.call(m, -1, this.maxSteps), {
|
|
1479
1485
|
status: "error",
|
|
1480
|
-
error:
|
|
1486
|
+
error: R.error
|
|
1481
1487
|
};
|
|
1482
|
-
|
|
1488
|
+
R.action && (k = await this.executeAction(S, R.action), console.log(`[CrowBrowserUse] Step ${U}:`, k)), R.reflection && console.log("[CrowBrowserUse] Reflection:", R.reflection.next_goal);
|
|
1483
1489
|
}
|
|
1484
1490
|
return await this.cleanup(), (C = (p = this.config).onProgress) == null || C.call(p, -1, this.maxSteps), {
|
|
1485
1491
|
status: "error",
|
package/dist/index.cjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const _=require("./browserUse-
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const _=require("./browserUse-CAnPpcJX.cjs");class k{constructor(){this.state={token:null,metadata:{},isVerified:!1},this.listeners=new Set}identify(e){const{token:t,...s}=e;this.state={token:t,metadata:s,isVerified:!1},this.notify(),console.log("[Crow] User identified")}setVerified(e){this.state={...this.state,isVerified:e},this.notify()}reset(){this.state={token:null,metadata:{},isVerified:!1},this.notify(),console.log("[Crow] User reset")}getToken(){return this.state.token}getState(){return{...this.state}}isIdentified(){return this.state.token!==null}isVerified(){return this.state.isVerified}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}notify(){const e=this.getState();for(const t of this.listeners)t(e)}}class C{constructor(){this.handlers={}}register(e){for(const[t,s]of Object.entries(e))typeof s=="function"?(this.handlers[t]=s,console.log(`[Crow] Registered client tool: ${t}`)):console.warn(`[Crow] Skipping ${t}: handler is not a function`)}unregister(e){delete this.handlers[e],console.log(`[Crow] Unregistered client tool: ${e}`)}has(e){return e in this.handlers}getRegisteredTools(){return Object.keys(this.handlers)}async execute(e,t){const s=this.handlers[e];if(!s)return console.warn(`[Crow] No handler registered for tool: ${e}`),{status:"error",error:`No handler registered for tool: ${e}`};try{console.log(`[Crow] Executing client tool: ${e}`,t);const r=await s(t);return console.log(`[Crow] Tool ${e} completed:`,r),r}catch(r){const i=r instanceof Error?r.message:String(r);return console.error(`[Crow] Tool ${e} failed:`,r),{status:"error",error:i}}}}const T="crow_conv_";class S{constructor(e,t){this.currentId=null,this.productId=e,this.apiUrl=t,this.currentId=this.loadFromStorage()}getStorageKey(){return`${T}${this.productId}`}loadFromStorage(){try{return localStorage.getItem(this.getStorageKey())}catch{return null}}saveToStorage(e){try{localStorage.setItem(this.getStorageKey(),e)}catch{}}clearStorage(){try{localStorage.removeItem(this.getStorageKey())}catch{}}getCurrentId(){return this.currentId}setCurrentId(e){this.currentId=e,e?this.saveToStorage(e):this.clearStorage()}hasRestoredConversation(){return this.currentId!==null}clear(){this.currentId=null,this.clearStorage()}async getConversations(e){try{const t=await fetch(`${this.apiUrl}/api/chat/conversations?product_id=${this.productId}&identity_token=${encodeURIComponent(e)}`);if(!t.ok)throw new Error(`HTTP error: ${t.status}`);return(await t.json()).conversations||[]}catch(t){return console.error("[Crow] Failed to load conversations:",t),[]}}async loadHistory(e,t){try{const s=await fetch(`${this.apiUrl}/api/chat/conversations/${e}/history?product_id=${this.productId}&identity_token=${encodeURIComponent(t)}`);if(!s.ok)throw new Error(`HTTP error: ${s.status}`);const r=await s.json();return this.parseHistoryMessages(r.messages||[])}catch(s){return console.error("[Crow] Failed to load conversation history:",s),[]}}async loadAnonymousHistory(e){try{const t=await fetch(`${this.apiUrl}/api/chat/conversations/${e}/history/anonymous?product_id=${this.productId}`);if(!t.ok)throw new Error(`HTTP error: ${t.status}`);const s=await t.json();return this.parseHistoryMessages(s.messages||[])}catch(t){return console.error("[Crow] Failed to load anonymous conversation history:",t),[]}}parseHistoryMessages(e){return e.filter(t=>t.role!=="tool"&&!t.content.startsWith("[Client Tool Result:")).map((t,s)=>({id:`history-${s}`,content:this.parseContent(t.content),role:t.role==="assistant"?"assistant":"user",timestamp:new Date}))}parseContent(e){try{const t=JSON.parse(e);if(Array.isArray(t)){const s=t.find(r=>r.type==="text");return(s==null?void 0:s.text)||e}}catch{}if(e.includes("'type': 'text'")){const t=e.match(/\{'text':\s*'((?:[^'\\]|\\.)*)'\s*,\s*'type':\s*'text'/);if(t)return t[1].replace(/\\n/g,`
|
|
2
2
|
`).replace(/\\'/g,"'")}return e}}function M(o){if(o==="[DONE]")return{type:"done"};try{const e=JSON.parse(o);switch(e.type){case"verification_status":return{type:"verification_status",isVerified:e.is_verified===!0};case"conversation_id":return{type:"conversation_id",conversationId:e.conversation_id};case"thinking":return e.status==="complete"?{type:"thinking_complete"}:null;case"thinking_token":return{type:"thinking",content:e.content||""};case"content":return{type:"content",text:e.content||"",accumulated:""};case"citations":return{type:"citations",citations:e.citations};case"error":return{type:"error",message:e.message||"Unknown error"};case"tool_call_start":return{type:"tool_call_start",toolName:e.tool_name,arguments:e.arguments||{}};case"tool_call_complete":return{type:"tool_call_complete",toolName:e.tool_name,success:e.success};case"client_tool_call":return{type:"client_tool_call",toolName:e.tool_name,arguments:e.arguments||{}};case"workflow_started":return{type:"workflow_started",name:e.name,todos:e.todos};case"todo_updated":return{type:"workflow_todo_updated",todoId:e.id,status:e.status};case"workflow_ended":return{type:"workflow_ended"};case"workflow_complete_prompt":return{type:"workflow_complete_prompt"};default:return null}}catch{return console.error("[Crow] Failed to parse SSE data:",o),null}}function*b(o){const e=o.split(`
|
|
3
3
|
`);for(const t of e)t.startsWith("data: ")&&(yield t.slice(6).trim())}async function*v(o,e){var i;const t=(i=o.body)==null?void 0:i.getReader();if(!t)throw new Error("Response body is not readable");const s=new TextDecoder;let r="";try{for(;;){if(e!=null&&e.aborted){t.cancel();return}const{done:l,value:d}=await t.read();if(l)break;const h=s.decode(d);for(const u of b(h)){const c=M(u);if(c&&(c.type==="content"?(r+=c.text,yield{...c,accumulated:r}):yield c,c.type==="done"))return}}}finally{t.releaseLock()}}const g={refreshPage:async()=>{try{return window.location.reload(),{status:"success",data:{message:"Page refresh initiated"}}}catch(o){return{status:"error",error:String(o)}}},whatsOnScreen:async()=>{try{const o=new _.PageController({viewportExpansion:500}),e=await o.getBrowserState();return o.dispose(),{status:"success",data:{url:e.url,title:e.title,content:`${e.header}
|
|
4
4
|
|
package/dist/index.js
CHANGED
package/package.json
CHANGED
|
@@ -1,9 +0,0 @@
|
|
|
1
|
-
"use strict";async function waitFor(o){await new Promise(e=>setTimeout(e,o*1e3))}async function movePointerToElement(o){const e=o.getBoundingClientRect(),n=e.left+e.width/2,r=e.top+e.height/2;window.dispatchEvent(new CustomEvent("PageAgent::MovePointerTo",{detail:{x:n,y:r}})),await waitFor(.3)}function getElementByIndex(o,e){const n=o.get(e);if(!n)throw new Error(`No interactive element found at index ${e}`);const r=n.ref;if(!r)throw new Error(`Element at index ${e} does not have a reference`);if(!(r instanceof HTMLElement))throw new Error(`Element at index ${e} is not an HTMLElement`);return r}let lastClickedElement=null;function blurLastClickedElement(){lastClickedElement&&(lastClickedElement.blur(),lastClickedElement.dispatchEvent(new MouseEvent("mouseout",{bubbles:!0,cancelable:!0})),lastClickedElement=null)}async function clickElement(o){blurLastClickedElement(),lastClickedElement=o,await scrollIntoViewIfNeeded(o),await movePointerToElement(o),window.dispatchEvent(new CustomEvent("PageAgent::ClickPointer")),await waitFor(.1),o.dispatchEvent(new MouseEvent("mouseenter",{bubbles:!0,cancelable:!0})),o.dispatchEvent(new MouseEvent("mouseover",{bubbles:!0,cancelable:!0})),o.dispatchEvent(new MouseEvent("mousedown",{bubbles:!0,cancelable:!0})),o.focus(),o.dispatchEvent(new MouseEvent("mouseup",{bubbles:!0,cancelable:!0})),o.dispatchEvent(new MouseEvent("click",{bubbles:!0,cancelable:!0})),await waitFor(.1)}const nativeInputValueSetter=Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype,"value").set,nativeTextAreaValueSetter=Object.getOwnPropertyDescriptor(window.HTMLTextAreaElement.prototype,"value").set;async function inputTextElement(o,e){if(!(o instanceof HTMLInputElement||o instanceof HTMLTextAreaElement))throw new Error("Element is not an input or textarea");await clickElement(o),o instanceof HTMLTextAreaElement?nativeTextAreaValueSetter.call(o,e):nativeInputValueSetter.call(o,e);const n=new Event("input",{bubbles:!0});o.dispatchEvent(n),await waitFor(.1),blurLastClickedElement()}async function selectOptionElement(o,e){if(!(o instanceof HTMLSelectElement))throw new Error("Element is not a select element");const r=Array.from(o.options).find(d=>{var h;return((h=d.textContent)==null?void 0:h.trim())===e.trim()});if(!r)throw new Error(`Option with text "${e}" not found in select element`);o.value=r.value,o.dispatchEvent(new Event("change",{bubbles:!0})),await waitFor(.1)}async function scrollIntoViewIfNeeded(o){const e=o;e.scrollIntoViewIfNeeded?e.scrollIntoViewIfNeeded():e.scrollIntoView({behavior:"auto",block:"center",inline:"nearest"})}async function scrollVertically(o,e,n){if(n){const l=n;console.log("[SCROLL DEBUG] Starting direct container scroll for element:",l.tagName);let f=l,v=!1,m=null,c=0,g=0;const C=e;for(;f&&g<10;){const B=window.getComputedStyle(f),D=/(auto|scroll|overlay)/.test(B.overflowY),S=f.scrollHeight>f.clientHeight;if(console.log("[SCROLL DEBUG] Checking element:",f.tagName,"hasScrollableY:",D,"canScrollVertically:",S,"scrollHeight:",f.scrollHeight,"clientHeight:",f.clientHeight),D&&S){const R=f.scrollTop,U=f.scrollHeight-f.clientHeight;let k=C/3;k>0?k=Math.min(k,U-R):k=Math.max(k,-R),f.scrollTop=R+k;const V=f.scrollTop,$=V-R;if(console.log("[SCROLL DEBUG] Scroll attempt:",f.tagName,"before:",R,"after:",V,"delta:",$),Math.abs($)>.5){v=!0,m=f,c=$,console.log("[SCROLL DEBUG] Successfully scrolled container:",f.tagName,"delta:",$);break}}if(f===document.body||f===document.documentElement)break;f=f.parentElement,g++}return v?`Scrolled container (${m==null?void 0:m.tagName}) by ${c}px`:`No scrollable container found for element (${l.tagName})`}const r=e,d=l=>l.clientHeight>=window.innerHeight*.5,h=l=>l&&/(auto|scroll|overlay)/.test(getComputedStyle(l).overflowY)&&l.scrollHeight>l.clientHeight&&d(l);let s=document.activeElement;for(;s&&!h(s)&&s!==document.body;)s=s.parentElement;if(s=h(s)?s:Array.from(document.querySelectorAll("*")).find(h)||document.scrollingElement||document.documentElement,s===document.scrollingElement||s===document.documentElement||s===document.body){const l=window.scrollY,f=document.documentElement.scrollHeight-window.innerHeight;window.scrollBy(0,r);const v=window.scrollY,m=v-l;if(Math.abs(m)<1)return r>0?"⚠️ Already at the bottom of the page, cannot scroll down further.":"⚠️ Already at the top of the page, cannot scroll up further.";const c=r>0&&v>=f-1,g=r<0&&v<=1;return c?`✅ Scrolled page by ${m}px. Reached the bottom of the page.`:g?`✅ Scrolled page by ${m}px. Reached the top of the page.`:`✅ Scrolled page by ${m}px.`}else{const l=s.scrollTop,f=s.scrollHeight-s.clientHeight;s.scrollBy({top:r,behavior:"smooth"}),await waitFor(.1);const v=s.scrollTop,m=v-l;if(Math.abs(m)<1)return r>0?`⚠️ Already at the bottom of container (${s.tagName}), cannot scroll down further.`:`⚠️ Already at the top of container (${s.tagName}), cannot scroll up further.`;const c=r>0&&v>=f-1,g=r<0&&v<=1;return c?`✅ Scrolled container (${s.tagName}) by ${m}px. Reached the bottom.`:g?`✅ Scrolled container (${s.tagName}) by ${m}px. Reached the top.`:`✅ Scrolled container (${s.tagName}) by ${m}px.`}}async function scrollHorizontally(o,e,n){if(n){const l=n;console.log("[SCROLL DEBUG] Starting direct container scroll for element:",l.tagName);let f=l,v=!1,m=null,c=0,g=0;const C=o?e:-e;for(;f&&g<10;){const B=window.getComputedStyle(f),D=/(auto|scroll|overlay)/.test(B.overflowX),S=f.scrollWidth>f.clientWidth;if(console.log("[SCROLL DEBUG] Checking element:",f.tagName,"hasScrollableX:",D,"canScrollHorizontally:",S,"scrollWidth:",f.scrollWidth,"clientWidth:",f.clientWidth),D&&S){const R=f.scrollLeft,U=f.scrollWidth-f.clientWidth;let k=C/3;k>0?k=Math.min(k,U-R):k=Math.max(k,-R),f.scrollLeft=R+k;const V=f.scrollLeft,$=V-R;if(console.log("[SCROLL DEBUG] Scroll attempt:",f.tagName,"before:",R,"after:",V,"delta:",$),Math.abs($)>.5){v=!0,m=f,c=$,console.log("[SCROLL DEBUG] Successfully scrolled container:",f.tagName,"delta:",$);break}}if(f===document.body||f===document.documentElement)break;f=f.parentElement,g++}return v?`Scrolled container (${m==null?void 0:m.tagName}) horizontally by ${c}px`:`No horizontally scrollable container found for element (${l.tagName})`}const r=o?e:-e,d=l=>l.clientWidth>=window.innerWidth*.5,h=l=>l&&/(auto|scroll|overlay)/.test(getComputedStyle(l).overflowX)&&l.scrollWidth>l.clientWidth&&d(l);let s=document.activeElement;for(;s&&!h(s)&&s!==document.body;)s=s.parentElement;if(s=h(s)?s:Array.from(document.querySelectorAll("*")).find(h)||document.scrollingElement||document.documentElement,s===document.scrollingElement||s===document.documentElement||s===document.body){const l=window.scrollX,f=document.documentElement.scrollWidth-window.innerWidth;window.scrollBy(r,0);const v=window.scrollX,m=v-l;if(Math.abs(m)<1)return r>0?"⚠️ Already at the right edge of the page, cannot scroll right further.":"⚠️ Already at the left edge of the page, cannot scroll left further.";const c=r>0&&v>=f-1,g=r<0&&v<=1;return c?`✅ Scrolled page by ${m}px. Reached the right edge of the page.`:g?`✅ Scrolled page by ${m}px. Reached the left edge of the page.`:`✅ Scrolled page horizontally by ${m}px.`}else{const l=s.scrollLeft,f=s.scrollWidth-s.clientWidth;s.scrollBy({left:r,behavior:"smooth"}),await waitFor(.1);const v=s.scrollLeft,m=v-l;if(Math.abs(m)<1)return r>0?`⚠️ Already at the right edge of container (${s.tagName}), cannot scroll right further.`:`⚠️ Already at the left edge of container (${s.tagName}), cannot scroll left further.`;const c=r>0&&v>=f-1,g=r<0&&v<=1;return c?`✅ Scrolled container (${s.tagName}) by ${m}px. Reached the right edge.`:g?`✅ Scrolled container (${s.tagName}) by ${m}px. Reached the left edge.`:`✅ Scrolled container (${s.tagName}) horizontally by ${m}px.`}}const VIEWPORT_EXPANSION=-1,domTree=(o={doHighlightElements:!0,focusHighlightIndex:-1,viewportExpansion:0,debugMode:!1,interactiveBlacklist:[],interactiveWhitelist:[],highlightOpacity:.1,highlightLabelOpacity:.5})=>{const{interactiveBlacklist:e,interactiveWhitelist:n,highlightOpacity:r,highlightLabelOpacity:d}=o,{doHighlightElements:h,focusHighlightIndex:s,viewportExpansion:l,debugMode:f}=o;let v=0;const m=new WeakMap;function c(t,i){!t||t.nodeType!==Node.ELEMENT_NODE||m.set(t,{...m.get(t),...i})}const g={boundingRects:new WeakMap,clientRects:new WeakMap,computedStyles:new WeakMap,clearCache:()=>{g.boundingRects=new WeakMap,g.clientRects=new WeakMap,g.computedStyles=new WeakMap}};function C(t){if(!t)return null;if(g.boundingRects.has(t))return g.boundingRects.get(t);const i=t.getBoundingClientRect();return i&&g.boundingRects.set(t,i),i}function B(t){if(!t)return null;if(g.computedStyles.has(t))return g.computedStyles.get(t);const i=window.getComputedStyle(t);return i&&g.computedStyles.set(t,i),i}function D(t){if(!t)return null;if(g.clientRects.has(t))return g.clientRects.get(t);const i=t.getClientRects();return i&&g.clientRects.set(t,i),i}const S={},R={current:0},U="playwright-highlight-container";function k(t,i,w=null){if(!t)return i;const u=[];let a=null,x=20,E=16,H=null;try{let b=document.getElementById(U);b||(b=document.createElement("div"),b.id=U,b.style.position="fixed",b.style.pointerEvents="none",b.style.top="0",b.style.left="0",b.style.width="100%",b.style.height="100%",b.style.zIndex="2147483640",b.style.backgroundColor="transparent",document.body.appendChild(b));const P=t.getClientRects();if(!P||P.length===0)return i;const O=["#FF0000","#00FF00","#0000FF","#FFA500","#800080","#008080","#FF69B4","#4B0082","#FF4500","#2E8B57","#DC143C","#4682B4"],p=i%O.length;let y=O[p];const I=y+Math.floor(r*255).toString(16).padStart(2,"0");y=y+Math.floor(d*255).toString(16).padStart(2,"0");let L={x:0,y:0};if(w){const N=w.getBoundingClientRect();L.x=N.left,L.y=N.top}const j=document.createDocumentFragment();for(const N of P){if(N.width===0||N.height===0)continue;const M=document.createElement("div");M.style.position="fixed",M.style.border=`2px solid ${y}`,M.style.backgroundColor=I,M.style.pointerEvents="none",M.style.boxSizing="border-box";const T=N.top+L.y,W=N.left+L.x;M.style.top=`${T}px`,M.style.left=`${W}px`,M.style.width=`${N.width}px`,M.style.height=`${N.height}px`,j.appendChild(M),u.push({element:M,initialRect:N})}const G=P[0];if(d>0){a=document.createElement("div"),a.className="playwright-highlight-label",a.style.position="fixed",a.style.background=y,a.style.color="white",a.style.padding="1px 4px",a.style.borderRadius="4px",a.style.fontSize=`${Math.min(12,Math.max(8,G.height/2))}px`,a.textContent=i.toString(),x=a.offsetWidth>0?a.offsetWidth:x,E=a.offsetHeight>0?a.offsetHeight:E;const N=G.top+L.y,M=G.left+L.x;let T=N+2,W=M+G.width-x-2;(G.width<x+4||G.height<E+4)&&(T=N-E-2,W=M+G.width-x,W<L.x&&(W=M)),T=Math.max(0,Math.min(T,window.innerHeight-E)),W=Math.max(0,Math.min(W,window.innerWidth-x)),a.style.top=`${T}px`,a.style.left=`${W}px`,j.appendChild(a)}const q=((N,M)=>{let T=0;return(...W)=>{const X=performance.now();if(!(X-T<M))return T=X,N(...W)}})(()=>{const N=t.getClientRects();let M={x:0,y:0};if(w){const T=w.getBoundingClientRect();M.x=T.left,M.y=T.top}if(u.forEach((T,W)=>{if(W<N.length){const X=N[W],tt=X.top+M.y,Q=X.left+M.x;T.element.style.top=`${tt}px`,T.element.style.left=`${Q}px`,T.element.style.width=`${X.width}px`,T.element.style.height=`${X.height}px`,T.element.style.display=X.width===0||X.height===0?"none":"block"}else T.element.style.display="none"}),N.length<u.length)for(let T=N.length;T<u.length;T++)u[T].element.style.display="none";if(a&&N.length>0){const T=N[0],W=T.top+M.y,X=T.left+M.x;let tt=W+2,Q=X+T.width-x-2;(T.width<x+4||T.height<E+4)&&(tt=W-E-2,Q=X+T.width-x,Q<M.x&&(Q=X)),tt=Math.max(0,Math.min(tt,window.innerHeight-E)),Q=Math.max(0,Math.min(Q,window.innerWidth-x)),a.style.top=`${tt}px`,a.style.left=`${Q}px`,a.style.display="block"}else a&&(a.style.display="none")},16);return window.addEventListener("scroll",q,!0),window.addEventListener("resize",q),H=()=>{window.removeEventListener("scroll",q,!0),window.removeEventListener("resize",q),u.forEach(N=>N.element.remove()),a&&a.remove()},b.appendChild(j),i+1}finally{H&&(window._highlightCleanupFunctions=window._highlightCleanupFunctions||[]).push(H)}}function V(t){if(!t||t.nodeType!==Node.ELEMENT_NODE)return null;const i=B(t);if(!i)return null;const w=i.display;if(w==="inline"||w==="inline-block")return null;const u=i.overflowX,a=i.overflowY,x=u==="auto"||u==="scroll",E=a==="auto"||a==="scroll";if(!x&&!E)return null;const H=t.scrollWidth-t.clientWidth,b=t.scrollHeight-t.clientHeight,P=4;if(H<P&&b<P||!E&&H<P||!x&&b<P)return null;const O=t.scrollTop,p=t.scrollLeft,y=t.scrollWidth-t.clientWidth-t.scrollLeft,I=t.scrollHeight-t.clientHeight-t.scrollTop,L={top:O,right:y,bottom:I,left:p};return c(t,{scrollable:!0,scrollData:L}),L}function $(t){try{if(l===-1){const E=t.parentElement;if(!E)return!1;try{return E.checkVisibility({checkOpacity:!0,checkVisibilityCSS:!0})}catch{const b=window.getComputedStyle(E);return b.display!=="none"&&b.visibility!=="hidden"&&b.opacity!=="0"}}const i=document.createRange();i.selectNodeContents(t);const w=i.getClientRects();if(!w||w.length===0)return!1;let u=!1,a=!1;for(const E of w)if(E.width>0&&E.height>0&&(u=!0,!(E.bottom<-l||E.top>window.innerHeight+l||E.right<-l||E.left>window.innerWidth+l))){a=!0;break}if(!u||!a)return!1;const x=t.parentElement;if(!x)return!1;try{return x.checkVisibility({checkOpacity:!0,checkVisibilityCSS:!0})}catch{const H=window.getComputedStyle(x);return H.display!=="none"&&H.visibility!=="hidden"&&H.opacity!=="0"}}catch(i){return console.warn("Error checking text node visibility:",i),!1}}function _(t){if(!t||!t.tagName)return!1;const i=new Set(["body","div","main","article","section","nav","header","footer"]),w=t.tagName.toLowerCase();return i.has(w)?!0:!new Set(["svg","script","style","link","meta","noscript","template"]).has(w)}function F(t){const i=B(t);return t.offsetWidth>0&&t.offsetHeight>0&&(i==null?void 0:i.visibility)!=="hidden"&&(i==null?void 0:i.display)!=="none"}function A(t){var I,L;if(!t||t.nodeType!==Node.ELEMENT_NODE||e.includes(t))return!1;if(n.includes(t))return!0;const i=t.tagName.toLowerCase(),w=B(t),u=new Set(["pointer","move","text","grab","grabbing","cell","copy","alias","all-scroll","col-resize","context-menu","crosshair","e-resize","ew-resize","help","n-resize","ne-resize","nesw-resize","ns-resize","nw-resize","nwse-resize","row-resize","s-resize","se-resize","sw-resize","vertical-text","w-resize","zoom-in","zoom-out"]),a=new Set(["not-allowed","no-drop","wait","progress","initial","inherit"]);function x(j){return j.tagName.toLowerCase()==="html"?!1:!!(w!=null&&w.cursor&&u.has(w.cursor))}if(x(t))return!0;const H=new Set(["a","button","input","select","textarea","details","summary","label","option","optgroup","fieldset","legend"]),b=new Set(["disabled","readonly"]);if(H.has(i)){if(w!=null&&w.cursor&&a.has(w.cursor))return!1;for(const j of b)if(t.hasAttribute(j)||t.getAttribute(j)==="true"||t.getAttribute(j)==="")return!1;return!(t.disabled||t.readOnly||t.inert)}const P=t.getAttribute("role"),O=t.getAttribute("aria-role");if(t.getAttribute("contenteditable")==="true"||t.isContentEditable||t.classList&&(t.classList.contains("button")||t.classList.contains("dropdown-toggle")||t.getAttribute("data-index")||t.getAttribute("data-toggle")==="dropdown"||t.getAttribute("aria-haspopup")==="true"))return!0;const p=new Set(["button","menu","menubar","menuitem","menuitemradio","menuitemcheckbox","radio","checkbox","tab","switch","slider","spinbutton","combobox","searchbox","textbox","listbox","option","scrollbar"]);if(H.has(i)||P&&p.has(P)||O&&p.has(O))return!0;try{if(typeof getEventListeners=="function"){const J=getEventListeners(t),nt=["click","mousedown","mouseup","dblclick"];for(const q of nt)if(J[q]&&J[q].length>0)return!0}const j=((L=(I=t==null?void 0:t.ownerDocument)==null?void 0:I.defaultView)==null?void 0:L.getEventListenersForNode)||window.getEventListenersForNode;if(typeof j=="function"){const J=j(t),nt=["click","mousedown","mouseup","keydown","keyup","submit","change","input","focus","blur"];for(const q of nt)for(const N of J)if(N.type===q)return!0}const G=["onclick","onmousedown","onmouseup","ondblclick"];for(const J of G)if(t.hasAttribute(J)||typeof t[J]=="function")return!0}catch{}return!!V(t)}function ot(t){if(l===-1)return!0;const i=D(t);if(!i||i.length===0)return!1;let w=!1;for(const b of i)if(b.width>0&&b.height>0&&!(b.bottom<-l||b.top>window.innerHeight+l||b.right<-l||b.left>window.innerWidth+l)){w=!0;break}if(!w)return!1;if(t.ownerDocument!==window.document)return!0;let a=Array.from(i).find(b=>b.width>0&&b.height>0);if(!a)return!1;const x=t.getRootNode();if(x instanceof ShadowRoot){const b=a.left+a.width/2,P=a.top+a.height/2;try{const O=x.elementFromPoint(b,P);if(!O)return!1;let p=O;for(;p&&p!==x;){if(p===t)return!0;p=p.parentElement}return!1}catch{return!0}}const E=5;return[{x:a.left+a.width/2,y:a.top+a.height/2},{x:a.left+E,y:a.top+E},{x:a.right-E,y:a.bottom-E}].some(({x:b,y:P})=>{try{const O=document.elementFromPoint(b,P);if(!O)return!1;let p=O;for(;p&&p!==document.documentElement;){if(p===t)return!0;p=p.parentElement}return!1}catch{return!0}})}function rt(t,i){if(i===-1)return!0;const w=t.getClientRects();if(!w||w.length===0){const u=C(t);return!u||u.width===0||u.height===0?!1:!(u.bottom<-i||u.top>window.innerHeight+i||u.right<-i||u.left>window.innerWidth+i)}for(const u of w)if(!(u.width===0||u.height===0)&&!(u.bottom<-i||u.top>window.innerHeight+i||u.right<-i||u.left>window.innerWidth+i))return!0;return!1}function z(t){if(!t||t.nodeType!==Node.ELEMENT_NODE)return!1;const i=t.tagName.toLowerCase();return new Set(["a","button","input","select","textarea","details","summary","label"]).has(i)?!0:t.hasAttribute("onclick")||t.hasAttribute("role")||t.hasAttribute("tabindex")||t.hasAttribute("aria-")||t.hasAttribute("data-action")||t.getAttribute("contenteditable")==="true"}const Y=new Set(["a","button","input","select","textarea","summary","details","label","option"]),K=new Set(["button","link","menuitem","menuitemradio","menuitemcheckbox","radio","checkbox","tab","switch","slider","spinbutton","combobox","searchbox","textbox","listbox","option","scrollbar"]);function et(t){if(!t||t.nodeType!==Node.ELEMENT_NODE||!F(t))return!1;const i=t.hasAttribute("role")||t.hasAttribute("tabindex")||t.hasAttribute("onclick")||typeof t.onclick=="function",w=/\b(btn|clickable|menu|item|entry|link)\b/i.test(t.className||""),u=!!t.closest('button,a,[role="button"],.menu,.dropdown,.list,.toolbar'),a=[...t.children].some(F),x=t.parentElement&&t.parentElement.isSameNode(document.body);return(A(t)||i||w)&&a&&u&&!x}function it(t){var u,a;if(!t||t.nodeType!==Node.ELEMENT_NODE)return!1;const i=t.tagName.toLowerCase(),w=t.getAttribute("role");if(i==="iframe"||Y.has(i)||w&&K.has(w)||t.isContentEditable||t.getAttribute("contenteditable")==="true"||t.hasAttribute("data-testid")||t.hasAttribute("data-cy")||t.hasAttribute("data-test")||t.hasAttribute("onclick")||typeof t.onclick=="function")return!0;try{const x=((a=(u=t==null?void 0:t.ownerDocument)==null?void 0:u.defaultView)==null?void 0:a.getEventListenersForNode)||window.getEventListenersForNode;if(typeof x=="function"){const H=x(t),b=["click","mousedown","mouseup","keydown","keyup","submit","change","input","focus","blur"];for(const P of b)for(const O of H)if(O.type===P)return!0}if(["onmousedown","onmouseup","onkeydown","onkeyup","onsubmit","onchange","oninput","onfocus","onblur"].some(H=>t.hasAttribute(H)))return!0}catch{}return!!et(t)}function st(t,i,w,u){if(!t.isInteractive)return!1;let a=!1;return u?it(i)?a=!0:a=!1:a=!0,a&&(t.isInViewport=rt(i,l),(t.isInViewport||l===-1)&&(t.highlightIndex=v++,h))?(s>=0?s===t.highlightIndex&&k(i,t.highlightIndex,w):k(i,t.highlightIndex,w),!0):!1}function Z(t,i=null,w=!1){var E,H,b,P,O;if(!t||t.id===U||t.nodeType!==Node.ELEMENT_NODE&&t.nodeType!==Node.TEXT_NODE||!t||t.id===U||((E=t.dataset)==null?void 0:E.browserUseIgnore)==="true"||t.getAttribute&&t.getAttribute("aria-hidden")==="true")return null;if(t===document.body){const p={tagName:"body",attributes:{},xpath:"/body",children:[]};for(const I of t.childNodes){const L=Z(I,i,!1);L&&p.children.push(L)}const y=`${R.current++}`;return S[y]=p,y}if(t.nodeType!==Node.ELEMENT_NODE&&t.nodeType!==Node.TEXT_NODE)return null;if(t.nodeType===Node.TEXT_NODE){const p=(H=t.textContent)==null?void 0:H.trim();if(!p)return null;const y=t.parentElement;if(!y||y.tagName.toLowerCase()==="script")return null;const I=`${R.current++}`;return S[I]={type:"TEXT_NODE",text:p,isVisible:$(t)},I}if(t.nodeType===Node.ELEMENT_NODE&&!_(t))return null;if(l!==-1&&!t.shadowRoot){const p=C(t),y=B(t),I=y&&(y.position==="fixed"||y.position==="sticky"),L=t.offsetWidth>0||t.offsetHeight>0;if(!p||!I&&!L&&(p.bottom<-l||p.top>window.innerHeight+l||p.right<-l||p.left>window.innerWidth+l))return null}const u={tagName:t.tagName.toLowerCase(),attributes:{},children:[]};if(z(t)||t.tagName.toLowerCase()==="iframe"||t.tagName.toLowerCase()==="body"){const p=((b=t.getAttributeNames)==null?void 0:b.call(t))||[];for(const y of p){const I=t.getAttribute(y);u.attributes[y]=I}t.tagName.toLowerCase()==="input"&&(t.type==="checkbox"||t.type==="radio")&&(u.attributes.checked=t.checked?"true":"false")}let a=!1;if(t.nodeType===Node.ELEMENT_NODE&&(u.isVisible=F(t),u.isVisible)){u.isTopElement=ot(t);const p=t.getAttribute("role"),y=p==="menu"||p==="menubar"||p==="listbox";(u.isTopElement||y)&&(u.isInteractive=A(t),a=st(u,t,i,w),u.ref=t)}if(t.tagName){const p=t.tagName.toLowerCase();if(p==="iframe")try{const y=t.contentDocument||((P=t.contentWindow)==null?void 0:P.document);if(y)for(const I of y.childNodes){const L=Z(I,t,!1);L&&u.children.push(L)}}catch(y){console.warn("Unable to access iframe:",y)}else if(t.isContentEditable||t.getAttribute("contenteditable")==="true"||t.id==="tinymce"||t.classList.contains("mce-content-body")||p==="body"&&((O=t.getAttribute("data-id"))!=null&&O.startsWith("mce_")))for(const y of t.childNodes){const I=Z(y,i,a);I&&u.children.push(I)}else{if(t.shadowRoot){u.shadowRoot=!0;for(const y of t.shadowRoot.childNodes){const I=Z(y,i,a);I&&u.children.push(I)}}for(const y of t.childNodes){const L=Z(y,i,a||w);L&&u.children.push(L)}}}if(u.tagName==="a"&&u.children.length===0&&!u.attributes.href){const p=C(t);if(!(p&&p.width>0&&p.height>0||t.offsetWidth>0||t.offsetHeight>0))return null}u.extra=m.get(t)||null;const x=`${R.current++}`;return S[x]=u,x}const lt=Z(document.body);return g.clearCache(),{rootId:lt,map:S}},newElementsCache=new WeakMap;function getFlatTree(o){const e=[];for(const h of o.interactiveBlacklist||[])typeof h=="function"?e.push(h()):e.push(h);const n=[];for(const h of o.interactiveWhitelist||[])typeof h=="function"?n.push(h()):n.push(h);const r=domTree({doHighlightElements:!0,debugMode:!0,focusHighlightIndex:-1,viewportExpansion:VIEWPORT_EXPANSION,interactiveBlacklist:e,interactiveWhitelist:n,highlightOpacity:o.highlightOpacity??0,highlightLabelOpacity:o.highlightLabelOpacity??.1}),d=window.location.href;for(const h in r.map){const s=r.map[h];if(s.isInteractive&&s.ref){const l=s.ref;newElementsCache.has(l)||(newElementsCache.set(l,d),s.isNew=!0)}}return r}function flatTreeToString(o,e){const n=["title","type","checked","name","role","value","placeholder","data-date-format","alt","aria-label","aria-expanded","data-state","aria-checked","id","for","target","aria-haspopup","aria-controls","aria-owns"],r=[...e||[],...n],d=(c,g)=>c.length>g?c.substring(0,g)+"...":c,h=c=>{const g=o.map[c];if(!g)return null;if(g.type==="TEXT_NODE"){const C=g;return{type:"text",text:C.text,isVisible:C.isVisible,parent:null,children:[]}}else{const C=g,B=[];if(C.children)for(const D of C.children){const S=h(D);S&&(S.parent=null,B.push(S))}return{type:"element",tagName:C.tagName,attributes:C.attributes??{},isVisible:C.isVisible??!1,isInteractive:C.isInteractive??!1,isTopElement:C.isTopElement??!1,isNew:C.isNew??!1,highlightIndex:C.highlightIndex,parent:null,children:B,extra:C.extra??{}}}},s=(c,g=null)=>{c.parent=g;for(const C of c.children)s(C,c)},l=h(o.rootId);if(!l)return"";s(l);const f=c=>{let g=c.parent;for(;g;){if(g.type==="element"&&g.highlightIndex!==void 0)return!0;g=g.parent}return!1},v=(c,g,C)=>{var S,R,U,k;let B=g;const D=" ".repeat(g);if(c.type==="element"){if(c.highlightIndex!==void 0){B+=1;const V=getAllTextTillNextClickableElement(c);let $="";if(r.length>0&&c.attributes){const A={};for(const z of r){const Y=c.attributes[z];Y&&Y.trim()!==""&&(A[z]=Y.trim())}const ot=r.filter(z=>z in A);if(ot.length>1){const z=new Set,Y={};for(const K of ot){const et=A[K];et.length>5&&(et in Y?z.add(K):Y[et]=K)}for(const K of z)delete A[K]}A.role===c.tagName&&delete A.role;const rt=["aria-label","placeholder","title"];for(const z of rt)A[z]&&A[z].toLowerCase().trim()===V.toLowerCase().trim()&&delete A[z];Object.keys(A).length>0&&($=Object.entries(A).map(([z,Y])=>`${z}=${d(Y,20)}`).join(" "))}const _=c.isNew?`*[${c.highlightIndex}]`:`[${c.highlightIndex}]`;let F=`${D}${_}<${c.tagName??""}`;if($&&(F+=` ${$}`),c.extra&&c.extra.scrollable){let A="";(S=c.extra.scrollData)!=null&&S.left&&(A+=`left=${c.extra.scrollData.left}, `),(R=c.extra.scrollData)!=null&&R.top&&(A+=`top=${c.extra.scrollData.top}, `),(U=c.extra.scrollData)!=null&&U.right&&(A+=`right=${c.extra.scrollData.right}, `),(k=c.extra.scrollData)!=null&&k.bottom&&(A+=`bottom=${c.extra.scrollData.bottom}`),F+=` data-scrollable="${A}"`}if(V){const A=V.trim();$||(F+=" "),F+=`>${A}`}else $||(F+=" ");F+=" />",C.push(F)}for(const V of c.children)v(V,B,C)}else if(c.type==="text"){if(f(c))return;c.parent&&c.parent.type==="element"&&c.parent.isVisible&&c.parent.isTopElement&&C.push(`${D}${c.text??""}`)}},m=[];return v(l,0,m),m.join(`
|
|
2
|
-
`)}const getAllTextTillNextClickableElement=(o,e=-1)=>{const n=[],r=(d,h)=>{if(!(e!==-1&&h>e)&&!(d.type==="element"&&d!==o&&d.highlightIndex!==void 0)){if(d.type==="text"&&d.text)n.push(d.text);else if(d.type==="element")for(const s of d.children)r(s,h+1)}};return r(o,0),n.join(`
|
|
3
|
-
`).trim()};function getSelectorMap(o){const e=new Map,n=Object.keys(o.map);for(const r of n){const d=o.map[r];d.isInteractive&&typeof d.highlightIndex=="number"&&e.set(d.highlightIndex,d)}return e}function getElementTextMap(o){const e=o.split(`
|
|
4
|
-
`).map(r=>r.trim()).filter(r=>r.length>0),n=new Map;for(const r of e){const h=/^\[(\d+)\]<[^>]+>([^<]*)/.exec(r);if(h){const s=parseInt(h[1],10);n.set(s,r)}}return n}function cleanUpHighlights(){const o=window._highlightCleanupFunctions||[];for(const e of o)typeof e=="function"&&e();window._highlightCleanupFunctions=[]}window.addEventListener("popstate",()=>{cleanUpHighlights()});window.addEventListener("hashchange",()=>{cleanUpHighlights()});window.addEventListener("beforeunload",()=>{cleanUpHighlights()});const navigation=window.navigation;if(navigation&&typeof navigation.addEventListener=="function")navigation.addEventListener("navigate",()=>{cleanUpHighlights()});else{let o=window.location.href;setInterval(()=>{window.location.href!==o&&(o=window.location.href,cleanUpHighlights())},500)}function getPageInfo(){const o=window.innerWidth,e=window.innerHeight,n=Math.max(document.documentElement.scrollWidth,document.body.scrollWidth||0),r=Math.max(document.documentElement.scrollHeight,document.body.scrollHeight||0),d=window.scrollX||window.pageXOffset||document.documentElement.scrollLeft||0,h=window.scrollY||window.pageYOffset||document.documentElement.scrollTop||0,s=Math.max(0,r-(window.innerHeight+h)),l=Math.max(0,n-(window.innerWidth+d));return{viewport_width:o,viewport_height:e,page_width:n,page_height:r,scroll_x:d,scroll_y:h,pixels_above:h,pixels_below:s,pages_above:e>0?h/e:0,pages_below:e>0?s/e:0,total_pages:e>0?r/e:0,current_page_position:h/Math.max(1,r-e),pixels_left:d,pixels_right:l}}function patchReact(o){const e=document.querySelectorAll('[data-reactroot], [data-reactid], [data-react-checksum], #root, #app, [id^="root-"], [id^="app-"], #adex-wrapper, #adex-root');for(const n of e)n.setAttribute("data-page-agent-not-interactive","true")}class PageController extends EventTarget{constructor(o={}){super(),this.flatTree=null,this.selectorMap=new Map,this.elementTextMap=new Map,this.simplifiedHTML="<EMPTY>",this.lastTimeUpdate=0,this.isIndexed=!1,this.mask=null,this.maskReady=null,this.config=o,patchReact(),o.enableMask&&this.initMask()}initMask(){this.maskReady===null&&(this.maskReady=(async()=>{const{SimulatorMask:o}=await Promise.resolve().then(()=>require("./SimulatorMask-jCkPs2Tt.cjs"));this.mask=new o})())}async getCurrentUrl(){return window.location.href}async getLastUpdateTime(){return this.lastTimeUpdate}async getBrowserState(){const o=window.location.href,e=document.title,n=getPageInfo(),r=this.config.viewportExpansion??VIEWPORT_EXPANSION;await this.updateTree();const d=this.simplifiedHTML,h=`Current Page: [${e}](${o})`,s=`Page info: ${n.viewport_width}x${n.viewport_height}px viewport, ${n.page_width}x${n.page_height}px total page size, ${n.pages_above.toFixed(1)} pages above, ${n.pages_below.toFixed(1)} pages below, ${n.total_pages.toFixed(1)} total pages, at ${(n.current_page_position*100).toFixed(0)}% of page`,l=r===-1?"Interactive elements from top layer of the current page (full page):":"Interactive elements from top layer of the current page inside the viewport:",v=n.pixels_above>4&&r!==-1?`... ${n.pixels_above} pixels above (${n.pages_above.toFixed(1)} pages) - scroll to see more ...`:"[Start of page]",m=`${h}
|
|
5
|
-
${s}
|
|
6
|
-
|
|
7
|
-
${l}
|
|
8
|
-
|
|
9
|
-
${v}`,g=n.pixels_below>4&&r!==-1?`... ${n.pixels_below} pixels below (${n.pages_below.toFixed(1)} pages) - scroll to see more ...`:"[End of page]";return{url:o,title:e,header:m,content:d,footer:g}}async updateTree(){this.dispatchEvent(new Event("beforeUpdate")),this.lastTimeUpdate=Date.now(),this.mask&&(this.mask.wrapper.style.pointerEvents="none"),cleanUpHighlights();const o=[...this.config.interactiveBlacklist||[],...document.querySelectorAll("[data-page-agent-not-interactive]").values()];return this.flatTree=getFlatTree({...this.config,interactiveBlacklist:o}),this.simplifiedHTML=flatTreeToString(this.flatTree,this.config.include_attributes),this.selectorMap.clear(),this.selectorMap=getSelectorMap(this.flatTree),this.elementTextMap.clear(),this.elementTextMap=getElementTextMap(this.simplifiedHTML),this.isIndexed=!0,this.mask&&(this.mask.wrapper.style.pointerEvents="auto"),this.dispatchEvent(new Event("afterUpdate")),this.simplifiedHTML}async cleanUpHighlights(){cleanUpHighlights()}assertIndexed(){if(!this.isIndexed)throw new Error("DOM tree not indexed yet. Can not perform actions on elements.")}async clickElement(o){try{this.assertIndexed();const e=getElementByIndex(this.selectorMap,o),n=this.elementTextMap.get(o);return await clickElement(e),e instanceof HTMLAnchorElement&&e.target==="_blank"?{success:!0,message:`✅ Clicked element (${n??o}). ⚠️ Link opens in a new tab. You are not capable of reading new tabs.`}:{success:!0,message:`✅ Clicked element (${n??o}).`}}catch(e){return{success:!1,message:`❌ Failed to click element: ${e}`}}}async inputText(o,e){try{this.assertIndexed();const n=getElementByIndex(this.selectorMap,o),r=this.elementTextMap.get(o);return await inputTextElement(n,e),{success:!0,message:`✅ Input text (${e}) into element (${r??o}).`}}catch(n){return{success:!1,message:`❌ Failed to input text: ${n}`}}}async selectOption(o,e){try{this.assertIndexed();const n=getElementByIndex(this.selectorMap,o),r=this.elementTextMap.get(o);return await selectOptionElement(n,e),{success:!0,message:`✅ Selected option (${e}) in element (${r??o}).`}}catch(n){return{success:!1,message:`❌ Failed to select option: ${n}`}}}async scroll(o){try{const{down:e,numPages:n,pixels:r,index:d}=o;this.assertIndexed();const h=r??n*(e?1:-1)*window.innerHeight,s=d!==void 0?getElementByIndex(this.selectorMap,d):null;return{success:!0,message:await scrollVertically(e,h,s)}}catch(e){return{success:!1,message:`❌ Failed to scroll: ${e}`}}}async scrollHorizontally(o){try{const{right:e,pixels:n,index:r}=o;this.assertIndexed();const d=n*(e?1:-1),h=r!==void 0?getElementByIndex(this.selectorMap,r):null;return{success:!0,message:await scrollHorizontally(e,d,h)}}catch(e){return{success:!1,message:`❌ Failed to scroll horizontally: ${e}`}}}async executeJavascript(script){try{const asyncFunction=eval(`(async () => { ${script} })`),result=await asyncFunction();return{success:!0,message:`✅ Executed JavaScript. Result: ${result}`}}catch(o){return{success:!1,message:`❌ Error executing JavaScript: ${o}`}}}async showMask(){var o;await this.maskReady,(o=this.mask)==null||o.show()}async hideMask(){var o;await this.maskReady,(o=this.mask)==null||o.hide()}dispose(){var o;cleanUpHighlights(),this.flatTree=null,this.selectorMap.clear(),this.elementTextMap.clear(),this.simplifiedHTML="<EMPTY>",this.isIndexed=!1,(o=this.mask)==null||o.dispose(),this.mask=null}}const PageController$1=Object.freeze(Object.defineProperty({__proto__:null,PageController},Symbol.toStringTag,{value:"Module"}));let injectedPageController=null,PageControllerModule=null;function setPageController(o){injectedPageController=o}async function getPageController(){if(injectedPageController)return injectedPageController;if(!PageControllerModule)try{PageControllerModule=await Promise.resolve().then(()=>PageController$1)}catch{throw new Error('PageController not available. Either import from "@usecrow/client/browser" or use the bundled version.')}return PageControllerModule.PageController}class CrowBrowserUse{constructor(e){this.pageController=null,this.sessionId=null,this.maxSteps=20,this.aborted=!1,this.config=e}async initPageController(){if(this.pageController)return this.pageController;try{const e=await getPageController();this.pageController=new e({enableMask:!0,viewportExpansion:500,highlightLabelOpacity:0,highlightOpacity:0}),await this.pageController.showMask();const n=this.pageController.mask;return n!=null&&n.wrapper&&(n.wrapper.style.pointerEvents="none"),console.log("[CrowBrowserUse] PageController initialized with non-blocking pointer"),this.pageController}catch(e){throw console.error("[CrowBrowserUse] Failed to initialize PageController:",e),new Error("Failed to initialize browser automation. Please import from @usecrow/client/browser.")}}async execute(e){var n,r,d,h,s,l,f,v,m,c,g,C,B,D;if(console.log("[CrowBrowserUse] Starting task:",e),this.config.onConfirmation&&!await this.config.onConfirmation(e))return console.log("[CrowBrowserUse] User declined browser automation"),(r=(n=this.config).onProgress)==null||r.call(n,-1,this.maxSteps),{status:"error",error:"User declined browser automation",data:{declined:!0}};try{const S=await this.initPageController(),R=await this.startSession(e);this.sessionId=R.session_id,this.maxSteps=R.max_steps,console.log("[CrowBrowserUse] Session started:",this.sessionId);let U=0,k;for(;U<this.maxSteps;){if(this.aborted)return console.log("[CrowBrowserUse] Task cancelled by user"),await this.cleanup(),(h=(d=this.config).onProgress)==null||h.call(d,-1,this.maxSteps),{status:"error",error:"Task cancelled by user"};U++;const V=await S.getBrowserState(),$=S.mask;$!=null&&$.wrapper&&($.wrapper.style.pointerEvents="none");const _=await this.processStep(V,k);if(_.needs_user_input&&_.question){if(console.log("[CrowBrowserUse] Asking user:",_.question),!this.config.onQuestion){k="User input not available - no callback provided",console.warn("[CrowBrowserUse] No onQuestion callback provided");continue}try{const F=await this.config.onQuestion(_.question);k=`User answered: ${F}`,console.log("[CrowBrowserUse] User answered:",F)}catch(F){if(k="User cancelled or failed to respond",console.log("[CrowBrowserUse] User cancelled or error:",F),this.aborted)return console.log("[CrowBrowserUse] Aborted after user cancelled"),await this.cleanup(),(l=(s=this.config).onProgress)==null||l.call(s,-1,this.maxSteps),{status:"error",error:"Task cancelled by user"}}continue}if(_.done)return console.log("[CrowBrowserUse] Task completed:",_.message),await this.cleanup(),(v=(f=this.config).onProgress)==null||v.call(f,U,this.maxSteps),{status:_.success?"success":"error",data:{message:_.message,steps:U},error:_.success?void 0:_.message};if(_.error)return console.error("[CrowBrowserUse] Error:",_.error),await this.cleanup(),(c=(m=this.config).onProgress)==null||c.call(m,-1,this.maxSteps),{status:"error",error:_.error};_.action&&(k=await this.executeAction(S,_.action),console.log(`[CrowBrowserUse] Step ${U}:`,k)),_.reflection&&console.log("[CrowBrowserUse] Reflection:",_.reflection.next_goal)}return await this.cleanup(),(C=(g=this.config).onProgress)==null||C.call(g,-1,this.maxSteps),{status:"error",error:`Task incomplete after ${this.maxSteps} steps`}}catch(S){return console.error("[CrowBrowserUse] Error:",S),await this.cleanup(),(D=(B=this.config).onProgress)==null||D.call(B,-1,this.maxSteps),{status:"error",error:S instanceof Error?S.message:String(S)}}}async startSession(e){const n=await fetch(`${this.config.apiUrl}/api/browser-use/start`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({product_id:this.config.productId,task:e})});if(!n.ok){const r=await n.json().catch(()=>({detail:"Unknown error"}));throw new Error(r.detail||`Failed to start session: ${n.status}`)}return n.json()}async processStep(e,n){const r=await fetch(`${this.config.apiUrl}/api/browser-use/step`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({session_id:this.sessionId,product_id:this.config.productId,browser_state:e,action_result:n})});if(!r.ok){const d=await r.json().catch(()=>({detail:"Unknown error"}));throw new Error(d.detail||`Failed to process step: ${r.status}`)}return r.json()}async executeAction(e,n){const r=Object.keys(n)[0],d=n[r];try{switch(r){case"click_element_by_index":return(await e.clickElement(d.index)).message;case"input_text":return(await e.inputText(d.index,d.text)).message;case"select_dropdown_option":return(await e.selectOption(d.index,d.text)).message;case"scroll":return(await e.scroll({down:d.down,numPages:d.num_pages,pixels:d.pixels,index:d.index})).message;case"scroll_horizontally":return(await e.scrollHorizontally({right:d.right,pixels:d.pixels,index:d.index})).message;case"wait":{const h=d.seconds||1;return await new Promise(s=>setTimeout(s,h*1e3)),`Waited ${h} seconds`}case"done":return"Task completed";default:return`Unknown action: ${r}`}}catch(h){return`Action failed: ${h instanceof Error?h.message:String(h)}`}}async cleanup(){if(this.pageController){try{await this.pageController.hideMask(),await this.pageController.cleanUpHighlights(),this.pageController.dispose()}catch(e){console.warn("[CrowBrowserUse] Cleanup error:",e)}this.pageController=null}if(this.sessionId){try{await fetch(`${this.config.apiUrl}/api/browser-use/end`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({session_id:this.sessionId,product_id:this.config.productId})})}catch{}this.sessionId=null}}async stop(){this.aborted=!0,await this.cleanup()}}exports.CrowBrowserUse=CrowBrowserUse;exports.PageController=PageController;exports.setPageController=setPageController;
|