@shiplightai/mcp 0.1.57 → 0.1.58
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/{agentHelpers-BWIZZVR4-6SA75OLH.js → agentHelpers-JS57XP7E-NTDU7ALG.js} +1 -1
- package/dist/{chunk-RONU7WUE.js → chunk-4R7SSOTO.js} +13 -13
- package/dist/{chunk-F2VF6EGN.js → chunk-HOPRFIKM.js} +4 -4
- package/dist/{chunk-X5NUVPAF.js → chunk-LATEXF4R.js} +1 -1
- package/dist/{chunk-KG3IU2VV.js → chunk-NEBLFLPV.js} +11 -11
- package/dist/{chunk-JTLVXRYI.js → chunk-THUEPEC3.js} +228 -220
- package/dist/{chunk-GTYDC5DF.js → chunk-VTK25XN7.js} +2 -2
- package/dist/{dist-I44QS3SL.js → dist-EFYURXGQ.js} +1 -1
- package/dist/{dist-CT5TSYOS.js → dist-K3ASWHBE.js} +1 -1
- package/dist/{handler-7JPASJ4Y-KWA27ONH.js → handler-65CN5L7D-IN6OTBXK.js} +1 -1
- package/dist/index.js +2 -2
- package/dist/{relayBrowserCache-QL6LD4JJ-7EUDH6YT.js → relayBrowserCache-QL6LD4JJ-WYEVE35H.js} +1 -1
- package/dist/{server-HRQ65FLP.js → server-MMON425X.js} +2 -2
- package/dist/{task-TMX75KZR-MX73VAM2.js → task-ERIJWZDN-6R32Q2PD.js} +1 -1
- package/package.json +1 -1
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { createRequire as __createRequire } from "module";
|
|
3
3
|
const require = __createRequire(import.meta.url);
|
|
4
|
-
import{a as cu,b as lu,c as Et,d as hu,e as du,f as pu,g as fu,h as gu,i as mu,l as xu,m as Au,p as ee,s as Eu}from"./chunk-R4J6G5GI.js";import{a as ru,b as nu,d as au,g as su,h as Xt}from"./chunk-2BZVD336.js";import{a as Tt,c as Zu,d as Qu,e as Xu,f as ne,g as ae,h as se}from"./chunk-GTYDC5DF.js";import{a as ue,b as H,c as ie,d as Bu,l as re,n as Cu,o as St}from"./chunk-KG3IU2VV.js";import{a as k}from"./chunk-UBUBM7F7.js";import{A as Ku,B as Ju,E as Yu,a as Du,b as bu,c as wu,d as yu,e as Fu,f as vu,g as ku,h as Su,i as Tu,j as Lu,k as Iu,l as _u,m as Nu,n as $u,o as Ru,p as Pu,q as qu,r as Ou,s as Mu,t as Uu,u as Hu,v as ju,w as Vu,x as Wu,y as Gu,z as zu}from"./chunk-RONU7WUE.js";import{b as iu,d as c}from"./chunk-HBXQFJ2K.js";import{a as ou,c as Z,d as te}from"./chunk-ETDHHU35.js";import{c as Qt,e as Ir}from"./chunk-LM633YUO.js";var ei=Qt((_o,ti)=>{"use strict";function V(t,e){typeof e=="boolean"&&(e={forever:e}),this._originalTimeouts=JSON.parse(JSON.stringify(t)),this._timeouts=t,this._options=e||{},this._maxRetryTime=e&&e.maxRetryTime||1/0,this._fn=null,this._errors=[],this._attempts=1,this._operationTimeout=null,this._operationTimeoutCb=null,this._timeout=null,this._operationStart=null,this._timer=null,this._options.forever&&(this._cachedTimeouts=this._timeouts.slice(0))}ti.exports=V;V.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts.slice(0)};V.prototype.stop=function(){this._timeout&&clearTimeout(this._timeout),this._timer&&clearTimeout(this._timer),this._timeouts=[],this._cachedTimeouts=null};V.prototype.retry=function(t){if(this._timeout&&clearTimeout(this._timeout),!t)return!1;var e=new Date().getTime();if(t&&e-this._operationStart>=this._maxRetryTime)return this._errors.push(t),this._errors.unshift(new Error("RetryOperation timeout occurred")),!1;this._errors.push(t);var u=this._timeouts.shift();if(u===void 0)if(this._cachedTimeouts)this._errors.splice(0,this._errors.length-1),u=this._cachedTimeouts.slice(-1);else return!1;var i=this;return this._timer=setTimeout(function(){i._attempts++,i._operationTimeoutCb&&(i._timeout=setTimeout(function(){i._operationTimeoutCb(i._attempts)},i._operationTimeout),i._options.unref&&i._timeout.unref()),i._fn(i._attempts)},u),this._options.unref&&this._timer.unref(),!0};V.prototype.attempt=function(t,e){this._fn=t,e&&(e.timeout&&(this._operationTimeout=e.timeout),e.cb&&(this._operationTimeoutCb=e.cb));var u=this;this._operationTimeoutCb&&(this._timeout=setTimeout(function(){u._operationTimeoutCb()},u._operationTimeout)),this._operationStart=new Date().getTime(),this._fn(this._attempts)};V.prototype.try=function(t){console.log("Using RetryOperation.try() is deprecated"),this.attempt(t)};V.prototype.start=function(t){console.log("Using RetryOperation.start() is deprecated"),this.attempt(t)};V.prototype.start=V.prototype.try;V.prototype.errors=function(){return this._errors};V.prototype.attempts=function(){return this._attempts};V.prototype.mainError=function(){if(this._errors.length===0)return null;for(var t={},e=null,u=0,i=0;i<this._errors.length;i++){var r=this._errors[i],n=r.message,a=(t[n]||0)+1;t[n]=a,a>=u&&(e=r,u=a)}return e}});var ui=Qt(ut=>{"use strict";var _r=ei();ut.operation=function(t){var e=ut.timeouts(t);return new _r(e,{forever:t&&(t.forever||t.retries===1/0),unref:t&&t.unref,maxRetryTime:t&&t.maxRetryTime})};ut.timeouts=function(t){if(t instanceof Array)return[].concat(t);var e={retries:10,factor:2,minTimeout:1*1e3,maxTimeout:1/0,randomize:!1};for(var u in t)e[u]=t[u];if(e.minTimeout>e.maxTimeout)throw new Error("minTimeout is greater than maxTimeout");for(var i=[],r=0;r<e.retries;r++)i.push(this.createTimeout(r,e));return t&&t.forever&&!i.length&&i.push(this.createTimeout(r,e)),i.sort(function(n,a){return n-a}),i};ut.createTimeout=function(t,e){var u=e.randomize?Math.random()+1:1,i=Math.round(u*Math.max(e.minTimeout,1)*Math.pow(e.factor,t));return i=Math.min(i,e.maxTimeout),i};ut.wrap=function(t,e,u){if(e instanceof Array&&(u=e,e=null),!u){u=[];for(var i in t)typeof t[i]=="function"&&u.push(i)}for(var r=0;r<u.length;r++){var n=u[r],a=t[n];t[n]=function(o){var l=ut.operation(e),d=Array.prototype.slice.call(arguments,1),E=d.pop();d.push(function(B){l.retry(B)||(B&&(arguments[0]=l.mainError()),E.apply(this,arguments))}),l.attempt(function(){o.apply(t,d)})}.bind(t,a),t[n].options=e}}});var ri=Qt(($o,ii)=>{"use strict";ii.exports=ui()});import{createRequire as Pr}from"module";import*as ji from"fs/promises";import*as xt from"vm";import*as be from"fs/promises";import{z as si}from"zod";import{z as Q}from"zod";import rt from"fs";import ao from"os";import Bt from"path";import{chromium as Pi,firefox as so,webkit as oo}from"playwright";import*as Tr from"fs";import*as bt from"path";import*as P from"fs";import*as M from"path";import{z as qi}from"zod";import*as Wt from"fs";var ai=Ir(ri(),1);var Nr=Object.prototype.toString,$r=t=>Nr.call(t)==="[object Error]",Rr=new Set(["network error","Failed to fetch","NetworkError when attempting to fetch resource.","The Internet connection appears to be offline.","Load failed","Network request failed","fetch failed","terminated"]);function oe(t){return t&&$r(t)&&t.name==="TypeError"&&typeof t.message=="string"?t.message==="Load failed"?t.stack===void 0:Rr.has(t.message):!1}var ce=class extends Error{constructor(e){super(),e instanceof Error?(this.originalError=e,{message:e}=e):(this.originalError=new Error(e),this.originalError.stack=this.stack),this.name="AbortError",this.message=e}},ni=(t,e,u)=>{let i=u.retries-(e-1);return t.attemptNumber=e,t.retriesLeft=i,t};async function le(t,e){return new Promise((u,i)=>{e={...e},e.onFailedAttempt??=()=>{},e.shouldRetry??=()=>!0,e.retries??=10;let r=ai.default.operation(e),n=()=>{r.stop(),i(e.signal?.reason)};e.signal&&!e.signal.aborted&&e.signal.addEventListener("abort",n,{once:!0});let a=()=>{e.signal?.removeEventListener("abort",n),r.stop()};r.attempt(async s=>{try{let o=await t(s);a(),u(o)}catch(o){try{if(!(o instanceof Error))throw new TypeError(`Non-error was thrown: "${o}". You should only throw errors.`);if(o instanceof ce)throw o.originalError;if(o instanceof TypeError&&!oe(o))throw o;if(ni(o,s,e),await e.shouldRetry(o)||(r.stop(),i(o)),await e.onFailedAttempt(o),!r.retry(o))throw r.mainError()}catch(l){ni(l,s,e),a(),i(l)}}})})}import{z as Rt}from"zod";var c0=Pr(import.meta.url),qr=Z((t,e)=>{"use strict";var u=function(A){return i(A)&&!r(A)};function i(A){return!!A&&typeof A=="object"}function r(A){var C=Object.prototype.toString.call(A);return C==="[object RegExp]"||C==="[object Date]"||s(A)}var n=typeof Symbol=="function"&&Symbol.for,a=n?Symbol.for("react.element"):60103;function s(A){return A.$$typeof===a}function o(A){return Array.isArray(A)?[]:{}}function l(A,C){return C.clone!==!1&&C.isMergeableObject(A)?y(o(A),A,C):A}function d(A,C,w){return A.concat(C).map(function(S){return l(S,w)})}function E(A,C){if(!C.customMerge)return y;var w=C.customMerge(A);return typeof w=="function"?w:y}function B(A){return Object.getOwnPropertySymbols?Object.getOwnPropertySymbols(A).filter(function(C){return Object.propertyIsEnumerable.call(A,C)}):[]}function m(A){return Object.keys(A).concat(B(A))}function x(A,C){try{return C in A}catch{return!1}}function F(A,C){return x(A,C)&&!(Object.hasOwnProperty.call(A,C)&&Object.propertyIsEnumerable.call(A,C))}function b(A,C,w){var S={};return w.isMergeableObject(A)&&m(A).forEach(function($){S[$]=l(A[$],w)}),m(C).forEach(function($){F(A,$)||(x(A,$)&&w.isMergeableObject(C[$])?S[$]=E($,w)(A[$],C[$],w):S[$]=l(C[$],w))}),S}function y(A,C,w){w=w||{},w.arrayMerge=w.arrayMerge||d,w.isMergeableObject=w.isMergeableObject||u,w.cloneUnlessOtherwiseSpecified=l;var S=Array.isArray(C),$=Array.isArray(A),Y=S===$;return Y?S?w.arrayMerge(A,C,w):b(A,C,w):l(C,w)}y.all=function(A,C){if(!Array.isArray(A))throw new Error("first argument should be an array");return A.reduce(function(w,S){return y(w,S,C)},{})};var _=y;e.exports=_}),Or=Z(t=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});function e(n){return n&&typeof n=="object"&&"default"in n?n.default:n}var u=e(ou("crypto")),i=(n,a,s)=>u.createHmac(n,Buffer.from(a,"hex")).update(Buffer.from(s,"hex")).digest().toString("hex"),r=(n,a)=>u.randomBytes(n).toString(a);t.createDigest=i,t.createRandomBytes=r}),Mr=Z(t=>{"use strict";var e="ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",u=[255,255,26,27,28,29,30,31,255,255,255,255,255,255,255,255,255,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,255,255,255,255,255,255,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,255,255,255,255,255];function i(r){var n=Math.floor(r.length/5);return r.length%5===0?n:n+1}t.encode=function(r){Buffer.isBuffer(r)||(r=new Buffer(r));for(var n=0,a=0,s=0,o=0,l=new Buffer(i(r)*8);n<r.length;){var d=r[n];s>3?(o=d&255>>s,s=(s+5)%8,o=o<<s|(n+1<r.length?r[n+1]:0)>>8-s,n++):(o=d>>8-(s+5)&31,s=(s+5)%8,s===0&&n++),l[a]=e.charCodeAt(o),a++}for(n=a;n<l.length;n++)l[n]=61;return l},t.decode=function(r){var n=0,a=0,s,o=0;Buffer.isBuffer(r)||(r=new Buffer(r));for(var l=new Buffer(Math.ceil(r.length*5/8)),d=0;d<r.length&&r[d]!==61;d++){var E=r[d]-48;if(E<u.length)a=u[E],n<=3?(n=(n+5)%8,n===0?(s|=a,l[o]=s,o++,s=0):s|=255&a<<8-n):(n=(n+5)%8,s|=255&a>>>n,l[o]=s,o++,s=255&a<<8-n);else throw new Error("Invalid input - it is not base32 encoded string")}return l.slice(0,o)}}),Ur=Z(t=>{"use strict";var e=Mr();t.encode=e.encode,t.decode=e.decode}),Hr=Z(t=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});function e(n){return n&&typeof n=="object"&&"default"in n?n.default:n}var u=e(Ur()),i=(n,a)=>u.decode(n).toString(a),r=(n,a)=>u.encode(Buffer.from(n,a).toString("ascii")).toString().replace(/=/g,"");t.keyDecoder=i,t.keyEncoder=r}),jr=Z(t=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});function e(p){return Object.keys(p).map(h=>p[h])}(function(p){p.SHA1="sha1",p.SHA256="sha256",p.SHA512="sha512"})(t.HashAlgorithms||(t.HashAlgorithms={}));var u=e(t.HashAlgorithms);(function(p){p.ASCII="ascii",p.BASE64="base64",p.HEX="hex",p.LATIN1="latin1",p.UTF8="utf8"})(t.KeyEncodings||(t.KeyEncodings={}));var i=e(t.KeyEncodings);(function(p){p.HOTP="hotp",p.TOTP="totp"})(t.Strategy||(t.Strategy={}));var r=e(t.Strategy),n=()=>{throw new Error("Please provide an options.createDigest implementation.")};function a(p){return/^(\d+)$/.test(p)}function s(p,h,g){return p.length>=h?p:`${Array(h+1).join(g)}${p}`.slice(-1*h)}function o(p){let h=`otpauth://${p.type}/{labelPrefix}:{accountName}?secret={secret}{query}`,g=[];if(r.indexOf(p.type)<0)throw new Error(`Expecting options.type to be one of ${r.join(", ")}. Received ${p.type}.`);if(p.type==="hotp"){if(p.counter==null||typeof p.counter!="number")throw new Error('Expecting options.counter to be a number when options.type is "hotp".');g.push(`&counter=${p.counter}`)}return p.type==="totp"&&p.step&&g.push(`&period=${p.step}`),p.digits&&g.push(`&digits=${p.digits}`),p.algorithm&&g.push(`&algorithm=${p.algorithm.toUpperCase()}`),p.issuer&&g.push(`&issuer=${encodeURIComponent(p.issuer)}`),h.replace("{labelPrefix}",encodeURIComponent(p.issuer||p.accountName)).replace("{accountName}",encodeURIComponent(p.accountName)).replace("{secret}",p.secret).replace("{query}",g.join(""))}var l=class Oi{constructor(h={}){this._defaultOptions=Object.freeze({...h}),this._options=Object.freeze({})}create(h={}){return new Oi(h)}clone(h={}){let g=this.create({...this._defaultOptions,...h});return g.options=this._options,g}get options(){return Object.freeze({...this._defaultOptions,...this._options})}set options(h){this._options=Object.freeze({...this._options,...h})}allOptions(){return this.options}resetOptions(){this._options=Object.freeze({})}};function d(p){if(typeof p.createDigest!="function")throw new Error("Expecting options.createDigest to be a function.");if(typeof p.createHmacKey!="function")throw new Error("Expecting options.createHmacKey to be a function.");if(typeof p.digits!="number")throw new Error("Expecting options.digits to be a number.");if(!p.algorithm||u.indexOf(p.algorithm)<0)throw new Error(`Expecting options.algorithm to be one of ${u.join(", ")}. Received ${p.algorithm}.`);if(!p.encoding||i.indexOf(p.encoding)<0)throw new Error(`Expecting options.encoding to be one of ${i.join(", ")}. Received ${p.encoding}.`)}var E=(p,h,g)=>Buffer.from(h,g).toString("hex");function B(){return{algorithm:t.HashAlgorithms.SHA1,createHmacKey:E,createDigest:n,digits:6,encoding:t.KeyEncodings.ASCII}}function m(p){let h={...B(),...p};return d(h),Object.freeze(h)}function x(p){let h=p.toString(16);return s(h,16,"0")}function F(p,h){let g=Buffer.from(p,"hex"),v=g[g.length-1]&15,I=((g[v]&127)<<24|(g[v+1]&255)<<16|(g[v+2]&255)<<8|g[v+3]&255)%Math.pow(10,h);return s(String(I),h,"0")}function b(p,h,g){let v=x(h),I=g.createHmacKey(g.algorithm,p,g.encoding);return g.createDigest(g.algorithm,I,v)}function y(p,h,g){let v=g.digest||b(p,h,g);return F(v,g.digits)}function _(p,h,g,v){if(!a(p))return!1;let I=y(h,g,v);return p===I}function A(p,h,g,v,I){return o({algorithm:I.algorithm,digits:I.digits,type:t.Strategy.HOTP,accountName:p,counter:v,issuer:h,secret:g})}var C=class Mi extends l{create(h={}){return new Mi(h)}allOptions(){return m(this.options)}generate(h,g){return y(h,g,this.allOptions())}check(h,g,v){return _(h,g,v,this.allOptions())}verify(h){if(typeof h!="object")throw new Error("Expecting argument 0 of verify to be an object");return this.check(h.token,h.secret,h.counter)}keyuri(h,g,v,I){return A(h,g,v,I,this.allOptions())}};function w(p){if(typeof p=="number")return[Math.abs(p),Math.abs(p)];if(Array.isArray(p)){let[h,g]=p;if(typeof h=="number"&&typeof g=="number")return[Math.abs(h),Math.abs(g)]}throw new Error("Expecting options.window to be an number or [number, number].")}function S(p){if(d(p),w(p.window),typeof p.epoch!="number")throw new Error("Expecting options.epoch to be a number.");if(typeof p.step!="number")throw new Error("Expecting options.step to be a number.")}var $=(p,h,g)=>{let v=p.length,I=Buffer.from(p,h).toString("hex");if(v<g){let et=new Array(g-v+1).join(I);return Buffer.from(et,"hex").slice(0,g).toString("hex")}return I},Y=(p,h,g)=>{switch(p){case t.HashAlgorithms.SHA1:return $(h,g,20);case t.HashAlgorithms.SHA256:return $(h,g,32);case t.HashAlgorithms.SHA512:return $(h,g,64);default:throw new Error(`Expecting algorithm to be one of ${u.join(", ")}. Received ${p}.`)}};function ct(){return{algorithm:t.HashAlgorithms.SHA1,createDigest:n,createHmacKey:Y,digits:6,encoding:t.KeyEncodings.ASCII,epoch:Date.now(),step:30,window:0}}function lt(p){let h={...ct(),...p};return S(h),Object.freeze(h)}function ht(p,h){return Math.floor(p/h/1e3)}function vt(p,h){let g=ht(h.epoch,h.step);return y(p,g,h)}function Ge(p,h,g,v){let I=[];if(v===0)return I;for(let et=1;et<=v;et++){let Zt=h*et*g;I.push(p+Zt)}return I}function ze(p,h,g){let v=w(g),I=h*1e3;return{current:p,past:Ge(p,-1,I,v[0]),future:Ge(p,1,I,v[1])}}function Gt(p,h,g){if(!a(p))return!1;let v=vt(h,g);return p===v}function zt(p,h,g,v){let I=null;return p.some((et,Zt)=>Gt(h,g,{...v,epoch:et})?(I=Zt+1,!0):!1),I}function Kt(p,h,g){if(Gt(p,h,g))return 0;let v=ze(g.epoch,g.step,g.window),I=zt(v.past,p,h,g);return I!==null?I*-1:zt(v.future,p,h,g)}function Jt(p,h){return Math.floor(p/1e3)%h}function Ke(p,h){return h-Jt(p,h)}function Je(p,h,g,v){return o({algorithm:v.algorithm,digits:v.digits,step:v.step,type:t.Strategy.TOTP,accountName:p,issuer:h,secret:g})}var Ye=class Ui extends C{create(h={}){return new Ui(h)}allOptions(){return lt(this.options)}generate(h){return vt(h,this.allOptions())}checkDelta(h,g){return Kt(h,g,this.allOptions())}check(h,g){return typeof this.checkDelta(h,g)=="number"}verify(h){if(typeof h!="object")throw new Error("Expecting argument 0 of verify to be an object");return this.check(h.token,h.secret)}timeRemaining(){let h=this.allOptions();return Ke(h.epoch,h.step)}timeUsed(){let h=this.allOptions();return Jt(h.epoch,h.step)}keyuri(h,g,v){return Je(h,g,v,this.allOptions())}};function Ze(p){if(S(p),typeof p.keyDecoder!="function")throw new Error("Expecting options.keyDecoder to be a function.");if(p.keyEncoder&&typeof p.keyEncoder!="function")throw new Error("Expecting options.keyEncoder to be a function.")}function Qe(){return{algorithm:t.HashAlgorithms.SHA1,createDigest:n,createHmacKey:Y,digits:6,encoding:t.KeyEncodings.HEX,epoch:Date.now(),step:30,window:0}}function Xe(p){let h={...Qe(),...p};return Ze(h),Object.freeze(h)}function Yt(p,h){return h.keyEncoder(p,h.encoding)}function kt(p,h){return h.keyDecoder(p,h.encoding)}function tu(p,h){let g=h.createRandomBytes(p,h.encoding);return Yt(g,h)}function eu(p,h){return vt(kt(p,h),h)}function uu(p,h,g){return Kt(p,kt(h,g),g)}var Lr=class Hi extends Ye{create(h={}){return new Hi(h)}allOptions(){return Xe(this.options)}generate(h){return eu(h,this.allOptions())}checkDelta(h,g){return uu(h,g,this.allOptions())}encode(h){return Yt(h,this.allOptions())}decode(h){return kt(h,this.allOptions())}generateSecret(h=10){return tu(h,this.allOptions())}};t.Authenticator=Lr,t.HASH_ALGORITHMS=u,t.HOTP=C,t.KEY_ENCODINGS=i,t.OTP=l,t.STRATEGY=r,t.TOTP=Ye,t.authenticatorCheckWithWindow=uu,t.authenticatorDecoder=kt,t.authenticatorDefaultOptions=Qe,t.authenticatorEncoder=Yt,t.authenticatorGenerateSecret=tu,t.authenticatorOptionValidator=Ze,t.authenticatorOptions=Xe,t.authenticatorToken=eu,t.createDigestPlaceholder=n,t.hotpCheck=_,t.hotpCounter=x,t.hotpCreateHmacKey=E,t.hotpDefaultOptions=B,t.hotpDigestToToken=F,t.hotpKeyuri=A,t.hotpOptions=m,t.hotpOptionsValidator=d,t.hotpToken=y,t.isTokenValid=a,t.keyuri=o,t.objectValues=e,t.padStart=s,t.totpCheck=Gt,t.totpCheckByEpoch=zt,t.totpCheckWithWindow=Kt,t.totpCounter=ht,t.totpCreateHmacKey=Y,t.totpDefaultOptions=ct,t.totpEpochAvailable=ze,t.totpKeyuri=Je,t.totpOptions=lt,t.totpOptionsValidator=S,t.totpPadSecret=$,t.totpTimeRemaining=Ke,t.totpTimeUsed=Jt,t.totpToken=vt}),Vr=Z(t=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});var e=Or(),u=Hr(),i=jr(),r=new i.HOTP({createDigest:e.createDigest}),n=new i.TOTP({createDigest:e.createDigest}),a=new i.Authenticator({createDigest:e.createDigest,createRandomBytes:e.createRandomBytes,keyDecoder:u.keyDecoder,keyEncoder:u.keyEncoder});t.authenticator=a,t.hotp=r,t.totp=n}),Wr=Z(t=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});var e=Vr();Object.keys(e).forEach(function(u){u!=="default"&&Object.defineProperty(t,u,{enumerable:!0,get:function(){return e[u]}})})});async function Gr(t,e){let u=await import(t),i=Object.keys(u),r=new xt.SyntheticModule(i,function(){for(let n of i)this.setExport(n,u[n])},{context:e});return await r.link(()=>{throw new Error("Nested imports not supported in VM context")}),await r.evaluate(),r}function zr(t,e,u,i=!1){if(t[e])if(i)c.info(`Overriding existing function: ${e}`),delete t[e];else{c.error(`The name ${e} is already defined in the global scope`);return}try{let r;if(xt.isContext(t)?r=new xt.Script(u,{importModuleDynamically:async n=>Gr(n,t)}).runInContext(t):r=(0,eval)(u),typeof r!="function")throw new Error("The injected code must be a function");t[e]=r}catch(r){c.error(`Error injecting user function ${e}: ${r.message}`)}}async function E0(t,e,u=!1){try{let i=await ji.readFile(e,"utf8"),r=JSON.parse(i);c.info(`Loading ${Object.keys(r).length} user functions...`);for(let[n,a]of Object.entries(r))zr(t,n,a,u)}catch(i){throw c.error("Failed to load user functions:",i),i}}async function B0(t){try{let e=await be.readFile(t,"utf8"),u=JSON.parse(e);return c.info(`Loaded ${u.length} knowledges from file`),u}catch(e){if(e.code==="ENOENT")return c.debug("No knowledges file found"),[];throw c.error("Failed to load knowledges:",e),e}}async function C0(t){try{let e=await be.readFile(t,"utf8"),u=JSON.parse(e);return c.info(`Loaded ${u.length} knowledge mappings from file`),u}catch(e){if(e.code==="ENOENT")return c.debug("No knowledge mappings file found"),[];throw c.error("Failed to load knowledge mappings:",e),e}}async function D0(t,e){if(!t.body)throw new Error("Response body is null");let u=t.body.getReader(),i=new TextDecoder,r="";try{for(;;){let{done:n,value:a}=await u.read();if(n)break;r+=i.decode(a,{stream:!0});let s=r.split(`
|
|
4
|
+
import{a as cu,b as lu,c as Et,d as hu,e as du,f as pu,g as fu,h as gu,i as mu,l as xu,m as Au,p as ee,s as Eu}from"./chunk-R4J6G5GI.js";import{a as ru,b as nu,d as au,g as su,h as Xt}from"./chunk-2BZVD336.js";import{a as Tt,c as Zu,d as Qu,e as Xu,f as ne,g as ae,h as se}from"./chunk-VTK25XN7.js";import{a as ue,b as H,c as ie,d as Bu,l as re,n as Cu,o as St}from"./chunk-NEBLFLPV.js";import{a as k}from"./chunk-UBUBM7F7.js";import{A as Ku,B as Ju,E as Yu,a as Du,b as bu,c as wu,d as yu,e as Fu,f as vu,g as ku,h as Su,i as Tu,j as Lu,k as Iu,l as _u,m as Nu,n as $u,o as Ru,p as Pu,q as qu,r as Ou,s as Mu,t as Uu,u as Hu,v as ju,w as Vu,x as Wu,y as Gu,z as zu}from"./chunk-4R7SSOTO.js";import{b as iu,d as c}from"./chunk-HBXQFJ2K.js";import{a as ou,c as Z,d as te}from"./chunk-ETDHHU35.js";import{c as Qt,e as Ir}from"./chunk-LM633YUO.js";var ei=Qt((_o,ti)=>{"use strict";function V(t,e){typeof e=="boolean"&&(e={forever:e}),this._originalTimeouts=JSON.parse(JSON.stringify(t)),this._timeouts=t,this._options=e||{},this._maxRetryTime=e&&e.maxRetryTime||1/0,this._fn=null,this._errors=[],this._attempts=1,this._operationTimeout=null,this._operationTimeoutCb=null,this._timeout=null,this._operationStart=null,this._timer=null,this._options.forever&&(this._cachedTimeouts=this._timeouts.slice(0))}ti.exports=V;V.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts.slice(0)};V.prototype.stop=function(){this._timeout&&clearTimeout(this._timeout),this._timer&&clearTimeout(this._timer),this._timeouts=[],this._cachedTimeouts=null};V.prototype.retry=function(t){if(this._timeout&&clearTimeout(this._timeout),!t)return!1;var e=new Date().getTime();if(t&&e-this._operationStart>=this._maxRetryTime)return this._errors.push(t),this._errors.unshift(new Error("RetryOperation timeout occurred")),!1;this._errors.push(t);var u=this._timeouts.shift();if(u===void 0)if(this._cachedTimeouts)this._errors.splice(0,this._errors.length-1),u=this._cachedTimeouts.slice(-1);else return!1;var i=this;return this._timer=setTimeout(function(){i._attempts++,i._operationTimeoutCb&&(i._timeout=setTimeout(function(){i._operationTimeoutCb(i._attempts)},i._operationTimeout),i._options.unref&&i._timeout.unref()),i._fn(i._attempts)},u),this._options.unref&&this._timer.unref(),!0};V.prototype.attempt=function(t,e){this._fn=t,e&&(e.timeout&&(this._operationTimeout=e.timeout),e.cb&&(this._operationTimeoutCb=e.cb));var u=this;this._operationTimeoutCb&&(this._timeout=setTimeout(function(){u._operationTimeoutCb()},u._operationTimeout)),this._operationStart=new Date().getTime(),this._fn(this._attempts)};V.prototype.try=function(t){console.log("Using RetryOperation.try() is deprecated"),this.attempt(t)};V.prototype.start=function(t){console.log("Using RetryOperation.start() is deprecated"),this.attempt(t)};V.prototype.start=V.prototype.try;V.prototype.errors=function(){return this._errors};V.prototype.attempts=function(){return this._attempts};V.prototype.mainError=function(){if(this._errors.length===0)return null;for(var t={},e=null,u=0,i=0;i<this._errors.length;i++){var r=this._errors[i],n=r.message,a=(t[n]||0)+1;t[n]=a,a>=u&&(e=r,u=a)}return e}});var ui=Qt(ut=>{"use strict";var _r=ei();ut.operation=function(t){var e=ut.timeouts(t);return new _r(e,{forever:t&&(t.forever||t.retries===1/0),unref:t&&t.unref,maxRetryTime:t&&t.maxRetryTime})};ut.timeouts=function(t){if(t instanceof Array)return[].concat(t);var e={retries:10,factor:2,minTimeout:1*1e3,maxTimeout:1/0,randomize:!1};for(var u in t)e[u]=t[u];if(e.minTimeout>e.maxTimeout)throw new Error("minTimeout is greater than maxTimeout");for(var i=[],r=0;r<e.retries;r++)i.push(this.createTimeout(r,e));return t&&t.forever&&!i.length&&i.push(this.createTimeout(r,e)),i.sort(function(n,a){return n-a}),i};ut.createTimeout=function(t,e){var u=e.randomize?Math.random()+1:1,i=Math.round(u*Math.max(e.minTimeout,1)*Math.pow(e.factor,t));return i=Math.min(i,e.maxTimeout),i};ut.wrap=function(t,e,u){if(e instanceof Array&&(u=e,e=null),!u){u=[];for(var i in t)typeof t[i]=="function"&&u.push(i)}for(var r=0;r<u.length;r++){var n=u[r],a=t[n];t[n]=function(o){var l=ut.operation(e),d=Array.prototype.slice.call(arguments,1),E=d.pop();d.push(function(B){l.retry(B)||(B&&(arguments[0]=l.mainError()),E.apply(this,arguments))}),l.attempt(function(){o.apply(t,d)})}.bind(t,a),t[n].options=e}}});var ri=Qt(($o,ii)=>{"use strict";ii.exports=ui()});import{createRequire as Pr}from"module";import*as ji from"fs/promises";import*as xt from"vm";import*as be from"fs/promises";import{z as si}from"zod";import{z as Q}from"zod";import rt from"fs";import ao from"os";import Bt from"path";import{chromium as Pi,firefox as so,webkit as oo}from"playwright";import*as Tr from"fs";import*as bt from"path";import*as P from"fs";import*as M from"path";import{z as qi}from"zod";import*as Wt from"fs";var ai=Ir(ri(),1);var Nr=Object.prototype.toString,$r=t=>Nr.call(t)==="[object Error]",Rr=new Set(["network error","Failed to fetch","NetworkError when attempting to fetch resource.","The Internet connection appears to be offline.","Load failed","Network request failed","fetch failed","terminated"]);function oe(t){return t&&$r(t)&&t.name==="TypeError"&&typeof t.message=="string"?t.message==="Load failed"?t.stack===void 0:Rr.has(t.message):!1}var ce=class extends Error{constructor(e){super(),e instanceof Error?(this.originalError=e,{message:e}=e):(this.originalError=new Error(e),this.originalError.stack=this.stack),this.name="AbortError",this.message=e}},ni=(t,e,u)=>{let i=u.retries-(e-1);return t.attemptNumber=e,t.retriesLeft=i,t};async function le(t,e){return new Promise((u,i)=>{e={...e},e.onFailedAttempt??=()=>{},e.shouldRetry??=()=>!0,e.retries??=10;let r=ai.default.operation(e),n=()=>{r.stop(),i(e.signal?.reason)};e.signal&&!e.signal.aborted&&e.signal.addEventListener("abort",n,{once:!0});let a=()=>{e.signal?.removeEventListener("abort",n),r.stop()};r.attempt(async s=>{try{let o=await t(s);a(),u(o)}catch(o){try{if(!(o instanceof Error))throw new TypeError(`Non-error was thrown: "${o}". You should only throw errors.`);if(o instanceof ce)throw o.originalError;if(o instanceof TypeError&&!oe(o))throw o;if(ni(o,s,e),await e.shouldRetry(o)||(r.stop(),i(o)),await e.onFailedAttempt(o),!r.retry(o))throw r.mainError()}catch(l){ni(l,s,e),a(),i(l)}}})})}import{z as Rt}from"zod";var c0=Pr(import.meta.url),qr=Z((t,e)=>{"use strict";var u=function(A){return i(A)&&!r(A)};function i(A){return!!A&&typeof A=="object"}function r(A){var C=Object.prototype.toString.call(A);return C==="[object RegExp]"||C==="[object Date]"||s(A)}var n=typeof Symbol=="function"&&Symbol.for,a=n?Symbol.for("react.element"):60103;function s(A){return A.$$typeof===a}function o(A){return Array.isArray(A)?[]:{}}function l(A,C){return C.clone!==!1&&C.isMergeableObject(A)?y(o(A),A,C):A}function d(A,C,w){return A.concat(C).map(function(S){return l(S,w)})}function E(A,C){if(!C.customMerge)return y;var w=C.customMerge(A);return typeof w=="function"?w:y}function B(A){return Object.getOwnPropertySymbols?Object.getOwnPropertySymbols(A).filter(function(C){return Object.propertyIsEnumerable.call(A,C)}):[]}function m(A){return Object.keys(A).concat(B(A))}function x(A,C){try{return C in A}catch{return!1}}function F(A,C){return x(A,C)&&!(Object.hasOwnProperty.call(A,C)&&Object.propertyIsEnumerable.call(A,C))}function b(A,C,w){var S={};return w.isMergeableObject(A)&&m(A).forEach(function($){S[$]=l(A[$],w)}),m(C).forEach(function($){F(A,$)||(x(A,$)&&w.isMergeableObject(C[$])?S[$]=E($,w)(A[$],C[$],w):S[$]=l(C[$],w))}),S}function y(A,C,w){w=w||{},w.arrayMerge=w.arrayMerge||d,w.isMergeableObject=w.isMergeableObject||u,w.cloneUnlessOtherwiseSpecified=l;var S=Array.isArray(C),$=Array.isArray(A),Y=S===$;return Y?S?w.arrayMerge(A,C,w):b(A,C,w):l(C,w)}y.all=function(A,C){if(!Array.isArray(A))throw new Error("first argument should be an array");return A.reduce(function(w,S){return y(w,S,C)},{})};var _=y;e.exports=_}),Or=Z(t=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});function e(n){return n&&typeof n=="object"&&"default"in n?n.default:n}var u=e(ou("crypto")),i=(n,a,s)=>u.createHmac(n,Buffer.from(a,"hex")).update(Buffer.from(s,"hex")).digest().toString("hex"),r=(n,a)=>u.randomBytes(n).toString(a);t.createDigest=i,t.createRandomBytes=r}),Mr=Z(t=>{"use strict";var e="ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",u=[255,255,26,27,28,29,30,31,255,255,255,255,255,255,255,255,255,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,255,255,255,255,255,255,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,255,255,255,255,255];function i(r){var n=Math.floor(r.length/5);return r.length%5===0?n:n+1}t.encode=function(r){Buffer.isBuffer(r)||(r=new Buffer(r));for(var n=0,a=0,s=0,o=0,l=new Buffer(i(r)*8);n<r.length;){var d=r[n];s>3?(o=d&255>>s,s=(s+5)%8,o=o<<s|(n+1<r.length?r[n+1]:0)>>8-s,n++):(o=d>>8-(s+5)&31,s=(s+5)%8,s===0&&n++),l[a]=e.charCodeAt(o),a++}for(n=a;n<l.length;n++)l[n]=61;return l},t.decode=function(r){var n=0,a=0,s,o=0;Buffer.isBuffer(r)||(r=new Buffer(r));for(var l=new Buffer(Math.ceil(r.length*5/8)),d=0;d<r.length&&r[d]!==61;d++){var E=r[d]-48;if(E<u.length)a=u[E],n<=3?(n=(n+5)%8,n===0?(s|=a,l[o]=s,o++,s=0):s|=255&a<<8-n):(n=(n+5)%8,s|=255&a>>>n,l[o]=s,o++,s=255&a<<8-n);else throw new Error("Invalid input - it is not base32 encoded string")}return l.slice(0,o)}}),Ur=Z(t=>{"use strict";var e=Mr();t.encode=e.encode,t.decode=e.decode}),Hr=Z(t=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});function e(n){return n&&typeof n=="object"&&"default"in n?n.default:n}var u=e(Ur()),i=(n,a)=>u.decode(n).toString(a),r=(n,a)=>u.encode(Buffer.from(n,a).toString("ascii")).toString().replace(/=/g,"");t.keyDecoder=i,t.keyEncoder=r}),jr=Z(t=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});function e(p){return Object.keys(p).map(h=>p[h])}(function(p){p.SHA1="sha1",p.SHA256="sha256",p.SHA512="sha512"})(t.HashAlgorithms||(t.HashAlgorithms={}));var u=e(t.HashAlgorithms);(function(p){p.ASCII="ascii",p.BASE64="base64",p.HEX="hex",p.LATIN1="latin1",p.UTF8="utf8"})(t.KeyEncodings||(t.KeyEncodings={}));var i=e(t.KeyEncodings);(function(p){p.HOTP="hotp",p.TOTP="totp"})(t.Strategy||(t.Strategy={}));var r=e(t.Strategy),n=()=>{throw new Error("Please provide an options.createDigest implementation.")};function a(p){return/^(\d+)$/.test(p)}function s(p,h,g){return p.length>=h?p:`${Array(h+1).join(g)}${p}`.slice(-1*h)}function o(p){let h=`otpauth://${p.type}/{labelPrefix}:{accountName}?secret={secret}{query}`,g=[];if(r.indexOf(p.type)<0)throw new Error(`Expecting options.type to be one of ${r.join(", ")}. Received ${p.type}.`);if(p.type==="hotp"){if(p.counter==null||typeof p.counter!="number")throw new Error('Expecting options.counter to be a number when options.type is "hotp".');g.push(`&counter=${p.counter}`)}return p.type==="totp"&&p.step&&g.push(`&period=${p.step}`),p.digits&&g.push(`&digits=${p.digits}`),p.algorithm&&g.push(`&algorithm=${p.algorithm.toUpperCase()}`),p.issuer&&g.push(`&issuer=${encodeURIComponent(p.issuer)}`),h.replace("{labelPrefix}",encodeURIComponent(p.issuer||p.accountName)).replace("{accountName}",encodeURIComponent(p.accountName)).replace("{secret}",p.secret).replace("{query}",g.join(""))}var l=class Oi{constructor(h={}){this._defaultOptions=Object.freeze({...h}),this._options=Object.freeze({})}create(h={}){return new Oi(h)}clone(h={}){let g=this.create({...this._defaultOptions,...h});return g.options=this._options,g}get options(){return Object.freeze({...this._defaultOptions,...this._options})}set options(h){this._options=Object.freeze({...this._options,...h})}allOptions(){return this.options}resetOptions(){this._options=Object.freeze({})}};function d(p){if(typeof p.createDigest!="function")throw new Error("Expecting options.createDigest to be a function.");if(typeof p.createHmacKey!="function")throw new Error("Expecting options.createHmacKey to be a function.");if(typeof p.digits!="number")throw new Error("Expecting options.digits to be a number.");if(!p.algorithm||u.indexOf(p.algorithm)<0)throw new Error(`Expecting options.algorithm to be one of ${u.join(", ")}. Received ${p.algorithm}.`);if(!p.encoding||i.indexOf(p.encoding)<0)throw new Error(`Expecting options.encoding to be one of ${i.join(", ")}. Received ${p.encoding}.`)}var E=(p,h,g)=>Buffer.from(h,g).toString("hex");function B(){return{algorithm:t.HashAlgorithms.SHA1,createHmacKey:E,createDigest:n,digits:6,encoding:t.KeyEncodings.ASCII}}function m(p){let h={...B(),...p};return d(h),Object.freeze(h)}function x(p){let h=p.toString(16);return s(h,16,"0")}function F(p,h){let g=Buffer.from(p,"hex"),v=g[g.length-1]&15,I=((g[v]&127)<<24|(g[v+1]&255)<<16|(g[v+2]&255)<<8|g[v+3]&255)%Math.pow(10,h);return s(String(I),h,"0")}function b(p,h,g){let v=x(h),I=g.createHmacKey(g.algorithm,p,g.encoding);return g.createDigest(g.algorithm,I,v)}function y(p,h,g){let v=g.digest||b(p,h,g);return F(v,g.digits)}function _(p,h,g,v){if(!a(p))return!1;let I=y(h,g,v);return p===I}function A(p,h,g,v,I){return o({algorithm:I.algorithm,digits:I.digits,type:t.Strategy.HOTP,accountName:p,counter:v,issuer:h,secret:g})}var C=class Mi extends l{create(h={}){return new Mi(h)}allOptions(){return m(this.options)}generate(h,g){return y(h,g,this.allOptions())}check(h,g,v){return _(h,g,v,this.allOptions())}verify(h){if(typeof h!="object")throw new Error("Expecting argument 0 of verify to be an object");return this.check(h.token,h.secret,h.counter)}keyuri(h,g,v,I){return A(h,g,v,I,this.allOptions())}};function w(p){if(typeof p=="number")return[Math.abs(p),Math.abs(p)];if(Array.isArray(p)){let[h,g]=p;if(typeof h=="number"&&typeof g=="number")return[Math.abs(h),Math.abs(g)]}throw new Error("Expecting options.window to be an number or [number, number].")}function S(p){if(d(p),w(p.window),typeof p.epoch!="number")throw new Error("Expecting options.epoch to be a number.");if(typeof p.step!="number")throw new Error("Expecting options.step to be a number.")}var $=(p,h,g)=>{let v=p.length,I=Buffer.from(p,h).toString("hex");if(v<g){let et=new Array(g-v+1).join(I);return Buffer.from(et,"hex").slice(0,g).toString("hex")}return I},Y=(p,h,g)=>{switch(p){case t.HashAlgorithms.SHA1:return $(h,g,20);case t.HashAlgorithms.SHA256:return $(h,g,32);case t.HashAlgorithms.SHA512:return $(h,g,64);default:throw new Error(`Expecting algorithm to be one of ${u.join(", ")}. Received ${p}.`)}};function ct(){return{algorithm:t.HashAlgorithms.SHA1,createDigest:n,createHmacKey:Y,digits:6,encoding:t.KeyEncodings.ASCII,epoch:Date.now(),step:30,window:0}}function lt(p){let h={...ct(),...p};return S(h),Object.freeze(h)}function ht(p,h){return Math.floor(p/h/1e3)}function vt(p,h){let g=ht(h.epoch,h.step);return y(p,g,h)}function Ge(p,h,g,v){let I=[];if(v===0)return I;for(let et=1;et<=v;et++){let Zt=h*et*g;I.push(p+Zt)}return I}function ze(p,h,g){let v=w(g),I=h*1e3;return{current:p,past:Ge(p,-1,I,v[0]),future:Ge(p,1,I,v[1])}}function Gt(p,h,g){if(!a(p))return!1;let v=vt(h,g);return p===v}function zt(p,h,g,v){let I=null;return p.some((et,Zt)=>Gt(h,g,{...v,epoch:et})?(I=Zt+1,!0):!1),I}function Kt(p,h,g){if(Gt(p,h,g))return 0;let v=ze(g.epoch,g.step,g.window),I=zt(v.past,p,h,g);return I!==null?I*-1:zt(v.future,p,h,g)}function Jt(p,h){return Math.floor(p/1e3)%h}function Ke(p,h){return h-Jt(p,h)}function Je(p,h,g,v){return o({algorithm:v.algorithm,digits:v.digits,step:v.step,type:t.Strategy.TOTP,accountName:p,issuer:h,secret:g})}var Ye=class Ui extends C{create(h={}){return new Ui(h)}allOptions(){return lt(this.options)}generate(h){return vt(h,this.allOptions())}checkDelta(h,g){return Kt(h,g,this.allOptions())}check(h,g){return typeof this.checkDelta(h,g)=="number"}verify(h){if(typeof h!="object")throw new Error("Expecting argument 0 of verify to be an object");return this.check(h.token,h.secret)}timeRemaining(){let h=this.allOptions();return Ke(h.epoch,h.step)}timeUsed(){let h=this.allOptions();return Jt(h.epoch,h.step)}keyuri(h,g,v){return Je(h,g,v,this.allOptions())}};function Ze(p){if(S(p),typeof p.keyDecoder!="function")throw new Error("Expecting options.keyDecoder to be a function.");if(p.keyEncoder&&typeof p.keyEncoder!="function")throw new Error("Expecting options.keyEncoder to be a function.")}function Qe(){return{algorithm:t.HashAlgorithms.SHA1,createDigest:n,createHmacKey:Y,digits:6,encoding:t.KeyEncodings.HEX,epoch:Date.now(),step:30,window:0}}function Xe(p){let h={...Qe(),...p};return Ze(h),Object.freeze(h)}function Yt(p,h){return h.keyEncoder(p,h.encoding)}function kt(p,h){return h.keyDecoder(p,h.encoding)}function tu(p,h){let g=h.createRandomBytes(p,h.encoding);return Yt(g,h)}function eu(p,h){return vt(kt(p,h),h)}function uu(p,h,g){return Kt(p,kt(h,g),g)}var Lr=class Hi extends Ye{create(h={}){return new Hi(h)}allOptions(){return Xe(this.options)}generate(h){return eu(h,this.allOptions())}checkDelta(h,g){return uu(h,g,this.allOptions())}encode(h){return Yt(h,this.allOptions())}decode(h){return kt(h,this.allOptions())}generateSecret(h=10){return tu(h,this.allOptions())}};t.Authenticator=Lr,t.HASH_ALGORITHMS=u,t.HOTP=C,t.KEY_ENCODINGS=i,t.OTP=l,t.STRATEGY=r,t.TOTP=Ye,t.authenticatorCheckWithWindow=uu,t.authenticatorDecoder=kt,t.authenticatorDefaultOptions=Qe,t.authenticatorEncoder=Yt,t.authenticatorGenerateSecret=tu,t.authenticatorOptionValidator=Ze,t.authenticatorOptions=Xe,t.authenticatorToken=eu,t.createDigestPlaceholder=n,t.hotpCheck=_,t.hotpCounter=x,t.hotpCreateHmacKey=E,t.hotpDefaultOptions=B,t.hotpDigestToToken=F,t.hotpKeyuri=A,t.hotpOptions=m,t.hotpOptionsValidator=d,t.hotpToken=y,t.isTokenValid=a,t.keyuri=o,t.objectValues=e,t.padStart=s,t.totpCheck=Gt,t.totpCheckByEpoch=zt,t.totpCheckWithWindow=Kt,t.totpCounter=ht,t.totpCreateHmacKey=Y,t.totpDefaultOptions=ct,t.totpEpochAvailable=ze,t.totpKeyuri=Je,t.totpOptions=lt,t.totpOptionsValidator=S,t.totpPadSecret=$,t.totpTimeRemaining=Ke,t.totpTimeUsed=Jt,t.totpToken=vt}),Vr=Z(t=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});var e=Or(),u=Hr(),i=jr(),r=new i.HOTP({createDigest:e.createDigest}),n=new i.TOTP({createDigest:e.createDigest}),a=new i.Authenticator({createDigest:e.createDigest,createRandomBytes:e.createRandomBytes,keyDecoder:u.keyDecoder,keyEncoder:u.keyEncoder});t.authenticator=a,t.hotp=r,t.totp=n}),Wr=Z(t=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});var e=Vr();Object.keys(e).forEach(function(u){u!=="default"&&Object.defineProperty(t,u,{enumerable:!0,get:function(){return e[u]}})})});async function Gr(t,e){let u=await import(t),i=Object.keys(u),r=new xt.SyntheticModule(i,function(){for(let n of i)this.setExport(n,u[n])},{context:e});return await r.link(()=>{throw new Error("Nested imports not supported in VM context")}),await r.evaluate(),r}function zr(t,e,u,i=!1){if(t[e])if(i)c.info(`Overriding existing function: ${e}`),delete t[e];else{c.error(`The name ${e} is already defined in the global scope`);return}try{let r;if(xt.isContext(t)?r=new xt.Script(u,{importModuleDynamically:async n=>Gr(n,t)}).runInContext(t):r=(0,eval)(u),typeof r!="function")throw new Error("The injected code must be a function");t[e]=r}catch(r){c.error(`Error injecting user function ${e}: ${r.message}`)}}async function E0(t,e,u=!1){try{let i=await ji.readFile(e,"utf8"),r=JSON.parse(i);c.info(`Loading ${Object.keys(r).length} user functions...`);for(let[n,a]of Object.entries(r))zr(t,n,a,u)}catch(i){throw c.error("Failed to load user functions:",i),i}}async function B0(t){try{let e=await be.readFile(t,"utf8"),u=JSON.parse(e);return c.info(`Loaded ${u.length} knowledges from file`),u}catch(e){if(e.code==="ENOENT")return c.debug("No knowledges file found"),[];throw c.error("Failed to load knowledges:",e),e}}async function C0(t){try{let e=await be.readFile(t,"utf8"),u=JSON.parse(e);return c.info(`Loaded ${u.length} knowledge mappings from file`),u}catch(e){if(e.code==="ENOENT")return c.debug("No knowledge mappings file found"),[];throw c.error("Failed to load knowledge mappings:",e),e}}async function D0(t,e){if(!t.body)throw new Error("Response body is null");let u=t.body.getReader(),i=new TextDecoder,r="";try{for(;;){let{done:n,value:a}=await u.read();if(n)break;r+=i.decode(a,{stream:!0});let s=r.split(`
|
|
5
5
|
`);r=s.pop()||"";for(let o of s){let l=null;if(o.startsWith("data: "))try{let d=o.slice(6);d.trim()&&(l=JSON.parse(d))}catch(d){console.error(`Failed to parse SSE event: ${o}`,d);continue}l&&e(l)}}}finally{u.releaseLock()}}var Kr=si.object({instruction:si.string().describe('The instruction of the operation to perform. Can only include one operation. Do not inlcude element indexes just describe the element, e.g. "select the text "Hello, world!" in "Hello, world!""')});function Jr(t){t.register({name:"perform_accurate_operation",description:"Perform an operation that requires accurate interaction like dragging or interacting with a specific area of an element. Only use this action when neccecary.",schema:Kr,usesElementIndex:!1,async execute(e,u){let{instruction:i}=e,r={page:u.page,agentServices:u.agentServices,domService:u.domService},n=await Zu(i,r,{});if(n.status==="error"||!n.actionEntity)return{success:!1,actionEntity:{action_description:i,action_data:{action_name:"perform_accurate_operation",kwargs:{instruction:i}}},error:n.error||"Failed to generate action"};let{actionEntity:a}=n,s=await Qu(a,r);return{success:s.success,actionEntity:a,message:s.success?`Successfully executed action: ${a.action_data?.action_name}`:void 0,error:s.error}}})}var T;(function(t){t.Root="root",t.Text="text",t.Directive="directive",t.Comment="comment",t.Script="script",t.Style="style",t.Tag="tag",t.CDATA="cdata",t.Doctype="doctype"})(T||(T={}));function Yr(t){return t.type===T.Tag||t.type===T.Script||t.type===T.Style}var Zr=T.Root,Qr=T.Text,Xr=T.Directive,tn=T.Comment,en=T.Script,un=T.Style,rn=T.Tag,nn=T.CDATA,an=T.Doctype,Vi=class{constructor(){this.parent=null,this.prev=null,this.next=null,this.startIndex=null,this.endIndex=null}get parentNode(){return this.parent}set parentNode(t){this.parent=t}get previousSibling(){return this.prev}set previousSibling(t){this.prev=t}get nextSibling(){return this.next}set nextSibling(t){this.next=t}cloneNode(t=!1){return Ji(this,t)}},we=class extends Vi{constructor(t){super(),this.data=t}get nodeValue(){return this.data}set nodeValue(t){this.data=t}},fe=class extends we{constructor(){super(...arguments),this.type=T.Text}get nodeType(){return 3}},Wi=class extends we{constructor(){super(...arguments),this.type=T.Comment}get nodeType(){return 8}},Gi=class extends we{constructor(t,e){super(e),this.name=t,this.type=T.Directive}get nodeType(){return 1}},ye=class extends Vi{constructor(t){super(),this.children=t}get firstChild(){var t;return(t=this.children[0])!==null&&t!==void 0?t:null}get lastChild(){return this.children.length>0?this.children[this.children.length-1]:null}get childNodes(){return this.children}set childNodes(t){this.children=t}},zi=class extends ye{constructor(){super(...arguments),this.type=T.CDATA}get nodeType(){return 4}},ge=class extends ye{constructor(){super(...arguments),this.type=T.Root}get nodeType(){return 9}},Ki=class extends ye{constructor(t,e,u=[],i=t==="script"?T.Script:t==="style"?T.Style:T.Tag){super(u),this.name=t,this.attribs=e,this.type=i}get nodeType(){return 1}get tagName(){return this.name}set tagName(t){this.name=t}get attributes(){return Object.keys(this.attribs).map(t=>{var e,u;return{name:t,value:this.attribs[t],namespace:(e=this["x-attribsNamespace"])===null||e===void 0?void 0:e[t],prefix:(u=this["x-attribsPrefix"])===null||u===void 0?void 0:u[t]}})}};function Fe(t){return Yr(t)}function sn(t){return t.type===T.CDATA}function on(t){return t.type===T.Text}function cn(t){return t.type===T.Comment}function ln(t){return t.type===T.Directive}function hn(t){return t.type===T.Root}function Ji(t,e=!1){let u;if(on(t))u=new fe(t.data);else if(cn(t))u=new Wi(t.data);else if(Fe(t)){let i=e?he(t.children):[],r=new Ki(t.name,{...t.attribs},i);i.forEach(n=>n.parent=r),t.namespace!=null&&(r.namespace=t.namespace),t["x-attribsNamespace"]&&(r["x-attribsNamespace"]={...t["x-attribsNamespace"]}),t["x-attribsPrefix"]&&(r["x-attribsPrefix"]={...t["x-attribsPrefix"]}),u=r}else if(sn(t)){let i=e?he(t.children):[],r=new zi(i);i.forEach(n=>n.parent=r),u=r}else if(hn(t)){let i=e?he(t.children):[],r=new ge(i);i.forEach(n=>n.parent=r),t["x-mode"]&&(r["x-mode"]=t["x-mode"]),u=r}else if(ln(t)){let i=new Gi(t.name,t.data);t["x-name"]!=null&&(i["x-name"]=t["x-name"],i["x-publicId"]=t["x-publicId"],i["x-systemId"]=t["x-systemId"]),u=i}else throw new Error(`Not implemented yet: ${t.type}`);return u.startIndex=t.startIndex,u.endIndex=t.endIndex,t.sourceCodeLocation!=null&&(u.sourceCodeLocation=t.sourceCodeLocation),u}function he(t){let e=t.map(u=>Ji(u,!0));for(let u=1;u<e.length;u++)e[u].prev=e[u-1],e[u-1].next=e[u];return e}var oi={withStartIndices:!1,withEndIndices:!1,xmlMode:!1},dn=class{constructor(t,e,u){this.dom=[],this.root=new ge(this.dom),this.done=!1,this.tagStack=[this.root],this.lastNode=null,this.parser=null,typeof e=="function"&&(u=e,e=oi),typeof t=="object"&&(e=t,t=void 0),this.callback=t??null,this.options=e??oi,this.elementCB=u??null}onparserinit(t){this.parser=t}onreset(){this.dom=[],this.root=new ge(this.dom),this.done=!1,this.tagStack=[this.root],this.lastNode=null,this.parser=null}onend(){this.done||(this.done=!0,this.parser=null,this.handleCallback(null))}onerror(t){this.handleCallback(t)}onclosetag(){this.lastNode=null;let t=this.tagStack.pop();this.options.withEndIndices&&(t.endIndex=this.parser.endIndex),this.elementCB&&this.elementCB(t)}onopentag(t,e){let u=this.options.xmlMode?T.Tag:void 0,i=new Ki(t,e,void 0,u);this.addNode(i),this.tagStack.push(i)}ontext(t){let{lastNode:e}=this;if(e&&e.type===T.Text)e.data+=t,this.options.withEndIndices&&(e.endIndex=this.parser.endIndex);else{let u=new fe(t);this.addNode(u),this.lastNode=u}}oncomment(t){if(this.lastNode&&this.lastNode.type===T.Comment){this.lastNode.data+=t;return}let e=new Wi(t);this.addNode(e),this.lastNode=e}oncommentend(){this.lastNode=null}oncdatastart(){let t=new fe(""),e=new zi([t]);this.addNode(e),t.parent=e,this.lastNode=t}oncdataend(){this.lastNode=null}onprocessinginstruction(t,e){let u=new Gi(t,e);this.addNode(u)}handleCallback(t){if(typeof this.callback=="function")this.callback(t,this.dom);else if(t)throw t}addNode(t){let e=this.tagStack[this.tagStack.length-1],u=e.children[e.children.length-1];this.options.withStartIndices&&(t.startIndex=this.parser.startIndex),this.options.withEndIndices&&(t.endIndex=this.parser.endIndex),e.children.push(t),u&&(t.prev=u,u.next=t),t.parent=e,this.lastNode=null}},pn=/\n/g;function fn(t){let e=[...t.matchAll(pn)].map(i=>i.index||0);e.unshift(-1);let u=me(e,0,e.length);return i=>Yi(u,i)}function me(t,e,u){if(u-e==1)return{offset:t[e],index:e+1};let i=Math.ceil((e+u)/2),r=me(t,e,i),n=me(t,i,u);return{offset:r.offset,low:r,high:n}}function Yi(t,e){return function(u){return Object.prototype.hasOwnProperty.call(u,"index")}(t)?{line:t.index,column:e-t.offset}:Yi(t.high.offset<e?t.high:t.low,e)}function Zi(t,e="",u={}){let i=typeof e!="string"?e:u,r=typeof e=="string"?e:"",n=t.map(gn),a=!!i.lineNumbers;return function(s,o=0){let l=a?fn(s):()=>({line:0,column:0}),d=o,E=[];t:for(;d<s.length;){let B=!1;for(let m of n){m.regex.lastIndex=d;let x=m.regex.exec(s);if(x&&x[0].length>0){if(!m.discard){let F=l(d),b=typeof m.replace=="string"?x[0].replace(new RegExp(m.regex.source,m.regex.flags),m.replace):x[0];E.push({state:r,name:m.name,text:b,offset:d,len:x[0].length,line:F.line,column:F.column})}if(d=m.regex.lastIndex,B=!0,m.push){let F=m.push(s,d);E.push(...F.tokens),d=F.offset}if(m.pop)break t;break}}if(!B)break}return{tokens:E,offset:d,complete:s.length<=d}}}function gn(t,e){return{...t,regex:mn(t,e)}}function mn(t,e){if(t.name.length===0)throw new Error(`Rule #${e} has empty name, which is not allowed.`);if(function(u){return Object.prototype.hasOwnProperty.call(u,"regex")}(t))return function(u){if(u.global)throw new Error(`Regular expression /${u.source}/${u.flags} contains the global flag, which is not allowed.`);return u.sticky?u:new RegExp(u.source,u.flags+"y")}(t.regex);if(function(u){return Object.prototype.hasOwnProperty.call(u,"str")}(t)){if(t.str.length===0)throw new Error(`Rule #${e} ("${t.name}") has empty "str" property, which is not allowed.`);return new RegExp(ci(t.str),"y")}return new RegExp(ci(t.name),"y")}function ci(t){return t.replace(/[-[\]{}()*+!<=:?./\\^$|#\s,]/g,"\\$&")}function tt(t,e){return(u,i)=>{let r=i,n;return i<u.tokens.length?(n=t(u.tokens[i],u,i),n!==void 0&&r++):e?.(u,i),n===void 0?{matched:!1}:{matched:!0,position:r,value:n}}}function ve(t,e){return t.matched?{matched:!0,position:t.position,value:e(t.value,t.position)}:t}function Ot(t,e){return t.matched?e(t):t}function O(t,e){return(u,i)=>ve(t(u,i),(r,n)=>e(r,u,i,n))}function Mt(t,e){return(u,i)=>{let r=t(u,i);return r.matched?r:{matched:!0,position:i,value:e}}}function Ht(...t){return(e,u)=>{for(let i of t){let r=i(e,u);if(r.matched)return r}return{matched:!1}}}function ot(t,e){return(u,i)=>{let r=t(u,i);return r.matched?r:e(u,i)}}function xn(t,e){return(u,i)=>{let r=[],n=!0;do{let a=t(u,i);a.matched&&e(a.value,r.length+1,u,i,a.position)?(r.push(a.value),i=a.position):n=!1}while(n);return{matched:!0,position:i,value:r}}}function ke(t){return xn(t,()=>!0)}function An(t){return U(t,ke(t),(e,u)=>[e,...u])}function U(t,e,u){return(i,r)=>Ot(t(i,r),n=>ve(e(i,n.position),(a,s)=>u(n.value,a,i,r,s)))}function En(t,e){return U(t,e,u=>u)}function li(t,e){return U(t,e,(u,i)=>i)}function Se(t,e,u,i){return(r,n)=>Ot(t(r,n),a=>Ot(e(r,a.position),s=>ve(u(r,s.position),(o,l)=>i(a.value,s.value,o,r,n,l))))}function Qi(t,e,u){return Se(t,e,u,(i,r)=>r)}function Bn(...t){return(e,u)=>{let i=[],r=u;for(let n of t){let a=n(e,r);if(a.matched)i.push(a.value),r=a.position;else return{matched:!1}}return{matched:!0,position:r,value:i}}}function Cn(...t){return Dn(Bn(...t))}function Dn(t){return O(t,e=>e.flatMap(u=>u))}function bn(t,e){return(u,i)=>{let r=!0,n=t,a=i;do{let s=e(n,u,a)(u,a);s.matched?(n=s.value,a=s.position):r=!1}while(r);return{matched:!0,position:a,value:n}}}function wn(t,e,u){return bn(t,i=>O(e,(r,n,a,s)=>u(i,r,n,a,s)))}function Xi(t,e,u){return yn(t,i=>wn(i,U(e,u,(r,n)=>[r,n]),(r,[n,a])=>n(r,a)))}function yn(t,e){return(u,i)=>Ot(t(u,i),r=>e(r.value,u,i,r.position)(u,r.position))}var Fn="(?:[ \\t\\r\\n\\f]*)",tr="(?:\\n|\\r\\n|\\r|\\f)",jt="[^\\x00-\\x7F]",wt="(?:\\\\[0-9a-f]{1,6}(?:\\r\\n|[ \\n\\r\\t\\f])?)",yt="(?:\\\\[^\\n\\r\\f0-9a-f])",vn=`(?:[_a-z]|${jt}|${wt}|${yt})`,er=`(?:[_a-z0-9-]|${jt}|${wt}|${yt})`,kn=`(?:${er}+)`,Sn=`(?:[-]?${vn}${er}*)`,Tn=`'([^\\n\\r\\f\\\\']|\\\\${tr}|${jt}|${wt}|${yt})*'`,Ln=`"([^\\n\\r\\f\\\\"]|\\\\${tr}|${jt}|${wt}|${yt})*"`,In=Zi([{name:"ws",regex:new RegExp(Fn)},{name:"hash",regex:new RegExp(`#${kn}`,"i")},{name:"ident",regex:new RegExp(Sn,"i")},{name:"str1",regex:new RegExp(Tn,"i")},{name:"str2",regex:new RegExp(Ln,"i")},{name:"*"},{name:"."},{name:","},{name:"["},{name:"]"},{name:"="},{name:">"},{name:"|"},{name:"+"},{name:"~"},{name:"^"},{name:"$"}]),_n=Zi([{name:"unicode",regex:new RegExp(wt,"i")},{name:"escape",regex:new RegExp(yt,"i")},{name:"any",regex:new RegExp("[\\s\\S]","i")}]);function ur([t,e,u],[i,r,n]){return[t+i,e+r,u+n]}function Nn(t){return t.reduce(ur,[0,0,0])}var $n=tt(t=>t.name==="unicode"?String.fromCodePoint(parseInt(t.text.slice(1),16)):void 0),Rn=tt(t=>t.name==="escape"?t.text.slice(1):void 0),Pn=tt(t=>t.name==="any"?t.text:void 0),qn=O(ke(Ht($n,Rn,Pn)),t=>t.join(""));function Te(t){let e=_n(t);return qn({tokens:e.tokens,options:void 0},0).value}function N(t){return tt(e=>e.name===t?!0:void 0)}var Le=tt(t=>t.name==="ws"?null:void 0),xe=Mt(Le,null);function ft(t){return Qi(xe,t,xe)}var Dt=tt(t=>t.name==="ident"?Te(t.text):void 0),On=tt(t=>t.name==="hash"?Te(t.text.slice(1)):void 0),Mn=tt(t=>t.name.startsWith("str")?Te(t.text.slice(1,-1)):void 0),ir=En(Mt(Dt,""),N("|")),Ie=ot(U(ir,Dt,(t,e)=>({name:e,namespace:t})),O(Dt,t=>({name:t,namespace:null}))),Un=ot(U(ir,N("*"),t=>({type:"universal",namespace:t,specificity:[0,0,0]})),O(N("*"),()=>({type:"universal",namespace:null,specificity:[0,0,0]}))),Hn=O(Ie,({name:t,namespace:e})=>({type:"tag",name:t,namespace:e,specificity:[0,0,1]})),jn=U(N("."),Dt,(t,e)=>({type:"class",name:e,specificity:[0,1,0]})),Vn=O(On,t=>({type:"id",name:t,specificity:[1,0,0]})),hi=tt(t=>{if(t.name==="ident"){if(t.text==="i"||t.text==="I")return"i";if(t.text==="s"||t.text==="S")return"s"}}),Wn=ot(U(Mn,Mt(li(xe,hi),null),(t,e)=>({value:t,modifier:e})),U(Dt,Mt(li(Le,hi),null),(t,e)=>({value:t,modifier:e}))),Gn=Ht(O(N("="),()=>"="),U(N("~"),N("="),()=>"~="),U(N("|"),N("="),()=>"|="),U(N("^"),N("="),()=>"^="),U(N("$"),N("="),()=>"$="),U(N("*"),N("="),()=>"*=")),zn=Se(N("["),ft(Ie),N("]"),(t,{name:e,namespace:u})=>({type:"attrPresence",name:e,namespace:u,specificity:[0,1,0]})),Kn=Qi(N("["),Se(ft(Ie),Gn,ft(Wn),({name:t,namespace:e},u,{value:i,modifier:r})=>({type:"attrValue",name:t,namespace:e,matcher:u,value:i,modifier:r,specificity:[0,1,0]})),N("]")),Jn=ot(zn,Kn),Yn=ot(Un,Hn),di=Ht(Vn,jn,Jn),pi=O(ot(Cn(Yn,ke(di)),An(di)),t=>({type:"compound",list:t,specificity:Nn(t.map(e=>e.specificity))})),Zn=Ht(O(N(">"),()=>">"),O(N("+"),()=>"+"),O(N("~"),()=>"~"),U(N("|"),N("|"),()=>"||")),Qn=ot(ft(Zn),O(Le,()=>" ")),Ae=Xi(pi,O(Qn,t=>(e,u)=>({type:"compound",list:[...u.list,{type:"combinator",combinator:t,left:e,specificity:e.specificity}],specificity:ur(e.specificity,u.specificity)})),pi),y0=Xi(O(Ae,t=>({type:"list",list:[t]})),O(ft(N(",")),()=>(t,e)=>({type:"list",list:[...t.list,e]})),Ae);function Xn(t,e){if(!(typeof e=="string"||e instanceof String))throw new Error("Expected a selector string. Actual input is not a string!");let u=In(e);if(!u.complete)throw new Error(`The input "${e}" was only partially tokenized, stopped at offset ${u.offset}!
|
|
6
6
|
`+fi(e,u.offset));let i=ft(t)({tokens:u.tokens,options:void 0},0);if(!i.matched)throw new Error(`No match for "${e}" input!`);if(i.position<u.tokens.length){let r=u.tokens[i.position];throw new Error(`The input "${e}" was only partially parsed, stopped at offset ${r.offset}!
|
|
7
7
|
`+fi(e,r.offset,r.len))}return i.value}function fi(t,e,u=1){return`${t.replace(/(\t)|(\r)|(\n)/g,(i,r,n)=>r?"\u2409":n?"\u240D":"\u240A")}
|
|
@@ -97,10 +97,10 @@ To: ${B.to}
|
|
|
97
97
|
Date: ${B.date}
|
|
98
98
|
|
|
99
99
|
Body:
|
|
100
|
-
${B.body}`,x=await Zs(m,r,e.model);c.info(`Extracted content: ${x}`),x&&x!=="NOT_FOUND"&&E.push({content:x,email_subject:B.subject,email_from:B.from,email_date:B.date})}if(E.length>0){let B=E[0],m=`$email_${e.extraction_type}`;e.extraction_type==="custom"?m="$email_extracted_content":e.extraction_type==="activation_link"?m="$email_magic_link":e.extraction_type==="verification_code"&&(m="$email_otp_code");let x=(new Date().getTime()-n.getTime())/1e3;return c.info(`Successfully extracted content after ${s} attempts in ${x.toFixed(1)} seconds`),{data:B.content,result_variable:m,status:"success",message:`Successfully extracted content from email: ${B.email_subject.substring(0,50)}... (attempts: ${s})`}}else c.info(`Found emails but no extractable content in attempt ${s}`)}else c.info(`No emails found in attempt ${s}`)}catch(l){c.warn(`Error in polling attempt ${s}: ${l.message}`)}if(new Date(Date.now()+i*1e3)>=a){c.info("Not enough time for another polling attempt");break}c.info(`Waiting ${i} seconds before next attempt...`),await new Promise(l=>setTimeout(l,i*1e3))}let o=(new Date().getTime()-n.getTime())/1e3;return{data:void 0,status:"error",message:`No emails with extractable content found after ${s} attempts over ${o.toFixed(1)} seconds`}}catch(r){return c.error(`Error extracting email content: ${r.message}`),{data:void 0,status:"error",message:`Error extracting email content: ${r.message}`}}}function Sr(t){switch(t){case"verification_code":return"email_otp_code";case"activation_link":return"email_magic_link";case"custom":return"email_extracted_content";default:return"email_content"}}var Xs=class{getMailgunConfig(){let t=iu().env||{};if(t.MAILGUN_API_KEY)return{apiKey:t.MAILGUN_API_KEY,domain:t.MAILGUN_DOMAIN||""}}async execute(t,e,u){let i=e.action_data;if(!i)throw new Error("Action data not found");let r=this.getMailgunConfig();if(!r)throw new Error("Mailgun configuration not provided. Please configure MAILGUN_API_KEY and MAILGUN_DOMAIN in SDK config.");let n=i.kwargs,a=u.getModel?.()||"gemini-2.5-pro",s=await Qs(r,{model:a,forward_email:n.forward_email,extraction_type:n.extraction_type,prompt:n.prompt,filters:{from_email:n.filter_from_email,to_email:n.filter_to_email,subject:n.filter_subject,body_contains:n.filter_body_contains},timeout:n.timeout});if(s.status==="success"&&s.data){let o=s.result_variable?.replace(/^\$/,"")||Sr(n.extraction_type);u.variableStore.set(o,s.data),c.info(`[extract_email_content] Extracted and saved to ${o}`)}else throw new Error(s.message||"Failed to extract email content")}transpile(t){let e=t.action_data?.kwargs||{};return['await agent.execAction("extract_email_content", page, {',` action_data: { kwargs: ${JSON.stringify(e)} },`,"});"]}},to=Q.object({forward_email:Q.string().describe("Email address where emails are forwarded to (Mailgun inbox)"),extraction_type:Q.enum(["verification_code","activation_link","custom"]).describe("Type of content to extract: verification_code for OTP codes, activation_link for magic links, custom for custom prompts"),prompt:Q.string().optional().describe("Custom extraction prompt (required when extraction_type is custom)"),filter_from_email:Q.string().optional().describe("Filter emails by sender address"),filter_to_email:Q.string().optional().describe("Filter emails by recipient address"),filter_subject:Q.string().optional().describe("Filter emails by subject (partial match)"),filter_body_contains:Q.string().optional().describe("Filter emails by body content (partial match)"),timeout:Q.number().optional().describe("Timeout in seconds for polling (default: 60)")});function eo(t,e){t.register({name:"extract_email_content",description:"Extract verification codes, magic links, or custom content from emails received via Mailgun. Polls the Mailgun inbox for matching emails and uses AI to extract the requested content.",schema:to,async execute(u,i){let{forward_email:r,extraction_type:n,prompt:a,filter_from_email:s,filter_to_email:o,filter_subject:l,filter_body_contains:d,timeout:E}=u,{page:B,agentServices:m}=i;c.info(`[extract_email_content] Extracting ${n} from ${r}`);try{let x={action_description:`Extract ${n} from email`,action_data:{action_name:"extract_email_content",kwargs:{forward_email:r,extraction_type:n,prompt:a,filter_from_email:s,filter_to_email:o,filter_subject:l,filter_body_contains:d,timeout:E}}};await e.execute(B,x,m);let F=Sr(n);return{success:!0,actionEntity:x,message:`Extracted ${n} and saved to $${F}`}}catch(x){return{success:!1,error:x.message,actionEntity:{action_description:`Extract ${n} from email (failed)`,action_data:{action_name:"extract_email_content",kwargs:{forward_email:r,extraction_type:n,prompt:a,filter_from_email:s,filter_to_email:o,filter_subject:l,filter_body_contains:d,timeout:E}},feedback:x.message}}}}})}var $t=null;async function J(){if($t)return $t;let t=(await import("./handler-
|
|
100
|
+
${B.body}`,x=await Zs(m,r,e.model);c.info(`Extracted content: ${x}`),x&&x!=="NOT_FOUND"&&E.push({content:x,email_subject:B.subject,email_from:B.from,email_date:B.date})}if(E.length>0){let B=E[0],m=`$email_${e.extraction_type}`;e.extraction_type==="custom"?m="$email_extracted_content":e.extraction_type==="activation_link"?m="$email_magic_link":e.extraction_type==="verification_code"&&(m="$email_otp_code");let x=(new Date().getTime()-n.getTime())/1e3;return c.info(`Successfully extracted content after ${s} attempts in ${x.toFixed(1)} seconds`),{data:B.content,result_variable:m,status:"success",message:`Successfully extracted content from email: ${B.email_subject.substring(0,50)}... (attempts: ${s})`}}else c.info(`Found emails but no extractable content in attempt ${s}`)}else c.info(`No emails found in attempt ${s}`)}catch(l){c.warn(`Error in polling attempt ${s}: ${l.message}`)}if(new Date(Date.now()+i*1e3)>=a){c.info("Not enough time for another polling attempt");break}c.info(`Waiting ${i} seconds before next attempt...`),await new Promise(l=>setTimeout(l,i*1e3))}let o=(new Date().getTime()-n.getTime())/1e3;return{data:void 0,status:"error",message:`No emails with extractable content found after ${s} attempts over ${o.toFixed(1)} seconds`}}catch(r){return c.error(`Error extracting email content: ${r.message}`),{data:void 0,status:"error",message:`Error extracting email content: ${r.message}`}}}function Sr(t){switch(t){case"verification_code":return"email_otp_code";case"activation_link":return"email_magic_link";case"custom":return"email_extracted_content";default:return"email_content"}}var Xs=class{getMailgunConfig(){let t=iu().env||{};if(t.MAILGUN_API_KEY)return{apiKey:t.MAILGUN_API_KEY,domain:t.MAILGUN_DOMAIN||""}}async execute(t,e,u){let i=e.action_data;if(!i)throw new Error("Action data not found");let r=this.getMailgunConfig();if(!r)throw new Error("Mailgun configuration not provided. Please configure MAILGUN_API_KEY and MAILGUN_DOMAIN in SDK config.");let n=i.kwargs,a=u.getModel?.()||"gemini-2.5-pro",s=await Qs(r,{model:a,forward_email:n.forward_email,extraction_type:n.extraction_type,prompt:n.prompt,filters:{from_email:n.filter_from_email,to_email:n.filter_to_email,subject:n.filter_subject,body_contains:n.filter_body_contains},timeout:n.timeout});if(s.status==="success"&&s.data){let o=s.result_variable?.replace(/^\$/,"")||Sr(n.extraction_type);u.variableStore.set(o,s.data),c.info(`[extract_email_content] Extracted and saved to ${o}`)}else throw new Error(s.message||"Failed to extract email content")}transpile(t){let e=t.action_data?.kwargs||{};return['await agent.execAction("extract_email_content", page, {',` action_data: { kwargs: ${JSON.stringify(e)} },`,"});"]}},to=Q.object({forward_email:Q.string().describe("Email address where emails are forwarded to (Mailgun inbox)"),extraction_type:Q.enum(["verification_code","activation_link","custom"]).describe("Type of content to extract: verification_code for OTP codes, activation_link for magic links, custom for custom prompts"),prompt:Q.string().optional().describe("Custom extraction prompt (required when extraction_type is custom)"),filter_from_email:Q.string().optional().describe("Filter emails by sender address"),filter_to_email:Q.string().optional().describe("Filter emails by recipient address"),filter_subject:Q.string().optional().describe("Filter emails by subject (partial match)"),filter_body_contains:Q.string().optional().describe("Filter emails by body content (partial match)"),timeout:Q.number().optional().describe("Timeout in seconds for polling (default: 60)")});function eo(t,e){t.register({name:"extract_email_content",description:"Extract verification codes, magic links, or custom content from emails received via Mailgun. Polls the Mailgun inbox for matching emails and uses AI to extract the requested content.",schema:to,async execute(u,i){let{forward_email:r,extraction_type:n,prompt:a,filter_from_email:s,filter_to_email:o,filter_subject:l,filter_body_contains:d,timeout:E}=u,{page:B,agentServices:m}=i;c.info(`[extract_email_content] Extracting ${n} from ${r}`);try{let x={action_description:`Extract ${n} from email`,action_data:{action_name:"extract_email_content",kwargs:{forward_email:r,extraction_type:n,prompt:a,filter_from_email:s,filter_to_email:o,filter_subject:l,filter_body_contains:d,timeout:E}}};await e.execute(B,x,m);let F=Sr(n);return{success:!0,actionEntity:x,message:`Extracted ${n} and saved to $${F}`}}catch(x){return{success:!1,error:x.message,actionEntity:{action_description:`Extract ${n} from email (failed)`,action_data:{action_name:"extract_email_content",kwargs:{forward_email:r,extraction_type:n,prompt:a,filter_from_email:s,filter_to_email:o,filter_subject:l,filter_body_contains:d,timeout:E}},feedback:x.message}}}}})}var $t=null;async function J(){if($t)return $t;let t=(await import("./handler-65CN5L7D-IN6OTBXK.js")).default;return $t=new t,$t}async function Re(t){let e=await J(),u=e.getAction("click"),i=e.getAction("hover"),r=e.getAction("right_click"),n=e.getAction("double_click");return Ju(t,u),Mu(t,i),Iu(t,r),Vu(t,n),"Click, hover, double-click, right-click, or drag elements"}async function Pe(t){let e=await J(),u=e.getAction("go_to_url"),i=e.getAction("go_back"),r=e.getAction("reload_page");return Ou(t,u),qu(t,i),Lu(t,r),"Navigate to URLs, go back, or reload the page"}async function qe(t){let e=await J(),u=e.getAction("clear_input"),i=e.getAction("input_text"),r=e.getAction("press");return Ku(t,u),Uu(t,i),Tu(t,r),"Type text into inputs, clear input values, or press keyboard keys"}async function Oe(t){let e=await J(),u=e.getAction("scroll_on_element"),i=e.getAction("scroll_to_text"),r=e.getAction("scroll");return $u(t,u),Ru(t,i),Nu(t,r),"Scroll the page or scroll to specific text/elements"}async function Me(t){let e=await J(),u=e.getAction("close_tab"),i=e.getAction("switch_tab");return Hu(t,u),yu(t,i),"Switch between browser tabs or close tabs"}async function Ue(t){let e=await J(),u=e.getAction("upload_file"),i=e.getAction("wait_for_download_complete");return vu(t,u),Su(t,i),"Upload files or wait for downloads to complete"}async function He(t){let e=await J(),u=e.getAction("get_dropdown_options"),i=e.getAction("select_dropdown_option"),r=e.getAction("set_date_for_native_date_picker");return Pu(t,u),bu(t,i),wu(t,r),"Get dropdown options, select dropdown values, or set date for native date picker input"}async function je(t){let e=await J(),u=e.getAction("wait"),i=e.getAction("save_variable"),r=e.getAction("done");return ku(t,u),_u(t,i),ju(t,r),Jr(t),"Wait for conditions, save variables, or complete tasks"}async function Ve(t){let e=(await J()).getAction("generate_2fa_code");Wu(t,e);let u=new Xs;return(await import("./handler-65CN5L7D-IN6OTBXK.js")).default.registerAction("extract_email_content",u),eo(t,u),"Generate 2FA codes or extract email/activation codes"}async function We(t){let e=await J(),u=e.getAction("verify"),i=e.getAction("ai_extract"),r=e.getAction("ai_wait_until");return Gu(t,u),zu(t,i),Du(t,r),"Perform AI-powered assertions, extractions, or wait conditions"}async function uo(t){let[e,u,i,r,n,a,s,o,l,d]=await Promise.all([Re(t),Pe(t),qe(t),Oe(t),Me(t),Ue(t),He(t),je(t),Ve(t),We(t)]);return{mouse:e,navigation:u,input:i,scroll:r,tabs:n,files:a,forms:s,utility:o,auth:l,ai:d}}function io(t){return[`- Mouse: ${t.mouse}`,`- Navigation: ${t.navigation}`,`- Input: ${t.input}`,`- Scroll: ${t.scroll}`,`- Tabs: ${t.tabs}`,`- Files: ${t.files}`,`- Forms: ${t.forms}`,`- Utility: ${t.utility}`,`- Auth: ${t.auth}`,`- AI: ${t.ai}`].join(`
|
|
101
101
|
`)}var ro=[Re(H),Pe(H),qe(H),Oe(H),Me(H),Ue(H),He(H),je(H),We(H),Ve(H)],no=Promise.all(ro);async function L0(){await no}function I0(){return H}function _0(t=!0){let e=new ue;return t&&(Re(e),Pe(e),qe(e),Oe(e),Me(e),Ue(e),He(e),Ve(e),je(e),We(e)),e}async function N0(){let t=new ue,e=await uo(t),u=io(e);return{registry:t,capabilities:e,summary:u}}function $0(){return["- Mouse: Click, hover, double-click, right-click or drag on elements","- Navigation: Navigate to URLs, go back, or reload the page","- Input: Type text into inputs, clear input fields, or press keyboard keys","- Scroll: Scroll the page or scroll to specific text/elements","- Tabs: Switch between browser tabs or close tabs","- Files: Upload files or wait for downloads to complete","- Forms: Get dropdown options or select dropdown values","- Utility: Wait for conditions, save variables, or complete tasks","- Auth: Generate 2FA codes or extract email/activation codes","- AI: Perform AI-powered verifications, extractions, or wait conditions"].join(`
|
|
102
102
|
`)}var R0=class{constructor(t,e){this.registry=t,this.getContext=e}getToolDefinitions(){return this.registry.getTools().filter(t=>t.availability.mcp).map(t=>({name:t.name,description:t.description,inputSchema:Tt(t.schema)}))}getToolDefinitionsFiltered(t){let e=new Set(t);return this.registry.getTools().filter(u=>e.has(u.name)&&u.availability.mcp).map(u=>({name:u.name,description:u.description,inputSchema:Tt(u.schema)}))}async createServer(t="web-sdk-tools"){throw new Error("MCP server creation not yet implemented. Install and configure an MCP SDK like @modelcontextprotocol/sdk")}async executeTool(t,e){let u=await this.getContext(),i=await this.registry.execute(t,e,u);return{content:[{type:"text",text:i.success?i.message||"Tool executed successfully":i.error||"Tool execution failed"}]}}getToolCount(){return this.registry.size()}getToolNames(){return this.registry.getToolNames()}};function P0(t){return t.getTools().map(e=>({name:e.name,description:e.description,inputSchema:Tt(e.schema)}))}async function co(t,e){let u=JSON.parse(rt.readFileSync(e,"utf-8"));u.cookies?.length&&await t.addCookies(u.cookies)}var H0=class{constructor(t={}){t.testDir&&(this.testDir=t.testDir,this.videoBasePath=Bt.join(t.testDir,"videos"),this.statesBasePath=Bt.join(t.testDir,"states"),this.downloadsBasePath=Bt.join(t.testDir,"downloads"),rt.mkdirSync(this.videoBasePath,{recursive:!0}),rt.mkdirSync(this.statesBasePath,{recursive:!0}),rt.mkdirSync(this.downloadsBasePath,{recursive:!0})),this.terminationTimeout=t.terminationTimeout??null,this.defaultHeadless=t.headless??!1,this.additionalArgs=t.additionalArgs??[]}async launchBrowser(t={}){let e=t.debugPort,u=t.headless??this.defaultHeadless,i=mu(t.deviceName),r=gu(t.deviceName),n=i===Et.Chromium,a=!!t.extensionPath;c.info(`[BrowserManager] Launching ${i} browser for device: ${t.deviceName||"default"}${e?` on port ${e}`:""}`);let s={headless:u};if(n){a&&u&&(c.warn("[BrowserManager] Extension requested in headless mode; forcing headed mode to load extension."),u=!1,s.headless=!1);let C=[];(t.enableCamera||t.enableMicrophone)&&(C.push("--use-fake-device-for-media-stream","--use-fake-ui-for-media-stream"),t.enableMicrophone&&t.fakeAudioCapturePath&&(C.push(`--use-file-for-fake-audio-capture=${t.fakeAudioCapturePath}`),c.info(`[BrowserManager] Using fake audio capture file: ${t.fakeAudioCapturePath}`)));let w=a&&t.extensionPath?[`--disable-extensions-except=${t.extensionPath}`,`--load-extension=${t.extensionPath}`]:[];s.args=[...nu(e,t.disableSecurity??!0,u),...C,...w,...this.additionalArgs],r&&(s.channel=r,c.debug(`[BrowserManager] Launching browser with channel: ${r}`))}let o=du(t.deviceName),l=fu(t.deviceName),d={acceptDownloads:!0,...o,timezoneId:t.timezoneId||"America/Los_Angeles",locale:t.locale||"en-US"};t.viewport&&(d.viewport=t.viewport,d.screen=t.viewport),t.isMobile!==void 0&&(d.isMobile=t.isMobile),t.hasTouch!==void 0&&(d.hasTouch=t.hasTouch),t.userAgent&&(d.userAgent=t.userAgent),t.colorScheme&&(d.colorScheme=t.colorScheme),t.geolocation&&(d.geolocation=t.geolocation,d.permissions=[...d.permissions||[],"geolocation"]);let E=a&&n?t.localStorageStatePath:void 0;t.localStorageStatePath&&!E&&(d.storageState=t.localStorageStatePath),t.recordVideo&&this.videoBasePath&&(d.recordVideo={dir:this.videoBasePath,size:{width:l.width,height:l.height}}),t.proxy&&(d.proxy=t.proxy);let B,m,x,F=!1;if(n&&(a||t.userDataDir)){if(t.userDataDir)x=t.userDataDir;else{let w=this.testDir||rt.mkdtempSync(Bt.join(ao.tmpdir(),"shiplight-"));x=Bt.join(w,`ext-profile-${Date.now()}`),rt.mkdirSync(x,{recursive:!0}),F=!0}let C={...s,...d};m=await Pi.launchPersistentContext(x,C),E&&(await co(m,E),c.info(`[BrowserManager] Loaded storage state into persistent context from ${E}`)),B=m.browser(),c.info(`[BrowserManager] Launched persistent context${t.extensionPath?` for extension at ${t.extensionPath}`:` with profile at ${x}`}`)}else{switch(i){case Et.Firefox:B=await so.launch(s);break;case Et.Webkit:B=await oo.launch(s);break;case Et.Chromium:default:B=await Pi.launch(s);break}m=await B.newContext(d)}if(m.addInitScript(ru),n){let C=["clipboard-read","clipboard-write"];t.enableCamera&&C.push("camera"),t.enableMicrophone&&C.push("microphone");try{await m.grantPermissions(C),c.info(`[BrowserManager] Granted permissions: ${C.join(", ")}`)}catch(w){c.warn("[BrowserManager] Failed to grant permissions:",w)}}else(t.enableCamera||t.enableMicrophone)&&c.warn("[BrowserManager] Camera/microphone enabled but browser is not Chromium; ignoring.");if(t.cookies&&t.cookies.length>0){let C=(Date.now()+31536e6)/1e3,w=t.cookies.map(S=>({...S,expires:C}));await m.addCookies(w),c.info(`[BrowserManager] Added ${t.cookies.length} cookies to browser context with expires=${C}`)}let b=t.viewport,y=b?{width:b.width,height:b.height+cu}:pu(t.deviceName);if(c.info(`[BrowserManager] windowSize=${JSON.stringify(y)}`),n){let C=async w=>{try{await su(w,y.width,y.height),b&&await w.setViewportSize(b)}catch(S){c.warn("[BrowserManager] Failed to set window bounds via CDP:",S)}};for(let w of m.pages())await C(w);m.on("page",C)}let _="";if(n&&e!==void 0)try{_=await au(e)}catch(C){c.warn("[BrowserManager] Failed to get CDP WebSocket URL:",C)}let A={debugPort:e,browser:B,context:m,startTime:new Date,timeout:null,browserWsUrl:_,downloadsBasePath:this.downloadsBasePath,browserType:i,userDataDir:x,isTempUserDataDir:F};if(this.terminationTimeout!==null){let C=setTimeout(()=>{c.info(`[BrowserManager] Browser auto-terminated after ${this.terminationTimeout}ms`),this.terminateBrowser(A).catch(w=>c.error("[BrowserManager] Error terminating browser:",w))},this.terminationTimeout);A.timeout=C}return A}async terminateBrowser(t){if(t.timeout&&clearTimeout(t.timeout),await t.context.close(),await t.browser.close(),t.isTempUserDataDir&&t.userDataDir)try{rt.rmSync(t.userDataDir,{recursive:!0,force:!0})}catch(e){c.warn("[BrowserManager] Failed to clean up temp user data dir:",t.userDataDir,e)}}getVideoBasePath(){return this.videoBasePath}getStatesBasePath(){return this.statesBasePath}getDownloadsBasePath(){return this.downloadsBasePath}},j0=t=>{if(!t||t===lu)return"desktop";let e=hu(t);return e&&e.isMobile?"mobile":"desktop"},lo=(t=>(t.Desktop="desktop",t.Mobile="mobile",t))(lo||{}),ho=class{constructor(t){this.currentPage=null,this.currentIndex=-1,this.context=t,this.initialize()}initialize(){this.context.on("page",async e=>{await this.handleNewPage(e)});let t=this.context.pages();t.length>0&&(this.currentPage=t[0],this.currentIndex=0);for(let e of t)this.setupPageListeners(e)}async handleNewPage(t){try{this.setupPageListeners(t);let e=this.context.pages().indexOf(t);await this.setCurrentPage(t,e)}catch{}}setupPageListeners(t){t.on("close",async()=>{await this.handlePageClose(t)})}async handlePageClose(t){try{if(this.currentPage===t){let e=this.context.pages(),u=e.slice().reverse().find(i=>!i.isClosed());u&&await this.setCurrentPage(u,e.indexOf(u))}}catch{}}async setCurrentPage(t,e){let u=this.currentPage!==t;this.currentPage=t,this.currentIndex=e,u&&await t.bringToFront()}async switchToPage(t){let e=this.context.pages();if(t<0||t>=e.length)throw new Error(`Invalid page index: ${t}. Available pages: 0-${e.length-1}`);let u=e[t];if(u.isClosed())throw new Error(`Page at index ${t} is closed`);return await this.setCurrentPage(u,t),u}async closePage(t){let e=this.context.pages();if(t<0||t>=e.length)throw new Error(`Invalid page index: ${t}. Available pages: 0-${e.length-1}`);let u=e[t];if(u.isClosed())throw new Error(`Page at index ${t} is already closed`);await u.close()}getCurrentPage(){return this.currentPage}getCurrentIndex(){return this.currentIndex}getAllPages(){return this.context.pages()}getPageCount(){return this.context.pages().length}};async function po(t,e=3e3,u=1e3){try{await Xt(t,e,u)}catch{}}async function fo(t,e,u){let i=u*1e3,r=100,n=Date.now();for(;!e.downloadStatus||e.downloadStatus.status==="inProgress";){if(Date.now()-n>i){let a;throw e.downloadStatus?a=`Timed out after ${i}ms waiting for download to complete`:a="No download in progress or completed",c.error(a),new Error(a)}await t.waitForTimeout(r)}if(e.downloadStatus.status==="failed"){let a=`Download failed: ${e.downloadStatus.error||"Unknown error"}`;throw c.error(a),new Error(a)}e.agentNote=`Download completed: ${e.downloadStatus.filename}`}async function go(t,e,u,i=60,r){let n=Math.min(i,280),a=Math.max(10,n/10)*1e3,s=Date.now()+n*1e3;for(c.info(`Waiting for condition: "${e}" (timeout: ${n}s)`);;){let o=Date.now();try{if(await u(t,e,r))return c.info(`Condition met: "${e}"`),!0}catch(d){c.warn(`Error evaluating condition: ${d.message}`)}if(Date.now()>s)return c.warn(`Timeout waiting for condition: "${e}"`),!1;let l=a-(Date.now()-o);l>0&&await t.waitForTimeout(l)}}var mo=te(Wr(),1);function xo(t){return t.url()===":"}var Ao=class{constructor(t){this.context=t,this.testDataFileNames=[],this.extensionEnabled=!1}setTestDataDownloader(t,e){this.testDataDownloader=t,this.testDataFileNames=e??[]}setupPageTracking(t){this.tabManager=new ho(t)}async switchTab(t){if(!this.tabManager)throw new Error("Tab manager not initialized");return await this.tabManager.switchToPage(t)}async closeTab(t){if(!this.tabManager)throw new Error("Tab manager not initialized");await this.tabManager.closePage(t)}getCurrentPage(){return this.tabManager?this.tabManager.getCurrentPage():null}validatePage(t){let e=this.getCurrentPage();if(e&&e!==t&&!e.isClosed())return c.info(`[validatePage] Page changed, switching to ${e.url()}`),e;if(t.isClosed()){let u=t.context().pages().filter(i=>!i.isClosed());if(u.length>0){let i=u[u.length-1];return c.info(`[validatePage] Page closed, switching to ${i.url()}`),i}c.error("[validatePage] No valid pages found")}return t}replaceVariables(t){return xu(t,this.context.variableStore.getAll())}getTestDataFileNames(){return this.testDataFileNames}getTestDataFilePath(t){let e=this.context.testDataDir||process.cwd();return bt.join(e,t)}async downloadTestDataFiles(t){if(t.length===0){c.debug("[AgentServices] No file paths provided for download");return}let e=this.context.testDataDir||process.cwd(),u=t.filter(i=>{let r=bt.basename(i),n=bt.join(e,r),a=Tr.existsSync(n);return a&&c.debug(`[AgentServices] File already exists locally: ${r}`),!a});if(u.length===0){c.debug("[AgentServices] All files exist locally, no download needed");return}if(!this.testDataDownloader){c.debug("[AgentServices] No test data downloader configured, assuming files are pre-populated");return}c.info(`[AgentServices] Downloading ${u.length} test data files: ${u.join(", ")}`),await this.testDataDownloader(u,e)}async waitForDownloadComplete(t,e){return fo(t,this.context,e)}getRecentDownloadedFilePath(){return this.context.downloadStatus?this.context.downloadStatus.status!=="completed"?(c.debug(`Download is ${this.context.downloadStatus.status}, not completed`),null):this.context.downloadStatus.filePath?(c.info(`Retrieved recent download path: ${this.context.downloadStatus.filePath}`),this.context.downloadStatus.filePath):(c.warn("Download completed but file path is missing"),null):(c.debug("No download found"),null)}addSensitive(t,e){this.context.variableStore.set(t,e,!0)}saveVariable(t,e){let u=t.startsWith("$")?t.slice(1):t;this.context.variableStore.set(u,e),c.debug(`Saved variable: ${u} = ${JSON.stringify(e)}`),this.context.agentNote=`A new value is saved to the variable "${u}".`}addNote(t){!t||t.trim()===""||(this.context.agentNote?this.context.agentNote+=`
|
|
103
|
-
${t.trim()}`:this.context.agentNote=t.trim())}readVariable(t){let e=t.startsWith("$")?t.slice(1):t,u=this.context.variableStore.get(e);return c.debug(`Read variable: ${e} = ${JSON.stringify(u)}`),u}async generate2faCode(t){try{let e=mo.authenticator.generate(t);return c.info(`Generated 2FA code: ${e}`),e}catch(e){throw c.error(`Failed to generate 2FA code: ${e.message}`),new Error(`Failed to generate 2FA code: ${e.message}`)}}async getDOMText(t){return await t.evaluate(()=>document.body.innerText)}async waitUntilStable(t,e){return Xt(t,e)}setPage(t){this.context.setPage?(c.info("[AgentServices] Calling setPage callback"),this.context.setPage(t)):c.debug("[AgentServices] setPage callback not configured")}getModel(){if(!this.context.model)throw new Error("No LLM model configured. An LLM model is required for AI-powered actions (login, verify, ai_extract, ai_wait_until, etc.). Set GOOGLE_API_KEY or ANTHROPIC_API_KEY in your MCP server configuration.");return this.context.model}get variableStore(){return this.context.variableStore}getDownloadDir(){return this.context.downloadDir}getActionSettings(){return this.context.organizationSettings?.action_code_conversion_settings||{}}getInteractiveClassNames(){return this.context.organizationSettings?.agent_settings?.interactive_class_names||[]}getIframeFallbackDomains(){return this.context.organizationSettings?.agent_settings?.iframe_fallback_domains||[]}isUseCleanScreenshotForAssertion(){return this.context.organizationSettings?.use_clean_screenshot_for_assertion||!1}isKnowledgeImagesEnabled(){return this.context.organizationSettings?.agent_settings?.enable_knowledge_images||!1}isSlicedScreenshotsEnabled(){return this.context.organizationSettings?.agent_settings?.use_sliced_screenshots||!1}isResizeSlicedScreenshotsEnabled(){return this.context.organizationSettings?.agent_settings?.resize_sliced_screenshots||!1}isAccessibilityTreeEnabled(){return this.context.organizationSettings?.agent_settings?.use_accessibility_tree||!1}isActionIntentFilteringEnabled(){return this.context.organizationSettings?.agent_settings?.use_action_intent_filtering||!1}isDomTreeTsEnabled(){let t=process.env.USE_DOM_TREE_TS;return t!==void 0?t==="true"||t==="1":this.context.organizationSettings?.agent_settings?.use_dom_tree_ts||!1}setExtensionEnabled(t){this.extensionEnabled=t}getDomServiceOptions(){return{useDomTreeTs:this.isDomTreeTsEnabled(),domTreeRoot:this.extensionEnabled?"document":"body"}}setKnowledgeRetriever(t){this.knowledgeRetriever=t}hasKnowledgeRetriever(){return this.knowledgeRetriever!==void 0}async retrieveKnowledges(t,e,u,i){if(!this.knowledgeRetriever)return c.debug("[AgentServices] No knowledge retriever configured"),[];try{let r=await this.knowledgeRetriever(t,e,u,i);return c.debug(`[AgentServices] Retrieved ${r.length} knowledges for statement`),r}catch(r){return c.warn(`[AgentServices] Failed to retrieve knowledges: ${r.message}`),[]}}},Eo=(t=>(t.Started="started",t.Action="action",t.Completion="completion",t.Error="error",t.Aborted="aborted",t.Keepalive="keepalive",t))(Eo||{}),Bo=class extends Error{constructor(t){super(t),this.name="AgentTaskFailedError",this.details=t}},Co=1,Do=3,bo=40;function Ct(t,e){let u={};for(let[i,r]of Object.entries(t))u[i]=e.has(i)?"*****":r;return u}var wo=class{constructor(t){this.context=t,this._newActionEntities=new Map,this.agentServices=new Ao(t),this.agentServices.agent=this,this.context.tokenUsages||(this.context.tokenUsages=[])}getNewActionEntities(){return this._newActionEntities}async getActionHandler(){if(!this._actionHandler){let{default:t}=await import("./handler-
|
|
103
|
+
${t.trim()}`:this.context.agentNote=t.trim())}readVariable(t){let e=t.startsWith("$")?t.slice(1):t,u=this.context.variableStore.get(e);return c.debug(`Read variable: ${e} = ${JSON.stringify(u)}`),u}async generate2faCode(t){try{let e=mo.authenticator.generate(t);return c.info(`Generated 2FA code: ${e}`),e}catch(e){throw c.error(`Failed to generate 2FA code: ${e.message}`),new Error(`Failed to generate 2FA code: ${e.message}`)}}async getDOMText(t){return await t.evaluate(()=>document.body.innerText)}async waitUntilStable(t,e){return Xt(t,e)}setPage(t){this.context.setPage?(c.info("[AgentServices] Calling setPage callback"),this.context.setPage(t)):c.debug("[AgentServices] setPage callback not configured")}getModel(){if(!this.context.model)throw new Error("No LLM model configured. An LLM model is required for AI-powered actions (login, verify, ai_extract, ai_wait_until, etc.). Set GOOGLE_API_KEY or ANTHROPIC_API_KEY in your MCP server configuration.");return this.context.model}get variableStore(){return this.context.variableStore}getDownloadDir(){return this.context.downloadDir}getActionSettings(){return this.context.organizationSettings?.action_code_conversion_settings||{}}getInteractiveClassNames(){return this.context.organizationSettings?.agent_settings?.interactive_class_names||[]}getIframeFallbackDomains(){return this.context.organizationSettings?.agent_settings?.iframe_fallback_domains||[]}isUseCleanScreenshotForAssertion(){return this.context.organizationSettings?.use_clean_screenshot_for_assertion||!1}isKnowledgeImagesEnabled(){return this.context.organizationSettings?.agent_settings?.enable_knowledge_images||!1}isSlicedScreenshotsEnabled(){return this.context.organizationSettings?.agent_settings?.use_sliced_screenshots||!1}isResizeSlicedScreenshotsEnabled(){return this.context.organizationSettings?.agent_settings?.resize_sliced_screenshots||!1}isAccessibilityTreeEnabled(){return this.context.organizationSettings?.agent_settings?.use_accessibility_tree||!1}isActionIntentFilteringEnabled(){return this.context.organizationSettings?.agent_settings?.use_action_intent_filtering||!1}isDomTreeTsEnabled(){let t=process.env.USE_DOM_TREE_TS;return t!==void 0?t==="true"||t==="1":this.context.organizationSettings?.agent_settings?.use_dom_tree_ts||!1}setExtensionEnabled(t){this.extensionEnabled=t}getDomServiceOptions(){return{useDomTreeTs:this.isDomTreeTsEnabled(),domTreeRoot:this.extensionEnabled?"document":"body"}}setKnowledgeRetriever(t){this.knowledgeRetriever=t}hasKnowledgeRetriever(){return this.knowledgeRetriever!==void 0}async retrieveKnowledges(t,e,u,i){if(!this.knowledgeRetriever)return c.debug("[AgentServices] No knowledge retriever configured"),[];try{let r=await this.knowledgeRetriever(t,e,u,i);return c.debug(`[AgentServices] Retrieved ${r.length} knowledges for statement`),r}catch(r){return c.warn(`[AgentServices] Failed to retrieve knowledges: ${r.message}`),[]}}},Eo=(t=>(t.Started="started",t.Action="action",t.Completion="completion",t.Error="error",t.Aborted="aborted",t.Keepalive="keepalive",t))(Eo||{}),Bo=class extends Error{constructor(t){super(t),this.name="AgentTaskFailedError",this.details=t}},Co=1,Do=3,bo=40;function Ct(t,e){let u={};for(let[i,r]of Object.entries(t))u[i]=e.has(i)?"*****":r;return u}var wo=class{constructor(t){this.context=t,this._newActionEntities=new Map,this.agentServices=new Ao(t),this.agentServices.agent=this,this.context.tokenUsages||(this.context.tokenUsages=[])}getNewActionEntities(){return this._newActionEntities}async getActionHandler(){if(!this._actionHandler){let{default:t}=await import("./handler-65CN5L7D-IN6OTBXK.js");this._actionHandler=new t}return this._actionHandler}async execAction(t,e,u){let i=(await this.getActionHandler()).getAction(t);if(!i)throw new Error(`Unknown action: ${t}`);await i.execute(e,u,this.agentServices)}async dismissModalIfPresent(t,e){try{let u=await this.execute(t,`TASK: Check if there is an INTRUSIVE POPUP blocking the page, and dismiss it if present.
|
|
104
104
|
|
|
105
105
|
ONLY dismiss intrusive popups such as:
|
|
106
106
|
- Cookie/GDPR consent banners
|
|
@@ -134,7 +134,7 @@ If the page is not signed in, sign in with the OAuth provider "${n.provider_name
|
|
|
134
134
|
`}e.additional_prompt&&(r+=`
|
|
135
135
|
Additional instructions: ${e.additional_prompt}
|
|
136
136
|
`);try{k.log("Level 3: Attempting agent-based login"),k.log(`Login prompt:
|
|
137
|
-
${r}`);let n=this.agentServices.knowledgeRetriever,a=!1;this.agentServices.hasKnowledgeRetriever()&&n&&(k.log("Setting up login knowledge retriever..."),this.agentServices.setKnowledgeRetriever(async(B,m,x,F)=>await n(B,m,x,"login")),a=!0,k.log("Login knowledge retriever configured"));let s;try{if(s=await this.run(t,r,"login"),!s.success)return k.log("Level 3 FAILED: Agent login failed"),c.info("Login: Failed"),{success:!1,page:t}}finally{a&&n&&(this.agentServices.setKnowledgeRetriever(n),k.log("Restored original knowledge retriever"))}let o=await t.context().storageState(),l;if(e.num_verification_exprs!==0)try{k.log("Generating validation locators for future login verification...");let B=await Eu(t,e.site_url,{verification_hint:e.verification_hint,num_verification_exprs:e.num_verification_exprs},async(m,x)=>this.run(m,x),async m=>this.getDOMText(m));B?(l=B,k.log(`Generated ${l.length} validation locator(s): ${JSON.stringify(l)}`)):k.log("Failed to generate validation locators, login will still succeed")}catch(B){k.log(`Error generating validation locators: ${B.message}`)}else k.log("Skipping validation locator generation (num_verification_exprs=0)");k.log("Level 3 SUCCESS: Agent login succeeded"),c.info("Login: Agent login succeeded");let d=s.actions||[],E=d.length>0?d:u?.cached_actions;return{success:!0,page:t,storage_state:o,cached_actions:E,validation_exprs:l}}catch(n){return k.error(`Agent login failed: ${n.message}`),c.info("Login: Failed"),{success:!1,page:t}}}async executeCachedLogin(t,e,u){let i=(await import("./handler-
|
|
137
|
+
${r}`);let n=this.agentServices.knowledgeRetriever,a=!1;this.agentServices.hasKnowledgeRetriever()&&n&&(k.log("Setting up login knowledge retriever..."),this.agentServices.setKnowledgeRetriever(async(B,m,x,F)=>await n(B,m,x,"login")),a=!0,k.log("Login knowledge retriever configured"));let s;try{if(s=await this.run(t,r,"login"),!s.success)return k.log("Level 3 FAILED: Agent login failed"),c.info("Login: Failed"),{success:!1,page:t}}finally{a&&n&&(this.agentServices.setKnowledgeRetriever(n),k.log("Restored original knowledge retriever"))}let o=await t.context().storageState(),l;if(e.num_verification_exprs!==0)try{k.log("Generating validation locators for future login verification...");let B=await Eu(t,e.site_url,{verification_hint:e.verification_hint,num_verification_exprs:e.num_verification_exprs},async(m,x)=>this.run(m,x),async m=>this.getDOMText(m));B?(l=B,k.log(`Generated ${l.length} validation locator(s): ${JSON.stringify(l)}`)):k.log("Failed to generate validation locators, login will still succeed")}catch(B){k.log(`Error generating validation locators: ${B.message}`)}else k.log("Skipping validation locator generation (num_verification_exprs=0)");k.log("Level 3 SUCCESS: Agent login succeeded"),c.info("Login: Agent login succeeded");let d=s.actions||[],E=d.length>0?d:u?.cached_actions;return{success:!0,page:t,storage_state:o,cached_actions:E,validation_exprs:l}}catch(n){return k.error(`Agent login failed: ${n.message}`),c.info("Login: Failed"),{success:!1,page:t}}}async executeCachedLogin(t,e,u){let i=(await import("./handler-65CN5L7D-IN6OTBXK.js")).default,r=new i;for(let n=0;n<e.length;n++){let a=e[n];k.log(`Executing cached action ${n+1}/${e.length}: ${a.action_description||a.action_data?.action_name}`);try{if(!a.action_data){k.log(`Action ${n+1} missing action_data, skipping`);continue}await r.execute(t,a,this.agentServices),await this.waitUntilStable(t,5e3)}catch(s){return k.error(`Cached action ${n+1} failed: ${s.message}`),{success:!1}}}return u&&u.length>0&&!await ee(t,u)?{success:!1}:{success:!0}}getCompletedExecutionHistory(){if(!this.context.executionHistory||this.context.executionHistory.length===0)return[];let t=this.context.executionHistory[this.context.executionHistory.length-1];return!t[1]||t[1].trim()===""?this.context.executionHistory.slice(0,-1):this.context.executionHistory}addToExecutionHistory(t,e){this.context.executionHistory||(this.context.executionHistory=[]),this.context.executionHistory.push([t,e])}async createStepResult(t,e,u){if(this.context.stepTracking&&!this.context.stepTracking.results[e]){this.context.stepTracking.currentStepId=e,this.context.stepTracking.onStepChange&&this.context.stepTracking.onStepChange(e);try{t=this.agentServices.validatePage(t),await this.waitUntilStable(t);let i={description:u,startTime:Date.now(),artifacts:[]};if(this.context.stepTracking.artifactsDir){let r=M.join(this.context.stepTracking.artifactsDir,e.replace(/\./g,"-"));P.mkdirSync(r,{recursive:!0});let n=M.join(r,"screenshot.png");t=this.agentServices.validatePage(t),await t.screenshot({type:"png",path:n}),i.screenshot=n}this.context.stepTracking.results[e]=i}catch(i){c.warn(`createStepResult failed for step ${e}: ${i}`),this.context.stepTracking.results[e]={description:u,startTime:Date.now(),artifacts:[]}}}}saveDebugInfoToFiles(t,e,u,i=0){let r={};if(!this.context.stepTracking?.artifactsDir)return c.debug("[saveDebugInfoToFiles] No artifacts directory configured, skipping debug info save"),r;let n=M.join(this.context.stepTracking.artifactsDir,t.replace(/\./g,"-"));try{if(P.mkdirSync(n,{recursive:!0}),e.systemPrompt){let a=M.join(n,`system_prompt_${i}.txt`);P.writeFileSync(a,e.systemPrompt),r.system_prompt_path=a,c.debug(`[saveDebugInfoToFiles] Saved system prompt to: ${a}`)}if(e.userPrompt)if(typeof e.userPrompt=="string"){let a=M.join(n,`user_prompt_${i}.txt`);P.writeFileSync(a,e.userPrompt),r.user_prompt_path=a,c.debug(`[saveDebugInfoToFiles] Saved user prompt to: ${a}`)}else{let a=e.userPrompt.map(l=>Array.isArray(l.content)?{...l,content:l.content.map(d=>d.type==="image"&&d.file?.startsWith("data:")?{...d,file:"[base64 image data stripped]"}:d)}:l),s=M.join(n,`messages_${i}.json`),o={system:e.systemPrompt,messages:a};P.writeFileSync(s,JSON.stringify(o,null,2)),r.messages_path=s,c.debug(`[saveDebugInfoToFiles] Saved messages to: ${s}`)}if(e.rawLlmResponse){let a=u?u.replace(/[\/\\:]/g,"-"):"llm",s=M.join(n,`${a}_response_${i}.txt`);P.writeFileSync(s,e.rawLlmResponse),r.response_path=s,c.debug(`[saveDebugInfoToFiles] Saved LLM response to: ${s}`)}if(e.screenshotWithSom){let a=M.join(n,`screenshot_${i}.png`);P.writeFileSync(a,Buffer.from(e.screenshotWithSom,"base64")),r.screenshot_path=a,c.debug(`[saveDebugInfoToFiles] Saved SOM screenshot to: ${a}`)}if(e.reasoningContent){let a=M.join(n,`reasoning_${i}.txt`);P.writeFileSync(a,e.reasoningContent),r.reasoning_path=a,c.debug(`[saveDebugInfoToFiles] Saved reasoning to: ${a}`)}c.debug(`[saveDebugInfoToFiles] Saved ${Object.keys(r).length} artifacts for step ${t}`)}catch(a){c.error(`[saveDebugInfoToFiles] Failed to save debug info for step ${t}:`,a)}return r}async updateStepResult(t,e,u,i,r){if(!this.context.stepTracking)return;let n=this.context.stepTracking.results[t];if(n){if(e&&(n.status=e,this.context.stepTracking.currentStepId=void 0,this.context.stepTracking.onStepChange&&this.context.stepTracking.onStepChange(void 0)),u!==void 0&&(n.message=u),i&&n.artifacts.push(i),r){let a=r.tokenUsages?.[0]?.model,s=n.artifacts.length,o=this.saveDebugInfoToFiles(t,r,a,s);Object.keys(o).length>0&&n.artifacts.push(o)}n.duration=Date.now()-n.startTime,this.context.stepTracking.onStepComplete&&this.context.stepTracking.onStepComplete(t,n)}}async writeExecutionResults(t,e){try{if(await P.promises.mkdir(t,{recursive:!0}),this.context.stepTracking?.results&&Object.keys(this.context.stepTracking.results).length>0){let u=M.join(t,"test-results.json");await P.promises.writeFile(u,JSON.stringify(this.context.stepTracking.results,null,2)),c.debug(`Test results written to: ${u}`)}if(e?.tokenUsages&&this.context.tokenUsages&&this.context.tokenUsages.length>0){let u=M.join(t,"token-usages.json");await P.promises.writeFile(u,JSON.stringify(this.context.tokenUsages,null,2)),c.debug(`Token usages written to: ${u}`)}if(this.context.aiActionDetails&&this.context.aiActionDetails.length>0){let u=M.join(t,"ai-actions.json");await P.promises.writeFile(u,JSON.stringify(this.context.aiActionDetails,null,2)),c.debug(`AI action details written to: ${u}`)}}catch(u){throw c.error("Failed to write execution results:",u),u}}};function yo(){let t=new Date,e=new Intl.DateTimeFormat("en-US",{timeZone:"America/Los_Angeles",year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",hour12:!1}).formatToParts(t),u=e.find(y=>y.type==="year").value,i=e.find(y=>y.type==="month").value,r=e.find(y=>y.type==="day").value,n=e.find(y=>y.type==="hour").value,a=e.find(y=>y.type==="minute").value,s=e.find(y=>y.type==="second").value,o=String(t.getMilliseconds()).padStart(3,"0"),l=`${u}-${i}-${r}T${n}:${a}:${s}.${o}`,d=t.toISOString().slice(0,-1),E=Date.parse(l+"Z"),B=Date.parse(d+"Z"),m=Math.round((B-E)/(1e3*60)),x=String(Math.floor(Math.abs(m)/60)).padStart(2,"0"),F=String(Math.abs(m)%60).padStart(2,"0"),b=m<=0?"+":"-";return`${u}-${i}-${r}T${n}:${a}:${s}.${o}${b}${x}:${F}`}function Fo(t){let e=t.variableStore;return e.has("currentTime")||e.set("currentTime",yo()),{model:t.model,variableStore:e,organizationId:t.organizationId,organizationSettings:t.organizationSettings,executionHistory:t.executionHistory||[],testDataDir:t.testDataDir,downloadDir:t.downloadDir,useNativeGenerator:t.useNativeGenerator,autoDisableModal:t.autoDisableModal,tokenUsages:[],aiActionDetails:[]}}function V0(t){let e=new Au,u=new Set(t.sensitiveKeys||[]);if(t.variables)for(let[r,n]of Object.entries(t.variables))e.set(r,n,u.has(r));let i=Fo({model:t.model,variableStore:e,testDataDir:t.testDataDir,downloadDir:t.downloadDir});return new wo(i)}var W0="1.0.0",vo=Rt.object({found:Rt.boolean().describe("Whether an activation code was found in the document"),activation_code:Rt.string().nullable().describe("The extracted activation code, or null if not found"),explanation:Rt.string().describe("Brief explanation of what was found or why nothing was found")});async function ko(t,e,u){c.info(`Extracting activation code from file: ${t}`);let i=`${e}/${t}`;if(!Wt.existsSync(i))throw new Error(`PDF file not found: ${i}`);let r=Wt.readFileSync(i).toString("base64"),n=`You are analyzing a PDF document to extract an activation code.
|
|
138
138
|
|
|
139
139
|
Please carefully examine the PDF and look for:
|
|
140
140
|
1. The activation code on the first page top right corner
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { createRequire as __createRequire } from "module";
|
|
3
3
|
const require = __createRequire(import.meta.url);
|
|
4
|
-
import{d as o,e as h,f as g}from"./chunk-HBXQFJ2K.js";import{createRequire as x}from"module";var S=x(import.meta.url),b={};g(b,{ACTION_TIMEOUT:()=>f,GOTO_TIMEOUT:()=>w,LOCATOR_TIMEOUT:()=>c,getActionTimeoutMs:()=>_,getFrameContext:()=>d,getLocator:()=>O,getMinimalActionEntity:()=>E,getPageLocatorExpression:()=>$,sanitizeForComment:()=>L});function _(e,t){return t??e?.getActionSettings()?.action_timeout_ms??f}function L(e){return e.replace(/\r\n/g," ").replace(/\n/g," ").replace(/\r/g," ").trim()}function O(e,t){let a=$(t);return a?new Function("page",`return ${a}`)(e):null}async function d(e,t=[]){let a=e;for(let l of t){let n=await a.locator(l).elementHandle();if(!n)return null;let r=await n.contentFrame();if(await n.dispose(),!r)return null;a=r}return a}function E(e){let t={action_data:e.action_data};return e.locator&&(t.locator=e.locator),e.xpath&&(t.xpath=e.xpath),e.frame_path&&(t.frame_path=e.frame_path),t}function T(e){let t=e.frame_path;return!t||t.length===0?"page":`page.frameLocator('${t[0]}')`}function W(e){let t=e.xpath;return typeof t=="string"&&t.trim()?!t.startsWith("xpath=")&&!t.startsWith("/")&&!t.startsWith("//")?`xpath=//${t}`:t.startsWith("xpath=")?t:`xpath=${t}`:null}function $(e){let t=T(e),a=e.locator;if(typeof a=="string"&&a.trim())return a=a.trim(),a.endsWith("first()")?`${t}.${a}`:`${t}.${a}.first()`;let l=W(e);if(l){let n=JSON.stringify(l);return`${t}.locator(${n}).first()`}return null}var c,f,w,v=h(()=>{c=5e3,f=
|
|
4
|
+
import{d as o,e as h,f as g}from"./chunk-HBXQFJ2K.js";import{createRequire as x}from"module";var S=x(import.meta.url),b={};g(b,{ACTION_TIMEOUT:()=>f,GOTO_TIMEOUT:()=>w,LOCATOR_TIMEOUT:()=>c,getActionTimeoutMs:()=>_,getFrameContext:()=>d,getLocator:()=>O,getMinimalActionEntity:()=>E,getPageLocatorExpression:()=>$,sanitizeForComment:()=>L});function _(e,t){return t??e?.getActionSettings()?.action_timeout_ms??f}function L(e){return e.replace(/\r\n/g," ").replace(/\n/g," ").replace(/\r/g," ").trim()}function O(e,t){let a=$(t);return a?new Function("page",`return ${a}`)(e):null}async function d(e,t=[]){let a=e;for(let l of t){let n=await a.locator(l).elementHandle();if(!n)return null;let r=await n.contentFrame();if(await n.dispose(),!r)return null;a=r}return a}function E(e){let t={action_data:e.action_data};return e.locator&&(t.locator=e.locator),e.xpath&&(t.xpath=e.xpath),e.frame_path&&(t.frame_path=e.frame_path),t}function T(e){let t=e.frame_path;return!t||t.length===0?"page":`page.frameLocator('${t[0]}')`}function W(e){let t=e.xpath;return typeof t=="string"&&t.trim()?!t.startsWith("xpath=")&&!t.startsWith("/")&&!t.startsWith("//")?`xpath=//${t}`:t.startsWith("xpath=")?t:`xpath=${t}`:null}function $(e){let t=T(e),a=e.locator;if(typeof a=="string"&&a.trim())return a=a.trim(),a.endsWith("first()")?`${t}.${a}`:`${t}.${a}.first()`;let l=W(e);if(l){let n=JSON.stringify(l);return`${t}.locator(${n}).first()`}return null}var c,f,w,v=h(()=>{c=5e3,f=1e4,w=2e4});v();async function y(e,t,a=[],l=[]){try{let n=await d(e,a);if(!n)return o.warn(`Could not find frame context for xpath: ${t}`),null;let r=null;if(l.length>0){let s=l[0];if(!s)return o.warn(`Missing shadow host xpath for element: ${t}`),null;let u=n.locator(`xpath=${m(s)}`),p=C(t);if(r=await(p?u.locator(`css=${p}`):u.locator(`xpath=${m(t)}`)).elementHandle({timeout:c}),!r)return o.warn(`Could not find shadow DOM element with xpath: ${t}`),null}else if(r=await n.locator(`xpath=${t}`).elementHandle({timeout:c}),!r)return o.warn(`Could not find element with xpath: ${t}`),null;let i=await n.evaluate(s=>typeof playwright<"u"&&playwright.generateLocator?playwright.generateLocator(s):null,r);return await r.dispose(),i?(o.debug(`Generated locator for ${t}: ${i}`),i):(o.debug("playwright.generateLocator is not available (PWDEBUG=console not set), using xpath fallback"),null)}catch(n){return o.error(`Error in pickBestLocator: ${n}`),null}}async function q(e,t){try{let a=await(await t.ownerFrame()??e).evaluate(l=>typeof playwright<"u"&&playwright.generateLocator?playwright.generateLocator(l):null,t);return await t.dispose(),a?(o.debug(`Generated locator: ${a}`),a):(o.debug("playwright.generateLocator is not available (PWDEBUG=console not set), using xpath fallback"),null)}catch(a){return o.error(`Error in pickBestLocator: ${a}`),null}}async function F(e,t){let a=new Map;return await Promise.all(t.map(async l=>{let n=await y(e,l);a.set(l,n)})),a}function m(e){let t=e.trim();return t.startsWith("/")||t.startsWith("(")||t.startsWith(".")?t:`//${t}`}function C(e){let t=e.trim().replace(/^\/+/,"");if(!t)return null;let a=t.split("/").filter(Boolean),l=[];for(let n of a){let r=n.match(/^([a-zA-Z][\w-]*)(?:\[(\d+)\])?$/);if(!r)return null;let i=r[1].toLowerCase(),s=r[2]?`:nth-of-type(${r[2]})`:"";l.push(`${i}${s}`)}return l.join(" > ")}async function H(e,t){if(t<0)return;let{page:a,domService:l}=e;return(e.domState||await l.getClickableElements(a)).selectorMap.get(t)}function M(e){let t=e.split("/").filter(n=>n);if(t.length===0)return"*";let a=t[t.length-1],l=a.match(/^(\w+)(?:\[(\d+)\])?$/);if(l){let[,n,r]=l;return r?`${n}:nth-of-type(${r})`:n}return a}function A(e,t=!0){try{let a=M(e.xpath);if(e.attributes.class&&t){let n=/^[a-zA-Z_][a-zA-Z0-9_-]*$/,r=e.attributes.class.split(/\s+/);for(let i of r)i.trim()&&n.test(i)&&(a+=`.${i}`)}let l=new Set(["id","name","type","placeholder","aria-label","aria-labelledby","aria-describedby","role","for","autocomplete","required","readonly","alt","title","target"]);t&&["data-id","data-qa","data-cy","data-testid","data-handlepos"].forEach(n=>l.add(n));for(let[n,r]of Object.entries(e.attributes)){if(n==="class"||!n.trim()||!l.has(n))continue;let i=n.replace(/:/g,"\\:");if(r==="")a+=`[${i}]`;else if(/["'<>`\n\r\t]/.test(r)){let s=r;r.includes(`
|
|
5
5
|
`)&&(s=r.split(`
|
|
6
6
|
`)[0]),s=s.replace(/\s+/g," ").trim();let u=s.replace(/"/g,'\\"');a+=`[${i}*="${u}"]`}else a+=`[${i}="${r}"]`}return a}catch{return`${e.tagName||"*"}[highlight_index='${e.highlightIndex}']`}}function k(e){let t=e.attributes;if(t.title)return`iframe[title="${t.title.replace(/"/g,'\\"')}"]`;if(t.id)return`iframe#${t.id}`;if(t.name)return`iframe[name="${t.name.replace(/"/g,'\\"')}"]`;if(t.src){try{let a=new URL(t.src);if(a.protocol==="chrome-extension:")return`iframe[src^="${a.origin}"]`}catch{}return`iframe[src="${t.src.replace(/"/g,'\\"')}"]`}return A(e,!1)}function B(e){let t=[],a=e;for(;a&&a.parent!==null;){let r=a.parent;t.push(r),a=r}t.reverse();let l=[],n=t.filter(r=>r.tagName==="iframe");for(let r of n){let i=k(r);o.debug("[frame-path] iframe attrs:",JSON.stringify(r.attributes),"\u2192",i),l.push(i)}return l}async function I(e,t){let a=null,l=B(t);return t.xpath&&(a=await y(e,t.xpath,l,t.shadowHostXPaths??[])),{locator:a||void 0,xpath:t.xpath,frame_path:l}}export{b as a,_ as b,O as c,$ as d,w as e,v as f,y as g,q as h,F as i,H as j,B as k,I as l};
|