@usecrow/client 0.1.28 → 0.1.30
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.d.ts +7 -4
- package/dist/browser.js +26 -17
- package/dist/browserUse-B-b3zqW1.cjs +9 -0
- package/dist/browserUse-D5NUCzN4.js +1616 -0
- package/dist/index.cjs +7 -3
- package/dist/index.d.ts +5 -4
- package/dist/index.js +71 -48
- package/package.json +1 -1
- package/dist/PageController-72owMK9b.cjs +0 -9
- package/dist/PageController-BT9YJiz0.js +0 -1379
- package/dist/browserUse-CMYea2D_.cjs +0 -1
- package/dist/browserUse-CMq8wG4u.js +0 -259
package/dist/index.cjs
CHANGED
|
@@ -1,3 +1,7 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const
|
|
2
|
-
`).replace(/\\'/g,"'")}return e}}function M(
|
|
3
|
-
`);for(const t of e)t.startsWith("data: ")&&(yield t.slice(6).trim())}async function*
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const _=require("./browserUse-B-b3zqW1.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
|
+
`).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
|
+
`);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
|
+
|
|
5
|
+
${e.content}
|
|
6
|
+
|
|
7
|
+
${e.footer}`}}}catch(o){return console.error("[Crow] whatsOnScreen error:",o),{status:"error",error:String(o)}}}},I=Object.keys(g),E="https://api.usecrow.org",$="claude-sonnet-4-20250514";class L{constructor(e){this.context={},this.abortController=null,this.callbacks={},this._messages=[],this.messageListeners=new Set,this._isLoading=!1,this.loadingListeners=new Set,this.config={productId:e.productId,apiUrl:e.apiUrl||E,model:e.model||$},this.identity=new k,this.tools=new C,this.conversations=new S(this.config.productId,this.config.apiUrl),this.tools.register(g),console.log("[Crow] Default tools registered:",I.join(", ")),this.identity.subscribe(t=>{var s,r;(r=(s=this.callbacks).onVerificationStatus)==null||r.call(s,t.isVerified)})}get productId(){return this.config.productId}get apiUrl(){return this.config.apiUrl}get model(){return this.config.model}set model(e){this.config.model=e}on(e){this.callbacks={...this.callbacks,...e}}identify(e){this.identity.identify(e)}resetUser(){this.identity.reset(),this.clearMessages()}isIdentified(){return this.identity.isIdentified()}isVerified(){return this.identity.isVerified()}registerTools(e){this.tools.register(e)}unregisterTool(e){this.tools.unregister(e)}getRegisteredTools(){return this.tools.getRegisteredTools()}setContext(e){this.context={...this.context,...e}}clearContext(){this.context={}}get messages(){return[...this._messages]}get isLoading(){return this._isLoading}onMessages(e){return this.messageListeners.add(e),()=>this.messageListeners.delete(e)}onLoading(e){return this.loadingListeners.add(e),()=>this.loadingListeners.delete(e)}clearMessages(){this._messages=[],this.conversations.clear(),this.notifyMessages()}loadMessages(e){this._messages=e,this.notifyMessages()}notifyMessages(){const e=this.messages;for(const t of this.messageListeners)t(e)}setLoading(e){this._isLoading=e;for(const t of this.loadingListeners)t(e)}addMessage(e){var t,s;this._messages=[...this._messages,e],this.notifyMessages(),(s=(t=this.callbacks).onMessage)==null||s.call(t,e)}updateMessage(e,t){var s,r;this._messages=this._messages.map(i=>i.id===e?{...i,...t}:i),this.notifyMessages(),(r=(s=this.callbacks).onMessageUpdate)==null||r.call(s,e,t)}generateMessageId(e){return`${e}-${Date.now()}-${Math.random().toString(36).slice(2,9)}`}get conversationId(){return this.conversations.getCurrentId()}set conversationId(e){this.conversations.setCurrentId(e)}async getConversations(){const e=this.identity.getToken();return e?this.conversations.getConversations(e):(console.warn("[Crow] Cannot get conversations: user not identified"),[])}async loadHistory(e){const t=this.identity.getToken();return t?this.conversations.loadHistory(e,t):this.conversations.loadAnonymousHistory(e)}async switchConversation(e){const t=await this.loadHistory(e);this.conversations.setCurrentId(e),this.loadMessages(t)}async*sendMessage(e){var l,d,h,u,c,f,p,y,w,m;if(!e.trim())return;const t=this.generateMessageId("user");this.addMessage({id:t,content:e,role:"user",timestamp:new Date});const s=this.generateMessageId("assistant");this.addMessage({id:s,content:"",role:"assistant",timestamp:new Date}),this.setLoading(!0),this.abortController=new AbortController;let r="",i="";try{const a=await fetch(`${this.config.apiUrl}/api/chat/message`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({product_id:this.config.productId,message:e,conversation_id:this.conversations.getCurrentId(),identity_token:this.identity.getToken(),model:this.config.model,context:Object.keys(this.context).length>0?this.context:void 0}),signal:this.abortController.signal});if(!a.ok)throw new Error(`HTTP error: ${a.status}`);for await(const n of v(a,this.abortController.signal)){switch(n.type){case"content":r=n.accumulated,this.updateMessage(s,{content:r});break;case"thinking":i+=n.content,this.updateMessage(s,{thinking:i});break;case"thinking_complete":this.updateMessage(s,{thinkingComplete:!0});break;case"citations":this.updateMessage(s,{citations:n.citations});break;case"verification_status":this.identity.setVerified(n.isVerified);break;case"conversation_id":this.conversations.setCurrentId(n.conversationId);break;case"client_tool_call":await this.tools.execute(n.toolName,n.arguments),(d=(l=this.callbacks).onToolCall)==null||d.call(l,n);break;case"tool_call_start":case"tool_call_complete":(u=(h=this.callbacks).onToolCall)==null||u.call(h,n);break;case"workflow_started":case"workflow_todo_updated":case"workflow_ended":case"workflow_complete_prompt":(f=(c=this.callbacks).onWorkflow)==null||f.call(c,n);break;case"error":this.updateMessage(s,{content:n.message}),(y=(p=this.callbacks).onError)==null||y.call(p,new Error(n.message));break}yield n}}catch(a){if(a instanceof Error&&a.name==="AbortError"){r?this.updateMessage(s,{content:r}):(this._messages=this._messages.filter(n=>n.id!==s),this.notifyMessages());return}console.error("[Crow] Error:",a),this.updateMessage(s,{content:"Sorry, I encountered an error. Please try again."}),(m=(w=this.callbacks).onError)==null||m.call(w,a instanceof Error?a:new Error(String(a)))}finally{this.setLoading(!1),this.abortController=null}}async send(e){let t=null;for await(const r of this.sendMessage(e))if(r.type==="done")break;const s=this.messages;return s.length>0&&(t=s[s.length-1],t.role==="assistant")?t:null}stop(){this.abortController&&(this.abortController.abort(),this.setLoading(!1))}destroy(){this.stop(),this.messageListeners.clear(),this.loadingListeners.clear()}}exports.CrowBrowserUse=_.CrowBrowserUse;exports.ConversationManager=S;exports.CrowClient=L;exports.DEFAULT_TOOLS=g;exports.DEFAULT_TOOL_NAMES=I;exports.IdentityManager=k;exports.ToolManager=C;exports.parseSSEChunk=b;exports.parseSSEData=M;exports.streamResponse=v;
|
package/dist/index.d.ts
CHANGED
|
@@ -98,6 +98,7 @@ export declare class CrowBrowserUse {
|
|
|
98
98
|
private pageController;
|
|
99
99
|
private sessionId;
|
|
100
100
|
private maxSteps;
|
|
101
|
+
private aborted;
|
|
101
102
|
constructor(config: BrowserUseConfig);
|
|
102
103
|
/**
|
|
103
104
|
* Initialize PageController with non-blocking pointer
|
|
@@ -115,10 +116,6 @@ export declare class CrowBrowserUse {
|
|
|
115
116
|
* Process a step on the server
|
|
116
117
|
*/
|
|
117
118
|
private processStep;
|
|
118
|
-
/**
|
|
119
|
-
* Submit user's response to an ask_user question
|
|
120
|
-
*/
|
|
121
|
-
private submitUserResponse;
|
|
122
119
|
/**
|
|
123
120
|
* Execute an action using PageController
|
|
124
121
|
*/
|
|
@@ -315,6 +312,10 @@ export declare const DEFAULT_TOOLS: {
|
|
|
315
312
|
* Refresh the current page in the user's browser
|
|
316
313
|
*/
|
|
317
314
|
readonly refreshPage: () => Promise<ToolResult>;
|
|
315
|
+
/**
|
|
316
|
+
* Capture what's on the user's screen (DOM snapshot)
|
|
317
|
+
*/
|
|
318
|
+
readonly whatsOnScreen: () => Promise<ToolResult>;
|
|
318
319
|
};
|
|
319
320
|
|
|
320
321
|
export declare type DefaultToolName = keyof typeof DEFAULT_TOOLS;
|
package/dist/index.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
|
-
import {
|
|
2
|
-
|
|
1
|
+
import { P as _ } from "./browserUse-D5NUCzN4.js";
|
|
2
|
+
import { C as R } from "./browserUse-D5NUCzN4.js";
|
|
3
|
+
class k {
|
|
3
4
|
constructor() {
|
|
4
5
|
this.state = {
|
|
5
6
|
token: null,
|
|
@@ -71,7 +72,7 @@ class _ {
|
|
|
71
72
|
e(t);
|
|
72
73
|
}
|
|
73
74
|
}
|
|
74
|
-
class
|
|
75
|
+
class C {
|
|
75
76
|
constructor() {
|
|
76
77
|
this.handlers = {};
|
|
77
78
|
}
|
|
@@ -123,7 +124,7 @@ class k {
|
|
|
123
124
|
}
|
|
124
125
|
}
|
|
125
126
|
}
|
|
126
|
-
const
|
|
127
|
+
const v = "crow_conv_";
|
|
127
128
|
class b {
|
|
128
129
|
constructor(t, e) {
|
|
129
130
|
this.currentId = null, this.productId = t, this.apiUrl = e, this.currentId = this.loadFromStorage();
|
|
@@ -132,7 +133,7 @@ class b {
|
|
|
132
133
|
* Get localStorage key for this product
|
|
133
134
|
*/
|
|
134
135
|
getStorageKey() {
|
|
135
|
-
return `${
|
|
136
|
+
return `${v}${this.productId}`;
|
|
136
137
|
}
|
|
137
138
|
/**
|
|
138
139
|
* Load conversation ID from localStorage
|
|
@@ -269,11 +270,11 @@ class b {
|
|
|
269
270
|
return t;
|
|
270
271
|
}
|
|
271
272
|
}
|
|
272
|
-
function
|
|
273
|
-
if (
|
|
273
|
+
function I(o) {
|
|
274
|
+
if (o === "[DONE]")
|
|
274
275
|
return { type: "done" };
|
|
275
276
|
try {
|
|
276
|
-
const t = JSON.parse(
|
|
277
|
+
const t = JSON.parse(o);
|
|
277
278
|
switch (t.type) {
|
|
278
279
|
case "verification_status":
|
|
279
280
|
return {
|
|
@@ -347,18 +348,18 @@ function v(n) {
|
|
|
347
348
|
return null;
|
|
348
349
|
}
|
|
349
350
|
} catch {
|
|
350
|
-
return console.error("[Crow] Failed to parse SSE data:",
|
|
351
|
+
return console.error("[Crow] Failed to parse SSE data:", o), null;
|
|
351
352
|
}
|
|
352
353
|
}
|
|
353
|
-
function*
|
|
354
|
-
const t =
|
|
354
|
+
function* M(o) {
|
|
355
|
+
const t = o.split(`
|
|
355
356
|
`);
|
|
356
357
|
for (const e of t)
|
|
357
358
|
e.startsWith("data: ") && (yield e.slice(6).trim());
|
|
358
359
|
}
|
|
359
|
-
async function*
|
|
360
|
+
async function* S(o, t) {
|
|
360
361
|
var i;
|
|
361
|
-
const e = (i =
|
|
362
|
+
const e = (i = o.body) == null ? void 0 : i.getReader();
|
|
362
363
|
if (!e)
|
|
363
364
|
throw new Error("Response body is not readable");
|
|
364
365
|
const s = new TextDecoder();
|
|
@@ -372,8 +373,8 @@ async function* M(n, t) {
|
|
|
372
373
|
const { done: l, value: d } = await e.read();
|
|
373
374
|
if (l) break;
|
|
374
375
|
const h = s.decode(d);
|
|
375
|
-
for (const u of
|
|
376
|
-
const c =
|
|
376
|
+
for (const u of M(h)) {
|
|
377
|
+
const c = I(u);
|
|
377
378
|
if (c && (c.type === "content" ? (r += c.text, yield { ...c, accumulated: r }) : yield c, c.type === "done"))
|
|
378
379
|
return;
|
|
379
380
|
}
|
|
@@ -382,28 +383,50 @@ async function* M(n, t) {
|
|
|
382
383
|
e.releaseLock();
|
|
383
384
|
}
|
|
384
385
|
}
|
|
385
|
-
const
|
|
386
|
+
const m = {
|
|
386
387
|
/**
|
|
387
388
|
* Refresh the current page in the user's browser
|
|
388
389
|
*/
|
|
389
390
|
refreshPage: async () => {
|
|
390
391
|
try {
|
|
391
392
|
return window.location.reload(), { status: "success", data: { message: "Page refresh initiated" } };
|
|
392
|
-
} catch (
|
|
393
|
-
return { status: "error", error: String(
|
|
393
|
+
} catch (o) {
|
|
394
|
+
return { status: "error", error: String(o) };
|
|
395
|
+
}
|
|
396
|
+
},
|
|
397
|
+
/**
|
|
398
|
+
* Capture what's on the user's screen (DOM snapshot)
|
|
399
|
+
*/
|
|
400
|
+
whatsOnScreen: async () => {
|
|
401
|
+
try {
|
|
402
|
+
const o = new _({ viewportExpansion: 500 }), t = await o.getBrowserState();
|
|
403
|
+
return o.dispose(), {
|
|
404
|
+
status: "success",
|
|
405
|
+
data: {
|
|
406
|
+
url: t.url,
|
|
407
|
+
title: t.title,
|
|
408
|
+
content: `${t.header}
|
|
409
|
+
|
|
410
|
+
${t.content}
|
|
411
|
+
|
|
412
|
+
${t.footer}`
|
|
413
|
+
}
|
|
414
|
+
};
|
|
415
|
+
} catch (o) {
|
|
416
|
+
return console.error("[Crow] whatsOnScreen error:", o), { status: "error", error: String(o) };
|
|
394
417
|
}
|
|
395
418
|
}
|
|
396
|
-
},
|
|
397
|
-
class
|
|
419
|
+
}, T = Object.keys(m), $ = "https://api.usecrow.org", E = "claude-sonnet-4-20250514";
|
|
420
|
+
class U {
|
|
398
421
|
constructor(t) {
|
|
399
422
|
this.context = {}, this.abortController = null, this.callbacks = {}, this._messages = [], this.messageListeners = /* @__PURE__ */ new Set(), this._isLoading = !1, this.loadingListeners = /* @__PURE__ */ new Set(), this.config = {
|
|
400
423
|
productId: t.productId,
|
|
401
|
-
apiUrl: t.apiUrl ||
|
|
402
|
-
model: t.model ||
|
|
403
|
-
}, this.identity = new
|
|
424
|
+
apiUrl: t.apiUrl || $,
|
|
425
|
+
model: t.model || E
|
|
426
|
+
}, this.identity = new k(), this.tools = new C(), this.conversations = new b(
|
|
404
427
|
this.config.productId,
|
|
405
428
|
this.config.apiUrl
|
|
406
|
-
), this.tools.register(
|
|
429
|
+
), this.tools.register(m), console.log("[Crow] Default tools registered:", T.join(", ")), this.identity.subscribe((e) => {
|
|
407
430
|
var s, r;
|
|
408
431
|
(r = (s = this.callbacks).onVerificationStatus) == null || r.call(s, e.isVerified);
|
|
409
432
|
});
|
|
@@ -610,7 +633,7 @@ class E {
|
|
|
610
633
|
* Returns an async generator of stream events
|
|
611
634
|
*/
|
|
612
635
|
async *sendMessage(t) {
|
|
613
|
-
var l, d, h, u, c, g, f, p, y,
|
|
636
|
+
var l, d, h, u, c, g, f, p, y, w;
|
|
614
637
|
if (!t.trim())
|
|
615
638
|
return;
|
|
616
639
|
const e = this.generateMessageId("user");
|
|
@@ -644,53 +667,53 @@ class E {
|
|
|
644
667
|
});
|
|
645
668
|
if (!a.ok)
|
|
646
669
|
throw new Error(`HTTP error: ${a.status}`);
|
|
647
|
-
for await (const
|
|
648
|
-
switch (
|
|
670
|
+
for await (const n of S(a, this.abortController.signal)) {
|
|
671
|
+
switch (n.type) {
|
|
649
672
|
case "content":
|
|
650
|
-
r =
|
|
673
|
+
r = n.accumulated, this.updateMessage(s, { content: r });
|
|
651
674
|
break;
|
|
652
675
|
case "thinking":
|
|
653
|
-
i +=
|
|
676
|
+
i += n.content, this.updateMessage(s, { thinking: i });
|
|
654
677
|
break;
|
|
655
678
|
case "thinking_complete":
|
|
656
679
|
this.updateMessage(s, { thinkingComplete: !0 });
|
|
657
680
|
break;
|
|
658
681
|
case "citations":
|
|
659
|
-
this.updateMessage(s, { citations:
|
|
682
|
+
this.updateMessage(s, { citations: n.citations });
|
|
660
683
|
break;
|
|
661
684
|
case "verification_status":
|
|
662
|
-
this.identity.setVerified(
|
|
685
|
+
this.identity.setVerified(n.isVerified);
|
|
663
686
|
break;
|
|
664
687
|
case "conversation_id":
|
|
665
|
-
this.conversations.setCurrentId(
|
|
688
|
+
this.conversations.setCurrentId(n.conversationId);
|
|
666
689
|
break;
|
|
667
690
|
case "client_tool_call":
|
|
668
|
-
await this.tools.execute(
|
|
691
|
+
await this.tools.execute(n.toolName, n.arguments), (d = (l = this.callbacks).onToolCall) == null || d.call(l, n);
|
|
669
692
|
break;
|
|
670
693
|
case "tool_call_start":
|
|
671
694
|
case "tool_call_complete":
|
|
672
|
-
(u = (h = this.callbacks).onToolCall) == null || u.call(h,
|
|
695
|
+
(u = (h = this.callbacks).onToolCall) == null || u.call(h, n);
|
|
673
696
|
break;
|
|
674
697
|
case "workflow_started":
|
|
675
698
|
case "workflow_todo_updated":
|
|
676
699
|
case "workflow_ended":
|
|
677
700
|
case "workflow_complete_prompt":
|
|
678
|
-
(g = (c = this.callbacks).onWorkflow) == null || g.call(c,
|
|
701
|
+
(g = (c = this.callbacks).onWorkflow) == null || g.call(c, n);
|
|
679
702
|
break;
|
|
680
703
|
case "error":
|
|
681
|
-
this.updateMessage(s, { content:
|
|
704
|
+
this.updateMessage(s, { content: n.message }), (p = (f = this.callbacks).onError) == null || p.call(f, new Error(n.message));
|
|
682
705
|
break;
|
|
683
706
|
}
|
|
684
|
-
yield
|
|
707
|
+
yield n;
|
|
685
708
|
}
|
|
686
709
|
} catch (a) {
|
|
687
710
|
if (a instanceof Error && a.name === "AbortError") {
|
|
688
|
-
r ? this.updateMessage(s, { content: r }) : (this._messages = this._messages.filter((
|
|
711
|
+
r ? this.updateMessage(s, { content: r }) : (this._messages = this._messages.filter((n) => n.id !== s), this.notifyMessages());
|
|
689
712
|
return;
|
|
690
713
|
}
|
|
691
714
|
console.error("[Crow] Error:", a), this.updateMessage(s, {
|
|
692
715
|
content: "Sorry, I encountered an error. Please try again."
|
|
693
|
-
}), (
|
|
716
|
+
}), (w = (y = this.callbacks).onError) == null || w.call(y, a instanceof Error ? a : new Error(String(a)));
|
|
694
717
|
} finally {
|
|
695
718
|
this.setLoading(!1), this.abortController = null;
|
|
696
719
|
}
|
|
@@ -724,13 +747,13 @@ class E {
|
|
|
724
747
|
}
|
|
725
748
|
export {
|
|
726
749
|
b as ConversationManager,
|
|
727
|
-
|
|
728
|
-
|
|
729
|
-
|
|
730
|
-
|
|
731
|
-
|
|
732
|
-
|
|
733
|
-
|
|
734
|
-
|
|
735
|
-
|
|
750
|
+
R as CrowBrowserUse,
|
|
751
|
+
U as CrowClient,
|
|
752
|
+
m as DEFAULT_TOOLS,
|
|
753
|
+
T as DEFAULT_TOOL_NAMES,
|
|
754
|
+
k as IdentityManager,
|
|
755
|
+
C as ToolManager,
|
|
756
|
+
M as parseSSEChunk,
|
|
757
|
+
I as parseSSEData,
|
|
758
|
+
S as streamResponse
|
|
736
759
|
};
|
package/package.json
CHANGED
|
@@ -1,9 +0,0 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});async function waitFor(e){await new Promise(n=>setTimeout(n,e*1e3))}async function movePointerToElement(e){const n=e.getBoundingClientRect(),s=n.left+n.width/2,i=n.top+n.height/2;window.dispatchEvent(new CustomEvent("PageAgent::MovePointerTo",{detail:{x:s,y:i}})),await waitFor(.3)}function getElementByIndex(e,n){const s=e.get(n);if(!s)throw new Error(`No interactive element found at index ${n}`);const i=s.ref;if(!i)throw new Error(`Element at index ${n} does not have a reference`);if(!(i instanceof HTMLElement))throw new Error(`Element at index ${n} is not an HTMLElement`);return i}let lastClickedElement=null;function blurLastClickedElement(){lastClickedElement&&(lastClickedElement.blur(),lastClickedElement.dispatchEvent(new MouseEvent("mouseout",{bubbles:!0,cancelable:!0})),lastClickedElement=null)}async function clickElement(e){blurLastClickedElement(),lastClickedElement=e,await scrollIntoViewIfNeeded(e),await movePointerToElement(e),window.dispatchEvent(new CustomEvent("PageAgent::ClickPointer")),await waitFor(.1),e.dispatchEvent(new MouseEvent("mouseenter",{bubbles:!0,cancelable:!0})),e.dispatchEvent(new MouseEvent("mouseover",{bubbles:!0,cancelable:!0})),e.dispatchEvent(new MouseEvent("mousedown",{bubbles:!0,cancelable:!0})),e.focus(),e.dispatchEvent(new MouseEvent("mouseup",{bubbles:!0,cancelable:!0})),e.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(e,n){if(!(e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement))throw new Error("Element is not an input or textarea");await clickElement(e),e instanceof HTMLTextAreaElement?nativeTextAreaValueSetter.call(e,n):nativeInputValueSetter.call(e,n);const s=new Event("input",{bubbles:!0});e.dispatchEvent(s),await waitFor(.1),blurLastClickedElement()}async function selectOptionElement(e,n){if(!(e instanceof HTMLSelectElement))throw new Error("Element is not a select element");const i=Array.from(e.options).find(w=>{var d;return((d=w.textContent)==null?void 0:d.trim())===n.trim()});if(!i)throw new Error(`Option with text "${n}" not found in select element`);e.value=i.value,e.dispatchEvent(new Event("change",{bubbles:!0})),await waitFor(.1)}async function scrollIntoViewIfNeeded(e){const n=e;n.scrollIntoViewIfNeeded?n.scrollIntoViewIfNeeded():n.scrollIntoView({behavior:"auto",block:"center",inline:"nearest"})}async function scrollVertically(e,n,s){if(s){const l=s;console.log("[SCROLL DEBUG] Starting direct container scroll for element:",l.tagName);let h=l,T=!1,b=null,u=0,f=0;const N=n;for(;h&&f<10;){const D=window.getComputedStyle(h),z=/(auto|scroll|overlay)/.test(D.overflowY),O=h.scrollHeight>h.clientHeight;if(console.log("[SCROLL DEBUG] Checking element:",h.tagName,"hasScrollableY:",z,"canScrollVertically:",O,"scrollHeight:",h.scrollHeight,"clientHeight:",h.clientHeight),z&&O){const R=h.scrollTop,U=h.scrollHeight-h.clientHeight;let H=N/3;H>0?H=Math.min(H,U-R):H=Math.max(H,-R),h.scrollTop=R+H;const B=h.scrollTop,_=B-R;if(console.log("[SCROLL DEBUG] Scroll attempt:",h.tagName,"before:",R,"after:",B,"delta:",_),Math.abs(_)>.5){T=!0,b=h,u=_,console.log("[SCROLL DEBUG] Successfully scrolled container:",h.tagName,"delta:",_);break}}if(h===document.body||h===document.documentElement)break;h=h.parentElement,f++}return T?`Scrolled container (${b==null?void 0:b.tagName}) by ${u}px`:`No scrollable container found for element (${l.tagName})`}const i=n,w=l=>l.clientHeight>=window.innerHeight*.5,d=l=>l&&/(auto|scroll|overlay)/.test(getComputedStyle(l).overflowY)&&l.scrollHeight>l.clientHeight&&w(l);let r=document.activeElement;for(;r&&!d(r)&&r!==document.body;)r=r.parentElement;if(r=d(r)?r:Array.from(document.querySelectorAll("*")).find(d)||document.scrollingElement||document.documentElement,r===document.scrollingElement||r===document.documentElement||r===document.body){const l=window.scrollY,h=document.documentElement.scrollHeight-window.innerHeight;window.scrollBy(0,i);const T=window.scrollY,b=T-l;if(Math.abs(b)<1)return i>0?"⚠️ Already at the bottom of the page, cannot scroll down further.":"⚠️ Already at the top of the page, cannot scroll up further.";const u=i>0&&T>=h-1,f=i<0&&T<=1;return u?`✅ Scrolled page by ${b}px. Reached the bottom of the page.`:f?`✅ Scrolled page by ${b}px. Reached the top of the page.`:`✅ Scrolled page by ${b}px.`}else{const l=r.scrollTop,h=r.scrollHeight-r.clientHeight;r.scrollBy({top:i,behavior:"smooth"}),await waitFor(.1);const T=r.scrollTop,b=T-l;if(Math.abs(b)<1)return i>0?`⚠️ Already at the bottom of container (${r.tagName}), cannot scroll down further.`:`⚠️ Already at the top of container (${r.tagName}), cannot scroll up further.`;const u=i>0&&T>=h-1,f=i<0&&T<=1;return u?`✅ Scrolled container (${r.tagName}) by ${b}px. Reached the bottom.`:f?`✅ Scrolled container (${r.tagName}) by ${b}px. Reached the top.`:`✅ Scrolled container (${r.tagName}) by ${b}px.`}}async function scrollHorizontally(e,n,s){if(s){const l=s;console.log("[SCROLL DEBUG] Starting direct container scroll for element:",l.tagName);let h=l,T=!1,b=null,u=0,f=0;const N=e?n:-n;for(;h&&f<10;){const D=window.getComputedStyle(h),z=/(auto|scroll|overlay)/.test(D.overflowX),O=h.scrollWidth>h.clientWidth;if(console.log("[SCROLL DEBUG] Checking element:",h.tagName,"hasScrollableX:",z,"canScrollHorizontally:",O,"scrollWidth:",h.scrollWidth,"clientWidth:",h.clientWidth),z&&O){const R=h.scrollLeft,U=h.scrollWidth-h.clientWidth;let H=N/3;H>0?H=Math.min(H,U-R):H=Math.max(H,-R),h.scrollLeft=R+H;const B=h.scrollLeft,_=B-R;if(console.log("[SCROLL DEBUG] Scroll attempt:",h.tagName,"before:",R,"after:",B,"delta:",_),Math.abs(_)>.5){T=!0,b=h,u=_,console.log("[SCROLL DEBUG] Successfully scrolled container:",h.tagName,"delta:",_);break}}if(h===document.body||h===document.documentElement)break;h=h.parentElement,f++}return T?`Scrolled container (${b==null?void 0:b.tagName}) horizontally by ${u}px`:`No horizontally scrollable container found for element (${l.tagName})`}const i=e?n:-n,w=l=>l.clientWidth>=window.innerWidth*.5,d=l=>l&&/(auto|scroll|overlay)/.test(getComputedStyle(l).overflowX)&&l.scrollWidth>l.clientWidth&&w(l);let r=document.activeElement;for(;r&&!d(r)&&r!==document.body;)r=r.parentElement;if(r=d(r)?r:Array.from(document.querySelectorAll("*")).find(d)||document.scrollingElement||document.documentElement,r===document.scrollingElement||r===document.documentElement||r===document.body){const l=window.scrollX,h=document.documentElement.scrollWidth-window.innerWidth;window.scrollBy(i,0);const T=window.scrollX,b=T-l;if(Math.abs(b)<1)return i>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 u=i>0&&T>=h-1,f=i<0&&T<=1;return u?`✅ Scrolled page by ${b}px. Reached the right edge of the page.`:f?`✅ Scrolled page by ${b}px. Reached the left edge of the page.`:`✅ Scrolled page horizontally by ${b}px.`}else{const l=r.scrollLeft,h=r.scrollWidth-r.clientWidth;r.scrollBy({left:i,behavior:"smooth"}),await waitFor(.1);const T=r.scrollLeft,b=T-l;if(Math.abs(b)<1)return i>0?`⚠️ Already at the right edge of container (${r.tagName}), cannot scroll right further.`:`⚠️ Already at the left edge of container (${r.tagName}), cannot scroll left further.`;const u=i>0&&T>=h-1,f=i<0&&T<=1;return u?`✅ Scrolled container (${r.tagName}) by ${b}px. Reached the right edge.`:f?`✅ Scrolled container (${r.tagName}) by ${b}px. Reached the left edge.`:`✅ Scrolled container (${r.tagName}) horizontally by ${b}px.`}}const VIEWPORT_EXPANSION=-1,domTree=(e={doHighlightElements:!0,focusHighlightIndex:-1,viewportExpansion:0,debugMode:!1,interactiveBlacklist:[],interactiveWhitelist:[],highlightOpacity:.1,highlightLabelOpacity:.5})=>{const{interactiveBlacklist:n,interactiveWhitelist:s,highlightOpacity:i,highlightLabelOpacity:w}=e,{doHighlightElements:d,focusHighlightIndex:r,viewportExpansion:l,debugMode:h}=e;let T=0;const b=new WeakMap;function u(t,o){!t||t.nodeType!==Node.ELEMENT_NODE||b.set(t,{...b.get(t),...o})}const f={boundingRects:new WeakMap,clientRects:new WeakMap,computedStyles:new WeakMap,clearCache:()=>{f.boundingRects=new WeakMap,f.clientRects=new WeakMap,f.computedStyles=new WeakMap}};function N(t){if(!t)return null;if(f.boundingRects.has(t))return f.boundingRects.get(t);const o=t.getBoundingClientRect();return o&&f.boundingRects.set(t,o),o}function D(t){if(!t)return null;if(f.computedStyles.has(t))return f.computedStyles.get(t);const o=window.getComputedStyle(t);return o&&f.computedStyles.set(t,o),o}function z(t){if(!t)return null;if(f.clientRects.has(t))return f.clientRects.get(t);const o=t.getClientRects();return o&&f.clientRects.set(t,o),o}const O={},R={current:0},U="playwright-highlight-container";function H(t,o,p=null){if(!t)return o;const a=[];let c=null,x=20,E=16,I=null;try{let m=document.getElementById(U);m||(m=document.createElement("div"),m.id=U,m.style.position="fixed",m.style.pointerEvents="none",m.style.top="0",m.style.left="0",m.style.width="100%",m.style.height="100%",m.style.zIndex="2147483640",m.style.backgroundColor="transparent",document.body.appendChild(m));const $=t.getClientRects();if(!$||$.length===0)return o;const A=["#FF0000","#00FF00","#0000FF","#FFA500","#800080","#008080","#FF69B4","#4B0082","#FF4500","#2E8B57","#DC143C","#4682B4"],g=o%A.length;let y=A[g];const C=y+Math.floor(i*255).toString(16).padStart(2,"0");y=y+Math.floor(w*255).toString(16).padStart(2,"0");let M={x:0,y:0};if(p){const k=p.getBoundingClientRect();M.x=k.left,M.y=k.top}const V=document.createDocumentFragment();for(const k of $){if(k.width===0||k.height===0)continue;const S=document.createElement("div");S.style.position="fixed",S.style.border=`2px solid ${y}`,S.style.backgroundColor=C,S.style.pointerEvents="none",S.style.boxSizing="border-box";const v=k.top+M.y,W=k.left+M.x;S.style.top=`${v}px`,S.style.left=`${W}px`,S.style.width=`${k.width}px`,S.style.height=`${k.height}px`,V.appendChild(S),a.push({element:S,initialRect:k})}const G=$[0];if(w>0){c=document.createElement("div"),c.className="playwright-highlight-label",c.style.position="fixed",c.style.background=y,c.style.color="white",c.style.padding="1px 4px",c.style.borderRadius="4px",c.style.fontSize=`${Math.min(12,Math.max(8,G.height/2))}px`,c.textContent=o.toString(),x=c.offsetWidth>0?c.offsetWidth:x,E=c.offsetHeight>0?c.offsetHeight:E;const k=G.top+M.y,S=G.left+M.x;let v=k+2,W=S+G.width-x-2;(G.width<x+4||G.height<E+4)&&(v=k-E-2,W=S+G.width-x,W<M.x&&(W=S)),v=Math.max(0,Math.min(v,window.innerHeight-E)),W=Math.max(0,Math.min(W,window.innerWidth-x)),c.style.top=`${v}px`,c.style.left=`${W}px`,V.appendChild(c)}const j=((k,S)=>{let v=0;return(...W)=>{const P=performance.now();if(!(P-v<S))return v=P,k(...W)}})(()=>{const k=t.getClientRects();let S={x:0,y:0};if(p){const v=p.getBoundingClientRect();S.x=v.left,S.y=v.top}if(a.forEach((v,W)=>{if(W<k.length){const P=k[W],Z=P.top+S.y,J=P.left+S.x;v.element.style.top=`${Z}px`,v.element.style.left=`${J}px`,v.element.style.width=`${P.width}px`,v.element.style.height=`${P.height}px`,v.element.style.display=P.width===0||P.height===0?"none":"block"}else v.element.style.display="none"}),k.length<a.length)for(let v=k.length;v<a.length;v++)a[v].element.style.display="none";if(c&&k.length>0){const v=k[0],W=v.top+S.y,P=v.left+S.x;let Z=W+2,J=P+v.width-x-2;(v.width<x+4||v.height<E+4)&&(Z=W-E-2,J=P+v.width-x,J<S.x&&(J=P)),Z=Math.max(0,Math.min(Z,window.innerHeight-E)),J=Math.max(0,Math.min(J,window.innerWidth-x)),c.style.top=`${Z}px`,c.style.left=`${J}px`,c.style.display="block"}else c&&(c.style.display="none")},16);return window.addEventListener("scroll",j,!0),window.addEventListener("resize",j),I=()=>{window.removeEventListener("scroll",j,!0),window.removeEventListener("resize",j),a.forEach(k=>k.element.remove()),c&&c.remove()},m.appendChild(V),o+1}finally{I&&(window._highlightCleanupFunctions=window._highlightCleanupFunctions||[]).push(I)}}function B(t){if(!t||t.nodeType!==Node.ELEMENT_NODE)return null;const o=D(t);if(!o)return null;const p=o.display;if(p==="inline"||p==="inline-block")return null;const a=o.overflowX,c=o.overflowY,x=a==="auto"||a==="scroll",E=c==="auto"||c==="scroll";if(!x&&!E)return null;const I=t.scrollWidth-t.clientWidth,m=t.scrollHeight-t.clientHeight,$=4;if(I<$&&m<$||!E&&I<$||!x&&m<$)return null;const A=t.scrollTop,g=t.scrollLeft,y=t.scrollWidth-t.clientWidth-t.scrollLeft,C=t.scrollHeight-t.clientHeight-t.scrollTop,M={top:A,right:y,bottom:C,left:g};return u(t,{scrollable:!0,scrollData:M}),M}function _(t){try{if(l===-1){const E=t.parentElement;if(!E)return!1;try{return E.checkVisibility({checkOpacity:!0,checkVisibilityCSS:!0})}catch{const m=window.getComputedStyle(E);return m.display!=="none"&&m.visibility!=="hidden"&&m.opacity!=="0"}}const o=document.createRange();o.selectNodeContents(t);const p=o.getClientRects();if(!p||p.length===0)return!1;let a=!1,c=!1;for(const E of p)if(E.width>0&&E.height>0&&(a=!0,!(E.bottom<-l||E.top>window.innerHeight+l||E.right<-l||E.left>window.innerWidth+l))){c=!0;break}if(!a||!c)return!1;const x=t.parentElement;if(!x)return!1;try{return x.checkVisibility({checkOpacity:!0,checkVisibilityCSS:!0})}catch{const I=window.getComputedStyle(x);return I.display!=="none"&&I.visibility!=="hidden"&&I.opacity!=="0"}}catch(o){return console.warn("Error checking text node visibility:",o),!1}}function ot(t){if(!t||!t.tagName)return!1;const o=new Set(["body","div","main","article","section","nav","header","footer"]),p=t.tagName.toLowerCase();return o.has(p)?!0:!new Set(["svg","script","style","link","meta","noscript","template"]).has(p)}function X(t){const o=D(t);return t.offsetWidth>0&&t.offsetHeight>0&&(o==null?void 0:o.visibility)!=="hidden"&&(o==null?void 0:o.display)!=="none"}function L(t){var C,M;if(!t||t.nodeType!==Node.ELEMENT_NODE||n.includes(t))return!1;if(s.includes(t))return!0;const o=t.tagName.toLowerCase(),p=D(t),a=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"]),c=new Set(["not-allowed","no-drop","wait","progress","initial","inherit"]);function x(V){return V.tagName.toLowerCase()==="html"?!1:!!(p!=null&&p.cursor&&a.has(p.cursor))}if(x(t))return!0;const I=new Set(["a","button","input","select","textarea","details","summary","label","option","optgroup","fieldset","legend"]),m=new Set(["disabled","readonly"]);if(I.has(o)){if(p!=null&&p.cursor&&c.has(p.cursor))return!1;for(const V of m)if(t.hasAttribute(V)||t.getAttribute(V)==="true"||t.getAttribute(V)==="")return!1;return!(t.disabled||t.readOnly||t.inert)}const $=t.getAttribute("role"),A=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 g=new Set(["button","menu","menubar","menuitem","menuitemradio","menuitemcheckbox","radio","checkbox","tab","switch","slider","spinbutton","combobox","searchbox","textbox","listbox","option","scrollbar"]);if(I.has(o)||$&&g.has($)||A&&g.has(A))return!0;try{if(typeof getEventListeners=="function"){const q=getEventListeners(t),nt=["click","mousedown","mouseup","dblclick"];for(const j of nt)if(q[j]&&q[j].length>0)return!0}const V=((M=(C=t==null?void 0:t.ownerDocument)==null?void 0:C.defaultView)==null?void 0:M.getEventListenersForNode)||window.getEventListenersForNode;if(typeof V=="function"){const q=V(t),nt=["click","mousedown","mouseup","keydown","keyup","submit","change","input","focus","blur"];for(const j of nt)for(const k of q)if(k.type===j)return!0}const G=["onclick","onmousedown","onmouseup","ondblclick"];for(const q of G)if(t.hasAttribute(q)||typeof t[q]=="function")return!0}catch{}return!!B(t)}function et(t){if(l===-1)return!0;const o=z(t);if(!o||o.length===0)return!1;let p=!1;for(const m of o)if(m.width>0&&m.height>0&&!(m.bottom<-l||m.top>window.innerHeight+l||m.right<-l||m.left>window.innerWidth+l)){p=!0;break}if(!p)return!1;if(t.ownerDocument!==window.document)return!0;let c=Array.from(o).find(m=>m.width>0&&m.height>0);if(!c)return!1;const x=t.getRootNode();if(x instanceof ShadowRoot){const m=c.left+c.width/2,$=c.top+c.height/2;try{const A=x.elementFromPoint(m,$);if(!A)return!1;let g=A;for(;g&&g!==x;){if(g===t)return!0;g=g.parentElement}return!1}catch{return!0}}const E=5;return[{x:c.left+c.width/2,y:c.top+c.height/2},{x:c.left+E,y:c.top+E},{x:c.right-E,y:c.bottom-E}].some(({x:m,y:$})=>{try{const A=document.elementFromPoint(m,$);if(!A)return!1;let g=A;for(;g&&g!==document.documentElement;){if(g===t)return!0;g=g.parentElement}return!1}catch{return!0}})}function it(t,o){if(o===-1)return!0;const p=t.getClientRects();if(!p||p.length===0){const a=N(t);return!a||a.width===0||a.height===0?!1:!(a.bottom<-o||a.top>window.innerHeight+o||a.right<-o||a.left>window.innerWidth+o)}for(const a of p)if(!(a.width===0||a.height===0)&&!(a.bottom<-o||a.top>window.innerHeight+o||a.right<-o||a.left>window.innerWidth+o))return!0;return!1}function F(t){if(!t||t.nodeType!==Node.ELEMENT_NODE)return!1;const o=t.tagName.toLowerCase();return new Set(["a","button","input","select","textarea","details","summary","label"]).has(o)?!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 tt(t){if(!t||t.nodeType!==Node.ELEMENT_NODE||!X(t))return!1;const o=t.hasAttribute("role")||t.hasAttribute("tabindex")||t.hasAttribute("onclick")||typeof t.onclick=="function",p=/\b(btn|clickable|menu|item|entry|link)\b/i.test(t.className||""),a=!!t.closest('button,a,[role="button"],.menu,.dropdown,.list,.toolbar'),c=[...t.children].some(X),x=t.parentElement&&t.parentElement.isSameNode(document.body);return(L(t)||o||p)&&c&&a&&!x}function rt(t){var a,c;if(!t||t.nodeType!==Node.ELEMENT_NODE)return!1;const o=t.tagName.toLowerCase(),p=t.getAttribute("role");if(o==="iframe"||Y.has(o)||p&&K.has(p)||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=((c=(a=t==null?void 0:t.ownerDocument)==null?void 0:a.defaultView)==null?void 0:c.getEventListenersForNode)||window.getEventListenersForNode;if(typeof x=="function"){const I=x(t),m=["click","mousedown","mouseup","keydown","keyup","submit","change","input","focus","blur"];for(const $ of m)for(const A of I)if(A.type===$)return!0}if(["onmousedown","onmouseup","onkeydown","onkeyup","onsubmit","onchange","oninput","onfocus","onblur"].some(I=>t.hasAttribute(I)))return!0}catch{}return!!tt(t)}function st(t,o,p,a){if(!t.isInteractive)return!1;let c=!1;return a?rt(o)?c=!0:c=!1:c=!0,c&&(t.isInViewport=it(o,l),(t.isInViewport||l===-1)&&(t.highlightIndex=T++,d))?(r>=0?r===t.highlightIndex&&H(o,t.highlightIndex,p):H(o,t.highlightIndex,p),!0):!1}function Q(t,o=null,p=!1){var E,I,m,$,A;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 g={tagName:"body",attributes:{},xpath:"/body",children:[]};for(const C of t.childNodes){const M=Q(C,o,!1);M&&g.children.push(M)}const y=`${R.current++}`;return O[y]=g,y}if(t.nodeType!==Node.ELEMENT_NODE&&t.nodeType!==Node.TEXT_NODE)return null;if(t.nodeType===Node.TEXT_NODE){const g=(I=t.textContent)==null?void 0:I.trim();if(!g)return null;const y=t.parentElement;if(!y||y.tagName.toLowerCase()==="script")return null;const C=`${R.current++}`;return O[C]={type:"TEXT_NODE",text:g,isVisible:_(t)},C}if(t.nodeType===Node.ELEMENT_NODE&&!ot(t))return null;if(l!==-1&&!t.shadowRoot){const g=N(t),y=D(t),C=y&&(y.position==="fixed"||y.position==="sticky"),M=t.offsetWidth>0||t.offsetHeight>0;if(!g||!C&&!M&&(g.bottom<-l||g.top>window.innerHeight+l||g.right<-l||g.left>window.innerWidth+l))return null}const a={tagName:t.tagName.toLowerCase(),attributes:{},children:[]};if(F(t)||t.tagName.toLowerCase()==="iframe"||t.tagName.toLowerCase()==="body"){const g=((m=t.getAttributeNames)==null?void 0:m.call(t))||[];for(const y of g){const C=t.getAttribute(y);a.attributes[y]=C}t.tagName.toLowerCase()==="input"&&(t.type==="checkbox"||t.type==="radio")&&(a.attributes.checked=t.checked?"true":"false")}let c=!1;if(t.nodeType===Node.ELEMENT_NODE&&(a.isVisible=X(t),a.isVisible)){a.isTopElement=et(t);const g=t.getAttribute("role"),y=g==="menu"||g==="menubar"||g==="listbox";(a.isTopElement||y)&&(a.isInteractive=L(t),c=st(a,t,o,p),a.ref=t)}if(t.tagName){const g=t.tagName.toLowerCase();if(g==="iframe")try{const y=t.contentDocument||(($=t.contentWindow)==null?void 0:$.document);if(y)for(const C of y.childNodes){const M=Q(C,t,!1);M&&a.children.push(M)}}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")||g==="body"&&((A=t.getAttribute("data-id"))!=null&&A.startsWith("mce_")))for(const y of t.childNodes){const C=Q(y,o,c);C&&a.children.push(C)}else{if(t.shadowRoot){a.shadowRoot=!0;for(const y of t.shadowRoot.childNodes){const C=Q(y,o,c);C&&a.children.push(C)}}for(const y of t.childNodes){const M=Q(y,o,c||p);M&&a.children.push(M)}}}if(a.tagName==="a"&&a.children.length===0&&!a.attributes.href){const g=N(t);if(!(g&&g.width>0&&g.height>0||t.offsetWidth>0||t.offsetHeight>0))return null}a.extra=b.get(t)||null;const x=`${R.current++}`;return O[x]=a,x}const lt=Q(document.body);return f.clearCache(),{rootId:lt,map:O}},newElementsCache=new WeakMap;function getFlatTree(e){const n=[];for(const d of e.interactiveBlacklist||[])typeof d=="function"?n.push(d()):n.push(d);const s=[];for(const d of e.interactiveWhitelist||[])typeof d=="function"?s.push(d()):s.push(d);const i=domTree({doHighlightElements:!0,debugMode:!0,focusHighlightIndex:-1,viewportExpansion:VIEWPORT_EXPANSION,interactiveBlacklist:n,interactiveWhitelist:s,highlightOpacity:e.highlightOpacity??0,highlightLabelOpacity:e.highlightLabelOpacity??.1}),w=window.location.href;for(const d in i.map){const r=i.map[d];if(r.isInteractive&&r.ref){const l=r.ref;newElementsCache.has(l)||(newElementsCache.set(l,w),r.isNew=!0)}}return i}function flatTreeToString(e,n){const s=["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"],i=[...n||[],...s],w=(u,f)=>u.length>f?u.substring(0,f)+"...":u,d=u=>{const f=e.map[u];if(!f)return null;if(f.type==="TEXT_NODE"){const N=f;return{type:"text",text:N.text,isVisible:N.isVisible,parent:null,children:[]}}else{const N=f,D=[];if(N.children)for(const z of N.children){const O=d(z);O&&(O.parent=null,D.push(O))}return{type:"element",tagName:N.tagName,attributes:N.attributes??{},isVisible:N.isVisible??!1,isInteractive:N.isInteractive??!1,isTopElement:N.isTopElement??!1,isNew:N.isNew??!1,highlightIndex:N.highlightIndex,parent:null,children:D,extra:N.extra??{}}}},r=(u,f=null)=>{u.parent=f;for(const N of u.children)r(N,u)},l=d(e.rootId);if(!l)return"";r(l);const h=u=>{let f=u.parent;for(;f;){if(f.type==="element"&&f.highlightIndex!==void 0)return!0;f=f.parent}return!1},T=(u,f,N)=>{var O,R,U,H;let D=f;const z=" ".repeat(f);if(u.type==="element"){if(u.highlightIndex!==void 0){D+=1;const B=getAllTextTillNextClickableElement(u);let _="";if(i.length>0&&u.attributes){const L={};for(const F of i){const Y=u.attributes[F];Y&&Y.trim()!==""&&(L[F]=Y.trim())}const et=i.filter(F=>F in L);if(et.length>1){const F=new Set,Y={};for(const K of et){const tt=L[K];tt.length>5&&(tt in Y?F.add(K):Y[tt]=K)}for(const K of F)delete L[K]}L.role===u.tagName&&delete L.role;const it=["aria-label","placeholder","title"];for(const F of it)L[F]&&L[F].toLowerCase().trim()===B.toLowerCase().trim()&&delete L[F];Object.keys(L).length>0&&(_=Object.entries(L).map(([F,Y])=>`${F}=${w(Y,20)}`).join(" "))}const ot=u.isNew?`*[${u.highlightIndex}]`:`[${u.highlightIndex}]`;let X=`${z}${ot}<${u.tagName??""}`;if(_&&(X+=` ${_}`),u.extra&&u.extra.scrollable){let L="";(O=u.extra.scrollData)!=null&&O.left&&(L+=`left=${u.extra.scrollData.left}, `),(R=u.extra.scrollData)!=null&&R.top&&(L+=`top=${u.extra.scrollData.top}, `),(U=u.extra.scrollData)!=null&&U.right&&(L+=`right=${u.extra.scrollData.right}, `),(H=u.extra.scrollData)!=null&&H.bottom&&(L+=`bottom=${u.extra.scrollData.bottom}`),X+=` data-scrollable="${L}"`}if(B){const L=B.trim();_||(X+=" "),X+=`>${L}`}else _||(X+=" ");X+=" />",N.push(X)}for(const B of u.children)T(B,D,N)}else if(u.type==="text"){if(h(u))return;u.parent&&u.parent.type==="element"&&u.parent.isVisible&&u.parent.isTopElement&&N.push(`${z}${u.text??""}`)}},b=[];return T(l,0,b),b.join(`
|
|
2
|
-
`)}const getAllTextTillNextClickableElement=(e,n=-1)=>{const s=[],i=(w,d)=>{if(!(n!==-1&&d>n)&&!(w.type==="element"&&w!==e&&w.highlightIndex!==void 0)){if(w.type==="text"&&w.text)s.push(w.text);else if(w.type==="element")for(const r of w.children)i(r,d+1)}};return i(e,0),s.join(`
|
|
3
|
-
`).trim()};function getSelectorMap(e){const n=new Map,s=Object.keys(e.map);for(const i of s){const w=e.map[i];w.isInteractive&&typeof w.highlightIndex=="number"&&n.set(w.highlightIndex,w)}return n}function getElementTextMap(e){const n=e.split(`
|
|
4
|
-
`).map(i=>i.trim()).filter(i=>i.length>0),s=new Map;for(const i of n){const d=/^\[(\d+)\]<[^>]+>([^<]*)/.exec(i);if(d){const r=parseInt(d[1],10);s.set(r,i)}}return s}function cleanUpHighlights(){const e=window._highlightCleanupFunctions||[];for(const n of e)typeof n=="function"&&n();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 e=window.location.href;setInterval(()=>{window.location.href!==e&&(e=window.location.href,cleanUpHighlights())},500)}function getPageInfo(){const e=window.innerWidth,n=window.innerHeight,s=Math.max(document.documentElement.scrollWidth,document.body.scrollWidth||0),i=Math.max(document.documentElement.scrollHeight,document.body.scrollHeight||0),w=window.scrollX||window.pageXOffset||document.documentElement.scrollLeft||0,d=window.scrollY||window.pageYOffset||document.documentElement.scrollTop||0,r=Math.max(0,i-(window.innerHeight+d)),l=Math.max(0,s-(window.innerWidth+w));return{viewport_width:e,viewport_height:n,page_width:s,page_height:i,scroll_x:w,scroll_y:d,pixels_above:d,pixels_below:r,pages_above:n>0?d/n:0,pages_below:n>0?r/n:0,total_pages:n>0?i/n:0,current_page_position:d/Math.max(1,i-n),pixels_left:w,pixels_right:l}}function patchReact(e){const n=document.querySelectorAll('[data-reactroot], [data-reactid], [data-react-checksum], #root, #app, [id^="root-"], [id^="app-"], #adex-wrapper, #adex-root');for(const s of n)s.setAttribute("data-page-agent-not-interactive","true")}class PageController extends EventTarget{constructor(e={}){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=e,patchReact(),e.enableMask&&this.initMask()}initMask(){this.maskReady===null&&(this.maskReady=(async()=>{const{SimulatorMask:e}=await Promise.resolve().then(()=>require("./SimulatorMask-jCkPs2Tt.cjs"));this.mask=new e})())}async getCurrentUrl(){return window.location.href}async getLastUpdateTime(){return this.lastTimeUpdate}async getBrowserState(){const e=window.location.href,n=document.title,s=getPageInfo(),i=this.config.viewportExpansion??VIEWPORT_EXPANSION;await this.updateTree();const w=this.simplifiedHTML,d=`Current Page: [${n}](${e})`,r=`Page info: ${s.viewport_width}x${s.viewport_height}px viewport, ${s.page_width}x${s.page_height}px total page size, ${s.pages_above.toFixed(1)} pages above, ${s.pages_below.toFixed(1)} pages below, ${s.total_pages.toFixed(1)} total pages, at ${(s.current_page_position*100).toFixed(0)}% of page`,l=i===-1?"Interactive elements from top layer of the current page (full page):":"Interactive elements from top layer of the current page inside the viewport:",T=s.pixels_above>4&&i!==-1?`... ${s.pixels_above} pixels above (${s.pages_above.toFixed(1)} pages) - scroll to see more ...`:"[Start of page]",b=`${d}
|
|
5
|
-
${r}
|
|
6
|
-
|
|
7
|
-
${l}
|
|
8
|
-
|
|
9
|
-
${T}`,f=s.pixels_below>4&&i!==-1?`... ${s.pixels_below} pixels below (${s.pages_below.toFixed(1)} pages) - scroll to see more ...`:"[End of page]";return{url:e,title:n,header:b,content:w,footer:f}}async updateTree(){this.dispatchEvent(new Event("beforeUpdate")),this.lastTimeUpdate=Date.now(),this.mask&&(this.mask.wrapper.style.pointerEvents="none"),cleanUpHighlights();const e=[...this.config.interactiveBlacklist||[],...document.querySelectorAll("[data-page-agent-not-interactive]").values()];return this.flatTree=getFlatTree({...this.config,interactiveBlacklist:e}),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(e){try{this.assertIndexed();const n=getElementByIndex(this.selectorMap,e),s=this.elementTextMap.get(e);return await clickElement(n),n instanceof HTMLAnchorElement&&n.target==="_blank"?{success:!0,message:`✅ Clicked element (${s??e}). ⚠️ Link opens in a new tab. You are not capable of reading new tabs.`}:{success:!0,message:`✅ Clicked element (${s??e}).`}}catch(n){return{success:!1,message:`❌ Failed to click element: ${n}`}}}async inputText(e,n){try{this.assertIndexed();const s=getElementByIndex(this.selectorMap,e),i=this.elementTextMap.get(e);return await inputTextElement(s,n),{success:!0,message:`✅ Input text (${n}) into element (${i??e}).`}}catch(s){return{success:!1,message:`❌ Failed to input text: ${s}`}}}async selectOption(e,n){try{this.assertIndexed();const s=getElementByIndex(this.selectorMap,e),i=this.elementTextMap.get(e);return await selectOptionElement(s,n),{success:!0,message:`✅ Selected option (${n}) in element (${i??e}).`}}catch(s){return{success:!1,message:`❌ Failed to select option: ${s}`}}}async scroll(e){try{const{down:n,numPages:s,pixels:i,index:w}=e;this.assertIndexed();const d=i??s*(n?1:-1)*window.innerHeight,r=w!==void 0?getElementByIndex(this.selectorMap,w):null;return{success:!0,message:await scrollVertically(n,d,r)}}catch(n){return{success:!1,message:`❌ Failed to scroll: ${n}`}}}async scrollHorizontally(e){try{const{right:n,pixels:s,index:i}=e;this.assertIndexed();const w=s*(n?1:-1),d=i!==void 0?getElementByIndex(this.selectorMap,i):null;return{success:!0,message:await scrollHorizontally(n,w,d)}}catch(n){return{success:!1,message:`❌ Failed to scroll horizontally: ${n}`}}}async executeJavascript(script){try{const asyncFunction=eval(`(async () => { ${script} })`),result=await asyncFunction();return{success:!0,message:`✅ Executed JavaScript. Result: ${result}`}}catch(e){return{success:!1,message:`❌ Error executing JavaScript: ${e}`}}}async showMask(){var e;await this.maskReady,(e=this.mask)==null||e.show()}async hideMask(){var e;await this.maskReady,(e=this.mask)==null||e.hide()}dispose(){var e;cleanUpHighlights(),this.flatTree=null,this.selectorMap.clear(),this.elementTextMap.clear(),this.simplifiedHTML="<EMPTY>",this.isIndexed=!1,(e=this.mask)==null||e.dispose(),this.mask=null}}exports.PageController=PageController;
|