momentic-mobile 0.0.18 → 0.0.20

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/bin/cli.js CHANGED
@@ -1,28 +1,28 @@
1
1
  #!/usr/bin/env node
2
- var Qv=Object.defineProperty;var Me=(r,e)=>()=>(r&&(e=r(r=0)),e);var Zv=(r,e)=>{for(var t in e)Qv(r,t,{get:e[t],enumerable:!0})};var df,mf=Me(()=>{"use strict";df=typeof globalThis=="object"?globalThis:global});var pf=Me(()=>{"use strict";mf()});var gf=Me(()=>{"use strict";pf()});var fr,iu=Me(()=>{"use strict";fr="1.9.0"});function l_(r){var e=new Set([r]),t=new Set,n=r.match(hf);if(!n)return function(){return!1};var o={major:+n[1],minor:+n[2],patch:+n[3],prerelease:n[4]};if(o.prerelease!=null)return function(c){return c===r};function i(l){return t.add(l),!1}function a(l){return e.add(l),!0}return function(c){if(e.has(c))return!0;if(t.has(c))return!1;var s=c.match(hf);if(!s)return i(c);var u={major:+s[1],minor:+s[2],patch:+s[3],prerelease:s[4]};return u.prerelease!=null||o.major!==u.major?i(c):o.major===0?o.minor===u.minor&&o.patch<=u.patch?a(c):i(c):o.minor<=u.minor?a(c):i(c)}}var hf,ff,Sf=Me(()=>{"use strict";iu();hf=/^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;ff=l_(fr)});function io(r,e,t,n){var o;n===void 0&&(n=!1);var i=vi[bi]=(o=vi[bi])!==null&&o!==void 0?o:{version:fr};if(!n&&i[r]){var a=new Error("@opentelemetry/api: Attempted duplicate registration of API: "+r);return t.error(a.stack||a.message),!1}if(i.version!==fr){var a=new Error("@opentelemetry/api: Registration of version v"+i.version+" for "+r+" does not match previously registered API v"+fr);return t.error(a.stack||a.message),!1}return i[r]=e,t.debug("@opentelemetry/api: Registered a global for "+r+" v"+fr+"."),!0}function Sr(r){var e,t,n=(e=vi[bi])===null||e===void 0?void 0:e.version;if(!(!n||!ff(n)))return(t=vi[bi])===null||t===void 0?void 0:t[r]}function ao(r,e){e.debug("@opentelemetry/api: Unregistering a global for "+r+" v"+fr+".");var t=vi[bi];t&&delete t[r]}var c_,bi,vi,Ai=Me(()=>{"use strict";gf();iu();Sf();c_=fr.split(".")[0],bi=Symbol.for("opentelemetry.js.api."+c_),vi=df});function wi(r,e,t){var n=Sr("diag");if(n)return t.unshift(e),n[r].apply(n,d_([],u_(t),!1))}var u_,d_,Ef,yf=Me(()=>{"use strict";Ai();u_=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},d_=function(r,e,t){if(t||arguments.length===2)for(var n=0,o=e.length,i;n<o;n++)(i||!(n in e))&&(i||(i=Array.prototype.slice.call(e,0,n)),i[n]=e[n]);return r.concat(i||Array.prototype.slice.call(e))},Ef=function(){function r(e){this._namespace=e.namespace||"DiagComponentLogger"}return r.prototype.debug=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return wi("debug",this._namespace,e)},r.prototype.error=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return wi("error",this._namespace,e)},r.prototype.info=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return wi("info",this._namespace,e)},r.prototype.warn=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return wi("warn",this._namespace,e)},r.prototype.verbose=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return wi("verbose",this._namespace,e)},r}()});var we,rs=Me(()=>{"use strict";(function(r){r[r.NONE=0]="NONE",r[r.ERROR=30]="ERROR",r[r.WARN=50]="WARN",r[r.INFO=60]="INFO",r[r.DEBUG=70]="DEBUG",r[r.VERBOSE=80]="VERBOSE",r[r.ALL=9999]="ALL"})(we||(we={}))});function Tf(r,e){r<we.NONE?r=we.NONE:r>we.ALL&&(r=we.ALL),e=e||{};function t(n,o){var i=e[n];return typeof i=="function"&&r>=o?i.bind(e):function(){}}return{error:t("error",we.ERROR),warn:t("warn",we.WARN),info:t("info",we.INFO),debug:t("debug",we.DEBUG),verbose:t("verbose",we.VERBOSE)}}var bf=Me(()=>{"use strict";rs()});var m_,p_,g_,rr,Ri=Me(()=>{"use strict";yf();bf();rs();Ai();m_=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},p_=function(r,e,t){if(t||arguments.length===2)for(var n=0,o=e.length,i;n<o;n++)(i||!(n in e))&&(i||(i=Array.prototype.slice.call(e,0,n)),i[n]=e[n]);return r.concat(i||Array.prototype.slice.call(e))},g_="diag",rr=function(){function r(){function e(o){return function(){for(var i=[],a=0;a<arguments.length;a++)i[a]=arguments[a];var l=Sr("diag");if(l)return l[o].apply(l,p_([],m_(i),!1))}}var t=this,n=function(o,i){var a,l,c;if(i===void 0&&(i={logLevel:we.INFO}),o===t){var s=new Error("Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation");return t.error((a=s.stack)!==null&&a!==void 0?a:s.message),!1}typeof i=="number"&&(i={logLevel:i});var u=Sr("diag"),d=Tf((l=i.logLevel)!==null&&l!==void 0?l:we.INFO,o);if(u&&!i.suppressOverrideMessage){var m=(c=new Error().stack)!==null&&c!==void 0?c:"<failed to generate stacktrace>";u.warn("Current logger will be overwritten from "+m),d.warn("Current logger will overwrite one already registered from "+m)}return io("diag",d,t,!0)};t.setLogger=n,t.disable=function(){ao(g_,t)},t.createComponentLogger=function(o){return new Ef(o)},t.verbose=e("verbose"),t.debug=e("debug"),t.info=e("info"),t.warn=e("warn"),t.error=e("error")}return r.instance=function(){return this._instance||(this._instance=new r),this._instance},r}()});var vf,Af=Me(()=>{"use strict";vf=Symbol("BaggageEntryMetadata")});function au(r){return typeof r!="string"&&(h_.error("Cannot create baggage metadata from unknown type: "+typeof r),r=""),{__TYPE__:vf,toString:function(){return r}}}var h_,wf=Me(()=>{"use strict";Ri();Af();h_=rr.instance()});function su(r){return Symbol.for(r)}var f_,lu,cu=Me(()=>{"use strict";f_=function(){function r(e){var t=this;t._currentContext=e?new Map(e):new Map,t.getValue=function(n){return t._currentContext.get(n)},t.setValue=function(n,o){var i=new r(t._currentContext);return i._currentContext.set(n,o),i},t.deleteValue=function(n){var o=new r(t._currentContext);return o._currentContext.delete(n),o}}return r}(),lu=new f_});function mu(){return du}var mn,S_,ns,E_,y_,T_,b_,uu,v_,A_,w_,du,R_,C_,x_,__,M_,I_,P_,pu=Me(()=>{"use strict";mn=function(){var r=function(e,t){return r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,o){n.__proto__=o}||function(n,o){for(var i in o)Object.prototype.hasOwnProperty.call(o,i)&&(n[i]=o[i])},r(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");r(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}}(),S_=function(){function r(){}return r.prototype.createGauge=function(e,t){return C_},r.prototype.createHistogram=function(e,t){return x_},r.prototype.createCounter=function(e,t){return R_},r.prototype.createUpDownCounter=function(e,t){return __},r.prototype.createObservableGauge=function(e,t){return I_},r.prototype.createObservableCounter=function(e,t){return M_},r.prototype.createObservableUpDownCounter=function(e,t){return P_},r.prototype.addBatchObservableCallback=function(e,t){},r.prototype.removeBatchObservableCallback=function(e){},r}(),ns=function(){function r(){}return r}(),E_=function(r){mn(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.add=function(t,n){},e}(ns),y_=function(r){mn(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.add=function(t,n){},e}(ns),T_=function(r){mn(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.record=function(t,n){},e}(ns),b_=function(r){mn(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.record=function(t,n){},e}(ns),uu=function(){function r(){}return r.prototype.addCallback=function(e){},r.prototype.removeCallback=function(e){},r}(),v_=function(r){mn(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(uu),A_=function(r){mn(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(uu),w_=function(r){mn(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(uu),du=new S_,R_=new E_,C_=new T_,x_=new b_,__=new y_,M_=new v_,I_=new A_,P_=new w_});var Ct,Rf=Me(()=>{"use strict";(function(r){r[r.INT=0]="INT",r[r.DOUBLE=1]="DOUBLE"})(Ct||(Ct={}))});var O_,L_,Cf,xf=Me(()=>{"use strict";cu();O_=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},L_=function(r,e,t){if(t||arguments.length===2)for(var n=0,o=e.length,i;n<o;n++)(i||!(n in e))&&(i||(i=Array.prototype.slice.call(e,0,n)),i[n]=e[n]);return r.concat(i||Array.prototype.slice.call(e))},Cf=function(){function r(){}return r.prototype.active=function(){return lu},r.prototype.with=function(e,t,n){for(var o=[],i=3;i<arguments.length;i++)o[i-3]=arguments[i];return t.call.apply(t,L_([n],O_(o),!1))},r.prototype.bind=function(e,t){return t},r.prototype.enable=function(){return this},r.prototype.disable=function(){return this},r}()});var N_,D_,gu,k_,_f,Mf=Me(()=>{"use strict";xf();Ai();Ri();N_=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},D_=function(r,e,t){if(t||arguments.length===2)for(var n=0,o=e.length,i;n<o;n++)(i||!(n in e))&&(i||(i=Array.prototype.slice.call(e,0,n)),i[n]=e[n]);return r.concat(i||Array.prototype.slice.call(e))},gu="context",k_=new Cf,_f=function(){function r(){}return r.getInstance=function(){return this._instance||(this._instance=new r),this._instance},r.prototype.setGlobalContextManager=function(e){return io(gu,e,rr.instance())},r.prototype.active=function(){return this._getContextManager().active()},r.prototype.with=function(e,t,n){for(var o,i=[],a=3;a<arguments.length;a++)i[a-3]=arguments[a];return(o=this._getContextManager()).with.apply(o,D_([e,t,n],N_(i),!1))},r.prototype.bind=function(e,t){return this._getContextManager().bind(e,t)},r.prototype._getContextManager=function(){return Sr(gu)||k_},r.prototype.disable=function(){this._getContextManager().disable(),ao(gu,rr.instance())},r}()});var so,If=Me(()=>{"use strict";Mf();so=_f.getInstance()});var F,Pf=Me(()=>{"use strict";Ri();F=rr.instance()});var U_,Of,Lf=Me(()=>{"use strict";pu();U_=function(){function r(){}return r.prototype.getMeter=function(e,t,n){return du},r}(),Of=new U_});var hu,Nf,Df=Me(()=>{"use strict";Lf();Ai();Ri();hu="metrics",Nf=function(){function r(){}return r.getInstance=function(){return this._instance||(this._instance=new r),this._instance},r.prototype.setGlobalMeterProvider=function(e){return io(hu,e,rr.instance())},r.prototype.getMeterProvider=function(){return Sr(hu)||Of},r.prototype.getMeter=function(e,t,n){return this.getMeterProvider().getMeter(e,t,n)},r.prototype.disable=function(){ao(hu,rr.instance())},r}()});var os,kf=Me(()=>{"use strict";Df();os=Nf.getInstance()});var he=Me(()=>{"use strict";wf();cu();rs();pu();Rf();If();Pf();kf()});import{Argument as jm,Command as $0,Option as q0}from"@commander-js/extra-typings";import oA from"appium";import{remote as iA}from"webdriverio";import{createInstanceClient as eA}from"@limrun/api";import{execSync as tA}from"child_process";import{hostname as rA}from"os";import nA from"path";async function Wm(r){let{apiClient:e,logger:t,creationOpts:n,onStatusUpdate:o,logLevel:i}=r,{token:a,webRtcUrl:l,adbUrl:c,name:s,apkDownloadUrl:u,region:d}=await e.createAndroidEmulator({...n,hostname:rA()}),m;try{tA("adb --version"),m="adb"}catch{if(process.env.ANDROID_HOME)m=nA.join(process.env.ANDROID_HOME,"platform-tools","adb");else throw new Error("adb not found in PATH and ANDROID_HOME not set")}t.info({emulatorName:s,apkToInstall:n.apkToInstall,region:d,apkDownloadUrl:u},"Android instance creation ok");let p=await eA({adbUrl:c,endpointUrl:l,token:a,logLevel:i,adbPath:m}),g=["https://github.com/appium/appium-uiautomator2-server/releases/download/v7.6.2/appium-uiautomator2-server-v7.6.2.apk","https://github.com/appium/appium-uiautomator2-server/releases/download/v7.6.2/appium-uiautomator2-server-debug-androidTest.apk","https://github.com/appium/io.appium.settings/releases/download/v5.14.15/settings_apk-debug.apk"];u&&g.push(u);let h=n.apkToInstall?.channel,f=n.apkToInstall?.tag;o(`Installing APK${h?` with channel ${h}`:""}${f?` and tag ${f}`:""}`),await Promise.all(g.map(T=>p.sendAsset(T))),o("Starting tunnel");let y=await p.startAdbTunnel();return{port:y.address.port,close:y.close,token:a,webRtcUrl:l,emulatorName:s}}async function la({onStatusUpdate:r,creationOpts:e,apiClient:t,logger:n,logLevel:o,appiumPort:i,socket:a}){let l=Date.now(),{close:c,port:s,limbarToken:u,limbarUrl:d,emulatorName:m}=await lA({apiClient:t,logger:n,creationOpts:e,onStatusUpdate:r}),p=[()=>t.deleteAndroidEmulator(m),c],g=async()=>{for(let f=p.length-1;f>=0;f-=1)try{await p[f]()}catch(y){if(y instanceof Error&&y.message.includes("ECONNREFUSED"))return;n.warn({err:y},"Error running cleanup task")}},h=async()=>{if(a&&!a.connected)throw await g(),new Error("Client disconnected before Appium driver could be started")};await h();try{let f=await aA({logger:n,logLevel:o,appiumPort:i,port:s,limbarStart:l,emulatorName:m,apiClient:t,onStatusUpdate:r,creationOpts:e});return p.push(f.appiumClose),p.push(async()=>f.driver.deleteSession()),await h(),{...f,emulatorName:m,limbarToken:u,limbarUrl:d,adbTunnelPort:s,cleanup:g,appiumPort:i}}catch(f){throw await g(),new Error(`Failed to start Appium driver: ${f}`)}}async function aA({logger:r,logLevel:e="warn",port:t,limbarStart:n,emulatorName:o,appiumPort:i}){let a=Date.now(),{close:l}=await sA({logger:r,logLevel:e,appiumPort:i}),c={platformName:"Android","appium:automationName":"UiAutomator2","appium:deviceName":"Android","appium:udid":`127.0.0.1:${t}`,"appium:newCommandTimeout":86400,"appium:skipDeviceInitialization":!0,"appium:skipServerInstallation":!0,"appium:androidInstallTimeout":3e5,"appium:autoWebview":!1,"appium:autoWebviewTimeout":0},s={hostname:"localhost",port:i,logLevel:e,capabilities:c},u=Date.now(),d=await iA(s);return await d.updateSettings({enableMultiWindows:!0}),r.info({timings:{limbarDuration:a-n,appiumDuration:u-a,wdioDuration:Date.now()-u},capabilities:c,emulatorName:o},"Started Appium driver"),{driver:d,appiumClose:l,appiumPort:i}}async function sA({logger:r,logLevel:e,appiumPort:t}){let n=await oA.main({port:t,address:"localhost",relaxedSecurityEnabled:!0,longStacktrace:e==="debug",logFormat:"json",loglevel:e});return{close:async()=>{await n.close()}}}async function lA({apiClient:r,logger:e,onStatusUpdate:t,creationOpts:n}){let{close:o,port:i,token:a,webRtcUrl:l,emulatorName:c}=await Wm({apiClient:r,logger:e,creationOpts:n,onStatusUpdate:t});return{port:i,close:o,limbarToken:a,limbarUrl:l,emulatorName:c}}import $m from"crypto";import cA from"fs";async function ca({tag:r,channel:e,filePath:t,apiClient:n,logger:o}){let i=await cA.promises.readFile(t),a=$m.createHash("md5").update(i).digest("base64"),l=$m.createHash("md5").update(i).digest("hex"),c=await n.generateAndroidAssetUrls({channel:e,tag:r??"latest",md5:a});if(c.md5&&(c.md5===a||c.md5===l)){o.info({channel:e,tag:r,md5:a,md5Hex:l},`Asset ${t} already exists on emulator platform`);return}if(c.uploadUrl){o.info({channel:e,tag:r,md5:a,uploadUrl:c.uploadUrl},`Uploading asset ${t} to emulator platform...`);try{let s=await fetch(c.uploadUrl,{headers:{"Content-Length":i.length.toString(),"Content-Type":"application/octet-stream"},method:"PUT",body:i});if(s.status!==200)throw new Error(`Got error response from emulator platform: ${s.status} ${await s.text()}`);o.info({channel:e,tag:r,md5:a},`Asset ${t} was uploaded successfully!`);return}catch(s){try{await n.deleteAndroidAsset(e,r??"latest")}catch(u){o.warn({err:u,tag:r,channel:e},"Failed to cleanup asset metadata for failed upload. Please contact Momentic support.")}throw o.error({err:s},"Failed to upload asset"),s}}throw new Error(`No upload URL was given for asset ${t}`)}import{execSync as Xh}from"child_process";import{existsSync as Px}from"fs";import{platform as Jh}from"os";import{dirname as Ox,join as Lx,resolve as Nx}from"path";import{z as qm}from"zod";var fk=qm.object({input:qm.string()});import{z as je}from"zod";var yk=je.object({srcs:je.array(je.string()),urls:je.array(je.string()),desiredSrc:je.string().optional(),desiredUrl:je.string().optional()}),Km=je.object({srcRegex:je.string().optional(),urlRegex:je.string().optional()}),Ym=je.object({x:je.number(),y:je.number(),correlation:je.number()}),Tk=je.object({searchImageBase64String:je.string(),pageImageBase64String:je.string(),id:je.string().uuid(),timeoutMs:je.number().max(1e4).min(0).optional()});import{z as I}from"zod";import*as L from"zod";import{extendZodWithOpenApi as uA}from"zod-openapi";uA(L);var Ar=(l=>(l.AI="AI",l.AI_HEALED="AI_HEALED",l.CLICK_TO_FIND="CLICK_TO_FIND",l.XY_PERCENT="XY_PERCENT",l.RECORDING="RECORDING",l.USER_CSS_SELECTOR="USER_CSS_SELECTOR",l.HEURISTIC_HEALED="HEURISTIC_HEALED",l))(Ar||{}),dA=L.object({mPathSelectorTokens:L.string().array(),frameSrcRegex:L.string().optional(),frameUrlRegex:L.string().optional(),indices:L.number().array()}),Kl=L.object({result:L.number(),traceId:L.string()}).array(),ua=L.object({type:L.literal("GCS_TRACES"),traces:Kl}),Xm=L.object({text:L.string().optional(),attributes:L.record(L.string(),L.string()).optional(),boundingBox:L.object({x:L.number(),y:L.number(),width:L.number(),height:L.number()}).optional()}),mA=L.object({selectors:L.string().array(),requirements:Xm.optional()}),wr=L.object({id:L.number().int(),dataMomenticId:L.number().int().optional(),selector:L.string().optional(),hybridSelector:L.object({textContent:L.string().nullish(),attributes:L.record(L.string(),L.string()),tagName:L.string(),expandShadowRoot:L.boolean().optional(),classNames:L.string().array(),nthChild:L.number()}).array().optional(),generatedSelectors:L.string().array().optional(),requirements:Xm.optional(),additionalElements:mA.array().optional(),role:L.string().optional(),name:L.string().optional(),numChildren:L.number().optional(),content:L.string().optional(),pathFromRoot:L.string().optional(),serializedHtml:L.string().optional().describe("pruned html including 1 neighbor and 1 layer of children. value for text inputs pruned."),nodeOnlySerializedHtml:L.string().optional().describe("outerHtml of the element without any children. value for text inputs pruned."),screenshotUrl:L.string().url().optional(),boundingBox:L.object({x:L.number().optional(),y:L.number().optional(),width:L.number(),height:L.number()}).describe("css pixel bounding box").optional(),frameCache:dA.optional(),inputDescription:L.string().optional().describe("the description that generated this cache"),targetSource:L.nativeEnum(Ar).optional(),targetUpdateTime:L.string().optional(),targetUpdateLoggerTags:L.record(L.string(),L.string()).optional(),cacheResolutionUpdateSource:L.string().optional(),cacheResolutionUpdateTime:L.string().optional(),cacheResolutionUpdateLoggerTags:L.record(L.string(),L.string()).optional(),memory:ua.optional()}).openapi({ref:"ElementTargetCache"});function da(r){return!!(r.serializedHtml||r.screenshotUrl||r.generatedSelectors||r.hybridSelector)}function Jm(r){r.serializedHtml=void 0,r.nodeOnlySerializedHtml=void 0,r.screenshotUrl=void 0,r.boundingBox=void 0,r.hybridSelector=void 0,r.generatedSelectors=void 0,r.id=-1}var pA=L.object({type:L.literal("description"),elementDescriptor:L.string().describe("Description of the element.")}).openapi({ref:"DescriptionTarget"}),gA=L.object({x:L.number(),y:L.number()}),hA=L.object({type:L.literal("coordinates"),pixels:gA}).openapi({ref:"CoordinatesTarget"});function Rr(r){return r.type==="description"}function Jt(r){return r.type==="coordinates"}var nt=L.discriminatedUnion("type",[pA,hA]).openapi({ref:"ElementTarget"});function Yl(r){if(!r)return!1;switch(r.type){case"description":return!!r.elementDescriptor}return!0}function Qm(r){return ua.safeParse(r).success}import{v4 as ae}from"uuid";import*as E from"zod";import{extendZodWithOpenApi as AA}from"zod-openapi";import{z as X}from"zod";import{extendZodWithOpenApi as fA}from"zod-openapi";import{z as Nn}from"zod";var Xl=Nn.object({result:Nn.boolean(),traceId:Nn.string()}).array(),Jl=Nn.object({type:Nn.literal("GCS_TRACES"),traces:Xl}),Ql=Nn.object({memory:Jl.optional()});fA(X);var Zm=X.object({plan:X.string().optional(),evidence:X.string().optional(),thoughts:X.string(),result:X.boolean(),relevantElements:X.array(X.number()).optional(),updatedMemory:Xl.optional()}),Cr=(o=>(o.CONTAINS="CONTAINS",o.STARTS_WITH="STARTS_WITH",o.EQUALS="EQUALS",o.EXISTS="EXISTS",o))(Cr||{});var SA=X.object({type:X.literal("ELEMENT_NAME"),negated:X.boolean().optional(),operation:X.nativeEnum(Cr),value:X.string()}).openapi({ref:"ElementNameAssertion"}),EA=X.object({type:X.literal("ELEMENT_STYLE"),negated:X.boolean().optional(),operation:X.nativeEnum(Cr),property:X.string(),value:X.string()}).openapi({ref:"ElementStyleAssertion"}),yA=X.object({type:X.literal("ELEMENT_CONTENT"),negated:X.boolean().optional(),operation:X.nativeEnum(Cr),value:X.string()}).openapi({ref:"ElementContentAssertion"}),TA=X.object({type:X.literal("ELEMENT_ATTRIBUTE"),negated:X.boolean().optional(),operation:X.nativeEnum(Cr),attr:X.string(),value:X.string()}).openapi({ref:"ElementAttributeValueAssertion"}),Dn=(i=>(i.EXISTS="EXISTS",i.VISIBLE="VISIBLE",i.ENABLED="ENABLED",i.EDITABLE="EDITABLE",i.FOCUSED="FOCUSED",i))(Dn||{}),bA=X.object({type:X.literal("ELEMENT_EXISTENCE"),negated:X.boolean().optional(),condition:X.nativeEnum(Dn).describe("Treated as the element exists AND is also ...")}).openapi({ref:"ElementExistenceAssertion"}),ep=X.discriminatedUnion("type",[yA,TA,bA,SA,EA]).openapi({ref:"ManualElementAssertion"});var vA=X.object({type:X.literal("CONTENT"),negated:X.boolean().optional(),value:X.string()}).openapi({ref:"PageContentAssertion"}),tp=X.discriminatedUnion("type",[vA]).openapi({ref:"ManualPageAssertion"});import ut from"zod";var Zl=ut.discriminatedUnion("type",[ut.object({type:ut.literal("SUBSTRING"),url:ut.string()}),ut.object({type:ut.literal("GLOB"),glob:ut.string()}),ut.object({type:ut.literal("REGEX"),regex:ut.string()}),ut.object({type:ut.literal("DOMAIN"),domain:ut.string()})]),Ho=ut.object({urlMatcher:Zl,method:ut.string().optional()});import{z as ie}from"zod";var ma=ie.object({url:ie.string(),method:ie.union([ie.literal("GET"),ie.literal("POST"),ie.literal("PUT"),ie.literal("DELETE"),ie.literal("PATCH")]),headers:ie.record(ie.string(),ie.string()).optional(),params:ie.record(ie.string(),ie.string()).optional(),body:ie.string().optional(),timeout:ie.number().int().optional().describe("Max seconds to wait for the request to complete")}),rp=ie.object({url:ie.string(),headers:ie.record(ie.string(),ie.string()).optional(),query:ie.string(),variables:ie.string().optional(),timeout:ie.number().int().optional().describe("Max seconds to wait for the request to complete")}),pa=ie.object({code:ie.string(),fragment:ie.boolean().optional(),environment:ie.union([ie.literal("NODE"),ie.literal("BROWSER")]).optional().describe("default NODE"),timeout:ie.number().int().max(60).optional().describe("Max seconds for the code to complete")});var Ze=(H=>(H.AI_EXTRACT="AI_EXTRACT",H.AI_ASSERTION="AI_ASSERTION",H.AUTH_LOAD="AUTH_LOAD",H.AUTH_SAVE="AUTH_SAVE",H.BLUR="BLUR",H.CAPTCHA="CAPTCHA",H.CLICK="CLICK",H.COOKIE="COOKIE",H.COPY="COPY",H.DIALOG="DIALOG",H.DRAG="DRAG",H.ELEMENT_CHECK="ELEMENT_CHECK",H.FILE_UPLOAD="FILE_UPLOAD",H.FOCUS="FOCUS",H.GO_BACK="GO_BACK",H.GO_FORWARD="GO_FORWARD",H.HOVER="HOVER",H.JAVASCRIPT="JAVASCRIPT",H.LOCAL_STORAGE="LOCAL_STORAGE",H.MOUSE_DRAG="MOUSE_DRAG",H.NAVIGATE="NAVIGATE",H.NEW_TAB="NEW_TAB",H.PAGE_CHECK="PAGE_CHECK",H.PASTE="PASTE",H.PRESS="PRESS",H.KEY_DOWN="KEY_DOWN",H.KEY_UP="KEY_UP",H.REFRESH="REFRESH",H.REQUEST="REQUEST",H.GRAPHQL_REQUEST="GRAPHQL_REQUEST",H.SCROLL_DOWN="SCROLL_DOWN",H.SCROLL_UP="SCROLL_UP",H.SCROLL_LEFT="SCROLL_LEFT",H.SCROLL_RIGHT="SCROLL_RIGHT",H.SELECT_OPTION="SELECT_OPTION",H.SWITCH_TAB="TAB",H.TYPE="TYPE",H.VISUAL_DIFF="VISUAL_DIFF",H.WAIT="WAIT",H.WAIT_FOR_URL="WAIT_FOR_URL",H.REGISTER_REQUEST_LISTENER="REGISTER_REQUEST_LISTENER",H.AWAIT_LISTENER="AWAIT_LISTENER",H.RECORD_REQUESTS="RECORD_REQUESTS",H.GET_RECORDED_REQUESTS="GET_RECORDED_REQUESTS",H.SET_HEADER="SET_HEADER",H.MOCK_ROUTE="MOCK_ROUTE",H.REMOVE_ROUTE_MOCK="REMOVE_ROUTE_MOCK",H.OFFLINE_MODE="OFFLINE_MODE",H.SUCCESS="SUCCESS",H))(Ze||{});AA(E);var G=E.object({thoughts:E.string().optional(),id:E.string().uuid().describe("unique identifier to this step, used for step cache")}),_t=E.object({useSelector:E.boolean().optional(),force:E.boolean().optional(),disableCache:E.boolean().optional().describe("disable element caching for this step"),iframeUrl:E.string().optional().describe("url or url regex for the iframe")}).openapi({ref:"CommonTargetingOptions"}),Mt=E.object({target:wr}).optional().openapi({ref:"SingleTargetCache"});function op(r){return Mt.safeParse(r).success}var ha=E.object({loadTimeout:E.number().int().max(60).optional().describe("Max seconds for the page to load")}),wA=G.merge(ha).merge(E.object({type:E.literal("NAVIGATE"),url:E.string()})).openapi({ref:"NavigateCommand"}),fa=_t.merge(E.object({cache:Mt})),kn=G.merge(fa.merge(E.object({target:nt.optional(),type:E.literal("SCROLL_UP"),deltaY:E.number().optional()}))).openapi({ref:"ScrollUpCommand"}),Un=G.merge(fa.merge(E.object({target:nt.optional(),type:E.literal("SCROLL_DOWN"),deltaY:E.number().optional()}))).openapi({ref:"ScrollDownCommand"}),Fn=G.merge(fa.merge(E.object({target:nt.optional(),type:E.literal("SCROLL_LEFT"),deltaX:E.number().optional()}))).openapi({ref:"ScrollLeftCommand"}),Bn=G.merge(fa.merge(E.object({target:nt.optional(),type:E.literal("SCROLL_RIGHT"),deltaX:E.number().optional()}))).openapi({ref:"ScrollRightCommand"}),Wk=E.discriminatedUnion("type",[kn,Un,Fn,Bn]).openapi({ref:"AllScrollCommands"}),RA=G.merge(E.object({type:E.literal("DIALOG"),action:E.union([E.literal("ACCEPT"),E.literal("DISMISS")])})).openapi({ref:"DialogCommand"}),CA=G.merge(E.object({type:E.literal("WAIT"),delay:E.number()})).openapi({ref:"WaitCommand"}),xA=E.object({caseInsensitive:E.boolean().optional().describe("Whether to ignore case when matching the URL"),negated:E.boolean().optional().describe("Wait for the URL to NOT match the provided matcher instead."),timeout:E.number().int().optional().describe("Max seconds to wait for the URL to match")}),_A=G.extend({type:E.literal("WAIT_FOR_URL"),matcher:Zl}).merge(xA).openapi({ref:"WaitUrlCommand"}),MA=G.merge(ha).merge(E.object({type:E.literal("REFRESH")})).openapi({ref:"RefreshCommand"}),IA=G.merge(E.object({type:E.literal("GO_BACK")})).openapi({ref:"GoBackCommand"}),PA=G.merge(E.object({type:E.literal("GO_FORWARD")})).openapi({ref:"GoForwardCommand"}),OA=G.extend({type:E.literal("AUTH_SAVE")}).openapi({ref:"AuthSaveCommand"}),LA=G.extend({type:E.literal("AUTH_LOAD"),storageState:E.string().describe("JSON string auth state. Leave blank or set to the empty string to clear all existing authentication.")}).openapi({ref:"AuthLoadCommand"}),ec=G.merge(_t).extend({type:E.literal("CAPTCHA")}).openapi({ref:"CaptchaCommand"}),NA=G.extend({type:E.literal("COPY"),value:E.string()}).openapi({ref:"CopyCommand"}),DA=G.extend({type:E.literal("PASTE")}).openapi({ref:"PasteCommand"}),kA=G.merge(pa).extend({type:E.literal("JAVASCRIPT")}).openapi({ref:"JavaScriptCommand"}),Vo=G.merge(_t).extend({type:E.literal("CLICK"),target:nt,doubleClick:E.boolean().optional(),rightClick:E.boolean().optional(),waitForDownload:E.boolean().optional().describe("Wait for the click to trigger a file download and for the file download to complete."),delayMs:E.number().optional(),downloadTimeoutMs:E.number().optional(),cache:Mt,relativePosition:E.object({x:E.number(),y:E.number()}).optional()}).openapi({ref:"ClickCommand"}),ip=E.object({fromTarget:wr.optional(),toTarget:wr.optional()}),jo=G.merge(_t).merge(E.object({type:E.literal("DRAG"),fromTarget:nt,toTarget:nt,steps:E.number().optional(),hoverSeconds:E.number().optional().describe("Seconds to hover the object before dropping"),cache:ip.optional()})).openapi({ref:"DragCommand"}),Wo=G.merge(_t).merge(E.object({type:E.literal("MOUSE_DRAG"),target:nt.optional(),deltaX:E.string().describe("pixels to move horizontally, can be template"),deltaY:E.string().describe("pixels to move vertically, can be template"),steps:E.number().optional(),cache:Mt})).openapi({ref:"MouseDragCommand"}),$o=G.merge(_t).merge(E.object({type:E.literal("HOVER"),target:nt,cache:Mt})).openapi({ref:"HoverCommand"}),qo=G.merge(_t).merge(E.object({type:E.literal("FOCUS"),target:nt,cache:Mt})).openapi({ref:"FocusCommand"}),Ko=G.merge(_t).extend({type:E.literal("BLUR"),target:nt.optional(),cache:Mt}).openapi({ref:"BlurCommand"}),UA=E.object({type:E.literal("URL"),url:E.string()}).describe("Accessible link to the file, either public http or local file://").openapi({ref:"UrlSource"}),FA=E.object({type:E.literal("USER_FILE"),name:E.string()}).describe("Accessible link to the file, references the google cloud file").openapi({ref:"UploadedFileSource"}),BA=G.extend({type:E.literal("FILE_UPLOAD"),fileSource:E.discriminatedUnion("type",[UA,FA]),filename:E.string().optional()}).openapi({ref:"FileUploadCommand"}),zA=E.discriminatedUnion("type",[E.object({type:E.literal("VALUE"),value:E.string()}),E.object({type:E.literal("LABEL"),label:E.string()}),E.object({type:E.literal("INDEX"),index:E.coerce.string()})]),Yo=G.merge(_t).extend({type:E.literal("SELECT_OPTION"),target:nt,cache:Mt,choice:zA.describe("new field for selecting options, optional for backcompat")}).openapi({ref:"SelectOptionCommand"}),tc=E.union([E.literal("MULTIMODAL"),E.literal("VISION_ONLY")]),Sa=G.merge(E.object({type:E.literal("AI_ASSERTION"),assertion:E.string(),disableCache:E.boolean().optional(),iframeUrl:E.string().optional(),contextChoice:tc.optional(),timeout:E.number().int().optional().describe("Max seconds to wait for assertion to be true"),cache:Ql.optional()})).openapi({ref:"AIAssertionCommand"}),xr=5,rc=600,Xo=G.merge(_t).extend({type:E.literal("ELEMENT_CHECK"),target:nt,assertion:ep,cache:Mt.or(Ql).optional(),timeout:E.number().int().min(0).max(rc).optional().describe("max seconds to wait for the assertion to be true")}).openapi({ref:"ElementAssertionCommand"}),GA=G.extend({type:E.literal("PAGE_CHECK"),assertion:tp,iframeUrl:E.string().optional().describe("url or url regex for the iframe"),timeout:E.number().int().min(0).max(rc).optional().describe("max seconds to wait for the assertion to be true")}).openapi({ref:"PageAssertionCommand"}),HA=G.merge(E.object({type:E.literal("AI_EXTRACT"),goal:E.string(),schema:E.string().optional(),envKey:E.string().optional(),disableCache:E.boolean().optional(),iframeUrl:E.string().optional()})).openapi({ref:"AIExtractCommand"}),VA=E.object({clearContent:E.boolean().optional(),forceClearContent:E.boolean().optional(),delay:E.number().min(0).max(1e3).optional().describe("Delay between each press in milliseconds."),force:E.boolean().optional(),pressEnter:E.boolean().optional()}),ap=25,Jo=G.merge(_t).merge(VA).extend({type:E.literal("TYPE"),target:nt.optional(),value:E.string(),cache:Mt}).openapi({ref:"TypeCommand"}),jA=G.merge(E.object({type:E.literal("PRESS"),value:E.string(),repeat:E.number().optional(),convertMeta:E.boolean().optional(),delayMs:E.number().optional()})).openapi({ref:"PressCommand"}),WA=G.merge(E.object({type:E.literal("KEY_DOWN"),value:E.string(),convertMeta:E.boolean().optional()})).openapi({ref:"KeyDownCommand"}),$A=G.merge(E.object({type:E.literal("KEY_UP"),value:E.string(),convertMeta:E.boolean().optional()})).openapi({ref:"KeyUpCommand"}),qA=E.object({type:E.literal("SUBSTRING"),substring:E.string()}),KA=E.object({type:E.literal("REGEX"),pattern:E.string()}),YA=E.object({type:E.literal("INDEX"),index:E.coerce.string()}),XA=E.discriminatedUnion("type",[qA,KA,YA]),JA=G.merge(ha).merge(E.object({type:E.literal("TAB"),action:XA})).openapi({ref:"TabCommand"}),QA=G.merge(ha).merge(E.object({type:E.literal("NEW_TAB"),url:E.string()})).openapi({ref:"NewTabCommand"}),ZA=G.merge(E.object({type:E.literal("COOKIE"),value:E.string()})).openapi({ref:"CookieCommand"}),ew=G.merge(E.object({type:E.literal("LOCAL_STORAGE"),key:E.string(),value:E.string()})).openapi({ref:"LocalStorageCommand"}),tw=G.extend({type:E.literal("REQUEST")}).merge(ma).openapi({ref:"RequestCommand"}),rw=G.extend({type:E.literal("GRAPHQL_REQUEST")}).merge(rp).openapi({ref:"GraphQLRequestCommand"}),nw=G.merge(E.object({type:E.literal("SUCCESS"),condition:Sa.optional()})).openapi({ref:"SuccessCommand"}),ow=G.merge(E.object({type:E.literal("FAILURE")})).openapi({ref:"FailureCommand"}),iw=E.object({data:E.string().describe("location at which to find a jpg"),width:E.number(),height:E.number()}),Qo=G.merge(_t).merge(E.object({type:E.literal("VISUAL_DIFF"),threshold:E.number().optional().describe("default 0.1"),target:nt.optional(),screenshot:iw.optional(),cache:Mt})).openapi({ref:"VisualDiffCommand"}),aw=G.merge(E.object({type:E.literal("REGISTER_REQUEST_LISTENER"),requestMatcher:Ho,key:E.string()})).openapi({ref:"RegisterRequestListenerCommand"}),sw=G.merge(E.object({type:E.literal("AWAIT_LISTENER"),key:E.string(),timeout:E.number().optional().describe("timeout")})).openapi({ref:"WaitForListenerCommand"}),lw=G.merge(E.object({type:E.literal("RECORD_REQUESTS"),requestMatcher:Ho,key:E.string()})).openapi({ref:"RecordRequestsCommand"}),cw=G.merge(E.object({type:E.literal("GET_RECORDED_REQUESTS"),key:E.string()})).openapi({ref:"GetRecordedRequestsCommand"}),uw=G.merge(E.object({type:E.literal("SET_HEADER"),name:E.string(),value:E.string(),requestMatcher:Ho.optional()})).openapi({ref:"SetHeaderCommand"}),dw=G.merge(E.object({type:E.literal("MOCK_ROUTE"),requestMatcher:Ho,responseGenerator:E.string().describe("JavaScript code to generate a response"),fetchOriginalResponse:E.boolean().optional().describe("Whether to fetch the real response and pass it to the response generator. If enabled, the original response will be available as `response` in the code."),key:E.string().optional().describe("Key to reference this mock. This only needs to be set if you plan to remove the mock later in the test.")}).openapi({ref:"MockRouteCommandOptions"})),mw=G.merge(E.object({type:E.literal("REMOVE_ROUTE_MOCK"),key:E.string().optional().describe("Key of the mock to remove. If not set, all route mocks will be removed.")}).openapi({ref:"RemoveRouteMockCommandOptions"})),pw=G.merge(E.object({type:E.literal("OFFLINE_MODE"),enable:E.boolean()})).openapi({ref:"OfflineModeCommand"}),sp=E.discriminatedUnion("type",[Vo,Jo,jA,WA,$A,Yo,wA,Un,kn,Sa,$o,CA,nw]),gw=E.discriminatedUnion("type",[HA,LA,OA,ec,ZA,NA,RA,jo,Xo,BA,IA,PA,kA,ew,Wo,QA,GA,DA,MA,tw,rw,Fn,Bn,JA,Qo,qo,Ko,_A,aw,sw,lw,cw,uw,dw,mw,pw]),zn=E.discriminatedUnion("type",[...sp.options,...gw.options]).openapi({ref:"Command"}),Ea=E.discriminatedUnion("type",[...sp.options,ow]);function mr(r){let e;switch(r){case"PASTE":case"AUTH_SAVE":case"VISUAL_DIFF":case"SUCCESS":case"SCROLL_DOWN":case"SCROLL_UP":case"SCROLL_LEFT":case"SCROLL_RIGHT":case"CAPTCHA":case"GO_BACK":case"GO_FORWARD":case"REFRESH":e={id:ae(),type:r};break;case"AUTH_LOAD":{e={id:ae(),type:r,storageState:""};break}case"AI_EXTRACT":e={id:ae(),type:r,goal:""};break;case"DIALOG":e={id:ae(),type:r,action:"DISMISS"};break;case"DRAG":e={id:ae(),type:r,fromTarget:{type:"description",elementDescriptor:""},toTarget:{type:"description",elementDescriptor:""}};break;case"MOUSE_DRAG":e={id:ae(),type:r,deltaX:"0",deltaY:"0",steps:1};break;case"WAIT_FOR_URL":e={id:ae(),type:r,matcher:{type:"SUBSTRING",url:""}};break;case"WAIT":e={id:ae(),type:r,delay:1};break;case"BLUR":e={id:ae(),type:r};break;case"HOVER":case"FOCUS":case"CLICK":e={id:ae(),type:r,target:{type:"description",elementDescriptor:""}};break;case"COOKIE":case"PRESS":case"COPY":case"TYPE":e={id:ae(),type:r,value:"",clearContent:!0};break;case"KEY_DOWN":case"KEY_UP":e={id:ae(),type:r,value:""};break;case"SELECT_OPTION":e={id:ae(),type:r,target:{type:"description",elementDescriptor:""},choice:{type:"VALUE",value:""}};break;case"NAVIGATE":case"NEW_TAB":return{id:ae(),type:r,url:""};case"TAB":e={id:ae(),type:r,action:{type:"SUBSTRING",substring:""}};break;case"REQUEST":e={id:ae(),type:r,url:"",method:"GET"};break;case"GRAPHQL_REQUEST":e={id:ae(),type:r,url:"",query:""};break;case"LOCAL_STORAGE":e={id:ae(),type:r,key:"",value:""};break;case"JAVASCRIPT":e={id:ae(),type:r,code:""};break;case"AI_ASSERTION":e={id:ae(),type:r,assertion:""};break;case"FILE_UPLOAD":{e={id:ae(),type:r,fileSource:{type:"URL",url:""}};break}case"ELEMENT_CHECK":{e={id:ae(),type:r,target:{type:"description",elementDescriptor:""},assertion:{type:"ELEMENT_EXISTENCE",condition:"EXISTS"}};break}case"PAGE_CHECK":{e={id:ae(),type:r,assertion:{type:"CONTENT",value:""}};break}case"REGISTER_REQUEST_LISTENER":{e={id:ae(),type:r,requestMatcher:{urlMatcher:{type:"REGEX",regex:""}},key:""};break}case"AWAIT_LISTENER":{e={id:ae(),type:r,key:""};break}case"RECORD_REQUESTS":{e={id:ae(),type:r,requestMatcher:{urlMatcher:{type:"REGEX",regex:""}},key:""};break}case"GET_RECORDED_REQUESTS":{e={id:ae(),type:r,key:""};break}case"SET_HEADER":{e={id:ae(),type:r,name:"",value:""};break}case"MOCK_ROUTE":{e={id:ae(),type:r,requestMatcher:{urlMatcher:{type:"REGEX",regex:""}},responseGenerator:""};break}case"REMOVE_ROUTE_MOCK":{e={id:ae(),type:r};break}case"OFFLINE_MODE":{e={id:ae(),type:r,enable:!0};break}default:return(n=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(r)}return e}function lp(r){switch(r.type){case"BLUR":case"CLICK":case"DRAG":case"FOCUS":case"HOVER":case"MOUSE_DRAG":case"PRESS":case"KEY_DOWN":case"KEY_UP":case"SCROLL_DOWN":case"SCROLL_UP":case"SCROLL_LEFT":case"SCROLL_RIGHT":case"TYPE":return!0;case"AUTH_LOAD":case"AUTH_SAVE":case"AWAIT_LISTENER":case"SUCCESS":case"AI_ASSERTION":case"AI_EXTRACT":case"CAPTCHA":case"COOKIE":case"COPY":case"DIALOG":case"ELEMENT_CHECK":case"FILE_UPLOAD":case"GET_RECORDED_REQUESTS":case"GO_BACK":case"GO_FORWARD":case"GRAPHQL_REQUEST":case"JAVASCRIPT":case"LOCAL_STORAGE":case"NAVIGATE":case"NEW_TAB":case"PASTE":case"PAGE_CHECK":case"RECORD_REQUESTS":case"REGISTER_REQUEST_LISTENER":case"REFRESH":case"REQUEST":case"SELECT_OPTION":case"SET_HEADER":case"TAB":case"VISUAL_DIFF":case"WAIT":case"WAIT_FOR_URL":case"OFFLINE_MODE":case"MOCK_ROUTE":case"REMOVE_ROUTE_MOCK":return!1;default:return(t=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(r)}}import{z as hw}from"zod";var Xk=hw.discriminatedUnion("type",[Ko,ec,Vo,jo,qo,$o,Wo,kn,Un,Fn,Bn,Yo,Jo,Qo,Xo]);import{z as fw}from"zod";import{z as _r}from"zod";function Zo(r){return _r.object({key:_r.string(),testId:_r.string().optional(),moduleId:_r.string().optional(),organizationId:_r.string(),value:r})}function ei(r){return Zo(r).extend({uniqueKey:_r.string()})}function ya(r){return _r.record(_r.string(),ei(r))}var dt={type:!0,cache:!0},Gn=fw.discriminatedUnion("type",[Sa.pick(dt),Ko.pick(dt),Vo.pick(dt),jo.pick(dt),Xo.pick(dt),qo.pick(dt),$o.pick(dt),Wo.pick(dt),kn.pick(dt),Un.pick(dt),Fn.pick(dt),Bn.pick(dt),Yo.pick(dt),Jo.pick(dt),Qo.pick(dt)]),nc=Object.values(Ze).filter(r=>Gn.options.some(e=>e.shape.type.safeParse(r).success));zn.options.forEach(r=>{if("target"in r.shape&&!nc.includes(r.shape.type.value))throw new Error(`Command ${r.shape.type.value} has a target but no cache`)});function cp(r){return nc.includes(r.type)}var up=Zo(Gn),dp=ei(Gn),oU=ya(Gn);import{z as oc}from"zod";import{extendZodWithOpenApi as yw}from"zod-openapi";import{z as mp}from"zod";import{extendZodWithOpenApi as Sw}from"zod-openapi";import{z as Qr}from"zod";var It=Qr.object({index:Qr.number().optional().describe("global index within a test (in-order traversal)"),id:Qr.string(),skipped:Qr.boolean().optional(),envKey:Qr.string().optional().describe("key in the environment to save the result of this step to"),aiSuggested:Qr.boolean().optional(),retries:Qr.number().optional()});Sw(mp);var Ew=It.extend({type:mp.literal("PRESET_ACTION")}),Pt=Ew.extend({command:zn}).openapi({ref:"PresetAction"});yw(oc);var Zr=It.extend({type:oc.literal("AI_ACTION"),text:oc.string(),steps:Pt.array().optional()}).openapi({ref:"AIAction"});import{z as mt}from"zod";import{z as Ta}from"zod";import{extendZodWithOpenApi as Tw}from"zod-openapi";Tw(Ta);var Hn=It.extend({type:Ta.literal("AI_ACTION_DYNAMIC"),text:Ta.string(),retries:Ta.number().optional()}).openapi({ref:"AIActionDynamic"});import{z as pp}from"zod";var ic=It.extend({type:pp.literal("CONDITIONAL"),skipped:pp.boolean().optional()});import{z as re}from"zod";var bw=re.object({cacheKey:re.string(),cacheExpiryMs:re.number()}),ac=It.extend({id:re.string().uuid().describe("ID of the module step itself. Used to 'namespace' step cache entries."),inputs:re.record(re.string()).optional(),cacheConfig:bw.optional()}),pr=ac.extend({type:re.literal("MODULE"),moduleId:re.string().uuid()}),vw=re.union([pr.pick({type:!0,moduleId:!0}),re.record(re.unknown())]),Aw=re.object({type:re.literal("URL_REGEX"),regex:re.string()}),ww=re.object({type:re.literal("PAGE_CHECK"),substring:re.string()}),sc=re.object({cacheInvalidation:re.discriminatedUnion("type",[ww,Aw]).optional()}),Ot=re.object({moduleId:re.string().uuid(),name:re.string(),description:re.string().nullish(),enabled:re.boolean().nullish(),parameters:re.string().array().nullish(),defaultParameters:re.record(re.string(),re.string()).nullish(),parameterEnums:re.record(re.string(),re.string().array()).nullish(),defaultCacheKey:re.string().nullish(),defaultCacheTtl:re.number().nullish(),defaultCacheAllInvocations:re.boolean().nullish(),autoAuth:re.boolean().nullish(),advanced:sc.nullish()});import{z as Lt}from"zod";var gp=(n=>(n.ALWAYS="ALWAYS",n.ON_FAILURE="ON_FAILURE",n.ON_ACTION_FAILURE="ON_ACTION_FAILURE",n))(gp||{});var Rw=Lt.discriminatedUnion("type",[Lt.object({type:Lt.literal("NAVIGATE_URL"),url:Lt.string().url()}),Lt.object({type:Lt.literal("GO_TO_SECTION_START")})]),Cw=Lt.object({trigger:Lt.nativeEnum(gp).optional(),attempts:Lt.number().int().optional(),restartBehavior:Rw}),ti=It.extend({type:Lt.literal("SECTION"),description:Lt.string().describe("user provided goal of what the section should accomplish"),plan:Lt.string().array().optional(),autohealingConfig:Cw.optional()});var hp=Ot.merge(ac).extend({type:mt.literal("RESOLVED_MODULE"),steps:mt.lazy(()=>$e.array())}),ri=Ot.extend({steps:mt.lazy(()=>$e.array())}),lc=ti.extend({steps:mt.lazy(()=>pt.array())}),xw=ti.extend({steps:mt.lazy(()=>$e.array())}),Vn=ic.extend({blocks:mt.object({assertion:mt.lazy(()=>Pt),steps:mt.lazy(()=>pt.array())}).array(),elseSteps:mt.lazy(()=>pt.array().optional())}),_w=ic.extend({blocks:mt.object({assertion:mt.lazy(()=>Pt),steps:mt.lazy(()=>$e.array())}).array(),elseSteps:mt.lazy(()=>$e.array().optional())}),pt=mt.discriminatedUnion("type",[Pt,Zr,Hn,pr,Vn,lc]),$e=mt.discriminatedUnion("type",[Pt,Zr,Hn,hp,_w,xw]);import{z as Nt}from"zod";var Mw=Nt.object({steps:pt.array(),beforeSteps:pt.array().nullish(),afterSteps:pt.array().nullish()}),jn=Nt.object({steps:$e.array(),beforeSteps:$e.array().nullish(),afterSteps:$e.array().nullish()}),en=Nt.object({steps:Nt.record(Nt.string(),Nt.unknown()).array(),beforeSteps:Nt.record(Nt.string(),Nt.unknown()).array().nullish(),afterSteps:Nt.record(Nt.string(),Nt.unknown()).array().nullish()});var Wn="1.0.21",ba="0.0.1";var fp=I.object({phrase:I.string()}),cc=I.object({thoughts:I.string().optional(),result:I.union([I.literal("NOT_FOUND"),I.string(),I.number(),I.array(I.unknown()),I.record(I.unknown(),I.unknown()),I.unknown()])}),VF=I.object({text:I.string()}),Sp=I.object({attributes:I.array(I.string()).optional(),text:I.boolean().optional(),boundingBox:I.boolean().optional()}),Iw=I.object({id:I.number().int(),requirements:Sp}),Pw=Iw.array(),Ep=I.object({thoughts:I.string(),review:I.string().optional(),id:I.number().int(),updatedMemory:Kl.optional(),requirements:Sp.optional(),additionalElements:Pw.optional()});var uc=(p=>(p.NO_DESCRIPTION_PROVIDED="NO_DESCRIPTION_PROVIDED",p.FEW_WORDS="FEW_WORDS",p.STYLE_TAG="STYLE_TAG",p.TYPE_IN_DESCRIPTION="TYPE_IN_DESCRIPTION",p.HARDCODED_ATTRIBUTE="HARDCODED_ATTRIBUTE",p.NONE="NONE",p.AMBIGUOUS_DESCRIPTION="AMBIGUOUS_DESCRIPTION",p.AMBIGUOUS_ASSERTION="AMBIGUOUS_ASSERTION",p.PREFER_PAGE_CHECK="PREFER_PAGE_CHECK",p.PREFER_ASSERTION="PREFER_ASSERTION",p.HTML_ELEMENTS="HTML_ELEMENTS",p.MULTIPLE_ELEMENTS_DESCRIPTION="MULTIPLE_ELEMENTS_DESCRIPTION",p.NEEDS_DATE_VARIABLE="NEEDS_DATE_VARIABLE",p))(uc||{}),yp=(o=>(o.NONE="NONE",o.AMBIGUOUS_DESCRIPTION="AMBIGUOUS_DESCRIPTION",o.COPILOT_MISUSE="COPILOT_MISUSE",o.IRRELEVANT_MESSAGE="IRRELEVANT_MESSAGE",o))(yp||{});var Tp=I.object({thoughts:I.string(),category:I.nativeEnum(uc)}),bp=I.object({thoughts:I.string(),category:I.nativeEnum(yp)}),Ow=I.discriminatedUnion("op",[I.object({op:I.literal("replace"),path:I.string(),value:I.string()}),I.object({op:I.literal("add"),path:I.string(),value:I.string()}),I.object({op:I.literal("remove"),path:I.string()})]),jF=I.object({thoughts:I.string(),patches:Ow.array()}),Lw=[I.literal("add"),I.literal("replace"),I.literal("remove")],Nw=I.object({op:I.union(Lw),path:I.string(),value:$e.optional()}),vp=I.object({patches:Nw.array(),thoughts:I.string()}),Ap=(n=>(n.LEGITIMATE="LEGITIMATE",n.RECOVERABLE="RECOVERABLE",n.INELIGIBLE="INELIGIBLE",n))(Ap||{}),wp=I.object({thoughts:I.string(),scenario:I.nativeEnum(Ap),instructions:I.string().nullish()}),Rp=I.object({reasoning:I.string(),scenario:I.string(),patch:I.null().optional()}),WF=I.object({thoughts:I.string(),evaluation:I.number().min(0).max(10)}),$F=I.object({observations:I.string(),reasoning:I.string(),command:Ea});var dc=I.object({summary:I.string(),reasoning:I.string(),evaluation:I.discriminatedUnion("type",[I.object({type:I.literal("DONE")}),I.object({type:I.literal("RIGHT_TRACK")}),I.object({type:I.literal("WRONG_TRACK"),feedback:I.string()}),I.object({type:I.literal("IMPOSSIBLE")})])}),Dw=I.object({startId:I.number().int(),endId:I.number().int()}),Cp=I.object({categoryThoughts:I.string(),category:I.string(),relevantSections:Dw.array()});import{z as _}from"zod";import*as J from"zod";var QF=J.object({thoughts:J.string().optional().describe("only provided if a description was provided"),target:wr.optional().describe("only provided if a description was provided"),pageState:J.string().optional().describe("serialized a11y tree, only provided if a description was provided"),options:J.object({label:J.string(),value:J.string()}).array().optional().describe("list of options, provided for <select> elements only"),screenshot:J.object({data:J.string(),height:J.number().int(),width:J.number().int()}).optional().describe("only provided if returnScreenshot is true")}),xp=J.union([J.literal("ELEMENT_CHECK"),J.literal("NEGATED_CHECK"),J.literal("NEGATED_ELEMENT_VISIBLE_CHECK"),J.literal("SELECT_OPTION"),J.literal("TYPE")]);function ni(r){if(!("useSelector"in r&&r.useSelector)){if(r.type==="SELECT_OPTION")return"SELECT_OPTION";if(r.type==="TYPE")return"TYPE";if(r.type==="ELEMENT_CHECK"&&r.assertion.type==="ELEMENT_EXISTENCE"&&r.assertion.condition==="EXISTS"&&r.assertion.negated)return"NEGATED_CHECK";if(r.type==="ELEMENT_CHECK"&&r.assertion.type==="ELEMENT_EXISTENCE"&&r.assertion.condition==="VISIBLE"&&r.assertion.negated)return"NEGATED_ELEMENT_VISIBLE_CHECK";if(r.type==="ELEMENT_CHECK")return"ELEMENT_CHECK"}}var oi=(a=>(a.USER_SELECTOR="USER_SELECTOR",a.CSS_SELECTOR="CSS_SELECTOR",a.HYBRID_SELECTOR="HYBRID_SELECTOR",a.HTML_DISTANCE="HTML_DISTANCE",a.TEMPLATE_MATCHING="TEMPLATE_MATCHING",a.AUTO_FRAME="AUTO_FRAME",a))(oi||{}),$n=J.object({matched:J.boolean(),reason:J.string().optional().describe("Human understandable description"),logs:J.string().array().optional().describe("Logs for debugging")}),kw=$n.extend({type:J.literal("USER_SELECTOR")}),Uw=$n.extend({type:J.literal("CSS_SELECTOR"),selectors:J.string().array()}),Fw=$n.extend({type:J.literal("HYBRID_SELECTOR")}),Bw=$n.extend({type:J.literal("HTML_DISTANCE"),distance:J.number().optional(),closestElement:J.string().optional(),savedElement:J.string().optional()}),zw=$n.extend({type:J.literal("TEMPLATE_MATCHING"),elementImageUrl:J.string().url()}),Gw=$n.extend({type:J.literal("AUTO_FRAME"),logs:J.string().array().optional()}),_p=J.discriminatedUnion("type",[kw,Uw,Fw,Bw,zw,Gw]);import{z as li}from"zod";import{z as Qw}from"zod";import*as z from"zod";import{extendZodWithOpenApi as jw}from"zod-openapi";import{cloneDeep as cB}from"lodash-es";import dB from"truncate-json";import*as nn from"zod";import{extendZodWithOpenApi as Hw}from"zod-openapi";import{z as ot}from"zod";import{z as fe}from"zod";var mc=fe.object({autoFollowNewTabs:fe.boolean().optional().describe("Deprecated: Auto-follow new tabs that are opened."),showZeroOpacityElements:fe.union([fe.boolean(),fe.literal("inputs-only")]).optional(),ignoreHrefForCaching:fe.boolean().optional(),disableSecondaryCacheResolution:fe.boolean().optional(),hybridSelectorMode:fe.enum(["off","test","prefer"]).optional(),globalLocatorRedirect:fe.boolean().optional(),visualActions:fe.boolean().optional(),autoExpandIframes:fe.boolean().optional(),disableHtmlSnapshots:fe.boolean().optional(),importantAttributes:fe.string().array().optional(),importantClasses:fe.string().array().optional(),importantStyles:fe.string().array().optional()});var Mp=1e4,Ip=6e4,tn=mc.extend({pageLoadTimeoutMs:fe.number().optional().refine(r=>r===void 0||r<=Ip&&r>=-1,{message:`Page load timeout must be between 0 and ${Ip/1e3} seconds`}).describe("global page load timeout default for all tests in ms, can still be overridden by individual tests"),smartWaitingTimeoutMs:fe.number().optional().refine(r=>r===void 0||r<=Mp&&r>=-1,{message:`Smart waiting timeout must be between 0 and ${Mp/1e3} seconds`}),localChromeExtensionPaths:fe.string().array().optional(),extraHeaders:fe.record(fe.string(),fe.string()).optional().describe("HTTP headers to be sent on every request"),userAgent:fe.string().optional(),disableGpu:fe.boolean().optional(),bustCacheOnBoundingBoxChange:fe.boolean().optional().describe("Bust the cache if no elements are matched that have the same bounding box and location as the original element. This will improve accuracy on sites that use many same components, at the expense of stability and speed."),allowPartialAccessibilityTree:fe.boolean().optional().describe("Allow fetching the partial accessibility tree if fetching the full tree takes too long."),ignoreHttpsErrors:fe.boolean().optional().describe("Ignore HTTPS errors, such as self-signed certificates and certificate errors. This can be useful for testing sites that use self-signed certificates or certificate errors.")});var pc="BASE_URL";var rn="ENV_NAME",qn="TEST_NAME",oB={[pc]:"https://www.google.com"},Pp=ot.string().describe("Name of the fixture (must be available locally in the fixtures directory)."),Op=ot.object({name:ot.string(),variables:ot.record(ot.string().describe("variable name"),ot.string().describe("variable value"))}),Lp=ot.object({name:ot.string(),variables:ot.record(ot.string().describe("variable name"),ot.unknown().describe("variable value")),browser:tn.optional()});var iB=ot.object({name:ot.string(),variables:ot.record(ot.string().describe("variable name"),ot.unknown().describe("variable value"))});Hw(nn);var gc=nn.object({env:nn.record(nn.unknown())}).openapi({ref:"TestContextSnapshot"});var et=(i=>(i.SUCCESS="SUCCESS",i.FAILED="FAILED",i.RUNNING="RUNNING",i.IDLE="IDLE",i.CANCELLED="CANCELLED",i))(et||{}),hc=(n=>(n.SUCCESS="SUCCESS",n.FAILED="FAILED",n.CANCELLED="CANCELLED",n))(hc||{});import{z as Qt}from"zod";import{extendZodWithOpenApi as Vw}from"zod-openapi";Vw(Qt);var ge=(m=>(m.AI_PROVIDER="AIProviderError",m.USER_INFRA="UserInfrastructureError",m.ACTION_FAILURE="ActionFailureError",m.ASSERTION_FAILURE="AssertionFailureError",m.CONFIG_ERROR="UserConfigurationError",m.SETUP_FAILURE="SetupFailureError",m.TEARDOWN_FAILURE="TeardownFailureError",m.WEB_AGENT_PLATFORM="InternalWebAgentError",m.UNKNOWN_PLATFORM="InternalPlatformError",m.JOB_TIMEOUT="JobTimeoutError",m.CONCURRENCY_ERROR="ConcurrencyError",m.UNKNOWN="UnknownError",m))(ge||{});var fc=Qt.object({reason:Qt.nativeEnum(ge),previousStepsDescription:Qt.array(Qt.string()).optional(),summary:Qt.string(),rootCause:Qt.string().optional()}).openapi({ref:"TestResultClassification"}),va=Qt.object({errorMessage:Qt.string(),errorStack:Qt.string().optional(),classification:fc.optional()}).openapi({ref:"TestFailureDetails"});jw(z);var Sc=z.object({beforeUrl:z.string().optional(),afterUrl:z.string().optional(),message:z.string().optional(),beforeSnapshot:z.string().optional(),afterSnapshot:z.string().optional(),startedAt:z.coerce.date(),finishedAt:z.coerce.date()}),Ww=Sc.extend({viewport:z.object({height:z.number(),width:z.number()}).nullish(),status:z.nativeEnum(hc),message:z.string().optional(),elementInteracted:z.string().optional()}),on=Sc.extend({status:z.nativeEnum(et),message:z.string().optional(),data:z.unknown().optional(),beforeTestContext:gc.optional(),afterTestContext:gc.optional(),failureReason:z.nativeEnum(ge).optional(),details:z.unknown().describe("Parse using StepExecutionLogSchema.array() to get type safety. We don't explicitly type it because it's non-critical information.")}).openapi({ref:"StepResultMetadata"}),Np=(t=>(t.NOT_ELIGIBLE="NOT_ELIGIBLE",t.ATTEMPTED="ATTEMPTED",t))(Np||{}),Aa=on.merge(Pt).extend({results:Ww.array().describe("Command that was executed. Array is just for consistency with other result types. There should only ever be one item."),previousAttempts:z.lazy(()=>Ke.array()).optional(),failureRecoveryStatus:z.object({type:z.nativeEnum(Np),message:z.string()}).optional()}),$w=on.merge(Zr).extend({results:z.lazy(()=>Aa.array()),previousAttempts:z.lazy(()=>Ke.array()).optional()}),qw=on.merge(Hn).extend({results:z.lazy(()=>Aa.array()),previousAttempts:z.lazy(()=>Ke.array()).optional()}),Kw=on.merge(pr).extend({moduleName:z.string().optional(),results:z.lazy(()=>Ke.array()),previousAttempts:z.lazy(()=>Ke.array()).optional()}),Yw=on.merge(Vn).extend({assertion:Aa.optional(),results:z.lazy(()=>Ke.array()).describe("results for the block actually executed"),previousAttempts:z.lazy(()=>Ke.array()).optional()}),Xw=on.merge(ti).extend({results:z.lazy(()=>Ke.array()),healingAttempts:z.lazy(()=>Ke.array().array()).optional(),previousAttempts:z.lazy(()=>Ke.array()).optional()}),Ke=z.discriminatedUnion("type",[$w,qw,Aa,Kw,Yw,Xw]),IB=on.pick({startedAt:!0,finishedAt:!0,status:!0,message:!0,data:!0}),Jw=Sc.extend({index:z.number().optional(),description:z.string(),pageState:z.string().optional(),elementInteracted:z.string().optional(),startedAt:z.coerce.date().or(z.string()).optional().catch(void 0),finishedAt:z.coerce.date().or(z.string()).optional().catch(void 0)}),wa=Jw.extend({beforeScreenshot:z.string().optional(),afterScreenshot:z.string().optional()});var Ec=Qw.object({results:Ke.array().describe("main results"),beforeResults:Ke.array().optional(),afterResults:Ke.array().optional()}),ii=Ec.partial();import{z as U}from"zod";import{extendZodWithOpenApi as iR}from"zod-openapi";var Kn=(t=>(t.WEB="WEB",t.ANDROID="ANDROID",t))(Kn||{});import{isValidCron as Zw}from"cron-validator";import{z as Q}from"zod";import{z as yc}from"zod";var Mr=(n=>(n.CHROMIUM="Chromium",n.GOOGLE_CHROME="Google Chrome",n.CHROME_FOR_TESTING="Chrome for Testing",n))(Mr||{});var Ra=yc.object({width:yc.number().min(200).max(1e4),height:yc.number().min(200).max(1e4)}),Dp={"Desktop Large":{width:1920,height:1080},"Desktop Small":{width:1280,height:800},iPad:{width:768,height:1024},"Pixel 8":{width:448,height:998},"iPhone 15":{width:393,height:852}},UB=Object.keys(Dp);var Ir=Dp["Desktop Large"],kp="en-us",Up="America/Los_Angeles";var Fp={latitude:37.7749,longitude:-122.4194};var Bp=["Africa/Abidjan","Africa/Accra","Africa/Algiers","Africa/Bissau","Africa/Cairo","Africa/Casablanca","Africa/Ceuta","Africa/El_Aaiun","Africa/Johannesburg","Africa/Juba","Africa/Khartoum","Africa/Lagos","Africa/Maputo","Africa/Monrovia","Africa/Nairobi","Africa/Ndjamena","Africa/Sao_Tome","Africa/Tripoli","Africa/Tunis","Africa/Windhoek","America/Adak","America/Anchorage","America/Argentina/Buenos_Aires","America/Argentina/Catamarca","America/Argentina/Cordoba","America/Argentina/Jujuy","America/Argentina/La_Rioja","America/Argentina/Mendoza","America/Argentina/Rio_Gallegos","America/Argentina/Salta","America/Argentina/San_Juan","America/Argentina/San_Luis","America/Argentina/Tucuman","America/Argentina/Ushuaia","America/Araguaina","America/Asuncion","America/Atikokan","America/Bahia","America/Bahia_Banderas","America/Barbados","America/Belem","America/Belize","America/Blanc-Sablon","America/Boa_Vista","America/Bogota","America/Boise","America/Cambridge_Bay","America/Campo_Grande","America/Cancun","America/Caracas","America/Cayenne","America/Chicago","America/Chihuahua","America/Costa_Rica","America/Creston","America/Cuiaba","America/Curacao","America/Danmarkshavn","America/Dawson","America/Dawson_Creek","America/Denver","America/Detroit","America/Dominica","America/Edmonton","America/Eirunepe","America/El_Salvador","America/Fort_Nelson","America/Fortaleza","America/Glace_Bay","America/Goose_Bay","America/Grand_Turk","America/Grenada","America/Guadeloupe","America/Guatemala","America/Guayaquil","America/Guyana","America/Halifax","America/Havana","America/Hermosillo","America/Indiana/Indianapolis","America/Indiana/Knox","America/Indiana/Marengo","America/Indiana/Petersburg","America/Indiana/Tell_City","America/Indiana/Vevay","America/Indiana/Vincennes","America/Indiana/Winamac","America/Inuvik","America/Iqaluit","America/Jamaica","America/Juneau","America/Kentucky/Louisville","America/Kentucky/Monticello","America/La_Paz","America/Lima","America/Los_Angeles","America/Maceio","America/Managua","America/Manaus","America/Marigot","America/Martinique","America/Matamoros","America/Mazatlan","America/Menominee","America/Merida","America/Metlakatla","America/Mexico_City","America/Miquelon","America/Moncton","America/Monterrey","America/Montevideo","America/Montserrat","America/Nassau","America/New_York","America/Nipigon","America/Nome","America/Noronha","America/North_Dakota/Beulah","America/North_Dakota/Center","America/North_Dakota/New_Salem","America/Ojinaga","America/Panama","America/Pangnirtung","America/Paramaribo","America/Phoenix","America/Port-au-Prince","America/Port_of_Spain","America/Porto_Velho","America/Puerto_Rico","America/Punta_Arenas","America/Rainy_River","America/Rankin_Inlet","America/Recife","America/Regina","America/Resolute","America/Rio_Branco","America/Santarem","America/Santiago","America/Santo_Domingo","America/Sao_Paulo","America/Scoresbysund","America/Sitka","America/St_Barthelemy","America/St_Johns","America/St_Kitts","America/St_Lucia","America/St_Thomas","America/St_Vincent","America/Swift_Current","America/Tegucigalpa","America/Thule","America/Thunder_Bay","America/Tijuana","America/Toronto","America/Tortola","America/Vancouver","America/Whitehorse","America/Winnipeg","America/Yakutat","America/Yellowknife","Antarctica/Casey","Antarctica/Davis","Antarctica/DumontDUrville","Antarctica/Macquarie","Antarctica/Mawson","Antarctica/Palmer","Antarctica/Rothera","Antarctica/Syowa","Antarctica/Troll","Antarctica/Vostok","Arctic/Longyearbyen","Asia/Aden","Asia/Almaty","Asia/Amman","Asia/Anadyr","Asia/Aqtau","Asia/Aqtobe","Asia/Ashgabat","Asia/Atyrau","Asia/Baghdad","Asia/Bahrain","Asia/Baku","Asia/Bangkok","Asia/Barnaul","Asia/Beirut","Asia/Bishkek","Asia/Brunei","Asia/Chita","Asia/Choibalsan","Asia/Colombo","Asia/Damascus","Asia/Dhaka","Asia/Dili","Asia/Dubai","Asia/Dushanbe","Asia/Famagusta","Asia/Gaza","Asia/Hebron","Asia/Ho_Chi_Minh","Asia/Hong_Kong","Asia/Hovd","Asia/Irkutsk","Asia/Jakarta","Asia/Jayapura","Asia/Jerusalem","Asia/Kabul","Asia/Kamchatka","Asia/Karachi","Asia/Kathmandu","Asia/Khandyga","Asia/Kolkata","Asia/Krasnoyarsk","Asia/Kuala_Lumpur","Asia/Kuching","Asia/Kuwait","Asia/Macau","Asia/Magadan","Asia/Makassar","Asia/Manila","Asia/Muscat","Asia/Nicosia","Asia/Novokuznetsk","Asia/Novosibirsk","Asia/Omsk","Asia/Oral","Asia/Phnom_Penh","Asia/Pontianak","Asia/Pyongyang","Asia/Qatar","Asia/Qostanay","Asia/Qyzylorda","Asia/Riyadh","Asia/Sakhalin","Asia/Samarkand","Asia/Seoul","Asia/Shanghai","Asia/Singapore","Asia/Srednekolymsk","Asia/Taipei","Asia/Tashkent","Asia/Tbilisi","Asia/Tehran","Asia/Thimphu","Asia/Tokyo","Asia/Tomsk","Asia/Ulaanbaatar","Asia/Urumqi","Asia/Ust-Nera","Asia/Vientiane","Asia/Vladivostok","Asia/Yakutsk","Asia/Yangon","Asia/Yekaterinburg","Asia/Yerevan","Atlantic/Azores","Atlantic/Bermuda","Atlantic/Canary","Atlantic/Cape_Verde","Atlantic/Faroe","Atlantic/Madeira","Atlantic/Reykjavik","Atlantic/South_Georgia","Atlantic/Stanley","Australia/Adelaide","Australia/Brisbane","Australia/Broken_Hill","Australia/Currie","Australia/Darwin","Australia/Eucla","Australia/Hobart","Australia/Lindeman","Australia/Lord_Howe","Australia/Melbourne","Australia/Perth","Australia/Sydney","Europe/Amsterdam","Europe/Andorra","Europe/Astrakhan","Europe/Athens","Europe/Belgrade","Europe/Berlin","Europe/Bratislava","Europe/Brussels","Europe/Bucharest","Europe/Budapest","Europe/Busingen","Europe/Chisinau","Europe/Copenhagen","Europe/Dublin","Europe/Gibraltar","Europe/Guernsey","Europe/Helsinki","Europe/Isle_of_Man","Europe/Istanbul","Europe/Jersey","Europe/Kaliningrad","Europe/Kiev","Europe/Kirov","Europe/Lisbon","Europe/Ljubljana","Europe/London","Europe/Luxembourg","Europe/Madrid","Europe/Malta","Europe/Mariehamn","Europe/Minsk","Europe/Monaco","Europe/Moscow","Europe/Oslo","Europe/Paris","Europe/Podgorica","Europe/Prague","Europe/Riga","Europe/Rome","Europe/Samara","Europe/San_Marino","Europe/Sarajevo","Europe/Saratov","Europe/Simferopol","Europe/Skopje","Europe/Sofia","Europe/Stockholm","Europe/Tallinn","Europe/Tirane","Europe/Ulyanovsk","Europe/Uzhgorod","Europe/Vaduz","Europe/Vatican","Europe/Vienna","Europe/Vilnius","Europe/Volgograd","Europe/Warsaw","Europe/Zagreb","Europe/Zaporozhye","Europe/Zurich","Indian/Antananarivo","Indian/Chagos","Indian/Christmas","Indian/Cocos","Indian/Comoro","Indian/Kerguelen","Indian/Mahe","Indian/Maldives","Indian/Mauritius","Indian/Mayotte","Indian/Reunion","Pacific/Apia","Pacific/Auckland","Pacific/Bougainville","Pacific/Chatham","Pacific/Chuuk","Pacific/Easter","Pacific/Efate","Pacific/Enderbury","Pacific/Fakaofo","Pacific/Fiji","Pacific/Funafuti","Pacific/Galapagos","Pacific/Gambier","Pacific/Guadalcanal","Pacific/Guam","Pacific/Honolulu","Pacific/Kiritimati","Pacific/Kosrae","Pacific/Kwajalein","Pacific/Majuro","Pacific/Marquesas","Pacific/Midway","Pacific/Nauru","Pacific/Niue","Pacific/Norfolk","Pacific/Noumea","Pacific/Pago_Pago","Pacific/Palau","Pacific/Pitcairn","Pacific/Pohnpei","Pacific/Port_Moresby","Pacific/Rarotonga","Pacific/Saipan","Pacific/Tahiti","Pacific/Tarawa","Pacific/Tongatapu","Pacific/Wake","Pacific/Wallis"];var zp=2e3,eR=tn.extend({browserType:Q.nativeEnum(Mr).optional(),slowMoMs:Q.number().optional().refine(r=>r===void 0||r<=zp&&r>=-1,{message:`Slow motion must be between 0 and ${zp} milliseconds`}),basicAuthorization:Q.object({username:Q.string().optional(),password:Q.string().optional()}).optional(),geolocation:Q.object({latitude:Q.coerce.number().refine(r=>r>=-90&&r<=90,{message:"Latitude must be between -90 and 90 degrees"}),longitude:Q.coerce.number().refine(r=>r>=-180&&r<=180,{message:"Longitude must be between -180 and 180 degrees"})}).optional(),disableJavaScript:Q.boolean().optional(),locale:Q.string().optional(),timezone:Q.enum(Bp).optional(),colorScheme:Q.enum(["light","dark"]).optional()});var Tc=Q.object({useMemory:Q.boolean().optional(),failureRecovery:Q.boolean().optional().describe("undefined means inherit org settings")}),tR=Tc.extend({disableAICaching:Q.boolean().optional(),failureRecoveryInstructions:Q.string().optional()}),rR=Q.object({viewport:Ra.optional()}),ai=rR.merge(tR).merge(eR),Yn=Q.object({cron:Q.string().refine(r=>Zw(r),{message:"Invalid cron expression."}).default("0 0 */1 * *"),enabled:Q.boolean().default(!1),env:Q.string().optional(),timeZone:Q.string().default("America/Los_Angeles"),jobKey:Q.string().optional()}),Xn=Q.object({onSuccess:Q.boolean().default(!1),failureMessage:Q.string().optional(),onFailure:Q.boolean().default(!0),successMessage:Q.string().optional()}),nR=Q.object({name:Q.string(),required:Q.boolean().optional(),defaultValue:Q.string().describe("this is not optional because we need a value when the editor is first loaded")}),Ca=nR.array(),oR=Q.object({name:Q.string(),value:Q.string()}),Gp=oR.array(),xa=Q.object({name:Q.string(),default:Q.boolean().optional(),fixtures:Pp.array().optional()});iR(U);var Dt={WEBHOOK:"WEBHOOK",CRON:"CRON",MANUAL:"MANUAL",CLI:"CLI"},me=(l=>(l.PENDING="PENDING",l.RUNNING="RUNNING",l.PASSED="PASSED",l.FAILED="FAILED",l.CANCELLED="CANCELLED",l.RETRYING="RETRYING",l.WAITING_FOR_USER="WAITING_FOR_USER",l))(me||{}),_a=(t=>(t.BEFORE_ALL="BEFORE_ALL",t.AFTER_ALL="AFTER_ALL",t))(_a||{});var Be=U.string().pipe(U.coerce.date()).or(U.date()),si=U.object({id:U.string(),runKey:U.string(),organizationId:U.string(),executionType:U.nativeEnum(Kn).optional().default("WEB"),createdAt:Be,createdBy:U.string(),flake:U.boolean().nullish(),scheduledAt:Be.or(U.null()),startedAt:Be.or(U.null()),updatedAt:Be.nullish(),finishedAt:Be.or(U.null()),resolvedBaseUrl:U.string().nullish(),environmentName:U.string().nullish(),gitBranchName:U.string().nullish(),githubRepository:U.string().nullish(),gitlabProjectPath:U.string().nullish(),labels:U.array(U.string()).optional(),gitOriginUrl:U.string().nullish(),gitCommitSha:U.string().nullish(),gitCommitShaShort:U.string().nullish(),gitCommitAuthorName:U.string().nullish(),cliVersion:U.string().nullish(),section:U.nativeEnum(_a).nullish(),status:U.nativeEnum(me),trigger:U.nativeEnum(Dt),attempts:U.number(),runAttempts:U.array(U.object({id:U.string(),status:U.nativeEnum(me),startedAt:Be.or(U.null()),finishedAt:Be.or(U.null())})).optional(),videos:U.array(U.string()).optional(),failureReason:U.nativeEnum(ge).nullish(),failureDetails:va.nullish(),failureRecoveryDetails:U.record(U.string(),U.unknown()).nullish(),pipelineId:U.string().nullish(),resolvedInputs:U.record(U.string(),U.string()).nullish(),quarantined:U.boolean().nullish().default(!1),quarantinedReason:U.string().nullish(),localTestId:U.string().nullish(),testId:U.string().nullish(),testName:U.string().nullish(),description:U.string().nullish(),test:U.object({name:U.string(),id:U.string()}).nullish().default(null),suiteId:U.string().nullish()}).openapi({ref:"RunMetadata"}),aR={id:!0,status:!0,testName:!0,localTestId:!0,testId:!0,test:{select:{name:!0,id:!0}},finishedAt:!0,failureReason:!0,failureDetails:!0},Ma=si.pick({...aR,test:!0}),Hp=si.omit({failureReason:!0,failureDetails:!0,test:!0}),bc=si.extend({stepsSnapshot:U.array(U.record(U.unknown())).nullish(),resolvedInputs:U.record(U.string(),U.string()).nullish(),test:U.object({name:U.string(),id:U.string(),description:U.string().nullish(),baseUrl:U.string().nullish(),advanced:ai.nullish()}).nullish()}).merge(Ec);var sR=li.object({id:li.string().uuid(),startedAt:Be.or(li.null()),finishedAt:Be.or(li.null()),status:li.nativeEnum(me)}).merge(ii),iz=sR.array();import{z as ze}from"zod";var lR=ze.object({id:ze.string(),status:ze.nativeEnum(me),trigger:ze.nativeEnum(Dt),createdAt:Be,startedAt:Be.nullish(),finishedAt:Be.nullish(),gitCommitSha:ze.string().nullish(),gitCommitShaShort:ze.string().nullish(),gitCommitTimestamp:Be.nullish(),gitBranchName:ze.string().nullish(),gitOriginUrl:ze.string().nullish(),gitCommitMessage:ze.string().nullish(),gitCommitAuthorName:ze.string().nullish(),githubRepository:ze.string().nullish(),gitlabProjectPath:ze.string().nullish(),pipelineId:ze.string().nullish(),cliVersion:ze.string().nullish(),labels:ze.string().array().optional(),suite:ze.object({id:ze.string(),name:ze.string()}).nullish(),runs:ze.object({status:ze.nativeEnum(me)}).array()}).openapi({ref:"RunGroup"}),Vp=lR.pick({id:!0,createdAt:!0,startedAt:!0,finishedAt:!0,status:!0,trigger:!0,suite:!0}).extend({runs:Ma.array()});import{z as Ye}from"zod";var cR=Ye.object({type:Ye.literal("TARGETING"),name:Ye.string().optional().describe("Target name to disambiguate for steps with multiple targets"),elementLocationDecisions:_p.array(),pageState:Ye.string().optional(),targetSource:Ye.nativeEnum(Ar).optional(),targetUpdateTime:Ye.string().optional()}),uR=Ye.object({type:Ye.literal("AI_LOCATION"),matched:Ye.boolean(),pageState:Ye.string().optional(),ragUsed:Ye.boolean().optional(),thoughts:Ye.string().optional()}),dR=Ye.object({type:Ye.literal("ASSERTION"),relevantElementsSerialized:Ye.string().array().optional(),pageState:Ye.string().optional(),ragUsed:Ye.boolean().optional()}),mR=Ye.discriminatedUnion("type",[cR,uR,dR]);import{z as ke}from"zod";var pR=ke.object({id:ke.string(),name:ke.string()}),yz=pR.merge(ke.object({createdAt:Be,createdBy:ke.string(),schedule:Yn,notification:Xn,environment:ke.object({name:ke.string()}).nullish(),beforeTests:ke.object({id:ke.string()}).array().nullish(),afterTests:ke.object({id:ke.string()}).array().nullish()})),jp=ke.object({id:ke.string().uuid(),orgId:ke.string(),createdAt:Be,startedAt:Be.or(ke.null()),finishedAt:Be.or(ke.null()),status:ke.nativeEnum(me),trigger:ke.nativeEnum(Dt),suite:ke.object({id:ke.string(),name:ke.string()}).nullish(),runs:si.array()}),Tz=jp.pick({id:!0,createdAt:!0,startedAt:!0,finishedAt:!0,status:!0,trigger:!0,suite:!0}),Wp=jp.extend({runs:Ma.array()});import{z as kt}from"zod";import{cloneDeep as Az}from"lodash-es";import{z as se}from"zod";var Mz=se.object({thoughts:se.string(),subGoals:se.object({instruction:se.string()}).array()}),Iz=se.object({thoughts:se.string(),newPlanMarkdown:se.string()}),Pz=se.object({thoughts:se.string(),correct:se.boolean(),failedActionIndex:se.number().optional()}),gR=se.object({type:se.literal("PLANNING"),beforePlan:se.string(),goalDecision:se.string(),thoughts:se.string()}),hR=se.object({type:se.literal("RUNNING"),stepDisplayName:se.string(),status:se.nativeEnum(et),results:Ke.array()}),fR=se.object({type:se.literal("REVISING"),beforePlan:se.string(),afterPlan:se.string(),errString:se.string(),diffs:se.string(),thoughts:se.string()}),SR=se.object({type:se.literal("SYSTEM"),message:se.string()}),ER=se.discriminatedUnion("type",[gR,hR,fR,SR]),$p=ER.array();var kz=kt.object({id:kt.string(),scheduledAt:kt.coerce.date().nullable(),startedAt:kt.coerce.date().nullable(),finishedAt:kt.coerce.date().nullable(),status:kt.nativeEnum(me),history:$p.nullable(),testPlan:kt.object({id:kt.string(),name:kt.string()}).nullable(),test:kt.object({id:kt.string(),name:kt.string()}).nullable()});import{z as gt}from"zod";var vc=gt.object({content:gt.string(),ids:gt.string().array(),tokenLength:gt.number()}),yR=gt.object({chunks:vc.array()}),Zz=gt.object({ids:gt.string().array(),score:gt.number(),tokenLength:gt.number()}),e1=yR.extend({description:gt.string().describe("Input to pass to RAG engine"),tokenLimit:gt.number()}),qp=gt.object({ids:gt.number().array()}),Kp=gt.object({indices:gt.number().array()});var it=_.object({disableCache:_.boolean().optional(),useMemory:_.boolean().optional(),loggerTags:_.record(_.string(),_.string()).optional(),langfuseSessionId:_.string().optional(),agentConfigVersion:_.string().optional()}),l1=it.extend({chunks:vc.array(),description:_.string().describe("Input to pass to AI"),type:_.union([_.literal("locator"),_.literal("assertion"),_.literal("ai-action")]),softTokenLimit:_.number(),hardTokenLimit:_.number()}),TR=_.object({screenshotBase64AfterCommand:_.string(),urlAfterCommand:_.string(),serializedCommand:_.string(),elementInteracted:_.string().optional(),thoughts:_.string().optional()}),Yp=_.object({goal:_.string(),browserState:_.string(),screenshot:_.string(),source:xp.optional().catch(void 0),memory:_.discriminatedUnion("type",[ua,_.object({type:_.literal("RESOLVED_TRACES"),traces:_.unknown().array()})]).optional()}),Xp=_.object({target:_.string().or(_.number()),browserState:_.string().optional(),screenshot:_.string().optional(),boundingBox:_.object({x:_.number(),y:_.number(),height:_.number(),width:_.number()}).optional()}),Jp=_.object({goal:_.string(),browserState:_.string(),screenshot:_.string().optional(),returnSchema:_.string().optional()}),bR=_.literal("NEGATED_CHECK"),Qp=_.object({goal:_.string(),browserState:_.string(),screenshot:_.string(),url:_.string(),contextChoice:tc.optional(),memory:_.discriminatedUnion("type",[Jl,_.object({type:_.literal("RESOLVED_TRACES"),traces:_.unknown().array()})]).optional(),source:bR.optional()}),Zp=_.object({command:zn}),eg=_.object({message:_.string()}),Ac=_.object({goal:_.string(),browserState:_.string(),startingScreenshot:_.string().optional(),screenshot:_.string(),url:_.string(),history:TR.array(),actionHint:_.string().optional(),lastError:_.string().optional()}),tg=_.object({results:wa.array(),errorMessage:_.string(),errorStack:_.string().optional()}),rg=_.object({results:wa.array(),goal:_.string(),errorMessage:_.string()}),ng=_.object({failedResults:wa.array(),nextStepsSerialized:_.string().array(),currentUrl:_.string(),currentPageState:_.string(),currentScreenshot:_.string(),customInstructions:_.string().optional(),testDescription:_.string().optional()}),c1=_.object({description:_.string(),type:_.union([_.literal("locator"),_.literal("assertion"),_.literal("ai-action")]),excerpt:_.string()}),og=_.object({type:_.string(),browserContext:_.string(),currentStep:_.string(),screenshot:_.string()});import{z as ci}from"zod";var m1=ci.object({goal:ci.string()}),ig=ci.object({keywords:ci.array(ci.string())});import{z as wc}from"zod";var Ia=(o=>(o.LOCATOR="locator",o.ASSERTION="assertion",o.VISUAL_ASSERTION="visual-assertion",o.TEXT_EXTRACTION="text-extraction",o))(Ia||{}),h1=wc.nativeEnum(Ia),vR=wc.enum(["v1","v2"]),f1=vR.or(wc.string().describe("for people with special configurations"));import{z as Ie}from"zod";var ag=Ie.object({attributesRequired:Ie.array(Ie.string()).optional(),textRequired:Ie.boolean().optional(),boundsRequired:Ie.boolean().optional()}),sg=Ie.object({id:Ie.number(),thoughts:Ie.string(),requirements:ag.optional(),additionalElements:Ie.object({id:Ie.number(),requirements:ag}).array().optional()}),lg=Ie.object({description:Ie.string(),screenXml:Ie.string(),screenshot:Ie.string()}),cg=Ie.object({assertion:Ie.string(),screenXml:Ie.string(),screenshot:Ie.string()}),ug=Ie.object({thoughts:Ie.string(),result:Ie.boolean(),relevantElements:Ie.array(Ie.number()).optional()});import{z as an}from"zod";var dg=an.object({id:an.string().uuid(),skipped:an.boolean().optional(),envKey:an.string().optional().describe("key in the environment to save the result of this step to")}),Rc=dg.merge(ma).extend({type:an.literal("REQUEST")}),Cc=dg.merge(pa).extend({type:an.literal("JAVASCRIPT")}),xc=an.discriminatedUnion("type",[Cc,Rc]);import{z as Ut}from"zod";import{z as sn}from"zod";var AR=/^[a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/,Jn=r=>{let e=r.trim().toLowerCase().replace(/[^a-z0-9]/g,"-");for(;e.includes("--");)e=e.replaceAll("--","-");return e.startsWith("-")&&(e=e.slice(1)),e.endsWith("-")&&(e=e.slice(0,e.length-1)),e};var Pa=sn.string().min(1).max(255).superRefine((r,e)=>{try{_c(r)}catch(t){return e.addIssue({code:sn.ZodIssueCode.custom,message:t.message,fatal:!0}),sn.NEVER}});function _c(r){if(r=r.toLowerCase().trim(),r.length===0||r.length>255)throw new Error("Name must be between 1 and 255 characters long");if(/[<>:"/\\|?*]/.test(r))throw new Error('Name contains one of the following invalid characters: <>:"/\\|?*');if(r.endsWith("-")||r.startsWith("-"))throw new Error("Name cannot start or end with a dash.");if(r.includes("\0"))throw new Error("Name cannot contain null characters");if(/^(con|prn|aux|nul|com[0-9]|lpt[0-9])(\..*)?$/i.test(r))throw new Error(`"${r}" is a reserved name on Windows and cannot be used as a filename.`);if(/^\.+$/.test(r)||/^\s|\s$/.test(r))throw new Error("Name cannot start or end with a space or dot.");if(r.endsWith(".yaml"))throw new Error('Name cannot end with ".yaml".');if(r==="none")throw new Error("Name cannot be 'none'.");if(r.match(AR))throw new Error("Name cannot be a UUID. Please choose a different name.")}var Oa=sn.preprocess(r=>r===null?"":r,sn.union([sn.string().url(),sn.literal("")])).optional();var mg=Ut.object({id:Ut.string(),name:Pa,description:Ut.string().optional().nullish(),baseUrl:Oa.nullish(),schemaVersion:Ut.string(),advanced:Ut.unknown().optional(),retries:Ut.number(),envs:Ut.array(xa).nullish(),parameters:Ca.nullish()}),wR=Ut.object({createdAt:Ut.coerce.date(),updatedAt:Ut.coerce.date(),schedule:Yn.nullish(),notification:Xn.nullish(),createdBy:Ut.string(),organizationId:Ut.string()}),RR=mg.merge(wR),H1=RR.extend({steps:xc.array()}),V1=mg.extend({steps:xc.array()});import{z as bt}from"zod";var pg=bt.object({startedAt:bt.coerce.date(),finishedAt:bt.coerce.date(),status:bt.nativeEnum(et),message:bt.string().optional(),data:bt.unknown().optional()}),CR=pg.merge(Cc).extend({type:bt.literal("JAVASCRIPT")}),xR=pg.merge(Rc).extend({type:bt.literal("REQUEST")}),_R=bt.discriminatedUnion("type",[CR,xR]),gg=bt.object({startedAt:bt.coerce.date(),finishedAt:bt.coerce.date().nullish(),status:bt.nativeEnum(me),results:_R.array(),failureReason:bt.string().nullish(),failureDetails:va.nullish()});import{z as vt}from"zod";var MR=vt.object({id:vt.string(),organizationId:vt.string(),createdAt:vt.coerce.date(),updatedAt:vt.coerce.date(),createdBy:vt.string(),scheduledAt:vt.coerce.date().nullish(),startedAt:vt.coerce.date().nullish(),finishedAt:vt.coerce.date().nullish(),status:vt.nativeEnum(me),trigger:vt.nativeEnum(Dt),results:gg.array().nullish(),apiTestName:vt.string().nullish(),apiTestPath:vt.string().nullish(),apiTestId:vt.string().nullish()}),Z1=MR.pick({status:!0,startedAt:!0,finishedAt:!0});var ui=(o=>(o.TestRun="test-run",o.MobileTestRun="mobile-test-run",o.CreditsUsed="credits-used",o.CreditsUsedV2="credits-used-v2",o))(ui||{}),hg=3;function IR(r){return r==="MODULE"||r==="CONDITIONAL"||r==="SECTION"||r==="RESOLVED_MODULE"}function Mc(r){if(!IR(r))switch(r){case"PRESET_ACTION":return 0;case"AI_ACTION":return 3;case"AI_ACTION_DYNAMIC":return 5;default:(t=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(r)}}function Ic(r){switch(r.type){case"AI_EXTRACT":case"AI_ASSERTION":return hg;case"CAPTCHA":return 3;case"CLICK":case"TYPE":case"SELECT_OPTION":case"HOVER":case"ELEMENT_CHECK":case"FOCUS":case"BLUR":case"SCROLL_DOWN":case"SCROLL_LEFT":case"SCROLL_RIGHT":case"SCROLL_UP":case"MOUSE_DRAG":return r.useSelector||!r.target||r.target.type!=="description"?0:1;case"DRAG":return r.useSelector?0:1;case"VISUAL_DIFF":case"TAB":case"JAVASCRIPT":case"NAVIGATE":case"WAIT":case"SUCCESS":case"AUTH_LOAD":case"AUTH_SAVE":case"COOKIE":case"DIALOG":case"FILE_UPLOAD":case"GO_BACK":case"GO_FORWARD":case"LOCAL_STORAGE":case"NEW_TAB":case"PAGE_CHECK":case"PRESS":case"KEY_DOWN":case"KEY_UP":case"COPY":case"PASTE":case"REFRESH":case"REQUEST":case"GRAPHQL_REQUEST":case"WAIT_FOR_URL":case"REGISTER_REQUEST_LISTENER":case"AWAIT_LISTENER":case"RECORD_REQUESTS":case"GET_RECORDED_REQUESTS":case"SET_HEADER":case"MOCK_ROUTE":case"REMOVE_ROUTE_MOCK":case"OFFLINE_MODE":return 0;default:(t=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(r)}}var La=class{trackStepExecution(){}async flush(){}};import{parseString as PR,splitCookiesString as OR}from"set-cookie-parser";import{z as ue}from"zod";var Pc=ue.object({name:ue.string(),value:ue.string(),url:ue.string().optional(),domain:ue.string().optional(),path:ue.string().optional(),expires:ue.number().default(Date.now()/1e3+60*60*24*365),httpOnly:ue.boolean().optional(),secure:ue.boolean().default(!0),sameSite:ue.union([ue.literal("Strict"),ue.literal("Lax"),ue.literal("None")]).default("None")});function Na(r,e){let t=[],n=OR(r);for(let o of n){let i=PR(o,{decodeValues:!1});if(!i.name)throw new Error("Name missing from cookie");if(!i.value)continue;let a;if(i.sameSite){let u=i.sameSite.trim().toLowerCase();if(u==="strict")a="Strict";else if(u==="lax")a="Lax";else if(u==="none")a="None";else throw new Error(`Invalid sameSite setting in cookie: ${u}`)}i.httpOnly===void 0&&(i.httpOnly=!1),!i.path&&i.domain&&(i.path="/"),!i.domain&&e&&(i.domain=e);let l=Pc.parse({...i,expires:i.expires?i.expires.getTime()/1e3:void 0,sameSite:a});t.push(l);let c=[l.name,...Object.keys(l)].map(u=>u.toLowerCase()),s=o.match(/\b(\S+)=([^;]*)/g);if(s)for(let u of s){let[d,m]=u.split("=");if(!d||!m)throw new Error(`Invalid key-value pair in cookie: ${u}`);c.includes(d.toLowerCase())||t.push({...l,name:d,value:m})}}return t}var LR=ue.object({origin:ue.string(),localStorage:ue.array(ue.object({name:ue.string(),value:ue.string()}))}),NR=ue.object({entries:ue.record(ue.string(),ue.array(ue.tuple([ue.unknown(),ue.unknown()]))),version:ue.number().optional()}),fg=ue.object({cookies:Pc.array().optional(),origins:LR.array().optional(),idb:ue.record(ue.string(),NR).optional().describe("key is db name")});function Sg(r,e){let t=[];return r.cloneSync()?.serializeSync()?.cookies.forEach(n=>{let o=Pc.safeParse({name:n.key,...n});if(!o.success)return;let i=o.data;!i.domain&&!i.url&&(i.domain=e),t.push(i)}),t}import WR from"zod";import{v4 as vG}from"uuid";import{z as le}from"zod";import*as Se from"zod";var Eg=Se.object({requiredText:Se.string().optional(),requiredAttributes:Se.record(Se.string(),Se.string()).optional(),requiredBounds:Se.boolean().optional()}),DR=Se.object({xPath:Se.string(),requirements:Eg.optional()}),kR=Se.object({type:Se.literal("NATIVE"),bounds:Se.number().array(),resolvedDescription:Se.string(),xPath:Se.string(),elementOnlySerializedXml:Se.string(),requirements:Eg.optional(),requiredRelatedElements:DR.array().optional()}),UR=Se.object({type:Se.literal("WEBVIEW"),resolvedDescription:Se.string(),xPath:Se.string(),browserCache:wr.optional()}),yg=Se.discriminatedUnion("type",[kR,UR]);var ln=(s=>(s.AI_CHECK="AI_CHECK",s.TAP="TAP",s.TYPE="TYPE",s.PRESS="PRESS",s.OPEN_APP="OPEN_APP",s.OPEN_NOTIFICATION_DRAWER="OPEN_NOTIFICATION_DRAWER",s.JAVASCRIPT="JAVASCRIPT",s.ADB="ADB",s.STATE="STATE",s))(ln||{}),Oc=(c=>(c.BACK="BACK",c.HOME="HOME",c.APP_SWITCHER="APP_SWITCHER",c.POWER="POWER",c.SEARCH="SEARCH",c.VOLUME_UP="VOLUME_UP",c.VOLUME_DOWN="VOLUME_DOWN",c.VOLUME_MUTE="VOLUME_MUTE",c))(Oc||{}),Tg=le.discriminatedUnion("type",[le.object({type:le.literal("description"),description:le.string()}),le.object({type:le.literal("coordinates"),xPercent:le.number(),yPercent:le.number()})]),gr=le.object({id:le.string().uuid(),disableCache:le.boolean().optional()}),FR=gr.extend({type:le.literal("STATE")}),bg=le.object({target:yg}),Lc=gr.extend({type:le.literal("TAP"),target:Tg,cache:bg.optional()}),Nc=gr.extend({type:le.literal("TYPE"),target:Tg.optional(),cache:bg.optional(),text:le.string()}),BR=gr.extend({type:le.literal("OPEN_NOTIFICATION_DRAWER")}),zR=gr.extend({type:le.literal("PRESS"),key:le.nativeEnum(Oc)}),GR=gr.extend({type:le.literal("OPEN_APP"),packageName:le.string(),activityName:le.string().optional()}),HR=gr.extend({type:le.literal("AI_CHECK"),assertion:le.string(),timeoutSecs:le.number().optional()}),VR=gr.extend({type:le.literal("JAVASCRIPT"),code:le.string(),timeout:le.number().int().max(60).optional().describe("Max seconds for the code to complete")}),jR=gr.extend({type:le.literal("ADB"),command:le.string()}),vg=le.discriminatedUnion("type",[Lc,Nc,zR,GR,BR,HR,VR,jR,FR]);var Dc=r=>{switch(r.type){case"description":return r.description;case"coordinates":return`${r.xPercent}%, ${r.yPercent}%`}};var Ag={type:!0,cache:!0},Pr=WR.discriminatedUnion("type",[Lc.pick(Ag),Nc.pick(Ag)]),$R=Object.values(ln).filter(r=>Pr.options.some(e=>e.shape.type.safeParse(r).success));function Da(r){return $R.includes(r.type)}var wg=Zo(Pr),Rg=ei(Pr),IG=ya(Pr);import{cloneDeep as di}from"lodash-es";import Cg from"truncate-json";var qR="\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022",KR=[rn,qn],xg=[rn,qn],Qn=class r{env={};varsFromMomenticEnvironment={};constructor(e){this.reset(e)}static dummyContext(e=void 0,t=void 0,n={}){return new r({testName:e,envName:t,variablesFromEnvironment:n})}static fromSnapshot({snapshot:e,environmentVariables:t}){let n=e.env[rn],o=e.env[qn],i={};for(let[l,c]of Object.entries(e.env))xg.includes(l)||(t??{})[l]===void 0&&(i[l]=c);return new r({dynamicVariables:i,envName:n,testName:o,variablesFromEnvironment:t??{}})}setEnvVariables(e){let t=di(e);this.env=Object.assign(this.env,t)}setInputs(e){e&&this.setEnvVariables(e)}setMomenticSystemVariable(e,t){this.varsFromMomenticEnvironment[e]=t}getVariable(e){return this.env[e]}setVariable(e,t){KR.includes(e)||(this.env[e]=t)}getEnvName(){return this.env[rn]}toObjectCopy(){let e={env:Object.assign({},this.env,this.varsFromMomenticEnvironment)};return di(e)}toEditorDisplayCopy(){return this.toObjectCopy()}toRedactedDisplayCopy(){let e=this.toObjectCopy();e.env=Object.fromEntries(Object.entries(e.env).map(([n,o])=>xg.includes(n)||this.varsFromMomenticEnvironment[n]===void 0?[n,o]:[n,qR]));for(let[n,o]of Object.entries(e.env)){if(!o){e.env[n]=o;continue}let{jsonString:i}=Cg(JSON.stringify(o),1e3);try{e.env[n]=JSON.parse(i)}catch{e.env[n]=void 0}}let{jsonString:t}=Cg(JSON.stringify(e.env),5e3);try{e.env=JSON.parse(t)}catch{e.env={}}return e}reset(e){this.env={},this.varsFromMomenticEnvironment={},this.setEnvVariables(e.dynamicVariables??{}),this.varsFromMomenticEnvironment=di(e.variablesFromEnvironment),e.envName&&this.setMomenticSystemVariable(rn,e.envName),e.testName&&this.setMomenticSystemVariable(qn,e.testName)}getDynamicVariablesCopy(){return di(this.env)}getVariablesFromEnvironmentCopy(){return di(this.varsFromMomenticEnvironment)}};import Or from"zod";import mi from"zod";var YR=mi.object({id:mi.string().uuid(),envKey:mi.string().optional()}),hr=YR.extend({type:mi.literal("MOBILE_PRESET_STEP"),command:vg}),FG=mi.discriminatedUnion("type",[hr]);import Pe from"zod";var Zn=Pe.object({startTime:Pe.number(),endTime:Pe.number().optional(),error:Pe.string().optional()});var kc=Zn.extend({type:Pe.literal("SECTION"),name:Pe.string(),subSpans:Pe.lazy(()=>tC.array())}),XR=Zn.extend({type:Pe.literal("AI_LOCATOR_CALL"),result:Pe.object({serializedElement:Pe.string(),id:Pe.number(),thoughts:Pe.string()}).optional()}),JR=Zn.extend({type:Pe.literal("AI_ASSERTION_CALL"),result:Pe.object({thoughts:Pe.string(),result:Pe.boolean()}).optional()}),QR=Zn.extend({type:Pe.literal("WAIT_FOR_STABILITY"),reason:Pe.string().optional()}),ZR=Zn.extend({type:Pe.literal("RESOLVE_TARGET_CACHE"),result:Pe.object({serializedElement:Pe.string()}).optional()}),eC=Zn.extend({type:Pe.literal("GET_EMULATOR_STATE")}),tC=Pe.discriminatedUnion("type",[kc,XR,JR,QR,ZR,eC]);var rC=Or.object({message:Or.string().optional(),startTime:Or.number(),endTime:Or.number(),status:Or.nativeEnum(et),trace:kc.optional().catch(void 0),beforeSnapshot:Or.string().optional(),afterSnapshot:Or.string().optional()}),nC=hr.merge(rC).extend({data:Or.unknown().optional().describe("output data from the step")}),eo=nC;import Ge from"zod";import{z as Wt}from"zod";import{z as Ce}from"zod";var jt=Ce.object({id:Ce.string(),name:Pa,baseUrl:Oa,description:Ce.string().optional().nullish(),schemaVersion:Ce.string(),advanced:ai,retries:Ce.number(),envs:Ce.array(xa).nullish(),parameters:Ca.nullish(),disabled:Ce.boolean().optional(),labels:Ce.array(Ce.string()).optional().catch([])}),JG=Ce.enum(["INHERIT","ENABLED","DISABLED"]);var oC=ai.extend({failureRecovery:Ce.boolean().or(Ce.string()).optional().transform(r=>typeof r=="string"?r:r===void 0?"INHERIT":r?"ENABLED":"DISABLED"),useMemory:Ce.boolean().or(Ce.string()).optional().transform(r=>typeof r=="string"?r:r===void 0?"INHERIT":r?"ENABLED":"DISABLED")});var QG=jt.pick({name:!0,description:!0,baseUrl:!0,retries:!0,disabled:!0,parameters:!0}).extend({advanced:oC}),ZG=jt.pick({name:!0,description:!0,baseUrl:!0,retries:!0,disabled:!0,advanced:!0,parameters:!0}),iC=Ce.object({labels:Ce.array(Ce.string()).optional(),outputs:Gp.nullish()}),to=jt.merge(iC),aC=Ce.object({createdAt:Ce.coerce.date(),updatedAt:Ce.coerce.date(),updatedBy:Ce.string().nullable(),schedule:Yn,notification:Xn,createdBy:Ce.string(),organizationId:Ce.string(),folderId:Ce.string().nullable().optional()}),sC=jt.merge(aC),eH=sC.merge(jn),ka=jt.merge(jn),tH=jt.merge(en);var _g="test",Mg="module",lC="mobile-test",Xe=(t=>(t.TEST=`${_g}.yaml`,t.MODULE=`${Mg}.yaml`,t))(Xe||{}),qe=(n=>(n.TEST=`momentic/${_g}`,n.MODULE=`momentic/${Mg}`,n.MOBILE_TEST=`momentic/${lC}`,n))(qe||{}),lH=jt.merge(en),Ig=Ot.extend({steps:Wt.array(Wt.record(Wt.string(),Wt.unknown())),schemaVersion:Wt.string()}),cH=Ig.extend({fileType:Wt.literal(qe.MODULE)}),uH=Wt.object({test:Wt.string().describe("YAML for the test, including metadata and steps"),modules:Wt.record(Wt.string(),Wt.string()).describe("Map of module name to YAML for the module")});var pi=(t=>(t.USWest1="us-west1",t.EUNorth1="eu-north1",t))(pi||{});var cC=Ge.object({disableDefaultWebviewAccessibilityTree:Ge.boolean().optional(),autoGrantPermissions:Ge.boolean().optional()}),Uc=cC.extend({region:Ge.nativeEnum(pi).optional()}),gi=Ge.object({retries:Ge.number().optional().describe("number of retries to run"),defaultChannel:Ge.string().optional().describe("default channel to use"),defaultTag:Ge.string().optional().describe("default tag to use, if not set uses latest"),defaultEnv:Ge.string().optional(),emulator:Uc.optional()}),cn=Ge.object({id:Ge.string().uuid(),description:Ge.string(),schemaVersion:Ge.string(),settings:gi.optional()}),uC=cn.merge(Ge.object({steps:Ge.array(hr)})),un=Ge.object({fileType:Ge.literal(qe.MOBILE_TEST)}).merge(uC),SH=Ge.object({name:Ge.string(),steps:Ge.array(hr).optional(),settings:gi.optional()});var DH=new Set(Object.values(Ze));var dC={AI_ACTION:"AI action",AI_ACTION_DYNAMIC:"AI action",RESOLVED_MODULE:"Module",AI_ASSERTION:"AI check",AI_EXTRACT:"AI extract",CLICK:"Click",TYPE:"Type",JAVASCRIPT:"JavaScript",SELECT_OPTION:"Select",PRESS:"Press",KEY_DOWN:"Key down",KEY_UP:"Key up",NAVIGATE:"Navigate",SCROLL_UP:"Scroll up",SCROLL_DOWN:"Scroll down",SCROLL_LEFT:"Scroll left",SCROLL_RIGHT:"Scroll right",HOVER:"Hover",BLUR:"Blur",FILE_UPLOAD:"File upload",FOCUS:"Focus",GO_BACK:"Go back",GO_FORWARD:"Go forward",WAIT:"Wait",REFRESH:"Refresh",TAB:"Switch tab",NEW_TAB:"New tab",COOKIE:"Cookie",LOCAL_STORAGE:"localStorage",REQUEST:"API request",GRAPHQL_REQUEST:"GraphQL request",CAPTCHA:"CAPTCHA",DRAG:"Drag & drop",VISUAL_DIFF:"Visual diff",DIALOG:"Dialog",MOUSE_DRAG:"Mouse drag",AUTH_LOAD:"Load auth state",AUTH_SAVE:"Save auth state",ELEMENT_CHECK:"Element check",PAGE_CHECK:"Page check",WAIT_FOR_URL:"Wait for URL",COPY:"Copy",PASTE:"Paste",REGISTER_REQUEST_LISTENER:"Register request listener",AWAIT_LISTENER:"Await listener",RECORD_REQUESTS:"Record requests",GET_RECORDED_REQUESTS:"Get recorded requests",SET_HEADER:"Set header",MOCK_ROUTE:"Mock route",REMOVE_ROUTE_MOCK:"Remove route mock",OFFLINE_MODE:"Offline mode",SUCCESS:"Done"},kH={AI_ACTION:["ai","action","agent"],AI_ACTION_DYNAMIC:["ai","action","dynamic","agent"],RESOLVED_MODULE:[],AI_ASSERTION:["ai","check","assert","make sure","ensure"],AI_EXTRACT:["ai","extract","data"],CLICK:["click","press"],TYPE:["type","input","write","press"],JAVASCRIPT:["js","javascript","code","execute"],SELECT_OPTION:["select","option","choose"],PRESS:["keyboard","type","key"],KEY_DOWN:["keyboard","type","key","down","press"],KEY_UP:["keyboard","type","key","up","press"],NAVIGATE:["go to","visit"],SCROLL_UP:[],SCROLL_DOWN:[],SCROLL_LEFT:[],SCROLL_RIGHT:[],HOVER:["scroll into view","go to"],BLUR:[],FILE_UPLOAD:[],FOCUS:[],GO_BACK:[],GO_FORWARD:[],WAIT:[],REFRESH:[],TAB:[],NEW_TAB:[],COOKIE:[],LOCAL_STORAGE:[],REQUEST:[],GRAPHQL_REQUEST:[],CAPTCHA:[],DRAG:[],VISUAL_DIFF:[],DIALOG:[],MOUSE_DRAG:[],AUTH_LOAD:[],AUTH_SAVE:[],ELEMENT_CHECK:[],PAGE_CHECK:[],WAIT_FOR_URL:[],COPY:[],PASTE:[],REGISTER_REQUEST_LISTENER:[],AWAIT_LISTENER:[],RECORD_REQUESTS:[],GET_RECORDED_REQUESTS:[],SET_HEADER:[],MOCK_ROUTE:[],REMOVE_ROUTE_MOCK:[],OFFLINE_MODE:[],SUCCESS:[]},UH={AI_ACTION:"Ask AI achieve a specific goal. Saves the steps for reuse. Please use Dynamic AI action instead.",AI_ACTION_DYNAMIC:"Ask AI achieve a specific goal. Fully dynamic and does not save the steps for reuse. Our most capable AI agent.",RESOLVED_MODULE:"A list of steps that can be reused in multiple tests.",AI_ASSERTION:"Ask AI to verify whether something is true on the page.",CLICK:"Click on an element on the page.",DIALOG:"Specify how native browser dialogs should be handled.",AI_EXTRACT:"Ask AI to extract data from the page.",HOVER:"Hover over an element on the page.",FILE_UPLOAD:"Automatically upload a file when the native file upload dialog is activated.",FOCUS:"Focus an element on the page.",BLUR:"Remove focus from an element on the page.",SELECT_OPTION:"Select an option from an HTML Select <select> element.",TYPE:"Type the specified text into an element.",PRESS:"Press the specified keys using the keyboard. (e.g. Control+A)",KEY_DOWN:"Hold down the specified keys on the keyboard. (e.g. Control+A)",KEY_UP:"Release the specified keys on the keyboard. (e.g. Control+A)",NAVIGATE:"Navigate to the specified URL.",SCROLL_UP:"Scroll up by a specified height.",SCROLL_DOWN:"Scroll down by a specified height.",SCROLL_LEFT:"Scroll left by a specified width.",SCROLL_RIGHT:"Scroll right by a specified width.",GO_BACK:"Go back in browser history.",GO_FORWARD:"Go forward in browser history.",WAIT:"Wait for the specified number of seconds.",REFRESH:"Refresh the page. This will not clear cookies or session data.",TAB:"Switch to different tab in the browser.",NEW_TAB:"Create and switch to a new tab in the browser.",COOKIE:"Set a cookie that will persist throughout the browser session.",LOCAL_STORAGE:"Set a localStorage value that will persist throughout the browser session",CAPTCHA:"Solve CAPTCHAs on the page. This feature is only available on Momentic Cloud and may take up to 60 seconds. Disabling CAPTCHAs in non-production environments is strongly advised.",REQUEST:"Make an API request to a URL.",GRAPHQL_REQUEST:"Make a GraphQL request to a URL.",JAVASCRIPT:"Run JavaScript code in the browser or a Node.js environment.",DRAG:"Click and drag an element to another location.",VISUAL_DIFF:"Compare a screenshot of the page or a specific element to a baseline image.",MOUSE_DRAG:"Click and drag the mouse by a specified distance.",AUTH_LOAD:"Load or clear session state using a JavaScript object including cookies, localStorage, and IndexDB entries.",AUTH_SAVE:"Save authentication state (cookies, localStorage) into a JavaScript object.",ELEMENT_CHECK:"Assert on an element's state using pre-built conditions, including content, visibility, attribute value checks.",PAGE_CHECK:"Assert on the active page's contents using pre-built conditions.",WAIT_FOR_URL:"Wait for the active page's URL to match a target value or pattern.",COPY:"Copy the specified value to the browser clipboard.",PASTE:"Paste the browser clipboard contents.",REGISTER_REQUEST_LISTENER:"Register a listener for network requests.",AWAIT_LISTENER:"Wait for a listener to fire, and return the response data.",RECORD_REQUESTS:"Record network requests that match a given pattern.",GET_RECORDED_REQUESTS:"Get recorded requests that matched the pattern.",SET_HEADER:"Set a header.",MOCK_ROUTE:"Mock network requests to a specific URL.",REMOVE_ROUTE_MOCK:"Remove a previously set route mock.",OFFLINE_MODE:"Configure offline mode.",SUCCESS:"Indicate the entire AI action has succeeded, optionally based on a condition."},FH={AI_CHECK:"AI check",TAP:"Tap",TYPE:"Type",PRESS:"Press",OPEN_APP:"Open app",JAVASCRIPT:"JavaScript",OPEN_NOTIFICATION_DRAWER:"Open notification drawer",ADB:"ADB command",STATE:"Debug state"},BH={AI_CHECK:"Ask AI to verify whether something is true on the screen.",TAP:"Tap on an element on the screen.",TYPE:"Type the specified text into an element.",PRESS:"Press a button on the device or on the screen.",OPEN_APP:"Open an app on the device.",JAVASCRIPT:"Execute JavaScript code in a NodeJS context.",OPEN_NOTIFICATION_DRAWER:"Open the notification drawer.",ADB:"Execute an ADB command on the device.",STATE:"Get the debug state of the device."};import mC from"semver";import{z as pC}from"zod";var VH=pC.string().refine(r=>mC.valid(r),{message:"must be a valid semver string"});import{Faker as $H,en as qH}from"@faker-js/faker";import{z as O}from"zod";var YH=O.object({body:O.string(),to:O.string(),from:O.string()}),XH=O.object({from:O.string().optional(),to:O.string(),timeout:O.number().optional(),beforeDate:O.string().pipe(O.coerce.date()).or(O.date()).optional(),afterDate:O.string().pipe(O.coerce.date()).or(O.date()).optional()}),JH=O.object({to:O.string().email(),from:O.string(),subject:O.string(),body:O.string(),html:O.string().optional()}),QH=O.object({inbox:O.string().transform(r=>r.toLowerCase()),afterDate:O.string().pipe(O.coerce.date()).or(O.date()).optional(),timeout:O.number().optional(),trimWhitespace:O.boolean().optional()}),ZH=O.object({inbox:O.string(),limit:O.number().optional(),afterDate:O.string().pipe(O.coerce.date()).or(O.date()).optional(),trimWhitespace:O.boolean().optional()});var Ua=(t=>(t.RAW="RAW",t.RESPONSE="RESPONSE",t))(Ua||{}),Pg=O.object({body:O.string().nullish(),status:O.number().optional(),headers:O.array(O.tuple([O.string(),O.string()])).optional()}),gC=O.object({url:O.string(),options:O.object({method:O.string(),body:O.string().nullish(),headers:O.array(O.tuple([O.string(),O.string()])).optional()}).optional()}).optional(),hC=O.object({body:O.string().nullish(),options:O.object({status:O.number(),statusText:O.string().optional(),headers:O.array(O.tuple([O.string(),O.string()])).optional()}).optional()}).optional(),Og=O.object({result:O.unknown(),variableUpdates:O.record(O.string(),O.unknown()).optional(),persistentVariableUpdates:O.record(O.string(),O.unknown()).optional(),error:O.string().optional(),success:O.boolean()}),eV=O.object({id:O.string().optional(),orgId:O.string(),momenticLambdaAuthHash:O.string(),code:O.string(),fragment:O.boolean(),state:O.object({env:O.record(O.string(),O.unknown()),request:gC,response:hC,additionalBindings:O.record(O.string(),O.unknown()).optional()}),timeoutMs:O.number().optional(),disallowVariableUpdates:O.boolean().optional(),responseSerialization:O.nativeEnum(Ua).optional()}),Lr=15e3;import*as at from"zod";import{extendZodWithOpenApi as fC}from"zod-openapi";fC(at);var SC=at.object({url:at.string(),lineNumber:at.number(),columnNumber:at.number()}).openapi({ref:"CodeLocation"}),Fa=at.object({timestamp:at.number(),text:at.string(),type:at.string(),tabIndex:at.number(),args:at.unknown().array().optional(),url:at.string().optional(),location:SC.optional()}).openapi({ref:"ConsoleLog"}),Lg=Fa.array(),EC=Lg.array();import*as Fc from"zod";import{extendZodWithOpenApi as FC}from"zod-openapi";import{z as C}from"zod";var yC=C.object({name:C.string(),version:C.string(),comment:C.string().optional()}),TC=C.object({name:C.string(),version:C.string(),comment:C.string().optional()}),bC=C.object({onContentLoad:C.number().optional(),onLoad:C.number().optional(),comment:C.string().optional()}),Dg=C.object({startedDateTime:C.string(),id:C.string(),title:C.string().optional(),pageTimings:bC,comment:C.string().optional()}),vC=C.array(Dg),AC=C.object({name:C.string(),value:C.string(),path:C.string().optional(),domain:C.string().optional(),expires:C.string().optional(),httpOnly:C.boolean().optional(),secure:C.boolean().optional(),comment:C.string().optional()}),kg=C.array(AC),wC=C.object({name:C.string(),value:C.string(),comment:C.string().optional()}),Ug=C.array(wC),RC=C.object({name:C.string(),value:C.string(),comment:C.string().optional()}),CC=C.array(RC),xC=C.object({name:C.string(),value:C.string().optional(),fileName:C.string().optional(),contentType:C.string().optional(),comment:C.string().optional()}),_C=C.array(xC),MC=C.object({mimeType:C.string(),params:_C,text:C.string(),comment:C.string().optional()}),IC=C.object({method:C.string(),url:C.string(),httpVersion:C.string().optional(),cookies:kg,headers:Ug,queryString:CC,postData:MC.optional(),headersSize:C.number().optional(),bodySize:C.number().optional(),comment:C.string().optional()}),PC=C.object({size:C.number().optional(),compression:C.number().optional(),mimeType:C.string().optional(),text:C.string().optional(),encoding:C.string().optional(),comment:C.string().optional()}),OC=C.object({status:C.number(),statusText:C.string(),httpVersion:C.string().optional(),cookies:kg,headers:Ug,content:PC,redirectURL:C.string().optional(),headersSize:C.number().optional(),bodySize:C.number().optional(),comment:C.string().optional(),_mocked:C.boolean().optional()}),Ng=C.object({expires:C.string().optional(),lastAccess:C.string(),eTag:C.string(),hitCount:C.number(),comment:C.string().optional()}),LC=C.object({beforeRequest:Ng.optional(),afterRequest:Ng.optional(),comment:C.string().optional()}),NC=C.object({blocked:C.number().optional(),dns:C.number().optional(),connect:C.number().optional(),send:C.number(),wait:C.number(),receive:C.number(),ssl:C.number().optional(),comment:C.string().optional()}),Fg=C.object({pageref:C.string().optional(),startedDateTime:C.string(),time:C.number().optional(),request:IC,response:OC.optional(),cache:LC.optional(),timings:NC,serverIPAddress:C.string().optional(),connection:C.string().optional(),comment:C.string().optional(),_resourceType:C.string().optional()}),DC=C.array(Fg),kC=C.object({version:C.string().default("1.1"),creator:yC.optional(),browser:TC.optional(),pages:vC.optional(),entries:DC,comment:C.string().optional()}),UC=C.object({log:kC}),Bg=C.record(C.string(),Dg),zg=C.record(C.string(),Fg);FC(Fc);var BC=Fc.object({logsPerPage:Fa.array().array(),harPages:Bg.optional(),harEntries:zg.optional()}).openapi({ref:"DebugData"});var A=class extends Error{reason;constructor(e,t,n){let o=!1;for(let i of Object.values(ge))if(t.startsWith(i)){o=!0,e=i;break}if(n?.errOptions?.cause)super(o?t:`${e}: ${t}`,n?.errOptions);else{let i=o?t:`${e}${t?`: ${t}`:""}`;super(i,n?.errOptions)}this.name="TestFailureError",this.stack=this.stack?.slice(this.name.length+2),this.reason=e}toString(){return this.message}toJSON(){return{message:this.message}}},ro=class extends Error{updatedLocatorMemory;constructor(e,t,n={}){super(e,n),this.updatedLocatorMemory=t,this.name="NoElementsFoundUsingAIError"}},Nr=class extends Error{decisions;constructor(e,t,n={}){super(e,n),this.decisions=t,this.name="NoElementsFoundUsingCacheError"}toString(){return`${this.message}
2
+ var WA=Object.defineProperty;var Ie=(r,e)=>()=>(r&&(e=r(r=0)),e);var $A=(r,e)=>{for(var t in e)WA(r,t,{get:e[t],enumerable:!0})};var wS,CS=Ie(()=>{"use strict";wS=typeof globalThis=="object"?globalThis:global});var xS=Ie(()=>{"use strict";CS()});var _S=Ie(()=>{"use strict";xS()});var Cr,Nu=Ie(()=>{"use strict";Cr="1.9.0"});function wM(r){var e=new Set([r]),t=new Set,n=r.match(MS);if(!n)return function(){return!1};var o={major:+n[1],minor:+n[2],patch:+n[3],prerelease:n[4]};if(o.prerelease!=null)return function(c){return c===r};function i(l){return t.add(l),!1}function a(l){return e.add(l),!0}return function(c){if(e.has(c))return!0;if(t.has(c))return!1;var s=c.match(MS);if(!s)return i(c);var u={major:+s[1],minor:+s[2],patch:+s[3],prerelease:s[4]};return u.prerelease!=null||o.major!==u.major?i(c):o.major===0?o.minor===u.minor&&o.patch<=u.patch?a(c):i(c):o.minor<=u.minor?a(c):i(c)}}var MS,IS,PS=Ie(()=>{"use strict";Nu();MS=/^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;IS=wM(Cr)});function Eo(r,e,t,n){var o;n===void 0&&(n=!1);var i=Di[Ni]=(o=Di[Ni])!==null&&o!==void 0?o:{version:Cr};if(!n&&i[r]){var a=new Error("@opentelemetry/api: Attempted duplicate registration of API: "+r);return t.error(a.stack||a.message),!1}if(i.version!==Cr){var a=new Error("@opentelemetry/api: Registration of version v"+i.version+" for "+r+" does not match previously registered API v"+Cr);return t.error(a.stack||a.message),!1}return i[r]=e,t.debug("@opentelemetry/api: Registered a global for "+r+" v"+Cr+"."),!0}function xr(r){var e,t,n=(e=Di[Ni])===null||e===void 0?void 0:e.version;if(!(!n||!IS(n)))return(t=Di[Ni])===null||t===void 0?void 0:t[r]}function bo(r,e){e.debug("@opentelemetry/api: Unregistering a global for "+r+" v"+Cr+".");var t=Di[Ni];t&&delete t[r]}var CM,Ni,Di,ki=Ie(()=>{"use strict";_S();Nu();PS();CM=Cr.split(".")[0],Ni=Symbol.for("opentelemetry.js.api."+CM),Di=wS});function Ui(r,e,t){var n=xr("diag");if(n)return t.unshift(e),n[r].apply(n,_M([],xM(t),!1))}var xM,_M,OS,LS=Ie(()=>{"use strict";ki();xM=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},_M=function(r,e,t){if(t||arguments.length===2)for(var n=0,o=e.length,i;n<o;n++)(i||!(n in e))&&(i||(i=Array.prototype.slice.call(e,0,n)),i[n]=e[n]);return r.concat(i||Array.prototype.slice.call(e))},OS=function(){function r(e){this._namespace=e.namespace||"DiagComponentLogger"}return r.prototype.debug=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return Ui("debug",this._namespace,e)},r.prototype.error=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return Ui("error",this._namespace,e)},r.prototype.info=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return Ui("info",this._namespace,e)},r.prototype.warn=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return Ui("warn",this._namespace,e)},r.prototype.verbose=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return Ui("verbose",this._namespace,e)},r}()});var we,Is=Ie(()=>{"use strict";(function(r){r[r.NONE=0]="NONE",r[r.ERROR=30]="ERROR",r[r.WARN=50]="WARN",r[r.INFO=60]="INFO",r[r.DEBUG=70]="DEBUG",r[r.VERBOSE=80]="VERBOSE",r[r.ALL=9999]="ALL"})(we||(we={}))});function NS(r,e){r<we.NONE?r=we.NONE:r>we.ALL&&(r=we.ALL),e=e||{};function t(n,o){var i=e[n];return typeof i=="function"&&r>=o?i.bind(e):function(){}}return{error:t("error",we.ERROR),warn:t("warn",we.WARN),info:t("info",we.INFO),debug:t("debug",we.DEBUG),verbose:t("verbose",we.VERBOSE)}}var DS=Ie(()=>{"use strict";Is()});var MM,IM,PM,dr,Fi=Ie(()=>{"use strict";LS();DS();Is();ki();MM=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},IM=function(r,e,t){if(t||arguments.length===2)for(var n=0,o=e.length,i;n<o;n++)(i||!(n in e))&&(i||(i=Array.prototype.slice.call(e,0,n)),i[n]=e[n]);return r.concat(i||Array.prototype.slice.call(e))},PM="diag",dr=function(){function r(){function e(o){return function(){for(var i=[],a=0;a<arguments.length;a++)i[a]=arguments[a];var l=xr("diag");if(l)return l[o].apply(l,IM([],MM(i),!1))}}var t=this,n=function(o,i){var a,l,c;if(i===void 0&&(i={logLevel:we.INFO}),o===t){var s=new Error("Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation");return t.error((a=s.stack)!==null&&a!==void 0?a:s.message),!1}typeof i=="number"&&(i={logLevel:i});var u=xr("diag"),d=NS((l=i.logLevel)!==null&&l!==void 0?l:we.INFO,o);if(u&&!i.suppressOverrideMessage){var p=(c=new Error().stack)!==null&&c!==void 0?c:"<failed to generate stacktrace>";u.warn("Current logger will be overwritten from "+p),d.warn("Current logger will overwrite one already registered from "+p)}return Eo("diag",d,t,!0)};t.setLogger=n,t.disable=function(){bo(PM,t)},t.createComponentLogger=function(o){return new OS(o)},t.verbose=e("verbose"),t.debug=e("debug"),t.info=e("info"),t.warn=e("warn"),t.error=e("error")}return r.instance=function(){return this._instance||(this._instance=new r),this._instance},r}()});var kS,US=Ie(()=>{"use strict";kS=Symbol("BaggageEntryMetadata")});function Du(r){return typeof r!="string"&&(OM.error("Cannot create baggage metadata from unknown type: "+typeof r),r=""),{__TYPE__:kS,toString:function(){return r}}}var OM,FS=Ie(()=>{"use strict";Fi();US();OM=dr.instance()});function ku(r){return Symbol.for(r)}var LM,Uu,Fu=Ie(()=>{"use strict";LM=function(){function r(e){var t=this;t._currentContext=e?new Map(e):new Map,t.getValue=function(n){return t._currentContext.get(n)},t.setValue=function(n,o){var i=new r(t._currentContext);return i._currentContext.set(n,o),i},t.deleteValue=function(n){var o=new r(t._currentContext);return o._currentContext.delete(n),o}}return r}(),Uu=new LM});function Gu(){return zu}var xn,NM,Ps,DM,kM,UM,FM,Bu,BM,zM,GM,zu,HM,VM,jM,WM,$M,qM,KM,Hu=Ie(()=>{"use strict";xn=function(){var r=function(e,t){return r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,o){n.__proto__=o}||function(n,o){for(var i in o)Object.prototype.hasOwnProperty.call(o,i)&&(n[i]=o[i])},r(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");r(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}}(),NM=function(){function r(){}return r.prototype.createGauge=function(e,t){return VM},r.prototype.createHistogram=function(e,t){return jM},r.prototype.createCounter=function(e,t){return HM},r.prototype.createUpDownCounter=function(e,t){return WM},r.prototype.createObservableGauge=function(e,t){return qM},r.prototype.createObservableCounter=function(e,t){return $M},r.prototype.createObservableUpDownCounter=function(e,t){return KM},r.prototype.addBatchObservableCallback=function(e,t){},r.prototype.removeBatchObservableCallback=function(e){},r}(),Ps=function(){function r(){}return r}(),DM=function(r){xn(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.add=function(t,n){},e}(Ps),kM=function(r){xn(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.add=function(t,n){},e}(Ps),UM=function(r){xn(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.record=function(t,n){},e}(Ps),FM=function(r){xn(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.record=function(t,n){},e}(Ps),Bu=function(){function r(){}return r.prototype.addCallback=function(e){},r.prototype.removeCallback=function(e){},r}(),BM=function(r){xn(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(Bu),zM=function(r){xn(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(Bu),GM=function(r){xn(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(Bu),zu=new NM,HM=new DM,VM=new UM,jM=new FM,WM=new kM,$M=new BM,qM=new zM,KM=new GM});var _t,BS=Ie(()=>{"use strict";(function(r){r[r.INT=0]="INT",r[r.DOUBLE=1]="DOUBLE"})(_t||(_t={}))});var YM,XM,zS,GS=Ie(()=>{"use strict";Fu();YM=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},XM=function(r,e,t){if(t||arguments.length===2)for(var n=0,o=e.length,i;n<o;n++)(i||!(n in e))&&(i||(i=Array.prototype.slice.call(e,0,n)),i[n]=e[n]);return r.concat(i||Array.prototype.slice.call(e))},zS=function(){function r(){}return r.prototype.active=function(){return Uu},r.prototype.with=function(e,t,n){for(var o=[],i=3;i<arguments.length;i++)o[i-3]=arguments[i];return t.call.apply(t,XM([n],YM(o),!1))},r.prototype.bind=function(e,t){return t},r.prototype.enable=function(){return this},r.prototype.disable=function(){return this},r}()});var JM,QM,Vu,ZM,HS,VS=Ie(()=>{"use strict";GS();ki();Fi();JM=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},QM=function(r,e,t){if(t||arguments.length===2)for(var n=0,o=e.length,i;n<o;n++)(i||!(n in e))&&(i||(i=Array.prototype.slice.call(e,0,n)),i[n]=e[n]);return r.concat(i||Array.prototype.slice.call(e))},Vu="context",ZM=new zS,HS=function(){function r(){}return r.getInstance=function(){return this._instance||(this._instance=new r),this._instance},r.prototype.setGlobalContextManager=function(e){return Eo(Vu,e,dr.instance())},r.prototype.active=function(){return this._getContextManager().active()},r.prototype.with=function(e,t,n){for(var o,i=[],a=3;a<arguments.length;a++)i[a-3]=arguments[a];return(o=this._getContextManager()).with.apply(o,QM([e,t,n],JM(i),!1))},r.prototype.bind=function(e,t){return this._getContextManager().bind(e,t)},r.prototype._getContextManager=function(){return xr(Vu)||ZM},r.prototype.disable=function(){this._getContextManager().disable(),bo(Vu,dr.instance())},r}()});var To,jS=Ie(()=>{"use strict";VS();To=HS.getInstance()});var F,WS=Ie(()=>{"use strict";Fi();F=dr.instance()});var eI,$S,qS=Ie(()=>{"use strict";Hu();eI=function(){function r(){}return r.prototype.getMeter=function(e,t,n){return zu},r}(),$S=new eI});var ju,KS,YS=Ie(()=>{"use strict";qS();ki();Fi();ju="metrics",KS=function(){function r(){}return r.getInstance=function(){return this._instance||(this._instance=new r),this._instance},r.prototype.setGlobalMeterProvider=function(e){return Eo(ju,e,dr.instance())},r.prototype.getMeterProvider=function(){return xr(ju)||$S},r.prototype.getMeter=function(e,t,n){return this.getMeterProvider().getMeter(e,t,n)},r.prototype.disable=function(){bo(ju,dr.instance())},r}()});var Os,XS=Ie(()=>{"use strict";YS();Os=KS.getInstance()});var he=Ie(()=>{"use strict";FS();Fu();Is();Hu();BS();jS();WS();XS()});import{Argument as ym,Command as iU,Option as aU}from"@commander-js/extra-typings";import JA from"appium";import{tmpdir as QA}from"os";import{remote as ZA}from"webdriverio";import{createInstanceClient as qA}from"@limrun/api";import{execSync as KA}from"child_process";import{hostname as YA}from"os";import XA from"path";async function Em(r){let{apiClient:e,logger:t,creationOpts:n,onStatusUpdate:o,logLevel:i}=r,{token:a,webRtcUrl:l,adbUrl:c,name:s,apkDownloadUrl:u,region:d}=await e.createAndroidEmulator({...n,hostname:YA()}),p;try{KA("adb --version"),p="adb"}catch{if(process.env.ANDROID_HOME)p=XA.join(process.env.ANDROID_HOME,"platform-tools","adb");else throw new Error("adb not found in PATH and ANDROID_HOME not set")}t.info({emulatorName:s,apkToInstall:n.apkToInstall,region:d,apkDownloadUrl:u},"Android instance creation ok");let m=await qA({adbUrl:c,endpointUrl:l,token:a,logLevel:i,adbPath:p}),g=["https://github.com/appium/appium-uiautomator2-server/releases/download/v7.6.2/appium-uiautomator2-server-v7.6.2.apk","https://github.com/appium/appium-uiautomator2-server/releases/download/v7.6.2/appium-uiautomator2-server-debug-androidTest.apk","https://github.com/appium/io.appium.settings/releases/download/v5.14.15/settings_apk-debug.apk"];u&&g.push(u);let h=n.apkToInstall?.channel,f=n.apkToInstall?.tag;o(`Installing APK${h?` with channel ${h}`:""}${f?` and tag ${f}`:""}`),await Promise.all(g.map(b=>m.sendAsset(b))),o("Starting tunnel");let E=await m.startAdbTunnel();return{port:E.address.port,close:E.close,token:a,webRtcUrl:l,emulatorName:s}}async function wa({onStatusUpdate:r,creationOpts:e,apiClient:t,logger:n,logLevel:o,appiumPort:i,socket:a}){let l=Date.now(),{close:c,port:s,limbarToken:u,limbarUrl:d,emulatorName:p}=await rR({apiClient:t,logger:n,creationOpts:e,onStatusUpdate:r}),m=[()=>t.deleteAndroidEmulator(p),c],g=async()=>{for(let f=m.length-1;f>=0;f-=1)try{await m[f]()}catch(E){if(E instanceof Error&&E.message.includes("ECONNREFUSED"))return;n.warn({err:E},"Error running cleanup task")}},h=async()=>{if(a&&!a.connected)throw await g(),new Error("Client disconnected before Appium driver could be started")};await h();try{let f=await eR({logger:n,logLevel:o,appiumPort:i,port:s,limbarStart:l,emulatorName:p,apiClient:t,onStatusUpdate:r,creationOpts:e});return m.push(f.appiumClose),m.push(async()=>f.driver.deleteSession()),await h(),{...f,emulatorName:p,limbarToken:u,limbarUrl:d,adbTunnelPort:s,cleanup:g,appiumPort:i}}catch(f){throw await g(),new Error(`Failed to start Appium driver: ${f}`)}}async function eR({logger:r,logLevel:e="warn",port:t,limbarStart:n,emulatorName:o,appiumPort:i}){let a=Date.now(),{close:l,logFile:c}=await tR({logger:r,logLevel:e,appiumPort:i}),s={platformName:"Android","appium:automationName":"UiAutomator2","appium:deviceName":"Android","appium:udid":`127.0.0.1:${t}`,"appium:adbExecTimeout":3e4,"appium:newCommandTimeout":300,"appium:skipDeviceInitialization":!0,"appium:skipServerInstallation":!0,"appium:androidInstallTimeout":6e4,"appium:autoWebview":!1,"appium:autoWebviewTimeout":0},u={hostname:"localhost",port:i,logLevel:e,capabilities:s,connectionRetryTimeout:3e4,connectionRetryCount:2},d=Date.now(),p=await ZA(u);await p.updateSettings({enableMultiWindows:!0});let m=new Map;return p.on("command",g=>{m.set(g.command,Date.now())}),p.on("result",g=>{let h=m.get(g.command);if(!h)return;let f=Date.now()-h;g.result instanceof Error?r.warn({err:g.result,command:g.command,args:g.body,durationMs:f},"Appium cmd failed"):f>1e4&&r.warn({command:g.command,args:g.body,durationMs:f},"Appium cmd took very long"),m.delete(g.command)}),r.info({timings:{limbarDuration:a-n,appiumDuration:d-a,wdioDuration:Date.now()-d},capabilities:s,emulatorName:o},"Started Appium driver"),{driver:p,appiumClose:l,appiumPort:i,appiumLogFile:c}}async function tR({logger:r,logLevel:e,appiumPort:t}){let n=`${QA()}/appium-port-${Date.now()}.log`,o=await JA.main({port:t,address:"localhost",relaxedSecurityEnabled:!0,longStacktrace:e==="debug",logFormat:"json",loglevel:e,logFile:n});return{logFile:n,close:async()=>{await o.close()}}}async function rR({apiClient:r,logger:e,onStatusUpdate:t,creationOpts:n}){let{close:o,port:i,token:a,webRtcUrl:l,emulatorName:c}=await Em({apiClient:r,logger:e,creationOpts:n,onStatusUpdate:t});return{port:i,close:o,limbarToken:a,limbarUrl:l,emulatorName:c}}import bm from"crypto";import nR from"fs";async function Ca({tag:r,channel:e,filePath:t,apiClient:n,logger:o}){let i=await nR.promises.readFile(t),a=bm.createHash("md5").update(i).digest("base64"),l=bm.createHash("md5").update(i).digest("hex"),c=await n.generateAndroidAssetUrls({channel:e,tag:r??"latest",md5:a});if(c.md5&&(c.md5===a||c.md5===l)){o.info({channel:e,tag:r,md5:a,md5Hex:l},`Asset ${t} already exists on emulator platform`);return}if(c.uploadUrl){o.info({channel:e,tag:r,md5:a,uploadUrl:c.uploadUrl},`Uploading asset ${t} to emulator platform...`);try{let s=await fetch(c.uploadUrl,{headers:{"Content-Length":i.length.toString(),"Content-Type":"application/octet-stream"},method:"PUT",body:i});if(s.status!==200)throw new Error(`Got error response from emulator platform: ${s.status} ${await s.text()}`);o.info({channel:e,tag:r,md5:a},`Asset ${t} was uploaded successfully!`);return}catch(s){try{await n.deleteAndroidAsset(e,r??"latest")}catch(u){o.warn({err:u,tag:r,channel:e},"Failed to cleanup asset metadata for failed upload. Please contact Momentic support.")}throw o.error({err:s},"Failed to upload asset"),s}}throw new Error(`No upload URL was given for asset ${t}`)}import{execSync as wf}from"child_process";import{existsSync as D_}from"fs";import{platform as Cf}from"os";import{dirname as k_,join as U_,resolve as F_}from"path";import{z as Tm}from"zod";var IU=Tm.object({input:Tm.string()});import{z as $e}from"zod";var LU=$e.object({srcs:$e.array($e.string()),urls:$e.array($e.string()),desiredSrc:$e.string().optional(),desiredUrl:$e.string().optional()}),vm=$e.object({srcRegex:$e.string().optional(),urlRegex:$e.string().optional()}),Am=$e.object({x:$e.number(),y:$e.number(),correlation:$e.number()}),NU=$e.object({searchImageBase64String:$e.string(),pageImageBase64String:$e.string(),id:$e.string().uuid(),timeoutMs:$e.number().max(1e4).min(0).optional()});import{z as I}from"zod";import*as L from"zod";import{extendZodWithOpenApi as oR}from"zod-openapi";oR(L);var Or=(l=>(l.AI="AI",l.AI_HEALED="AI_HEALED",l.CLICK_TO_FIND="CLICK_TO_FIND",l.XY_PERCENT="XY_PERCENT",l.RECORDING="RECORDING",l.USER_CSS_SELECTOR="USER_CSS_SELECTOR",l.HEURISTIC_HEALED="HEURISTIC_HEALED",l))(Or||{}),iR=L.object({mPathSelectorTokens:L.string().array(),frameSrcRegex:L.string().optional(),frameUrlRegex:L.string().optional(),indices:L.number().array()}),gc=L.object({result:L.number(),traceId:L.string()}).array(),xa=L.object({type:L.literal("GCS_TRACES"),traces:gc}),Rm=L.object({text:L.string().optional(),attributes:L.record(L.string(),L.string()).optional(),boundingBox:L.object({x:L.number(),y:L.number(),width:L.number(),height:L.number()}).optional()}),aR=L.object({selectors:L.string().array(),requirements:Rm.optional()}),Lr=L.object({id:L.number().int(),dataMomenticId:L.number().int().optional(),selector:L.string().optional(),hybridSelector:L.object({textContent:L.string().nullish(),attributes:L.record(L.string(),L.string()),tagName:L.string(),expandShadowRoot:L.boolean().optional(),classNames:L.string().array(),nthChild:L.number()}).array().optional(),generatedSelectors:L.string().array().optional(),requirements:Rm.optional(),additionalElements:aR.array().optional(),role:L.string().optional(),name:L.string().optional(),numChildren:L.number().optional(),content:L.string().optional(),pathFromRoot:L.string().optional(),serializedHtml:L.string().optional().describe("pruned html including 1 neighbor and 1 layer of children. value for text inputs pruned."),nodeOnlySerializedHtml:L.string().optional().describe("outerHtml of the element without any children. value for text inputs pruned."),screenshotUrl:L.string().url().optional(),boundingBox:L.object({x:L.number().optional(),y:L.number().optional(),width:L.number(),height:L.number()}).describe("css pixel bounding box").optional(),frameCache:iR.optional(),inputDescription:L.string().optional().describe("the description that generated this cache"),targetSource:L.nativeEnum(Or).optional(),targetUpdateTime:L.string().optional(),targetUpdateLoggerTags:L.record(L.string(),L.string()).optional(),cacheResolutionUpdateSource:L.string().optional(),cacheResolutionUpdateTime:L.string().optional(),cacheResolutionUpdateLoggerTags:L.record(L.string(),L.string()).optional(),memory:xa.optional()}).openapi({ref:"ElementTargetCache"});function _a(r){return!!(r.serializedHtml||r.screenshotUrl||r.generatedSelectors||r.hybridSelector)}function hc(r){r.serializedHtml=void 0,r.nodeOnlySerializedHtml=void 0,r.screenshotUrl=void 0,r.boundingBox=void 0,r.hybridSelector=void 0,r.generatedSelectors=void 0,r.id=-1}var sR=L.object({type:L.literal("description"),elementDescriptor:L.string().describe("Description of the element.")}).openapi({ref:"DescriptionTarget"}),lR=L.object({x:L.number(),y:L.number()}),cR=L.object({type:L.literal("coordinates"),pixels:lR}).openapi({ref:"CoordinatesTarget"});function Nr(r){return r.type==="description"}function nr(r){return r.type==="coordinates"}var it=L.discriminatedUnion("type",[sR,cR]).openapi({ref:"ElementTarget"});function fc(r){if(!r)return!1;switch(r.type){case"description":return!!r.elementDescriptor}return!0}function wm(r){return xa.safeParse(r).success}import{v4 as se}from"uuid";import*as y from"zod";import{extendZodWithOpenApi as SR}from"zod-openapi";import{z as X}from"zod";import{extendZodWithOpenApi as uR}from"zod-openapi";import{z as qn}from"zod";var Sc=qn.object({result:qn.boolean(),traceId:qn.string()}).array(),yc=qn.object({type:qn.literal("GCS_TRACES"),traces:Sc}),Ec=qn.object({memory:yc.optional()});uR(X);var Cm=X.object({plan:X.string().optional(),evidence:X.string().optional(),thoughts:X.string(),result:X.boolean(),relevantElements:X.array(X.number()).optional(),updatedMemory:Sc.optional()}),Dr=(o=>(o.CONTAINS="CONTAINS",o.STARTS_WITH="STARTS_WITH",o.EQUALS="EQUALS",o.EXISTS="EXISTS",o))(Dr||{});var dR=X.object({type:X.literal("ELEMENT_NAME"),negated:X.boolean().optional(),operation:X.nativeEnum(Dr),value:X.string()}).openapi({ref:"ElementNameAssertion"}),pR=X.object({type:X.literal("ELEMENT_STYLE"),negated:X.boolean().optional(),operation:X.nativeEnum(Dr),property:X.string(),value:X.string()}).openapi({ref:"ElementStyleAssertion"}),mR=X.object({type:X.literal("ELEMENT_CONTENT"),negated:X.boolean().optional(),operation:X.nativeEnum(Dr),value:X.string()}).openapi({ref:"ElementContentAssertion"}),gR=X.object({type:X.literal("ELEMENT_ATTRIBUTE"),negated:X.boolean().optional(),operation:X.nativeEnum(Dr),attr:X.string(),value:X.string()}).openapi({ref:"ElementAttributeValueAssertion"}),Kn=(i=>(i.EXISTS="EXISTS",i.VISIBLE="VISIBLE",i.ENABLED="ENABLED",i.EDITABLE="EDITABLE",i.FOCUSED="FOCUSED",i))(Kn||{}),hR=X.object({type:X.literal("ELEMENT_EXISTENCE"),negated:X.boolean().optional(),condition:X.nativeEnum(Kn).describe("Treated as the element exists AND is also ...")}).openapi({ref:"ElementExistenceAssertion"}),xm=X.discriminatedUnion("type",[mR,gR,hR,dR,pR]).openapi({ref:"ManualElementAssertion"});var fR=X.object({type:X.literal("CONTENT"),negated:X.boolean().optional(),value:X.string()}).openapi({ref:"PageContentAssertion"}),_m=X.discriminatedUnion("type",[fR]).openapi({ref:"ManualPageAssertion"});import pt from"zod";var bc=pt.discriminatedUnion("type",[pt.object({type:pt.literal("SUBSTRING"),url:pt.string()}),pt.object({type:pt.literal("GLOB"),glob:pt.string()}),pt.object({type:pt.literal("REGEX"),regex:pt.string()}),pt.object({type:pt.literal("DOMAIN"),domain:pt.string()})]),Zo=pt.object({urlMatcher:bc,method:pt.string().optional()});import{z as ae}from"zod";var Ma=ae.object({url:ae.string(),method:ae.union([ae.literal("GET"),ae.literal("POST"),ae.literal("PUT"),ae.literal("DELETE"),ae.literal("PATCH")]),headers:ae.record(ae.string(),ae.string()).optional(),params:ae.record(ae.string(),ae.string()).optional(),body:ae.string().optional(),timeout:ae.number().int().optional().describe("Max seconds to wait for the request to complete")}),Mm=ae.object({url:ae.string(),headers:ae.record(ae.string(),ae.string()).optional(),query:ae.string(),variables:ae.string().optional(),timeout:ae.number().int().optional().describe("Max seconds to wait for the request to complete")}),Ia=ae.object({code:ae.string(),fragment:ae.boolean().optional(),environment:ae.union([ae.literal("NODE"),ae.literal("BROWSER")]).optional().describe("default NODE"),timeout:ae.number().int().max(60).optional().describe("Max seconds for the code to complete")});var rt=(H=>(H.AI_EXTRACT="AI_EXTRACT",H.AI_ASSERTION="AI_ASSERTION",H.AUTH_LOAD="AUTH_LOAD",H.AUTH_SAVE="AUTH_SAVE",H.BLUR="BLUR",H.CAPTCHA="CAPTCHA",H.CLICK="CLICK",H.COOKIE="COOKIE",H.COPY="COPY",H.DIALOG="DIALOG",H.DRAG="DRAG",H.ELEMENT_CHECK="ELEMENT_CHECK",H.FILE_UPLOAD="FILE_UPLOAD",H.FOCUS="FOCUS",H.GO_BACK="GO_BACK",H.GO_FORWARD="GO_FORWARD",H.HOVER="HOVER",H.JAVASCRIPT="JAVASCRIPT",H.LOCAL_STORAGE="LOCAL_STORAGE",H.MOUSE_DRAG="MOUSE_DRAG",H.NAVIGATE="NAVIGATE",H.NEW_TAB="NEW_TAB",H.PAGE_CHECK="PAGE_CHECK",H.PASTE="PASTE",H.PRESS="PRESS",H.KEY_DOWN="KEY_DOWN",H.KEY_UP="KEY_UP",H.REFRESH="REFRESH",H.REQUEST="REQUEST",H.GRAPHQL_REQUEST="GRAPHQL_REQUEST",H.SCROLL_DOWN="SCROLL_DOWN",H.SCROLL_UP="SCROLL_UP",H.SCROLL_LEFT="SCROLL_LEFT",H.SCROLL_RIGHT="SCROLL_RIGHT",H.SELECT_OPTION="SELECT_OPTION",H.SWITCH_TAB="TAB",H.TYPE="TYPE",H.VISUAL_DIFF="VISUAL_DIFF",H.WAIT="WAIT",H.WAIT_FOR_URL="WAIT_FOR_URL",H.REGISTER_REQUEST_LISTENER="REGISTER_REQUEST_LISTENER",H.AWAIT_LISTENER="AWAIT_LISTENER",H.RECORD_REQUESTS="RECORD_REQUESTS",H.GET_RECORDED_REQUESTS="GET_RECORDED_REQUESTS",H.SET_HEADER="SET_HEADER",H.MOCK_ROUTE="MOCK_ROUTE",H.REMOVE_ROUTE_MOCK="REMOVE_ROUTE_MOCK",H.OFFLINE_MODE="OFFLINE_MODE",H.SUCCESS="SUCCESS",H))(rt||{});SR(y);var G=y.object({thoughts:y.string().optional(),id:y.string().uuid().describe("unique identifier to this step, used for step cache")}),It=y.object({useSelector:y.boolean().optional(),force:y.boolean().optional(),disableCache:y.boolean().optional().describe("disable element caching for this step"),iframeUrl:y.string().optional().describe("url or url regex for the iframe")}).openapi({ref:"CommonTargetingOptions"}),Pt=y.object({target:Lr}).optional().openapi({ref:"SingleTargetCache"});function Pm(r){return Pt.safeParse(r).success}var Oa=y.object({loadTimeout:y.number().int().max(60).optional().describe("Max seconds for the page to load")}),yR=G.merge(Oa).merge(y.object({type:y.literal("NAVIGATE"),url:y.string()})).openapi({ref:"NavigateCommand"}),La=It.merge(y.object({cache:Pt})),Yn=G.merge(La.merge(y.object({target:it.optional(),type:y.literal("SCROLL_UP"),deltaY:y.number().optional()}))).openapi({ref:"ScrollUpCommand"}),Xn=G.merge(La.merge(y.object({target:it.optional(),type:y.literal("SCROLL_DOWN"),deltaY:y.number().optional()}))).openapi({ref:"ScrollDownCommand"}),Jn=G.merge(La.merge(y.object({target:it.optional(),type:y.literal("SCROLL_LEFT"),deltaX:y.number().optional()}))).openapi({ref:"ScrollLeftCommand"}),Qn=G.merge(La.merge(y.object({target:it.optional(),type:y.literal("SCROLL_RIGHT"),deltaX:y.number().optional()}))).openapi({ref:"ScrollRightCommand"}),iF=y.discriminatedUnion("type",[Yn,Xn,Jn,Qn]).openapi({ref:"AllScrollCommands"}),ER=G.merge(y.object({type:y.literal("DIALOG"),action:y.union([y.literal("ACCEPT"),y.literal("DISMISS")])})).openapi({ref:"DialogCommand"}),bR=G.merge(y.object({type:y.literal("WAIT"),delay:y.number()})).openapi({ref:"WaitCommand"}),TR=y.object({caseInsensitive:y.boolean().optional().describe("Whether to ignore case when matching the URL"),negated:y.boolean().optional().describe("Wait for the URL to NOT match the provided matcher instead."),timeout:y.number().int().optional().describe("Max seconds to wait for the URL to match")}),vR=G.extend({type:y.literal("WAIT_FOR_URL"),matcher:bc}).merge(TR).openapi({ref:"WaitUrlCommand"}),AR=G.merge(Oa).merge(y.object({type:y.literal("REFRESH")})).openapi({ref:"RefreshCommand"}),RR=G.merge(y.object({type:y.literal("GO_BACK")})).openapi({ref:"GoBackCommand"}),wR=G.merge(y.object({type:y.literal("GO_FORWARD")})).openapi({ref:"GoForwardCommand"}),CR=G.extend({type:y.literal("AUTH_SAVE")}).openapi({ref:"AuthSaveCommand"}),xR=G.extend({type:y.literal("AUTH_LOAD"),storageState:y.string().describe("JSON string auth state. Leave blank or set to the empty string to clear all existing authentication.")}).openapi({ref:"AuthLoadCommand"}),Tc=G.merge(It).extend({type:y.literal("CAPTCHA")}).openapi({ref:"CaptchaCommand"}),_R=G.extend({type:y.literal("COPY"),value:y.string()}).openapi({ref:"CopyCommand"}),MR=G.extend({type:y.literal("PASTE")}).openapi({ref:"PasteCommand"}),IR=G.merge(Ia).extend({type:y.literal("JAVASCRIPT")}).openapi({ref:"JavaScriptCommand"}),ei=G.merge(It).extend({type:y.literal("CLICK"),target:it,doubleClick:y.boolean().optional(),rightClick:y.boolean().optional(),waitForDownload:y.boolean().optional().describe("Wait for the click to trigger a file download and for the file download to complete."),delayMs:y.number().optional(),downloadTimeoutMs:y.number().optional(),cache:Pt,relativePosition:y.object({x:y.number(),y:y.number()}).optional()}).openapi({ref:"ClickCommand"}),Om=y.object({fromTarget:Lr.optional(),toTarget:Lr.optional()}),ti=G.merge(It).merge(y.object({type:y.literal("DRAG"),fromTarget:it,toTarget:it,steps:y.number().optional(),hoverSeconds:y.number().optional().describe("Seconds to hover the object before dropping"),cache:Om.optional()})).openapi({ref:"DragCommand"}),ri=G.merge(It).merge(y.object({type:y.literal("MOUSE_DRAG"),target:it.optional(),deltaX:y.string().describe("pixels to move horizontally, can be template"),deltaY:y.string().describe("pixels to move vertically, can be template"),steps:y.number().optional(),cache:Pt})).openapi({ref:"MouseDragCommand"}),ni=G.merge(It).merge(y.object({type:y.literal("HOVER"),target:it,cache:Pt})).openapi({ref:"HoverCommand"}),oi=G.merge(It).merge(y.object({type:y.literal("FOCUS"),target:it,cache:Pt})).openapi({ref:"FocusCommand"}),ii=G.merge(It).extend({type:y.literal("BLUR"),target:it.optional(),cache:Pt}).openapi({ref:"BlurCommand"}),PR=y.object({type:y.literal("URL"),url:y.string()}).describe("Accessible link to the file, either public http or local file://").openapi({ref:"UrlSource"}),OR=y.object({type:y.literal("USER_FILE"),name:y.string()}).describe("Accessible link to the file, references the google cloud file").openapi({ref:"UploadedFileSource"}),LR=G.extend({type:y.literal("FILE_UPLOAD"),fileSource:y.discriminatedUnion("type",[PR,OR]),filename:y.string().optional()}).openapi({ref:"FileUploadCommand"}),NR=y.discriminatedUnion("type",[y.object({type:y.literal("VALUE"),value:y.string()}),y.object({type:y.literal("LABEL"),label:y.string()}),y.object({type:y.literal("INDEX"),index:y.coerce.string()})]),ai=G.merge(It).extend({type:y.literal("SELECT_OPTION"),target:it,cache:Pt,choice:NR.describe("new field for selecting options, optional for backcompat")}).openapi({ref:"SelectOptionCommand"}),vc=y.union([y.literal("MULTIMODAL"),y.literal("VISION_ONLY")]),Na=G.merge(y.object({type:y.literal("AI_ASSERTION"),assertion:y.string(),disableCache:y.boolean().optional(),iframeUrl:y.string().optional(),contextChoice:vc.optional(),timeout:y.number().int().optional().describe("Max seconds to wait for assertion to be true"),cache:Ec.optional()})).openapi({ref:"AIAssertionCommand"}),kr=5,Ac=600,si=G.merge(It).extend({type:y.literal("ELEMENT_CHECK"),target:it,assertion:xm,cache:Pt.or(Ec).optional(),timeout:y.number().int().min(0).max(Ac).optional().describe("max seconds to wait for the assertion to be true")}).openapi({ref:"ElementAssertionCommand"}),DR=G.extend({type:y.literal("PAGE_CHECK"),assertion:_m,iframeUrl:y.string().optional().describe("url or url regex for the iframe"),timeout:y.number().int().min(0).max(Ac).optional().describe("max seconds to wait for the assertion to be true")}).openapi({ref:"PageAssertionCommand"}),kR=G.merge(y.object({type:y.literal("AI_EXTRACT"),goal:y.string(),schema:y.string().optional(),envKey:y.string().optional(),disableCache:y.boolean().optional(),iframeUrl:y.string().optional()})).openapi({ref:"AIExtractCommand"}),UR=y.object({clearContent:y.boolean().optional(),forceClearContent:y.boolean().optional(),delay:y.number().min(0).max(1e3).optional().describe("Delay between each press in milliseconds."),force:y.boolean().optional(),pressEnter:y.boolean().optional()}),Lm=25,li=G.merge(It).merge(UR).extend({type:y.literal("TYPE"),target:it.optional(),value:y.string(),cache:Pt}).openapi({ref:"TypeCommand"}),FR=G.merge(y.object({type:y.literal("PRESS"),value:y.string(),repeat:y.number().optional(),convertMeta:y.boolean().optional(),delayMs:y.number().optional()})).openapi({ref:"PressCommand"}),BR=G.merge(y.object({type:y.literal("KEY_DOWN"),value:y.string(),convertMeta:y.boolean().optional()})).openapi({ref:"KeyDownCommand"}),zR=G.merge(y.object({type:y.literal("KEY_UP"),value:y.string(),convertMeta:y.boolean().optional()})).openapi({ref:"KeyUpCommand"}),GR=y.object({type:y.literal("SUBSTRING"),substring:y.string()}),HR=y.object({type:y.literal("REGEX"),pattern:y.string()}),VR=y.object({type:y.literal("INDEX"),index:y.coerce.string()}),jR=y.discriminatedUnion("type",[GR,HR,VR]),WR=G.merge(Oa).merge(y.object({type:y.literal("TAB"),action:jR})).openapi({ref:"TabCommand"}),$R=G.merge(Oa).merge(y.object({type:y.literal("NEW_TAB"),url:y.string()})).openapi({ref:"NewTabCommand"}),qR=G.merge(y.object({type:y.literal("COOKIE"),value:y.string()})).openapi({ref:"CookieCommand"}),KR=G.merge(y.object({type:y.literal("LOCAL_STORAGE"),key:y.string(),value:y.string()})).openapi({ref:"LocalStorageCommand"}),YR=G.extend({type:y.literal("REQUEST")}).merge(Ma).openapi({ref:"RequestCommand"}),XR=G.extend({type:y.literal("GRAPHQL_REQUEST")}).merge(Mm).openapi({ref:"GraphQLRequestCommand"}),JR=G.merge(y.object({type:y.literal("SUCCESS"),condition:Na.optional()})).openapi({ref:"SuccessCommand"}),QR=G.merge(y.object({type:y.literal("FAILURE")})).openapi({ref:"FailureCommand"}),ZR=y.object({data:y.string().describe("location at which to find a jpg"),width:y.number(),height:y.number()}),ci=G.merge(It).merge(y.object({type:y.literal("VISUAL_DIFF"),threshold:y.number().optional().describe("default 0.1"),target:it.optional(),screenshot:ZR.optional(),cache:Pt})).openapi({ref:"VisualDiffCommand"}),ew=G.merge(y.object({type:y.literal("REGISTER_REQUEST_LISTENER"),requestMatcher:Zo,key:y.string()})).openapi({ref:"RegisterRequestListenerCommand"}),tw=G.merge(y.object({type:y.literal("AWAIT_LISTENER"),key:y.string(),timeout:y.number().optional().describe("timeout")})).openapi({ref:"WaitForListenerCommand"}),rw=G.merge(y.object({type:y.literal("RECORD_REQUESTS"),requestMatcher:Zo,key:y.string()})).openapi({ref:"RecordRequestsCommand"}),nw=G.merge(y.object({type:y.literal("GET_RECORDED_REQUESTS"),key:y.string()})).openapi({ref:"GetRecordedRequestsCommand"}),ow=G.merge(y.object({type:y.literal("SET_HEADER"),name:y.string(),value:y.string(),requestMatcher:Zo.optional()})).openapi({ref:"SetHeaderCommand"}),iw=G.merge(y.object({type:y.literal("MOCK_ROUTE"),requestMatcher:Zo,responseGenerator:y.string().describe("JavaScript code to generate a response"),fetchOriginalResponse:y.boolean().optional().describe("Whether to fetch the real response and pass it to the response generator. If enabled, the original response will be available as `response` in the code."),key:y.string().optional().describe("Key to reference this mock. This only needs to be set if you plan to remove the mock later in the test.")}).openapi({ref:"MockRouteCommandOptions"})),aw=G.merge(y.object({type:y.literal("REMOVE_ROUTE_MOCK"),key:y.string().optional().describe("Key of the mock to remove. If not set, all route mocks will be removed.")}).openapi({ref:"RemoveRouteMockCommandOptions"})),sw=G.merge(y.object({type:y.literal("OFFLINE_MODE"),enable:y.boolean()})).openapi({ref:"OfflineModeCommand"}),Nm=y.discriminatedUnion("type",[ei,li,FR,BR,zR,ai,yR,Xn,Yn,Na,ni,bR,JR]),lw=y.discriminatedUnion("type",[kR,xR,CR,Tc,qR,_R,ER,ti,si,LR,RR,wR,IR,KR,ri,$R,DR,MR,AR,YR,XR,Jn,Qn,WR,ci,oi,ii,vR,ew,tw,rw,nw,ow,iw,aw,sw]),Zn=y.discriminatedUnion("type",[...Nm.options,...lw.options]).openapi({ref:"Command"}),Da=y.discriminatedUnion("type",[...Nm.options,QR]);function Ar(r){let e;switch(r){case"PASTE":case"AUTH_SAVE":case"VISUAL_DIFF":case"SUCCESS":case"SCROLL_DOWN":case"SCROLL_UP":case"SCROLL_LEFT":case"SCROLL_RIGHT":case"CAPTCHA":case"GO_BACK":case"GO_FORWARD":case"REFRESH":e={id:se(),type:r};break;case"AUTH_LOAD":{e={id:se(),type:r,storageState:""};break}case"AI_EXTRACT":e={id:se(),type:r,goal:""};break;case"DIALOG":e={id:se(),type:r,action:"DISMISS"};break;case"DRAG":e={id:se(),type:r,fromTarget:{type:"description",elementDescriptor:""},toTarget:{type:"description",elementDescriptor:""}};break;case"MOUSE_DRAG":e={id:se(),type:r,deltaX:"0",deltaY:"0",steps:1};break;case"WAIT_FOR_URL":e={id:se(),type:r,matcher:{type:"SUBSTRING",url:""}};break;case"WAIT":e={id:se(),type:r,delay:1};break;case"BLUR":e={id:se(),type:r};break;case"HOVER":case"FOCUS":case"CLICK":e={id:se(),type:r,target:{type:"description",elementDescriptor:""}};break;case"COOKIE":case"PRESS":case"COPY":case"TYPE":e={id:se(),type:r,value:"",clearContent:!0};break;case"KEY_DOWN":case"KEY_UP":e={id:se(),type:r,value:""};break;case"SELECT_OPTION":e={id:se(),type:r,target:{type:"description",elementDescriptor:""},choice:{type:"VALUE",value:""}};break;case"NAVIGATE":case"NEW_TAB":return{id:se(),type:r,url:""};case"TAB":e={id:se(),type:r,action:{type:"SUBSTRING",substring:""}};break;case"REQUEST":e={id:se(),type:r,url:"",method:"GET"};break;case"GRAPHQL_REQUEST":e={id:se(),type:r,url:"",query:""};break;case"LOCAL_STORAGE":e={id:se(),type:r,key:"",value:""};break;case"JAVASCRIPT":e={id:se(),type:r,code:""};break;case"AI_ASSERTION":e={id:se(),type:r,assertion:""};break;case"FILE_UPLOAD":{e={id:se(),type:r,fileSource:{type:"URL",url:""}};break}case"ELEMENT_CHECK":{e={id:se(),type:r,target:{type:"description",elementDescriptor:""},assertion:{type:"ELEMENT_EXISTENCE",condition:"EXISTS"}};break}case"PAGE_CHECK":{e={id:se(),type:r,assertion:{type:"CONTENT",value:""}};break}case"REGISTER_REQUEST_LISTENER":{e={id:se(),type:r,requestMatcher:{urlMatcher:{type:"REGEX",regex:""}},key:""};break}case"AWAIT_LISTENER":{e={id:se(),type:r,key:""};break}case"RECORD_REQUESTS":{e={id:se(),type:r,requestMatcher:{urlMatcher:{type:"REGEX",regex:""}},key:""};break}case"GET_RECORDED_REQUESTS":{e={id:se(),type:r,key:""};break}case"SET_HEADER":{e={id:se(),type:r,name:"",value:""};break}case"MOCK_ROUTE":{e={id:se(),type:r,requestMatcher:{urlMatcher:{type:"REGEX",regex:""}},responseGenerator:""};break}case"REMOVE_ROUTE_MOCK":{e={id:se(),type:r};break}case"OFFLINE_MODE":{e={id:se(),type:r,enable:!0};break}default:return(n=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(r)}return e}function Dm(r){switch(r.type){case"BLUR":case"CLICK":case"DRAG":case"FOCUS":case"HOVER":case"MOUSE_DRAG":case"PRESS":case"KEY_DOWN":case"KEY_UP":case"SCROLL_DOWN":case"SCROLL_UP":case"SCROLL_LEFT":case"SCROLL_RIGHT":case"TYPE":return!0;case"AUTH_LOAD":case"AUTH_SAVE":case"AWAIT_LISTENER":case"SUCCESS":case"AI_ASSERTION":case"AI_EXTRACT":case"CAPTCHA":case"COOKIE":case"COPY":case"DIALOG":case"ELEMENT_CHECK":case"FILE_UPLOAD":case"GET_RECORDED_REQUESTS":case"GO_BACK":case"GO_FORWARD":case"GRAPHQL_REQUEST":case"JAVASCRIPT":case"LOCAL_STORAGE":case"NAVIGATE":case"NEW_TAB":case"PASTE":case"PAGE_CHECK":case"RECORD_REQUESTS":case"REGISTER_REQUEST_LISTENER":case"REFRESH":case"REQUEST":case"SELECT_OPTION":case"SET_HEADER":case"TAB":case"VISUAL_DIFF":case"WAIT":case"WAIT_FOR_URL":case"OFFLINE_MODE":case"MOCK_ROUTE":case"REMOVE_ROUTE_MOCK":return!1;default:return(t=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(r)}}import{z as cw}from"zod";var uF=cw.discriminatedUnion("type",[ii,Tc,ei,ti,oi,ni,ri,Yn,Xn,Jn,Qn,ai,li,ci,si]);import{z as uw}from"zod";import{z as Ur}from"zod";function ui(r){return Ur.object({key:Ur.string(),testId:Ur.string().optional(),moduleId:Ur.string().optional(),organizationId:Ur.string(),value:r})}function di(r){return ui(r).extend({uniqueKey:Ur.string()})}function ka(r){return Ur.record(Ur.string(),di(r))}var mt={type:!0,cache:!0},eo=uw.discriminatedUnion("type",[Na.pick(mt),ii.pick(mt),ei.pick(mt),ti.pick(mt),si.pick(mt),oi.pick(mt),ni.pick(mt),ri.pick(mt),Yn.pick(mt),Xn.pick(mt),Jn.pick(mt),Qn.pick(mt),ai.pick(mt),li.pick(mt),ci.pick(mt)]),Rc=Object.values(rt).filter(r=>eo.options.some(e=>e.shape.type.safeParse(r).success));Zn.options.forEach(r=>{if("target"in r.shape&&!Rc.includes(r.shape.type.value))throw new Error(`Command ${r.shape.type.value} has a target but no cache`)});function km(r){return Rc.includes(r.type)}var Um=ui(eo),Fm=di(eo),yF=ka(eo);import{z as wc}from"zod";import{extendZodWithOpenApi as mw}from"zod-openapi";import{z as Bm}from"zod";import{extendZodWithOpenApi as dw}from"zod-openapi";import{z as sn}from"zod";var Ot=sn.object({index:sn.number().optional().describe("global index within a test (in-order traversal)"),id:sn.string(),skipped:sn.boolean().optional(),envKey:sn.string().optional().describe("key in the environment to save the result of this step to"),aiSuggested:sn.boolean().optional(),retries:sn.number().optional()});dw(Bm);var pw=Ot.extend({type:Bm.literal("PRESET_ACTION")}),Lt=pw.extend({command:Zn}).openapi({ref:"PresetAction"});mw(wc);var ln=Ot.extend({type:wc.literal("AI_ACTION"),text:wc.string(),steps:Lt.array().optional()}).openapi({ref:"AIAction"});import{z as gt}from"zod";import{z as Ua}from"zod";import{extendZodWithOpenApi as gw}from"zod-openapi";gw(Ua);var to=Ot.extend({type:Ua.literal("AI_ACTION_DYNAMIC"),text:Ua.string(),retries:Ua.number().optional()}).openapi({ref:"AIActionDynamic"});import{z as zm}from"zod";var Cc=Ot.extend({type:zm.literal("CONDITIONAL"),skipped:zm.boolean().optional()});import{z as ne}from"zod";var hw=ne.object({cacheKey:ne.string(),cacheExpiryMs:ne.number()}),xc=Ot.extend({id:ne.string().uuid().describe("ID of the module step itself. Used to 'namespace' step cache entries."),inputs:ne.record(ne.string()).optional(),cacheConfig:hw.optional()}),Rr=xc.extend({type:ne.literal("MODULE"),moduleId:ne.string().uuid()}),fw=ne.union([Rr.pick({type:!0,moduleId:!0}),ne.record(ne.unknown())]),Sw=ne.object({type:ne.literal("URL_REGEX"),regex:ne.string()}),yw=ne.object({type:ne.literal("PAGE_CHECK"),substring:ne.string()}),_c=ne.object({cacheInvalidation:ne.discriminatedUnion("type",[yw,Sw]).optional()}),Nt=ne.object({moduleId:ne.string().uuid(),name:ne.string(),description:ne.string().nullish(),enabled:ne.boolean().nullish(),parameters:ne.string().array().nullish(),defaultParameters:ne.record(ne.string(),ne.string()).nullish(),parameterEnums:ne.record(ne.string(),ne.string().array()).nullish(),defaultCacheKey:ne.string().nullish(),defaultCacheTtl:ne.number().nullish(),defaultCacheAllInvocations:ne.boolean().nullish(),autoAuth:ne.boolean().nullish(),advanced:_c.nullish()});import{z as Dt}from"zod";var Gm=(n=>(n.ALWAYS="ALWAYS",n.ON_FAILURE="ON_FAILURE",n.ON_ACTION_FAILURE="ON_ACTION_FAILURE",n))(Gm||{});var Ew=Dt.discriminatedUnion("type",[Dt.object({type:Dt.literal("NAVIGATE_URL"),url:Dt.string().url()}),Dt.object({type:Dt.literal("GO_TO_SECTION_START")})]),bw=Dt.object({trigger:Dt.nativeEnum(Gm).optional(),attempts:Dt.number().int().optional(),restartBehavior:Ew}),pi=Ot.extend({type:Dt.literal("SECTION"),description:Dt.string().describe("user provided goal of what the section should accomplish"),plan:Dt.string().array().optional(),autohealingConfig:bw.optional()});var Hm=Nt.merge(xc).extend({type:gt.literal("RESOLVED_MODULE"),steps:gt.lazy(()=>Ke.array())}),mi=Nt.extend({steps:gt.lazy(()=>Ke.array())}),Mc=pi.extend({steps:gt.lazy(()=>ht.array())}),Tw=pi.extend({steps:gt.lazy(()=>Ke.array())}),ro=Cc.extend({blocks:gt.object({assertion:gt.lazy(()=>Lt),steps:gt.lazy(()=>ht.array())}).array(),elseSteps:gt.lazy(()=>ht.array().optional())}),vw=Cc.extend({blocks:gt.object({assertion:gt.lazy(()=>Lt),steps:gt.lazy(()=>Ke.array())}).array(),elseSteps:gt.lazy(()=>Ke.array().optional())}),ht=gt.discriminatedUnion("type",[Lt,ln,to,Rr,ro,Mc]),Ke=gt.discriminatedUnion("type",[Lt,ln,to,Hm,vw,Tw]);import{z as kt}from"zod";var Aw=kt.object({steps:ht.array(),beforeSteps:ht.array().nullish(),afterSteps:ht.array().nullish()}),no=kt.object({steps:Ke.array(),beforeSteps:Ke.array().nullish(),afterSteps:Ke.array().nullish()}),cn=kt.object({steps:kt.record(kt.string(),kt.unknown()).array(),beforeSteps:kt.record(kt.string(),kt.unknown()).array().nullish(),afterSteps:kt.record(kt.string(),kt.unknown()).array().nullish()});var un="1.0.21",Ic="0.0.1";var Vm=I.object({phrase:I.string()}),Pc=I.object({thoughts:I.string().optional(),result:I.union([I.literal("NOT_FOUND"),I.string(),I.number(),I.array(I.unknown()),I.record(I.unknown(),I.unknown()),I.unknown()])}),nz=I.object({text:I.string()}),jm=I.object({attributes:I.array(I.string()).optional(),text:I.boolean().optional(),boundingBox:I.boolean().optional()}),Rw=I.object({id:I.number().int(),requirements:jm}),ww=Rw.array(),Wm=I.object({thoughts:I.string(),review:I.string().optional(),id:I.number().int(),updatedMemory:gc.optional(),requirements:jm.optional(),additionalElements:ww.optional()});var Oc=(m=>(m.NO_DESCRIPTION_PROVIDED="NO_DESCRIPTION_PROVIDED",m.FEW_WORDS="FEW_WORDS",m.STYLE_TAG="STYLE_TAG",m.TYPE_IN_DESCRIPTION="TYPE_IN_DESCRIPTION",m.HARDCODED_ATTRIBUTE="HARDCODED_ATTRIBUTE",m.NONE="NONE",m.AMBIGUOUS_DESCRIPTION="AMBIGUOUS_DESCRIPTION",m.AMBIGUOUS_ASSERTION="AMBIGUOUS_ASSERTION",m.PREFER_PAGE_CHECK="PREFER_PAGE_CHECK",m.PREFER_ASSERTION="PREFER_ASSERTION",m.HTML_ELEMENTS="HTML_ELEMENTS",m.MULTIPLE_ELEMENTS_DESCRIPTION="MULTIPLE_ELEMENTS_DESCRIPTION",m.NEEDS_DATE_VARIABLE="NEEDS_DATE_VARIABLE",m))(Oc||{}),$m=(o=>(o.NONE="NONE",o.AMBIGUOUS_DESCRIPTION="AMBIGUOUS_DESCRIPTION",o.COPILOT_MISUSE="COPILOT_MISUSE",o.IRRELEVANT_MESSAGE="IRRELEVANT_MESSAGE",o))($m||{});var qm=I.object({thoughts:I.string(),category:I.nativeEnum(Oc)}),Km=I.object({thoughts:I.string(),category:I.nativeEnum($m)}),Cw=I.discriminatedUnion("op",[I.object({op:I.literal("replace"),path:I.string(),value:I.string()}),I.object({op:I.literal("add"),path:I.string(),value:I.string()}),I.object({op:I.literal("remove"),path:I.string()})]),oz=I.object({thoughts:I.string(),patches:Cw.array()}),xw=[I.literal("add"),I.literal("replace"),I.literal("remove")],_w=I.object({op:I.union(xw),path:I.string(),value:Ke.optional()}),Ym=I.object({patches:_w.array(),thoughts:I.string()}),Xm=(n=>(n.LEGITIMATE="LEGITIMATE",n.RECOVERABLE="RECOVERABLE",n.INELIGIBLE="INELIGIBLE",n))(Xm||{}),Jm=I.object({thoughts:I.string(),scenario:I.nativeEnum(Xm),instructions:I.string().nullish()}),Qm=I.object({reasoning:I.string(),scenario:I.string(),patch:I.null().optional()}),iz=I.object({thoughts:I.string(),evaluation:I.number().min(0).max(10)}),az=I.object({observations:I.string(),reasoning:I.string(),command:Da});var Lc=I.object({summary:I.string(),reasoning:I.string(),evaluation:I.discriminatedUnion("type",[I.object({type:I.literal("DONE")}),I.object({type:I.literal("RIGHT_TRACK")}),I.object({type:I.literal("WRONG_TRACK"),feedback:I.string()}),I.object({type:I.literal("IMPOSSIBLE")})])}),Mw=I.object({startId:I.number().int(),endId:I.number().int()}),Zm=I.object({categoryThoughts:I.string(),category:I.string(),relevantSections:Mw.array()});import{z as _}from"zod";import*as J from"zod";var pz=J.object({thoughts:J.string().optional().describe("only provided if a description was provided"),target:Lr.optional().describe("only provided if a description was provided"),pageState:J.string().optional().describe("serialized a11y tree, only provided if a description was provided"),options:J.object({label:J.string(),value:J.string()}).array().optional().describe("list of options, provided for <select> elements only"),screenshot:J.object({data:J.string(),height:J.number().int(),width:J.number().int()}).optional().describe("only provided if returnScreenshot is true")}),eg=J.union([J.literal("ELEMENT_CHECK"),J.literal("NEGATED_CHECK"),J.literal("NEGATED_ELEMENT_VISIBLE_CHECK"),J.literal("SELECT_OPTION"),J.literal("TYPE")]);function gi(r){if(!("useSelector"in r&&r.useSelector)){if(r.type==="SELECT_OPTION")return"SELECT_OPTION";if(r.type==="TYPE")return"TYPE";if(r.type==="ELEMENT_CHECK"&&r.assertion.type==="ELEMENT_EXISTENCE"&&r.assertion.condition==="EXISTS"&&r.assertion.negated)return"NEGATED_CHECK";if(r.type==="ELEMENT_CHECK"&&r.assertion.type==="ELEMENT_EXISTENCE"&&r.assertion.condition==="VISIBLE"&&r.assertion.negated)return"NEGATED_ELEMENT_VISIBLE_CHECK";if(r.type==="ELEMENT_CHECK")return"ELEMENT_CHECK"}}var hi=(a=>(a.USER_SELECTOR="USER_SELECTOR",a.CSS_SELECTOR="CSS_SELECTOR",a.HYBRID_SELECTOR="HYBRID_SELECTOR",a.HTML_DISTANCE="HTML_DISTANCE",a.TEMPLATE_MATCHING="TEMPLATE_MATCHING",a.AUTO_FRAME="AUTO_FRAME",a))(hi||{}),oo=J.object({matched:J.boolean(),reason:J.string().optional().describe("Human understandable description"),logs:J.string().array().optional().describe("Logs for debugging")}),Iw=oo.extend({type:J.literal("USER_SELECTOR")}),Pw=oo.extend({type:J.literal("CSS_SELECTOR"),selectors:J.string().array()}),Ow=oo.extend({type:J.literal("HYBRID_SELECTOR")}),Lw=oo.extend({type:J.literal("HTML_DISTANCE"),distance:J.number().optional(),closestElement:J.string().optional(),savedElement:J.string().optional()}),Nw=oo.extend({type:J.literal("TEMPLATE_MATCHING"),elementImageUrl:J.string().url()}),Dw=oo.extend({type:J.literal("AUTO_FRAME"),logs:J.string().array().optional()}),tg=J.discriminatedUnion("type",[Iw,Pw,Ow,Lw,Nw,Dw]);import{z as Ei}from"zod";import{z as $w}from"zod";import*as z from"zod";import{extendZodWithOpenApi as Fw}from"zod-openapi";import{cloneDeep as Az}from"lodash-es";import wz from"truncate-json";import*as mn from"zod";import{extendZodWithOpenApi as kw}from"zod-openapi";import{z as at}from"zod";import{z as fe}from"zod";var Nc=fe.object({autoFollowNewTabs:fe.boolean().optional().describe("Deprecated: Auto-follow new tabs that are opened."),showZeroOpacityElements:fe.union([fe.boolean(),fe.literal("inputs-only")]).optional(),ignoreHrefForCaching:fe.boolean().optional(),disableSecondaryCacheResolution:fe.boolean().optional(),hybridSelectorMode:fe.enum(["off","test","prefer"]).optional(),globalLocatorRedirect:fe.boolean().optional(),visualActions:fe.boolean().optional(),autoExpandIframes:fe.boolean().optional(),disableHtmlSnapshots:fe.boolean().optional(),importantAttributes:fe.string().array().optional(),importantClasses:fe.string().array().optional(),importantStyles:fe.string().array().optional()});var rg=1e4,ng=6e4,dn=Nc.extend({pageLoadTimeoutMs:fe.number().optional().refine(r=>r===void 0||r<=ng&&r>=-1,{message:`Page load timeout must be between 0 and ${ng/1e3} seconds`}).describe("global page load timeout default for all tests in ms, can still be overridden by individual tests"),smartWaitingTimeoutMs:fe.number().optional().refine(r=>r===void 0||r<=rg&&r>=-1,{message:`Smart waiting timeout must be between 0 and ${rg/1e3} seconds`}),localChromeExtensionPaths:fe.string().array().optional(),extraHeaders:fe.record(fe.string(),fe.string()).optional().describe("HTTP headers to be sent on every request"),userAgent:fe.string().optional(),disableGpu:fe.boolean().optional(),bustCacheOnBoundingBoxChange:fe.boolean().optional().describe("Bust the cache if no elements are matched that have the same bounding box and location as the original element. This will improve accuracy on sites that use many same components, at the expense of stability and speed."),allowPartialAccessibilityTree:fe.boolean().optional().describe("Allow fetching the partial accessibility tree if fetching the full tree takes too long."),ignoreHttpsErrors:fe.boolean().optional().describe("Ignore HTTPS errors, such as self-signed certificates and certificate errors. This can be useful for testing sites that use self-signed certificates or certificate errors.")});var Dc="BASE_URL";var pn="ENV_NAME",io="TEST_NAME",yz={[Dc]:"https://www.google.com"},og=at.string().describe("Name of the fixture (must be available locally in the fixtures directory)."),ig=at.object({name:at.string(),variables:at.record(at.string().describe("variable name"),at.string().describe("variable value"))}),ag=at.object({name:at.string(),variables:at.record(at.string().describe("variable name"),at.unknown().describe("variable value")),browser:dn.optional()});var Ez=at.object({name:at.string(),variables:at.record(at.string().describe("variable name"),at.unknown().describe("variable value"))});kw(mn);var kc=mn.object({env:mn.record(mn.unknown())}).openapi({ref:"TestContextSnapshot"});var Ye=(i=>(i.SUCCESS="SUCCESS",i.FAILED="FAILED",i.RUNNING="RUNNING",i.IDLE="IDLE",i.CANCELLED="CANCELLED",i))(Ye||{}),Uc=(n=>(n.SUCCESS="SUCCESS",n.FAILED="FAILED",n.CANCELLED="CANCELLED",n))(Uc||{});import{z as or}from"zod";import{extendZodWithOpenApi as Uw}from"zod-openapi";Uw(or);var ge=(p=>(p.AI_PROVIDER="AIProviderError",p.USER_INFRA="UserInfrastructureError",p.ACTION_FAILURE="ActionFailureError",p.ASSERTION_FAILURE="AssertionFailureError",p.CONFIG_ERROR="UserConfigurationError",p.SETUP_FAILURE="SetupFailureError",p.TEARDOWN_FAILURE="TeardownFailureError",p.WEB_AGENT_PLATFORM="InternalWebAgentError",p.UNKNOWN_PLATFORM="InternalPlatformError",p.JOB_TIMEOUT="JobTimeoutError",p.CONCURRENCY_ERROR="ConcurrencyError",p.UNKNOWN="UnknownError",p))(ge||{});var Fc=or.object({reason:or.nativeEnum(ge),previousStepsDescription:or.array(or.string()).optional(),summary:or.string(),rootCause:or.string().optional()}).openapi({ref:"TestResultClassification"}),Fa=or.object({errorMessage:or.string(),errorStack:or.string().optional(),classification:Fc.optional()}).openapi({ref:"TestFailureDetails"});Fw(z);var Bc=z.object({beforeUrl:z.string().optional(),afterUrl:z.string().optional(),message:z.string().optional(),beforeSnapshot:z.string().optional(),afterSnapshot:z.string().optional(),startedAt:z.coerce.date(),finishedAt:z.coerce.date()}),Bw=Bc.extend({viewport:z.object({height:z.number(),width:z.number()}).nullish(),status:z.nativeEnum(Uc),message:z.string().optional(),elementInteracted:z.string().optional()}),gn=Bc.extend({status:z.nativeEnum(Ye),message:z.string().optional(),data:z.unknown().optional(),beforeTestContext:kc.optional(),afterTestContext:kc.optional(),failureReason:z.nativeEnum(ge).optional(),details:z.unknown().describe("Parse using StepExecutionLogSchema.array() to get type safety. We don't explicitly type it because it's non-critical information.")}).openapi({ref:"StepResultMetadata"}),sg=(t=>(t.NOT_ELIGIBLE="NOT_ELIGIBLE",t.ATTEMPTED="ATTEMPTED",t))(sg||{}),Ba=gn.merge(Lt).extend({results:Bw.array().describe("Command that was executed. Array is just for consistency with other result types. There should only ever be one item."),previousAttempts:z.lazy(()=>Qe.array()).optional(),failureRecoveryStatus:z.object({type:z.nativeEnum(sg),message:z.string()}).optional()}),zw=gn.merge(ln).extend({results:z.lazy(()=>Ba.array()),previousAttempts:z.lazy(()=>Qe.array()).optional()}),Gw=gn.merge(to).extend({results:z.lazy(()=>Ba.array()),previousAttempts:z.lazy(()=>Qe.array()).optional()}),Hw=gn.merge(Rr).extend({moduleName:z.string().optional(),results:z.lazy(()=>Qe.array()),previousAttempts:z.lazy(()=>Qe.array()).optional()}),Vw=gn.merge(ro).extend({assertion:Ba.optional(),results:z.lazy(()=>Qe.array()).describe("results for the block actually executed"),previousAttempts:z.lazy(()=>Qe.array()).optional()}),jw=gn.merge(pi).extend({results:z.lazy(()=>Qe.array()),healingAttempts:z.lazy(()=>Qe.array().array()).optional(),previousAttempts:z.lazy(()=>Qe.array()).optional()}),Qe=z.discriminatedUnion("type",[zw,Gw,Ba,Hw,Vw,jw]),jz=gn.pick({startedAt:!0,finishedAt:!0,status:!0,message:!0,data:!0}),Ww=Bc.extend({index:z.number().optional(),description:z.string(),pageState:z.string().optional(),elementInteracted:z.string().optional(),startedAt:z.coerce.date().or(z.string()).optional().catch(void 0),finishedAt:z.coerce.date().or(z.string()).optional().catch(void 0)}),za=Ww.extend({beforeScreenshot:z.string().optional(),afterScreenshot:z.string().optional()});var zc=$w.object({results:Qe.array().describe("main results"),beforeResults:Qe.array().optional(),afterResults:Qe.array().optional()}),fi=zc.partial();import{z as k}from"zod";import{extendZodWithOpenApi as Zw}from"zod-openapi";var ao=(t=>(t.WEB="WEB",t.ANDROID="ANDROID",t))(ao||{});import{isValidCron as qw}from"cron-validator";import{z as Q}from"zod";import{z as Gc}from"zod";var Fr=(n=>(n.CHROMIUM="Chromium",n.GOOGLE_CHROME="Google Chrome",n.CHROME_FOR_TESTING="Chrome for Testing",n))(Fr||{});var Ga=Gc.object({width:Gc.number().min(200).max(1e4),height:Gc.number().min(200).max(1e4)}),lg={"Desktop Large":{width:1920,height:1080},"Desktop Small":{width:1280,height:800},iPad:{width:768,height:1024},"Pixel 8":{width:448,height:998},"iPhone 15":{width:393,height:852}},Jz=Object.keys(lg);var Br=lg["Desktop Large"],cg="en-us",ug="America/Los_Angeles";var dg={latitude:37.7749,longitude:-122.4194};var pg=["Africa/Abidjan","Africa/Accra","Africa/Algiers","Africa/Bissau","Africa/Cairo","Africa/Casablanca","Africa/Ceuta","Africa/El_Aaiun","Africa/Johannesburg","Africa/Juba","Africa/Khartoum","Africa/Lagos","Africa/Maputo","Africa/Monrovia","Africa/Nairobi","Africa/Ndjamena","Africa/Sao_Tome","Africa/Tripoli","Africa/Tunis","Africa/Windhoek","America/Adak","America/Anchorage","America/Argentina/Buenos_Aires","America/Argentina/Catamarca","America/Argentina/Cordoba","America/Argentina/Jujuy","America/Argentina/La_Rioja","America/Argentina/Mendoza","America/Argentina/Rio_Gallegos","America/Argentina/Salta","America/Argentina/San_Juan","America/Argentina/San_Luis","America/Argentina/Tucuman","America/Argentina/Ushuaia","America/Araguaina","America/Asuncion","America/Atikokan","America/Bahia","America/Bahia_Banderas","America/Barbados","America/Belem","America/Belize","America/Blanc-Sablon","America/Boa_Vista","America/Bogota","America/Boise","America/Cambridge_Bay","America/Campo_Grande","America/Cancun","America/Caracas","America/Cayenne","America/Chicago","America/Chihuahua","America/Costa_Rica","America/Creston","America/Cuiaba","America/Curacao","America/Danmarkshavn","America/Dawson","America/Dawson_Creek","America/Denver","America/Detroit","America/Dominica","America/Edmonton","America/Eirunepe","America/El_Salvador","America/Fort_Nelson","America/Fortaleza","America/Glace_Bay","America/Goose_Bay","America/Grand_Turk","America/Grenada","America/Guadeloupe","America/Guatemala","America/Guayaquil","America/Guyana","America/Halifax","America/Havana","America/Hermosillo","America/Indiana/Indianapolis","America/Indiana/Knox","America/Indiana/Marengo","America/Indiana/Petersburg","America/Indiana/Tell_City","America/Indiana/Vevay","America/Indiana/Vincennes","America/Indiana/Winamac","America/Inuvik","America/Iqaluit","America/Jamaica","America/Juneau","America/Kentucky/Louisville","America/Kentucky/Monticello","America/La_Paz","America/Lima","America/Los_Angeles","America/Maceio","America/Managua","America/Manaus","America/Marigot","America/Martinique","America/Matamoros","America/Mazatlan","America/Menominee","America/Merida","America/Metlakatla","America/Mexico_City","America/Miquelon","America/Moncton","America/Monterrey","America/Montevideo","America/Montserrat","America/Nassau","America/New_York","America/Nipigon","America/Nome","America/Noronha","America/North_Dakota/Beulah","America/North_Dakota/Center","America/North_Dakota/New_Salem","America/Ojinaga","America/Panama","America/Pangnirtung","America/Paramaribo","America/Phoenix","America/Port-au-Prince","America/Port_of_Spain","America/Porto_Velho","America/Puerto_Rico","America/Punta_Arenas","America/Rainy_River","America/Rankin_Inlet","America/Recife","America/Regina","America/Resolute","America/Rio_Branco","America/Santarem","America/Santiago","America/Santo_Domingo","America/Sao_Paulo","America/Scoresbysund","America/Sitka","America/St_Barthelemy","America/St_Johns","America/St_Kitts","America/St_Lucia","America/St_Thomas","America/St_Vincent","America/Swift_Current","America/Tegucigalpa","America/Thule","America/Thunder_Bay","America/Tijuana","America/Toronto","America/Tortola","America/Vancouver","America/Whitehorse","America/Winnipeg","America/Yakutat","America/Yellowknife","Antarctica/Casey","Antarctica/Davis","Antarctica/DumontDUrville","Antarctica/Macquarie","Antarctica/Mawson","Antarctica/Palmer","Antarctica/Rothera","Antarctica/Syowa","Antarctica/Troll","Antarctica/Vostok","Arctic/Longyearbyen","Asia/Aden","Asia/Almaty","Asia/Amman","Asia/Anadyr","Asia/Aqtau","Asia/Aqtobe","Asia/Ashgabat","Asia/Atyrau","Asia/Baghdad","Asia/Bahrain","Asia/Baku","Asia/Bangkok","Asia/Barnaul","Asia/Beirut","Asia/Bishkek","Asia/Brunei","Asia/Chita","Asia/Choibalsan","Asia/Colombo","Asia/Damascus","Asia/Dhaka","Asia/Dili","Asia/Dubai","Asia/Dushanbe","Asia/Famagusta","Asia/Gaza","Asia/Hebron","Asia/Ho_Chi_Minh","Asia/Hong_Kong","Asia/Hovd","Asia/Irkutsk","Asia/Jakarta","Asia/Jayapura","Asia/Jerusalem","Asia/Kabul","Asia/Kamchatka","Asia/Karachi","Asia/Kathmandu","Asia/Khandyga","Asia/Kolkata","Asia/Krasnoyarsk","Asia/Kuala_Lumpur","Asia/Kuching","Asia/Kuwait","Asia/Macau","Asia/Magadan","Asia/Makassar","Asia/Manila","Asia/Muscat","Asia/Nicosia","Asia/Novokuznetsk","Asia/Novosibirsk","Asia/Omsk","Asia/Oral","Asia/Phnom_Penh","Asia/Pontianak","Asia/Pyongyang","Asia/Qatar","Asia/Qostanay","Asia/Qyzylorda","Asia/Riyadh","Asia/Sakhalin","Asia/Samarkand","Asia/Seoul","Asia/Shanghai","Asia/Singapore","Asia/Srednekolymsk","Asia/Taipei","Asia/Tashkent","Asia/Tbilisi","Asia/Tehran","Asia/Thimphu","Asia/Tokyo","Asia/Tomsk","Asia/Ulaanbaatar","Asia/Urumqi","Asia/Ust-Nera","Asia/Vientiane","Asia/Vladivostok","Asia/Yakutsk","Asia/Yangon","Asia/Yekaterinburg","Asia/Yerevan","Atlantic/Azores","Atlantic/Bermuda","Atlantic/Canary","Atlantic/Cape_Verde","Atlantic/Faroe","Atlantic/Madeira","Atlantic/Reykjavik","Atlantic/South_Georgia","Atlantic/Stanley","Australia/Adelaide","Australia/Brisbane","Australia/Broken_Hill","Australia/Currie","Australia/Darwin","Australia/Eucla","Australia/Hobart","Australia/Lindeman","Australia/Lord_Howe","Australia/Melbourne","Australia/Perth","Australia/Sydney","Europe/Amsterdam","Europe/Andorra","Europe/Astrakhan","Europe/Athens","Europe/Belgrade","Europe/Berlin","Europe/Bratislava","Europe/Brussels","Europe/Bucharest","Europe/Budapest","Europe/Busingen","Europe/Chisinau","Europe/Copenhagen","Europe/Dublin","Europe/Gibraltar","Europe/Guernsey","Europe/Helsinki","Europe/Isle_of_Man","Europe/Istanbul","Europe/Jersey","Europe/Kaliningrad","Europe/Kiev","Europe/Kirov","Europe/Lisbon","Europe/Ljubljana","Europe/London","Europe/Luxembourg","Europe/Madrid","Europe/Malta","Europe/Mariehamn","Europe/Minsk","Europe/Monaco","Europe/Moscow","Europe/Oslo","Europe/Paris","Europe/Podgorica","Europe/Prague","Europe/Riga","Europe/Rome","Europe/Samara","Europe/San_Marino","Europe/Sarajevo","Europe/Saratov","Europe/Simferopol","Europe/Skopje","Europe/Sofia","Europe/Stockholm","Europe/Tallinn","Europe/Tirane","Europe/Ulyanovsk","Europe/Uzhgorod","Europe/Vaduz","Europe/Vatican","Europe/Vienna","Europe/Vilnius","Europe/Volgograd","Europe/Warsaw","Europe/Zagreb","Europe/Zaporozhye","Europe/Zurich","Indian/Antananarivo","Indian/Chagos","Indian/Christmas","Indian/Cocos","Indian/Comoro","Indian/Kerguelen","Indian/Mahe","Indian/Maldives","Indian/Mauritius","Indian/Mayotte","Indian/Reunion","Pacific/Apia","Pacific/Auckland","Pacific/Bougainville","Pacific/Chatham","Pacific/Chuuk","Pacific/Easter","Pacific/Efate","Pacific/Enderbury","Pacific/Fakaofo","Pacific/Fiji","Pacific/Funafuti","Pacific/Galapagos","Pacific/Gambier","Pacific/Guadalcanal","Pacific/Guam","Pacific/Honolulu","Pacific/Kiritimati","Pacific/Kosrae","Pacific/Kwajalein","Pacific/Majuro","Pacific/Marquesas","Pacific/Midway","Pacific/Nauru","Pacific/Niue","Pacific/Norfolk","Pacific/Noumea","Pacific/Pago_Pago","Pacific/Palau","Pacific/Pitcairn","Pacific/Pohnpei","Pacific/Port_Moresby","Pacific/Rarotonga","Pacific/Saipan","Pacific/Tahiti","Pacific/Tarawa","Pacific/Tongatapu","Pacific/Wake","Pacific/Wallis"];var mg=2e3,Kw=dn.extend({browserType:Q.nativeEnum(Fr).optional(),slowMoMs:Q.number().optional().refine(r=>r===void 0||r<=mg&&r>=-1,{message:`Slow motion must be between 0 and ${mg} milliseconds`}),basicAuthorization:Q.object({username:Q.string().optional(),password:Q.string().optional()}).optional(),geolocation:Q.object({latitude:Q.coerce.number().refine(r=>r>=-90&&r<=90,{message:"Latitude must be between -90 and 90 degrees"}),longitude:Q.coerce.number().refine(r=>r>=-180&&r<=180,{message:"Longitude must be between -180 and 180 degrees"})}).optional(),disableJavaScript:Q.boolean().optional(),locale:Q.string().optional(),timezone:Q.enum(pg).optional(),colorScheme:Q.enum(["light","dark"]).optional()});var Hc=Q.object({useMemory:Q.boolean().optional(),failureRecovery:Q.boolean().optional().describe("undefined means inherit org settings")}),Yw=Hc.extend({disableAICaching:Q.boolean().optional(),failureRecoveryInstructions:Q.string().optional()}),Xw=Q.object({viewport:Ga.optional()}),Si=Xw.merge(Yw).merge(Kw),so=Q.object({cron:Q.string().refine(r=>qw(r),{message:"Invalid cron expression."}).default("0 0 */1 * *"),enabled:Q.boolean().default(!1),env:Q.string().optional(),timeZone:Q.string().default("America/Los_Angeles"),jobKey:Q.string().optional()}),lo=Q.object({onSuccess:Q.boolean().default(!1),failureMessage:Q.string().optional(),onFailure:Q.boolean().default(!0),successMessage:Q.string().optional()}),Jw=Q.object({name:Q.string(),required:Q.boolean().optional(),defaultValue:Q.string().describe("this is not optional because we need a value when the editor is first loaded")}),Ha=Jw.array(),Qw=Q.object({name:Q.string(),value:Q.string()}),gg=Qw.array(),Va=Q.object({name:Q.string(),default:Q.boolean().optional(),fixtures:og.array().optional()});Zw(k);var Ut={WEBHOOK:"WEBHOOK",CRON:"CRON",MANUAL:"MANUAL",CLI:"CLI"},me=(l=>(l.PENDING="PENDING",l.RUNNING="RUNNING",l.PASSED="PASSED",l.FAILED="FAILED",l.CANCELLED="CANCELLED",l.RETRYING="RETRYING",l.WAITING_FOR_USER="WAITING_FOR_USER",l))(me||{}),ja=(t=>(t.BEFORE_ALL="BEFORE_ALL",t.AFTER_ALL="AFTER_ALL",t))(ja||{});var ze=k.string().pipe(k.coerce.date()).or(k.date()),yi=k.object({id:k.string(),runKey:k.string(),organizationId:k.string(),executionType:k.nativeEnum(ao).optional().default("WEB"),createdAt:ze,createdBy:k.string(),flake:k.boolean().nullish(),scheduledAt:ze.or(k.null()),startedAt:ze.or(k.null()),updatedAt:ze.nullish(),finishedAt:ze.or(k.null()),resolvedBaseUrl:k.string().nullish(),environmentName:k.string().nullish(),gitBranchName:k.string().nullish(),githubRepository:k.string().nullish(),gitlabProjectPath:k.string().nullish(),labels:k.array(k.string()).optional(),gitOriginUrl:k.string().nullish(),gitCommitSha:k.string().nullish(),gitCommitShaShort:k.string().nullish(),gitCommitAuthorName:k.string().nullish(),cliVersion:k.string().nullish(),section:k.nativeEnum(ja).nullish(),status:k.nativeEnum(me),trigger:k.nativeEnum(Ut),attempts:k.number(),runAttempts:k.array(k.object({id:k.string(),status:k.nativeEnum(me),startedAt:ze.or(k.null()),finishedAt:ze.or(k.null())})).optional(),videos:k.array(k.string()).optional(),failureReason:k.nativeEnum(ge).nullish(),failureDetails:Fa.nullish(),failureRecoveryDetails:k.record(k.string(),k.unknown()).nullish(),pipelineId:k.string().nullish(),resolvedInputs:k.record(k.string(),k.string()).nullish(),quarantined:k.boolean().nullish().default(!1),quarantinedReason:k.string().nullish(),localTestId:k.string().nullish(),testId:k.string().nullish(),testName:k.string().nullish(),description:k.string().nullish(),test:k.object({name:k.string(),id:k.string()}).nullish().default(null),suiteId:k.string().nullish()}).openapi({ref:"RunMetadata"}),eC={id:!0,status:!0,testName:!0,localTestId:!0,testId:!0,test:{select:{name:!0,id:!0}},finishedAt:!0,failureReason:!0,failureDetails:!0},Wa=yi.pick({...eC,test:!0}),hg=yi.omit({failureReason:!0,failureDetails:!0,test:!0}),Vc=yi.extend({stepsSnapshot:k.array(k.record(k.unknown())).nullish(),resolvedInputs:k.record(k.string(),k.string()).nullish(),test:k.object({name:k.string(),id:k.string(),description:k.string().nullish(),baseUrl:k.string().nullish(),advanced:Si.nullish()}).nullish()}).merge(zc);var tC=Ei.object({id:Ei.string().uuid(),startedAt:ze.or(Ei.null()),finishedAt:ze.or(Ei.null()),status:Ei.nativeEnum(me)}).merge(fi),E1=tC.array();import{z as Ge}from"zod";var rC=Ge.object({id:Ge.string(),status:Ge.nativeEnum(me),trigger:Ge.nativeEnum(Ut),createdAt:ze,startedAt:ze.nullish(),finishedAt:ze.nullish(),gitCommitSha:Ge.string().nullish(),gitCommitShaShort:Ge.string().nullish(),gitCommitTimestamp:ze.nullish(),gitBranchName:Ge.string().nullish(),gitOriginUrl:Ge.string().nullish(),gitCommitMessage:Ge.string().nullish(),gitCommitAuthorName:Ge.string().nullish(),githubRepository:Ge.string().nullish(),gitlabProjectPath:Ge.string().nullish(),pipelineId:Ge.string().nullish(),cliVersion:Ge.string().nullish(),labels:Ge.string().array().optional(),suite:Ge.object({id:Ge.string(),name:Ge.string()}).nullish(),runs:Ge.object({status:Ge.nativeEnum(me)}).array()}).openapi({ref:"RunGroup"}),fg=rC.pick({id:!0,createdAt:!0,startedAt:!0,finishedAt:!0,status:!0,trigger:!0,suite:!0}).extend({runs:Wa.array()});import{z as Ze}from"zod";var nC=Ze.object({type:Ze.literal("TARGETING"),name:Ze.string().optional().describe("Target name to disambiguate for steps with multiple targets"),elementLocationDecisions:tg.array(),pageState:Ze.string().optional(),targetSource:Ze.nativeEnum(Or).optional(),targetUpdateTime:Ze.string().optional()}),oC=Ze.object({type:Ze.literal("AI_LOCATION"),matched:Ze.boolean(),pageState:Ze.string().optional(),ragUsed:Ze.boolean().optional(),thoughts:Ze.string().optional()}),iC=Ze.object({type:Ze.literal("ASSERTION"),relevantElementsSerialized:Ze.string().array().optional(),pageState:Ze.string().optional(),ragUsed:Ze.boolean().optional()}),aC=Ze.discriminatedUnion("type",[nC,oC,iC]);import{z as Ue}from"zod";var sC=Ue.object({id:Ue.string(),name:Ue.string()}),L1=sC.merge(Ue.object({createdAt:ze,createdBy:Ue.string(),schedule:so,notification:lo,environment:Ue.object({name:Ue.string()}).nullish(),beforeTests:Ue.object({id:Ue.string()}).array().nullish(),afterTests:Ue.object({id:Ue.string()}).array().nullish()})),Sg=Ue.object({id:Ue.string().uuid(),orgId:Ue.string(),createdAt:ze,startedAt:ze.or(Ue.null()),finishedAt:ze.or(Ue.null()),status:Ue.nativeEnum(me),trigger:Ue.nativeEnum(Ut),suite:Ue.object({id:Ue.string(),name:Ue.string()}).nullish(),runs:yi.array()}),N1=Sg.pick({id:!0,createdAt:!0,startedAt:!0,finishedAt:!0,status:!0,trigger:!0,suite:!0}),yg=Sg.extend({runs:Wa.array()});import{z as Ft}from"zod";import{cloneDeep as U1}from"lodash-es";import{z as le}from"zod";var V1=le.object({thoughts:le.string(),subGoals:le.object({instruction:le.string()}).array()}),j1=le.object({thoughts:le.string(),newPlanMarkdown:le.string()}),W1=le.object({thoughts:le.string(),correct:le.boolean(),failedActionIndex:le.number().optional()}),lC=le.object({type:le.literal("PLANNING"),beforePlan:le.string(),goalDecision:le.string(),thoughts:le.string()}),cC=le.object({type:le.literal("RUNNING"),stepDisplayName:le.string(),status:le.nativeEnum(Ye),results:Qe.array()}),uC=le.object({type:le.literal("REVISING"),beforePlan:le.string(),afterPlan:le.string(),errString:le.string(),diffs:le.string(),thoughts:le.string()}),dC=le.object({type:le.literal("SYSTEM"),message:le.string()}),pC=le.discriminatedUnion("type",[lC,cC,uC,dC]),Eg=pC.array();var X1=Ft.object({id:Ft.string(),scheduledAt:Ft.coerce.date().nullable(),startedAt:Ft.coerce.date().nullable(),finishedAt:Ft.coerce.date().nullable(),status:Ft.nativeEnum(me),history:Eg.nullable(),testPlan:Ft.object({id:Ft.string(),name:Ft.string()}).nullable(),test:Ft.object({id:Ft.string(),name:Ft.string()}).nullable()});import{z as ft}from"zod";var jc=ft.object({content:ft.string(),ids:ft.string().array(),tokenLength:ft.number()}),mC=ft.object({chunks:jc.array()}),mG=ft.object({ids:ft.string().array(),score:ft.number(),tokenLength:ft.number()}),gG=mC.extend({description:ft.string().describe("Input to pass to RAG engine"),tokenLimit:ft.number()}),bg=ft.object({ids:ft.number().array()}),Tg=ft.object({indices:ft.number().array()});var st=_.object({disableCache:_.boolean().optional(),useMemory:_.boolean().optional(),loggerTags:_.record(_.string(),_.string()).optional(),langfuseSessionId:_.string().optional(),agentConfigVersion:_.string().optional()}),vG=st.extend({chunks:jc.array(),description:_.string().describe("Input to pass to AI"),type:_.union([_.literal("locator"),_.literal("assertion"),_.literal("ai-action")]),softTokenLimit:_.number(),hardTokenLimit:_.number()}),gC=_.object({screenshotBase64AfterCommand:_.string(),urlAfterCommand:_.string(),serializedCommand:_.string(),elementInteracted:_.string().optional(),thoughts:_.string().optional()}),vg=_.object({goal:_.string(),browserState:_.string(),screenshot:_.string(),source:eg.optional().catch(void 0),memory:_.discriminatedUnion("type",[xa,_.object({type:_.literal("RESOLVED_TRACES"),traces:_.unknown().array()})]).optional()}),Ag=_.object({target:_.string().or(_.number()),browserState:_.string().optional(),screenshot:_.string().optional(),boundingBox:_.object({x:_.number(),y:_.number(),height:_.number(),width:_.number()}).optional()}),Rg=_.object({goal:_.string(),browserState:_.string(),screenshot:_.string().optional(),returnSchema:_.string().optional()}),hC=_.literal("NEGATED_CHECK"),wg=_.object({goal:_.string(),browserState:_.string(),screenshot:_.string(),url:_.string(),contextChoice:vc.optional(),memory:_.discriminatedUnion("type",[yc,_.object({type:_.literal("RESOLVED_TRACES"),traces:_.unknown().array()})]).optional(),source:hC.optional()}),Cg=_.object({command:Zn}),xg=_.object({message:_.string()}),Wc=_.object({goal:_.string(),browserState:_.string(),startingScreenshot:_.string().optional(),screenshot:_.string(),url:_.string(),history:gC.array(),actionHint:_.string().optional(),lastError:_.string().optional()}),_g=_.object({results:za.array(),errorMessage:_.string(),errorStack:_.string().optional()}),Mg=_.object({results:za.array(),goal:_.string(),errorMessage:_.string()}),Ig=_.object({failedResults:za.array(),nextStepsSerialized:_.string().array(),currentUrl:_.string(),currentPageState:_.string(),currentScreenshot:_.string(),customInstructions:_.string().optional(),testDescription:_.string().optional()}),AG=_.object({description:_.string(),type:_.union([_.literal("locator"),_.literal("assertion"),_.literal("ai-action")]),excerpt:_.string()}),Pg=_.object({type:_.string(),browserContext:_.string(),currentStep:_.string(),screenshot:_.string()});import{z as bi}from"zod";var CG=bi.object({goal:bi.string()}),Og=bi.object({keywords:bi.array(bi.string())});import{z as $c}from"zod";var $a=(o=>(o.LOCATOR="locator",o.ASSERTION="assertion",o.VISUAL_ASSERTION="visual-assertion",o.TEXT_EXTRACTION="text-extraction",o))($a||{}),MG=$c.nativeEnum($a),fC=$c.enum(["v1","v2"]),IG=fC.or($c.string().describe("for people with special configurations"));import{z as Pe}from"zod";var Lg=Pe.object({attributesRequired:Pe.array(Pe.string()).optional(),textRequired:Pe.boolean().optional(),boundsRequired:Pe.boolean().optional()}),Ng=Pe.object({id:Pe.number(),thoughts:Pe.string(),requirements:Lg.optional(),additionalElements:Pe.object({id:Pe.number(),requirements:Lg}).array().optional()}),Dg=Pe.object({description:Pe.string(),screenXml:Pe.string(),screenshot:Pe.string()}),kg=Pe.object({assertion:Pe.string(),screenXml:Pe.string(),screenshot:Pe.string()}),Ug=Pe.object({thoughts:Pe.string(),result:Pe.boolean(),relevantElements:Pe.array(Pe.number()).optional()});import{z as hn}from"zod";var Fg=hn.object({id:hn.string().uuid(),skipped:hn.boolean().optional(),envKey:hn.string().optional().describe("key in the environment to save the result of this step to")}),qc=Fg.merge(Ma).extend({type:hn.literal("REQUEST")}),Kc=Fg.merge(Ia).extend({type:hn.literal("JAVASCRIPT")}),Yc=hn.discriminatedUnion("type",[Kc,qc]);import{z as Bt}from"zod";import{z as fn}from"zod";var SC=/^[a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/,zr=r=>{let e=r.trim().toLowerCase().replace(/[^a-z0-9]/g,"-");for(;e.includes("--");)e=e.replaceAll("--","-");return e.startsWith("-")&&(e=e.slice(1)),e.endsWith("-")&&(e=e.slice(0,e.length-1)),e};var qa=fn.string().min(1).max(255).superRefine((r,e)=>{try{Xc(r)}catch(t){return e.addIssue({code:fn.ZodIssueCode.custom,message:t.message,fatal:!0}),fn.NEVER}});function Xc(r){if(r=r.toLowerCase().trim(),r.length===0||r.length>255)throw new Error("Name must be between 1 and 255 characters long");if(/[<>:"/\\|?*]/.test(r))throw new Error('Name contains one of the following invalid characters: <>:"/\\|?*');if(r.endsWith("-")||r.startsWith("-"))throw new Error("Name cannot start or end with a dash.");if(r.includes("\0"))throw new Error("Name cannot contain null characters");if(/^(con|prn|aux|nul|com[0-9]|lpt[0-9])(\..*)?$/i.test(r))throw new Error(`"${r}" is a reserved name on Windows and cannot be used as a filename.`);if(/^\.+$/.test(r)||/^\s|\s$/.test(r))throw new Error("Name cannot start or end with a space or dot.");if(r.endsWith(".yaml"))throw new Error('Name cannot end with ".yaml".');if(r==="none")throw new Error("Name cannot be 'none'.");if(r.match(SC))throw new Error("Name cannot be a UUID. Please choose a different name.")}var Ka=fn.preprocess(r=>r===null?"":r,fn.union([fn.string().url(),fn.literal("")])).optional();var Bg=Bt.object({id:Bt.string(),name:qa,description:Bt.string().optional().nullish(),baseUrl:Ka.nullish(),schemaVersion:Bt.string(),advanced:Bt.unknown().optional(),retries:Bt.number(),envs:Bt.array(Va).nullish(),parameters:Ha.nullish()}),yC=Bt.object({createdAt:Bt.coerce.date(),updatedAt:Bt.coerce.date(),schedule:so.nullish(),notification:lo.nullish(),createdBy:Bt.string(),organizationId:Bt.string()}),EC=Bg.merge(yC),rH=EC.extend({steps:Yc.array()}),nH=Bg.extend({steps:Yc.array()});import{z as vt}from"zod";var zg=vt.object({startedAt:vt.coerce.date(),finishedAt:vt.coerce.date(),status:vt.nativeEnum(Ye),message:vt.string().optional(),data:vt.unknown().optional()}),bC=zg.merge(Kc).extend({type:vt.literal("JAVASCRIPT")}),TC=zg.merge(qc).extend({type:vt.literal("REQUEST")}),vC=vt.discriminatedUnion("type",[bC,TC]),Gg=vt.object({startedAt:vt.coerce.date(),finishedAt:vt.coerce.date().nullish(),status:vt.nativeEnum(me),results:vC.array(),failureReason:vt.string().nullish(),failureDetails:Fa.nullish()});import{z as At}from"zod";var AC=At.object({id:At.string(),organizationId:At.string(),createdAt:At.coerce.date(),updatedAt:At.coerce.date(),createdBy:At.string(),scheduledAt:At.coerce.date().nullish(),startedAt:At.coerce.date().nullish(),finishedAt:At.coerce.date().nullish(),status:At.nativeEnum(me),trigger:At.nativeEnum(Ut),results:Gg.array().nullish(),apiTestName:At.string().nullish(),apiTestPath:At.string().nullish(),apiTestId:At.string().nullish()}),mH=AC.pick({status:!0,startedAt:!0,finishedAt:!0});var Ti=(o=>(o.TestRun="test-run",o.MobileTestRun="mobile-test-run",o.CreditsUsed="credits-used",o.CreditsUsedV2="credits-used-v2",o))(Ti||{}),Hg=3;function RC(r){return r==="MODULE"||r==="CONDITIONAL"||r==="SECTION"||r==="RESOLVED_MODULE"}function Jc(r){if(!RC(r))switch(r){case"PRESET_ACTION":return 0;case"AI_ACTION":return 3;case"AI_ACTION_DYNAMIC":return 5;default:(t=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(r)}}function Qc(r){switch(r.type){case"AI_EXTRACT":case"AI_ASSERTION":return Hg;case"CAPTCHA":return 3;case"CLICK":case"TYPE":case"SELECT_OPTION":case"HOVER":case"ELEMENT_CHECK":case"FOCUS":case"BLUR":case"SCROLL_DOWN":case"SCROLL_LEFT":case"SCROLL_RIGHT":case"SCROLL_UP":case"MOUSE_DRAG":return r.useSelector||!r.target||r.target.type!=="description"?0:1;case"DRAG":return r.useSelector?0:1;case"VISUAL_DIFF":case"TAB":case"JAVASCRIPT":case"NAVIGATE":case"WAIT":case"SUCCESS":case"AUTH_LOAD":case"AUTH_SAVE":case"COOKIE":case"DIALOG":case"FILE_UPLOAD":case"GO_BACK":case"GO_FORWARD":case"LOCAL_STORAGE":case"NEW_TAB":case"PAGE_CHECK":case"PRESS":case"KEY_DOWN":case"KEY_UP":case"COPY":case"PASTE":case"REFRESH":case"REQUEST":case"GRAPHQL_REQUEST":case"WAIT_FOR_URL":case"REGISTER_REQUEST_LISTENER":case"AWAIT_LISTENER":case"RECORD_REQUESTS":case"GET_RECORDED_REQUESTS":case"SET_HEADER":case"MOCK_ROUTE":case"REMOVE_ROUTE_MOCK":case"OFFLINE_MODE":return 0;default:(t=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(r)}}var Ya=class{trackStepExecution(){}async flush(){}};import{parseString as wC,splitCookiesString as CC}from"set-cookie-parser";import{z as de}from"zod";var Zc=de.object({name:de.string(),value:de.string(),url:de.string().optional(),domain:de.string().optional(),path:de.string().optional(),expires:de.number().default(Date.now()/1e3+60*60*24*365),httpOnly:de.boolean().optional(),secure:de.boolean().default(!0),sameSite:de.union([de.literal("Strict"),de.literal("Lax"),de.literal("None")]).default("None")});function Xa(r,e){let t=[],n=CC(r);for(let o of n){let i=wC(o,{decodeValues:!1});if(!i.name)throw new Error("Name missing from cookie");if(!i.value)continue;let a;if(i.sameSite){let u=i.sameSite.trim().toLowerCase();if(u==="strict")a="Strict";else if(u==="lax")a="Lax";else if(u==="none")a="None";else throw new Error(`Invalid sameSite setting in cookie: ${u}`)}i.httpOnly===void 0&&(i.httpOnly=!1),!i.path&&i.domain&&(i.path="/"),!i.domain&&e&&(i.domain=e);let l=Zc.parse({...i,expires:i.expires?i.expires.getTime()/1e3:void 0,sameSite:a});t.push(l);let c=[l.name,...Object.keys(l)].map(u=>u.toLowerCase()),s=o.match(/\b(\S+)=([^;]*)/g);if(s)for(let u of s){let[d,p]=u.split("=");if(!d||!p)throw new Error(`Invalid key-value pair in cookie: ${u}`);c.includes(d.toLowerCase())||t.push({...l,name:d,value:p})}}return t}var xC=de.object({origin:de.string(),localStorage:de.array(de.object({name:de.string(),value:de.string()}))}),_C=de.object({entries:de.record(de.string(),de.array(de.tuple([de.unknown(),de.unknown()]))),version:de.number().optional()}),Vg=de.object({cookies:Zc.array().optional(),origins:xC.array().optional(),idb:de.record(de.string(),_C).optional().describe("key is db name")});function jg(r,e){let t=[];return r.cloneSync()?.serializeSync()?.cookies.forEach(n=>{let o=Zc.safeParse({name:n.key,...n});if(!o.success)return;let i=o.data;!i.domain&&!i.url&&(i.domain=e),t.push(i)}),t}import GC from"zod";import{v4 as kH}from"uuid";import{z as Z}from"zod";import*as Se from"zod";var Wg=Se.object({requiredText:Se.string().optional(),requiredAttributes:Se.record(Se.string(),Se.string()).optional(),requiredBounds:Se.boolean().optional()}),MC=Se.object({xPath:Se.string(),requirements:Wg.optional()}),IC=Se.object({type:Se.literal("NATIVE"),bounds:Se.number().array(),resolvedDescription:Se.string(),xPath:Se.string(),elementOnlySerializedXml:Se.string(),requirements:Wg.optional(),requiredRelatedElements:MC.array().optional()}),PC=Se.object({type:Se.literal("WEBVIEW"),resolvedDescription:Se.string(),xPath:Se.string(),browserCache:Lr.optional()}),$g=Se.discriminatedUnion("type",[IC,PC]);var Sn=(u=>(u.AI_CHECK="AI_CHECK",u.TAP="TAP",u.TYPE="TYPE",u.PRESS="PRESS",u.PRESS_KEYBOARD="PRESS_KEYBOARD",u.OPEN_APP="OPEN_APP",u.OPEN_NOTIFICATION_DRAWER="OPEN_NOTIFICATION_DRAWER",u.JAVASCRIPT="JAVASCRIPT",u.ADB="ADB",u.STATE="STATE",u))(Sn||{}),eu=(c=>(c.BACK="BACK",c.HOME="HOME",c.APP_SWITCHER="APP_SWITCHER",c.POWER="POWER",c.SEARCH="SEARCH",c.VOLUME_UP="VOLUME_UP",c.VOLUME_DOWN="VOLUME_DOWN",c.VOLUME_MUTE="VOLUME_MUTE",c))(eu||{}),tu=(n=>(n.CLOSE_KEYBOARD="CLOSE_KEYBOARD",n.ENTER="ENTER",n.BACKSPACE="BACKSPACE",n))(tu||{}),qg=Z.discriminatedUnion("type",[Z.object({type:Z.literal("description"),description:Z.string()}),Z.object({type:Z.literal("coordinates"),xPercent:Z.number(),yPercent:Z.number()})]),OC=Z.object({updatedAt:Z.coerce.date().optional()}),ir=Z.object({id:Z.string().uuid(),disableCache:Z.boolean().optional()}),LC=ir.extend({type:Z.literal("STATE")}),Kg=OC.extend({target:$g}),ru=ir.extend({type:Z.literal("TAP"),target:qg,cache:Kg.optional(),longPress:Z.boolean().optional(),longPressDurationMs:Z.number().optional()}),nu=ir.extend({type:Z.literal("TYPE"),target:qg.optional(),cache:Kg.optional(),keyPressDelayMs:Z.number().optional(),text:Z.string(),clearContent:Z.boolean().optional()}),NC=ir.extend({type:Z.literal("OPEN_NOTIFICATION_DRAWER")}),DC=ir.extend({type:Z.literal("PRESS"),key:Z.nativeEnum(eu),longPress:Z.boolean().optional()}),kC=ir.extend({type:Z.literal("PRESS_KEYBOARD"),key:Z.nativeEnum(tu)}),UC=ir.extend({type:Z.literal("OPEN_APP"),packageName:Z.string(),activityName:Z.string().optional()}),FC=ir.extend({type:Z.literal("AI_CHECK"),assertion:Z.string(),timeoutSecs:Z.number().optional()}),BC=ir.extend({type:Z.literal("JAVASCRIPT"),code:Z.string(),timeout:Z.number().int().max(60).optional().describe("Max seconds for the code to complete")}),zC=ir.extend({type:Z.literal("ADB"),command:Z.string()}),Yg=Z.discriminatedUnion("type",[ru,nu,DC,UC,NC,FC,BC,kC,zC,LC]);var ou=r=>{switch(r.type){case"description":return r.description;case"coordinates":return`${r.xPercent}%, ${r.yPercent}%`}};var Xg={type:!0,cache:!0},Gr=GC.discriminatedUnion("type",[ru.pick(Xg),nu.pick(Xg)]),HC=Object.values(Sn).filter(r=>Gr.options.some(e=>e.shape.type.safeParse(r).success));function Ja(r){return HC.includes(r.type)}var Jg=ui(Gr),Qg=di(Gr),jH=ka(Gr);import{cloneDeep as vi}from"lodash-es";import Zg from"truncate-json";var VC="\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022",jC=[pn,io],eh=[pn,io],co=class r{env={};varsFromMomenticEnvironment={};constructor(e){this.reset(e)}static dummyContext(e=void 0,t=void 0,n={}){return new r({testName:e,envName:t,variablesFromEnvironment:n})}static fromSnapshot({snapshot:e,environmentVariables:t}){let n=e.env[pn],o=e.env[io],i={};for(let[l,c]of Object.entries(e.env))eh.includes(l)||(t??{})[l]===void 0&&(i[l]=c);return new r({dynamicVariables:i,envName:n,testName:o,variablesFromEnvironment:t??{}})}setEnvVariables(e){let t=vi(e);this.env=Object.assign(this.env,t)}setInputs(e){e&&this.setEnvVariables(e)}setMomenticSystemVariable(e,t){this.varsFromMomenticEnvironment[e]=t}getVariable(e){return this.env[e]}setVariable(e,t){jC.includes(e)||(this.env[e]=t)}getEnvName(){return this.env[pn]}toObjectCopy(){let e={env:Object.assign({},this.env,this.varsFromMomenticEnvironment)};return vi(e)}toEditorDisplayCopy(){return this.toObjectCopy()}toRedactedDisplayCopy(){let e=this.toObjectCopy();e.env=Object.fromEntries(Object.entries(e.env).map(([n,o])=>eh.includes(n)||this.varsFromMomenticEnvironment[n]===void 0?[n,o]:[n,VC]));for(let[n,o]of Object.entries(e.env)){if(!o){e.env[n]=o;continue}let{jsonString:i}=Zg(JSON.stringify(o),1e3);try{e.env[n]=JSON.parse(i)}catch{e.env[n]=void 0}}let{jsonString:t}=Zg(JSON.stringify(e.env),5e3);try{e.env=JSON.parse(t)}catch{e.env={}}return e}reset(e){this.env={},this.varsFromMomenticEnvironment={},this.setEnvVariables(e.dynamicVariables??{}),this.varsFromMomenticEnvironment=vi(e.variablesFromEnvironment),e.envName&&this.setMomenticSystemVariable(pn,e.envName),e.testName&&this.setMomenticSystemVariable(io,e.testName)}getDynamicVariablesCopy(){return vi(this.env)}getVariablesFromEnvironmentCopy(){return vi(this.varsFromMomenticEnvironment)}};var Ai=(t=>(t.USWest1="us-west1",t.EUNorth1="eu-north1",t))(Ai||{});import He from"zod";import{z as qt}from"zod";import{z as xe}from"zod";var $t=xe.object({id:xe.string(),name:qa,baseUrl:Ka,description:xe.string().optional().nullish(),schemaVersion:xe.string(),advanced:Si,retries:xe.number(),envs:xe.array(Va).nullish(),parameters:Ha.nullish(),disabled:xe.boolean().optional(),labels:xe.array(xe.string()).optional().catch([])}),tV=xe.enum(["INHERIT","ENABLED","DISABLED"]);var WC=Si.extend({failureRecovery:xe.boolean().or(xe.string()).optional().transform(r=>typeof r=="string"?r:r===void 0?"INHERIT":r?"ENABLED":"DISABLED"),useMemory:xe.boolean().or(xe.string()).optional().transform(r=>typeof r=="string"?r:r===void 0?"INHERIT":r?"ENABLED":"DISABLED")});var rV=$t.pick({name:!0,description:!0,baseUrl:!0,retries:!0,disabled:!0,parameters:!0}).extend({advanced:WC}),nV=$t.pick({name:!0,description:!0,baseUrl:!0,retries:!0,disabled:!0,advanced:!0,parameters:!0}),$C=xe.object({labels:xe.array(xe.string()).optional(),outputs:gg.nullish()}),uo=$t.merge($C),qC=xe.object({createdAt:xe.coerce.date(),updatedAt:xe.coerce.date(),updatedBy:xe.string().nullable(),schedule:so,notification:lo,createdBy:xe.string(),organizationId:xe.string(),folderId:xe.string().nullable().optional()}),KC=$t.merge(qC),oV=KC.merge(no),Qa=$t.merge(no),iV=$t.merge(cn);var YC="test",XC="module",JC="mobile-test",QC="mobile-module";var ye=(o=>(o.TEST=`momentic/${YC}`,o.MODULE=`momentic/${XC}`,o.MOBILE_TEST=`momentic/${JC}`,o.MOBILE_MODULE=`momentic/${QC}`,o))(ye||{}),pV=$t.merge(cn),th=Nt.extend({steps:qt.array(qt.record(qt.string(),qt.unknown())),schemaVersion:qt.string()}),mV=th.extend({fileType:qt.literal(ye.MODULE)}),gV=qt.object({test:qt.string().describe("YAML for the test, including metadata and steps"),modules:qt.record(qt.string(),qt.string()).describe("Map of module name to YAML for the module")});var iu=He.object({parameterNames:He.string().array(),defaultParameters:He.record(He.string(),He.string()).optional(),parameterEnums:He.record(He.string(),He.string().array()).optional()}),ZC=He.object({moduleId:He.string().uuid(),name:He.string(),description:He.string().nullish(),parameters:iu.optional(),enabled:He.boolean().nullish(),schemaVersion:He.string()}),Ri=ZC.omit({name:!0}),Za=Ri.extend({steps:He.array(He.record(He.string(),He.unknown()))}),ex=He.object({fileType:He.literal(ye.MOBILE_MODULE)}).merge(Za);import Rt from"zod";var Kt=(t=>(t.PRESET="MOBILE_PRESET_STEP",t.MODULE="MOBILE_MODULE_STEP",t))(Kt||{}),es=Rt.object({id:Rt.string().uuid(),envKey:Rt.string().optional(),skipped:Rt.boolean().optional()}),wi=es.extend({type:Rt.literal("MOBILE_PRESET_STEP"),command:Yg,keyPressDelayMs:Rt.number().optional()}),po=Rt.object({moduleId:Rt.string(),inputs:Rt.record(Rt.string(),Rt.string()).optional(),parameters:iu.optional()}),Ci=es.merge(po.extend({type:Rt.literal("MOBILE_MODULE_STEP")})),vV=po.extend({steps:Rt.lazy(()=>Yt.array())}),Yt=Rt.discriminatedUnion("type",[wi,Ci]);import Ve from"zod";import ts from"zod";var wr=(e=>(e.MODULE="RESOLVED_MOBILE_MODULE",e))(wr||{}),tx=po.extend({steps:ts.lazy(()=>xi.array()),name:ts.string().describe("name of the module")}),rx=es.merge(tx).extend({type:ts.literal("RESOLVED_MOBILE_MODULE")}),xi=ts.discriminatedUnion("type",[rx,wi]);function rh(r){return Object.values(wr).includes(r)||Object.values(Kt).includes(r)}var nx=Ve.object({disableDefaultWebviewAccessibilityTree:Ve.boolean().optional(),autoGrantPermissions:Ve.boolean().optional()}),au=nx.extend({region:Ve.nativeEnum(Ai).optional()}),_i=Ve.object({retries:Ve.number().optional().describe("number of retries to run"),defaultChannel:Ve.string().optional().describe("default channel to use"),defaultTag:Ve.string().optional().describe("default tag to use, if not set uses latest"),defaultEnv:Ve.string().optional(),emulator:au.optional()}),ar=Ve.object({id:Ve.string().uuid(),description:Ve.string(),schemaVersion:Ve.string(),settings:_i.optional()}),ox=ar.merge(Ve.object({steps:Ve.array(Yt)})),rs=Ve.object({fileType:Ve.literal(ye.MOBILE_TEST)}).merge(ox),kV=Ve.object({name:Ve.string(),steps:Ve.array(Yt).optional(),settings:_i.optional()}),ix=ar.extend({steps:xi.array()});import Oe from"zod";var mo=Oe.object({startTime:Oe.number(),endTime:Oe.number().optional(),error:Oe.string().optional()});var ax=mo.extend({type:Oe.literal("SECTION"),name:Oe.string(),subSpans:Oe.lazy(()=>px.array())}),sx=mo.extend({type:Oe.literal("AI_LOCATOR_CALL"),result:Oe.object({serializedElement:Oe.string(),id:Oe.number(),thoughts:Oe.string()}).optional()}),lx=mo.extend({type:Oe.literal("AI_ASSERTION_CALL"),result:Oe.object({thoughts:Oe.string(),result:Oe.boolean()}).optional()}),cx=mo.extend({type:Oe.literal("WAIT_FOR_STABILITY"),reason:Oe.string().optional()}),ux=mo.extend({type:Oe.literal("RESOLVE_TARGET_CACHE"),result:Oe.object({serializedElement:Oe.string()}).optional()}),dx=mo.extend({type:Oe.literal("GET_EMULATOR_STATE")}),px=Oe.discriminatedUnion("type",[ax,sx,lx,cx,ux,dx]);import Xt from"zod";var nh=Xt.object({message:Xt.string().optional(),startTime:Xt.number(),endTime:Xt.number(),status:Xt.nativeEnum(Ye),trace:Xt.unknown(),beforeSnapshot:Xt.string().optional(),afterSnapshot:Xt.string().optional(),data:Xt.unknown().optional().describe("output data from the step")}),mx=nh.merge(wi),gx=nh.merge(Ci).extend({steps:Xt.lazy(()=>yn.array())}),yn=Xt.discriminatedUnion("type",[mx,gx]);var cj=new Set(Object.values(rt));var hx={AI_ACTION:"AI action",AI_ACTION_DYNAMIC:"AI action",RESOLVED_MODULE:"Module",AI_ASSERTION:"AI check",AI_EXTRACT:"AI extract",CLICK:"Click",TYPE:"Type",JAVASCRIPT:"JavaScript",SELECT_OPTION:"Select",PRESS:"Press",KEY_DOWN:"Key down",KEY_UP:"Key up",NAVIGATE:"Navigate",SCROLL_UP:"Scroll up",SCROLL_DOWN:"Scroll down",SCROLL_LEFT:"Scroll left",SCROLL_RIGHT:"Scroll right",HOVER:"Hover",BLUR:"Blur",FILE_UPLOAD:"File upload",FOCUS:"Focus",GO_BACK:"Go back",GO_FORWARD:"Go forward",WAIT:"Wait",REFRESH:"Refresh",TAB:"Switch tab",NEW_TAB:"New tab",COOKIE:"Cookie",LOCAL_STORAGE:"localStorage",REQUEST:"API request",GRAPHQL_REQUEST:"GraphQL request",CAPTCHA:"CAPTCHA",DRAG:"Drag & drop",VISUAL_DIFF:"Visual diff",DIALOG:"Dialog",MOUSE_DRAG:"Mouse drag",AUTH_LOAD:"Load auth state",AUTH_SAVE:"Save auth state",ELEMENT_CHECK:"Element check",PAGE_CHECK:"Page check",WAIT_FOR_URL:"Wait for URL",COPY:"Copy",PASTE:"Paste",REGISTER_REQUEST_LISTENER:"Register request listener",AWAIT_LISTENER:"Await listener",RECORD_REQUESTS:"Record requests",GET_RECORDED_REQUESTS:"Get recorded requests",SET_HEADER:"Set header",MOCK_ROUTE:"Mock route",REMOVE_ROUTE_MOCK:"Remove route mock",OFFLINE_MODE:"Offline mode",SUCCESS:"Done"},uj={AI_ACTION:["ai","action","agent"],AI_ACTION_DYNAMIC:["ai","action","dynamic","agent"],RESOLVED_MODULE:[],AI_ASSERTION:["ai","check","assert","make sure","ensure"],AI_EXTRACT:["ai","extract","data"],CLICK:["click","press"],TYPE:["type","input","write","press"],JAVASCRIPT:["js","javascript","code","execute"],SELECT_OPTION:["select","option","choose"],PRESS:["keyboard","type","key"],KEY_DOWN:["keyboard","type","key","down","press"],KEY_UP:["keyboard","type","key","up","press"],NAVIGATE:["go to","visit"],SCROLL_UP:[],SCROLL_DOWN:[],SCROLL_LEFT:[],SCROLL_RIGHT:[],HOVER:["scroll into view","go to"],BLUR:[],FILE_UPLOAD:[],FOCUS:[],GO_BACK:[],GO_FORWARD:[],WAIT:[],REFRESH:[],TAB:[],NEW_TAB:[],COOKIE:[],LOCAL_STORAGE:[],REQUEST:[],GRAPHQL_REQUEST:[],CAPTCHA:[],DRAG:[],VISUAL_DIFF:[],DIALOG:[],MOUSE_DRAG:[],AUTH_LOAD:[],AUTH_SAVE:[],ELEMENT_CHECK:[],PAGE_CHECK:[],WAIT_FOR_URL:[],COPY:[],PASTE:[],REGISTER_REQUEST_LISTENER:[],AWAIT_LISTENER:[],RECORD_REQUESTS:[],GET_RECORDED_REQUESTS:[],SET_HEADER:[],MOCK_ROUTE:[],REMOVE_ROUTE_MOCK:[],OFFLINE_MODE:[],SUCCESS:[]},dj={AI_ACTION:"Ask AI achieve a specific goal. Saves the steps for reuse. Please use Dynamic AI action instead.",AI_ACTION_DYNAMIC:"Ask AI achieve a specific goal. Fully dynamic and does not save the steps for reuse. Our most capable AI agent.",RESOLVED_MODULE:"A list of steps that can be reused in multiple tests.",AI_ASSERTION:"Ask AI to verify whether something is true on the page.",CLICK:"Click on an element on the page.",DIALOG:"Specify how native browser dialogs should be handled.",AI_EXTRACT:"Ask AI to extract data from the page.",HOVER:"Hover over an element on the page.",FILE_UPLOAD:"Automatically upload a file when the native file upload dialog is activated.",FOCUS:"Focus an element on the page.",BLUR:"Remove focus from an element on the page.",SELECT_OPTION:"Select an option from an HTML Select <select> element.",TYPE:"Type the specified text into an element.",PRESS:"Press the specified keys using the keyboard. (e.g. Control+A)",KEY_DOWN:"Hold down the specified keys on the keyboard. (e.g. Control+A)",KEY_UP:"Release the specified keys on the keyboard. (e.g. Control+A)",NAVIGATE:"Navigate to the specified URL.",SCROLL_UP:"Scroll up by a specified height.",SCROLL_DOWN:"Scroll down by a specified height.",SCROLL_LEFT:"Scroll left by a specified width.",SCROLL_RIGHT:"Scroll right by a specified width.",GO_BACK:"Go back in browser history.",GO_FORWARD:"Go forward in browser history.",WAIT:"Wait for the specified number of seconds.",REFRESH:"Refresh the page. This will not clear cookies or session data.",TAB:"Switch to different tab in the browser.",NEW_TAB:"Create and switch to a new tab in the browser.",COOKIE:"Set a cookie that will persist throughout the browser session.",LOCAL_STORAGE:"Set a localStorage value that will persist throughout the browser session",CAPTCHA:"Solve CAPTCHAs on the page. This feature is only available on Momentic Cloud and may take up to 60 seconds. Disabling CAPTCHAs in non-production environments is strongly advised.",REQUEST:"Make an API request to a URL.",GRAPHQL_REQUEST:"Make a GraphQL request to a URL.",JAVASCRIPT:"Run JavaScript code in the browser or a Node.js environment.",DRAG:"Click and drag an element to another location.",VISUAL_DIFF:"Compare a screenshot of the page or a specific element to a baseline image.",MOUSE_DRAG:"Click and drag the mouse by a specified distance.",AUTH_LOAD:"Load or clear session state using a JavaScript object including cookies, localStorage, and IndexDB entries.",AUTH_SAVE:"Save authentication state (cookies, localStorage) into a JavaScript object.",ELEMENT_CHECK:"Assert on an element's state using pre-built conditions, including content, visibility, attribute value checks.",PAGE_CHECK:"Assert on the active page's contents using pre-built conditions.",WAIT_FOR_URL:"Wait for the active page's URL to match a target value or pattern.",COPY:"Copy the specified value to the browser clipboard.",PASTE:"Paste the browser clipboard contents.",REGISTER_REQUEST_LISTENER:"Register a listener for network requests.",AWAIT_LISTENER:"Wait for a listener to fire, and return the response data.",RECORD_REQUESTS:"Record network requests that match a given pattern.",GET_RECORDED_REQUESTS:"Get recorded requests that matched the pattern.",SET_HEADER:"Set a header.",MOCK_ROUTE:"Mock network requests to a specific URL.",REMOVE_ROUTE_MOCK:"Remove a previously set route mock.",OFFLINE_MODE:"Configure offline mode.",SUCCESS:"Indicate the entire AI action has succeeded, optionally based on a condition."},pj={AI_CHECK:"AI check",TAP:"Tap",TYPE:"Type",PRESS:"Press button",PRESS_KEYBOARD:"Press keyboard",OPEN_APP:"Open app",JAVASCRIPT:"JavaScript",OPEN_NOTIFICATION_DRAWER:"Open notification drawer",ADB:"ADB command",STATE:"Debug state",RESOLVED_MOBILE_MODULE:"Module"},mj={AI_CHECK:"Ask AI to verify whether something is true on the screen.",TAP:"Tap on an element on the screen.",TYPE:"Type the specified text into an element.",PRESS:"Press a physical button on the device.",PRESS_KEYBOARD:"Press a special key on the keyboard.",OPEN_APP:"Open an app on the device.",JAVASCRIPT:"Execute JavaScript code in a NodeJS context.",OPEN_NOTIFICATION_DRAWER:"Open the notification drawer.",ADB:"Execute an ADB command on the device.",STATE:"Get the debug state of the device.",RESOLVED_MOBILE_MODULE:"A list of steps that can be reused in multiple tests."};import fx from"semver";import{z as Sx}from"zod";var Sj=Sx.string().refine(r=>fx.valid(r),{message:"must be a valid semver string"});import{Faker as bj,en as Tj}from"@faker-js/faker";import{z as O}from"zod";var Aj=O.object({body:O.string(),to:O.string(),from:O.string()}),Rj=O.object({from:O.string().optional(),to:O.string(),timeout:O.number().optional(),beforeDate:O.string().pipe(O.coerce.date()).or(O.date()).optional(),afterDate:O.string().pipe(O.coerce.date()).or(O.date()).optional()}),wj=O.object({to:O.string().email(),from:O.string(),subject:O.string(),body:O.string(),html:O.string().optional()}),Cj=O.object({inbox:O.string().transform(r=>r.toLowerCase()),afterDate:O.string().pipe(O.coerce.date()).or(O.date()).optional(),timeout:O.number().optional(),trimWhitespace:O.boolean().optional()}),xj=O.object({inbox:O.string(),limit:O.number().optional(),afterDate:O.string().pipe(O.coerce.date()).or(O.date()).optional(),trimWhitespace:O.boolean().optional()});var ns=(t=>(t.RAW="RAW",t.RESPONSE="RESPONSE",t))(ns||{}),oh=O.object({body:O.string().nullish(),status:O.number().optional(),headers:O.array(O.tuple([O.string(),O.string()])).optional()}),yx=O.object({url:O.string(),options:O.object({method:O.string(),body:O.string().nullish(),headers:O.array(O.tuple([O.string(),O.string()])).optional()}).optional()}).optional(),Ex=O.object({body:O.string().nullish(),options:O.object({status:O.number(),statusText:O.string().optional(),headers:O.array(O.tuple([O.string(),O.string()])).optional()}).optional()}).optional(),ih=O.object({result:O.unknown(),variableUpdates:O.record(O.string(),O.unknown()).optional(),persistentVariableUpdates:O.record(O.string(),O.unknown()).optional(),error:O.string().optional(),success:O.boolean()}),_j=O.object({id:O.string().optional(),orgId:O.string(),momenticLambdaAuthHash:O.string(),code:O.string(),fragment:O.boolean(),state:O.object({env:O.record(O.string(),O.unknown()),request:yx,response:Ex,additionalBindings:O.record(O.string(),O.unknown()).optional()}),timeoutMs:O.number().optional(),disallowVariableUpdates:O.boolean().optional(),responseSerialization:O.nativeEnum(ns).optional()}),Hr=15e3;import*as lt from"zod";import{extendZodWithOpenApi as bx}from"zod-openapi";bx(lt);var Tx=lt.object({url:lt.string(),lineNumber:lt.number(),columnNumber:lt.number()}).openapi({ref:"CodeLocation"}),os=lt.object({timestamp:lt.number(),text:lt.string(),type:lt.string(),tabIndex:lt.number(),args:lt.unknown().array().optional(),url:lt.string().optional(),location:Tx.optional()}).openapi({ref:"ConsoleLog"}),ah=os.array(),vx=ah.array();import*as su from"zod";import{extendZodWithOpenApi as Hx}from"zod-openapi";import{z as C}from"zod";var Ax=C.object({name:C.string(),version:C.string(),comment:C.string().optional()}),Rx=C.object({name:C.string(),version:C.string(),comment:C.string().optional()}),wx=C.object({onContentLoad:C.number().optional(),onLoad:C.number().optional(),comment:C.string().optional()}),lh=C.object({startedDateTime:C.string(),id:C.string(),title:C.string().optional(),pageTimings:wx,comment:C.string().optional()}),Cx=C.array(lh),xx=C.object({name:C.string(),value:C.string(),path:C.string().optional(),domain:C.string().optional(),expires:C.string().optional(),httpOnly:C.boolean().optional(),secure:C.boolean().optional(),comment:C.string().optional()}),ch=C.array(xx),_x=C.object({name:C.string(),value:C.string(),comment:C.string().optional()}),uh=C.array(_x),Mx=C.object({name:C.string(),value:C.string(),comment:C.string().optional()}),Ix=C.array(Mx),Px=C.object({name:C.string(),value:C.string().optional(),fileName:C.string().optional(),contentType:C.string().optional(),comment:C.string().optional()}),Ox=C.array(Px),Lx=C.object({mimeType:C.string(),params:Ox,text:C.string(),comment:C.string().optional()}),Nx=C.object({method:C.string(),url:C.string(),httpVersion:C.string().optional(),cookies:ch,headers:uh,queryString:Ix,postData:Lx.optional(),headersSize:C.number().optional(),bodySize:C.number().optional(),comment:C.string().optional()}),Dx=C.object({size:C.number().optional(),compression:C.number().optional(),mimeType:C.string().optional(),text:C.string().optional(),encoding:C.string().optional(),comment:C.string().optional()}),kx=C.object({status:C.number(),statusText:C.string(),httpVersion:C.string().optional(),cookies:ch,headers:uh,content:Dx,redirectURL:C.string().optional(),headersSize:C.number().optional(),bodySize:C.number().optional(),comment:C.string().optional(),_mocked:C.boolean().optional()}),sh=C.object({expires:C.string().optional(),lastAccess:C.string(),eTag:C.string(),hitCount:C.number(),comment:C.string().optional()}),Ux=C.object({beforeRequest:sh.optional(),afterRequest:sh.optional(),comment:C.string().optional()}),Fx=C.object({blocked:C.number().optional(),dns:C.number().optional(),connect:C.number().optional(),send:C.number(),wait:C.number(),receive:C.number(),ssl:C.number().optional(),comment:C.string().optional()}),dh=C.object({pageref:C.string().optional(),startedDateTime:C.string(),time:C.number().optional(),request:Nx,response:kx.optional(),cache:Ux.optional(),timings:Fx,serverIPAddress:C.string().optional(),connection:C.string().optional(),comment:C.string().optional(),_resourceType:C.string().optional()}),Bx=C.array(dh),zx=C.object({version:C.string().default("1.1"),creator:Ax.optional(),browser:Rx.optional(),pages:Cx.optional(),entries:Bx,comment:C.string().optional()}),Gx=C.object({log:zx}),ph=C.record(C.string(),lh),mh=C.record(C.string(),dh);Hx(su);var Vx=su.object({logsPerPage:os.array().array(),harPages:ph.optional(),harEntries:mh.optional()}).openapi({ref:"DebugData"});var w=class extends Error{reason;constructor(e,t,n){let o=!1;for(let i of Object.values(ge))if(t.startsWith(i)){o=!0,e=i;break}if(n?.errOptions?.cause)super(o?t:`${e}: ${t}`,n?.errOptions);else{let i=o?t:`${e}${t?`: ${t}`:""}`;super(i,n?.errOptions)}this.name="TestFailureError",this.stack=this.stack?.slice(this.name.length+2),this.reason=e}toString(){return this.message}toJSON(){return{message:this.message}}},go=class extends Error{updatedLocatorMemory;constructor(e,t,n={}){super(e,n),this.updatedLocatorMemory=t,this.name="NoElementsFoundUsingAIError"}},Vr=class extends Error{decisions;constructor(e,t,n={}){super(e,n),this.decisions=t,this.name="NoElementsFoundUsingCacheError"}toString(){return`${this.message}
3
3
  Decisions:
4
4
  ${this.decisions.map(e=>e.toString()).join(`
5
- `)}`}};function Gg(r){return r instanceof Error?r.message.includes("Timeout")&&r.message.includes("exceeded")&&r.message.includes("waiting for locator"):!1}function Bc(r){return!(r instanceof Error)||r.message.includes("locator resolved to visible")?!1:!!(r.message.includes("Timeout")&&r.message.includes("exceeded")&&r.message.includes("body >")||r.message.includes("Element is not attached to the DOM"))}var Zt=class extends Error{retryableWithAI;constructor(e,t,n={}){super(e,n),this.name="CacheAttributesDisqualifyElementError",this.retryableWithAI=t}},Ba=class extends Zt{constructor(e,t={}){super(e,!0,t),this.name="BoundingBoxMovedError"}},za=class extends Zt{constructor(e,t={}){super(e,!1,t),this.name="ZeroOpacityError"}};function zc(r){return r instanceof Error?r.message.includes("Could not find attribute data-momentic-id for object"):!1}function Gc(r){return r instanceof Error?r.message.includes("Timeout")&&r.message.includes("exceeded")&&r.message.includes("waiting for locator")&&r.message.includes("data-momentic-id")&&!r.message.includes("locator resolved")&&!r.message.includes("waiting for element to be"):!1}function Hc(r){return r instanceof Error?r.message.includes("Protocol error (DOM.resolveNode): No node with given id found")||r.message.includes("Could not resolve backend node"):!1}var hi=class extends Error{constructor(e,t={}){super(e,t),this.name="InsufficientCacheDataError"}};import{cloneDeep as zC}from"lodash-es";import{z as er}from"zod";var Ha=(g=>(g.DisableClickhouseCaches="disable_clickhouse_caches",g.DisableClickHouseLastUpdatedEndpoint="disable_clickhouse_last_updated_endpoint",g.IconKnowledgeBase="icon_knowledge_base",g.MiniModelInitialAssertion="mini_model_initial_assertion",g.MiniModelInitialLocator="mini_model_initial_locator",g.ShowTestPlans="show_test_plans",g.AiPageSummary="ai_page_summary",g.ShowZeroOpacityElements="show_zero_opacity_elements",g.VisualActions="visual_actions",g.RagV2="rag_v2",g.DisableSecondaryCacheResolution="disable_secondary_cache_resolution",g.GlobalLocatorRedirect="global_locator_redirect",g.FakerConstantSeed="faker_constant_seed",g.AutoExpandIframes="auto_expand_iframes",g))(Ha||{});var Hg=er.union([er.string(),er.number(),er.boolean(),er.null(),er.record(er.string(),er.lazy(()=>Hg)),er.array(er.lazy(()=>Hg))]),Ga=class{flags;payloads;constructor(e,t){this.flags=e,this.payloads=t}isBooleanFlagEnabled(e){return process.env&&process.env[`MOMENTIC_FLAG_OVERRIDE_${e.toUpperCase()}`]==="true"?!0:process.env&&process.env[`MOMENTIC_FLAG_OVERRIDE_${e.toUpperCase()}`]==="false"?!1:this.flags[e]===!0}getAllFlags(){let e=zC(this.flags);return Object.entries(e).forEach(([t,n])=>{typeof n=="boolean"&&Object.values(Ha).includes(t)&&(e[t]=this.isBooleanFlagEnabled(t))}),e}getFlagPayload(e){let t=this.payloads[e];if(t!==void 0){if(typeof t=="string")try{return JSON.parse(t)}catch{return t}return t}}refresh(){throw new Error("Not implemented")}},Vc=new Ga({},{});var jc={".123":"application/vnd.lotus-1-2-3",".3dml":"text/vnd.in3d.3dml",".3g2":"video/3gpp2",".3gp":"video/3gpp",".a":"application/octet-stream",".aab":"application/x-authorware-bin",".aac":"audio/x-aac",".aam":"application/x-authorware-map",".aas":"application/x-authorware-seg",".abw":"application/x-abiword",".acc":"application/vnd.americandynamics.acc",".ace":"application/x-ace-compressed",".acu":"application/vnd.acucobol",".acutc":"application/vnd.acucorp",".adp":"audio/adpcm",".aep":"application/vnd.audiograph",".afm":"application/x-font-type1",".afp":"application/vnd.ibm.modcap",".ai":"application/postscript",".aif":"audio/x-aiff",".aifc":"audio/x-aiff",".aiff":"audio/x-aiff",".air":"application/vnd.adobe.air-application-installer-package+zip",".ami":"application/vnd.amiga.ami",".apk":"application/vnd.android.package-archive",".application":"application/x-ms-application",".apr":"application/vnd.lotus-approach",".asc":"application/pgp-signature",".asf":"video/x-ms-asf",".asm":"text/x-asm",".aso":"application/vnd.accpac.simply.aso",".asx":"video/x-ms-asf",".atc":"application/vnd.acucorp",".atom":"application/atom+xml",".atomcat":"application/atomcat+xml",".atomsvc":"application/atomsvc+xml",".atx":"application/vnd.antix.game-component",".au":"audio/basic",".avi":"video/x-msvideo",".aw":"application/applixware",".azf":"application/vnd.airzip.filesecure.azf",".azs":"application/vnd.airzip.filesecure.azs",".azw":"application/vnd.amazon.ebook",".bat":"application/x-msdownload",".bcpio":"application/x-bcpio",".bdf":"application/x-font-bdf",".bdm":"application/vnd.syncml.dm+wbxml",".bh2":"application/vnd.fujitsu.oasysprs",".bin":"application/octet-stream",".bmi":"application/vnd.bmi",".bmp":"image/bmp",".book":"application/vnd.framemaker",".box":"application/vnd.previewsystems.box",".boz":"application/x-bzip2",".bpk":"application/octet-stream",".btif":"image/prs.btif",".bz":"application/x-bzip",".bz2":"application/x-bzip2",".c":"text/x-c",".c4d":"application/vnd.clonk.c4group",".c4f":"application/vnd.clonk.c4group",".c4g":"application/vnd.clonk.c4group",".c4p":"application/vnd.clonk.c4group",".c4u":"application/vnd.clonk.c4group",".cab":"application/vnd.ms-cab-compressed",".car":"application/vnd.curl.car",".cat":"application/vnd.ms-pki.seccat",".cc":"text/x-c",".cct":"application/x-director",".ccxml":"application/ccxml+xml",".cdbcmsg":"application/vnd.contact.cmsg",".cdf":"application/x-netcdf",".cdkey":"application/vnd.mediastation.cdkey",".cdx":"chemical/x-cdx",".cdxml":"application/vnd.chemdraw+xml",".cdy":"application/vnd.cinderella",".cer":"application/pkix-cert",".cgm":"image/cgm",".chat":"application/x-chat",".chm":"application/vnd.ms-htmlhelp",".chrt":"application/vnd.kde.kchart",".cif":"chemical/x-cif",".cii":"application/vnd.anser-web-certificate-issue-initiation",".cil":"application/vnd.ms-artgalry",".cla":"application/vnd.claymore",".class":"application/java-vm",".clkk":"application/vnd.crick.clicker.keyboard",".clkp":"application/vnd.crick.clicker.palette",".clkt":"application/vnd.crick.clicker.template",".clkw":"application/vnd.crick.clicker.wordbank",".clkx":"application/vnd.crick.clicker",".clp":"application/x-msclip",".cmc":"application/vnd.cosmocaller",".cmdf":"chemical/x-cmdf",".cml":"chemical/x-cml",".cmp":"application/vnd.yellowriver-custom-menu",".cmx":"image/x-cmx",".cod":"application/vnd.rim.cod",".com":"application/x-msdownload",".conf":"text/plain",".cpio":"application/x-cpio",".cpp":"text/x-c",".cpt":"application/mac-compactpro",".crd":"application/x-mscardfile",".crl":"application/pkix-crl",".crt":"application/x-x509-ca-cert",".csh":"application/x-csh",".csml":"chemical/x-csml",".csp":"application/vnd.commonspace",".css":"text/css",".cst":"application/x-director",".csv":"text/csv",".cu":"application/cu-seeme",".curl":"text/vnd.curl",".cww":"application/prs.cww",".cxt":"application/x-director",".cxx":"text/x-c",".daf":"application/vnd.mobius.daf",".dataless":"application/vnd.fdsn.seed",".davmount":"application/davmount+xml",".dcr":"application/x-director",".dcurl":"text/vnd.curl.dcurl",".dd2":"application/vnd.oma.dd2+xml",".ddd":"application/vnd.fujixerox.ddd",".deb":"application/x-debian-package",".def":"text/plain",".deploy":"application/octet-stream",".der":"application/x-x509-ca-cert",".dfac":"application/vnd.dreamfactory",".dic":"text/x-c",".diff":"text/plain",".dir":"application/x-director",".dis":"application/vnd.mobius.dis",".dist":"application/octet-stream",".distz":"application/octet-stream",".djv":"image/vnd.djvu",".djvu":"image/vnd.djvu",".dll":"application/x-msdownload",".dmg":"application/octet-stream",".dms":"application/octet-stream",".dna":"application/vnd.dna",".doc":"application/msword",".docm":"application/vnd.ms-word.document.macroenabled.12",".docx":"application/vnd.openxmlformats-officedocument.wordprocessingml.document",".dot":"application/msword",".dotm":"application/vnd.ms-word.template.macroenabled.12",".dotx":"application/vnd.openxmlformats-officedocument.wordprocessingml.template",".dp":"application/vnd.osgi.dp",".dpg":"application/vnd.dpgraph",".dsc":"text/prs.lines.tag",".dtb":"application/x-dtbook+xml",".dtd":"application/xml-dtd",".dts":"audio/vnd.dts",".dtshd":"audio/vnd.dts.hd",".dump":"application/octet-stream",".dvi":"application/x-dvi",".dwf":"model/vnd.dwf",".dwg":"image/vnd.dwg",".dxf":"image/vnd.dxf",".dxp":"application/vnd.spotfire.dxp",".dxr":"application/x-director",".ecelp4800":"audio/vnd.nuera.ecelp4800",".ecelp7470":"audio/vnd.nuera.ecelp7470",".ecelp9600":"audio/vnd.nuera.ecelp9600",".ecma":"application/ecmascript",".edm":"application/vnd.novadigm.edm",".edx":"application/vnd.novadigm.edx",".efif":"application/vnd.picsel",".ei6":"application/vnd.pg.osasli",".elc":"application/octet-stream",".eml":"message/rfc822",".emma":"application/emma+xml",".eol":"audio/vnd.digital-winds",".eot":"application/vnd.ms-fontobject",".eps":"application/postscript",".epub":"application/epub+zip",".es3":"application/vnd.eszigno3+xml",".esf":"application/vnd.epson.esf",".et3":"application/vnd.eszigno3+xml",".etx":"text/x-setext",".exe":"application/x-msdownload",".ext":"application/vnd.novadigm.ext",".ez":"application/andrew-inset",".ez2":"application/vnd.ezpix-album",".ez3":"application/vnd.ezpix-package",".f":"text/x-fortran",".f4v":"video/x-f4v",".f77":"text/x-fortran",".f90":"text/x-fortran",".fbs":"image/vnd.fastbidsheet",".fdf":"application/vnd.fdf",".fe_launch":"application/vnd.denovo.fcselayout-link",".fg5":"application/vnd.fujitsu.oasysgp",".fgd":"application/x-director",".fh":"image/x-freehand",".fh4":"image/x-freehand",".fh5":"image/x-freehand",".fh7":"image/x-freehand",".fhc":"image/x-freehand",".fig":"application/x-xfig",".fli":"video/x-fli",".flo":"application/vnd.micrografx.flo",".flv":"video/x-flv",".flw":"application/vnd.kde.kivio",".flx":"text/vnd.fmi.flexstor",".fly":"text/vnd.fly",".fm":"application/vnd.framemaker",".fnc":"application/vnd.frogans.fnc",".for":"text/x-fortran",".fpx":"image/vnd.fpx",".frame":"application/vnd.framemaker",".fsc":"application/vnd.fsc.weblaunch",".fst":"image/vnd.fst",".ftc":"application/vnd.fluxtime.clip",".fti":"application/vnd.anser-web-funds-transfer-initiation",".fvt":"video/vnd.fvt",".fzs":"application/vnd.fuzzysheet",".g3":"image/g3fax",".gac":"application/vnd.groove-account",".gdl":"model/vnd.gdl",".geo":"application/vnd.dynageo",".gex":"application/vnd.geometry-explorer",".ggb":"application/vnd.geogebra.file",".ggt":"application/vnd.geogebra.tool",".ghf":"application/vnd.groove-help",".gif":"image/gif",".gim":"application/vnd.groove-identity-message",".gmx":"application/vnd.gmx",".gnumeric":"application/x-gnumeric",".gph":"application/vnd.flographit",".gqf":"application/vnd.grafeq",".gqs":"application/vnd.grafeq",".gram":"application/srgs",".gre":"application/vnd.geometry-explorer",".grv":"application/vnd.groove-injector",".grxml":"application/srgs+xml",".gsf":"application/x-font-ghostscript",".gtar":"application/x-gtar",".gtm":"application/vnd.groove-tool-message",".gtw":"model/vnd.gtw",".gv":"text/vnd.graphviz",".gz":"application/x-gzip",".h":"text/x-c",".h261":"video/h261",".h263":"video/h263",".h264":"video/h264",".hbci":"application/vnd.hbci",".hdf":"application/x-hdf",".hh":"text/x-c",".hlp":"application/winhlp",".hpgl":"application/vnd.hp-hpgl",".hpid":"application/vnd.hp-hpid",".hps":"application/vnd.hp-hps",".hqx":"application/mac-binhex40",".htke":"application/vnd.kenameaapp",".htm":"text/html",".html":"text/html",".hvd":"application/vnd.yamaha.hv-dic",".hvp":"application/vnd.yamaha.hv-voice",".hvs":"application/vnd.yamaha.hv-script",".icc":"application/vnd.iccprofile",".ice":"x-conference/x-cooltalk",".icm":"application/vnd.iccprofile",".ico":"image/x-icon",".ics":"text/calendar",".ief":"image/ief",".ifb":"text/calendar",".ifm":"application/vnd.shana.informed.formdata",".iges":"model/iges",".igl":"application/vnd.igloader",".igs":"model/iges",".igx":"application/vnd.micrografx.igx",".iif":"application/vnd.shana.informed.interchange",".imp":"application/vnd.accpac.simply.imp",".ims":"application/vnd.ms-ims",".in":"text/plain",".ipk":"application/vnd.shana.informed.package",".irm":"application/vnd.ibm.rights-management",".irp":"application/vnd.irepository.package+xml",".iso":"application/octet-stream",".itp":"application/vnd.shana.informed.formtemplate",".ivp":"application/vnd.immervision-ivp",".ivu":"application/vnd.immervision-ivu",".jad":"text/vnd.sun.j2me.app-descriptor",".jam":"application/vnd.jam",".jar":"application/java-archive",".java":"text/x-java-source",".jisp":"application/vnd.jisp",".jlt":"application/vnd.hp-jlyt",".jnlp":"application/x-java-jnlp-file",".joda":"application/vnd.joost.joda-archive",".jpe":"image/jpeg",".jpeg":"image/jpeg",".jpg":"image/jpeg",".jpgm":"video/jpm",".jpgv":"video/jpeg",".jpm":"video/jpm",".js":"application/javascript",".json":"application/json",".kar":"audio/midi",".karbon":"application/vnd.kde.karbon",".kfo":"application/vnd.kde.kformula",".kia":"application/vnd.kidspiration",".kil":"application/x-killustrator",".kml":"application/vnd.google-earth.kml+xml",".kmz":"application/vnd.google-earth.kmz",".kne":"application/vnd.kinar",".knp":"application/vnd.kinar",".kon":"application/vnd.kde.kontour",".kpr":"application/vnd.kde.kpresenter",".kpt":"application/vnd.kde.kpresenter",".ksh":"text/plain",".ksp":"application/vnd.kde.kspread",".ktr":"application/vnd.kahootz",".ktz":"application/vnd.kahootz",".kwd":"application/vnd.kde.kword",".kwt":"application/vnd.kde.kword",".latex":"application/x-latex",".lbd":"application/vnd.llamagraphics.life-balance.desktop",".lbe":"application/vnd.llamagraphics.life-balance.exchange+xml",".les":"application/vnd.hhe.lesson-player",".lha":"application/octet-stream",".link66":"application/vnd.route66.link66+xml",".list":"text/plain",".list3820":"application/vnd.ibm.modcap",".listafp":"application/vnd.ibm.modcap",".log":"text/plain",".lostxml":"application/lost+xml",".lrf":"application/octet-stream",".lrm":"application/vnd.ms-lrm",".ltf":"application/vnd.frogans.ltf",".lvp":"audio/vnd.lucent.voice",".lwp":"application/vnd.lotus-wordpro",".lzh":"application/octet-stream",".m13":"application/x-msmediaview",".m14":"application/x-msmediaview",".m1v":"video/mpeg",".m2a":"audio/mpeg",".m2v":"video/mpeg",".m3a":"audio/mpeg",".m3u":"audio/x-mpegurl",".m4u":"video/vnd.mpegurl",".m4v":"video/x-m4v",".ma":"application/mathematica",".mag":"application/vnd.ecowin.chart",".maker":"application/vnd.framemaker",".man":"text/troff",".mathml":"application/mathml+xml",".mb":"application/mathematica",".mbk":"application/vnd.mobius.mbk",".mbox":"application/mbox",".mc1":"application/vnd.medcalcdata",".mcd":"application/vnd.mcd",".mcurl":"text/vnd.curl.mcurl",".mdb":"application/x-msaccess",".mdi":"image/vnd.ms-modi",".me":"text/troff",".mesh":"model/mesh",".mfm":"application/vnd.mfmp",".mgz":"application/vnd.proteus.magazine",".mht":"message/rfc822",".mhtml":"message/rfc822",".mid":"audio/midi",".midi":"audio/midi",".mif":"application/vnd.mif",".mime":"message/rfc822",".mj2":"video/mj2",".mjp2":"video/mj2",".mkv":"video/x-matroska",".mlp":"application/vnd.dolby.mlp",".mmd":"application/vnd.chipnuts.karaoke-mmd",".mmf":"application/vnd.smaf",".mmr":"image/vnd.fujixerox.edmics-mmr",".mny":"application/x-msmoney",".mobi":"application/x-mobipocket-ebook",".mov":"video/quicktime",".movie":"video/x-sgi-movie",".mp2":"audio/mpeg",".mp2a":"audio/mpeg",".mp3":"audio/mpeg",".mp4":"video/mp4",".mp4a":"audio/mp4",".mp4s":"application/mp4",".mp4v":"video/mp4",".mpa":"video/mpeg",".mpc":"application/vnd.mophun.certificate",".mpe":"video/mpeg",".mpeg":"video/mpeg",".mpg":"video/mpeg",".mpg4":"video/mp4",".mpga":"audio/mpeg",".mpkg":"application/vnd.apple.installer+xml",".mpm":"application/vnd.blueice.multipass",".mpn":"application/vnd.mophun.application",".mpp":"application/vnd.ms-project",".mpt":"application/vnd.ms-project",".mpy":"application/vnd.ibm.minipay",".mqy":"application/vnd.mobius.mqy",".mrc":"application/marc",".ms":"text/troff",".mscml":"application/mediaservercontrol+xml",".mseed":"application/vnd.fdsn.mseed",".mseq":"application/vnd.mseq",".msf":"application/vnd.epson.msf",".msh":"model/mesh",".msi":"application/x-msdownload",".msl":"application/vnd.mobius.msl",".msty":"application/vnd.muvee.style",".mts":"model/vnd.mts",".mus":"application/vnd.musician",".musicxml":"application/vnd.recordare.musicxml+xml",".mvb":"application/x-msmediaview",".mwf":"application/vnd.mfer",".mxf":"application/mxf",".mxl":"application/vnd.recordare.musicxml",".mxml":"application/xv+xml",".mxs":"application/vnd.triscape.mxs",".mxu":"video/vnd.mpegurl",".n-gage":"application/vnd.nokia.n-gage.symbian.install",".nb":"application/mathematica",".nc":"application/x-netcdf",".ncx":"application/x-dtbncx+xml",".ngdat":"application/vnd.nokia.n-gage.data",".nlu":"application/vnd.neurolanguage.nlu",".nml":"application/vnd.enliven",".nnd":"application/vnd.noblenet-directory",".nns":"application/vnd.noblenet-sealer",".nnw":"application/vnd.noblenet-web",".npx":"image/vnd.net-fpx",".nsf":"application/vnd.lotus-notes",".nws":"message/rfc822",".o":"application/octet-stream",".oa2":"application/vnd.fujitsu.oasys2",".oa3":"application/vnd.fujitsu.oasys3",".oas":"application/vnd.fujitsu.oasys",".obd":"application/x-msbinder",".obj":"application/octet-stream",".oda":"application/oda",".odb":"application/vnd.oasis.opendocument.database",".odc":"application/vnd.oasis.opendocument.chart",".odf":"application/vnd.oasis.opendocument.formula",".odft":"application/vnd.oasis.opendocument.formula-template",".odg":"application/vnd.oasis.opendocument.graphics",".odi":"application/vnd.oasis.opendocument.image",".odp":"application/vnd.oasis.opendocument.presentation",".ods":"application/vnd.oasis.opendocument.spreadsheet",".odt":"application/vnd.oasis.opendocument.text",".oga":"audio/ogg",".ogg":"audio/ogg",".ogv":"video/ogg",".ogx":"application/ogg",".onepkg":"application/onenote",".onetmp":"application/onenote",".onetoc":"application/onenote",".onetoc2":"application/onenote",".opf":"application/oebps-package+xml",".oprc":"application/vnd.palm",".org":"application/vnd.lotus-organizer",".osf":"application/vnd.yamaha.openscoreformat",".osfpvg":"application/vnd.yamaha.openscoreformat.osfpvg+xml",".otc":"application/vnd.oasis.opendocument.chart-template",".otf":"application/x-font-otf",".otg":"application/vnd.oasis.opendocument.graphics-template",".oth":"application/vnd.oasis.opendocument.text-web",".oti":"application/vnd.oasis.opendocument.image-template",".otm":"application/vnd.oasis.opendocument.text-master",".otp":"application/vnd.oasis.opendocument.presentation-template",".ots":"application/vnd.oasis.opendocument.spreadsheet-template",".ott":"application/vnd.oasis.opendocument.text-template",".oxt":"application/vnd.openofficeorg.extension",".p":"text/x-pascal",".p10":"application/pkcs10",".p12":"application/x-pkcs12",".p7b":"application/x-pkcs7-certificates",".p7c":"application/pkcs7-mime",".p7m":"application/pkcs7-mime",".p7r":"application/x-pkcs7-certreqresp",".p7s":"application/pkcs7-signature",".pas":"text/x-pascal",".pbd":"application/vnd.powerbuilder6",".pbm":"image/x-portable-bitmap",".pcf":"application/x-font-pcf",".pcl":"application/vnd.hp-pcl",".pclxl":"application/vnd.hp-pclxl",".pct":"image/x-pict",".pcurl":"application/vnd.curl.pcurl",".pcx":"image/x-pcx",".pdb":"application/vnd.palm",".pdf":"application/pdf",".pfa":"application/x-font-type1",".pfb":"application/x-font-type1",".pfm":"application/x-font-type1",".pfr":"application/font-tdpfr",".pfx":"application/x-pkcs12",".pgm":"image/x-portable-graymap",".pgn":"application/x-chess-pgn",".pgp":"application/pgp-encrypted",".pic":"image/x-pict",".pkg":"application/octet-stream",".pki":"application/pkixcmp",".pkipath":"application/pkix-pkipath",".pl":"text/plain",".plb":"application/vnd.3gpp.pic-bw-large",".plc":"application/vnd.mobius.plc",".plf":"application/vnd.pocketlearn",".pls":"application/pls+xml",".pml":"application/vnd.ctc-posml",".png":"image/png",".pnm":"image/x-portable-anymap",".portpkg":"application/vnd.macports.portpkg",".pot":"application/vnd.ms-powerpoint",".potm":"application/vnd.ms-powerpoint.template.macroenabled.12",".potx":"application/vnd.openxmlformats-officedocument.presentationml.template",".ppa":"application/vnd.ms-powerpoint",".ppam":"application/vnd.ms-powerpoint.addin.macroenabled.12",".ppd":"application/vnd.cups-ppd",".ppm":"image/x-portable-pixmap",".pps":"application/vnd.ms-powerpoint",".ppsm":"application/vnd.ms-powerpoint.slideshow.macroenabled.12",".ppsx":"application/vnd.openxmlformats-officedocument.presentationml.slideshow",".ppt":"application/vnd.ms-powerpoint",".pptm":"application/vnd.ms-powerpoint.presentation.macroenabled.12",".pptx":"application/vnd.openxmlformats-officedocument.presentationml.presentation",".pqa":"application/vnd.palm",".prc":"application/x-mobipocket-ebook",".pre":"application/vnd.lotus-freelance",".prf":"application/pics-rules",".ps":"application/postscript",".psb":"application/vnd.3gpp.pic-bw-small",".psd":"image/vnd.adobe.photoshop",".psf":"application/x-font-linux-psf",".ptid":"application/vnd.pvi.ptid1",".pub":"application/x-mspublisher",".pvb":"application/vnd.3gpp.pic-bw-var",".pwn":"application/vnd.3m.post-it-notes",".pwz":"application/vnd.ms-powerpoint",".py":"text/x-python",".pya":"audio/vnd.ms-playready.media.pya",".pyc":"application/x-python-code",".pyo":"application/x-python-code",".pyv":"video/vnd.ms-playready.media.pyv",".qam":"application/vnd.epson.quickanime",".qbo":"application/vnd.intu.qbo",".qfx":"application/vnd.intu.qfx",".qps":"application/vnd.publishare-delta-tree",".qt":"video/quicktime",".qwd":"application/vnd.quark.quarkxpress",".qwt":"application/vnd.quark.quarkxpress",".qxb":"application/vnd.quark.quarkxpress",".qxd":"application/vnd.quark.quarkxpress",".qxl":"application/vnd.quark.quarkxpress",".qxt":"application/vnd.quark.quarkxpress",".ra":"audio/x-pn-realaudio",".ram":"audio/x-pn-realaudio",".rar":"application/x-rar-compressed",".ras":"image/x-cmu-raster",".rcprofile":"application/vnd.ipunplugged.rcprofile",".rdf":"application/rdf+xml",".rdz":"application/vnd.data-vision.rdz",".rep":"application/vnd.businessobjects",".res":"application/x-dtbresource+xml",".rgb":"image/x-rgb",".rif":"application/reginfo+xml",".rl":"application/resource-lists+xml",".rlc":"image/vnd.fujixerox.edmics-rlc",".rld":"application/resource-lists-diff+xml",".rm":"application/vnd.rn-realmedia",".rmi":"audio/midi",".rmp":"audio/x-pn-realaudio-plugin",".rms":"application/vnd.jcp.javame.midlet-rms",".rnc":"application/relax-ng-compact-syntax",".roff":"text/troff",".rpm":"application/x-rpm",".rpss":"application/vnd.nokia.radio-presets",".rpst":"application/vnd.nokia.radio-preset",".rq":"application/sparql-query",".rs":"application/rls-services+xml",".rsd":"application/rsd+xml",".rss":"application/rss+xml",".rtf":"application/rtf",".rtx":"text/richtext",".s":"text/x-asm",".saf":"application/vnd.yamaha.smaf-audio",".sbml":"application/sbml+xml",".sc":"application/vnd.ibm.secure-container",".scd":"application/x-msschedule",".scm":"application/vnd.lotus-screencam",".scq":"application/scvp-cv-request",".scs":"application/scvp-cv-response",".scurl":"text/vnd.curl.scurl",".sda":"application/vnd.stardivision.draw",".sdc":"application/vnd.stardivision.calc",".sdd":"application/vnd.stardivision.impress",".sdkd":"application/vnd.solent.sdkm+xml",".sdkm":"application/vnd.solent.sdkm+xml",".sdp":"application/sdp",".sdw":"application/vnd.stardivision.writer",".see":"application/vnd.seemail",".seed":"application/vnd.fdsn.seed",".sema":"application/vnd.sema",".semd":"application/vnd.semd",".semf":"application/vnd.semf",".ser":"application/java-serialized-object",".setpay":"application/set-payment-initiation",".setreg":"application/set-registration-initiation",".sfd-hdstx":"application/vnd.hydrostatix.sof-data",".sfs":"application/vnd.spotfire.sfs",".sgl":"application/vnd.stardivision.writer-global",".sgm":"text/sgml",".sgml":"text/sgml",".sh":"application/x-sh",".shar":"application/x-shar",".shf":"application/shf+xml",".si":"text/vnd.wap.si",".sic":"application/vnd.wap.sic",".sig":"application/pgp-signature",".silo":"model/mesh",".sis":"application/vnd.symbian.install",".sisx":"application/vnd.symbian.install",".sit":"application/x-stuffit",".sitx":"application/x-stuffitx",".skd":"application/vnd.koan",".skm":"application/vnd.koan",".skp":"application/vnd.koan",".skt":"application/vnd.koan",".sl":"text/vnd.wap.sl",".slc":"application/vnd.wap.slc",".sldm":"application/vnd.ms-powerpoint.slide.macroenabled.12",".sldx":"application/vnd.openxmlformats-officedocument.presentationml.slide",".slt":"application/vnd.epson.salt",".smf":"application/vnd.stardivision.math",".smi":"application/smil+xml",".smil":"application/smil+xml",".snd":"audio/basic",".snf":"application/x-font-snf",".so":"application/octet-stream",".spc":"application/x-pkcs7-certificates",".spf":"application/vnd.yamaha.smaf-phrase",".spl":"application/x-futuresplash",".spot":"text/vnd.in3d.spot",".spp":"application/scvp-vp-response",".spq":"application/scvp-vp-request",".spx":"audio/ogg",".src":"application/x-wais-source",".srx":"application/sparql-results+xml",".sse":"application/vnd.kodak-descriptor",".ssf":"application/vnd.epson.ssf",".ssml":"application/ssml+xml",".stc":"application/vnd.sun.xml.calc.template",".std":"application/vnd.sun.xml.draw.template",".stf":"application/vnd.wt.stf",".sti":"application/vnd.sun.xml.impress.template",".stk":"application/hyperstudio",".stl":"application/vnd.ms-pki.stl",".str":"application/vnd.pg.format",".stw":"application/vnd.sun.xml.writer.template",".sus":"application/vnd.sus-calendar",".susp":"application/vnd.sus-calendar",".sv4cpio":"application/x-sv4cpio",".sv4crc":"application/x-sv4crc",".svd":"application/vnd.svd",".svg":"image/svg+xml",".svgz":"image/svg+xml",".swa":"application/x-director",".swf":"application/x-shockwave-flash",".swi":"application/vnd.arastra.swi",".sxc":"application/vnd.sun.xml.calc",".sxd":"application/vnd.sun.xml.draw",".sxg":"application/vnd.sun.xml.writer.global",".sxi":"application/vnd.sun.xml.impress",".sxm":"application/vnd.sun.xml.math",".sxw":"application/vnd.sun.xml.writer",".t":"text/troff",".tao":"application/vnd.tao.intent-module-archive",".tar":"application/x-tar",".tcap":"application/vnd.3gpp2.tcap",".tcl":"application/x-tcl",".teacher":"application/vnd.smart.teacher",".tex":"application/x-tex",".texi":"application/x-texinfo",".texinfo":"application/x-texinfo",".text":"text/plain",".tfm":"application/x-tex-tfm",".tgz":"application/x-gzip",".tif":"image/tiff",".tiff":"image/tiff",".tmo":"application/vnd.tmobile-livetv",".torrent":"application/x-bittorrent",".tpl":"application/vnd.groove-tool-template",".tpt":"application/vnd.trid.tpt",".tr":"text/troff",".tra":"application/vnd.trueapp",".trm":"application/x-msterminal",".tsv":"text/tab-separated-values",".ttc":"application/x-font-ttf",".ttf":"application/x-font-ttf",".twd":"application/vnd.simtech-mindmapper",".twds":"application/vnd.simtech-mindmapper",".txd":"application/vnd.genomatix.tuxedo",".txf":"application/vnd.mobius.txf",".txt":"text/plain",".u32":"application/x-authorware-bin",".udeb":"application/x-debian-package",".ufd":"application/vnd.ufdl",".ufdl":"application/vnd.ufdl",".umj":"application/vnd.umajin",".unityweb":"application/vnd.unity",".uoml":"application/vnd.uoml+xml",".uri":"text/uri-list",".uris":"text/uri-list",".urls":"text/uri-list",".ustar":"application/x-ustar",".utz":"application/vnd.uiq.theme",".uu":"text/x-uuencode",".vcd":"application/x-cdlink",".vcf":"text/x-vcard",".vcg":"application/vnd.groove-vcard",".vcs":"text/x-vcalendar",".vcx":"application/vnd.vcx",".vis":"application/vnd.visionary",".viv":"video/vnd.vivo",".vor":"application/vnd.stardivision.writer",".vox":"application/x-authorware-bin",".vrml":"model/vrml",".vsd":"application/vnd.visio",".vsf":"application/vnd.vsf",".vss":"application/vnd.visio",".vst":"application/vnd.visio",".vsw":"application/vnd.visio",".vtu":"model/vnd.vtu",".vxml":"application/voicexml+xml",".w3d":"application/x-director",".webm":"video/webm",".wad":"application/x-doom",".wav":"audio/x-wav",".wax":"audio/x-ms-wax",".wbmp":"image/vnd.wap.wbmp",".wbs":"application/vnd.criticaltools.wbs+xml",".wbxml":"application/vnd.wap.wbxml",".wcm":"application/vnd.ms-works",".wdb":"application/vnd.ms-works",".wiz":"application/msword",".wks":"application/vnd.ms-works",".wm":"video/x-ms-wm",".wma":"audio/x-ms-wma",".wmd":"application/x-ms-wmd",".wmf":"application/x-msmetafile",".wml":"text/vnd.wap.wml",".wmlc":"application/vnd.wap.wmlc",".wmls":"text/vnd.wap.wmlscript",".wmlsc":"application/vnd.wap.wmlscriptc",".wmv":"video/x-ms-wmv",".wmx":"video/x-ms-wmx",".wmz":"application/x-ms-wmz",".wpd":"application/vnd.wordperfect",".wpl":"application/vnd.ms-wpl",".wps":"application/vnd.ms-works",".wqd":"application/vnd.wqd",".wri":"application/x-mswrite",".wrl":"model/vrml",".wsdl":"application/wsdl+xml",".wspolicy":"application/wspolicy+xml",".wtb":"application/vnd.webturbo",".wvx":"video/x-ms-wvx",".x32":"application/x-authorware-bin",".x3d":"application/vnd.hzn-3d-crossword",".xap":"application/x-silverlight-app",".xar":"application/vnd.xara",".xbap":"application/x-ms-xbap",".xbd":"application/vnd.fujixerox.docuworks.binder",".xbm":"image/x-xbitmap",".xdm":"application/vnd.syncml.dm+xml",".xdp":"application/vnd.adobe.xdp+xml",".xdw":"application/vnd.fujixerox.docuworks",".xenc":"application/xenc+xml",".xer":"application/patch-ops-error+xml",".xfdf":"application/vnd.adobe.xfdf",".xfdl":"application/vnd.xfdl",".xht":"application/xhtml+xml",".xhtml":"application/xhtml+xml",".xhvml":"application/xv+xml",".xif":"image/vnd.xiff",".xla":"application/vnd.ms-excel",".xlam":"application/vnd.ms-excel.addin.macroenabled.12",".xlb":"application/vnd.ms-excel",".xlc":"application/vnd.ms-excel",".xlm":"application/vnd.ms-excel",".xls":"application/vnd.ms-excel",".xlsb":"application/vnd.ms-excel.sheet.binary.macroenabled.12",".xlsm":"application/vnd.ms-excel.sheet.macroenabled.12",".xlsx":"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",".xlt":"application/vnd.ms-excel",".xltm":"application/vnd.ms-excel.template.macroenabled.12",".xltx":"application/vnd.openxmlformats-officedocument.spreadsheetml.template",".xlw":"application/vnd.ms-excel",".xml":"application/xml",".xo":"application/vnd.olpc-sugar",".xop":"application/xop+xml",".xpdl":"application/xml",".xpi":"application/x-xpinstall",".xpm":"image/x-xpixmap",".xpr":"application/vnd.is-xpr",".xps":"application/vnd.ms-xpsdocument",".xpw":"application/vnd.intercon.formnet",".xpx":"application/vnd.intercon.formnet",".xsl":"application/xml",".xslt":"application/xslt+xml",".xsm":"application/vnd.syncml+xml",".xspf":"application/xspf+xml",".xul":"application/vnd.mozilla.xul+xml",".xvm":"application/xv+xml",".xvml":"application/xv+xml",".xwd":"image/x-xwindowdump",".xyz":"chemical/x-xyz",".zaz":"application/vnd.zzazz.deck+xml",".zip":"application/zip",".zir":"application/vnd.zul",".zirz":"application/vnd.zul",".zmm":"application/vnd.handheld-entertainment+xml"},Vg=[".sh",".exe",".app",".bat",".cmd",".msi",".apk",".jar",".py",".js",".cron",".php",".asp"],$V=Object.keys(jc);import*as jg from"zod";var KV=jg.custom().refine(r=>r&&r.length>0).refine(r=>r&&r[0]instanceof File,{message:"Please upload a valid file."});import{z as Dr}from"zod";var JV=Dr.object({id:Dr.string(),name:Dr.string(),createdAt:Dr.coerce.date(),createdBy:Dr.string(),updatedAt:Dr.coerce.date(),updatedBy:Dr.string().nullable(),organizationId:Dr.string()});import{z as P}from"zod";import kr from"zod";var no=kr.object({platformSep:kr.string(),fullPathSegments:kr.string().array(),relativePathSegments:kr.string().array(),relativePath:kr.string().describe("path relative to the root test directory, i.e. my-folder/my-test.yaml"),fileName:kr.string().describe("base name of the file including the extension, e.g. my-module.module.yaml"),lastModified:kr.coerce.date(),createdAt:kr.coerce.date()});var GC=P.array(no.extend({id:P.string(),name:P.string(),description:P.string().optional(),labels:P.string().array().optional()})),HC=P.array(no.extend({id:P.string(),name:P.string(),description:P.string().optional(),content:ri})),uj=P.object({tests:GC,modules:HC,labels:P.string().array()}),dj=ka.merge(to),mj=P.object({schemaVersion:P.string(),stepLists:jn}),pj=to.partial().merge(jt.pick({id:!0})),VC={name:P.string().min(1).max(255).describe("1-255 chars; Only letters/numbers/dashes. Cannot start/end with '-'. Not '.yaml', 'none', or UUID."),description:P.string().optional(),baseUrl:P.string().url().optional().describe("For LLM: Ask the user for the base URL if they don't provide it."),environment:P.string().optional().describe("For LLM: Do not include the variable unless the user explicitly asks for it and use the environment lookup tool to get the correct one before passing here."),browserType:P.nativeEnum(Mr).optional().describe("For LLM: Never assign this variable unless the user explicitly asks for it."),viewport:Ra.optional().describe("For LLM: Never assign this variable unless the user explicitly asks for it."),pathSegments:P.string().array().optional().describe("For LLM: Only use if explicitly called for by the user. Used to create the test in the correct folder.")},gj=P.object(VC),hj=ka.merge(P.object({relativeFilePath:P.string().describe("relative to project root")})),fj=P.object({name:P.string()}),Sj=P.object({relativeFilePath:P.string()}),Ej=P.object({name:P.string()}),yj=P.object({relativeFilePath:P.string()}),Tj=P.object({name:P.string(),description:P.string(),enabled:P.boolean(),steps:P.lazy(()=>$e.array()),testFilePath:P.string().describe("relative to the project root"),folderPath:P.string().optional().describe("user selected folder path")}),bj=P.object({name:P.string(),description:P.string(),enabled:P.boolean()}).partial();var vj=P.array(Lp),Aj=P.object({defaultEnv:P.string().optional().describe("name of the default env, or undefined to unset")}),wj=P.object({configFilePath:P.string().describe("full path on disk")}),Rj=P.string().array(),Cj=P.object({message:P.string(),newRelativeTestPath:P.string().optional()}),Wc=P.object({name:P.string(),absolutePath:P.string(),relativePath:P.string(),pathSegments:P.array(P.string()),isDirectory:P.boolean(),size:P.number(),createdAt:P.coerce.date(),modifiedAt:P.coerce.date(),accessedAt:P.coerce.date()}),Wg=P.object({pathSegments:P.array(P.string())}),xj=P.object({absolutePath:P.string(),pathSegments:P.array(P.string()),contents:P.array(Wc)}),$g=P.object({pathSegments:P.array(P.string())}),qg=P.object({pathSegments:P.array(P.string()),newPathSegments:P.array(P.string())}),Kg=P.object({pathSegments:P.array(P.string()),recursive:P.boolean().optional()}),_j=P.object({success:P.boolean(),message:P.string(),pathSegments:P.array(P.string()).optional()});var Va=["node_modules","dist","bin",".git",".npm",".next","out",".yarn","__pycache__","build",".env",".venv","venv","env","wheels"],ja=Va.map(r=>`**/${r}/**`),Yg=!0,fi=!1;import tr from"chalk";import jC from"safe-stable-stringify";import WC from"truncate-json";import $C from"zod";var Ur=jC.configure({deterministic:!1});function Xg(r){let e=Ur(r),{jsonString:t}=WC(e,1e4);return t}var qC=["app","version","env","namespace","host"];function de(r){let e=r.bindings()??{},t={};for(let n of Object.keys(e)){let o=e[n];!qC.includes(n)&&typeof o=="string"&&(t[n]=o)}return t}var $a=$C.enum(["debug","info","warn","error"]);var Si={debug:20,info:30,warn:40,error:50},qa={20:"debug",30:"info",40:"warn",50:"error"},$c=class r{minLogLevel;logBindings;constructor(e,t){typeof e=="string"?this.minLogLevel=Si[e]:this.minLogLevel=e,this.logBindings=t}logWithLevel(e,t,...n){try{this.logWithLevelHelper(e,t,...n)}catch(o){console.error(`Failed to log to console: ${o}`)}}logWithLevelHelper(e,t,...n){if(e<this.minLogLevel)return;let o;Array.isArray(n[0])?(o=n[0],n=n.slice(1)):typeof n[0]=="object"&&!(n[0]instanceof Error)&&Object.entries(n[0]).length&&(o={...n[0],...this.logBindings},n=n.slice(1));let i=[];if(i.push(...n),console.log(t(...i)),o&&!Array.isArray(o)){let a=Object.entries(o);for(let[l,c]of a){let s=c;c instanceof Error?(s=c.message,console.log(t(` ${l}:`,s)),console.log(t(" stack:",c.stack))):typeof c=="object"&&(s=Ur(c,void 0,2),s=s.split(`
5
+ `)}`}};function gh(r){return r instanceof Error?r.message.includes("Timeout")&&r.message.includes("exceeded")&&r.message.includes("waiting for locator"):!1}function lu(r){return!(r instanceof Error)||r.message.includes("locator resolved to visible")?!1:!!(r.message.includes("Timeout")&&r.message.includes("exceeded")&&r.message.includes("body >")||r.message.includes("Element is not attached to the DOM"))}var sr=class extends Error{retryableWithAI;constructor(e,t,n={}){super(e,n),this.name="CacheAttributesDisqualifyElementError",this.retryableWithAI=t}},is=class extends sr{constructor(e,t={}){super(e,!0,t),this.name="BoundingBoxMovedError"}},as=class extends sr{constructor(e,t={}){super(e,!1,t),this.name="ZeroOpacityError"}};function cu(r){return r instanceof Error?r.message.includes("Could not find attribute data-momentic-id for object"):!1}function uu(r){return r instanceof Error?r.message.includes("Timeout")&&r.message.includes("exceeded")&&r.message.includes("waiting for locator")&&r.message.includes("data-momentic-id")&&!r.message.includes("locator resolved")&&!r.message.includes("waiting for element to be"):!1}function du(r){return r instanceof Error?r.message.includes("Protocol error (DOM.resolveNode): No node with given id found")||r.message.includes("Could not resolve backend node"):!1}var Mi=class extends Error{constructor(e,t={}){super(e,t),this.name="InsufficientCacheDataError"}};import{cloneDeep as jx}from"lodash-es";import{z as lr}from"zod";var fh=(c=>(c.DisableClickhouseCaches="disable_clickhouse_caches",c.ShowZeroOpacityElements="show_zero_opacity_elements",c.VisualActions="visual_actions",c.RagV2="rag_v2",c.DisableSecondaryCacheResolution="disable_secondary_cache_resolution",c.GlobalLocatorRedirect="global_locator_redirect",c.FakerConstantSeed="faker_constant_seed",c.AutoExpandIframes="auto_expand_iframes",c))(fh||{});var hh=lr.union([lr.string(),lr.number(),lr.boolean(),lr.null(),lr.record(lr.string(),lr.lazy(()=>hh)),lr.array(lr.lazy(()=>hh))]),ss=class{flags;payloads;constructor(e,t){this.flags=e,this.payloads=t}isBooleanFlagEnabled(e){return process.env&&process.env[`MOMENTIC_FLAG_OVERRIDE_${e.toUpperCase()}`]==="true"?!0:process.env&&process.env[`MOMENTIC_FLAG_OVERRIDE_${e.toUpperCase()}`]==="false"?!1:this.flags[e]===!0}getAllFlags(){let e=jx(this.flags);return Object.entries(e).forEach(([t,n])=>{typeof n=="boolean"&&Object.values(fh).includes(t)&&(e[t]=this.isBooleanFlagEnabled(t))}),e}getFlagPayload(e){let t=this.payloads[e];if(t!==void 0){if(typeof t=="string")try{return JSON.parse(t)}catch{return t}return t}}refresh(){throw new Error("Not implemented")}},EW=new ss({},{});var pu={".123":"application/vnd.lotus-1-2-3",".3dml":"text/vnd.in3d.3dml",".3g2":"video/3gpp2",".3gp":"video/3gpp",".a":"application/octet-stream",".aab":"application/x-authorware-bin",".aac":"audio/x-aac",".aam":"application/x-authorware-map",".aas":"application/x-authorware-seg",".abw":"application/x-abiword",".acc":"application/vnd.americandynamics.acc",".ace":"application/x-ace-compressed",".acu":"application/vnd.acucobol",".acutc":"application/vnd.acucorp",".adp":"audio/adpcm",".aep":"application/vnd.audiograph",".afm":"application/x-font-type1",".afp":"application/vnd.ibm.modcap",".ai":"application/postscript",".aif":"audio/x-aiff",".aifc":"audio/x-aiff",".aiff":"audio/x-aiff",".air":"application/vnd.adobe.air-application-installer-package+zip",".ami":"application/vnd.amiga.ami",".apk":"application/vnd.android.package-archive",".application":"application/x-ms-application",".apr":"application/vnd.lotus-approach",".asc":"application/pgp-signature",".asf":"video/x-ms-asf",".asm":"text/x-asm",".aso":"application/vnd.accpac.simply.aso",".asx":"video/x-ms-asf",".atc":"application/vnd.acucorp",".atom":"application/atom+xml",".atomcat":"application/atomcat+xml",".atomsvc":"application/atomsvc+xml",".atx":"application/vnd.antix.game-component",".au":"audio/basic",".avi":"video/x-msvideo",".aw":"application/applixware",".azf":"application/vnd.airzip.filesecure.azf",".azs":"application/vnd.airzip.filesecure.azs",".azw":"application/vnd.amazon.ebook",".bat":"application/x-msdownload",".bcpio":"application/x-bcpio",".bdf":"application/x-font-bdf",".bdm":"application/vnd.syncml.dm+wbxml",".bh2":"application/vnd.fujitsu.oasysprs",".bin":"application/octet-stream",".bmi":"application/vnd.bmi",".bmp":"image/bmp",".book":"application/vnd.framemaker",".box":"application/vnd.previewsystems.box",".boz":"application/x-bzip2",".bpk":"application/octet-stream",".btif":"image/prs.btif",".bz":"application/x-bzip",".bz2":"application/x-bzip2",".c":"text/x-c",".c4d":"application/vnd.clonk.c4group",".c4f":"application/vnd.clonk.c4group",".c4g":"application/vnd.clonk.c4group",".c4p":"application/vnd.clonk.c4group",".c4u":"application/vnd.clonk.c4group",".cab":"application/vnd.ms-cab-compressed",".car":"application/vnd.curl.car",".cat":"application/vnd.ms-pki.seccat",".cc":"text/x-c",".cct":"application/x-director",".ccxml":"application/ccxml+xml",".cdbcmsg":"application/vnd.contact.cmsg",".cdf":"application/x-netcdf",".cdkey":"application/vnd.mediastation.cdkey",".cdx":"chemical/x-cdx",".cdxml":"application/vnd.chemdraw+xml",".cdy":"application/vnd.cinderella",".cer":"application/pkix-cert",".cgm":"image/cgm",".chat":"application/x-chat",".chm":"application/vnd.ms-htmlhelp",".chrt":"application/vnd.kde.kchart",".cif":"chemical/x-cif",".cii":"application/vnd.anser-web-certificate-issue-initiation",".cil":"application/vnd.ms-artgalry",".cla":"application/vnd.claymore",".class":"application/java-vm",".clkk":"application/vnd.crick.clicker.keyboard",".clkp":"application/vnd.crick.clicker.palette",".clkt":"application/vnd.crick.clicker.template",".clkw":"application/vnd.crick.clicker.wordbank",".clkx":"application/vnd.crick.clicker",".clp":"application/x-msclip",".cmc":"application/vnd.cosmocaller",".cmdf":"chemical/x-cmdf",".cml":"chemical/x-cml",".cmp":"application/vnd.yellowriver-custom-menu",".cmx":"image/x-cmx",".cod":"application/vnd.rim.cod",".com":"application/x-msdownload",".conf":"text/plain",".cpio":"application/x-cpio",".cpp":"text/x-c",".cpt":"application/mac-compactpro",".crd":"application/x-mscardfile",".crl":"application/pkix-crl",".crt":"application/x-x509-ca-cert",".csh":"application/x-csh",".csml":"chemical/x-csml",".csp":"application/vnd.commonspace",".css":"text/css",".cst":"application/x-director",".csv":"text/csv",".cu":"application/cu-seeme",".curl":"text/vnd.curl",".cww":"application/prs.cww",".cxt":"application/x-director",".cxx":"text/x-c",".daf":"application/vnd.mobius.daf",".dataless":"application/vnd.fdsn.seed",".davmount":"application/davmount+xml",".dcr":"application/x-director",".dcurl":"text/vnd.curl.dcurl",".dd2":"application/vnd.oma.dd2+xml",".ddd":"application/vnd.fujixerox.ddd",".deb":"application/x-debian-package",".def":"text/plain",".deploy":"application/octet-stream",".der":"application/x-x509-ca-cert",".dfac":"application/vnd.dreamfactory",".dic":"text/x-c",".diff":"text/plain",".dir":"application/x-director",".dis":"application/vnd.mobius.dis",".dist":"application/octet-stream",".distz":"application/octet-stream",".djv":"image/vnd.djvu",".djvu":"image/vnd.djvu",".dll":"application/x-msdownload",".dmg":"application/octet-stream",".dms":"application/octet-stream",".dna":"application/vnd.dna",".doc":"application/msword",".docm":"application/vnd.ms-word.document.macroenabled.12",".docx":"application/vnd.openxmlformats-officedocument.wordprocessingml.document",".dot":"application/msword",".dotm":"application/vnd.ms-word.template.macroenabled.12",".dotx":"application/vnd.openxmlformats-officedocument.wordprocessingml.template",".dp":"application/vnd.osgi.dp",".dpg":"application/vnd.dpgraph",".dsc":"text/prs.lines.tag",".dtb":"application/x-dtbook+xml",".dtd":"application/xml-dtd",".dts":"audio/vnd.dts",".dtshd":"audio/vnd.dts.hd",".dump":"application/octet-stream",".dvi":"application/x-dvi",".dwf":"model/vnd.dwf",".dwg":"image/vnd.dwg",".dxf":"image/vnd.dxf",".dxp":"application/vnd.spotfire.dxp",".dxr":"application/x-director",".ecelp4800":"audio/vnd.nuera.ecelp4800",".ecelp7470":"audio/vnd.nuera.ecelp7470",".ecelp9600":"audio/vnd.nuera.ecelp9600",".ecma":"application/ecmascript",".edm":"application/vnd.novadigm.edm",".edx":"application/vnd.novadigm.edx",".efif":"application/vnd.picsel",".ei6":"application/vnd.pg.osasli",".elc":"application/octet-stream",".eml":"message/rfc822",".emma":"application/emma+xml",".eol":"audio/vnd.digital-winds",".eot":"application/vnd.ms-fontobject",".eps":"application/postscript",".epub":"application/epub+zip",".es3":"application/vnd.eszigno3+xml",".esf":"application/vnd.epson.esf",".et3":"application/vnd.eszigno3+xml",".etx":"text/x-setext",".exe":"application/x-msdownload",".ext":"application/vnd.novadigm.ext",".ez":"application/andrew-inset",".ez2":"application/vnd.ezpix-album",".ez3":"application/vnd.ezpix-package",".f":"text/x-fortran",".f4v":"video/x-f4v",".f77":"text/x-fortran",".f90":"text/x-fortran",".fbs":"image/vnd.fastbidsheet",".fdf":"application/vnd.fdf",".fe_launch":"application/vnd.denovo.fcselayout-link",".fg5":"application/vnd.fujitsu.oasysgp",".fgd":"application/x-director",".fh":"image/x-freehand",".fh4":"image/x-freehand",".fh5":"image/x-freehand",".fh7":"image/x-freehand",".fhc":"image/x-freehand",".fig":"application/x-xfig",".fli":"video/x-fli",".flo":"application/vnd.micrografx.flo",".flv":"video/x-flv",".flw":"application/vnd.kde.kivio",".flx":"text/vnd.fmi.flexstor",".fly":"text/vnd.fly",".fm":"application/vnd.framemaker",".fnc":"application/vnd.frogans.fnc",".for":"text/x-fortran",".fpx":"image/vnd.fpx",".frame":"application/vnd.framemaker",".fsc":"application/vnd.fsc.weblaunch",".fst":"image/vnd.fst",".ftc":"application/vnd.fluxtime.clip",".fti":"application/vnd.anser-web-funds-transfer-initiation",".fvt":"video/vnd.fvt",".fzs":"application/vnd.fuzzysheet",".g3":"image/g3fax",".gac":"application/vnd.groove-account",".gdl":"model/vnd.gdl",".geo":"application/vnd.dynageo",".gex":"application/vnd.geometry-explorer",".ggb":"application/vnd.geogebra.file",".ggt":"application/vnd.geogebra.tool",".ghf":"application/vnd.groove-help",".gif":"image/gif",".gim":"application/vnd.groove-identity-message",".gmx":"application/vnd.gmx",".gnumeric":"application/x-gnumeric",".gph":"application/vnd.flographit",".gqf":"application/vnd.grafeq",".gqs":"application/vnd.grafeq",".gram":"application/srgs",".gre":"application/vnd.geometry-explorer",".grv":"application/vnd.groove-injector",".grxml":"application/srgs+xml",".gsf":"application/x-font-ghostscript",".gtar":"application/x-gtar",".gtm":"application/vnd.groove-tool-message",".gtw":"model/vnd.gtw",".gv":"text/vnd.graphviz",".gz":"application/x-gzip",".h":"text/x-c",".h261":"video/h261",".h263":"video/h263",".h264":"video/h264",".hbci":"application/vnd.hbci",".hdf":"application/x-hdf",".hh":"text/x-c",".hlp":"application/winhlp",".hpgl":"application/vnd.hp-hpgl",".hpid":"application/vnd.hp-hpid",".hps":"application/vnd.hp-hps",".hqx":"application/mac-binhex40",".htke":"application/vnd.kenameaapp",".htm":"text/html",".html":"text/html",".hvd":"application/vnd.yamaha.hv-dic",".hvp":"application/vnd.yamaha.hv-voice",".hvs":"application/vnd.yamaha.hv-script",".icc":"application/vnd.iccprofile",".ice":"x-conference/x-cooltalk",".icm":"application/vnd.iccprofile",".ico":"image/x-icon",".ics":"text/calendar",".ief":"image/ief",".ifb":"text/calendar",".ifm":"application/vnd.shana.informed.formdata",".iges":"model/iges",".igl":"application/vnd.igloader",".igs":"model/iges",".igx":"application/vnd.micrografx.igx",".iif":"application/vnd.shana.informed.interchange",".imp":"application/vnd.accpac.simply.imp",".ims":"application/vnd.ms-ims",".in":"text/plain",".ipk":"application/vnd.shana.informed.package",".irm":"application/vnd.ibm.rights-management",".irp":"application/vnd.irepository.package+xml",".iso":"application/octet-stream",".itp":"application/vnd.shana.informed.formtemplate",".ivp":"application/vnd.immervision-ivp",".ivu":"application/vnd.immervision-ivu",".jad":"text/vnd.sun.j2me.app-descriptor",".jam":"application/vnd.jam",".jar":"application/java-archive",".java":"text/x-java-source",".jisp":"application/vnd.jisp",".jlt":"application/vnd.hp-jlyt",".jnlp":"application/x-java-jnlp-file",".joda":"application/vnd.joost.joda-archive",".jpe":"image/jpeg",".jpeg":"image/jpeg",".jpg":"image/jpeg",".jpgm":"video/jpm",".jpgv":"video/jpeg",".jpm":"video/jpm",".js":"application/javascript",".json":"application/json",".kar":"audio/midi",".karbon":"application/vnd.kde.karbon",".kfo":"application/vnd.kde.kformula",".kia":"application/vnd.kidspiration",".kil":"application/x-killustrator",".kml":"application/vnd.google-earth.kml+xml",".kmz":"application/vnd.google-earth.kmz",".kne":"application/vnd.kinar",".knp":"application/vnd.kinar",".kon":"application/vnd.kde.kontour",".kpr":"application/vnd.kde.kpresenter",".kpt":"application/vnd.kde.kpresenter",".ksh":"text/plain",".ksp":"application/vnd.kde.kspread",".ktr":"application/vnd.kahootz",".ktz":"application/vnd.kahootz",".kwd":"application/vnd.kde.kword",".kwt":"application/vnd.kde.kword",".latex":"application/x-latex",".lbd":"application/vnd.llamagraphics.life-balance.desktop",".lbe":"application/vnd.llamagraphics.life-balance.exchange+xml",".les":"application/vnd.hhe.lesson-player",".lha":"application/octet-stream",".link66":"application/vnd.route66.link66+xml",".list":"text/plain",".list3820":"application/vnd.ibm.modcap",".listafp":"application/vnd.ibm.modcap",".log":"text/plain",".lostxml":"application/lost+xml",".lrf":"application/octet-stream",".lrm":"application/vnd.ms-lrm",".ltf":"application/vnd.frogans.ltf",".lvp":"audio/vnd.lucent.voice",".lwp":"application/vnd.lotus-wordpro",".lzh":"application/octet-stream",".m13":"application/x-msmediaview",".m14":"application/x-msmediaview",".m1v":"video/mpeg",".m2a":"audio/mpeg",".m2v":"video/mpeg",".m3a":"audio/mpeg",".m3u":"audio/x-mpegurl",".m4u":"video/vnd.mpegurl",".m4v":"video/x-m4v",".ma":"application/mathematica",".mag":"application/vnd.ecowin.chart",".maker":"application/vnd.framemaker",".man":"text/troff",".mathml":"application/mathml+xml",".mb":"application/mathematica",".mbk":"application/vnd.mobius.mbk",".mbox":"application/mbox",".mc1":"application/vnd.medcalcdata",".mcd":"application/vnd.mcd",".mcurl":"text/vnd.curl.mcurl",".mdb":"application/x-msaccess",".mdi":"image/vnd.ms-modi",".me":"text/troff",".mesh":"model/mesh",".mfm":"application/vnd.mfmp",".mgz":"application/vnd.proteus.magazine",".mht":"message/rfc822",".mhtml":"message/rfc822",".mid":"audio/midi",".midi":"audio/midi",".mif":"application/vnd.mif",".mime":"message/rfc822",".mj2":"video/mj2",".mjp2":"video/mj2",".mkv":"video/x-matroska",".mlp":"application/vnd.dolby.mlp",".mmd":"application/vnd.chipnuts.karaoke-mmd",".mmf":"application/vnd.smaf",".mmr":"image/vnd.fujixerox.edmics-mmr",".mny":"application/x-msmoney",".mobi":"application/x-mobipocket-ebook",".mov":"video/quicktime",".movie":"video/x-sgi-movie",".mp2":"audio/mpeg",".mp2a":"audio/mpeg",".mp3":"audio/mpeg",".mp4":"video/mp4",".mp4a":"audio/mp4",".mp4s":"application/mp4",".mp4v":"video/mp4",".mpa":"video/mpeg",".mpc":"application/vnd.mophun.certificate",".mpe":"video/mpeg",".mpeg":"video/mpeg",".mpg":"video/mpeg",".mpg4":"video/mp4",".mpga":"audio/mpeg",".mpkg":"application/vnd.apple.installer+xml",".mpm":"application/vnd.blueice.multipass",".mpn":"application/vnd.mophun.application",".mpp":"application/vnd.ms-project",".mpt":"application/vnd.ms-project",".mpy":"application/vnd.ibm.minipay",".mqy":"application/vnd.mobius.mqy",".mrc":"application/marc",".ms":"text/troff",".mscml":"application/mediaservercontrol+xml",".mseed":"application/vnd.fdsn.mseed",".mseq":"application/vnd.mseq",".msf":"application/vnd.epson.msf",".msh":"model/mesh",".msi":"application/x-msdownload",".msl":"application/vnd.mobius.msl",".msty":"application/vnd.muvee.style",".mts":"model/vnd.mts",".mus":"application/vnd.musician",".musicxml":"application/vnd.recordare.musicxml+xml",".mvb":"application/x-msmediaview",".mwf":"application/vnd.mfer",".mxf":"application/mxf",".mxl":"application/vnd.recordare.musicxml",".mxml":"application/xv+xml",".mxs":"application/vnd.triscape.mxs",".mxu":"video/vnd.mpegurl",".n-gage":"application/vnd.nokia.n-gage.symbian.install",".nb":"application/mathematica",".nc":"application/x-netcdf",".ncx":"application/x-dtbncx+xml",".ngdat":"application/vnd.nokia.n-gage.data",".nlu":"application/vnd.neurolanguage.nlu",".nml":"application/vnd.enliven",".nnd":"application/vnd.noblenet-directory",".nns":"application/vnd.noblenet-sealer",".nnw":"application/vnd.noblenet-web",".npx":"image/vnd.net-fpx",".nsf":"application/vnd.lotus-notes",".nws":"message/rfc822",".o":"application/octet-stream",".oa2":"application/vnd.fujitsu.oasys2",".oa3":"application/vnd.fujitsu.oasys3",".oas":"application/vnd.fujitsu.oasys",".obd":"application/x-msbinder",".obj":"application/octet-stream",".oda":"application/oda",".odb":"application/vnd.oasis.opendocument.database",".odc":"application/vnd.oasis.opendocument.chart",".odf":"application/vnd.oasis.opendocument.formula",".odft":"application/vnd.oasis.opendocument.formula-template",".odg":"application/vnd.oasis.opendocument.graphics",".odi":"application/vnd.oasis.opendocument.image",".odp":"application/vnd.oasis.opendocument.presentation",".ods":"application/vnd.oasis.opendocument.spreadsheet",".odt":"application/vnd.oasis.opendocument.text",".oga":"audio/ogg",".ogg":"audio/ogg",".ogv":"video/ogg",".ogx":"application/ogg",".onepkg":"application/onenote",".onetmp":"application/onenote",".onetoc":"application/onenote",".onetoc2":"application/onenote",".opf":"application/oebps-package+xml",".oprc":"application/vnd.palm",".org":"application/vnd.lotus-organizer",".osf":"application/vnd.yamaha.openscoreformat",".osfpvg":"application/vnd.yamaha.openscoreformat.osfpvg+xml",".otc":"application/vnd.oasis.opendocument.chart-template",".otf":"application/x-font-otf",".otg":"application/vnd.oasis.opendocument.graphics-template",".oth":"application/vnd.oasis.opendocument.text-web",".oti":"application/vnd.oasis.opendocument.image-template",".otm":"application/vnd.oasis.opendocument.text-master",".otp":"application/vnd.oasis.opendocument.presentation-template",".ots":"application/vnd.oasis.opendocument.spreadsheet-template",".ott":"application/vnd.oasis.opendocument.text-template",".oxt":"application/vnd.openofficeorg.extension",".p":"text/x-pascal",".p10":"application/pkcs10",".p12":"application/x-pkcs12",".p7b":"application/x-pkcs7-certificates",".p7c":"application/pkcs7-mime",".p7m":"application/pkcs7-mime",".p7r":"application/x-pkcs7-certreqresp",".p7s":"application/pkcs7-signature",".pas":"text/x-pascal",".pbd":"application/vnd.powerbuilder6",".pbm":"image/x-portable-bitmap",".pcf":"application/x-font-pcf",".pcl":"application/vnd.hp-pcl",".pclxl":"application/vnd.hp-pclxl",".pct":"image/x-pict",".pcurl":"application/vnd.curl.pcurl",".pcx":"image/x-pcx",".pdb":"application/vnd.palm",".pdf":"application/pdf",".pfa":"application/x-font-type1",".pfb":"application/x-font-type1",".pfm":"application/x-font-type1",".pfr":"application/font-tdpfr",".pfx":"application/x-pkcs12",".pgm":"image/x-portable-graymap",".pgn":"application/x-chess-pgn",".pgp":"application/pgp-encrypted",".pic":"image/x-pict",".pkg":"application/octet-stream",".pki":"application/pkixcmp",".pkipath":"application/pkix-pkipath",".pl":"text/plain",".plb":"application/vnd.3gpp.pic-bw-large",".plc":"application/vnd.mobius.plc",".plf":"application/vnd.pocketlearn",".pls":"application/pls+xml",".pml":"application/vnd.ctc-posml",".png":"image/png",".pnm":"image/x-portable-anymap",".portpkg":"application/vnd.macports.portpkg",".pot":"application/vnd.ms-powerpoint",".potm":"application/vnd.ms-powerpoint.template.macroenabled.12",".potx":"application/vnd.openxmlformats-officedocument.presentationml.template",".ppa":"application/vnd.ms-powerpoint",".ppam":"application/vnd.ms-powerpoint.addin.macroenabled.12",".ppd":"application/vnd.cups-ppd",".ppm":"image/x-portable-pixmap",".pps":"application/vnd.ms-powerpoint",".ppsm":"application/vnd.ms-powerpoint.slideshow.macroenabled.12",".ppsx":"application/vnd.openxmlformats-officedocument.presentationml.slideshow",".ppt":"application/vnd.ms-powerpoint",".pptm":"application/vnd.ms-powerpoint.presentation.macroenabled.12",".pptx":"application/vnd.openxmlformats-officedocument.presentationml.presentation",".pqa":"application/vnd.palm",".prc":"application/x-mobipocket-ebook",".pre":"application/vnd.lotus-freelance",".prf":"application/pics-rules",".ps":"application/postscript",".psb":"application/vnd.3gpp.pic-bw-small",".psd":"image/vnd.adobe.photoshop",".psf":"application/x-font-linux-psf",".ptid":"application/vnd.pvi.ptid1",".pub":"application/x-mspublisher",".pvb":"application/vnd.3gpp.pic-bw-var",".pwn":"application/vnd.3m.post-it-notes",".pwz":"application/vnd.ms-powerpoint",".py":"text/x-python",".pya":"audio/vnd.ms-playready.media.pya",".pyc":"application/x-python-code",".pyo":"application/x-python-code",".pyv":"video/vnd.ms-playready.media.pyv",".qam":"application/vnd.epson.quickanime",".qbo":"application/vnd.intu.qbo",".qfx":"application/vnd.intu.qfx",".qps":"application/vnd.publishare-delta-tree",".qt":"video/quicktime",".qwd":"application/vnd.quark.quarkxpress",".qwt":"application/vnd.quark.quarkxpress",".qxb":"application/vnd.quark.quarkxpress",".qxd":"application/vnd.quark.quarkxpress",".qxl":"application/vnd.quark.quarkxpress",".qxt":"application/vnd.quark.quarkxpress",".ra":"audio/x-pn-realaudio",".ram":"audio/x-pn-realaudio",".rar":"application/x-rar-compressed",".ras":"image/x-cmu-raster",".rcprofile":"application/vnd.ipunplugged.rcprofile",".rdf":"application/rdf+xml",".rdz":"application/vnd.data-vision.rdz",".rep":"application/vnd.businessobjects",".res":"application/x-dtbresource+xml",".rgb":"image/x-rgb",".rif":"application/reginfo+xml",".rl":"application/resource-lists+xml",".rlc":"image/vnd.fujixerox.edmics-rlc",".rld":"application/resource-lists-diff+xml",".rm":"application/vnd.rn-realmedia",".rmi":"audio/midi",".rmp":"audio/x-pn-realaudio-plugin",".rms":"application/vnd.jcp.javame.midlet-rms",".rnc":"application/relax-ng-compact-syntax",".roff":"text/troff",".rpm":"application/x-rpm",".rpss":"application/vnd.nokia.radio-presets",".rpst":"application/vnd.nokia.radio-preset",".rq":"application/sparql-query",".rs":"application/rls-services+xml",".rsd":"application/rsd+xml",".rss":"application/rss+xml",".rtf":"application/rtf",".rtx":"text/richtext",".s":"text/x-asm",".saf":"application/vnd.yamaha.smaf-audio",".sbml":"application/sbml+xml",".sc":"application/vnd.ibm.secure-container",".scd":"application/x-msschedule",".scm":"application/vnd.lotus-screencam",".scq":"application/scvp-cv-request",".scs":"application/scvp-cv-response",".scurl":"text/vnd.curl.scurl",".sda":"application/vnd.stardivision.draw",".sdc":"application/vnd.stardivision.calc",".sdd":"application/vnd.stardivision.impress",".sdkd":"application/vnd.solent.sdkm+xml",".sdkm":"application/vnd.solent.sdkm+xml",".sdp":"application/sdp",".sdw":"application/vnd.stardivision.writer",".see":"application/vnd.seemail",".seed":"application/vnd.fdsn.seed",".sema":"application/vnd.sema",".semd":"application/vnd.semd",".semf":"application/vnd.semf",".ser":"application/java-serialized-object",".setpay":"application/set-payment-initiation",".setreg":"application/set-registration-initiation",".sfd-hdstx":"application/vnd.hydrostatix.sof-data",".sfs":"application/vnd.spotfire.sfs",".sgl":"application/vnd.stardivision.writer-global",".sgm":"text/sgml",".sgml":"text/sgml",".sh":"application/x-sh",".shar":"application/x-shar",".shf":"application/shf+xml",".si":"text/vnd.wap.si",".sic":"application/vnd.wap.sic",".sig":"application/pgp-signature",".silo":"model/mesh",".sis":"application/vnd.symbian.install",".sisx":"application/vnd.symbian.install",".sit":"application/x-stuffit",".sitx":"application/x-stuffitx",".skd":"application/vnd.koan",".skm":"application/vnd.koan",".skp":"application/vnd.koan",".skt":"application/vnd.koan",".sl":"text/vnd.wap.sl",".slc":"application/vnd.wap.slc",".sldm":"application/vnd.ms-powerpoint.slide.macroenabled.12",".sldx":"application/vnd.openxmlformats-officedocument.presentationml.slide",".slt":"application/vnd.epson.salt",".smf":"application/vnd.stardivision.math",".smi":"application/smil+xml",".smil":"application/smil+xml",".snd":"audio/basic",".snf":"application/x-font-snf",".so":"application/octet-stream",".spc":"application/x-pkcs7-certificates",".spf":"application/vnd.yamaha.smaf-phrase",".spl":"application/x-futuresplash",".spot":"text/vnd.in3d.spot",".spp":"application/scvp-vp-response",".spq":"application/scvp-vp-request",".spx":"audio/ogg",".src":"application/x-wais-source",".srx":"application/sparql-results+xml",".sse":"application/vnd.kodak-descriptor",".ssf":"application/vnd.epson.ssf",".ssml":"application/ssml+xml",".stc":"application/vnd.sun.xml.calc.template",".std":"application/vnd.sun.xml.draw.template",".stf":"application/vnd.wt.stf",".sti":"application/vnd.sun.xml.impress.template",".stk":"application/hyperstudio",".stl":"application/vnd.ms-pki.stl",".str":"application/vnd.pg.format",".stw":"application/vnd.sun.xml.writer.template",".sus":"application/vnd.sus-calendar",".susp":"application/vnd.sus-calendar",".sv4cpio":"application/x-sv4cpio",".sv4crc":"application/x-sv4crc",".svd":"application/vnd.svd",".svg":"image/svg+xml",".svgz":"image/svg+xml",".swa":"application/x-director",".swf":"application/x-shockwave-flash",".swi":"application/vnd.arastra.swi",".sxc":"application/vnd.sun.xml.calc",".sxd":"application/vnd.sun.xml.draw",".sxg":"application/vnd.sun.xml.writer.global",".sxi":"application/vnd.sun.xml.impress",".sxm":"application/vnd.sun.xml.math",".sxw":"application/vnd.sun.xml.writer",".t":"text/troff",".tao":"application/vnd.tao.intent-module-archive",".tar":"application/x-tar",".tcap":"application/vnd.3gpp2.tcap",".tcl":"application/x-tcl",".teacher":"application/vnd.smart.teacher",".tex":"application/x-tex",".texi":"application/x-texinfo",".texinfo":"application/x-texinfo",".text":"text/plain",".tfm":"application/x-tex-tfm",".tgz":"application/x-gzip",".tif":"image/tiff",".tiff":"image/tiff",".tmo":"application/vnd.tmobile-livetv",".torrent":"application/x-bittorrent",".tpl":"application/vnd.groove-tool-template",".tpt":"application/vnd.trid.tpt",".tr":"text/troff",".tra":"application/vnd.trueapp",".trm":"application/x-msterminal",".tsv":"text/tab-separated-values",".ttc":"application/x-font-ttf",".ttf":"application/x-font-ttf",".twd":"application/vnd.simtech-mindmapper",".twds":"application/vnd.simtech-mindmapper",".txd":"application/vnd.genomatix.tuxedo",".txf":"application/vnd.mobius.txf",".txt":"text/plain",".u32":"application/x-authorware-bin",".udeb":"application/x-debian-package",".ufd":"application/vnd.ufdl",".ufdl":"application/vnd.ufdl",".umj":"application/vnd.umajin",".unityweb":"application/vnd.unity",".uoml":"application/vnd.uoml+xml",".uri":"text/uri-list",".uris":"text/uri-list",".urls":"text/uri-list",".ustar":"application/x-ustar",".utz":"application/vnd.uiq.theme",".uu":"text/x-uuencode",".vcd":"application/x-cdlink",".vcf":"text/x-vcard",".vcg":"application/vnd.groove-vcard",".vcs":"text/x-vcalendar",".vcx":"application/vnd.vcx",".vis":"application/vnd.visionary",".viv":"video/vnd.vivo",".vor":"application/vnd.stardivision.writer",".vox":"application/x-authorware-bin",".vrml":"model/vrml",".vsd":"application/vnd.visio",".vsf":"application/vnd.vsf",".vss":"application/vnd.visio",".vst":"application/vnd.visio",".vsw":"application/vnd.visio",".vtu":"model/vnd.vtu",".vxml":"application/voicexml+xml",".w3d":"application/x-director",".webm":"video/webm",".wad":"application/x-doom",".wav":"audio/x-wav",".wax":"audio/x-ms-wax",".wbmp":"image/vnd.wap.wbmp",".wbs":"application/vnd.criticaltools.wbs+xml",".wbxml":"application/vnd.wap.wbxml",".wcm":"application/vnd.ms-works",".wdb":"application/vnd.ms-works",".wiz":"application/msword",".wks":"application/vnd.ms-works",".wm":"video/x-ms-wm",".wma":"audio/x-ms-wma",".wmd":"application/x-ms-wmd",".wmf":"application/x-msmetafile",".wml":"text/vnd.wap.wml",".wmlc":"application/vnd.wap.wmlc",".wmls":"text/vnd.wap.wmlscript",".wmlsc":"application/vnd.wap.wmlscriptc",".wmv":"video/x-ms-wmv",".wmx":"video/x-ms-wmx",".wmz":"application/x-ms-wmz",".wpd":"application/vnd.wordperfect",".wpl":"application/vnd.ms-wpl",".wps":"application/vnd.ms-works",".wqd":"application/vnd.wqd",".wri":"application/x-mswrite",".wrl":"model/vrml",".wsdl":"application/wsdl+xml",".wspolicy":"application/wspolicy+xml",".wtb":"application/vnd.webturbo",".wvx":"video/x-ms-wvx",".x32":"application/x-authorware-bin",".x3d":"application/vnd.hzn-3d-crossword",".xap":"application/x-silverlight-app",".xar":"application/vnd.xara",".xbap":"application/x-ms-xbap",".xbd":"application/vnd.fujixerox.docuworks.binder",".xbm":"image/x-xbitmap",".xdm":"application/vnd.syncml.dm+xml",".xdp":"application/vnd.adobe.xdp+xml",".xdw":"application/vnd.fujixerox.docuworks",".xenc":"application/xenc+xml",".xer":"application/patch-ops-error+xml",".xfdf":"application/vnd.adobe.xfdf",".xfdl":"application/vnd.xfdl",".xht":"application/xhtml+xml",".xhtml":"application/xhtml+xml",".xhvml":"application/xv+xml",".xif":"image/vnd.xiff",".xla":"application/vnd.ms-excel",".xlam":"application/vnd.ms-excel.addin.macroenabled.12",".xlb":"application/vnd.ms-excel",".xlc":"application/vnd.ms-excel",".xlm":"application/vnd.ms-excel",".xls":"application/vnd.ms-excel",".xlsb":"application/vnd.ms-excel.sheet.binary.macroenabled.12",".xlsm":"application/vnd.ms-excel.sheet.macroenabled.12",".xlsx":"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",".xlt":"application/vnd.ms-excel",".xltm":"application/vnd.ms-excel.template.macroenabled.12",".xltx":"application/vnd.openxmlformats-officedocument.spreadsheetml.template",".xlw":"application/vnd.ms-excel",".xml":"application/xml",".xo":"application/vnd.olpc-sugar",".xop":"application/xop+xml",".xpdl":"application/xml",".xpi":"application/x-xpinstall",".xpm":"image/x-xpixmap",".xpr":"application/vnd.is-xpr",".xps":"application/vnd.ms-xpsdocument",".xpw":"application/vnd.intercon.formnet",".xpx":"application/vnd.intercon.formnet",".xsl":"application/xml",".xslt":"application/xslt+xml",".xsm":"application/vnd.syncml+xml",".xspf":"application/xspf+xml",".xul":"application/vnd.mozilla.xul+xml",".xvm":"application/xv+xml",".xvml":"application/xv+xml",".xwd":"image/x-xwindowdump",".xyz":"chemical/x-xyz",".zaz":"application/vnd.zzazz.deck+xml",".zip":"application/zip",".zir":"application/vnd.zul",".zirz":"application/vnd.zul",".zmm":"application/vnd.handheld-entertainment+xml"},Sh=[".sh",".exe",".app",".bat",".cmd",".msi",".apk",".jar",".py",".js",".cron",".php",".asp"],TW=Object.keys(pu);import*as yh from"zod";var AW=yh.custom().refine(r=>r&&r.length>0).refine(r=>r&&r[0]instanceof File,{message:"Please upload a valid file."});import{z as jr}from"zod";var CW=jr.object({id:jr.string(),name:jr.string(),createdAt:jr.coerce.date(),createdBy:jr.string(),updatedAt:jr.coerce.date(),updatedBy:jr.string().nullable(),organizationId:jr.string()});import{z as P}from"zod";import Wr from"zod";var ho=Wr.object({platformSep:Wr.string(),fullPathSegments:Wr.string().array(),relativePathSegments:Wr.string().array(),relativePath:Wr.string().describe("path relative to the root test directory, i.e. my-folder/my-test.yaml"),fileName:Wr.string().describe("base name of the file including the extension, e.g. my-module.module.yaml"),lastModified:Wr.coerce.date(),createdAt:Wr.coerce.date()});var Wx=P.array(ho.extend({id:P.string(),name:P.string(),description:P.string().optional(),labels:P.string().array().optional()})),$x=P.array(ho.extend({id:P.string(),name:P.string(),description:P.string().optional(),content:mi})),BW=P.object({tests:Wx,modules:$x,labels:P.string().array()}),zW=Qa.merge(uo),GW=P.object({schemaVersion:P.string(),stepLists:no}),HW=uo.partial().merge($t.pick({id:!0})),qx={name:P.string().min(1).max(255).describe("1-255 chars; Only letters/numbers/dashes. Cannot start/end with '-'. Not '.yaml', 'none', or UUID."),description:P.string().optional(),baseUrl:P.string().url().optional().describe("For LLM: Ask the user for the base URL if they don't provide it."),environment:P.string().optional().describe("For LLM: Do not include the variable unless the user explicitly asks for it and use the environment lookup tool to get the correct one before passing here."),browserType:P.nativeEnum(Fr).optional().describe("For LLM: Never assign this variable unless the user explicitly asks for it."),viewport:Ga.optional().describe("For LLM: Never assign this variable unless the user explicitly asks for it."),pathSegments:P.string().array().optional().describe("For LLM: Only use if explicitly called for by the user. Used to create the test in the correct folder.")},VW=P.object(qx),jW=Qa.merge(P.object({relativeFilePath:P.string().describe("relative to project root")})),WW=P.object({name:P.string()}),$W=P.object({relativeFilePath:P.string()}),qW=P.object({name:P.string()}),KW=P.object({relativeFilePath:P.string()}),YW=P.object({name:P.string(),description:P.string(),enabled:P.boolean(),steps:P.lazy(()=>Ke.array()),testFilePath:P.string().describe("relative to the project root"),folderPath:P.string().optional().describe("user selected folder path")}),XW=P.object({name:P.string(),description:P.string(),enabled:P.boolean()}).partial();var JW=P.array(ag),QW=P.object({defaultEnv:P.string().optional().describe("name of the default env, or undefined to unset")}),ZW=P.object({configFilePath:P.string().describe("full path on disk")}),e$=P.string().array(),t$=P.object({message:P.string(),newRelativeTestPath:P.string().optional()}),mu=P.object({name:P.string(),absolutePath:P.string(),relativePath:P.string(),pathSegments:P.array(P.string()),isDirectory:P.boolean(),size:P.number(),createdAt:P.coerce.date(),modifiedAt:P.coerce.date(),accessedAt:P.coerce.date()}),Eh=P.object({pathSegments:P.array(P.string())}),r$=P.object({absolutePath:P.string(),pathSegments:P.array(P.string()),contents:P.array(mu)}),bh=P.object({pathSegments:P.array(P.string())}),Th=P.object({pathSegments:P.array(P.string()),newPathSegments:P.array(P.string())}),vh=P.object({pathSegments:P.array(P.string()),recursive:P.boolean().optional()}),n$=P.object({success:P.boolean(),message:P.string(),pathSegments:P.array(P.string()).optional()});var ls=["node_modules","dist","bin",".git",".npm",".next","out",".yarn","__pycache__","build",".env",".venv","venv","env","wheels"],cs=ls.map(r=>`**/${r}/**`),Ah=!0,En=!1;import cr from"chalk";import Kx from"safe-stable-stringify";import Yx from"truncate-json";import Xx from"zod";var $r=Kx.configure({deterministic:!1});function Rh(r){let e=$r(r),{jsonString:t}=Yx(e,1e4);return t}var Jx=["app","version","env","namespace","host"];function pe(r){let e=r.bindings()??{},t={};for(let n of Object.keys(e)){let o=e[n];!Jx.includes(n)&&typeof o=="string"&&(t[n]=o)}return t}var ds=Xx.enum(["debug","info","warn","error"]);var Ii={debug:20,info:30,warn:40,error:50},ps={20:"debug",30:"info",40:"warn",50:"error"},gu=class r{minLogLevel;logBindings;constructor(e,t){typeof e=="string"?this.minLogLevel=Ii[e]:this.minLogLevel=e,this.logBindings=t}logWithLevel(e,t,...n){try{this.logWithLevelHelper(e,t,...n)}catch(o){console.error(`Failed to log to console: ${o}`)}}logWithLevelHelper(e,t,...n){if(e<this.minLogLevel)return;let o;Array.isArray(n[0])?(o=n[0],n=n.slice(1)):typeof n[0]=="object"&&!(n[0]instanceof Error)&&Object.entries(n[0]).length&&(o={...n[0],...this.logBindings},n=n.slice(1));let i=[];if(i.push(...n),console.log(t(...i)),o&&!Array.isArray(o)){let a=Object.entries(o);for(let[l,c]of a){let s=c;c instanceof Error?(s=c.message,console.log(t(` ${l}:`,s)),console.log(t(" stack:",c.stack))):typeof c=="object"&&(s=$r(c,void 0,2),s=s.split(`
6
6
  `).map((u,d)=>d>0?` ${u}`:u).join(`
7
- `),console.log(t(` ${l}:`,s)))}}else if(o)for(let a of o){let l=a;typeof a=="object"&&(l=Ur(a,void 0,2),l=l.split(`
7
+ `),console.log(t(` ${l}:`,s)))}}else if(o)for(let a of o){let l=a;typeof a=="object"&&(l=$r(a,void 0,2),l=l.split(`
8
8
  `).map((c,s)=>s>0?` ${c}`:c).join(`
9
- `)),console.log(" ",t(l))}}getLevel(){return qa[this.minLogLevel]}setMinLevel(e){typeof e=="string"?this.minLogLevel=Si[e]:this.minLogLevel=e}log(...e){this.logWithLevel(30,tr.reset,...e)}info(...e){this.logWithLevel(30,tr.white,...e)}debug(...e){this.logWithLevel(20,tr.dim,...e)}warn(...e){this.logWithLevel(40,tr.yellow,...e)}error(...e){this.logWithLevel(50,tr.red,...e)}success(...e){this.logWithLevel(1/0,tr.green,...e)}dimmed(...e){this.logWithLevel(30,tr.dim,...e)}underline(...e){this.logWithLevel(40,tr.underline,...e)}bold(...e){this.logWithLevel(40,tr.bold,...e)}grey(...e){this.logWithLevel(20,tr.grey,...e)}child(e){return new r(this.minLogLevel,{...this.logBindings,...e})}flush(){}bindings(){return this.logBindings}},qc=class{debug(){}info(){}warn(){}error(){}success(){}dimmed(){}underline(){}bold(){}grey(){}child(){return this}getLevel(){return"error"}flush(){}bindings(){return{}}},kj=new qc,KC=typeof window>"u"&&typeof process<"u"&&$a.safeParse(process?.env?.MOMENTIC_DEV_LOG_LEVEL).success?$a.parse(process.env.MOMENTIC_DEV_LOG_LEVEL):30,w=new $c(KC,{}),dn={info:()=>{},error:()=>{},debug:()=>{},warn:()=>{},child:()=>dn,flush:()=>{},bindings:()=>({}),getLevel:()=>"error"},Wa={},Ka=({logger:r,logKey:e,maxCount:t,intervalMs:n},o,i,...a)=>{let l=Wa[e];l?clearTimeout(l.timer):(l={count:0,totalCount:0},Wa[e]=l),l.totalCount++,l.count<t&&(l.count++,r.debug(o,i,...a)),l.timer=setTimeout(()=>{let c=Wa[e];c?.totalCount!==c?.count&&r.debug({logKey:e,totalCount:c?.totalCount,count:c?.count},`Debug logs were rate-limited for ${e}`),delete Wa[e]},n)};import{z as pe}from"zod";var YC=pe.array(no.extend({id:pe.string(),name:pe.string(),description:pe.string().optional(),labels:pe.string().array().optional()})),XC=pe.array(no.extend({id:pe.string(),name:pe.string(),description:pe.string().optional(),content:ri})),Jg=pe.object({name:pe.string(),description:pe.string().optional(),steps:pe.array(hr).optional(),settings:gi.optional(),pathSegments:pe.string().array()}),Hj=pe.object({id:pe.string(),fileName:pe.string(),fullPath:pe.string(),relativeFilePath:pe.string().describe("relative to project root")});var Qg=pe.object({steps:pe.array(hr).optional(),settings:gi.optional()}),Vj=pe.object({message:pe.literal("ok")}),Zg=pe.object({tag:pe.string(),channel:pe.string(),filePath:pe.string()}),jj=pe.object({tests:YC,modules:XC,labels:pe.string().array()});import{z as Ue}from"zod";var eh=Ue.object({id:Ue.string(),createdAt:Ue.coerce.date(),createdBy:Ue.string(),organizationId:Ue.string(),name:Ue.string(),description:Ue.string().nullish(),enabled:Ue.boolean(),schemaVersion:Ue.string().describe("Schema version for steps"),parameters:Ue.string().array().nullish().describe("Parameter list"),parameterEnums:Ue.record(Ue.string(),Ue.string().array()).nullish(),defaultParameters:Ue.record(Ue.string(),Ue.string()).nullish(),defaultCacheKey:Ue.string().nullish(),defaultCacheTtl:Ue.number().nullish(),defaultCacheAllInvocations:Ue.boolean().nullish(),autoAuth:Ue.boolean().nullish(),advanced:sc.nullish()}),Zj=eh.extend({steps:Ue.lazy(()=>pt.array())}),eW=5*60*1e3,JC=Ot.merge(eh.omit({id:!0,createdAt:!0,createdBy:!0,organizationId:!0,enabled:!0}));import{formatInTimeZone as nW}from"date-fns-tz";import{z as Ee}from"zod";var Kc=Tc.extend({aiAction:Ee.boolean().optional(),stepLintSuggestions:Ee.boolean().optional(),agentConfig:Ee.record(Ee.string(),Ee.string()).optional(),aiFailureAnalysis:Ee.boolean().optional(),aiPageFiltering:Ee.boolean().optional().describe("rag v2 feature flag")}),Yc=Ee.object({fakerConstantSeed:Ee.boolean().optional()}),cW=Ee.object({ai:Kc.optional(),githubAppInstallationId:Ee.number().nullish(),githubAppSummaryMessageEnabled:Ee.boolean().nullish(),githubReleaseAppInstallationId:Ee.number().nullish(),gitlabAppAccessToken:Ee.string().nullish(),gitlabAppBaseUrl:Ee.string().nullish(),qaseAccessToken:Ee.string().nullish(),testSuggestionsEnabled:Ee.boolean().nullish(),browser:mc.optional(),advanced:Yc.optional()}),uW=Ee.object({globalOverrides:Ee.record(Ee.string()).optional(),agentConfig:Ee.record(Ee.string(),Ee.string()).optional()}),dW=Ee.record(Ee.string(),Ee.string()).nullish();import*as S from"zod";import{z as Le}from"zod";var Xc=(e=>(e.TEST_REVIEW="TEST_REVIEW",e))(Xc||{});var QC=Le.object({type:Le.literal("DESCRIPTION_UPDATE"),thoughts:Le.string()}),Ya=Le.discriminatedUnion("type",[QC]),ZC=Le.object({testId:Le.string(),name:Le.string(),orgId:Le.string(),runId:Le.string(),steps:$e.array(),purpose:Le.nativeEnum(Xc),details:Ya.or(Ya.array()).optional()});var hW=ZC.pick({name:!0,orgId:!0}),ex=Le.object({id:Le.string(),name:Le.string().nullish(),createdAt:Le.string().pipe(Le.coerce.date()).or(Le.date()),organizationId:Le.string(),schemaVersion:Le.string(),runId:Le.string().nullish(),purpose:Le.nativeEnum(Xc),details:Ya.or(Ya.array()).optional(),applied:Le.boolean().nullish(),appliedAt:Le.coerce.date().nullish()}),th=ex.extend({steps:$e.array()});var rh="x-momentic-cli-version",nh="x-momentic-cli-type",tx="x-momentic-main-branch-name",rx="x-momentic-branch-name",nx="x-momentic-commit-timestamp",ox="x-momentic-last-commit-on-main",ix="x-momentic-last-commit-on-main-timestamp",ax="x-momentic-merged-branch-name";var OW=S.object({error:S.boolean(),reason:S.string(),message:S.string()}),LW=it.merge(Ac),oh=Ea,NW=it.merge(Ac);var DW=it.merge(Qp).extend({useConsensus:S.boolean().optional(),attemptNumber:S.number().optional()}),Jc=Zm,kW=it.merge(eg),ih=bp,UW=it.merge(Zp),ah=Tp,FW=it.merge(Yp),sh=Ep,BW=it.merge(Xp),lh=fp,zW=it.merge(Jp);var GW=it.merge(og),HW=S.object({testPaths:S.string().array().describe("can be either hyphenated, lowercase test names or UUIDs"),env:S.string().optional(),all:S.boolean().optional(),urlOverride:S.string().optional(),customHeaders:S.record(S.string(),S.string()).optional(),testInputMatrix:S.record(S.string(),S.string()).array().optional()}),ch=S.object({queuedTests:S.unknown().array(),runIds:S.string().uuid().array(),runGroupId:S.string().optional()});var VW=S.string().array(),jW=S.union([S.object({paths:S.string().array().describe("run specific test paths (e.g. todo-test)"),all:S.boolean().describe("run all tests").optional()}),S.object({path:S.string().describe("deprecated; present for backcompat")})]),uh=S.object({tests:S.record(S.string().describe("Test name"),S.string().describe("Test YAML")),modules:S.record(S.string().describe("Module name"),S.string().describe("Module YAML"))}),sx=S.object({test:S.string().describe("test YAML"),modules:S.record(S.string().describe("moduleId"),S.string().describe("module YAML"))}),WW=sx.array(),$W=S.object({testId:S.string(),schemaVersion:S.string()}).merge(en);function Qc(r){let{gitMainBranch:e,gitBranchName:t,gitCommitTimestamp:n,lastCommitOnMainSha:o,lastCommitOnMainTimestamp:i}=r,a={};return e&&(a[tx]=encodeURIComponent(e)),t&&(a[rx]=encodeURIComponent(t)),n&&(a[nx]=n.toISOString()),o&&(a[ox]=encodeURIComponent(o)),i&&(a[ix]=i.toISOString()),r.mergedGitBranchName&&(a[ax]=encodeURIComponent(r.mergedGitBranchName)),a}var qW=S.object({entries:S.array(up),testId:S.string()}),KW=S.object({entries:S.array(wg),testId:S.string()}),YW=S.object({testId:S.string()});function dh(r){return S.record(S.unknown()).transform(e=>{let t={};for(let[n,o]of Object.entries(e)){let i=r.safeParse(o);i.success&&(t[n]=i.data)}return t})}var mh=dh(dp),ph=dh(Rg),gh=S.object({trigger:S.nativeEnum(Dt),status:S.nativeEnum(me),startedAt:S.coerce.date().optional(),gitCommitSha:S.string().optional(),gitCommitShaShort:S.string().optional(),gitCommitTimestamp:S.coerce.date().optional(),gitBranchName:S.string().optional(),gitOriginUrl:S.string().optional(),gitCommitMessage:S.string().optional(),gitCommitAuthorName:S.string().optional(),githubRepository:S.string().optional(),gitlabProjectPath:S.string().optional(),pipelineId:S.string().optional(),cliVersion:S.string().optional()}),XW=S.object({id:S.string()}),hh=S.object({status:S.nativeEnum(me),updatedAt:S.coerce.date().optional(),finishedAt:S.coerce.date().optional()}),fh=S.object({stepsSnapshot:S.array(S.record(S.unknown())).optional(),runGroupId:S.string().optional(),testId:S.string(),testName:S.string(),resolvedBaseUrl:S.string().optional(),environmentName:S.string().optional(),labels:S.array(S.string()).optional(),cliVersion:S.string().optional(),trigger:S.nativeEnum(Dt),schemaVersion:S.string().optional(),section:S.nativeEnum(_a).optional(),resolvedInputs:S.record(S.string(),S.string()).optional(),quarantined:S.boolean().optional().default(!1),quarantinedReason:S.string().optional()}),JW=S.object({id:S.string()}),lx=bc.pick({id:!0,status:!0,testName:!0,testId:!0,test:!0,failureReason:!0,failureDetails:!0}),Sh=lx.array(),Eh=bc.pick({startedAt:!0,finishedAt:!0,updatedAt:!0,results:!0,beforeResults:!0,afterResults:!0,status:!0,failureDetails:!0,failureReason:!0,resolvedBaseUrl:!0,environmentName:!0,labels:!0,cliVersion:!0,resolvedInputs:!0,attempts:!0,flake:!0}).partial(),QW=S.object({id:S.string()}),yh=S.object({status:S.nativeEnum(me),finishedAt:S.coerce.date().optional(),schemaVersion:S.string().optional().default("1.0.19"),results:S.record(S.string(),S.unknown()).array().optional(),beforeResults:S.record(S.string(),S.unknown()).array().optional(),afterResults:S.record(S.string(),S.unknown()).array().optional()}),ZW=S.object({screenshot:S.string()}),Th=S.object({key:S.string()}),bh=S.object({orgId:S.string(),userId:S.string()}),vh=S.array(Op),e$=S.record(S.string(),S.union([S.string(),S.boolean()])),t$=S.object({paths:S.string().array(),env:S.string().optional(),urlOverride:S.string().optional(),customHeaders:S.record(S.string(),S.string()).optional()}),Ah=S.object({suiteRunIds:S.string().array(),runGroupIds:S.string().array()}),r$=S.object({suiteRunIds:S.string().array()}),n$=Wp.array(),o$=S.object({runGroupIds:S.string().array()}),cx=S.object({uploadUrl:S.string()}),i$=it.merge(tg),a$=it.merge(ng),s$=it.merge(rg),ux=S.object({testId:S.string().optional().default(""),testName:S.string().optional().default(""),suiteId:S.string().optional().default(""),suiteName:S.string().optional().default(""),creditsUsed:S.number().optional()}),dx=S.object({transactionId:S.string(),timestamp:S.string(),event:S.nativeEnum(ui),properties:ux}),l$=dx.array(),wh=th.omit({steps:!0}).extend({steps:S.array(S.record(S.string(),S.unknown())).describe("unparsed ResolvedStep[]")}),c$=S.object({limit:S.number().max(10).optional(),afterTime:S.number().optional()}),Rh=Hp.array(),u$=S.object({applied:S.boolean().optional(),appliedAt:S.coerce.date().optional()}),Ch=cx.extend({id:S.string()}),d$=S.object({runGroupId:S.string().uuid().optional()}),xh=S.object({runGroupId:S.string().uuid()}),_h=S.object({quarantined:S.object({testId:S.string().uuid(),quarantinedAt:S.coerce.date(),quarantinedBy:S.string().optional(),quarantinedReason:S.string()}).array()}),m$=S.object({testId:S.string().uuid(),testName:S.string().optional(),reason:S.string(),gitLocalUsername:S.string().optional(),gitLocalEmail:S.string().optional(),gitLocalName:S.string().optional()}),p$=S.object({testName:S.string().optional(),reason:S.string().optional(),gitLocalUsername:S.string().optional(),gitLocalEmail:S.string().optional(),gitLocalName:S.string().optional()}),g$=it.merge(lg),h$=it.merge(cg),f$=S.object({apkToInstall:S.object({channel:S.string(),tag:S.string().optional()}).optional(),hostname:S.string().optional(),region:S.nativeEnum(pi).optional()}),Mh=S.object({name:S.string(),webRtcUrl:S.string(),adbUrl:S.string(),token:S.string(),apkDownloadUrl:S.string().optional(),region:S.string().optional()}),S$=S.object({channel:S.string(),tag:S.string(),md5:S.string()}),Ih=S.object({id:S.string(),uploadUrl:S.string().optional(),downloadUrl:S.string(),md5:S.string().optional()}),Ph=S.object({assets:S.array(S.object({channel:S.string(),tag:S.string(),md5:S.string(),createdAt:S.number().describe("Unix timestamp in milliseconds")}))});import{z as W}from"zod";var mx=3,T$=W.object({localTestId:W.string(),quarantinedAt:W.date(),quarantinedBy:W.string().optional(),quarantinedReason:W.string(),quarantinedByGitEmail:W.string().optional(),quarantinedByGitName:W.string().optional(),quarantinedByGitUsername:W.string().optional()}).or(W.object({cloudTestId:W.string(),quarantinedAt:W.date(),quarantinedBy:W.string().optional(),quarantinedReason:W.string(),quarantinedByGitEmail:W.string().optional(),quarantinedByGitName:W.string().optional(),quarantinedByGitUsername:W.string().optional()})),Oh=(t=>(t.QUARANTINE="QUARANTINE",t.UNQUARANTINE="UNQUARANTINE",t))(Oh||{});var Zc=W.object({name:W.string(),description:W.string().nullish(),effect:W.nativeEnum(Oh),labels:W.array(W.string()),githubRepository:W.string().nullish(),gitlabProjectPath:W.string().nullish(),gitBranchName:W.string().nullish()}),px=W.object({type:W.literal("LAST_N_RUNS"),lastN:W.number().min(mx).max(10)}),gx=W.object({type:W.literal("LAST_N_HOURS"),lastN:W.number().min(1).max(24)}),hx=W.object({type:W.literal("LAST_N_DAYS"),lastN:W.number().min(1).max(7)}),eu=W.discriminatedUnion("type",[px,gx,hx]),fx=W.object({flakeRateThreshold:W.number().min(1).max(100),evaluationWindow:eu}),Sx=Zc.extend({type:W.literal("FLAKE_RATE"),config:fx}),Ex=W.object({passRateThreshold:W.number().min(1).max(100),evaluationWindow:eu}),yx=Zc.extend({type:W.literal("PASS_RATE"),config:Ex}),Tx=W.object({failureCountThreshold:W.number().min(0),evaluationWindow:eu}),bx=Zc.extend({type:W.literal("FAILURE_COUNT"),config:Tx}),b$=W.discriminatedUnion("type",[Sx,yx,bx]);import{z as Fe}from"zod";var w$=Fe.object({repositoriesIndexed:Fe.boolean(),indexingInProgress:Fe.boolean(),indexesOutdated:Fe.boolean()}),Lh=(a=>(a.Queued="queued",a.InProgress="in_progress",a.Completed="completed",a.Waiting="waiting",a.Requested="requested",a.Pending="pending",a))(Lh||{}),Nh=(l=>(l.Success="success",l.Failure="failure",l.Neutral="neutral",l.Cancelled="cancelled",l.Skipped="skipped",l.TimedOut="timed_out",l.ActionRequired="action_required",l))(Nh||{}),R$=Fe.object({name:Fe.string(),status:Fe.nativeEnum(Lh),conclusion:Fe.nativeEnum(Nh).nullable()}),Ei=Fe.object({sha:Fe.string(),message:Fe.string(),author:Fe.object({name:Fe.string().optional(),email:Fe.string().optional(),date:Fe.coerce.date().optional()}),committer:Fe.object({name:Fe.string().optional(),email:Fe.string().optional(),date:Fe.coerce.date().optional()})}),tu=Fe.object({mergedBranch:Fe.string().optional()});import{z as xe}from"zod";var Dh=xe.object({orgId:xe.string(),cacheKeys:xe.string().array()}),_$=xe.object({keyParams:Dh,clientMetadata:xe.string(),lockAcquisitionTimeoutMs:xe.number().optional()}),kh=xe.object({acquired:xe.boolean(),acquiredByMetadata:xe.string(),keyPrefix:xe.string()}),M$=xe.object({keyPrefix:xe.string(),result:xe.string(),ttlMs:xe.number()}),I$=xe.union([xe.object({keyPrefix:xe.string()}),Dh]),vx=xe.object({remainingTtlMs:xe.number(),value:xe.string().nullish()}),P$=xe.object({results:xe.record(xe.string(),vx),activeLocks:xe.string().array()});var O$=5*60*1e3;var k$=90*24*60*60*1e3,U$=7*24*60*60*1e3;import{z as Uh}from"zod";var z$=Uh.object({quarantineNotifications:Uh.string().nullish()});import{z as tt}from"zod";var Ax=tt.object({version:tt.string(),json:tt.record(tt.unknown()),hash:tt.string()}),Fh=tt.record(tt.unknown()),j$=tt.object({newSvgs:tt.array(Ax),metadata:Fh.optional()}),wx=tt.object({version:tt.string(),json:tt.record(tt.unknown()).nullish(),hash:tt.string(),description:tt.string().nullish(),metadata:Fh.nullish()}),Bh=tt.record(tt.string().describe("icon hash"),wx);import{z as Oe}from"zod";var ru=Oe.object({assertion:Oe.string().describe("A human readable assertion that evaluates to either true or false depending on the state of the system.")}),Rx=Oe.object({instruction:Oe.string().describe("Human readable instruction to execute the step. Instructions should only describe concrete actions that need to be taken. Any checks or assertions should be described in the preConditions, postConditions, or expectedResults."),expectedResults:ru.array().optional().describe("Human readable description of the expected results after the step is executed. Each expected result should contain a single assertion that evaluates to true or false.")}),zh=Rx.extend({subSteps:Oe.lazy(()=>zh.array().optional()).describe("More granular steps to be take to achieve the current step's higher level objective.")}),Gh=Oe.object({name:Oe.string().describe("Short name describing the test plan"),description:Oe.string().nullish().transform(r=>r??void 0).describe("Longer form description of the high level goal of the test plan")}),Hh=Gh.extend({id:Oe.string(),createdAt:Oe.coerce.date(),updatedAt:Oe.coerce.date(),updatedBy:Oe.string(),createdBy:Oe.string(),test:Oe.object({id:Oe.string(),name:Oe.string()}).nullish().transform(r=>r??void 0)}),K$=Hh.extend({testGenRuns:Oe.tuple([]).or(Oe.tuple([Oe.object({id:Oe.string(),startedAt:Oe.coerce.date(),status:Oe.nativeEnum(me)})]))}),Vh=Oe.object({preConditions:ru.array().nullish().transform(r=>r??[]),postConditions:ru.array().nullish().transform(r=>r??[]),steps:zh.array().nullish().transform(r=>r??[])}),Y$=Hh.extend({plan:Vh.nullish().transform(r=>r??{preConditions:[],postConditions:[],steps:[]})}),Cx=Gh.extend({plan:Vh.nullish().transform(r=>r??{preConditions:[],postConditions:[],steps:[]})}),X$=Cx.array().nullish().transform(r=>r??[]);import{validator as xx}from"@exodus/schemasafe";function jh(r){let e;try{e=JSON.parse(r)}catch(t){return`The schema is not valid JSON. ${t}`}try{xx(e)}catch(t){return`The schema is not a valid JSON schema. ${t}`}}var Wh=r=>{r.extraHeaders&&(r.extraHeaders=Object.fromEntries(Object.entries(r.extraHeaders).filter(([e,t])=>e.trim()&&t.trim())))};var Xa=class{async prepareGoldenScreenshotForComparison(e,t,n){return n}};import{z as pq}from"zod";var Ja=class{async resolveEntries(){}async saveEntries(){}};var oo=class r{spans;parentSection;name;finished=!1;startTime;endTime;constructor(e,t){this.startTime=t?.startTime??Date.now(),this.spans=t?.subSpans??[],this.parentSection=t,this.name=e}startSection(e){let t={type:"SECTION",name:e,startTime:Date.now(),endTime:void 0,subSpans:[]};return new r(e,t)}finish(){if(!this.finished){this.endTime=Date.now();for(let e of this.spans)e.endTime||(e.endTime=this.endTime);this.parentSection&&(this.parentSection.endTime=this.endTime),this.finished=!0}}addSpan(e){this.spans.push(e)}startSpan(e,t){let n={type:e,startTime:Date.now(),endTime:void 0},o;try{o=t(n),n.endTime=Date.now()}catch(i){throw n.error=i instanceof Error?i.message:String(i),n.endTime=Date.now(),i}finally{this.addSpan(n)}return o}async startAsyncSpan(e,t){let n={type:e,startTime:Date.now(),endTime:void 0},o;try{o=await t(n),n.endTime=Date.now()}catch(i){throw n.error=i instanceof Error?i.message:String(i),n.endTime=Date.now(),i}finally{this.addSpan(n)}return o}getRootSpan(){return this.finished||this.finish(),{type:"SECTION",name:this.name,startTime:this.startTime,endTime:this.endTime,subSpans:this.spans}}};import{z as j}from"zod";var _x=j.object({step:$e,status:j.nativeEnum(et),startedAt:j.coerce.date(),finishedAt:j.coerce.date().optional(),healMetadata:j.object({healType:j.nativeEnum(oi).or(j.literal("AI")),healedAt:j.coerce.date()}).optional(),beforeSnapshotId:j.string().uuid().optional(),afterSnapshotId:j.string().uuid().optional(),message:j.string().optional()}),Iq=_x.extend({finishedAt:j.coerce.date().optional().transform(r=>r??new Date)}),qh="1.0.0",nu=yh.extend({id:j.string().uuid().optional(),startedAt:j.coerce.date(),runAttemptSchemaVersion:j.string().optional(),schemaVersion:j.string().optional().default("1.0.19"),results:j.record(j.string(),j.unknown()).array().optional(),beforeResults:j.record(j.string(),j.unknown()).array().optional(),afterResults:j.record(j.string(),j.unknown()).array().optional()}),Kh=nu.extend({finishedAt:j.coerce.date().optional().transform(r=>r??new Date)}),Pq=nu.merge(ii),Oq=Kh.merge(ii),Yh=j.object({results:j.array(eo),beforeResults:j.array(eo).optional(),afterResults:j.array(eo).optional()}),Lq=nu.merge(Yh),Nq=Kh.merge(Yh),Mx=Eh.merge(fh).extend({executionType:j.nativeEnum(Kn).optional().default("WEB"),testId:j.string().uuid(),testDescription:j.string().optional(),runGroupId:j.string().uuid(),status:j.nativeEnum(me),startedAt:j.coerce.date(),attempts:j.number(),failureRecoveryDetails:j.record(j.unknown()).optional()}),Dq=Mx.extend({finishedAt:j.coerce.date().optional().transform(r=>r??new Date)}),Ix=gh.merge(hh).extend({id:j.string().uuid().optional(),startedAt:j.coerce.date(),cliVersion:j.string(),labels:j.string().array().optional().default([])}),yi=Ix.extend({updatedAt:j.coerce.date().optional().transform(r=>r??new Date),finishedAt:j.coerce.date().optional().transform(r=>r??new Date)});import{fileURLToPath as Dx}from"url";var Qh,kx=Dx(import.meta.url),Ux=Ox(kx);Qh=Nx(Ux,"..");var Ti=Qh;w.info(`Setting APPIUM_HOME to ${Ti}`);process.env.APPIUM_HOME=Ti;var Fx="If you do not have Java installed, please download the JDK 24 from https://www.oracle.com/java/technologies/downloads/, move it to your home directory, and then set the JAVA_HOME environment variable in your shell profile to the JDK path.",Bx="If you do not have Android Studio installed, please download it first from https://developer.android.com/studio and then follow all setup instructions in the Android Studio app.",zx="Follow the instructions at https://developer.android.com/tools/variables to set the ANDROID_HOME environment variable.",Zh="On Mac OS, the SDK is typically installed at /Users/<username>/Library/Android/sdk.",ef="On Windows, the SDK is typically installed at C:\\Users\\<username>\\AppData\\Local\\Android\\Sdk.";function Gx(){if(!process.env.JAVA_HOME)w.warn("JAVA_HOME is not set. Some Appium drivers and Android tools may not work as expected.");else{process.platform==="darwin"&&/\.jdk\/?$/.test(process.env.JAVA_HOME)&&w.warn("JAVA_HOME appears to point at a *.jdk bundle, which is incorrect. The correct path should be formatted like '<bundle>/Contents/Home'.");let e=((t,n)=>Lx(t,"bin",process.platform==="win32"?`${n}.exe`:n))(process.env.JAVA_HOME,"java");Px(e)||w.warn(`JAVA_HOME does not appear to point to a valid Java installation: expected the 'java' binary to exist at ${e}`)}try{Xh("java --version",{stdio:"pipe",encoding:"utf-8"})||(w.error(`Could not find a Java installation. ${Fx}`),process.exit(1))}catch(r){w.error(`Got error while checking if the Java JDK is installed: ${r}`),process.exit(1)}}function Hx(){process.env.ANDROID_HOME||(w.error(`The ANDROID_HOME environment variable is not set. ${zx} ${Jh()==="darwin"?Zh:ef}`),process.exit(1))}function Vx(){let r=process.env.ANDROID_HOME?`${process.env.ANDROID_HOME}/platform-tools/adb`:"adb";try{Xh(`${r} version`,{stdio:"pipe",encoding:"utf-8"})||(w.error(`Could not find the Android Debug Bridge (ADB) tool locally. This tool is included with Android Studio. ${Bx} Finally, ensure that the 'adb' command is available in your shell. ${Jh()==="darwin"?Zh:ef}`),process.exit(1))}catch(e){w.error(`Got error while checking if ADB is installed: ${e}`),process.exit(1)}}function tf(){Gx(),Hx(),Vx()}import{Server as RN}from"socket.io";import{randomUUID as e_}from"crypto";import{faker as jx}from"@faker-js/faker";import Wx from"assert";import $x from"axios";import*as qx from"child_process";import Kx from"moment";import*as Yx from"otpauth";import Xx from"pg";var Fr=class extends Error{constructor(e){super(e),this.name="TimeoutError"}};var rf=r=>{let e=r.reason===void 0?new DOMException("This operation was aborted.","AbortError"):r.reason;return e instanceof Error?e:new DOMException(e,"AbortError")};function B(r,e){let{milliseconds:t,fallback:n,message:o,customTimers:i={setTimeout,clearTimeout}}=e,a,l;if(typeof t!="number"||Math.sign(t)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${t}\``);return new Promise((c,s)=>{if(e.signal){let{signal:d}=e;if(d.aborted)return s(rf(d));l=()=>s(rf(d)),d.addEventListener("abort",l)}let u=()=>{if(n)try{c(n())}catch(d){s(d)}else{typeof r.cancel=="function"&&Promise.resolve().then(()=>r.cancel()).catch(()=>{});let d=o instanceof Error?o:new Fr(o??`Promise timed out after ${t}ms`);s(d)}};a=i.setTimeout(u,t),Promise.resolve(r).then(d=>c(d)).catch(d=>s(d))}).finally(()=>{i.clearTimeout(a),e.signal&&l&&e.signal.removeEventListener("abort",l)})}async function nf(r){let e;try{e=new URL(r.url).hostname}catch{}let t=[];return r.headers.getSetCookie()?.forEach(n=>{let o=Na(n,e);t.push(...o)}),t}function Jx(r,e){if(!r&&!e)return;let t;if(r){let{url:o,options:i}=r;t=new Request(o,i)}let n;if(e){let{body:o,options:i}=e;n=new Response(o??null,i)}return{request:t,response:n}}async function Qx(r,e){switch(r){case"RAW":return e;case"RESPONSE":if(e instanceof Response){let t=[];return e.headers.forEach((o,i)=>{t.push([i,o])}),{status:e.status,headers:t,body:await e.text()}}else throw new Error("Result is not a Response object")}}var Zx=Object.getPrototypeOf(async function(){}).constructor;async function of(r,e,t){let n=e.code;e.options.fragment&&(n=`return ${e.code}`);let{env:o,additionalBindings:i,request:a,response:l}=e.bindings,c=e.tools,s={},u=(v,R)=>{o[v]=R,s[v]=R},d={},m=(v,R)=>{o[v]=R,d[v]=R},p;n.includes("Octokit")&&(p=(await import("@octokit/rest")).Octokit);let g;n.includes("createAppAuth")&&(g=(await import("@octokit/auth-app")).createAppAuth);let h=async()=>await Promise.resolve(new Zx("axios","moment","faker","assert","pg","Octokit","createAppAuth","OTPAuth","child_process","extractCookiesFromResponse","env","setVariable","setPersistentVariable","sendSms","waitForLatestSms","email","sms","ai","mock",...Object.keys(i??{}),n)($x,Kx,c.fakerInstance??jx,Wx,Xx,p,g,Yx,qx,nf,o,e.options.disallowVariableUpdates?void 0:u,e.options.disallowVariableUpdates?void 0:m,R=>c.sms.send(R),R=>c.sms.fetchLatest(R),c.email,c.sms,c.ai,Jx(a,l),...Object.values(i??{}))),f=!0,y,T;try{let v=await B(h(),{milliseconds:e.options.timeoutMs,message:`Timeout of ${e.options.timeoutMs}ms exceeded for code execution`,signal:e.signal});y=await Qx(e.options.responseSerialization??"RAW",v)}catch(v){t.error({err:v,env:o,evalCode:n},`[${r}] Error executing code: ${v}`),f=!1,v instanceof Fr?T=`Timeout of ${e.options.timeoutMs}ms exceeded for code execution`:T=v instanceof Error?v.message:`${v}`}return{result:y,variableUpdates:s,persistentVariableUpdates:d,success:f,error:T}}async function af({code:r,fragment:e,context:t,localTools:n,logger:o,signal:i,timeoutMs:a=Lr,disallowVariableUpdates:l,additionalBindings:c,responseSerialization:s,mock:u}){let d=e_(),m=await of(d,{code:r,options:{fragment:e,timeoutMs:a,disallowVariableUpdates:l,responseSerialization:s},bindings:{...t.toObjectCopy(),...u,additionalBindings:c},tools:n,signal:i},o);return w.debug(`[${d}] Got execution result: ${JSON.stringify(m)}`),m}import{createHmac as t_,randomUUID as r_}from"crypto";import n_ from"fetch-retry";var o_=n_(global.fetch,{retries:3,retryOn:function(r,e,t){return!!(e!==null||t&&t.status>=500)},retryDelay:function(r){return Math.pow(2,r)*500}}),sf=process.env.GCP_JS_EVAL_FUNCTION_ENDPOINT,lf=process.env.MOMENTIC_LAMBDA_AUTH_SECRET;async function cf({orgId:r,code:e,fragment:t,context:n,timeoutMs:o=Lr,retries:i=2,signal:a,logger:l,additionalBindings:c,disallowVariableUpdates:s,responseSerialization:u,mock:d}){if(!sf)throw new Error("GCP_JS_EVAL_FUNCTION_ENDPOINT environment variable not set");let m,p,g=0;if(!lf)throw new Error("Missing lambda auth secret.");let h=t_("sha256",lf).update(r).digest("hex");for(;g<=i;){g++,a?.throwIfAborted();let y={id:r_(),orgId:r,momenticLambdaAuthHash:h,code:e,fragment:t,state:{...n.toObjectCopy(),...d,additionalBindings:c},timeoutMs:o,disallowVariableUpdates:s,responseSerialization:u};try{if(m=await B(o_(sf,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(y)}),{milliseconds:o,message:`Timeout of ${o}ms exceeded for code execution`,signal:a}),!m)throw new Error("Got empty response from code evaluation server");if(!m.ok)throw new Error(`Code evaluation server returned error code ${m.status}`);p=void 0;break}catch(T){p=T}}if(p)throw l.error({err:p},"Failed to evaluate code remotely"),p;if(!m)throw new Error(`An unexpected code evaluation error occurred${p?`: ${p}`:""}`);let f;try{f=Og.parse(await m.json())}catch(y){throw new Error(`Code evaluation server returned invalid response: ${y}`)}if(f.error)throw new Error(`Code evaluation error: ${f.error}`);return f}async function Br(r){let e;if(process.env.GCP_JS_EVAL_FUNCTION_ENDPOINT)e=await cf(r);else if(r.localTools)e=await af({...r,localTools:r.localTools});else throw new Error("No code evaluation environment available");if(e.error){let t=`Failed to evaluate code:
9
+ `)),console.log(" ",t(l))}}getLevel(){return ps[this.minLogLevel]}setMinLevel(e){typeof e=="string"?this.minLogLevel=Ii[e]:this.minLogLevel=e}log(...e){this.logWithLevel(30,cr.reset,...e)}info(...e){this.logWithLevel(30,cr.white,...e)}debug(...e){this.logWithLevel(20,cr.dim,...e)}warn(...e){this.logWithLevel(40,cr.yellow,...e)}error(...e){this.logWithLevel(50,cr.red,...e)}success(...e){this.logWithLevel(1/0,cr.green,...e)}dimmed(...e){this.logWithLevel(30,cr.dim,...e)}underline(...e){this.logWithLevel(40,cr.underline,...e)}bold(...e){this.logWithLevel(40,cr.bold,...e)}grey(...e){this.logWithLevel(20,cr.grey,...e)}child(e){return new r(this.minLogLevel,{...this.logBindings,...e})}flush(){}bindings(){return this.logBindings}},hu=class{debug(){}info(){}warn(){}error(){}success(){}dimmed(){}underline(){}bold(){}grey(){}child(){return this}getLevel(){return"error"}flush(){}bindings(){return{}}},d$=new hu,Qx=typeof window>"u"&&typeof process<"u"&&ds.safeParse(process?.env?.MOMENTIC_DEV_LOG_LEVEL).success?ds.parse(process.env.MOMENTIC_DEV_LOG_LEVEL):30,R=new gu(Qx,{}),bn={info:()=>{},error:()=>{},debug:()=>{},warn:()=>{},child:()=>bn,flush:()=>{},bindings:()=>({}),getLevel:()=>"error"},us={},ms=({logger:r,logKey:e,maxCount:t,intervalMs:n},o,i,...a)=>{let l=us[e];l?clearTimeout(l.timer):(l={count:0,totalCount:0},us[e]=l),l.totalCount++,l.count<t&&(l.count++,r.debug(o,i,...a)),l.timer=setTimeout(()=>{let c=us[e];c?.totalCount!==c?.count&&r.debug({logKey:e,totalCount:c?.totalCount,count:c?.count},`Debug logs were rate-limited for ${e}`),delete us[e]},n)};import{z as ce}from"zod";var Zx=ce.array(ho.extend({id:ce.string(),name:ce.string(),description:ce.string().optional(),labels:ce.string().array().optional()})),e_=ce.array(ho.extend({id:ce.string(),name:ce.string(),description:ce.string().optional(),content:mi})),wh=ce.object({name:ce.string(),description:ce.string().optional(),settings:_i.optional(),pathSegments:ce.string().array()}),S$=ce.object({id:ce.string(),fileName:ce.string(),fullPath:ce.string(),relativeFilePath:ce.string().describe("relative to project root")});var Ch=ce.object({steps:xi.array().optional(),settings:_i.optional()}),y$=ce.object({message:ce.literal("ok")}),xh=ce.object({tag:ce.string(),channel:ce.string(),filePath:ce.string()}),E$=ce.object({tests:Zx,modules:e_,labels:ce.string().array()}),_h=ce.object({name:ce.string(),description:ce.string(),enabled:ce.boolean()}).partial();import{z as Fe}from"zod";var Mh=Fe.object({id:Fe.string(),createdAt:Fe.coerce.date(),createdBy:Fe.string(),organizationId:Fe.string(),name:Fe.string(),description:Fe.string().nullish(),enabled:Fe.boolean(),schemaVersion:Fe.string().describe("Schema version for steps"),parameters:Fe.string().array().nullish().describe("Parameter list"),parameterEnums:Fe.record(Fe.string(),Fe.string().array()).nullish(),defaultParameters:Fe.record(Fe.string(),Fe.string()).nullish(),defaultCacheKey:Fe.string().nullish(),defaultCacheTtl:Fe.number().nullish(),defaultCacheAllInvocations:Fe.boolean().nullish(),autoAuth:Fe.boolean().nullish(),advanced:_c.nullish()}),_$=Mh.extend({steps:Fe.lazy(()=>ht.array())}),M$=5*60*1e3,t_=Nt.merge(Mh.omit({id:!0,createdAt:!0,createdBy:!0,organizationId:!0,enabled:!0}));import{formatInTimeZone as O$}from"date-fns-tz";import{z as Ee}from"zod";var fu=Hc.extend({aiAction:Ee.boolean().optional(),stepLintSuggestions:Ee.boolean().optional(),agentConfig:Ee.record(Ee.string(),Ee.string()).optional(),aiFailureAnalysis:Ee.boolean().optional(),aiPageFiltering:Ee.boolean().optional().describe("rag v2 feature flag")}),Su=Ee.object({fakerConstantSeed:Ee.boolean().optional()}),F$=Ee.object({ai:fu.optional(),githubAppInstallationId:Ee.number().nullish(),githubAppSummaryMessageEnabled:Ee.boolean().nullish(),githubReleaseAppInstallationId:Ee.number().nullish(),gitlabAppAccessToken:Ee.string().nullish(),gitlabAppBaseUrl:Ee.string().nullish(),qaseAccessToken:Ee.string().nullish(),testSuggestionsEnabled:Ee.boolean().nullish(),browser:Nc.optional(),advanced:Su.optional()}),B$=Ee.object({globalOverrides:Ee.record(Ee.string()).optional(),agentConfig:Ee.record(Ee.string(),Ee.string()).optional()}),z$=Ee.record(Ee.string(),Ee.string()).nullish();import*as S from"zod";import{z as Ne}from"zod";var yu=(e=>(e.TEST_REVIEW="TEST_REVIEW",e))(yu||{});var r_=Ne.object({type:Ne.literal("DESCRIPTION_UPDATE"),thoughts:Ne.string()}),gs=Ne.discriminatedUnion("type",[r_]),n_=Ne.object({testId:Ne.string(),name:Ne.string(),orgId:Ne.string(),runId:Ne.string(),steps:Ke.array(),purpose:Ne.nativeEnum(yu),details:gs.or(gs.array()).optional()});var j$=n_.pick({name:!0,orgId:!0}),o_=Ne.object({id:Ne.string(),name:Ne.string().nullish(),createdAt:Ne.string().pipe(Ne.coerce.date()).or(Ne.date()),organizationId:Ne.string(),schemaVersion:Ne.string(),runId:Ne.string().nullish(),purpose:Ne.nativeEnum(yu),details:gs.or(gs.array()).optional(),applied:Ne.boolean().nullish(),appliedAt:Ne.coerce.date().nullish()}),Ih=o_.extend({steps:Ke.array()});var Ph="x-momentic-cli-version",Oh="x-momentic-cli-type",i_="x-momentic-main-branch-name",a_="x-momentic-branch-name",s_="x-momentic-commit-timestamp",l_="x-momentic-last-commit-on-main",c_="x-momentic-last-commit-on-main-timestamp",u_="x-momentic-merged-branch-name";var sq=S.object({error:S.boolean(),reason:S.string(),message:S.string()}),lq=st.merge(Wc),Lh=Da,cq=st.merge(Wc);var uq=st.merge(wg).extend({useConsensus:S.boolean().optional(),attemptNumber:S.number().optional()}),Eu=Cm,dq=st.merge(xg),Nh=Km,pq=st.merge(Cg),Dh=qm,mq=st.merge(vg),kh=Wm,gq=st.merge(Ag),Uh=Vm,hq=st.merge(Rg);var fq=st.merge(Pg),Sq=S.object({testPaths:S.string().array().describe("can be either hyphenated, lowercase test names or UUIDs"),env:S.string().optional(),all:S.boolean().optional(),urlOverride:S.string().optional(),customHeaders:S.record(S.string(),S.string()).optional(),testInputMatrix:S.record(S.string(),S.string()).array().optional()}),Fh=S.object({queuedTests:S.unknown().array(),runIds:S.string().uuid().array(),runGroupId:S.string().optional()});var yq=S.string().array(),Eq=S.union([S.object({paths:S.string().array().describe("run specific test paths (e.g. todo-test)"),all:S.boolean().describe("run all tests").optional()}),S.object({path:S.string().describe("deprecated; present for backcompat")})]),Bh=S.object({tests:S.record(S.string().describe("Test name"),S.string().describe("Test YAML")),modules:S.record(S.string().describe("Module name"),S.string().describe("Module YAML"))}),d_=S.object({test:S.string().describe("test YAML"),modules:S.record(S.string().describe("moduleId"),S.string().describe("module YAML"))}),bq=d_.array(),Tq=S.object({testId:S.string(),schemaVersion:S.string()}).merge(cn);function bu(r){let{gitMainBranch:e,gitBranchName:t,gitCommitTimestamp:n,lastCommitOnMainSha:o,lastCommitOnMainTimestamp:i}=r,a={};return e&&(a[i_]=encodeURIComponent(e)),t&&(a[a_]=encodeURIComponent(t)),n&&(a[s_]=n.toISOString()),o&&(a[l_]=encodeURIComponent(o)),i&&(a[c_]=i.toISOString()),r.mergedGitBranchName&&(a[u_]=encodeURIComponent(r.mergedGitBranchName)),a}var vq=S.object({entries:S.array(Um),testId:S.string()}),Aq=S.object({entries:S.array(Jg),testId:S.string()}),Rq=S.object({testId:S.string()});function zh(r){return S.record(S.unknown()).transform(e=>{let t={};for(let[n,o]of Object.entries(e)){let i=r.safeParse(o);i.success&&(t[n]=i.data)}return t})}var Gh=zh(Fm),Hh=zh(Qg),Vh=S.object({trigger:S.nativeEnum(Ut),status:S.nativeEnum(me),startedAt:S.coerce.date().optional(),gitCommitSha:S.string().optional(),gitCommitShaShort:S.string().optional(),gitCommitTimestamp:S.coerce.date().optional(),gitBranchName:S.string().optional(),gitOriginUrl:S.string().optional(),gitCommitMessage:S.string().optional(),gitCommitAuthorName:S.string().optional(),githubRepository:S.string().optional(),gitlabProjectPath:S.string().optional(),pipelineId:S.string().optional(),cliVersion:S.string().optional()}),wq=S.object({id:S.string()}),jh=S.object({status:S.nativeEnum(me),updatedAt:S.coerce.date().optional(),finishedAt:S.coerce.date().optional()}),Wh=S.object({stepsSnapshot:S.array(S.record(S.unknown())).optional(),runGroupId:S.string().optional(),testId:S.string(),testName:S.string(),resolvedBaseUrl:S.string().optional(),environmentName:S.string().optional(),labels:S.array(S.string()).optional(),cliVersion:S.string().optional(),trigger:S.nativeEnum(Ut),schemaVersion:S.string().optional(),section:S.nativeEnum(ja).optional(),resolvedInputs:S.record(S.string(),S.string()).optional(),quarantined:S.boolean().optional().default(!1),quarantinedReason:S.string().optional()}),Cq=S.object({id:S.string()}),p_=Vc.pick({id:!0,status:!0,testName:!0,testId:!0,test:!0,failureReason:!0,failureDetails:!0}),$h=p_.array(),qh=Vc.pick({startedAt:!0,finishedAt:!0,updatedAt:!0,results:!0,beforeResults:!0,afterResults:!0,status:!0,failureDetails:!0,failureReason:!0,resolvedBaseUrl:!0,environmentName:!0,labels:!0,cliVersion:!0,resolvedInputs:!0,attempts:!0,flake:!0}).partial(),xq=S.object({id:S.string()}),Kh=S.object({status:S.nativeEnum(me),finishedAt:S.coerce.date().optional(),schemaVersion:S.string().optional().default("1.0.19"),results:S.record(S.string(),S.unknown()).array().optional(),beforeResults:S.record(S.string(),S.unknown()).array().optional(),afterResults:S.record(S.string(),S.unknown()).array().optional()}),_q=S.object({screenshot:S.string()}),Yh=S.object({key:S.string()}),Xh=S.object({orgId:S.string(),userId:S.string()}),Jh=S.array(ig),Mq=S.record(S.string(),S.union([S.string(),S.boolean()])),Iq=S.object({paths:S.string().array(),env:S.string().optional(),urlOverride:S.string().optional(),customHeaders:S.record(S.string(),S.string()).optional()}),Qh=S.object({suiteRunIds:S.string().array(),runGroupIds:S.string().array()}),Pq=S.object({suiteRunIds:S.string().array()}),Oq=yg.array(),Lq=S.object({runGroupIds:S.string().array()}),m_=S.object({uploadUrl:S.string()}),Nq=st.merge(_g),Dq=st.merge(Ig),kq=st.merge(Mg),g_=S.object({testId:S.string().optional().default(""),testName:S.string().optional().default(""),suiteId:S.string().optional().default(""),suiteName:S.string().optional().default(""),creditsUsed:S.number().optional()}),h_=S.object({transactionId:S.string(),timestamp:S.string(),event:S.nativeEnum(Ti),properties:g_}),Uq=h_.array(),Zh=Ih.omit({steps:!0}).extend({steps:S.array(S.record(S.string(),S.unknown())).describe("unparsed ResolvedStep[]")}),Fq=S.object({limit:S.number().max(10).optional(),afterTime:S.number().optional()}),ef=hg.array(),Bq=S.object({applied:S.boolean().optional(),appliedAt:S.coerce.date().optional()}),tf=m_.extend({id:S.string()}),zq=S.object({runGroupId:S.string().uuid().optional()}),rf=S.object({runGroupId:S.string().uuid()}),nf=S.object({quarantined:S.object({testId:S.string().uuid(),quarantinedAt:S.coerce.date(),quarantinedBy:S.string().optional(),quarantinedReason:S.string()}).array()}),Gq=S.object({testId:S.string().uuid(),testName:S.string().optional(),reason:S.string(),gitLocalUsername:S.string().optional(),gitLocalEmail:S.string().optional(),gitLocalName:S.string().optional()}),Hq=S.object({testName:S.string().optional(),reason:S.string().optional(),gitLocalUsername:S.string().optional(),gitLocalEmail:S.string().optional(),gitLocalName:S.string().optional()}),Vq=st.merge(Dg),jq=st.merge(kg),Wq=S.object({apkToInstall:S.object({channel:S.string(),tag:S.string().optional()}).optional(),hostname:S.string().optional(),region:S.nativeEnum(Ai).optional()}),of=S.object({name:S.string(),webRtcUrl:S.string(),adbUrl:S.string(),token:S.string(),apkDownloadUrl:S.string().optional(),region:S.string().optional()}),$q=S.object({channel:S.string(),tag:S.string(),md5:S.string()}),af=S.object({id:S.string(),uploadUrl:S.string().optional(),downloadUrl:S.string(),md5:S.string().optional()}),sf=S.object({assets:S.array(S.object({channel:S.string(),tag:S.string(),md5:S.string(),createdAt:S.number().describe("Unix timestamp in milliseconds")}))});import{z as W}from"zod";var f_=3,Yq=W.object({localTestId:W.string(),quarantinedAt:W.date(),quarantinedBy:W.string().optional(),quarantinedReason:W.string(),quarantinedByGitEmail:W.string().optional(),quarantinedByGitName:W.string().optional(),quarantinedByGitUsername:W.string().optional()}).or(W.object({cloudTestId:W.string(),quarantinedAt:W.date(),quarantinedBy:W.string().optional(),quarantinedReason:W.string(),quarantinedByGitEmail:W.string().optional(),quarantinedByGitName:W.string().optional(),quarantinedByGitUsername:W.string().optional()})),lf=(t=>(t.QUARANTINE="QUARANTINE",t.UNQUARANTINE="UNQUARANTINE",t))(lf||{});var Tu=W.object({name:W.string(),description:W.string().nullish(),effect:W.nativeEnum(lf),labels:W.array(W.string()),githubRepository:W.string().nullish(),gitlabProjectPath:W.string().nullish(),gitBranchName:W.string().nullish()}),S_=W.object({type:W.literal("LAST_N_RUNS"),lastN:W.number().min(f_).max(10)}),y_=W.object({type:W.literal("LAST_N_HOURS"),lastN:W.number().min(1).max(24)}),E_=W.object({type:W.literal("LAST_N_DAYS"),lastN:W.number().min(1).max(7)}),vu=W.discriminatedUnion("type",[S_,y_,E_]),b_=W.object({flakeRateThreshold:W.number().min(1).max(100),evaluationWindow:vu}),T_=Tu.extend({type:W.literal("FLAKE_RATE"),config:b_}),v_=W.object({passRateThreshold:W.number().min(1).max(100),evaluationWindow:vu}),A_=Tu.extend({type:W.literal("PASS_RATE"),config:v_}),R_=W.object({failureCountThreshold:W.number().min(0),evaluationWindow:vu}),w_=Tu.extend({type:W.literal("FAILURE_COUNT"),config:R_}),Xq=W.discriminatedUnion("type",[T_,A_,w_]);import{z as Be}from"zod";var Zq=Be.object({repositoriesIndexed:Be.boolean(),indexingInProgress:Be.boolean(),indexesOutdated:Be.boolean()}),cf=(a=>(a.Queued="queued",a.InProgress="in_progress",a.Completed="completed",a.Waiting="waiting",a.Requested="requested",a.Pending="pending",a))(cf||{}),uf=(l=>(l.Success="success",l.Failure="failure",l.Neutral="neutral",l.Cancelled="cancelled",l.Skipped="skipped",l.TimedOut="timed_out",l.ActionRequired="action_required",l))(uf||{}),e2=Be.object({name:Be.string(),status:Be.nativeEnum(cf),conclusion:Be.nativeEnum(uf).nullable()}),Pi=Be.object({sha:Be.string(),message:Be.string(),author:Be.object({name:Be.string().optional(),email:Be.string().optional(),date:Be.coerce.date().optional()}),committer:Be.object({name:Be.string().optional(),email:Be.string().optional(),date:Be.coerce.date().optional()})}),Au=Be.object({mergedBranch:Be.string().optional()});import{z as _e}from"zod";var df=_e.object({orgId:_e.string(),cacheKeys:_e.string().array()}),n2=_e.object({keyParams:df,clientMetadata:_e.string(),lockAcquisitionTimeoutMs:_e.number().optional()}),pf=_e.object({acquired:_e.boolean(),acquiredByMetadata:_e.string(),keyPrefix:_e.string()}),o2=_e.object({keyPrefix:_e.string(),result:_e.string(),ttlMs:_e.number()}),i2=_e.union([_e.object({keyPrefix:_e.string()}),df]),C_=_e.object({remainingTtlMs:_e.number(),value:_e.string().nullish()}),a2=_e.object({results:_e.record(_e.string(),C_),activeLocks:_e.string().array()});var s2=5*60*1e3;var d2=90*24*60*60*1e3,p2=7*24*60*60*1e3;import{z as mf}from"zod";var h2=mf.object({quarantineNotifications:mf.string().nullish()});import{z as nt}from"zod";var x_=nt.object({version:nt.string(),json:nt.record(nt.unknown()),hash:nt.string()}),gf=nt.record(nt.unknown()),E2=nt.object({newSvgs:nt.array(x_),metadata:gf.optional()}),__=nt.object({version:nt.string(),json:nt.record(nt.unknown()).nullish(),hash:nt.string(),description:nt.string().nullish(),metadata:gf.nullish()}),hf=nt.record(nt.string().describe("icon hash"),__);import{z as Le}from"zod";var Ru=Le.object({assertion:Le.string().describe("A human readable assertion that evaluates to either true or false depending on the state of the system.")}),M_=Le.object({instruction:Le.string().describe("Human readable instruction to execute the step. Instructions should only describe concrete actions that need to be taken. Any checks or assertions should be described in the preConditions, postConditions, or expectedResults."),expectedResults:Ru.array().optional().describe("Human readable description of the expected results after the step is executed. Each expected result should contain a single assertion that evaluates to true or false.")}),ff=M_.extend({subSteps:Le.lazy(()=>ff.array().optional()).describe("More granular steps to be take to achieve the current step's higher level objective.")}),Sf=Le.object({name:Le.string().describe("Short name describing the test plan"),description:Le.string().nullish().transform(r=>r??void 0).describe("Longer form description of the high level goal of the test plan")}),yf=Sf.extend({id:Le.string(),createdAt:Le.coerce.date(),updatedAt:Le.coerce.date(),updatedBy:Le.string(),createdBy:Le.string(),test:Le.object({id:Le.string(),name:Le.string()}).nullish().transform(r=>r??void 0)}),A2=yf.extend({testGenRuns:Le.tuple([]).or(Le.tuple([Le.object({id:Le.string(),startedAt:Le.coerce.date(),status:Le.nativeEnum(me)})]))}),Ef=Le.object({preConditions:Ru.array().nullish().transform(r=>r??[]),postConditions:Ru.array().nullish().transform(r=>r??[]),steps:ff.array().nullish().transform(r=>r??[])}),R2=yf.extend({plan:Ef.nullish().transform(r=>r??{preConditions:[],postConditions:[],steps:[]})}),I_=Sf.extend({plan:Ef.nullish().transform(r=>r??{preConditions:[],postConditions:[],steps:[]})}),w2=I_.array().nullish().transform(r=>r??[]);import{validator as P_}from"@exodus/schemasafe";function bf(r){let e;try{e=JSON.parse(r)}catch(t){return`The schema is not valid JSON. ${t}`}try{P_(e)}catch(t){return`The schema is not a valid JSON schema. ${t}`}}var Tf=r=>{r.extraHeaders&&(r.extraHeaders=Object.fromEntries(Object.entries(r.extraHeaders).filter(([e,t])=>e.trim()&&t.trim())))};var hs=class{async prepareGoldenScreenshotForComparison(e,t,n){return n}};import{z as H2}from"zod";var fs=class{async resolveEntries(){}async saveEntries(){}};var fo=class r{spans;parentSection;name;finished=!1;startTime;endTime;constructor(e,t){this.startTime=t?.startTime??Date.now(),this.spans=t?.subSpans??[],this.parentSection=t,this.name=e}startSection(e){let t={type:"SECTION",name:e,startTime:Date.now(),endTime:void 0,subSpans:[]};return new r(e,t)}finish(){if(!this.finished){this.endTime=Date.now();for(let e of this.spans)e.endTime||(e.endTime=this.endTime);this.parentSection&&(this.parentSection.endTime=this.endTime),this.finished=!0}}addSpan(e){this.spans.push(e)}startSpan(e,t){let n={type:e,startTime:Date.now(),endTime:void 0},o;try{o=t(n),n.endTime=Date.now()}catch(i){throw n.error=i instanceof Error?i.message:String(i),n.endTime=Date.now(),i}finally{this.addSpan(n)}return o}async startAsyncSpan(e,t){let n={type:e,startTime:Date.now(),endTime:void 0},o;try{o=await t(n),n.endTime=Date.now()}catch(i){throw n.error=i instanceof Error?i.message:String(i),n.endTime=Date.now(),i}finally{this.addSpan(n)}return o}getRootSpan(){return this.finished||this.finish(),{type:"SECTION",name:this.name,startTime:this.startTime,endTime:this.endTime,subSpans:this.spans}}};import{z as j}from"zod";var O_=j.object({step:Ke,status:j.nativeEnum(Ye),startedAt:j.coerce.date(),finishedAt:j.coerce.date().optional(),healMetadata:j.object({healType:j.nativeEnum(hi).or(j.literal("AI")),healedAt:j.coerce.date()}).optional(),beforeSnapshotId:j.string().uuid().optional(),afterSnapshotId:j.string().uuid().optional(),message:j.string().optional()}),iK=O_.extend({finishedAt:j.coerce.date().optional().transform(r=>r??new Date)}),vf="1.0.0",Cu=Kh.extend({id:j.string().uuid().optional(),startedAt:j.coerce.date(),runAttemptSchemaVersion:j.string().optional(),schemaVersion:j.string().optional().default("1.0.19"),results:j.record(j.string(),j.unknown()).array().optional(),beforeResults:j.record(j.string(),j.unknown()).array().optional(),afterResults:j.record(j.string(),j.unknown()).array().optional()}),Af=Cu.extend({finishedAt:j.coerce.date().optional().transform(r=>r??new Date)}),aK=Cu.merge(fi),sK=Af.merge(fi),Rf=j.object({results:j.array(yn),beforeResults:j.array(yn).optional(),afterResults:j.array(yn).optional()}),lK=Cu.merge(Rf),cK=Af.merge(Rf),L_=qh.merge(Wh).extend({executionType:j.nativeEnum(ao).optional().default("WEB"),testId:j.string().uuid(),testDescription:j.string().optional(),runGroupId:j.string().uuid(),status:j.nativeEnum(me),startedAt:j.coerce.date(),attempts:j.number(),failureRecoveryDetails:j.record(j.unknown()).optional()}),uK=L_.extend({finishedAt:j.coerce.date().optional().transform(r=>r??new Date)}),N_=Vh.merge(jh).extend({id:j.string().uuid().optional(),startedAt:j.coerce.date(),cliVersion:j.string(),labels:j.string().array().optional().default([])}),Oi=N_.extend({updatedAt:j.coerce.date().optional().transform(r=>r??new Date),finishedAt:j.coerce.date().optional().transform(r=>r??new Date)});import{fileURLToPath as B_}from"url";var xf,z_=B_(import.meta.url),G_=k_(z_);xf=F_(G_,"..");var Li=xf;R.info(`Setting APPIUM_HOME to ${Li}`);process.env.APPIUM_HOME=Li;var H_="If you do not have Java installed, please download the JDK 24 from https://www.oracle.com/java/technologies/downloads/, move it to your home directory, and then set the JAVA_HOME environment variable in your shell profile to the JDK path.",V_="If you do not have Android Studio installed, please download it first from https://developer.android.com/studio and then follow all setup instructions in the Android Studio app.",j_="Follow the instructions at https://developer.android.com/tools/variables to set the ANDROID_HOME environment variable.",_f="On Mac OS, the SDK is typically installed at /Users/<username>/Library/Android/sdk.",Mf="On Windows, the SDK is typically installed at C:\\Users\\<username>\\AppData\\Local\\Android\\Sdk.";function W_(){if(!process.env.JAVA_HOME)R.warn("JAVA_HOME is not set. Some Appium drivers and Android tools may not work as expected.");else{process.platform==="darwin"&&/\.jdk\/?$/.test(process.env.JAVA_HOME)&&R.warn("JAVA_HOME appears to point at a *.jdk bundle, which is incorrect. The correct path should be formatted like '<bundle>/Contents/Home'.");let e=((t,n)=>U_(t,"bin",process.platform==="win32"?`${n}.exe`:n))(process.env.JAVA_HOME,"java");D_(e)||R.warn(`JAVA_HOME does not appear to point to a valid Java installation: expected the 'java' binary to exist at ${e}`)}try{wf("java --version",{stdio:"pipe",encoding:"utf-8"})||(R.error(`Could not find a Java installation. ${H_}`),process.exit(1))}catch(r){R.error(`Got error while checking if the Java JDK is installed: ${r}`),process.exit(1)}}function $_(){process.env.ANDROID_HOME||(R.error(`The ANDROID_HOME environment variable is not set. ${j_} ${Cf()==="darwin"?_f:Mf}`),process.exit(1))}function q_(){let r=process.env.ANDROID_HOME?`${process.env.ANDROID_HOME}/platform-tools/adb`:"adb";try{wf(`${r} version`,{stdio:"pipe",encoding:"utf-8"})||(R.error(`Could not find the Android Debug Bridge (ADB) tool locally. This tool is included with Android Studio. ${V_} Finally, ensure that the 'adb' command is available in your shell. ${Cf()==="darwin"?_f:Mf}`),process.exit(1))}catch(e){R.error(`Got error while checking if ADB is installed: ${e}`),process.exit(1)}}function If(){W_(),$_(),q_()}import{Server as KD}from"socket.io";import{randomUUID as oM}from"crypto";import{faker as K_}from"@faker-js/faker";import Y_ from"assert";import X_ from"axios";import*as J_ from"child_process";import Q_ from"moment";import*as Z_ from"otpauth";import eM from"pg";var qr=class extends Error{constructor(e){super(e),this.name="TimeoutError"}};var Pf=r=>{let e=r.reason===void 0?new DOMException("This operation was aborted.","AbortError"):r.reason;return e instanceof Error?e:new DOMException(e,"AbortError")};function B(r,e){let{milliseconds:t,fallback:n,message:o,customTimers:i={setTimeout,clearTimeout}}=e,a,l;if(typeof t!="number"||Math.sign(t)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${t}\``);return new Promise((c,s)=>{if(e.signal){let{signal:d}=e;if(d.aborted)return s(Pf(d));l=()=>s(Pf(d)),d.addEventListener("abort",l)}let u=()=>{if(n)try{c(n())}catch(d){s(d)}else{typeof r.cancel=="function"&&Promise.resolve().then(()=>r.cancel()).catch(()=>{});let d=o instanceof Error?o:new qr(o??`Promise timed out after ${t}ms`);s(d)}};a=i.setTimeout(u,t),Promise.resolve(r).then(d=>c(d)).catch(d=>s(d))}).finally(()=>{i.clearTimeout(a),e.signal&&l&&e.signal.removeEventListener("abort",l)})}async function Of(r){let e;try{e=new URL(r.url).hostname}catch{}let t=[];return r.headers.getSetCookie()?.forEach(n=>{let o=Xa(n,e);t.push(...o)}),t}function tM(r,e){if(!r&&!e)return;let t;if(r){let{url:o,options:i}=r;t=new Request(o,i)}let n;if(e){let{body:o,options:i}=e;n=new Response(o??null,i)}return{request:t,response:n}}async function rM(r,e){switch(r){case"RAW":return e;case"RESPONSE":if(e instanceof Response){let t=[];return e.headers.forEach((o,i)=>{t.push([i,o])}),{status:e.status,headers:t,body:await e.text()}}else throw new Error("Result is not a Response object")}}var nM=Object.getPrototypeOf(async function(){}).constructor;async function Lf(r,e,t){let n=e.code;e.options.fragment&&(n=`return ${e.code}`);let{env:o,additionalBindings:i,request:a,response:l}=e.bindings,c=e.tools,s={},u=(v,A)=>{o[v]=A,s[v]=A},d={},p=(v,A)=>{o[v]=A,d[v]=A},m;n.includes("Octokit")&&(m=(await import("@octokit/rest")).Octokit);let g;n.includes("createAppAuth")&&(g=(await import("@octokit/auth-app")).createAppAuth);let h=async()=>await Promise.resolve(new nM("axios","moment","faker","assert","pg","Octokit","createAppAuth","OTPAuth","child_process","extractCookiesFromResponse","env","setVariable","setPersistentVariable","sendSms","waitForLatestSms","email","sms","ai","mock",...Object.keys(i??{}),n)(X_,Q_,c.fakerInstance??K_,Y_,eM,m,g,Z_,J_,Of,o,e.options.disallowVariableUpdates?void 0:u,e.options.disallowVariableUpdates?void 0:p,A=>c.sms.send(A),A=>c.sms.fetchLatest(A),c.email,c.sms,c.ai,tM(a,l),...Object.values(i??{}))),f=!0,E,b;try{let v=await B(h(),{milliseconds:e.options.timeoutMs,message:`Timeout of ${e.options.timeoutMs}ms exceeded for code execution`,signal:e.signal});E=await rM(e.options.responseSerialization??"RAW",v)}catch(v){t.error({err:v,env:o,evalCode:n},`[${r}] Error executing code: ${v}`),f=!1,v instanceof qr?b=`Timeout of ${e.options.timeoutMs}ms exceeded for code execution`:b=v instanceof Error?v.message:`${v}`}return{result:E,variableUpdates:s,persistentVariableUpdates:d,success:f,error:b}}async function Nf({code:r,fragment:e,context:t,localTools:n,logger:o,signal:i,timeoutMs:a=Hr,disallowVariableUpdates:l,additionalBindings:c,responseSerialization:s,mock:u}){let d=oM(),p=await Lf(d,{code:r,options:{fragment:e,timeoutMs:a,disallowVariableUpdates:l,responseSerialization:s},bindings:{...t.toObjectCopy(),...u,additionalBindings:c},tools:n,signal:i},o);return R.debug(`[${d}] Got execution result: ${JSON.stringify(p)}`),p}import{createHmac as iM,randomUUID as aM}from"crypto";import sM from"fetch-retry";var lM=sM(global.fetch,{retries:3,retryOn:function(r,e,t){return!!(e!==null||t&&t.status>=500)},retryDelay:function(r){return Math.pow(2,r)*500}}),Df=process.env.GCP_JS_EVAL_FUNCTION_ENDPOINT,kf=process.env.MOMENTIC_LAMBDA_AUTH_SECRET;async function Uf({orgId:r,code:e,fragment:t,context:n,timeoutMs:o=Hr,retries:i=2,signal:a,logger:l,additionalBindings:c,disallowVariableUpdates:s,responseSerialization:u,mock:d}){if(!Df)throw new Error("GCP_JS_EVAL_FUNCTION_ENDPOINT environment variable not set");let p,m,g=0;if(!kf)throw new Error("Missing lambda auth secret.");let h=iM("sha256",kf).update(r).digest("hex");for(;g<=i;){g++,a?.throwIfAborted();let E={id:aM(),orgId:r,momenticLambdaAuthHash:h,code:e,fragment:t,state:{...n.toObjectCopy(),...d,additionalBindings:c},timeoutMs:o,disallowVariableUpdates:s,responseSerialization:u};try{if(p=await B(lM(Df,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(E)}),{milliseconds:o,message:`Timeout of ${o}ms exceeded for code execution`,signal:a}),!p)throw new Error("Got empty response from code evaluation server");if(!p.ok)throw new Error(`Code evaluation server returned error code ${p.status}`);m=void 0;break}catch(b){m=b}}if(m)throw l.error({err:m},"Failed to evaluate code remotely"),m;if(!p)throw new Error(`An unexpected code evaluation error occurred${m?`: ${m}`:""}`);let f;try{f=ih.parse(await p.json())}catch(E){throw new Error(`Code evaluation server returned invalid response: ${E}`)}if(f.error)throw new Error(`Code evaluation error: ${f.error}`);return f}async function ur(r){let e;if(process.env.GCP_JS_EVAL_FUNCTION_ENDPOINT)e=await Uf(r);else if(r.localTools)e=await Nf({...r,localTools:r.localTools});else throw new Error("No code evaluation environment available");if(e.error){let t=`Failed to evaluate code:
10
10
  ${e.error}
11
11
  Code received:
12
- ${r.code}`;throw r.logger.error({err:e.error,code:r.code,env:r.context.toObjectCopy()},t),new Error(t)}if(e.variableUpdates)for(let[t,n]of Object.entries(e.variableUpdates))r.context.setVariable(t,n);if(e.persistentVariableUpdates&&Object.keys(e.persistentVariableUpdates).length>0){await r.callbacks?.onPersistentVariableUpdates?.(e.persistentVariableUpdates);for(let[t,n]of Object.entries(e.persistentVariableUpdates))r.context.setVariable(t,n)}return e.result}import{set as i_}from"lodash-es";async function ou(r){let{orgId:e,s:t,context:n,logger:o,signal:i,retries:a=2,timeoutMs:l=Lr,allowUndefined:c=!1}=r,s=/{{(.*?)}}/g,u=t.matchAll(s),d=t;for(let m of u){if(m.length<2)continue;let p=m[1].trim(),g;try{g=await Br({orgId:e,code:p,fragment:!0,context:n,timeoutMs:l,logger:o,retries:a,localTools:r.localTools,signal:i})}catch(f){throw o.error({err:f,value:t},"Error evaluating template string"),f}if(g===void 0&&!c)throw new A("UserConfigurationError",`Template fragment '${p}' evaluated to undefined. Please ensure that the variable name is spelled correctly and it is only referenced after being assigned a value.`);let h=typeof g=="string"?g:`${g}`;h=h.replaceAll(/\$/g,"$$$$"),d=d.replace(m[0],h)}return d}async function Qa(r){return uf(r)}async function uf({obj:r,bannedKeys:e,allowList:t,context:n,prefixPath:o=[],replacements:i=[],...a}){for(let l in r){if(e.includes(l))continue;let c=!1;if(t)if(t.includes(l))c=!0;else continue;let s=r[l],u=[...o,l];if(typeof s=="string"&&s.includes("{{")){let d=await ou({s,context:n,...a});if(s===d)continue;i.push({path:u,original:s}),r[l]=d}else typeof s=="object"&&s!==null&&!Array.isArray(s)&&await uf({obj:s,bannedKeys:e,context:n,prefixPath:u,replacements:i,allowList:c?void 0:t,...a})}return i}function Za(r,e){for(let{path:t,original:n}of e)i_(r,t,n)}import a_ from"fetch-retry";var TY=process.env.MAILINATOR_API_KEY,bY=a_(global.fetch,{retryOn:function(r,e,t){return r>3?!1:!!(e!==null||t&&t.status>=400)},retryDelay:function(r){return 500}});import{randomUUID as pN}from"crypto";import{diff as gN}from"deep-object-diff";import{mkdirSync as hN}from"fs";import{cloneDeep as fN}from"lodash-es";var es=class{increment(e,t,n){}gauge(e,t){}distribution(e,t,n){}async flush(){}async recordDuration({fn:e}){return await e()}};function s_(r){if(!r||r.length===0)return{};let e={};for(let t of r){let n=t.indexOf(":");if(n>-1){let o=t.slice(0,n).trim(),i=t.slice(n+1).trim();o&&(e[o]=i);continue}e[t]=!0}return e}function ts(r,e){let t=s_(r);return!e||Object.keys(e).length===0?t:{...e,...t}}var Uf="=",is=";",fu=",";var Ff=8192;var lo={};Zv(lo,{getKeyPairs:()=>z_,parseKeyPairsIntoRecord:()=>G_,parsePairKeyValue:()=>Bf,serializeKeyPairs:()=>B_});he();var F_=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i};function B_(r){return r.reduce(function(e,t){var n=""+e+(e!==""?fu:"")+t;return n.length>Ff?e:n},"")}function z_(r){return r.getAllEntries().map(function(e){var t=F_(e,2),n=t[0],o=t[1],i=encodeURIComponent(n)+"="+encodeURIComponent(o.value);return o.metadata!==void 0&&(i+=is+o.metadata.toString()),i})}function Bf(r){var e=r.split(is);if(!(e.length<=0)){var t=e.shift();if(t){var n=t.indexOf(Uf);if(!(n<=0)){var o=decodeURIComponent(t.substring(0,n).trim()),i=decodeURIComponent(t.substring(n+1).trim()),a;return e.length>0&&(a=au(e.join(is))),{key:o,value:i,metadata:a}}}}}function G_(r){return typeof r!="string"||r.length===0?{}:r.split(fu).map(function(e){return Bf(e)}).filter(function(e){return e!==void 0&&e.value.length>0}).reduce(function(e,t){return e[t.key]=t.value,e},{})}he();var as;(function(r){r.AlwaysOff="always_off",r.AlwaysOn="always_on",r.ParentBasedAlwaysOff="parentbased_always_off",r.ParentBasedAlwaysOn="parentbased_always_on",r.ParentBasedTraceIdRatio="parentbased_traceidratio",r.TraceIdRatio="traceidratio"})(as||(as={}));var H_=",",V_=["OTEL_SDK_DISABLED"];function j_(r){return V_.indexOf(r)>-1}var W_=["OTEL_BSP_EXPORT_TIMEOUT","OTEL_BSP_MAX_EXPORT_BATCH_SIZE","OTEL_BSP_MAX_QUEUE_SIZE","OTEL_BSP_SCHEDULE_DELAY","OTEL_BLRP_EXPORT_TIMEOUT","OTEL_BLRP_MAX_EXPORT_BATCH_SIZE","OTEL_BLRP_MAX_QUEUE_SIZE","OTEL_BLRP_SCHEDULE_DELAY","OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT","OTEL_ATTRIBUTE_COUNT_LIMIT","OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT","OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT","OTEL_LOGRECORD_ATTRIBUTE_VALUE_LENGTH_LIMIT","OTEL_LOGRECORD_ATTRIBUTE_COUNT_LIMIT","OTEL_SPAN_EVENT_COUNT_LIMIT","OTEL_SPAN_LINK_COUNT_LIMIT","OTEL_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT","OTEL_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT","OTEL_EXPORTER_OTLP_TIMEOUT","OTEL_EXPORTER_OTLP_TRACES_TIMEOUT","OTEL_EXPORTER_OTLP_METRICS_TIMEOUT","OTEL_EXPORTER_OTLP_LOGS_TIMEOUT","OTEL_EXPORTER_JAEGER_AGENT_PORT"];function $_(r){return W_.indexOf(r)>-1}var q_=["OTEL_NO_PATCH_MODULES","OTEL_PROPAGATORS"];function K_(r){return q_.indexOf(r)>-1}var Su=1/0,Eu=128,Y_=128,X_=128,yu={OTEL_SDK_DISABLED:!1,CONTAINER_NAME:"",ECS_CONTAINER_METADATA_URI_V4:"",ECS_CONTAINER_METADATA_URI:"",HOSTNAME:"",KUBERNETES_SERVICE_HOST:"",NAMESPACE:"",OTEL_BSP_EXPORT_TIMEOUT:3e4,OTEL_BSP_MAX_EXPORT_BATCH_SIZE:512,OTEL_BSP_MAX_QUEUE_SIZE:2048,OTEL_BSP_SCHEDULE_DELAY:5e3,OTEL_BLRP_EXPORT_TIMEOUT:3e4,OTEL_BLRP_MAX_EXPORT_BATCH_SIZE:512,OTEL_BLRP_MAX_QUEUE_SIZE:2048,OTEL_BLRP_SCHEDULE_DELAY:5e3,OTEL_EXPORTER_JAEGER_AGENT_HOST:"",OTEL_EXPORTER_JAEGER_AGENT_PORT:6832,OTEL_EXPORTER_JAEGER_ENDPOINT:"",OTEL_EXPORTER_JAEGER_PASSWORD:"",OTEL_EXPORTER_JAEGER_USER:"",OTEL_EXPORTER_OTLP_ENDPOINT:"",OTEL_EXPORTER_OTLP_TRACES_ENDPOINT:"",OTEL_EXPORTER_OTLP_METRICS_ENDPOINT:"",OTEL_EXPORTER_OTLP_LOGS_ENDPOINT:"",OTEL_EXPORTER_OTLP_HEADERS:"",OTEL_EXPORTER_OTLP_TRACES_HEADERS:"",OTEL_EXPORTER_OTLP_METRICS_HEADERS:"",OTEL_EXPORTER_OTLP_LOGS_HEADERS:"",OTEL_EXPORTER_OTLP_TIMEOUT:1e4,OTEL_EXPORTER_OTLP_TRACES_TIMEOUT:1e4,OTEL_EXPORTER_OTLP_METRICS_TIMEOUT:1e4,OTEL_EXPORTER_OTLP_LOGS_TIMEOUT:1e4,OTEL_EXPORTER_ZIPKIN_ENDPOINT:"http://localhost:9411/api/v2/spans",OTEL_LOG_LEVEL:we.INFO,OTEL_NO_PATCH_MODULES:[],OTEL_PROPAGATORS:["tracecontext","baggage"],OTEL_RESOURCE_ATTRIBUTES:"",OTEL_SERVICE_NAME:"",OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT:Su,OTEL_ATTRIBUTE_COUNT_LIMIT:Eu,OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT:Su,OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT:Eu,OTEL_LOGRECORD_ATTRIBUTE_VALUE_LENGTH_LIMIT:Su,OTEL_LOGRECORD_ATTRIBUTE_COUNT_LIMIT:Eu,OTEL_SPAN_EVENT_COUNT_LIMIT:128,OTEL_SPAN_LINK_COUNT_LIMIT:128,OTEL_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT:Y_,OTEL_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT:X_,OTEL_TRACES_EXPORTER:"",OTEL_TRACES_SAMPLER:as.ParentBasedAlwaysOn,OTEL_TRACES_SAMPLER_ARG:"",OTEL_LOGS_EXPORTER:"",OTEL_EXPORTER_OTLP_INSECURE:"",OTEL_EXPORTER_OTLP_TRACES_INSECURE:"",OTEL_EXPORTER_OTLP_METRICS_INSECURE:"",OTEL_EXPORTER_OTLP_LOGS_INSECURE:"",OTEL_EXPORTER_OTLP_CERTIFICATE:"",OTEL_EXPORTER_OTLP_TRACES_CERTIFICATE:"",OTEL_EXPORTER_OTLP_METRICS_CERTIFICATE:"",OTEL_EXPORTER_OTLP_LOGS_CERTIFICATE:"",OTEL_EXPORTER_OTLP_COMPRESSION:"",OTEL_EXPORTER_OTLP_TRACES_COMPRESSION:"",OTEL_EXPORTER_OTLP_METRICS_COMPRESSION:"",OTEL_EXPORTER_OTLP_LOGS_COMPRESSION:"",OTEL_EXPORTER_OTLP_CLIENT_KEY:"",OTEL_EXPORTER_OTLP_TRACES_CLIENT_KEY:"",OTEL_EXPORTER_OTLP_METRICS_CLIENT_KEY:"",OTEL_EXPORTER_OTLP_LOGS_CLIENT_KEY:"",OTEL_EXPORTER_OTLP_CLIENT_CERTIFICATE:"",OTEL_EXPORTER_OTLP_TRACES_CLIENT_CERTIFICATE:"",OTEL_EXPORTER_OTLP_METRICS_CLIENT_CERTIFICATE:"",OTEL_EXPORTER_OTLP_LOGS_CLIENT_CERTIFICATE:"",OTEL_EXPORTER_OTLP_PROTOCOL:"http/protobuf",OTEL_EXPORTER_OTLP_TRACES_PROTOCOL:"http/protobuf",OTEL_EXPORTER_OTLP_METRICS_PROTOCOL:"http/protobuf",OTEL_EXPORTER_OTLP_LOGS_PROTOCOL:"http/protobuf",OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE:"cumulative"};function J_(r,e,t){if(!(typeof t[r]>"u")){var n=String(t[r]);e[r]=n.toLowerCase()==="true"}}function Q_(r,e,t,n,o){if(n===void 0&&(n=-1/0),o===void 0&&(o=1/0),typeof t[r]<"u"){var i=Number(t[r]);isNaN(i)||(i<n?e[r]=n:i>o?e[r]=o:e[r]=i)}}function Z_(r,e,t,n){n===void 0&&(n=H_);var o=t[r];typeof o=="string"&&(e[r]=o.split(n).map(function(i){return i.trim()}))}var eM={ALL:we.ALL,VERBOSE:we.VERBOSE,DEBUG:we.DEBUG,INFO:we.INFO,WARN:we.WARN,ERROR:we.ERROR,NONE:we.NONE};function tM(r,e,t){var n=t[r];if(typeof n=="string"){var o=eM[n.toUpperCase()];o!=null&&(e[r]=o)}}function zf(r){var e={};for(var t in yu){var n=t;switch(n){case"OTEL_LOG_LEVEL":tM(n,e,r);break;default:if(j_(n))J_(n,e,r);else if($_(n))Q_(n,e,r);else if(K_(n))Z_(n,e,r);else{var o=r[n];typeof o<"u"&&o!==null&&(e[n]=String(o))}}}return e}function rt(){var r=zf(process.env);return Object.assign({},yu,r)}function Gf(r){return r>=48&&r<=57?r-48:r>=97&&r<=102?r-87:r-55}function ss(r){for(var e=new Uint8Array(r.length/2),t=0,n=0;n<r.length;n+=2){var o=Gf(r.charCodeAt(n)),i=Gf(r.charCodeAt(n+1));e[t++]=o<<4|i}return e}var Hf="1.25.1";var rM="deployment.environment";var nM="process.runtime.name";var oM="service.name";var iM="service.instance.id";var aM="telemetry.sdk.name",sM="telemetry.sdk.language",lM="telemetry.sdk.version";var Vf=rM;var jf=nM;var ls=oM;var Wf=iM;var xi=aM,_i=sM,Mi=lM;var cM="nodejs";var $f=cM;var co,cs=(co={},co[xi]="opentelemetry",co[jf]="node",co[_i]=$f,co[Mi]=Hf,co);var uM=9,dM=6,mM=Math.pow(10,dM),pM=Math.pow(10,uM);function qf(r){var e=r/1e3,t=Math.trunc(e),n=Math.round(r%1e3*mM);return[t,n]}function Kf(r){return r[0]*pM+r[1]}function Ii(r){return r[0]*1e6+r[1]/1e3}var pn;(function(r){r[r.SUCCESS=0]="SUCCESS",r[r.FAILED=1]="FAILED"})(pn||(pn={}));var Yf=function(){function r(){var e=this;this._promise=new Promise(function(t,n){e._resolve=t,e._reject=n})}return Object.defineProperty(r.prototype,"promise",{get:function(){return this._promise},enumerable:!1,configurable:!0}),r.prototype.resolve=function(e){this._resolve(e)},r.prototype.reject=function(e){this._reject(e)},r}();var gM=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},hM=function(r,e,t){if(t||arguments.length===2)for(var n=0,o=e.length,i;n<o;n++)(i||!(n in e))&&(i||(i=Array.prototype.slice.call(e,0,n)),i[n]=e[n]);return r.concat(i||Array.prototype.slice.call(e))},Xf=function(){function r(e,t){this._callback=e,this._that=t,this._isCalled=!1,this._deferred=new Yf}return Object.defineProperty(r.prototype,"isCalled",{get:function(){return this._isCalled},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"promise",{get:function(){return this._deferred.promise},enumerable:!1,configurable:!0}),r.prototype.call=function(){for(var e,t=this,n=[],o=0;o<arguments.length;o++)n[o]=arguments[o];if(!this._isCalled){this._isCalled=!0;try{Promise.resolve((e=this._callback).call.apply(e,hM([this._that],gM(n),!1))).then(function(i){return t._deferred.resolve(i)},function(i){return t._deferred.reject(i)})}catch(i){this._deferred.reject(i)}}return this._deferred.promise},r}();var Ft;(function(r){r[r.DELTA=0]="DELTA",r[r.CUMULATIVE=1]="CUMULATIVE"})(Ft||(Ft={}));var st;(function(r){r[r.HISTOGRAM=0]="HISTOGRAM",r[r.EXPONENTIAL_HISTOGRAM=1]="EXPONENTIAL_HISTOGRAM",r[r.GAUGE=2]="GAUGE",r[r.SUM=3]="SUM"})(st||(st={}));var fM=function(){var r=function(e,t){return r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,o){n.__proto__=o}||function(n,o){for(var i in o)Object.prototype.hasOwnProperty.call(o,i)&&(n[i]=o[i])},r(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");r(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}}();var k5=function(r){fM(e,r);function e(t){var n=r.call(this,t)||this;return Object.setPrototypeOf(n,e.prototype),n}return e}(Error);function Jf(r,e){for(var t=0,n=r.length-1;n-t>1;){var o=Math.trunc((n+t)/2);r[o]<=e?t=o:n=o-1}return r[n]<=e?n:r[t]<=e?t:-1}he();var Bt;(function(r){r[r.DROP=0]="DROP",r[r.SUM=1]="SUM",r[r.LAST_VALUE=2]="LAST_VALUE",r[r.HISTOGRAM=3]="HISTOGRAM",r[r.EXPONENTIAL_HISTOGRAM=4]="EXPONENTIAL_HISTOGRAM"})(Bt||(Bt={}));var Qf=function(){function r(){this.kind=Bt.DROP}return r.prototype.createAccumulation=function(){},r.prototype.merge=function(e,t){},r.prototype.diff=function(e,t){},r.prototype.toMetricData=function(e,t,n,o){},r}();var Z;(function(r){r.COUNTER="COUNTER",r.GAUGE="GAUGE",r.HISTOGRAM="HISTOGRAM",r.UP_DOWN_COUNTER="UP_DOWN_COUNTER",r.OBSERVABLE_COUNTER="OBSERVABLE_COUNTER",r.OBSERVABLE_GAUGE="OBSERVABLE_GAUGE",r.OBSERVABLE_UP_DOWN_COUNTER="OBSERVABLE_UP_DOWN_COUNTER"})(Z||(Z={}));var SM=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i};function EM(r){var e=r.map(function(){return 0});return e.push(0),{buckets:{boundaries:r,counts:e},sum:0,count:0,hasMinMax:!1,min:1/0,max:-1/0}}var Tu=function(){function r(e,t,n,o){n===void 0&&(n=!0),o===void 0&&(o=EM(t)),this.startTime=e,this._boundaries=t,this._recordMinMax=n,this._current=o}return r.prototype.record=function(e){if(!Number.isNaN(e)){this._current.count+=1,this._current.sum+=e,this._recordMinMax&&(this._current.min=Math.min(e,this._current.min),this._current.max=Math.max(e,this._current.max),this._current.hasMinMax=!0);var t=Jf(this._boundaries,e);this._current.buckets.counts[t+1]+=1}},r.prototype.setStartTime=function(e){this.startTime=e},r.prototype.toPointValue=function(){return this._current},r}();var bu=function(){function r(e,t){this._boundaries=e,this._recordMinMax=t,this.kind=Bt.HISTOGRAM}return r.prototype.createAccumulation=function(e){return new Tu(e,this._boundaries,this._recordMinMax)},r.prototype.merge=function(e,t){for(var n=e.toPointValue(),o=t.toPointValue(),i=n.buckets.counts,a=o.buckets.counts,l=new Array(i.length),c=0;c<i.length;c++)l[c]=i[c]+a[c];var s=1/0,u=-1/0;return this._recordMinMax&&(n.hasMinMax&&o.hasMinMax?(s=Math.min(n.min,o.min),u=Math.max(n.max,o.max)):n.hasMinMax?(s=n.min,u=n.max):o.hasMinMax&&(s=o.min,u=o.max)),new Tu(e.startTime,n.buckets.boundaries,this._recordMinMax,{buckets:{boundaries:n.buckets.boundaries,counts:l},count:n.count+o.count,sum:n.sum+o.sum,hasMinMax:this._recordMinMax&&(n.hasMinMax||o.hasMinMax),min:s,max:u})},r.prototype.diff=function(e,t){for(var n=e.toPointValue(),o=t.toPointValue(),i=n.buckets.counts,a=o.buckets.counts,l=new Array(i.length),c=0;c<i.length;c++)l[c]=a[c]-i[c];return new Tu(t.startTime,n.buckets.boundaries,this._recordMinMax,{buckets:{boundaries:n.buckets.boundaries,counts:l},count:o.count-n.count,sum:o.sum-n.sum,hasMinMax:!1,min:1/0,max:-1/0})},r.prototype.toMetricData=function(e,t,n,o){return{descriptor:e,aggregationTemporality:t,dataPointType:st.HISTOGRAM,dataPoints:n.map(function(i){var a=SM(i,2),l=a[0],c=a[1],s=c.toPointValue(),u=e.type===Z.GAUGE||e.type===Z.UP_DOWN_COUNTER||e.type===Z.OBSERVABLE_GAUGE||e.type===Z.OBSERVABLE_UP_DOWN_COUNTER;return{attributes:l,startTime:c.startTime,endTime:o,value:{min:s.hasMinMax?s.min:void 0,max:s.hasMinMax?s.max:void 0,sum:u?void 0:s.sum,buckets:s.buckets,count:s.count}}})}},r}();he();var vu=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},Au=function(r,e,t){if(t||arguments.length===2)for(var n=0,o=e.length,i;n<o;n++)(i||!(n in e))&&(i||(i=Array.prototype.slice.call(e,0,n)),i[n]=e[n]);return r.concat(i||Array.prototype.slice.call(e))},wu=function(){function r(e,t,n,o){e===void 0&&(e=new yM),t===void 0&&(t=0),n===void 0&&(n=0),o===void 0&&(o=0),this.backing=e,this.indexBase=t,this.indexStart=n,this.indexEnd=o}return Object.defineProperty(r.prototype,"offset",{get:function(){return this.indexStart},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"length",{get:function(){return this.backing.length===0||this.indexEnd===this.indexStart&&this.at(0)===0?0:this.indexEnd-this.indexStart+1},enumerable:!1,configurable:!0}),r.prototype.counts=function(){var e=this;return Array.from({length:this.length},function(t,n){return e.at(n)})},r.prototype.at=function(e){var t=this.indexBase-this.indexStart;return e<t&&(e+=this.backing.length),e-=t,this.backing.countAt(e)},r.prototype.incrementBucket=function(e,t){this.backing.increment(e,t)},r.prototype.decrementBucket=function(e,t){this.backing.decrement(e,t)},r.prototype.trim=function(){for(var e=0;e<this.length;e++)if(this.at(e)!==0){this.indexStart+=e;break}else if(e===this.length-1){this.indexStart=this.indexEnd=this.indexBase=0;return}for(var e=this.length-1;e>=0;e--)if(this.at(e)!==0){this.indexEnd-=this.length-e-1;break}this._rotate()},r.prototype.downscale=function(e){this._rotate();for(var t=1+this.indexEnd-this.indexStart,n=1<<e,o=0,i=0,a=this.indexStart;a<=this.indexEnd;){var l=a%n;l<0&&(l+=n);for(var c=l;c<n&&o<t;c++)this._relocateBucket(i,o),o++,a++;i++}this.indexStart>>=e,this.indexEnd>>=e,this.indexBase=this.indexStart},r.prototype.clone=function(){return new r(this.backing.clone(),this.indexBase,this.indexStart,this.indexEnd)},r.prototype._rotate=function(){var e=this.indexBase-this.indexStart;e!==0&&(e>0?(this.backing.reverse(0,this.backing.length),this.backing.reverse(0,e),this.backing.reverse(e,this.backing.length)):(this.backing.reverse(0,this.backing.length),this.backing.reverse(0,this.backing.length+e)),this.indexBase=this.indexStart)},r.prototype._relocateBucket=function(e,t){e!==t&&this.incrementBucket(e,this.backing.emptyBucket(t))},r}();var yM=function(){function r(e){e===void 0&&(e=[0]),this._counts=e}return Object.defineProperty(r.prototype,"length",{get:function(){return this._counts.length},enumerable:!1,configurable:!0}),r.prototype.countAt=function(e){return this._counts[e]},r.prototype.growTo=function(e,t,n){var o=new Array(e).fill(0);o.splice.apply(o,Au([n,this._counts.length-t],vu(this._counts.slice(t)),!1)),o.splice.apply(o,Au([0,t],vu(this._counts.slice(0,t)),!1)),this._counts=o},r.prototype.reverse=function(e,t){for(var n=Math.floor((e+t)/2)-e,o=0;o<n;o++){var i=this._counts[e+o];this._counts[e+o]=this._counts[t-o-1],this._counts[t-o-1]=i}},r.prototype.emptyBucket=function(e){var t=this._counts[e];return this._counts[e]=0,t},r.prototype.increment=function(e,t){this._counts[e]+=t},r.prototype.decrement=function(e,t){this._counts[e]>=t?this._counts[e]-=t:this._counts[e]=0},r.prototype.clone=function(){return new r(Au([],vu(this._counts),!1))},r}();var Zf=52,TM=2146435072,bM=1048575,Ru=1023,us=-Ru+1,ds=Ru,Pi=Math.pow(2,-1022);function ms(r){var e=new DataView(new ArrayBuffer(8));e.setFloat64(0,r);var t=e.getUint32(0),n=(t&TM)>>20;return n-Ru}function ps(r){var e=new DataView(new ArrayBuffer(8));e.setFloat64(0,r);var t=e.getUint32(0),n=e.getUint32(4),o=(t&bM)*Math.pow(2,32);return o+n}function Oi(r,e){return r===0||r===Number.POSITIVE_INFINITY||r===Number.NEGATIVE_INFINITY||Number.isNaN(r)?r:r*Math.pow(2,e)}function tS(r){return r--,r|=r>>1,r|=r>>2,r|=r>>4,r|=r>>8,r|=r>>16,r++,r}var vM=function(){var r=function(e,t){return r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,o){n.__proto__=o}||function(n,o){for(var i in o)Object.prototype.hasOwnProperty.call(o,i)&&(n[i]=o[i])},r(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");r(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}}(),zr=function(r){vM(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(Error);var nS=function(){function r(e){this._shift=-e}return r.prototype.mapToIndex=function(e){if(e<Pi)return this._minNormalLowerBoundaryIndex();var t=ms(e),n=this._rightShift(ps(e)-1,Zf);return t+n>>this._shift},r.prototype.lowerBoundary=function(e){var t=this._minNormalLowerBoundaryIndex();if(e<t)throw new zr("underflow: "+e+" is < minimum lower boundary: "+t);var n=this._maxNormalLowerBoundaryIndex();if(e>n)throw new zr("overflow: "+e+" is > maximum lower boundary: "+n);return Oi(1,e<<this._shift)},Object.defineProperty(r.prototype,"scale",{get:function(){return this._shift===0?0:-this._shift},enumerable:!1,configurable:!0}),r.prototype._minNormalLowerBoundaryIndex=function(){var e=us>>this._shift;return this._shift<2&&e--,e},r.prototype._maxNormalLowerBoundaryIndex=function(){return ds>>this._shift},r.prototype._rightShift=function(e,t){return Math.floor(e*Math.pow(2,-t))},r}();var oS=function(){function r(e){this._scale=e,this._scaleFactor=Oi(Math.LOG2E,e),this._inverseFactor=Oi(Math.LN2,-e)}return r.prototype.mapToIndex=function(e){if(e<=Pi)return this._minNormalLowerBoundaryIndex()-1;if(ps(e)===0){var t=ms(e);return(t<<this._scale)-1}var n=Math.floor(Math.log(e)*this._scaleFactor),o=this._maxNormalLowerBoundaryIndex();return n>=o?o:n},r.prototype.lowerBoundary=function(e){var t=this._maxNormalLowerBoundaryIndex();if(e>=t){if(e===t)return 2*Math.exp((e-(1<<this._scale))/this._scaleFactor);throw new zr("overflow: "+e+" is > maximum lower boundary: "+t)}var n=this._minNormalLowerBoundaryIndex();if(e<=n){if(e===n)return Pi;if(e===n-1)return Math.exp((e+(1<<this._scale))/this._scaleFactor)/2;throw new zr("overflow: "+e+" is < minimum lower boundary: "+n)}return Math.exp(e*this._inverseFactor)},Object.defineProperty(r.prototype,"scale",{get:function(){return this._scale},enumerable:!1,configurable:!0}),r.prototype._minNormalLowerBoundaryIndex=function(){return us<<this._scale},r.prototype._maxNormalLowerBoundaryIndex=function(){return(ds+1<<this._scale)-1},r}();var iS=-10,aS=20,AM=Array.from({length:31},function(r,e){return e>10?new oS(e-10):new nS(e-10)});function Cu(r){if(r>aS||r<iS)throw new zr("expected scale >= "+iS+" && <= "+aS+", got: "+r);return AM[r+10]}var wM=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},gs=function(){function r(e,t){this.low=e,this.high=t}return r.combine=function(e,t){return new r(Math.min(e.low,t.low),Math.max(e.high,t.high))},r}(),RM=20,CM=160,xu=2,xM=function(){function r(e,t,n,o,i,a,l,c,s,u,d){e===void 0&&(e=e),t===void 0&&(t=CM),n===void 0&&(n=!0),o===void 0&&(o=0),i===void 0&&(i=0),a===void 0&&(a=0),l===void 0&&(l=Number.POSITIVE_INFINITY),c===void 0&&(c=Number.NEGATIVE_INFINITY),s===void 0&&(s=new wu),u===void 0&&(u=new wu),d===void 0&&(d=Cu(RM)),this.startTime=e,this._maxSize=t,this._recordMinMax=n,this._sum=o,this._count=i,this._zeroCount=a,this._min=l,this._max=c,this._positive=s,this._negative=u,this._mapping=d,this._maxSize<xu&&(F.warn("Exponential Histogram Max Size set to "+this._maxSize+", changing to the minimum size of: "+xu),this._maxSize=xu)}return r.prototype.record=function(e){this.updateByIncrement(e,1)},r.prototype.setStartTime=function(e){this.startTime=e},r.prototype.toPointValue=function(){return{hasMinMax:this._recordMinMax,min:this.min,max:this.max,sum:this.sum,positive:{offset:this.positive.offset,bucketCounts:this.positive.counts()},negative:{offset:this.negative.offset,bucketCounts:this.negative.counts()},count:this.count,scale:this.scale,zeroCount:this.zeroCount}},Object.defineProperty(r.prototype,"sum",{get:function(){return this._sum},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"min",{get:function(){return this._min},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"max",{get:function(){return this._max},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"count",{get:function(){return this._count},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"zeroCount",{get:function(){return this._zeroCount},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"scale",{get:function(){return this._count===this._zeroCount?0:this._mapping.scale},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"positive",{get:function(){return this._positive},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"negative",{get:function(){return this._negative},enumerable:!1,configurable:!0}),r.prototype.updateByIncrement=function(e,t){if(!Number.isNaN(e)){if(e>this._max&&(this._max=e),e<this._min&&(this._min=e),this._count+=t,e===0){this._zeroCount+=t;return}this._sum+=e*t,e>0?this._updateBuckets(this._positive,e,t):this._updateBuckets(this._negative,-e,t)}},r.prototype.merge=function(e){this._count===0?(this._min=e.min,this._max=e.max):e.count!==0&&(e.min<this.min&&(this._min=e.min),e.max>this.max&&(this._max=e.max)),this.startTime=e.startTime,this._sum+=e.sum,this._count+=e.count,this._zeroCount+=e.zeroCount;var t=this._minScale(e);this._downscale(this.scale-t),this._mergeBuckets(this.positive,e,e.positive,t),this._mergeBuckets(this.negative,e,e.negative,t)},r.prototype.diff=function(e){this._min=1/0,this._max=-1/0,this._sum-=e.sum,this._count-=e.count,this._zeroCount-=e.zeroCount;var t=this._minScale(e);this._downscale(this.scale-t),this._diffBuckets(this.positive,e,e.positive,t),this._diffBuckets(this.negative,e,e.negative,t)},r.prototype.clone=function(){return new r(this.startTime,this._maxSize,this._recordMinMax,this._sum,this._count,this._zeroCount,this._min,this._max,this.positive.clone(),this.negative.clone(),this._mapping)},r.prototype._updateBuckets=function(e,t,n){var o=this._mapping.mapToIndex(t),i=!1,a=0,l=0;if(e.length===0?(e.indexStart=o,e.indexEnd=e.indexStart,e.indexBase=e.indexStart):o<e.indexStart&&e.indexEnd-o>=this._maxSize?(i=!0,l=o,a=e.indexEnd):o>e.indexEnd&&o-e.indexStart>=this._maxSize&&(i=!0,l=e.indexStart,a=o),i){var c=this._changeScale(a,l);this._downscale(c),o=this._mapping.mapToIndex(t)}this._incrementIndexBy(e,o,n)},r.prototype._incrementIndexBy=function(e,t,n){if(n!==0){if(e.length===0&&(e.indexStart=e.indexEnd=e.indexBase=t),t<e.indexStart){var o=e.indexEnd-t;o>=e.backing.length&&this._grow(e,o+1),e.indexStart=t}else if(t>e.indexEnd){var o=t-e.indexStart;o>=e.backing.length&&this._grow(e,o+1),e.indexEnd=t}var i=t-e.indexBase;i<0&&(i+=e.backing.length),e.incrementBucket(i,n)}},r.prototype._grow=function(e,t){var n=e.backing.length,o=e.indexBase-e.indexStart,i=n-o,a=tS(t);a>this._maxSize&&(a=this._maxSize);var l=a-o;e.backing.growTo(a,i,l)},r.prototype._changeScale=function(e,t){for(var n=0;e-t>=this._maxSize;)e>>=1,t>>=1,n++;return n},r.prototype._downscale=function(e){if(e!==0){if(e<0)throw new Error("impossible change of scale: "+this.scale);var t=this._mapping.scale-e;this._positive.downscale(e),this._negative.downscale(e),this._mapping=Cu(t)}},r.prototype._minScale=function(e){var t=Math.min(this.scale,e.scale),n=gs.combine(this._highLowAtScale(this.positive,this.scale,t),this._highLowAtScale(e.positive,e.scale,t)),o=gs.combine(this._highLowAtScale(this.negative,this.scale,t),this._highLowAtScale(e.negative,e.scale,t));return Math.min(t-this._changeScale(n.high,n.low),t-this._changeScale(o.high,o.low))},r.prototype._highLowAtScale=function(e,t,n){if(e.length===0)return new gs(0,-1);var o=t-n;return new gs(e.indexStart>>o,e.indexEnd>>o)},r.prototype._mergeBuckets=function(e,t,n,o){for(var i=n.offset,a=t.scale-o,l=0;l<n.length;l++)this._incrementIndexBy(e,i+l>>a,n.at(l))},r.prototype._diffBuckets=function(e,t,n,o){for(var i=n.offset,a=t.scale-o,l=0;l<n.length;l++){var c=i+l>>a,s=c-e.indexBase;s<0&&(s+=e.backing.length),e.decrementBucket(s,n.at(l))}e.trim()},r}();var sS=function(){function r(e,t){this._maxSize=e,this._recordMinMax=t,this.kind=Bt.EXPONENTIAL_HISTOGRAM}return r.prototype.createAccumulation=function(e){return new xM(e,this._maxSize,this._recordMinMax)},r.prototype.merge=function(e,t){var n=t.clone();return n.merge(e),n},r.prototype.diff=function(e,t){var n=t.clone();return n.diff(e),n},r.prototype.toMetricData=function(e,t,n,o){return{descriptor:e,aggregationTemporality:t,dataPointType:st.EXPONENTIAL_HISTOGRAM,dataPoints:n.map(function(i){var a=wM(i,2),l=a[0],c=a[1],s=c.toPointValue(),u=e.type===Z.GAUGE||e.type===Z.UP_DOWN_COUNTER||e.type===Z.OBSERVABLE_GAUGE||e.type===Z.OBSERVABLE_UP_DOWN_COUNTER;return{attributes:l,startTime:c.startTime,endTime:o,value:{min:s.hasMinMax?s.min:void 0,max:s.hasMinMax?s.max:void 0,sum:u?void 0:s.sum,positive:{offset:s.positive.offset,bucketCounts:s.positive.bucketCounts},negative:{offset:s.negative.offset,bucketCounts:s.negative.bucketCounts},count:s.count,scale:s.scale,zeroCount:s.zeroCount}}})}},r}();var _M=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},_u=function(){function r(e,t,n){t===void 0&&(t=0),n===void 0&&(n=[0,0]),this.startTime=e,this._current=t,this.sampleTime=n}return r.prototype.record=function(e){this._current=e,this.sampleTime=qf(Date.now())},r.prototype.setStartTime=function(e){this.startTime=e},r.prototype.toPointValue=function(){return this._current},r}();var lS=function(){function r(){this.kind=Bt.LAST_VALUE}return r.prototype.createAccumulation=function(e){return new _u(e)},r.prototype.merge=function(e,t){var n=Ii(t.sampleTime)>=Ii(e.sampleTime)?t:e;return new _u(e.startTime,n.toPointValue(),n.sampleTime)},r.prototype.diff=function(e,t){var n=Ii(t.sampleTime)>=Ii(e.sampleTime)?t:e;return new _u(t.startTime,n.toPointValue(),n.sampleTime)},r.prototype.toMetricData=function(e,t,n,o){return{descriptor:e,aggregationTemporality:t,dataPointType:st.GAUGE,dataPoints:n.map(function(i){var a=_M(i,2),l=a[0],c=a[1];return{attributes:l,startTime:c.startTime,endTime:o,value:c.toPointValue()}})}},r}();var MM=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},Li=function(){function r(e,t,n,o){n===void 0&&(n=0),o===void 0&&(o=!1),this.startTime=e,this.monotonic=t,this._current=n,this.reset=o}return r.prototype.record=function(e){this.monotonic&&e<0||(this._current+=e)},r.prototype.setStartTime=function(e){this.startTime=e},r.prototype.toPointValue=function(){return this._current},r}();var Mu=function(){function r(e){this.monotonic=e,this.kind=Bt.SUM}return r.prototype.createAccumulation=function(e){return new Li(e,this.monotonic)},r.prototype.merge=function(e,t){var n=e.toPointValue(),o=t.toPointValue();return t.reset?new Li(t.startTime,this.monotonic,o,t.reset):new Li(e.startTime,this.monotonic,n+o)},r.prototype.diff=function(e,t){var n=e.toPointValue(),o=t.toPointValue();return this.monotonic&&n>o?new Li(t.startTime,this.monotonic,o,!0):new Li(t.startTime,this.monotonic,o-n)},r.prototype.toMetricData=function(e,t,n,o){return{descriptor:e,aggregationTemporality:t,dataPointType:st.SUM,dataPoints:n.map(function(i){var a=MM(i,2),l=a[0],c=a[1];return{attributes:l,startTime:c.startTime,endTime:o,value:c.toPointValue()}}),isMonotonic:this.monotonic}},r}();var gn=function(){var r=function(e,t){return r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,o){n.__proto__=o}||function(n,o){for(var i in o)Object.prototype.hasOwnProperty.call(o,i)&&(n[i]=o[i])},r(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");r(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}}(),nr=function(){function r(){}return r.Drop=function(){return fS},r.Sum=function(){return SS},r.LastValue=function(){return ES},r.Histogram=function(){return yS},r.ExponentialHistogram=function(){return IM},r.Default=function(){return PM},r}();var cS=function(r){gn(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.createAggregator=function(t){return e.DEFAULT_INSTANCE},e.DEFAULT_INSTANCE=new Qf,e}(nr);var uS=function(r){gn(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.createAggregator=function(t){switch(t.type){case Z.COUNTER:case Z.OBSERVABLE_COUNTER:case Z.HISTOGRAM:return e.MONOTONIC_INSTANCE;default:return e.NON_MONOTONIC_INSTANCE}},e.MONOTONIC_INSTANCE=new Mu(!0),e.NON_MONOTONIC_INSTANCE=new Mu(!1),e}(nr);var dS=function(r){gn(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.createAggregator=function(t){return e.DEFAULT_INSTANCE},e.DEFAULT_INSTANCE=new lS,e}(nr);var mS=function(r){gn(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.createAggregator=function(t){return e.DEFAULT_INSTANCE},e.DEFAULT_INSTANCE=new bu([0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4],!0),e}(nr);var pS=function(r){gn(e,r);function e(t,n){n===void 0&&(n=!0);var o=r.call(this)||this;if(o._recordMinMax=n,t==null)throw new Error("ExplicitBucketHistogramAggregation should be created with explicit boundaries, if a single bucket histogram is required, please pass an empty array");t=t.concat(),t=t.sort(function(l,c){return l-c});var i=t.lastIndexOf(-1/0),a=t.indexOf(1/0);return a===-1&&(a=void 0),o._boundaries=t.slice(i+1,a),o}return e.prototype.createAggregator=function(t){return new bu(this._boundaries,this._recordMinMax)},e}(nr);var gS=function(r){gn(e,r);function e(t,n){t===void 0&&(t=160),n===void 0&&(n=!0);var o=r.call(this)||this;return o._maxSize=t,o._recordMinMax=n,o}return e.prototype.createAggregator=function(t){return new sS(this._maxSize,this._recordMinMax)},e}(nr);var hS=function(r){gn(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype._resolve=function(t){switch(t.type){case Z.COUNTER:case Z.UP_DOWN_COUNTER:case Z.OBSERVABLE_COUNTER:case Z.OBSERVABLE_UP_DOWN_COUNTER:return SS;case Z.GAUGE:case Z.OBSERVABLE_GAUGE:return ES;case Z.HISTOGRAM:return t.advice.explicitBucketBoundaries?new pS(t.advice.explicitBucketBoundaries):yS}return F.warn("Unable to recognize instrument type: "+t.type),fS},e.prototype.createAggregator=function(t){return this._resolve(t).createAggregator(t)},e}(nr);var fS=new cS,SS=new uS,ES=new dS,yS=new mS,IM=new gS,PM=new hS;he();function hs(){return"unknown_service:"+process.argv0}var Gr=function(){return Gr=Object.assign||function(r){for(var e,t=1,n=arguments.length;t<n;t++){e=arguments[t];for(var o in e)Object.prototype.hasOwnProperty.call(e,o)&&(r[o]=e[o])}return r},Gr.apply(this,arguments)},OM=function(r,e,t,n){function o(i){return i instanceof t?i:new t(function(a){a(i)})}return new(t||(t=Promise))(function(i,a){function l(u){try{s(n.next(u))}catch(d){a(d)}}function c(u){try{s(n.throw(u))}catch(d){a(d)}}function s(u){u.done?i(u.value):o(u.value).then(l,c)}s((n=n.apply(r,e||[])).next())})},LM=function(r,e){var t={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},n,o,i,a;return a={next:l(0),throw:l(1),return:l(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function l(s){return function(u){return c([s,u])}}function c(s){if(n)throw new TypeError("Generator is already executing.");for(;t;)try{if(n=1,o&&(i=s[0]&2?o.return:s[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,s[1])).done)return i;switch(o=0,i&&(s=[s[0]&2,i.value]),s[0]){case 0:case 1:i=s;break;case 4:return t.label++,{value:s[1],done:!1};case 5:t.label++,o=s[1],s=[0];continue;case 7:s=t.ops.pop(),t.trys.pop();continue;default:if(i=t.trys,!(i=i.length>0&&i[i.length-1])&&(s[0]===6||s[0]===2)){t=0;continue}if(s[0]===3&&(!i||s[1]>i[0]&&s[1]<i[3])){t.label=s[1];break}if(s[0]===6&&t.label<i[1]){t.label=i[1],i=s;break}if(i&&t.label<i[2]){t.label=i[2],t.ops.push(s);break}i[2]&&t.ops.pop(),t.trys.pop();continue}s=e.call(r,t)}catch(u){s=[6,u],o=0}finally{n=i=0}if(s[0]&5)throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}},NM=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},Iu=function(){function r(e,t){var n=this,o;this._attributes=e,this.asyncAttributesPending=t!=null,this._syncAttributes=(o=this._attributes)!==null&&o!==void 0?o:{},this._asyncAttributesPromise=t?.then(function(i){return n._attributes=Object.assign({},n._attributes,i),n.asyncAttributesPending=!1,i},function(i){return F.debug("a resource's async attributes promise rejected: %s",i),n.asyncAttributesPending=!1,{}})}return r.empty=function(){return r.EMPTY},r.default=function(){var e;return new r((e={},e[ls]=hs(),e[_i]=cs[_i],e[xi]=cs[xi],e[Mi]=cs[Mi],e))},Object.defineProperty(r.prototype,"attributes",{get:function(){var e;return this.asyncAttributesPending&&F.error("Accessing resource attributes before async attributes settled"),(e=this._attributes)!==null&&e!==void 0?e:{}},enumerable:!1,configurable:!0}),r.prototype.waitForAsyncAttributes=function(){return OM(this,void 0,void 0,function(){return LM(this,function(e){switch(e.label){case 0:return this.asyncAttributesPending?[4,this._asyncAttributesPromise]:[3,2];case 1:e.sent(),e.label=2;case 2:return[2]}})})},r.prototype.merge=function(e){var t=this,n;if(!e)return this;var o=Gr(Gr({},this._syncAttributes),(n=e._syncAttributes)!==null&&n!==void 0?n:e.attributes);if(!this._asyncAttributesPromise&&!e._asyncAttributesPromise)return new r(o);var i=Promise.all([this._asyncAttributesPromise,e._asyncAttributesPromise]).then(function(a){var l,c=NM(a,2),s=c[0],u=c[1];return Gr(Gr(Gr(Gr({},t._syncAttributes),s),(l=e._syncAttributes)!==null&&l!==void 0?l:e.attributes),u)});return new r(o,i)},r.EMPTY=new r({}),r}();var hn;(function(r){r[r.DELTA=0]="DELTA",r[r.CUMULATIVE=1]="CUMULATIVE",r[r.LOWMEMORY=2]="LOWMEMORY"})(hn||(hn={}));he();var DM=function(r,e,t,n){function o(i){return i instanceof t?i:new t(function(a){a(i)})}return new(t||(t=Promise))(function(i,a){function l(u){try{s(n.next(u))}catch(d){a(d)}}function c(u){try{s(n.throw(u))}catch(d){a(d)}}function s(u){u.done?i(u.value):o(u.value).then(l,c)}s((n=n.apply(r,e||[])).next())})},kM=function(r,e){var t={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},n,o,i,a;return a={next:l(0),throw:l(1),return:l(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function l(s){return function(u){return c([s,u])}}function c(s){if(n)throw new TypeError("Generator is already executing.");for(;t;)try{if(n=1,o&&(i=s[0]&2?o.return:s[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,s[1])).done)return i;switch(o=0,i&&(s=[s[0]&2,i.value]),s[0]){case 0:case 1:i=s;break;case 4:return t.label++,{value:s[1],done:!1};case 5:t.label++,o=s[1],s=[0];continue;case 7:s=t.ops.pop(),t.trys.pop();continue;default:if(i=t.trys,!(i=i.length>0&&i[i.length-1])&&(s[0]===6||s[0]===2)){t=0;continue}if(s[0]===3&&(!i||s[1]>i[0]&&s[1]<i[3])){t.label=s[1];break}if(s[0]===6&&t.label<i[1]){t.label=i[1],i=s;break}if(i&&t.label<i[2]){t.label=i[2],t.ops.push(s);break}i[2]&&t.ops.pop(),t.trys.pop();continue}s=e.call(r,t)}catch(u){s=[6,u],o=0}finally{n=i=0}if(s[0]&5)throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}},Pu=function(){return Ft.CUMULATIVE},TS=function(r){switch(r){case Z.COUNTER:case Z.OBSERVABLE_COUNTER:case Z.GAUGE:case Z.HISTOGRAM:case Z.OBSERVABLE_GAUGE:return Ft.DELTA;case Z.UP_DOWN_COUNTER:case Z.OBSERVABLE_UP_DOWN_COUNTER:return Ft.CUMULATIVE}},bS=function(r){switch(r){case Z.COUNTER:case Z.HISTOGRAM:return Ft.DELTA;case Z.GAUGE:case Z.UP_DOWN_COUNTER:case Z.OBSERVABLE_UP_DOWN_COUNTER:case Z.OBSERVABLE_COUNTER:case Z.OBSERVABLE_GAUGE:return Ft.CUMULATIVE}};function UM(){var r=rt(),e=r.OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE.trim().toLowerCase();return e==="cumulative"?Pu:e==="delta"?TS:e==="lowmemory"?bS:(F.warn("OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE is set to '"+r.OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE+"', but only 'cumulative' and 'delta' are allowed. Using default ('cumulative') instead."),Pu)}function FM(r){return r!=null?r===hn.DELTA?TS:r===hn.LOWMEMORY?bS:Pu:UM()}function BM(r){return r?.aggregationPreference?r.aggregationPreference:function(e){return nr.Default()}}var vS=function(){function r(e,t){this._otlpExporter=e,this._aggregationSelector=BM(t),this._aggregationTemporalitySelector=FM(t?.temporalityPreference)}return r.prototype.export=function(e,t){this._otlpExporter.export([e],t)},r.prototype.shutdown=function(){return DM(this,void 0,void 0,function(){return kM(this,function(e){switch(e.label){case 0:return[4,this._otlpExporter.shutdown()];case 1:return e.sent(),[2]}})})},r.prototype.forceFlush=function(){return Promise.resolve()},r.prototype.selectAggregation=function(e){return this._aggregationSelector(e)},r.prototype.selectAggregationTemporality=function(e){return this._aggregationTemporalitySelector(e)},r}();he();he();var zM=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},AS=1e4,wS=5,RS=1e3,CS=5e3,xS=1.5;function Ni(r){r===void 0&&(r={});var e={};return Object.entries(r).forEach(function(t){var n=zM(t,2),o=n[0],i=n[1];typeof i<"u"?e[o]=String(i):F.warn('Header "'+o+'" has invalid value ('+i+") and will be ignored")}),e}function Ou(r,e){return r.endsWith("/")||(r=r+"/"),r+e}function Lu(r){try{var e=new URL(r);return e.pathname===""&&(e.pathname=e.pathname+"/"),e.toString()}catch{return F.warn("Could not parse export URL: '"+r+"'"),r}}function Nu(r){return typeof r=="number"?r<=0?Du(r,AS):r:GM()}function GM(){var r,e=Number((r=rt().OTEL_EXPORTER_OTLP_TRACES_TIMEOUT)!==null&&r!==void 0?r:rt().OTEL_EXPORTER_OTLP_TIMEOUT);return e<=0?Du(e,AS):e}function Du(r,e){return F.warn("Timeout must be greater than 0",r),e}function _S(r){var e=[429,502,503,504];return e.includes(r)}function MS(r){if(r==null)return-1;var e=Number.parseInt(r,10);if(Number.isInteger(e))return e>0?e*1e3:-1;var t=new Date(r).getTime()-Date.now();return t>=0?t:0}var IS=function(){function r(e){e===void 0&&(e={}),this._sendingPromises=[],this.url=this.getDefaultUrl(e),typeof e.hostname=="string"&&(this.hostname=e.hostname),this.shutdown=this.shutdown.bind(this),this._shutdownOnce=new Xf(this._shutdown,this),this._concurrencyLimit=typeof e.concurrencyLimit=="number"?e.concurrencyLimit:30,this.timeoutMillis=Nu(e.timeoutMillis),this.onInit(e)}return r.prototype.export=function(e,t){if(this._shutdownOnce.isCalled){t({code:pn.FAILED,error:new Error("Exporter has been shutdown")});return}if(this._sendingPromises.length>=this._concurrencyLimit){t({code:pn.FAILED,error:new Error("Concurrent export limit reached")});return}this._export(e).then(function(){t({code:pn.SUCCESS})}).catch(function(n){t({code:pn.FAILED,error:n})})},r.prototype._export=function(e){var t=this;return new Promise(function(n,o){try{F.debug("items to be sent",e),t.send(e,n,o)}catch(i){o(i)}})},r.prototype.shutdown=function(){return this._shutdownOnce.call()},r.prototype.forceFlush=function(){return Promise.all(this._sendingPromises).then(function(){})},r.prototype._shutdown=function(){return F.debug("shutdown started"),this.onShutdown(),this.forceFlush()},r}();he();import*as ku from"url";import*as Ss from"http";import*as Es from"https";import*as PS from"zlib";import{Readable as VM}from"stream";var Hr;(function(r){r.NONE="none",r.GZIP="gzip"})(Hr||(Hr={}));var HM=function(){var r=function(e,t){return r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,o){n.__proto__=o}||function(n,o){for(var i in o)Object.prototype.hasOwnProperty.call(o,i)&&(n[i]=o[i])},r(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");r(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}}(),uo=function(r){HM(e,r);function e(t,n,o){var i=r.call(this,t)||this;return i.name="OTLPExporterError",i.data=o,i.code=n,i}return e}(Error);var fs=function(){return fs=Object.assign||function(r){for(var e,t=1,n=arguments.length;t<n;t++){e=arguments[t];for(var o in e)Object.prototype.hasOwnProperty.call(e,o)&&(r[o]=e[o])}return r},fs.apply(this,arguments)};function Uu(r,e,t,n,o){var i=r.timeoutMillis,a=new ku.URL(r.url),l=Number(process.versions.node.split(".")[0]),c,s,u=!1,d=setTimeout(function(){if(clearTimeout(c),u=!0,s.destroyed){var h=new uo("Request Timeout");o(h)}else l>=14?s.destroy():s.abort()},i),m={hostname:a.hostname,port:a.port,path:a.pathname,method:"POST",headers:fs({"Content-Type":t},r.headers),agent:r.agent},p=a.protocol==="http:"?Ss.request:Es.request,g=function(h,f){switch(h===void 0&&(h=wS),f===void 0&&(f=RS),s=p(m,function(T){var v="";T.on("data",function(R){return v+=R}),T.on("aborted",function(){if(u){var R=new uo("Request Timeout");o(R)}}),T.on("end",function(){if(u===!1)if(T.statusCode&&T.statusCode<299)F.debug("statusCode: "+T.statusCode,v),n(),clearTimeout(d),clearTimeout(c);else if(T.statusCode&&_S(T.statusCode)&&h>0){var R=void 0;f=xS*f,T.headers["retry-after"]?R=MS(T.headers["retry-after"]):R=Math.round(Math.random()*(CS-f)+f),c=setTimeout(function(){g(h-1,f)},R)}else{var b=new uo(T.statusMessage,T.statusCode,v);o(b),clearTimeout(d),clearTimeout(c)}})}),s.on("error",function(T){if(u){var v=new uo("Request Timeout",T.code);o(v)}else o(T);clearTimeout(d),clearTimeout(c)}),s.on("abort",function(){if(u){var T=new uo("Request Timeout");o(T)}clearTimeout(d),clearTimeout(c)}),r.compression){case Hr.GZIP:{s.setHeader("Content-Encoding","gzip");var y=jM(e);y.on("error",o).pipe(PS.createGzip()).on("error",o).pipe(s);break}default:s.end(Buffer.from(e));break}};g()}function jM(r){var e=new VM;return e.push(r),e.push(null),e}function Fu(r){if(r.httpAgentOptions&&r.keepAlive===!1){F.warn("httpAgentOptions is used only when keepAlive is true");return}if(!(r.keepAlive===!1||!r.url))try{var e=new ku.URL(r.url),t=e.protocol==="http:"?Ss.Agent:Es.Agent;return new t(fs({keepAlive:!0},r.httpAgentOptions))}catch(n){F.error("collector exporter failed to create http agent. err: "+n.message);return}}function Bu(r){if(r)return r;var e=rt().OTEL_EXPORTER_OTLP_TRACES_COMPRESSION||rt().OTEL_EXPORTER_OTLP_COMPRESSION;return e===Hr.GZIP?Hr.GZIP:Hr.NONE}he();var WM=function(){var r=function(e,t){return r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,o){n.__proto__=o}||function(n,o){for(var i in o)Object.prototype.hasOwnProperty.call(o,i)&&(n[i]=o[i])},r(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");r(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}}(),ys=function(r){WM(e,r);function e(t,n,o){t===void 0&&(t={});var i=r.call(this,t)||this;return i.DEFAULT_HEADERS={},i._contentType=o,t.metadata&&F.warn("Metadata cannot be set when using http"),i.headers=Object.assign(i.DEFAULT_HEADERS,Ni(t.headers),lo.parseKeyPairsIntoRecord(rt().OTEL_EXPORTER_OTLP_HEADERS)),i.agent=Fu(t),i.compression=Bu(t.compression),i._serializer=n,i}return e.prototype.onInit=function(t){},e.prototype.send=function(t,n,o){var i=this;if(this._shutdownOnce.isCalled){F.debug("Shutdown already started. Cannot send objects");return}var a=new Promise(function(c,s){var u;Uu(i,(u=i._serializer.serializeRequest(t))!==null&&u!==void 0?u:new Uint8Array,i._contentType,c,s)}).then(n,o);this._sendingPromises.push(a);var l=function(){var c=i._sendingPromises.indexOf(a);i._sendingPromises.splice(c,1)};a.then(l,l)},e.prototype.onShutdown=function(){},e}(IS);function LS(r){var e=BigInt(1e9);return BigInt(r[0])*e+BigInt(r[1])}function $M(r){var e=Number(BigInt.asUintN(32,r)),t=Number(BigInt.asUintN(32,r>>BigInt(32)));return{low:e,high:t}}function NS(r){var e=LS(r);return $M(e)}function qM(r){var e=LS(r);return e.toString()}var KM=typeof BigInt<"u"?qM:Kf;function OS(r){return r}function DS(r){if(r!==void 0)return ss(r)}var YM={encodeHrTime:NS,encodeSpanContext:ss,encodeOptionalSpanContext:DS};function kS(r){var e,t;if(r===void 0)return YM;var n=(e=r.useLongBits)!==null&&e!==void 0?e:!0,o=(t=r.useHex)!==null&&t!==void 0?t:!1;return{encodeHrTime:n?NS:KM,encodeSpanContext:o?OS:ss,encodeOptionalSpanContext:o?OS:DS}}var XM=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i};function US(r){return{name:r.name,version:r.version}}function mo(r){return Object.keys(r).map(function(e){return FS(e,r[e])})}function FS(r,e){return{key:r,value:BS(e)}}function BS(r){var e=typeof r;return e==="string"?{stringValue:r}:e==="number"?Number.isInteger(r)?{intValue:r}:{doubleValue:r}:e==="boolean"?{boolValue:r}:r instanceof Uint8Array?{bytesValue:r}:Array.isArray(r)?{arrayValue:{values:r.map(BS)}}:e==="object"&&r!=null?{kvlistValue:{values:Object.entries(r).map(function(t){var n=XM(t,2),o=n[0],i=n[1];return FS(o,i)})}}:{}}function zS(r){return{attributes:mo(r.attributes),droppedAttributesCount:0}}he();function HS(r,e){var t=kS(e);return{resource:zS(r.resource),schemaUrl:void 0,scopeMetrics:JM(r.scopeMetrics,t)}}function JM(r,e){return Array.from(r.map(function(t){return{scope:US(t.scope),metrics:t.metrics.map(function(n){return QM(n,e)}),schemaUrl:t.scope.schemaUrl}}))}function QM(r,e){var t={name:r.descriptor.name,description:r.descriptor.description,unit:r.descriptor.unit},n=rI(r.aggregationTemporality);switch(r.dataPointType){case st.SUM:t.sum={aggregationTemporality:n,isMonotonic:r.isMonotonic,dataPoints:GS(r,e)};break;case st.GAUGE:t.gauge={dataPoints:GS(r,e)};break;case st.HISTOGRAM:t.histogram={aggregationTemporality:n,dataPoints:eI(r,e)};break;case st.EXPONENTIAL_HISTOGRAM:t.exponentialHistogram={aggregationTemporality:n,dataPoints:tI(r,e)};break}return t}function ZM(r,e,t){var n={attributes:mo(r.attributes),startTimeUnixNano:t.encodeHrTime(r.startTime),timeUnixNano:t.encodeHrTime(r.endTime)};switch(e){case Ct.INT:n.asInt=r.value;break;case Ct.DOUBLE:n.asDouble=r.value;break}return n}function GS(r,e){return r.dataPoints.map(function(t){return ZM(t,r.descriptor.valueType,e)})}function eI(r,e){return r.dataPoints.map(function(t){var n=t.value;return{attributes:mo(t.attributes),bucketCounts:n.buckets.counts,explicitBounds:n.buckets.boundaries,count:n.count,sum:n.sum,min:n.min,max:n.max,startTimeUnixNano:e.encodeHrTime(t.startTime),timeUnixNano:e.encodeHrTime(t.endTime)}})}function tI(r,e){return r.dataPoints.map(function(t){var n=t.value;return{attributes:mo(t.attributes),count:n.count,min:n.min,max:n.max,sum:n.sum,positive:{offset:n.positive.offset,bucketCounts:n.positive.bucketCounts},negative:{offset:n.negative.offset,bucketCounts:n.negative.bucketCounts},scale:n.scale,zeroCount:n.zeroCount,startTimeUnixNano:e.encodeHrTime(t.startTime),timeUnixNano:e.encodeHrTime(t.endTime)}})}function rI(r){switch(r){case Ft.DELTA:return 1;case Ft.CUMULATIVE:return 2}}function VS(r,e){return{resourceMetrics:r.map(function(t){return HS(t,e)})}}var zu={serializeRequest:function(r){var e=VS(r,{useLongBits:!1}),t=new TextEncoder;return t.encode(JSON.stringify(e))},deserializeResponse:function(r){var e=new TextDecoder;return JSON.parse(e.decode(r))}};var jS="0.52.1";var WS=function(){var r=function(e,t){return r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,o){n.__proto__=o}||function(n,o){for(var i in o)Object.prototype.hasOwnProperty.call(o,i)&&(n[i]=o[i])},r(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");r(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}}(),po=function(){return po=Object.assign||function(r){for(var e,t=1,n=arguments.length;t<n;t++){e=arguments[t];for(var o in e)Object.prototype.hasOwnProperty.call(e,o)&&(r[o]=e[o])}return r},po.apply(this,arguments)},$S="v1/metrics",nI="http://localhost:4318/"+$S,oI={"User-Agent":"OTel-OTLP-Exporter-JavaScript/"+jS},iI=function(r){WS(e,r);function e(t){var n=r.call(this,t,zu,"application/json")||this;return n.headers=po(po(po(po({},n.headers),oI),lo.parseKeyPairsIntoRecord(rt().OTEL_EXPORTER_OTLP_METRICS_HEADERS)),Ni(t?.headers)),n}return e.prototype.getDefaultUrl=function(t){return typeof t.url=="string"?t.url:rt().OTEL_EXPORTER_OTLP_METRICS_ENDPOINT.length>0?Lu(rt().OTEL_EXPORTER_OTLP_METRICS_ENDPOINT):rt().OTEL_EXPORTER_OTLP_ENDPOINT.length>0?Ou(rt().OTEL_EXPORTER_OTLP_ENDPOINT,$S):nI},e}(ys),qS=function(r){WS(e,r);function e(t){return r.call(this,new iI(t),t)||this}return e}(vS);var go;(function(r){r[r.DELTA=0]="DELTA",r[r.CUMULATIVE=1]="CUMULATIVE"})(go||(go={}));var or;(function(r){r[r.HISTOGRAM=0]="HISTOGRAM",r[r.EXPONENTIAL_HISTOGRAM=1]="EXPONENTIAL_HISTOGRAM",r[r.GAUGE=2]="GAUGE",r[r.SUM=3]="SUM"})(or||(or={}));he();var aI=function(){var r=function(e,t){return r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,o){n.__proto__=o}||function(n,o){for(var i in o)Object.prototype.hasOwnProperty.call(o,i)&&(n[i]=o[i])},r(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");r(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}}(),KS=function(r,e,t,n){function o(i){return i instanceof t?i:new t(function(a){a(i)})}return new(t||(t=Promise))(function(i,a){function l(u){try{s(n.next(u))}catch(d){a(d)}}function c(u){try{s(n.throw(u))}catch(d){a(d)}}function s(u){u.done?i(u.value):o(u.value).then(l,c)}s((n=n.apply(r,e||[])).next())})},YS=function(r,e){var t={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},n,o,i,a;return a={next:l(0),throw:l(1),return:l(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function l(s){return function(u){return c([s,u])}}function c(s){if(n)throw new TypeError("Generator is already executing.");for(;t;)try{if(n=1,o&&(i=s[0]&2?o.return:s[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,s[1])).done)return i;switch(o=0,i&&(s=[s[0]&2,i.value]),s[0]){case 0:case 1:i=s;break;case 4:return t.label++,{value:s[1],done:!1};case 5:t.label++,o=s[1],s=[0];continue;case 7:s=t.ops.pop(),t.trys.pop();continue;default:if(i=t.trys,!(i=i.length>0&&i[i.length-1])&&(s[0]===6||s[0]===2)){t=0;continue}if(s[0]===3&&(!i||s[1]>i[0]&&s[1]<i[3])){t.label=s[1];break}if(s[0]===6&&t.label<i[1]){t.label=i[1],i=s;break}if(i&&t.label<i[2]){t.label=i[2],t.ops.push(s);break}i[2]&&t.ops.pop(),t.trys.pop();continue}s=e.call(r,t)}catch(u){s=[6,u],o=0}finally{n=i=0}if(s[0]&5)throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}},sI=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},lI=function(r,e,t){if(t||arguments.length===2)for(var n=0,o=e.length,i;n<o;n++)(i||!(n in e))&&(i||(i=Array.prototype.slice.call(e,0,n)),i[n]=e[n]);return r.concat(i||Array.prototype.slice.call(e))},cI=function(r){var e=typeof Symbol=="function"&&Symbol.iterator,t=e&&r[e],n=0;if(t)return t.call(r);if(r&&typeof r.length=="number")return{next:function(){return r&&n>=r.length&&(r=void 0),{value:r&&r[n++],done:!r}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")};function XS(r){return r!=null}function Ts(r){var e=Object.keys(r);return e.length===0?"":(e=e.sort(),JSON.stringify(e.map(function(t){return[t,r[t]]})))}function JS(r){var e,t;return r.name+":"+((e=r.version)!==null&&e!==void 0?e:"")+":"+((t=r.schemaUrl)!==null&&t!==void 0?t:"")}var Gu=function(r){aI(e,r);function e(t){var n=r.call(this,t)||this;return Object.setPrototypeOf(n,e.prototype),n}return e}(Error);function Vr(r,e){var t,n=new Promise(function(i,a){t=setTimeout(function(){a(new Gu("Operation timed out."))},e)});return Promise.race([r,n]).then(function(o){return clearTimeout(t),o},function(o){throw clearTimeout(t),o})}function QS(r){return KS(this,void 0,void 0,function(){var e=this;return YS(this,function(t){return[2,Promise.all(r.map(function(n){return KS(e,void 0,void 0,function(){var o,i;return YS(this,function(a){switch(a.label){case 0:return a.trys.push([0,2,,3]),[4,n];case 1:return o=a.sent(),[2,{status:"fulfilled",value:o}];case 2:return i=a.sent(),[2,{status:"rejected",reason:i}];case 3:return[2]}})})}))]})})}function ZS(r){return r.status==="rejected"}function Hu(r,e){var t=[];return r.forEach(function(n){t.push.apply(t,lI([],sI(e(n)),!1))}),t}function eE(r,e){var t,n;if(r.size!==e.size)return!1;try{for(var o=cI(r),i=o.next();!i.done;i=o.next()){var a=i.value;if(!e.has(a))return!1}}catch(l){t={error:l}}finally{try{i&&!i.done&&(n=o.return)&&n.call(o)}finally{if(t)throw t.error}}return!0}function tE(r,e){for(var t=0,n=r.length-1,o=r.length;n>=t;){var i=t+Math.trunc((n-t)/2);r[i]<e?t=i+1:(o=i,n=i-1)}return o}function rE(r,e){return r.toLowerCase()===e.toLowerCase()}he();var zt;(function(r){r[r.DROP=0]="DROP",r[r.SUM=1]="SUM",r[r.LAST_VALUE=2]="LAST_VALUE",r[r.HISTOGRAM=3]="HISTOGRAM",r[r.EXPONENTIAL_HISTOGRAM=4]="EXPONENTIAL_HISTOGRAM"})(zt||(zt={}));var Vu=function(){function r(){this.kind=zt.DROP}return r.prototype.createAccumulation=function(){},r.prototype.merge=function(e,t){},r.prototype.diff=function(e,t){},r.prototype.toMetricData=function(e,t,n,o){},r}();he();var ne;(function(r){r.COUNTER="COUNTER",r.GAUGE="GAUGE",r.HISTOGRAM="HISTOGRAM",r.UP_DOWN_COUNTER="UP_DOWN_COUNTER",r.OBSERVABLE_COUNTER="OBSERVABLE_COUNTER",r.OBSERVABLE_GAUGE="OBSERVABLE_GAUGE",r.OBSERVABLE_UP_DOWN_COUNTER="OBSERVABLE_UP_DOWN_COUNTER"})(ne||(ne={}));function ir(r,e,t){var n,o,i,a;return dI(r)||F.warn('Invalid metric name: "'+r+'". The metric name should be a ASCII string with a length no greater than 255 characters.'),{name:r,type:e,description:(n=t?.description)!==null&&n!==void 0?n:"",unit:(o=t?.unit)!==null&&o!==void 0?o:"",valueType:(i=t?.valueType)!==null&&i!==void 0?i:Ct.DOUBLE,advice:(a=t?.advice)!==null&&a!==void 0?a:{}}}function nE(r,e){var t,n;return{name:(t=r.name)!==null&&t!==void 0?t:e.name,description:(n=r.description)!==null&&n!==void 0?n:e.description,type:e.type,unit:e.unit,valueType:e.valueType,advice:e.advice}}function oE(r,e){return rE(r.name,e.name)&&r.unit===e.unit&&r.type===e.type&&r.valueType===e.valueType}var uI=/^[a-z][a-z0-9_.\-/]{0,254}$/i;function dI(r){return r.match(uI)!=null}var mI=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i};function pI(r){var e=r.map(function(){return 0});return e.push(0),{buckets:{boundaries:r,counts:e},sum:0,count:0,hasMinMax:!1,min:1/0,max:-1/0}}var bs=function(){function r(e,t,n,o){n===void 0&&(n=!0),o===void 0&&(o=pI(t)),this.startTime=e,this._boundaries=t,this._recordMinMax=n,this._current=o}return r.prototype.record=function(e){if(!Number.isNaN(e)){this._current.count+=1,this._current.sum+=e,this._recordMinMax&&(this._current.min=Math.min(e,this._current.min),this._current.max=Math.max(e,this._current.max),this._current.hasMinMax=!0);var t=tE(this._boundaries,e);this._current.buckets.counts[t]+=1}},r.prototype.setStartTime=function(e){this.startTime=e},r.prototype.toPointValue=function(){return this._current},r}();var vs=function(){function r(e,t){this._boundaries=e,this._recordMinMax=t,this.kind=zt.HISTOGRAM}return r.prototype.createAccumulation=function(e){return new bs(e,this._boundaries,this._recordMinMax)},r.prototype.merge=function(e,t){for(var n=e.toPointValue(),o=t.toPointValue(),i=n.buckets.counts,a=o.buckets.counts,l=new Array(i.length),c=0;c<i.length;c++)l[c]=i[c]+a[c];var s=1/0,u=-1/0;return this._recordMinMax&&(n.hasMinMax&&o.hasMinMax?(s=Math.min(n.min,o.min),u=Math.max(n.max,o.max)):n.hasMinMax?(s=n.min,u=n.max):o.hasMinMax&&(s=o.min,u=o.max)),new bs(e.startTime,n.buckets.boundaries,this._recordMinMax,{buckets:{boundaries:n.buckets.boundaries,counts:l},count:n.count+o.count,sum:n.sum+o.sum,hasMinMax:this._recordMinMax&&(n.hasMinMax||o.hasMinMax),min:s,max:u})},r.prototype.diff=function(e,t){for(var n=e.toPointValue(),o=t.toPointValue(),i=n.buckets.counts,a=o.buckets.counts,l=new Array(i.length),c=0;c<i.length;c++)l[c]=a[c]-i[c];return new bs(t.startTime,n.buckets.boundaries,this._recordMinMax,{buckets:{boundaries:n.buckets.boundaries,counts:l},count:o.count-n.count,sum:o.sum-n.sum,hasMinMax:!1,min:1/0,max:-1/0})},r.prototype.toMetricData=function(e,t,n,o){return{descriptor:e,aggregationTemporality:t,dataPointType:or.HISTOGRAM,dataPoints:n.map(function(i){var a=mI(i,2),l=a[0],c=a[1],s=c.toPointValue(),u=e.type===ne.GAUGE||e.type===ne.UP_DOWN_COUNTER||e.type===ne.OBSERVABLE_GAUGE||e.type===ne.OBSERVABLE_UP_DOWN_COUNTER;return{attributes:l,startTime:c.startTime,endTime:o,value:{min:s.hasMinMax?s.min:void 0,max:s.hasMinMax?s.max:void 0,sum:u?void 0:s.sum,buckets:s.buckets,count:s.count}}})}},r}();he();var ju=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},Wu=function(r,e,t){if(t||arguments.length===2)for(var n=0,o=e.length,i;n<o;n++)(i||!(n in e))&&(i||(i=Array.prototype.slice.call(e,0,n)),i[n]=e[n]);return r.concat(i||Array.prototype.slice.call(e))},$u=function(){function r(e,t,n,o){e===void 0&&(e=new gI),t===void 0&&(t=0),n===void 0&&(n=0),o===void 0&&(o=0),this.backing=e,this.indexBase=t,this.indexStart=n,this.indexEnd=o}return Object.defineProperty(r.prototype,"offset",{get:function(){return this.indexStart},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"length",{get:function(){return this.backing.length===0||this.indexEnd===this.indexStart&&this.at(0)===0?0:this.indexEnd-this.indexStart+1},enumerable:!1,configurable:!0}),r.prototype.counts=function(){var e=this;return Array.from({length:this.length},function(t,n){return e.at(n)})},r.prototype.at=function(e){var t=this.indexBase-this.indexStart;return e<t&&(e+=this.backing.length),e-=t,this.backing.countAt(e)},r.prototype.incrementBucket=function(e,t){this.backing.increment(e,t)},r.prototype.decrementBucket=function(e,t){this.backing.decrement(e,t)},r.prototype.trim=function(){for(var e=0;e<this.length;e++)if(this.at(e)!==0){this.indexStart+=e;break}else if(e===this.length-1){this.indexStart=this.indexEnd=this.indexBase=0;return}for(var e=this.length-1;e>=0;e--)if(this.at(e)!==0){this.indexEnd-=this.length-e-1;break}this._rotate()},r.prototype.downscale=function(e){this._rotate();for(var t=1+this.indexEnd-this.indexStart,n=1<<e,o=0,i=0,a=this.indexStart;a<=this.indexEnd;){var l=a%n;l<0&&(l+=n);for(var c=l;c<n&&o<t;c++)this._relocateBucket(i,o),o++,a++;i++}this.indexStart>>=e,this.indexEnd>>=e,this.indexBase=this.indexStart},r.prototype.clone=function(){return new r(this.backing.clone(),this.indexBase,this.indexStart,this.indexEnd)},r.prototype._rotate=function(){var e=this.indexBase-this.indexStart;e!==0&&(e>0?(this.backing.reverse(0,this.backing.length),this.backing.reverse(0,e),this.backing.reverse(e,this.backing.length)):(this.backing.reverse(0,this.backing.length),this.backing.reverse(0,this.backing.length+e)),this.indexBase=this.indexStart)},r.prototype._relocateBucket=function(e,t){e!==t&&this.incrementBucket(e,this.backing.emptyBucket(t))},r}();var gI=function(){function r(e){e===void 0&&(e=[0]),this._counts=e}return Object.defineProperty(r.prototype,"length",{get:function(){return this._counts.length},enumerable:!1,configurable:!0}),r.prototype.countAt=function(e){return this._counts[e]},r.prototype.growTo=function(e,t,n){var o=new Array(e).fill(0);o.splice.apply(o,Wu([n,this._counts.length-t],ju(this._counts.slice(t)),!1)),o.splice.apply(o,Wu([0,t],ju(this._counts.slice(0,t)),!1)),this._counts=o},r.prototype.reverse=function(e,t){for(var n=Math.floor((e+t)/2)-e,o=0;o<n;o++){var i=this._counts[e+o];this._counts[e+o]=this._counts[t-o-1],this._counts[t-o-1]=i}},r.prototype.emptyBucket=function(e){var t=this._counts[e];return this._counts[e]=0,t},r.prototype.increment=function(e,t){this._counts[e]+=t},r.prototype.decrement=function(e,t){this._counts[e]>=t?this._counts[e]-=t:this._counts[e]=0},r.prototype.clone=function(){return new r(Wu([],ju(this._counts),!1))},r}();var iE=52,hI=2146435072,fI=1048575,qu=1023,As=-qu+1,ws=qu,Di=Math.pow(2,-1022);function Rs(r){var e=new DataView(new ArrayBuffer(8));e.setFloat64(0,r);var t=e.getUint32(0),n=(t&hI)>>20;return n-qu}function Cs(r){var e=new DataView(new ArrayBuffer(8));e.setFloat64(0,r);var t=e.getUint32(0),n=e.getUint32(4),o=(t&fI)*Math.pow(2,32);return o+n}function ki(r,e){return r===0||r===Number.POSITIVE_INFINITY||r===Number.NEGATIVE_INFINITY||Number.isNaN(r)?r:r*Math.pow(2,e)}function sE(r){return r--,r|=r>>1,r|=r>>2,r|=r>>4,r|=r>>8,r|=r>>16,r++,r}var SI=function(){var r=function(e,t){return r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,o){n.__proto__=o}||function(n,o){for(var i in o)Object.prototype.hasOwnProperty.call(o,i)&&(n[i]=o[i])},r(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");r(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}}(),jr=function(r){SI(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(Error);var cE=function(){function r(e){this._shift=-e}return r.prototype.mapToIndex=function(e){if(e<Di)return this._minNormalLowerBoundaryIndex();var t=Rs(e),n=this._rightShift(Cs(e)-1,iE);return t+n>>this._shift},r.prototype.lowerBoundary=function(e){var t=this._minNormalLowerBoundaryIndex();if(e<t)throw new jr("underflow: "+e+" is < minimum lower boundary: "+t);var n=this._maxNormalLowerBoundaryIndex();if(e>n)throw new jr("overflow: "+e+" is > maximum lower boundary: "+n);return ki(1,e<<this._shift)},Object.defineProperty(r.prototype,"scale",{get:function(){return this._shift===0?0:-this._shift},enumerable:!1,configurable:!0}),r.prototype._minNormalLowerBoundaryIndex=function(){var e=As>>this._shift;return this._shift<2&&e--,e},r.prototype._maxNormalLowerBoundaryIndex=function(){return ws>>this._shift},r.prototype._rightShift=function(e,t){return Math.floor(e*Math.pow(2,-t))},r}();var uE=function(){function r(e){this._scale=e,this._scaleFactor=ki(Math.LOG2E,e),this._inverseFactor=ki(Math.LN2,-e)}return r.prototype.mapToIndex=function(e){if(e<=Di)return this._minNormalLowerBoundaryIndex()-1;if(Cs(e)===0){var t=Rs(e);return(t<<this._scale)-1}var n=Math.floor(Math.log(e)*this._scaleFactor),o=this._maxNormalLowerBoundaryIndex();return n>=o?o:n},r.prototype.lowerBoundary=function(e){var t=this._maxNormalLowerBoundaryIndex();if(e>=t){if(e===t)return 2*Math.exp((e-(1<<this._scale))/this._scaleFactor);throw new jr("overflow: "+e+" is > maximum lower boundary: "+t)}var n=this._minNormalLowerBoundaryIndex();if(e<=n){if(e===n)return Di;if(e===n-1)return Math.exp((e+(1<<this._scale))/this._scaleFactor)/2;throw new jr("overflow: "+e+" is < minimum lower boundary: "+n)}return Math.exp(e*this._inverseFactor)},Object.defineProperty(r.prototype,"scale",{get:function(){return this._scale},enumerable:!1,configurable:!0}),r.prototype._minNormalLowerBoundaryIndex=function(){return As<<this._scale},r.prototype._maxNormalLowerBoundaryIndex=function(){return(ws+1<<this._scale)-1},r}();var dE=-10,mE=20,EI=Array.from({length:31},function(r,e){return e>10?new uE(e-10):new cE(e-10)});function Ku(r){if(r>mE||r<dE)throw new jr("expected scale >= "+dE+" && <= "+mE+", got: "+r);return EI[r+10]}var yI=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},xs=function(){function r(e,t){this.low=e,this.high=t}return r.combine=function(e,t){return new r(Math.min(e.low,t.low),Math.max(e.high,t.high))},r}(),TI=20,bI=160,Yu=2,pE=function(){function r(e,t,n,o,i,a,l,c,s,u,d){e===void 0&&(e=e),t===void 0&&(t=bI),n===void 0&&(n=!0),o===void 0&&(o=0),i===void 0&&(i=0),a===void 0&&(a=0),l===void 0&&(l=Number.POSITIVE_INFINITY),c===void 0&&(c=Number.NEGATIVE_INFINITY),s===void 0&&(s=new $u),u===void 0&&(u=new $u),d===void 0&&(d=Ku(TI)),this.startTime=e,this._maxSize=t,this._recordMinMax=n,this._sum=o,this._count=i,this._zeroCount=a,this._min=l,this._max=c,this._positive=s,this._negative=u,this._mapping=d,this._maxSize<Yu&&(F.warn("Exponential Histogram Max Size set to "+this._maxSize+", changing to the minimum size of: "+Yu),this._maxSize=Yu)}return r.prototype.record=function(e){this.updateByIncrement(e,1)},r.prototype.setStartTime=function(e){this.startTime=e},r.prototype.toPointValue=function(){return{hasMinMax:this._recordMinMax,min:this.min,max:this.max,sum:this.sum,positive:{offset:this.positive.offset,bucketCounts:this.positive.counts()},negative:{offset:this.negative.offset,bucketCounts:this.negative.counts()},count:this.count,scale:this.scale,zeroCount:this.zeroCount}},Object.defineProperty(r.prototype,"sum",{get:function(){return this._sum},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"min",{get:function(){return this._min},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"max",{get:function(){return this._max},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"count",{get:function(){return this._count},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"zeroCount",{get:function(){return this._zeroCount},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"scale",{get:function(){return this._count===this._zeroCount?0:this._mapping.scale},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"positive",{get:function(){return this._positive},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"negative",{get:function(){return this._negative},enumerable:!1,configurable:!0}),r.prototype.updateByIncrement=function(e,t){if(!Number.isNaN(e)){if(e>this._max&&(this._max=e),e<this._min&&(this._min=e),this._count+=t,e===0){this._zeroCount+=t;return}this._sum+=e*t,e>0?this._updateBuckets(this._positive,e,t):this._updateBuckets(this._negative,-e,t)}},r.prototype.merge=function(e){this._count===0?(this._min=e.min,this._max=e.max):e.count!==0&&(e.min<this.min&&(this._min=e.min),e.max>this.max&&(this._max=e.max)),this.startTime=e.startTime,this._sum+=e.sum,this._count+=e.count,this._zeroCount+=e.zeroCount;var t=this._minScale(e);this._downscale(this.scale-t),this._mergeBuckets(this.positive,e,e.positive,t),this._mergeBuckets(this.negative,e,e.negative,t)},r.prototype.diff=function(e){this._min=1/0,this._max=-1/0,this._sum-=e.sum,this._count-=e.count,this._zeroCount-=e.zeroCount;var t=this._minScale(e);this._downscale(this.scale-t),this._diffBuckets(this.positive,e,e.positive,t),this._diffBuckets(this.negative,e,e.negative,t)},r.prototype.clone=function(){return new r(this.startTime,this._maxSize,this._recordMinMax,this._sum,this._count,this._zeroCount,this._min,this._max,this.positive.clone(),this.negative.clone(),this._mapping)},r.prototype._updateBuckets=function(e,t,n){var o=this._mapping.mapToIndex(t),i=!1,a=0,l=0;if(e.length===0?(e.indexStart=o,e.indexEnd=e.indexStart,e.indexBase=e.indexStart):o<e.indexStart&&e.indexEnd-o>=this._maxSize?(i=!0,l=o,a=e.indexEnd):o>e.indexEnd&&o-e.indexStart>=this._maxSize&&(i=!0,l=e.indexStart,a=o),i){var c=this._changeScale(a,l);this._downscale(c),o=this._mapping.mapToIndex(t)}this._incrementIndexBy(e,o,n)},r.prototype._incrementIndexBy=function(e,t,n){if(n!==0){if(e.length===0&&(e.indexStart=e.indexEnd=e.indexBase=t),t<e.indexStart){var o=e.indexEnd-t;o>=e.backing.length&&this._grow(e,o+1),e.indexStart=t}else if(t>e.indexEnd){var o=t-e.indexStart;o>=e.backing.length&&this._grow(e,o+1),e.indexEnd=t}var i=t-e.indexBase;i<0&&(i+=e.backing.length),e.incrementBucket(i,n)}},r.prototype._grow=function(e,t){var n=e.backing.length,o=e.indexBase-e.indexStart,i=n-o,a=sE(t);a>this._maxSize&&(a=this._maxSize);var l=a-o;e.backing.growTo(a,i,l)},r.prototype._changeScale=function(e,t){for(var n=0;e-t>=this._maxSize;)e>>=1,t>>=1,n++;return n},r.prototype._downscale=function(e){if(e!==0){if(e<0)throw new Error("impossible change of scale: "+this.scale);var t=this._mapping.scale-e;this._positive.downscale(e),this._negative.downscale(e),this._mapping=Ku(t)}},r.prototype._minScale=function(e){var t=Math.min(this.scale,e.scale),n=xs.combine(this._highLowAtScale(this.positive,this.scale,t),this._highLowAtScale(e.positive,e.scale,t)),o=xs.combine(this._highLowAtScale(this.negative,this.scale,t),this._highLowAtScale(e.negative,e.scale,t));return Math.min(t-this._changeScale(n.high,n.low),t-this._changeScale(o.high,o.low))},r.prototype._highLowAtScale=function(e,t,n){if(e.length===0)return new xs(0,-1);var o=t-n;return new xs(e.indexStart>>o,e.indexEnd>>o)},r.prototype._mergeBuckets=function(e,t,n,o){for(var i=n.offset,a=t.scale-o,l=0;l<n.length;l++)this._incrementIndexBy(e,i+l>>a,n.at(l))},r.prototype._diffBuckets=function(e,t,n,o){for(var i=n.offset,a=t.scale-o,l=0;l<n.length;l++){var c=i+l>>a,s=c-e.indexBase;s<0&&(s+=e.backing.length),e.decrementBucket(s,n.at(l))}e.trim()},r}();var Xu=function(){function r(e,t){this._maxSize=e,this._recordMinMax=t,this.kind=zt.EXPONENTIAL_HISTOGRAM}return r.prototype.createAccumulation=function(e){return new pE(e,this._maxSize,this._recordMinMax)},r.prototype.merge=function(e,t){var n=t.clone();return n.merge(e),n},r.prototype.diff=function(e,t){var n=t.clone();return n.diff(e),n},r.prototype.toMetricData=function(e,t,n,o){return{descriptor:e,aggregationTemporality:t,dataPointType:or.EXPONENTIAL_HISTOGRAM,dataPoints:n.map(function(i){var a=yI(i,2),l=a[0],c=a[1],s=c.toPointValue(),u=e.type===ne.GAUGE||e.type===ne.UP_DOWN_COUNTER||e.type===ne.OBSERVABLE_GAUGE||e.type===ne.OBSERVABLE_UP_DOWN_COUNTER;return{attributes:l,startTime:c.startTime,endTime:o,value:{min:s.hasMinMax?s.min:void 0,max:s.hasMinMax?s.max:void 0,sum:u?void 0:s.sum,positive:{offset:s.positive.offset,bucketCounts:s.positive.bucketCounts},negative:{offset:s.negative.offset,bucketCounts:s.negative.bucketCounts},count:s.count,scale:s.scale,zeroCount:s.zeroCount}}})}},r}();he();var vI=su("OpenTelemetry SDK Context Key SUPPRESS_TRACING");function gE(r){return r.setValue(vI,!0)}he();function hE(){return function(r){F.error(AI(r))}}function AI(r){return typeof r=="string"?r:JSON.stringify(wI(r))}function wI(r){for(var e={},t=r;t!==null;)Object.getOwnPropertyNames(t).forEach(function(n){if(!e[n]){var o=t[n];o&&(e[n]=String(o))}}),t=Object.getPrototypeOf(t);return e}var RI=hE();function _s(r){try{RI(r)}catch{}}var fE="1.30.1";var CI="process.runtime.name";var xI="service.name";var _I="telemetry.sdk.name",MI="telemetry.sdk.language",II="telemetry.sdk.version";var SE=CI;var EE=xI;var Ui=_I,Fi=MI,Bi=II;var PI="nodejs";var yE=PI;var ho,fn=(ho={},ho[Ui]="opentelemetry",ho[SE]="node",ho[Fi]=yE,ho[Bi]=fE,ho);function zi(r){r.unref()}var FI=9,BI=6,zI=Math.pow(10,BI),zJ=Math.pow(10,FI);function Sn(r){var e=r/1e3,t=Math.trunc(e),n=Math.round(r%1e3*zI);return[t,n]}function fo(r){return r[0]*1e6+r[1]/1e3}var Gi;(function(r){r[r.SUCCESS=0]="SUCCESS",r[r.FAILED=1]="FAILED"})(Gi||(Gi={}));he();function TE(r,e){return new Promise(function(t){so.with(gE(so.active()),function(){r.export(e,function(n){t(n)})})})}var bE={_export:TE};var GI=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},Ms=function(){function r(e,t,n){t===void 0&&(t=0),n===void 0&&(n=[0,0]),this.startTime=e,this._current=t,this.sampleTime=n}return r.prototype.record=function(e){this._current=e,this.sampleTime=Sn(Date.now())},r.prototype.setStartTime=function(e){this.startTime=e},r.prototype.toPointValue=function(){return this._current},r}();var Ju=function(){function r(){this.kind=zt.LAST_VALUE}return r.prototype.createAccumulation=function(e){return new Ms(e)},r.prototype.merge=function(e,t){var n=fo(t.sampleTime)>=fo(e.sampleTime)?t:e;return new Ms(e.startTime,n.toPointValue(),n.sampleTime)},r.prototype.diff=function(e,t){var n=fo(t.sampleTime)>=fo(e.sampleTime)?t:e;return new Ms(t.startTime,n.toPointValue(),n.sampleTime)},r.prototype.toMetricData=function(e,t,n,o){return{descriptor:e,aggregationTemporality:t,dataPointType:or.GAUGE,dataPoints:n.map(function(i){var a=GI(i,2),l=a[0],c=a[1];return{attributes:l,startTime:c.startTime,endTime:o,value:c.toPointValue()}})}},r}();var HI=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},So=function(){function r(e,t,n,o){n===void 0&&(n=0),o===void 0&&(o=!1),this.startTime=e,this.monotonic=t,this._current=n,this.reset=o}return r.prototype.record=function(e){this.monotonic&&e<0||(this._current+=e)},r.prototype.setStartTime=function(e){this.startTime=e},r.prototype.toPointValue=function(){return this._current},r}();var Is=function(){function r(e){this.monotonic=e,this.kind=zt.SUM}return r.prototype.createAccumulation=function(e){return new So(e,this.monotonic)},r.prototype.merge=function(e,t){var n=e.toPointValue(),o=t.toPointValue();return t.reset?new So(t.startTime,this.monotonic,o,t.reset):new So(e.startTime,this.monotonic,n+o)},r.prototype.diff=function(e,t){var n=e.toPointValue(),o=t.toPointValue();return this.monotonic&&n>o?new So(t.startTime,this.monotonic,o,!0):new So(t.startTime,this.monotonic,o-n)},r.prototype.toMetricData=function(e,t,n,o){return{descriptor:e,aggregationTemporality:t,dataPointType:or.SUM,dataPoints:n.map(function(i){var a=HI(i,2),l=a[0],c=a[1];return{attributes:l,startTime:c.startTime,endTime:o,value:c.toPointValue()}}),isMonotonic:this.monotonic}},r}();var En=function(){var r=function(e,t){return r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,o){n.__proto__=o}||function(n,o){for(var i in o)Object.prototype.hasOwnProperty.call(o,i)&&(n[i]=o[i])},r(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");r(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}}(),Gt=function(){function r(){}return r.Drop=function(){return _E},r.Sum=function(){return ME},r.LastValue=function(){return IE},r.Histogram=function(){return PE},r.ExponentialHistogram=function(){return VI},r.Default=function(){return jI},r}();var vE=function(r){En(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.createAggregator=function(t){return e.DEFAULT_INSTANCE},e.DEFAULT_INSTANCE=new Vu,e}(Gt);var AE=function(r){En(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.createAggregator=function(t){switch(t.type){case ne.COUNTER:case ne.OBSERVABLE_COUNTER:case ne.HISTOGRAM:return e.MONOTONIC_INSTANCE;default:return e.NON_MONOTONIC_INSTANCE}},e.MONOTONIC_INSTANCE=new Is(!0),e.NON_MONOTONIC_INSTANCE=new Is(!1),e}(Gt);var wE=function(r){En(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.createAggregator=function(t){return e.DEFAULT_INSTANCE},e.DEFAULT_INSTANCE=new Ju,e}(Gt);var RE=function(r){En(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.createAggregator=function(t){return e.DEFAULT_INSTANCE},e.DEFAULT_INSTANCE=new vs([0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4],!0),e}(Gt);var Ps=function(r){En(e,r);function e(t,n){n===void 0&&(n=!0);var o=r.call(this)||this;if(o._recordMinMax=n,t==null)throw new Error("ExplicitBucketHistogramAggregation should be created with explicit boundaries, if a single bucket histogram is required, please pass an empty array");t=t.concat(),t=t.sort(function(l,c){return l-c});var i=t.lastIndexOf(-1/0),a=t.indexOf(1/0);return a===-1&&(a=void 0),o._boundaries=t.slice(i+1,a),o}return e.prototype.createAggregator=function(t){return new vs(this._boundaries,this._recordMinMax)},e}(Gt);var CE=function(r){En(e,r);function e(t,n){t===void 0&&(t=160),n===void 0&&(n=!0);var o=r.call(this)||this;return o._maxSize=t,o._recordMinMax=n,o}return e.prototype.createAggregator=function(t){return new Xu(this._maxSize,this._recordMinMax)},e}(Gt);var xE=function(r){En(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype._resolve=function(t){switch(t.type){case ne.COUNTER:case ne.UP_DOWN_COUNTER:case ne.OBSERVABLE_COUNTER:case ne.OBSERVABLE_UP_DOWN_COUNTER:return ME;case ne.GAUGE:case ne.OBSERVABLE_GAUGE:return IE;case ne.HISTOGRAM:return t.advice.explicitBucketBoundaries?new Ps(t.advice.explicitBucketBoundaries):PE}return F.warn("Unable to recognize instrument type: "+t.type),_E},e.prototype.createAggregator=function(t){return this._resolve(t).createAggregator(t)},e}(Gt);var _E=new vE,ME=new AE,IE=new wE,PE=new RE,VI=new CE,jI=new xE;var OE=function(r){return Gt.Default()},LE=function(r){return go.CUMULATIVE};var Qu=function(r,e,t,n){function o(i){return i instanceof t?i:new t(function(a){a(i)})}return new(t||(t=Promise))(function(i,a){function l(u){try{s(n.next(u))}catch(d){a(d)}}function c(u){try{s(n.throw(u))}catch(d){a(d)}}function s(u){u.done?i(u.value):o(u.value).then(l,c)}s((n=n.apply(r,e||[])).next())})},Zu=function(r,e){var t={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},n,o,i,a;return a={next:l(0),throw:l(1),return:l(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function l(s){return function(u){return c([s,u])}}function c(s){if(n)throw new TypeError("Generator is already executing.");for(;t;)try{if(n=1,o&&(i=s[0]&2?o.return:s[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,s[1])).done)return i;switch(o=0,i&&(s=[s[0]&2,i.value]),s[0]){case 0:case 1:i=s;break;case 4:return t.label++,{value:s[1],done:!1};case 5:t.label++,o=s[1],s=[0];continue;case 7:s=t.ops.pop(),t.trys.pop();continue;default:if(i=t.trys,!(i=i.length>0&&i[i.length-1])&&(s[0]===6||s[0]===2)){t=0;continue}if(s[0]===3&&(!i||s[1]>i[0]&&s[1]<i[3])){t.label=s[1];break}if(s[0]===6&&t.label<i[1]){t.label=i[1],i=s;break}if(i&&t.label<i[2]){t.label=i[2],t.ops.push(s);break}i[2]&&t.ops.pop(),t.trys.pop();continue}s=e.call(r,t)}catch(u){s=[6,u],o=0}finally{n=i=0}if(s[0]&5)throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}},NE=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},WI=function(r,e,t){if(t||arguments.length===2)for(var n=0,o=e.length,i;n<o;n++)(i||!(n in e))&&(i||(i=Array.prototype.slice.call(e,0,n)),i[n]=e[n]);return r.concat(i||Array.prototype.slice.call(e))},DE=function(){function r(e){var t,n,o;this._shutdown=!1,this._aggregationSelector=(t=e?.aggregationSelector)!==null&&t!==void 0?t:OE,this._aggregationTemporalitySelector=(n=e?.aggregationTemporalitySelector)!==null&&n!==void 0?n:LE,this._metricProducers=(o=e?.metricProducers)!==null&&o!==void 0?o:[],this._cardinalitySelector=e?.cardinalitySelector}return r.prototype.setMetricProducer=function(e){if(this._sdkMetricProducer)throw new Error("MetricReader can not be bound to a MeterProvider again.");this._sdkMetricProducer=e,this.onInitialized()},r.prototype.selectAggregation=function(e){return this._aggregationSelector(e)},r.prototype.selectAggregationTemporality=function(e){return this._aggregationTemporalitySelector(e)},r.prototype.selectCardinalityLimit=function(e){return this._cardinalitySelector?this._cardinalitySelector(e):2e3},r.prototype.onInitialized=function(){},r.prototype.collect=function(e){return Qu(this,void 0,void 0,function(){var t,n,o,i,a,l;return Zu(this,function(c){switch(c.label){case 0:if(this._sdkMetricProducer===void 0)throw new Error("MetricReader is not bound to a MetricProducer");if(this._shutdown)throw new Error("MetricReader is shutdown");return[4,Promise.all(WI([this._sdkMetricProducer.collect({timeoutMillis:e?.timeoutMillis})],NE(this._metricProducers.map(function(s){return s.collect({timeoutMillis:e?.timeoutMillis})})),!1))];case 1:return t=NE.apply(void 0,[c.sent()]),n=t[0],o=t.slice(1),i=n.errors.concat(Hu(o,function(s){return s.errors})),a=n.resourceMetrics.resource,l=n.resourceMetrics.scopeMetrics.concat(Hu(o,function(s){return s.resourceMetrics.scopeMetrics})),[2,{resourceMetrics:{resource:a,scopeMetrics:l},errors:i}]}})})},r.prototype.shutdown=function(e){return Qu(this,void 0,void 0,function(){return Zu(this,function(t){switch(t.label){case 0:return this._shutdown?(F.error("Cannot call shutdown twice."),[2]):e?.timeoutMillis!=null?[3,2]:[4,this.onShutdown()];case 1:return t.sent(),[3,4];case 2:return[4,Vr(this.onShutdown(),e.timeoutMillis)];case 3:t.sent(),t.label=4;case 4:return this._shutdown=!0,[2]}})})},r.prototype.forceFlush=function(e){return Qu(this,void 0,void 0,function(){return Zu(this,function(t){switch(t.label){case 0:return this._shutdown?(F.warn("Cannot forceFlush on already shutdown MetricReader."),[2]):e?.timeoutMillis!=null?[3,2]:[4,this.onForceFlush()];case 1:return t.sent(),[2];case 2:return[4,Vr(this.onForceFlush(),e.timeoutMillis)];case 3:return t.sent(),[2]}})})},r}();he();var $I=function(){var r=function(e,t){return r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,o){n.__proto__=o}||function(n,o){for(var i in o)Object.prototype.hasOwnProperty.call(o,i)&&(n[i]=o[i])},r(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");r(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}}(),Os=function(r,e,t,n){function o(i){return i instanceof t?i:new t(function(a){a(i)})}return new(t||(t=Promise))(function(i,a){function l(u){try{s(n.next(u))}catch(d){a(d)}}function c(u){try{s(n.throw(u))}catch(d){a(d)}}function s(u){u.done?i(u.value):o(u.value).then(l,c)}s((n=n.apply(r,e||[])).next())})},Ls=function(r,e){var t={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},n,o,i,a;return a={next:l(0),throw:l(1),return:l(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function l(s){return function(u){return c([s,u])}}function c(s){if(n)throw new TypeError("Generator is already executing.");for(;t;)try{if(n=1,o&&(i=s[0]&2?o.return:s[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,s[1])).done)return i;switch(o=0,i&&(s=[s[0]&2,i.value]),s[0]){case 0:case 1:i=s;break;case 4:return t.label++,{value:s[1],done:!1};case 5:t.label++,o=s[1],s=[0];continue;case 7:s=t.ops.pop(),t.trys.pop();continue;default:if(i=t.trys,!(i=i.length>0&&i[i.length-1])&&(s[0]===6||s[0]===2)){t=0;continue}if(s[0]===3&&(!i||s[1]>i[0]&&s[1]<i[3])){t.label=s[1];break}if(s[0]===6&&t.label<i[1]){t.label=i[1],i=s;break}if(i&&t.label<i[2]){t.label=i[2],t.ops.push(s);break}i[2]&&t.ops.pop(),t.trys.pop();continue}s=e.call(r,t)}catch(u){s=[6,u],o=0}finally{n=i=0}if(s[0]&5)throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}},qI=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},KI=function(r,e,t){if(t||arguments.length===2)for(var n=0,o=e.length,i;n<o;n++)(i||!(n in e))&&(i||(i=Array.prototype.slice.call(e,0,n)),i[n]=e[n]);return r.concat(i||Array.prototype.slice.call(e))},ed=function(r){$I(e,r);function e(t){var n,o,i,a,l=r.call(this,{aggregationSelector:(n=t.exporter.selectAggregation)===null||n===void 0?void 0:n.bind(t.exporter),aggregationTemporalitySelector:(o=t.exporter.selectAggregationTemporality)===null||o===void 0?void 0:o.bind(t.exporter),metricProducers:t.metricProducers})||this;if(t.exportIntervalMillis!==void 0&&t.exportIntervalMillis<=0)throw Error("exportIntervalMillis must be greater than 0");if(t.exportTimeoutMillis!==void 0&&t.exportTimeoutMillis<=0)throw Error("exportTimeoutMillis must be greater than 0");if(t.exportTimeoutMillis!==void 0&&t.exportIntervalMillis!==void 0&&t.exportIntervalMillis<t.exportTimeoutMillis)throw Error("exportIntervalMillis must be greater than or equal to exportTimeoutMillis");return l._exportInterval=(i=t.exportIntervalMillis)!==null&&i!==void 0?i:6e4,l._exportTimeout=(a=t.exportTimeoutMillis)!==null&&a!==void 0?a:3e4,l._exporter=t.exporter,l}return e.prototype._runOnce=function(){return Os(this,void 0,void 0,function(){var t;return Ls(this,function(n){switch(n.label){case 0:return n.trys.push([0,2,,3]),[4,Vr(this._doRun(),this._exportTimeout)];case 1:return n.sent(),[3,3];case 2:return t=n.sent(),t instanceof Gu?(F.error("Export took longer than %s milliseconds and timed out.",this._exportTimeout),[2]):(_s(t),[3,3]);case 3:return[2]}})})},e.prototype._doRun=function(){var t,n;return Os(this,void 0,void 0,function(){var o,i,a,l,c,s;return Ls(this,function(u){switch(u.label){case 0:return[4,this.collect({timeoutMillis:this._exportTimeout})];case 1:if(o=u.sent(),i=o.resourceMetrics,a=o.errors,a.length>0&&(s=F).error.apply(s,KI(["PeriodicExportingMetricReader: metrics collection errors"],qI(a),!1)),!i.resource.asyncAttributesPending)return[3,5];u.label=2;case 2:return u.trys.push([2,4,,5]),[4,(n=(t=i.resource).waitForAsyncAttributes)===null||n===void 0?void 0:n.call(t)];case 3:return u.sent(),[3,5];case 4:return l=u.sent(),F.debug("Error while resolving async portion of resource: ",l),_s(l),[3,5];case 5:return i.scopeMetrics.length===0?[2]:[4,bE._export(this._exporter,i)];case 6:if(c=u.sent(),c.code!==Gi.SUCCESS)throw new Error("PeriodicExportingMetricReader: metrics export failed (error "+c.error+")");return[2]}})})},e.prototype.onInitialized=function(){var t=this;this._interval=setInterval(function(){t._runOnce()},this._exportInterval),zi(this._interval)},e.prototype.onForceFlush=function(){return Os(this,void 0,void 0,function(){return Ls(this,function(t){switch(t.label){case 0:return[4,this._runOnce()];case 1:return t.sent(),[4,this._exporter.forceFlush()];case 2:return t.sent(),[2]}})})},e.prototype.onShutdown=function(){return Os(this,void 0,void 0,function(){return Ls(this,function(t){switch(t.label){case 0:return this._interval&&clearInterval(this._interval),[4,this.onForceFlush()];case 1:return t.sent(),[4,this._exporter.shutdown()];case 2:return t.sent(),[2]}})})},e}(DE);he();he();function Ns(){return"unknown_service:"+process.argv0}var Wr=function(){return Wr=Object.assign||function(r){for(var e,t=1,n=arguments.length;t<n;t++){e=arguments[t];for(var o in e)Object.prototype.hasOwnProperty.call(e,o)&&(r[o]=e[o])}return r},Wr.apply(this,arguments)},YI=function(r,e,t,n){function o(i){return i instanceof t?i:new t(function(a){a(i)})}return new(t||(t=Promise))(function(i,a){function l(u){try{s(n.next(u))}catch(d){a(d)}}function c(u){try{s(n.throw(u))}catch(d){a(d)}}function s(u){u.done?i(u.value):o(u.value).then(l,c)}s((n=n.apply(r,e||[])).next())})},XI=function(r,e){var t={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},n,o,i,a;return a={next:l(0),throw:l(1),return:l(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function l(s){return function(u){return c([s,u])}}function c(s){if(n)throw new TypeError("Generator is already executing.");for(;t;)try{if(n=1,o&&(i=s[0]&2?o.return:s[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,s[1])).done)return i;switch(o=0,i&&(s=[s[0]&2,i.value]),s[0]){case 0:case 1:i=s;break;case 4:return t.label++,{value:s[1],done:!1};case 5:t.label++,o=s[1],s=[0];continue;case 7:s=t.ops.pop(),t.trys.pop();continue;default:if(i=t.trys,!(i=i.length>0&&i[i.length-1])&&(s[0]===6||s[0]===2)){t=0;continue}if(s[0]===3&&(!i||s[1]>i[0]&&s[1]<i[3])){t.label=s[1];break}if(s[0]===6&&t.label<i[1]){t.label=i[1],i=s;break}if(i&&t.label<i[2]){t.label=i[2],t.ops.push(s);break}i[2]&&t.ops.pop(),t.trys.pop();continue}s=e.call(r,t)}catch(u){s=[6,u],o=0}finally{n=i=0}if(s[0]&5)throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}},JI=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},Ds=function(){function r(e,t){var n=this,o;this._attributes=e,this.asyncAttributesPending=t!=null,this._syncAttributes=(o=this._attributes)!==null&&o!==void 0?o:{},this._asyncAttributesPromise=t?.then(function(i){return n._attributes=Object.assign({},n._attributes,i),n.asyncAttributesPending=!1,i},function(i){return F.debug("a resource's async attributes promise rejected: %s",i),n.asyncAttributesPending=!1,{}})}return r.empty=function(){return r.EMPTY},r.default=function(){var e;return new r((e={},e[EE]=Ns(),e[Fi]=fn[Fi],e[Ui]=fn[Ui],e[Bi]=fn[Bi],e))},Object.defineProperty(r.prototype,"attributes",{get:function(){var e;return this.asyncAttributesPending&&F.error("Accessing resource attributes before async attributes settled"),(e=this._attributes)!==null&&e!==void 0?e:{}},enumerable:!1,configurable:!0}),r.prototype.waitForAsyncAttributes=function(){return YI(this,void 0,void 0,function(){return XI(this,function(e){switch(e.label){case 0:return this.asyncAttributesPending?[4,this._asyncAttributesPromise]:[3,2];case 1:e.sent(),e.label=2;case 2:return[2]}})})},r.prototype.merge=function(e){var t=this,n;if(!e)return this;var o=Wr(Wr({},this._syncAttributes),(n=e._syncAttributes)!==null&&n!==void 0?n:e.attributes);if(!this._asyncAttributesPromise&&!e._asyncAttributesPromise)return new r(o);var i=Promise.all([this._asyncAttributesPromise,e._asyncAttributesPromise]).then(function(a){var l,c=JI(a,2),s=c[0],u=c[1];return Wr(Wr(Wr(Wr({},t._syncAttributes),s),(l=e._syncAttributes)!==null&&l!==void 0?l:e.attributes),u)});return new r(o,i)},r.EMPTY=new r({}),r}();var kE=function(){function r(){this._registeredViews=[]}return r.prototype.addView=function(e){this._registeredViews.push(e)},r.prototype.findViews=function(e,t){var n=this,o=this._registeredViews.filter(function(i){return n._matchInstrument(i.instrumentSelector,e)&&n._matchMeter(i.meterSelector,t)});return o},r.prototype._matchInstrument=function(e,t){return(e.getType()===void 0||t.type===e.getType())&&e.getNameFilter().match(t.name)&&e.getUnitFilter().match(t.unit)},r.prototype._matchMeter=function(e,t){return e.getNameFilter().match(t.name)&&(t.version===void 0||e.getVersionFilter().match(t.version))&&(t.schemaUrl===void 0||e.getSchemaUrlFilter().match(t.schemaUrl))},r}();he();var yn=function(){var r=function(e,t){return r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,o){n.__proto__=o}||function(n,o){for(var i in o)Object.prototype.hasOwnProperty.call(o,i)&&(n[i]=o[i])},r(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");r(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}}(),ks=function(){function r(e,t){this._writableMetricStorage=e,this._descriptor=t}return r.prototype._record=function(e,t,n){if(t===void 0&&(t={}),n===void 0&&(n=so.active()),typeof e!="number"){F.warn("non-number value provided to metric "+this._descriptor.name+": "+e);return}this._descriptor.valueType===Ct.INT&&!Number.isInteger(e)&&(F.warn("INT value type cannot accept a floating-point value for "+this._descriptor.name+", ignoring the fractional digits."),e=Math.trunc(e),!Number.isInteger(e))||this._writableMetricStorage.record(e,t,n,Sn(Date.now()))},r}();var UE=function(r){yn(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.add=function(t,n,o){this._record(t,n,o)},e}(ks);var FE=function(r){yn(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.add=function(t,n,o){if(t<0){F.warn("negative value provided to counter "+this._descriptor.name+": "+t);return}this._record(t,n,o)},e}(ks);var BE=function(r){yn(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.record=function(t,n,o){this._record(t,n,o)},e}(ks);var zE=function(r){yn(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.record=function(t,n,o){if(t<0){F.warn("negative value provided to histogram "+this._descriptor.name+": "+t);return}this._record(t,n,o)},e}(ks);var Us=function(){function r(e,t,n){this._observableRegistry=n,this._descriptor=e,this._metricStorages=t}return r.prototype.addCallback=function(e){this._observableRegistry.addCallback(e,this)},r.prototype.removeCallback=function(e){this._observableRegistry.removeCallback(e,this)},r}();var GE=function(r){yn(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(Us);var HE=function(r){yn(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(Us);var VE=function(r){yn(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(Us);function Hi(r){return r instanceof Us}var jE=function(){function r(e){this._meterSharedState=e}return r.prototype.createGauge=function(e,t){var n=ir(e,ne.GAUGE,t),o=this._meterSharedState.registerMetricStorage(n);return new BE(o,n)},r.prototype.createHistogram=function(e,t){var n=ir(e,ne.HISTOGRAM,t),o=this._meterSharedState.registerMetricStorage(n);return new zE(o,n)},r.prototype.createCounter=function(e,t){var n=ir(e,ne.COUNTER,t),o=this._meterSharedState.registerMetricStorage(n);return new FE(o,n)},r.prototype.createUpDownCounter=function(e,t){var n=ir(e,ne.UP_DOWN_COUNTER,t),o=this._meterSharedState.registerMetricStorage(n);return new UE(o,n)},r.prototype.createObservableGauge=function(e,t){var n=ir(e,ne.OBSERVABLE_GAUGE,t),o=this._meterSharedState.registerAsyncMetricStorage(n);return new HE(n,o,this._meterSharedState.observableRegistry)},r.prototype.createObservableCounter=function(e,t){var n=ir(e,ne.OBSERVABLE_COUNTER,t),o=this._meterSharedState.registerAsyncMetricStorage(n);return new GE(n,o,this._meterSharedState.observableRegistry)},r.prototype.createObservableUpDownCounter=function(e,t){var n=ir(e,ne.OBSERVABLE_UP_DOWN_COUNTER,t),o=this._meterSharedState.registerAsyncMetricStorage(n);return new VE(n,o,this._meterSharedState.observableRegistry)},r.prototype.addBatchObservableCallback=function(e,t){this._meterSharedState.observableRegistry.addBatchCallback(e,t)},r.prototype.removeBatchObservableCallback=function(e,t){this._meterSharedState.observableRegistry.removeBatchCallback(e,t)},r}();var Fs=function(){function r(e){this._instrumentDescriptor=e}return r.prototype.getInstrumentDescriptor=function(){return this._instrumentDescriptor},r.prototype.updateDescription=function(e){this._instrumentDescriptor=ir(this._instrumentDescriptor.name,this._instrumentDescriptor.type,{description:e,valueType:this._instrumentDescriptor.valueType,unit:this._instrumentDescriptor.unit,advice:this._instrumentDescriptor.advice})},r}();var QI=function(){var r=function(e,t){return r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,o){n.__proto__=o}||function(n,o){for(var i in o)Object.prototype.hasOwnProperty.call(o,i)&&(n[i]=o[i])},r(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");r(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}}(),WE=function(r,e){var t={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},n,o,i,a;return a={next:l(0),throw:l(1),return:l(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function l(s){return function(u){return c([s,u])}}function c(s){if(n)throw new TypeError("Generator is already executing.");for(;t;)try{if(n=1,o&&(i=s[0]&2?o.return:s[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,s[1])).done)return i;switch(o=0,i&&(s=[s[0]&2,i.value]),s[0]){case 0:case 1:i=s;break;case 4:return t.label++,{value:s[1],done:!1};case 5:t.label++,o=s[1],s=[0];continue;case 7:s=t.ops.pop(),t.trys.pop();continue;default:if(i=t.trys,!(i=i.length>0&&i[i.length-1])&&(s[0]===6||s[0]===2)){t=0;continue}if(s[0]===3&&(!i||s[1]>i[0]&&s[1]<i[3])){t.label=s[1];break}if(s[0]===6&&t.label<i[1]){t.label=i[1],i=s;break}if(i&&t.label<i[2]){t.label=i[2],t.ops.push(s);break}i[2]&&t.ops.pop(),t.trys.pop();continue}s=e.call(r,t)}catch(u){s=[6,u],o=0}finally{n=i=0}if(s[0]&5)throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}},ZI=function(){function r(e){this._hash=e,this._valueMap=new Map,this._keyMap=new Map}return r.prototype.get=function(e,t){return t??(t=this._hash(e)),this._valueMap.get(t)},r.prototype.getOrDefault=function(e,t){var n=this._hash(e);if(this._valueMap.has(n))return this._valueMap.get(n);var o=t();return this._keyMap.has(n)||this._keyMap.set(n,e),this._valueMap.set(n,o),o},r.prototype.set=function(e,t,n){n??(n=this._hash(e)),this._keyMap.has(n)||this._keyMap.set(n,e),this._valueMap.set(n,t)},r.prototype.has=function(e,t){return t??(t=this._hash(e)),this._valueMap.has(t)},r.prototype.keys=function(){var e,t;return WE(this,function(n){switch(n.label){case 0:e=this._keyMap.entries(),t=e.next(),n.label=1;case 1:return t.done===!0?[3,3]:[4,[t.value[1],t.value[0]]];case 2:return n.sent(),t=e.next(),[3,1];case 3:return[2]}})},r.prototype.entries=function(){var e,t;return WE(this,function(n){switch(n.label){case 0:e=this._valueMap.entries(),t=e.next(),n.label=1;case 1:return t.done===!0?[3,3]:[4,[this._keyMap.get(t.value[0]),t.value[1],t.value[0]]];case 2:return n.sent(),t=e.next(),[3,1];case 3:return[2]}})},Object.defineProperty(r.prototype,"size",{get:function(){return this._valueMap.size},enumerable:!1,configurable:!0}),r}();var $t=function(r){QI(e,r);function e(){return r.call(this,Ts)||this}return e}(ZI);var eP=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},Bs=function(){function r(e,t){this._aggregator=e,this._activeCollectionStorage=new $t,this._cumulativeMemoStorage=new $t,this._overflowAttributes={"otel.metric.overflow":!0},this._cardinalityLimit=(t??2e3)-1,this._overflowHashCode=Ts(this._overflowAttributes)}return r.prototype.record=function(e,t,n,o){var i=this,a=this._activeCollectionStorage.get(t);if(!a){if(this._activeCollectionStorage.size>=this._cardinalityLimit){var l=this._activeCollectionStorage.getOrDefault(this._overflowAttributes,function(){return i._aggregator.createAccumulation(o)});l?.record(e);return}a=this._aggregator.createAccumulation(o),this._activeCollectionStorage.set(t,a)}a?.record(e)},r.prototype.batchCumulate=function(e,t){var n=this;Array.from(e.entries()).forEach(function(o){var i=eP(o,3),a=i[0],l=i[1],c=i[2],s=n._aggregator.createAccumulation(t);s?.record(l);var u=s;if(n._cumulativeMemoStorage.has(a,c)){var d=n._cumulativeMemoStorage.get(a,c);u=n._aggregator.diff(d,s)}else if(n._cumulativeMemoStorage.size>=n._cardinalityLimit&&(a=n._overflowAttributes,c=n._overflowHashCode,n._cumulativeMemoStorage.has(a,c))){var d=n._cumulativeMemoStorage.get(a,c);u=n._aggregator.diff(d,s)}if(n._activeCollectionStorage.has(a,c)){var m=n._activeCollectionStorage.get(a,c);u=n._aggregator.merge(m,u)}n._cumulativeMemoStorage.set(a,s,c),n._activeCollectionStorage.set(a,u,c)})},r.prototype.collect=function(){var e=this._activeCollectionStorage;return this._activeCollectionStorage=new $t,e},r}();var td=function(r){var e=typeof Symbol=="function"&&Symbol.iterator,t=e&&r[e],n=0;if(t)return t.call(r);if(r&&typeof r.length=="number")return{next:function(){return r&&n>=r.length&&(r=void 0),{value:r&&r[n++],done:!r}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")},$E=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},zs=function(){function r(e,t){var n=this;this._aggregator=e,this._unreportedAccumulations=new Map,this._reportHistory=new Map,t.forEach(function(o){n._unreportedAccumulations.set(o,[])})}return r.prototype.buildMetrics=function(e,t,n,o){this._stashAccumulations(n);var i=this._getMergedUnreportedAccumulations(e),a=i,l;if(this._reportHistory.has(e)){var c=this._reportHistory.get(e),s=c.collectionTime;l=c.aggregationTemporality,l===go.CUMULATIVE?a=r.merge(c.accumulations,i,this._aggregator):a=r.calibrateStartTime(c.accumulations,i,s)}else l=e.selectAggregationTemporality(t.type);this._reportHistory.set(e,{accumulations:a,collectionTime:o,aggregationTemporality:l});var u=tP(a);if(u.length!==0)return this._aggregator.toMetricData(t,l,u,o)},r.prototype._stashAccumulations=function(e){var t,n,o=this._unreportedAccumulations.keys();try{for(var i=td(o),a=i.next();!a.done;a=i.next()){var l=a.value,c=this._unreportedAccumulations.get(l);c===void 0&&(c=[],this._unreportedAccumulations.set(l,c)),c.push(e)}}catch(s){t={error:s}}finally{try{a&&!a.done&&(n=i.return)&&n.call(i)}finally{if(t)throw t.error}}},r.prototype._getMergedUnreportedAccumulations=function(e){var t,n,o=new $t,i=this._unreportedAccumulations.get(e);if(this._unreportedAccumulations.set(e,[]),i===void 0)return o;try{for(var a=td(i),l=a.next();!l.done;l=a.next()){var c=l.value;o=r.merge(o,c,this._aggregator)}}catch(s){t={error:s}}finally{try{l&&!l.done&&(n=a.return)&&n.call(a)}finally{if(t)throw t.error}}return o},r.merge=function(e,t,n){for(var o=e,i=t.entries(),a=i.next();a.done!==!0;){var l=$E(a.value,3),c=l[0],s=l[1],u=l[2];if(e.has(c,u)){var d=e.get(c,u),m=n.merge(d,s);o.set(c,m,u)}else o.set(c,s,u);a=i.next()}return o},r.calibrateStartTime=function(e,t,n){var o,i;try{for(var a=td(e.keys()),l=a.next();!l.done;l=a.next()){var c=$E(l.value,2),s=c[0],u=c[1],d=t.get(s,u);d?.setStartTime(n)}}catch(m){o={error:m}}finally{try{l&&!l.done&&(i=a.return)&&i.call(a)}finally{if(o)throw o.error}}return t},r}();function tP(r){return Array.from(r.entries())}var rP=function(){var r=function(e,t){return r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,o){n.__proto__=o}||function(n,o){for(var i in o)Object.prototype.hasOwnProperty.call(o,i)&&(n[i]=o[i])},r(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");r(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}}(),nP=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},qE=function(r){rP(e,r);function e(t,n,o,i,a){var l=r.call(this,t)||this;return l._attributesProcessor=o,l._aggregationCardinalityLimit=a,l._deltaMetricStorage=new Bs(n,l._aggregationCardinalityLimit),l._temporalMetricStorage=new zs(n,i),l}return e.prototype.record=function(t,n){var o=this,i=new $t;Array.from(t.entries()).forEach(function(a){var l=nP(a,2),c=l[0],s=l[1];i.set(o._attributesProcessor.process(c),s)}),this._deltaMetricStorage.batchCumulate(i,n)},e.prototype.collect=function(t,n){var o=this._deltaMetricStorage.collect();return this._temporalMetricStorage.buildMetrics(t,this._instrumentDescriptor,o,n)},e}(Fs);he();function rd(r,e){var t="";return r.unit!==e.unit&&(t+=" - Unit '"+r.unit+"' does not match '"+e.unit+`'
12
+ ${r.code}`;throw r.logger.error({err:e.error,code:r.code,env:r.context.toObjectCopy()},t),new Error(t)}if(e.variableUpdates)for(let[t,n]of Object.entries(e.variableUpdates))r.context.setVariable(t,n);if(e.persistentVariableUpdates&&Object.keys(e.persistentVariableUpdates).length>0){await r.callbacks?.onPersistentVariableUpdates?.(e.persistentVariableUpdates);for(let[t,n]of Object.entries(e.persistentVariableUpdates))r.context.setVariable(t,n)}return e.result}import{set as cM}from"lodash-es";async function xu(r){let{orgId:e,s:t,context:n,logger:o,signal:i,retries:a=2,timeoutMs:l=Hr,allowUndefined:c=!1}=r,s=/{{(.*?)}}/g,u=t.matchAll(s),d=t;for(let p of u){if(p.length<2)continue;let m=p[1].trim(),g;try{g=await ur({orgId:e,code:m,fragment:!0,context:n,timeoutMs:l,logger:o,retries:a,localTools:r.localTools,signal:i})}catch(f){throw o.error({err:f,value:t},"Error evaluating template string"),f}if(g===void 0&&!c)throw new w("UserConfigurationError",`Template fragment '${m}' evaluated to undefined. Please ensure that the variable name is spelled correctly and it is only referenced after being assigned a value.`);let h=typeof g=="string"?g:`${g}`;h=h.replaceAll(/\$/g,"$$$$"),d=d.replace(p[0],h)}return d}async function Ss(r){return Ff(r)}async function Ff({obj:r,bannedKeys:e,allowList:t,context:n,prefixPath:o=[],replacements:i=[],...a}){for(let l in r){if(e.includes(l))continue;let c=!1;if(t)if(t.includes(l))c=!0;else continue;let s=r[l],u=[...o,l];if(typeof s=="string"&&s.includes("{{")){let d=await xu({s,context:n,...a});if(s===d)continue;i.push({path:u,original:s}),r[l]=d}else typeof s=="object"&&s!==null&&!Array.isArray(s)&&await Ff({obj:s,bannedKeys:e,context:n,prefixPath:u,replacements:i,allowList:c?void 0:t,...a})}return i}function ys(r,e){for(let{path:t,original:n}of e)cM(r,t,n)}import uM from"fetch-retry";var YX=process.env.MAILINATOR_API_KEY,XX=uM(global.fetch,{retryOn:function(r,e,t){return r>3?!1:!!(e!==null||t&&t.status>=400)},retryDelay:function(r){return 500}});import{randomUUID as vD}from"crypto";import AD from"path";function _u({steps:r,topLevel:e=!0,...t}){let{stepCacheEntries:n,logger:o,keyPrefix:i}=t,a=[],l=[],c=[],s=0,u=(p,m)=>{try{let g=Gr.parse(m.value);if(g.type!==p.type){o.warn({parsedCacheEntry:g,command:p},"Not using step cache due to type mismatch"),l.push(m.key);return}p.cache=g.cache,a.push(m.key),c.push(m.uniqueKey)}catch(g){l.push(m.key),o.error({err:g,cacheEntry:m},"Not using step cache due to parsing error")}},d=(p,m)=>{let g=mM(p.id,m),h=g.find(f=>!!n[f]);if(h)u(p,n[h]);else{if(p.type==="AI_CHECK")return;l.push(g[0])}};for(let p of r)switch(p.type){case"MOBILE_PRESET_STEP":{if(!Ja(p.command)||p.command.type==="TYPE"&&!p.command.target||"cache"in p.command&&p.command.cache)continue;s++,d(p.command,i);break}case"RESOLVED_MOBILE_MODULE":{s+=p.steps.length;let{cacheKeysHit:m,cacheKeysMissed:g,uniqueKeysHit:h}=_u({...t,steps:p.steps,keyPrefix:i?`${i}:${p.id}`:p.id,topLevel:!1});a.push(...m),l.push(...g),c.push(...h);break}default:{let m=p}}return e&&s&&l.length>0&&o.warn({totalSteps:s,cacheKeysMissed:l,cacheKeysHit:a,uniqueKeysHit:c,cacheEntries:n.length},"Step cache did not fully resolve"),{cacheKeysHit:a,cacheKeysMissed:l,uniqueKeysHit:c}}function pM(r,e){return e?`${e}:${r}`:r}function mM(r,e){let t=[],n=e?.split(":")??[];for(let o=n.length;o>=0;o--){let i=[...n.slice(o),r];t.push(i.join(":"))}return t.reverse(),t}function Mu(r){let{moduleStepParents:e=[],moduleIdParents:t=[]}=r;if(e.length!==t.length)throw new Error(`Invalid cache entry parent length: ${JSON.stringify(e)}
13
+ ${JSON.stringify(t)}`);let n=[];return n.push({key:pM(r.id,e.join(":")),organizationId:r.orgId,value:r.value,testId:r.testId}),n}function Es({cmd:r,newTarget:e,key:t,logger:n}){r.type==="DRAG"?t!=="fromTarget"&&t!=="toTarget"?n.error({cmd:r,newTarget:e,key:t},"Attempted to apply invalid cache to DRAG command"):r.cache={...r.cache,[t]:e}:t==="target"&&km(r)?r.cache={...r.cache,target:e}:n.error({cmd:r,newTarget:e,key:t},"Invalid target cache application")}function bs(r,e,t){let n=r.cache&&"memory"in r.cache?r.cache.memory?.traces:void 0;return JSON.stringify(n)===JSON.stringify(e)?{changed:!1}:(t.info({updatedTraces:e,oldCmd:r},"Wrote new memory to assertion command"),r.cache={...r.cache,memory:{type:"GCS_TRACES",traces:e}},{changed:!0})}function St(r,e,t=!1){return r.length<e?r:r.slice(0,e-3)+(t?"...TRUNCATED...":"[...]")}var vn={EQUALS:"equals",CONTAINS:"contains",STARTS_WITH:"starts with",EXISTS:"exists"},An={EQUALS:"does not equal",CONTAINS:"does not contain",STARTS_WITH:"does not start with",EXISTS:"does not exist"},Bf={EXISTS:"exists",VISIBLE:"is visible",ENABLED:"is enabled",EDITABLE:"is editable",FOCUSED:"is focused"},zf={EXISTS:"does not exist",VISIBLE:"is not visible",ENABLED:"is disabled",EDITABLE:"is not editable",FOCUSED:"is not focused"};var $5={CONTENT:"The page"};function Gf(r){switch(r.type){case"SUBSTRING":return`match substring '${r.url}'`;case"REGEX":return`match regex '${r.regex}'`;case"GLOB":return`match glob '${r.glob}'`;case"DOMAIN":return`match domain '${r.domain}'`;default:return(t=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(r)}}function gM(r){return typeof r=="object"&&r!==null}function Tn(r){if(Array.isArray(r))return r.map(Tn);if(gM(r)){let e={};return Object.entries(r).forEach(([t,n])=>{n!==void 0&&(e[t]=Tn(n))}),e}return r}function hM(r){switch(r.type){case"OPEN_APP":return`Open app: ${r.packageName}`;case"AI_CHECK":return`AI check: ${r.assertion}`;case"TAP":return`Tap on element: ${ou(r.target)}`;case"TYPE":return`Type ${r.text} ${r.target?`into ${ou(r.target)}`:""}`;case"PRESS":return`Press the ${r.key} button`;case"PRESS_KEYBOARD":return`Press the ${r.key} key`;case"JAVASCRIPT":return`Execute JavaScript: ${r.code}`;case"OPEN_NOTIFICATION_DRAWER":return"Open notification drawer";case"ADB":return`ADB command: ${r.command}`;case"STATE":return"Get state";default:{let e=r;throw new Error("If Typescript complains about the line above, you missed a case or break in the switch above")}}}function Hf(r){switch(r.type){case"MOBILE_PRESET_STEP":return hM(r.command);case"MOBILE_MODULE_STEP":return`Module ${r.moduleId}`;case"RESOLVED_MOBILE_MODULE":return`Module ${r.name}`;default:{let e=r;throw new Error("If Typescript complains about the line above, you missed a case or break in the switch above")}}}import{cloneDeep as Vf}from"lodash-es";async function jf(r){let e={},{resolvedSteps:t,newSchemaVersion:n}=await Ts({rawSteps:r.rawStepLists.steps,onFetchModule:r.onFetchModule,logger:r.logger,metadata:r.testMetadata,resolvedModuleCache:e}),o={steps:t};for(let i of["beforeSteps","afterSteps"]){let a=r.rawStepLists[i];if(!a)continue;let{resolvedSteps:l}=await Ts({rawSteps:a,onFetchModule:r.onFetchModule,logger:r.logger,metadata:r.testMetadata,resolvedModuleCache:e});o[i]=l}return{resolvedStepLists:o,moduleIds:Array.from(Object.keys(e))}}async function Ts({rawSteps:r,onFetchModule:e,logger:t,metadata:n,resolvedModuleCache:o={}}){let i=[];for(let a of r)i.push(await Wf({rawStep:Yt.parse(a),onFetchModule:e,logger:t,resolvedModuleCache:o}));return{resolvedSteps:i,newSchemaVersion:n.schemaVersion}}async function Wf({rawStep:r,onFetchModule:e,logger:t,resolvedModuleCache:n}){switch(r.type){case"MOBILE_MODULE_STEP":{let o=r.moduleId,i=n[o];if(i)return{...Vf(i),...r,type:"RESOLVED_MOBILE_MODULE"};let a=await e(o);if(!a)throw new Error(`Could not find module with id ${o}`);let l;try{l=Yt.array().parse(a.steps)}catch(u){throw t.error({err:u,steps:a.steps,moduleId:o},"Module failed to parse (mobile)"),u}let c=await Promise.all(l.map(u=>Wf({rawStep:u,onFetchModule:e,logger:t,resolvedModuleCache:n}))),s={...a,steps:c};return n[o]=Vf(s),{...s,...r,type:"RESOLVED_MOBILE_MODULE"}}case"MOBILE_PRESET_STEP":return r}}import{cloneDeep as fM}from"lodash-es";import{v4 as Iu}from"uuid";async function Rn(r){let e=new Map,t=new Set,n=fM(r.steps),o=await $f({...r,steps:n,moduleStepParents:[],moduleIdParents:[],moduleIdReplacements:e,seenModules:t});return{stepsToSave:o.stepsToSave,cachesToSave:o.cachesToSave,moduleUpdates:o.moduleUpdates}}async function $f({steps:r,...e}){let{seenModules:t,cacheCreationParams:n,moduleIdParents:o,moduleStepParents:i,moduleIdReplacements:a,shouldCreateNewModuleId:l,createNewCacheIds:c}=e,s={cachesToSave:[],stepsToSave:[],moduleUpdates:[]};for(let u of r)switch(u.id=c?Iu():u.id,u.type){case"MOBILE_PRESET_STEP":{let d=u.command;d.id=c?Iu():d.id,"cache"in d&&d.cache&&(n&&(s.cachesToSave=s.cachesToSave.concat(Mu({id:d.id,orgId:n.orgId,testId:n.testId,value:Gr.parse(d),moduleIdParents:o,moduleStepParents:i}))),delete d.cache),s.stepsToSave.push({...u,command:d});break}case"RESOLVED_MOBILE_MODULE":{let d=c?Iu():u.id,p=u.moduleId;a.has(p)?p=a.get(p):l!==void 0&&(p=await l(u),a.set(u.moduleId,p));let{cachesToSave:m,stepsToSave:g,moduleUpdates:h}=await $f({...e,steps:u.steps,cacheCreationParams:n?{...n}:void 0,createNewCacheIds:!1,moduleStepParents:[...i,d],moduleIdParents:[...o,p],skipCacheIntermediateEntries:c});s.moduleUpdates=s.moduleUpdates.concat(h),s.cachesToSave=s.cachesToSave.concat(m),t.has(p)||(t.add(p),s.moduleUpdates.push({...po.parse(u),steps:Yt.array().parse(g),moduleId:p}));let f=Ci.parse({...u,type:"MOBILE_MODULE_STEP",moduleId:p,inputs:u.inputs,id:d});s.stepsToSave.push(f);break}default:{let d=u}}return s}function SM(r){let e={parentChain:[]};return qf(r,e),e}function qf(r,e){let{onPreset:t,onModule:n,earlyStop:o}=r;for(let i of r.steps){if(i.type==="RESOLVED_MOBILE_MODULE"){if(n?.(i,e)&&o||(e.parentChain.push(i),qf({...r,steps:i.steps},e)&&o))return!0;e.parentChain.pop();continue}if(t(i,e)&&o)return!0}return!1}function yM(r,e,t=[]){let n,o=[],i=(a,l)=>{let c=JSON.stringify(l.parentChain.map(u=>u.id)),s=t.length===0?!0:JSON.stringify(t)===c;return a.id===e&&s?(n=a,o=l.parentChain,!0):!1};return SM({steps:r,earlyStop:!0,onPreset:i,onModule:i}),{result:n,parentChain:o}}function Kf({currentStep:r,currentParentChain:e,desiredStepId:t,desiredStepParentChain:n}){let o=Array.from(e),i=Array.from(n);for(let l=0;l<o.length;l++){if(o[l]!==i[l])return!1;i.shift()}return!!yM([r],t,i).result}function Yf(r){let e=r[0],t=r[0],n=!1;for(;!n&&t;)switch(t.type){case"MOBILE_MODULE_STEP":if(!t.steps.length){e=t,n=!0;break}t=t.steps[0];break;case"MOBILE_PRESET_STEP":e=t,n=!0;break;default:{let l=t}}let o=r[r.length-1],i=r[r.length-1],a=!1;for(;!a&&i;)switch(i.type){case"MOBILE_MODULE_STEP":if(!i.steps.length){o=i,a=!0;break}i=i.steps[i.steps.length-1];break;case"MOBILE_PRESET_STEP":o=i,a=!0;break;default:{let l=i}}return{firstMetadata:e,lastMetadata:o}}function Xf({result:r,firstMetadata:e,lastMetadata:t}){e&&(r.beforeSnapshot=e.beforeSnapshot),t&&(r.data=t.data,r.afterSnapshot=t.afterSnapshot,t.status!=="SUCCESS"&&(r.message=t.message))}import{cloneDeep as H3}from"lodash-es";import j3 from"truncate-json";import{v4 as Z3}from"uuid";import{cloneDeep as O3,unset as L3}from"lodash-es";import{cloneDeep as o4}from"lodash-es";import{cloneDeep as xJ}from"lodash-es";import K4 from"diff-lines";import Pu,{gte as X4}from"semver";var Jf={name:"Migrate to ai step v2",fromVersion:"1.0.4",toVersion:"1.0.5",recursiveKeys:new Set(["results","commands"]),stopOnFailure:!0,execute:async r=>(r=r.filter(e=>!(e.status!==void 0&&e.type==="AI_ACTION")),r=r.map(e=>(e.status===void 0||e.type==="PRESET_ACTION"&&(e.results=e.commands??e.results??[]),e)),r)};var Qf={name:"Make sure ai step v2 has done command",fromVersion:"1.0.5",toVersion:"1.0.6",recursiveKeys:new Set(["results","commands"]),stopOnFailure:!0,execute:async r=>r.map(e=>{if(e.type!=="AI_ACTION"||e.status!==void 0||!e.commands||!e.commands.length)return e;let t=e.commands,n=t[t.length-1];return n&&n.type!=="SUCCESS"&&t.push({type:"SUCCESS"}),e})};var EM=["target","fromTarget","toTarget"];function Zf(r){for(let e of EM){if(r[e]===void 0)continue;let t=r[e];t.elementDescriptor!==void 0?t.type="description":r[e]={type:"description",elementDescriptor:""}}}var eS={name:"Migrate element target to discriminated union",fromVersion:"1.0.6",toVersion:"1.0.7",recursiveKeys:new Set(["results","steps"]),stopOnFailure:!0,execute:async r=>r.map(e=>{switch(e.type){case"PRESET_ACTION":return Zf(e.command),e;case"AI_ACTION":{let t=e.commands;for(let n of t??[])Zf(n);return e}default:return e}})};import{v4 as bM}from"uuid";var tS={name:"Ensure module steps have ids",fromVersion:"1.0.7",toVersion:"1.0.8",recursiveKeys:new Set(["results","steps"]),stopOnFailure:!0,execute:async r=>r.map(e=>{switch(e.type){case"MODULE":return e.id||(e.id=bM()),e;default:return e}})};import{v4 as rS}from"uuid";var nS={name:"Ensure module steps have ids",fromVersion:"1.0.8",toVersion:"1.0.9",recursiveKeys:new Set(["results","steps"]),stopOnFailure:!0,execute:async r=>r.map(e=>{switch(e.type){case"PRESET_ACTION":{if(!e.command)return e;let t=e.command;return t.id=t.id??rS(),e}case"AI_ACTION":return e.commands&&(e.steps=e.commands.map(t=>({type:"PRESET_ACTION",command:{...t,id:t.id??rS()}})),delete e.commands),e;default:return e}})};var oS={name:"Migrate ai waits to checks",fromVersion:"1.0.9",toVersion:"1.0.10",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!0,execute:async r=>r.map(e=>{switch(e.type){case"PRESET_ACTION":{if(!e.command)return e;let t=e.command;return typeof t.type!="string"||t.type!=="AI_WAIT"||(t.type="AI_ASSERTION",t.timeout||(t.timeout=10)),e}default:return e}})};import{v4 as TM}from"uuid";var iS={name:"Add ids to all steps",fromVersion:"1.0.10",toVersion:"1.0.11",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!0,execute:async r=>r.map(e=>("id"in e&&typeof e.id=="string"||(e.id=TM()),e))};import{v4 as aS}from"uuid";var sS={name:"Add ids to all steps",fromVersion:"1.0.11",toVersion:"1.0.12",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!0,execute:async r=>r.map(e=>{if("id"in e&&typeof e.id=="string")return e;if("condition"in e&&typeof e.condition=="object"&&e.condition){let t=e.condition;t.id||(t.id=aS())}return e.id=aS(),e})};var lS={name:"Move env key to steps",fromVersion:"1.0.12",toVersion:"1.0.13",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!0,execute:async r=>r.map(e=>{if(e.type!=="PRESET_ACTION")return e;let t=e.command;return!t||typeof t.envKey!="string"||(e.envKey=t.envKey,delete t.envKey),e})};import{v4 as vM}from"uuid";var cS={name:"Redo last two migrations",fromVersion:"1.0.13",toVersion:"1.0.14",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!0,execute:async r=>r.map(e=>{if((!("id"in e)||typeof e.id!="string")&&(e.id=vM()),e.type!=="PRESET_ACTION")return e;let t=e.command;return!t||typeof t.envKey!="string"||(e.envKey=t.envKey,delete t.envKey),e})};var uS={name:"Migrate select choice",fromVersion:"1.0.14",toVersion:"1.0.15",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!0,execute:async r=>r.map(e=>{if(e.type!=="PRESET_ACTION")return e;let t=e.command;return!t||t.type!=="SELECT_OPTION"||e.option===void 0||(e.choice={type:"VALUE",value:t.option},e.option=void 0),e})};var dS={name:"Migrate select choice",fromVersion:"1.0.15",toVersion:"1.0.16",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!0,execute:async r=>r.map(e=>{if(e.type!=="PRESET_ACTION")return e;let t=e.command;return t&&pS(t),e})};function pS(r){r&&Object.keys(r).forEach(e=>{if(typeof r[e]=="object"&&r[e]){pS(r[e]);return}if(typeof r[e]!="string")return;let t=r[e];e==="code"?r[e]=t.replace(/inputs\./g,"env."):t.includes("{{")&&t.includes("}}")&&(r[e]=t.replace(/inputs\./g,"env."))})}var mS={name:"Migrate switch tab choice",fromVersion:"1.0.16",toVersion:"1.0.17",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!0,execute:async r=>r.map(e=>{if(e.type!=="PRESET_ACTION")return e;let t=e.command;return!t||t.type!=="TAB"||t.url===void 0||(t.action={type:"SUBSTRING",substring:t.url},t.url=void 0),e})};var gS={name:"Remove press keys sequentially",fromVersion:"1.0.17",toVersion:"1.0.18",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!1,execute:async r=>r.map(e=>{if(e.type!=="PRESET_ACTION")return e;let t=e.command;return!t||t.type!=="TYPE"?e:t.pressKeysSequentially===void 0?(t.delay=0,e):(t.pressKeysSequentially&&(t.pressKeysSequentially=void 0,t.delay=50),e)})};var hS={name:"Migrate wait for URL to matcher",fromVersion:"1.0.18",toVersion:"1.0.19",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!1,execute:async r=>r.map(e=>{if(e.type!=="PRESET_ACTION")return e;let t=e.command;return!t||t.type!=="WAIT_FOR_URL"||t.url===void 0||(t.matcher={type:"GLOB",glob:t.url},t.url=void 0),e})};var fS={name:"Migrate select choice round 2",fromVersion:"1.0.19",toVersion:"1.0.20",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!0,execute:async r=>r.map(e=>{if(e.type!=="PRESET_ACTION")return e;let t=e.command;if(!t)return e;if(t.type==="SELECT_OPTION"){if(t.option===void 0)return e;t.choice={type:"VALUE",value:t.option},t.option=void 0}else if(t.type==="TAB"){if(t.url===void 0)return e;t.action={type:"SUBSTRING",substring:t.url},t.url=void 0}else if(t.type==="WAIT_FOR_URL"){if(t.url===void 0)return e;t.matcher={type:"GLOB",glob:t.url},t.url=void 0}else t.type==="AI_WAIT"&&(t.type="AI_ASSERTION",t.timeout||(t.timeout=10));return e})};var SS={name:"Migrate ",fromVersion:"1.0.20",toVersion:"1.0.21",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!1,execute:async r=>r.map(e=>{if(e.type!=="PRESET_ACTION")return e;let t=e.command;return!t||t.type!=="MOCK_ROUTE"&&t.type!=="SET_HEADER"&&t.type!=="RECORD_REQUESTS"&&t.type!=="REGISTER_REQUEST_LISTENER"||(t.type==="REGISTER_REQUEST_LISTENER"||t.type==="RECORD_REQUESTS"?t.requestMatcher={urlMatcher:{type:"REGEX",regex:t.pattern}}:(t.type==="SET_HEADER"||t.type==="MOCK_ROUTE")&&t.urlPattern&&(t.requestMatcher={urlMatcher:{type:"REGEX",regex:t.urlPattern}})),e})};var yS={name:"Migrate AI checks to preset actions",fromVersion:"1.0.0",toVersion:"1.0.1",recursiveKeys:new Set,execute:async r=>r.map(e=>{if(e.type!=="AI_ASSERTION")return e;let n={type:"PRESET_ACTION",command:{type:"AI_ASSERTION",assertion:e.text,useVision:!1,disableCache:!0}},o={...e,...n};return delete o.text,o}),stopOnFailure:!0};var vs=new Set(["CLICK","TYPE","SELECT_OPTION"]),ES={name:"Migrate element descriptor to live in a target object",fromVersion:"1.0.3",toVersion:"1.0.4",recursiveKeys:new Set,execute:async r=>r.map(e=>{let t=e.command,n=t?.type,o=t?.elementDescriptor;return(o!==void 0||vs.has(n))&&(t.target={elementDescriptor:o??""}),e.commands&&Array.isArray(e.commands)&&e.commands.forEach(a=>{let l=a?.elementDescriptor,c=a?.type;(l!==void 0||vs.has(c))&&(a.target={elementDescriptor:l??""})}),e.results&&Array.isArray(e.results)&&e.results.forEach(a=>{let l=a.command,c=l?.elementDescriptor,s=l?.type;(c!==void 0||vs.has(s))&&(l.target={elementDescriptor:c??""}),a.commands&&Array.isArray(a.commands)&&a.commands.forEach(d=>{let p=d?.elementDescriptor,m=d?.type;(p!==void 0||vs.has(m))&&(d.target={elementDescriptor:p??""})})}),e}),stopOnFailure:!0};var bS={name:"Migrate FAILURE status to FAILED",fromVersion:"1.0.1",toVersion:"1.0.2",recursiveKeys:new Set,execute:async r=>r.map(e=>{let t=e;return t.status==="FAILURE"&&(t.status="FAILED"),typeof t.commands=="object"&&Array.isArray(t.commands)&&t.commands.forEach(n=>{if(n&&typeof n=="object"){let o=n;o?.status==="FAILURE"&&(o.status="FAILED")}}),t}),stopOnFailure:!0};var TS={name:"Migrate preset step types to use the same",fromVersion:"1.0.2",toVersion:"1.0.3",recursiveKeys:new Set,execute:async r=>r.map(e=>{let t=e.command,n=t?.type;return n?.startsWith("PRESET_")&&(t.type=n.slice(7)),e.commands&&Array.isArray(e.commands)&&e.commands.forEach(i=>{let a=i.type;a?.startsWith("PRESET_")&&(i.type=a.slice(7))}),e.results&&Array.isArray(e.results)&&e.results.forEach(i=>{let a=i.command,l=a?.type;l?.startsWith("PRESET_")&&(a.type=l.slice(7)),i.commands&&Array.isArray(i.commands)&&i.commands.forEach(s=>{let u=s.type;u?.startsWith("PRESET_")&&(s.type=u.slice(7))})}),e}),stopOnFailure:!0};var As=[yS,bS,TS,ES,Jf,Qf,eS,tS,nS,oS,iS,sS,lS,cS,uS,dS,mS,gS,hS,fS,SS];if(un!==As[As.length-1].toVersion)throw new Error("Please bump LATEST_SCHEMA_VERSION in types package after adding a migration");As.forEach((r,e)=>{if(!Pu.valid(r.toVersion)||!Pu.valid(r.fromVersion))throw new Error(`Migration '${r.name}' has invalid version`);if(!Pu.gt(r.toVersion,r.fromVersion))throw new Error(`Migration '${r.name}' has toVersion <= fromVersion`);if(e===0)return;if(As[e-1].toVersion!==r.fromVersion)throw new Error(`Migration '${r.name}' at index ${e} is not contiguous with previous migration`)});import{diff as WJ}from"deep-object-diff";import{cloneDeep as qJ}from"lodash-es";import{v4 as l8}from"uuid";import{cloneDeep as p8}from"lodash-es";import{stringify as R8}from"yaml";async function $(r,e){if(!(r<=0))return new Promise((t,n)=>{if(e?.aborted){n(e.reason);return}e?.addEventListener("abort",i);let o=setTimeout(()=>{e?.removeEventListener("abort",i),t()},r);function i(){clearTimeout(o),e?.removeEventListener("abort",i),n(e?.reason)}})}async function Ou({promiseGenerator:r,signal:e,codePath:t,logger:n}){let i=Date.now(),a=setInterval(()=>{if(e?.aborted){clearInterval(a);return}n?.warn({codePath:t,startTime:i,elapsedMilliseconds:Date.now()-i},`Asynchronous operation is taking a long time (${t})`)},5e3);return new Promise((l,c)=>{function s(){clearInterval(a),e?.removeEventListener("abort",s),c(e?.reason)}if(e?.aborted){c(e?.reason),clearInterval(a);return}e?.addEventListener("abort",s),(async()=>{try{l(await r())}catch(u){c(u)}finally{clearInterval(a),e?.removeEventListener("abort",s)}})()})}async function wn({promiseGenerator:r,timeoutMs:e,codePath:t,logger:n,signal:o}){let i=!1,a=new AbortController,l=()=>{a.abort()},c=setTimeout(()=>{i||a.abort()},e);o?.addEventListener("abort",l);try{return await Ou({promiseGenerator:r,signal:a.signal,codePath:t,logger:n})}finally{i=!0,o?.removeEventListener("abort",l),clearTimeout(c)}}function Rs(r){let e;return r>10*60*1e3?e=2*60*1e3:r>60*1e3?e=20*1e3:r>10*1e3?e=2*1e3:e=1e3,e}import AM from"picomatch";var ws=(r,e,t)=>{t?.caseInsensitive&&(r=r.toLowerCase());let n;switch(e.type){case"SUBSTRING":{let o=t?.caseInsensitive?e.url.toLowerCase():e.url;n=r.includes(o);break}case"GLOB":{let o=t?.caseInsensitive?e.glob.toLowerCase():e.glob;n=r===e.glob||AM(o)(r);break}case"REGEX":{n=new RegExp(e.regex).test(r);break}case"DOMAIN":{let o=t?.caseInsensitive?e.domain.toLowerCase():e.domain;n=new URL(r).hostname===o;break}}return t?.negated?!n:n},Cs=(r,e)=>{try{let{hostname:t,pathname:n}=new URL(r),{hostname:o,pathname:i}=new URL(e);return t!==o||n!==i}catch{return!1}},So=r=>{try{return new URL(r),!0}catch{return!1}},AS=r=>!r.toLowerCase().startsWith("http"),yo=(r,e)=>{try{return new URL(r,e),!0}catch{return!1}};function Cn(r,e){try{return!!new URL(r).origin.trim()}catch(t){return e?.error({url:r,err:t},"Invalid URL in check"),!1}}import{v4 as RS}from"uuid";function Lu(r,e){return{...r,testId:e?.testId??"",testName:e?.testName??"",suiteId:e?.suiteId??"",suiteName:e?.suiteName??""}}var xs=class{reporter;asyncWork;metadata;creditsUsedV1=0;creditsUsedV2=0;constructor({logger:e,reporter:t,runType:n,runId:o,testMetadata:i,suiteMetadata:a}){this.reporter=t,this.metadata={testId:i.id,testName:i.name,suiteId:a?.id,suiteName:a?.name},this.asyncWork=[t.reportBillableEvents(e,[{event:n,timestamp:new Date().toISOString(),transactionId:o,properties:Lu({},this.metadata)}]).catch(l=>e.error({err:l},"Failed to report billable event"))]}trackStepExecution(e){if(rh(e.type)){this.creditsUsedV2+=1;return}let t=Jc(e.type);if(this.creditsUsedV1+=t??0,e.type==="PRESET_ACTION"){this.creditsUsedV2+=1;let n=Qc(e.command);this.creditsUsedV1+=n??0}}async flush(e){this.creditsUsedV1>0&&this.asyncWork.push(this.reporter.reportBillableEvents(e,[{event:"credits-used",timestamp:new Date().toISOString(),transactionId:RS(),properties:Lu({creditsUsed:this.creditsUsedV1},this.metadata)}]).catch(t=>e.error({err:t},"Failed to report credits used"))),this.creditsUsedV2>0&&this.asyncWork.push(this.reporter.reportBillableEvents(e,[{event:"credits-used-v2",timestamp:new Date().toISOString(),transactionId:RS(),properties:Lu({creditsUsed:this.creditsUsedV2},this.metadata)}]).catch(t=>e.error({err:t},"Failed to report credits used"))),await Promise.allSettled(this.asyncWork)}};import{mkdirSync as QO}from"fs";import{tmpdir as ZO}from"os";import Nb from"path";import{diff as XO}from"deep-object-diff";import{cloneDeep as JO}from"lodash-es";var _s=class{increment(e,t,n){}gauge(e,t){}distribution(e,t,n){}async flush(){}async recordDuration({fn:e}){return await e()}};function RM(r){if(!r||r.length===0)return{};let e={};for(let t of r){let n=t.indexOf(":");if(n>-1){let o=t.slice(0,n).trim(),i=t.slice(n+1).trim();o&&(e[o]=i);continue}e[t]=!0}return e}function Ms(r,e){let t=RM(r);return!e||Object.keys(e).length===0?t:{...e,...t}}var JS="=",Ls=";",Wu=",";var QS=8192;var vo={};$A(vo,{getKeyPairs:()=>nI,parseKeyPairsIntoRecord:()=>oI,parsePairKeyValue:()=>ZS,serializeKeyPairs:()=>rI});he();var tI=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i};function rI(r){return r.reduce(function(e,t){var n=""+e+(e!==""?Wu:"")+t;return n.length>QS?e:n},"")}function nI(r){return r.getAllEntries().map(function(e){var t=tI(e,2),n=t[0],o=t[1],i=encodeURIComponent(n)+"="+encodeURIComponent(o.value);return o.metadata!==void 0&&(i+=Ls+o.metadata.toString()),i})}function ZS(r){var e=r.split(Ls);if(!(e.length<=0)){var t=e.shift();if(t){var n=t.indexOf(JS);if(!(n<=0)){var o=decodeURIComponent(t.substring(0,n).trim()),i=decodeURIComponent(t.substring(n+1).trim()),a;return e.length>0&&(a=Du(e.join(Ls))),{key:o,value:i,metadata:a}}}}}function oI(r){return typeof r!="string"||r.length===0?{}:r.split(Wu).map(function(e){return ZS(e)}).filter(function(e){return e!==void 0&&e.value.length>0}).reduce(function(e,t){return e[t.key]=t.value,e},{})}he();var Ns;(function(r){r.AlwaysOff="always_off",r.AlwaysOn="always_on",r.ParentBasedAlwaysOff="parentbased_always_off",r.ParentBasedAlwaysOn="parentbased_always_on",r.ParentBasedTraceIdRatio="parentbased_traceidratio",r.TraceIdRatio="traceidratio"})(Ns||(Ns={}));var iI=",",aI=["OTEL_SDK_DISABLED"];function sI(r){return aI.indexOf(r)>-1}var lI=["OTEL_BSP_EXPORT_TIMEOUT","OTEL_BSP_MAX_EXPORT_BATCH_SIZE","OTEL_BSP_MAX_QUEUE_SIZE","OTEL_BSP_SCHEDULE_DELAY","OTEL_BLRP_EXPORT_TIMEOUT","OTEL_BLRP_MAX_EXPORT_BATCH_SIZE","OTEL_BLRP_MAX_QUEUE_SIZE","OTEL_BLRP_SCHEDULE_DELAY","OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT","OTEL_ATTRIBUTE_COUNT_LIMIT","OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT","OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT","OTEL_LOGRECORD_ATTRIBUTE_VALUE_LENGTH_LIMIT","OTEL_LOGRECORD_ATTRIBUTE_COUNT_LIMIT","OTEL_SPAN_EVENT_COUNT_LIMIT","OTEL_SPAN_LINK_COUNT_LIMIT","OTEL_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT","OTEL_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT","OTEL_EXPORTER_OTLP_TIMEOUT","OTEL_EXPORTER_OTLP_TRACES_TIMEOUT","OTEL_EXPORTER_OTLP_METRICS_TIMEOUT","OTEL_EXPORTER_OTLP_LOGS_TIMEOUT","OTEL_EXPORTER_JAEGER_AGENT_PORT"];function cI(r){return lI.indexOf(r)>-1}var uI=["OTEL_NO_PATCH_MODULES","OTEL_PROPAGATORS"];function dI(r){return uI.indexOf(r)>-1}var $u=1/0,qu=128,pI=128,mI=128,Ku={OTEL_SDK_DISABLED:!1,CONTAINER_NAME:"",ECS_CONTAINER_METADATA_URI_V4:"",ECS_CONTAINER_METADATA_URI:"",HOSTNAME:"",KUBERNETES_SERVICE_HOST:"",NAMESPACE:"",OTEL_BSP_EXPORT_TIMEOUT:3e4,OTEL_BSP_MAX_EXPORT_BATCH_SIZE:512,OTEL_BSP_MAX_QUEUE_SIZE:2048,OTEL_BSP_SCHEDULE_DELAY:5e3,OTEL_BLRP_EXPORT_TIMEOUT:3e4,OTEL_BLRP_MAX_EXPORT_BATCH_SIZE:512,OTEL_BLRP_MAX_QUEUE_SIZE:2048,OTEL_BLRP_SCHEDULE_DELAY:5e3,OTEL_EXPORTER_JAEGER_AGENT_HOST:"",OTEL_EXPORTER_JAEGER_AGENT_PORT:6832,OTEL_EXPORTER_JAEGER_ENDPOINT:"",OTEL_EXPORTER_JAEGER_PASSWORD:"",OTEL_EXPORTER_JAEGER_USER:"",OTEL_EXPORTER_OTLP_ENDPOINT:"",OTEL_EXPORTER_OTLP_TRACES_ENDPOINT:"",OTEL_EXPORTER_OTLP_METRICS_ENDPOINT:"",OTEL_EXPORTER_OTLP_LOGS_ENDPOINT:"",OTEL_EXPORTER_OTLP_HEADERS:"",OTEL_EXPORTER_OTLP_TRACES_HEADERS:"",OTEL_EXPORTER_OTLP_METRICS_HEADERS:"",OTEL_EXPORTER_OTLP_LOGS_HEADERS:"",OTEL_EXPORTER_OTLP_TIMEOUT:1e4,OTEL_EXPORTER_OTLP_TRACES_TIMEOUT:1e4,OTEL_EXPORTER_OTLP_METRICS_TIMEOUT:1e4,OTEL_EXPORTER_OTLP_LOGS_TIMEOUT:1e4,OTEL_EXPORTER_ZIPKIN_ENDPOINT:"http://localhost:9411/api/v2/spans",OTEL_LOG_LEVEL:we.INFO,OTEL_NO_PATCH_MODULES:[],OTEL_PROPAGATORS:["tracecontext","baggage"],OTEL_RESOURCE_ATTRIBUTES:"",OTEL_SERVICE_NAME:"",OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT:$u,OTEL_ATTRIBUTE_COUNT_LIMIT:qu,OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT:$u,OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT:qu,OTEL_LOGRECORD_ATTRIBUTE_VALUE_LENGTH_LIMIT:$u,OTEL_LOGRECORD_ATTRIBUTE_COUNT_LIMIT:qu,OTEL_SPAN_EVENT_COUNT_LIMIT:128,OTEL_SPAN_LINK_COUNT_LIMIT:128,OTEL_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT:pI,OTEL_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT:mI,OTEL_TRACES_EXPORTER:"",OTEL_TRACES_SAMPLER:Ns.ParentBasedAlwaysOn,OTEL_TRACES_SAMPLER_ARG:"",OTEL_LOGS_EXPORTER:"",OTEL_EXPORTER_OTLP_INSECURE:"",OTEL_EXPORTER_OTLP_TRACES_INSECURE:"",OTEL_EXPORTER_OTLP_METRICS_INSECURE:"",OTEL_EXPORTER_OTLP_LOGS_INSECURE:"",OTEL_EXPORTER_OTLP_CERTIFICATE:"",OTEL_EXPORTER_OTLP_TRACES_CERTIFICATE:"",OTEL_EXPORTER_OTLP_METRICS_CERTIFICATE:"",OTEL_EXPORTER_OTLP_LOGS_CERTIFICATE:"",OTEL_EXPORTER_OTLP_COMPRESSION:"",OTEL_EXPORTER_OTLP_TRACES_COMPRESSION:"",OTEL_EXPORTER_OTLP_METRICS_COMPRESSION:"",OTEL_EXPORTER_OTLP_LOGS_COMPRESSION:"",OTEL_EXPORTER_OTLP_CLIENT_KEY:"",OTEL_EXPORTER_OTLP_TRACES_CLIENT_KEY:"",OTEL_EXPORTER_OTLP_METRICS_CLIENT_KEY:"",OTEL_EXPORTER_OTLP_LOGS_CLIENT_KEY:"",OTEL_EXPORTER_OTLP_CLIENT_CERTIFICATE:"",OTEL_EXPORTER_OTLP_TRACES_CLIENT_CERTIFICATE:"",OTEL_EXPORTER_OTLP_METRICS_CLIENT_CERTIFICATE:"",OTEL_EXPORTER_OTLP_LOGS_CLIENT_CERTIFICATE:"",OTEL_EXPORTER_OTLP_PROTOCOL:"http/protobuf",OTEL_EXPORTER_OTLP_TRACES_PROTOCOL:"http/protobuf",OTEL_EXPORTER_OTLP_METRICS_PROTOCOL:"http/protobuf",OTEL_EXPORTER_OTLP_LOGS_PROTOCOL:"http/protobuf",OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE:"cumulative"};function gI(r,e,t){if(!(typeof t[r]>"u")){var n=String(t[r]);e[r]=n.toLowerCase()==="true"}}function hI(r,e,t,n,o){if(n===void 0&&(n=-1/0),o===void 0&&(o=1/0),typeof t[r]<"u"){var i=Number(t[r]);isNaN(i)||(i<n?e[r]=n:i>o?e[r]=o:e[r]=i)}}function fI(r,e,t,n){n===void 0&&(n=iI);var o=t[r];typeof o=="string"&&(e[r]=o.split(n).map(function(i){return i.trim()}))}var SI={ALL:we.ALL,VERBOSE:we.VERBOSE,DEBUG:we.DEBUG,INFO:we.INFO,WARN:we.WARN,ERROR:we.ERROR,NONE:we.NONE};function yI(r,e,t){var n=t[r];if(typeof n=="string"){var o=SI[n.toUpperCase()];o!=null&&(e[r]=o)}}function ey(r){var e={};for(var t in Ku){var n=t;switch(n){case"OTEL_LOG_LEVEL":yI(n,e,r);break;default:if(sI(n))gI(n,e,r);else if(cI(n))hI(n,e,r);else if(dI(n))fI(n,e,r);else{var o=r[n];typeof o<"u"&&o!==null&&(e[n]=String(o))}}}return e}function ot(){var r=ey(process.env);return Object.assign({},Ku,r)}function ty(r){return r>=48&&r<=57?r-48:r>=97&&r<=102?r-87:r-55}function Ds(r){for(var e=new Uint8Array(r.length/2),t=0,n=0;n<r.length;n+=2){var o=ty(r.charCodeAt(n)),i=ty(r.charCodeAt(n+1));e[t++]=o<<4|i}return e}var ry="1.25.1";var EI="deployment.environment";var bI="process.runtime.name";var TI="service.name";var vI="service.instance.id";var AI="telemetry.sdk.name",RI="telemetry.sdk.language",wI="telemetry.sdk.version";var ny=EI;var oy=bI;var ks=TI;var iy=vI;var zi=AI,Gi=RI,Hi=wI;var CI="nodejs";var ay=CI;var Ao,Us=(Ao={},Ao[zi]="opentelemetry",Ao[oy]="node",Ao[Gi]=ay,Ao[Hi]=ry,Ao);var xI=9,_I=6,MI=Math.pow(10,_I),II=Math.pow(10,xI);function sy(r){var e=r/1e3,t=Math.trunc(e),n=Math.round(r%1e3*MI);return[t,n]}function ly(r){return r[0]*II+r[1]}function Vi(r){return r[0]*1e6+r[1]/1e3}var _n;(function(r){r[r.SUCCESS=0]="SUCCESS",r[r.FAILED=1]="FAILED"})(_n||(_n={}));var cy=function(){function r(){var e=this;this._promise=new Promise(function(t,n){e._resolve=t,e._reject=n})}return Object.defineProperty(r.prototype,"promise",{get:function(){return this._promise},enumerable:!1,configurable:!0}),r.prototype.resolve=function(e){this._resolve(e)},r.prototype.reject=function(e){this._reject(e)},r}();var PI=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},OI=function(r,e,t){if(t||arguments.length===2)for(var n=0,o=e.length,i;n<o;n++)(i||!(n in e))&&(i||(i=Array.prototype.slice.call(e,0,n)),i[n]=e[n]);return r.concat(i||Array.prototype.slice.call(e))},uy=function(){function r(e,t){this._callback=e,this._that=t,this._isCalled=!1,this._deferred=new cy}return Object.defineProperty(r.prototype,"isCalled",{get:function(){return this._isCalled},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"promise",{get:function(){return this._deferred.promise},enumerable:!1,configurable:!0}),r.prototype.call=function(){for(var e,t=this,n=[],o=0;o<arguments.length;o++)n[o]=arguments[o];if(!this._isCalled){this._isCalled=!0;try{Promise.resolve((e=this._callback).call.apply(e,OI([this._that],PI(n),!1))).then(function(i){return t._deferred.resolve(i)},function(i){return t._deferred.reject(i)})}catch(i){this._deferred.reject(i)}}return this._deferred.promise},r}();var zt;(function(r){r[r.DELTA=0]="DELTA",r[r.CUMULATIVE=1]="CUMULATIVE"})(zt||(zt={}));var ct;(function(r){r[r.HISTOGRAM=0]="HISTOGRAM",r[r.EXPONENTIAL_HISTOGRAM=1]="EXPONENTIAL_HISTOGRAM",r[r.GAUGE=2]="GAUGE",r[r.SUM=3]="SUM"})(ct||(ct={}));var LI=function(){var r=function(e,t){return r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,o){n.__proto__=o}||function(n,o){for(var i in o)Object.prototype.hasOwnProperty.call(o,i)&&(n[i]=o[i])},r(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");r(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}}();var P7=function(r){LI(e,r);function e(t){var n=r.call(this,t)||this;return Object.setPrototypeOf(n,e.prototype),n}return e}(Error);function dy(r,e){for(var t=0,n=r.length-1;n-t>1;){var o=Math.trunc((n+t)/2);r[o]<=e?t=o:n=o-1}return r[n]<=e?n:r[t]<=e?t:-1}he();var Gt;(function(r){r[r.DROP=0]="DROP",r[r.SUM=1]="SUM",r[r.LAST_VALUE=2]="LAST_VALUE",r[r.HISTOGRAM=3]="HISTOGRAM",r[r.EXPONENTIAL_HISTOGRAM=4]="EXPONENTIAL_HISTOGRAM"})(Gt||(Gt={}));var py=function(){function r(){this.kind=Gt.DROP}return r.prototype.createAccumulation=function(){},r.prototype.merge=function(e,t){},r.prototype.diff=function(e,t){},r.prototype.toMetricData=function(e,t,n,o){},r}();var ee;(function(r){r.COUNTER="COUNTER",r.GAUGE="GAUGE",r.HISTOGRAM="HISTOGRAM",r.UP_DOWN_COUNTER="UP_DOWN_COUNTER",r.OBSERVABLE_COUNTER="OBSERVABLE_COUNTER",r.OBSERVABLE_GAUGE="OBSERVABLE_GAUGE",r.OBSERVABLE_UP_DOWN_COUNTER="OBSERVABLE_UP_DOWN_COUNTER"})(ee||(ee={}));var NI=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i};function DI(r){var e=r.map(function(){return 0});return e.push(0),{buckets:{boundaries:r,counts:e},sum:0,count:0,hasMinMax:!1,min:1/0,max:-1/0}}var Yu=function(){function r(e,t,n,o){n===void 0&&(n=!0),o===void 0&&(o=DI(t)),this.startTime=e,this._boundaries=t,this._recordMinMax=n,this._current=o}return r.prototype.record=function(e){if(!Number.isNaN(e)){this._current.count+=1,this._current.sum+=e,this._recordMinMax&&(this._current.min=Math.min(e,this._current.min),this._current.max=Math.max(e,this._current.max),this._current.hasMinMax=!0);var t=dy(this._boundaries,e);this._current.buckets.counts[t+1]+=1}},r.prototype.setStartTime=function(e){this.startTime=e},r.prototype.toPointValue=function(){return this._current},r}();var Xu=function(){function r(e,t){this._boundaries=e,this._recordMinMax=t,this.kind=Gt.HISTOGRAM}return r.prototype.createAccumulation=function(e){return new Yu(e,this._boundaries,this._recordMinMax)},r.prototype.merge=function(e,t){for(var n=e.toPointValue(),o=t.toPointValue(),i=n.buckets.counts,a=o.buckets.counts,l=new Array(i.length),c=0;c<i.length;c++)l[c]=i[c]+a[c];var s=1/0,u=-1/0;return this._recordMinMax&&(n.hasMinMax&&o.hasMinMax?(s=Math.min(n.min,o.min),u=Math.max(n.max,o.max)):n.hasMinMax?(s=n.min,u=n.max):o.hasMinMax&&(s=o.min,u=o.max)),new Yu(e.startTime,n.buckets.boundaries,this._recordMinMax,{buckets:{boundaries:n.buckets.boundaries,counts:l},count:n.count+o.count,sum:n.sum+o.sum,hasMinMax:this._recordMinMax&&(n.hasMinMax||o.hasMinMax),min:s,max:u})},r.prototype.diff=function(e,t){for(var n=e.toPointValue(),o=t.toPointValue(),i=n.buckets.counts,a=o.buckets.counts,l=new Array(i.length),c=0;c<i.length;c++)l[c]=a[c]-i[c];return new Yu(t.startTime,n.buckets.boundaries,this._recordMinMax,{buckets:{boundaries:n.buckets.boundaries,counts:l},count:o.count-n.count,sum:o.sum-n.sum,hasMinMax:!1,min:1/0,max:-1/0})},r.prototype.toMetricData=function(e,t,n,o){return{descriptor:e,aggregationTemporality:t,dataPointType:ct.HISTOGRAM,dataPoints:n.map(function(i){var a=NI(i,2),l=a[0],c=a[1],s=c.toPointValue(),u=e.type===ee.GAUGE||e.type===ee.UP_DOWN_COUNTER||e.type===ee.OBSERVABLE_GAUGE||e.type===ee.OBSERVABLE_UP_DOWN_COUNTER;return{attributes:l,startTime:c.startTime,endTime:o,value:{min:s.hasMinMax?s.min:void 0,max:s.hasMinMax?s.max:void 0,sum:u?void 0:s.sum,buckets:s.buckets,count:s.count}}})}},r}();he();var Ju=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},Qu=function(r,e,t){if(t||arguments.length===2)for(var n=0,o=e.length,i;n<o;n++)(i||!(n in e))&&(i||(i=Array.prototype.slice.call(e,0,n)),i[n]=e[n]);return r.concat(i||Array.prototype.slice.call(e))},Zu=function(){function r(e,t,n,o){e===void 0&&(e=new kI),t===void 0&&(t=0),n===void 0&&(n=0),o===void 0&&(o=0),this.backing=e,this.indexBase=t,this.indexStart=n,this.indexEnd=o}return Object.defineProperty(r.prototype,"offset",{get:function(){return this.indexStart},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"length",{get:function(){return this.backing.length===0||this.indexEnd===this.indexStart&&this.at(0)===0?0:this.indexEnd-this.indexStart+1},enumerable:!1,configurable:!0}),r.prototype.counts=function(){var e=this;return Array.from({length:this.length},function(t,n){return e.at(n)})},r.prototype.at=function(e){var t=this.indexBase-this.indexStart;return e<t&&(e+=this.backing.length),e-=t,this.backing.countAt(e)},r.prototype.incrementBucket=function(e,t){this.backing.increment(e,t)},r.prototype.decrementBucket=function(e,t){this.backing.decrement(e,t)},r.prototype.trim=function(){for(var e=0;e<this.length;e++)if(this.at(e)!==0){this.indexStart+=e;break}else if(e===this.length-1){this.indexStart=this.indexEnd=this.indexBase=0;return}for(var e=this.length-1;e>=0;e--)if(this.at(e)!==0){this.indexEnd-=this.length-e-1;break}this._rotate()},r.prototype.downscale=function(e){this._rotate();for(var t=1+this.indexEnd-this.indexStart,n=1<<e,o=0,i=0,a=this.indexStart;a<=this.indexEnd;){var l=a%n;l<0&&(l+=n);for(var c=l;c<n&&o<t;c++)this._relocateBucket(i,o),o++,a++;i++}this.indexStart>>=e,this.indexEnd>>=e,this.indexBase=this.indexStart},r.prototype.clone=function(){return new r(this.backing.clone(),this.indexBase,this.indexStart,this.indexEnd)},r.prototype._rotate=function(){var e=this.indexBase-this.indexStart;e!==0&&(e>0?(this.backing.reverse(0,this.backing.length),this.backing.reverse(0,e),this.backing.reverse(e,this.backing.length)):(this.backing.reverse(0,this.backing.length),this.backing.reverse(0,this.backing.length+e)),this.indexBase=this.indexStart)},r.prototype._relocateBucket=function(e,t){e!==t&&this.incrementBucket(e,this.backing.emptyBucket(t))},r}();var kI=function(){function r(e){e===void 0&&(e=[0]),this._counts=e}return Object.defineProperty(r.prototype,"length",{get:function(){return this._counts.length},enumerable:!1,configurable:!0}),r.prototype.countAt=function(e){return this._counts[e]},r.prototype.growTo=function(e,t,n){var o=new Array(e).fill(0);o.splice.apply(o,Qu([n,this._counts.length-t],Ju(this._counts.slice(t)),!1)),o.splice.apply(o,Qu([0,t],Ju(this._counts.slice(0,t)),!1)),this._counts=o},r.prototype.reverse=function(e,t){for(var n=Math.floor((e+t)/2)-e,o=0;o<n;o++){var i=this._counts[e+o];this._counts[e+o]=this._counts[t-o-1],this._counts[t-o-1]=i}},r.prototype.emptyBucket=function(e){var t=this._counts[e];return this._counts[e]=0,t},r.prototype.increment=function(e,t){this._counts[e]+=t},r.prototype.decrement=function(e,t){this._counts[e]>=t?this._counts[e]-=t:this._counts[e]=0},r.prototype.clone=function(){return new r(Qu([],Ju(this._counts),!1))},r}();var my=52,UI=2146435072,FI=1048575,ed=1023,Fs=-ed+1,Bs=ed,ji=Math.pow(2,-1022);function zs(r){var e=new DataView(new ArrayBuffer(8));e.setFloat64(0,r);var t=e.getUint32(0),n=(t&UI)>>20;return n-ed}function Gs(r){var e=new DataView(new ArrayBuffer(8));e.setFloat64(0,r);var t=e.getUint32(0),n=e.getUint32(4),o=(t&FI)*Math.pow(2,32);return o+n}function Wi(r,e){return r===0||r===Number.POSITIVE_INFINITY||r===Number.NEGATIVE_INFINITY||Number.isNaN(r)?r:r*Math.pow(2,e)}function hy(r){return r--,r|=r>>1,r|=r>>2,r|=r>>4,r|=r>>8,r|=r>>16,r++,r}var BI=function(){var r=function(e,t){return r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,o){n.__proto__=o}||function(n,o){for(var i in o)Object.prototype.hasOwnProperty.call(o,i)&&(n[i]=o[i])},r(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");r(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}}(),Kr=function(r){BI(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(Error);var Sy=function(){function r(e){this._shift=-e}return r.prototype.mapToIndex=function(e){if(e<ji)return this._minNormalLowerBoundaryIndex();var t=zs(e),n=this._rightShift(Gs(e)-1,my);return t+n>>this._shift},r.prototype.lowerBoundary=function(e){var t=this._minNormalLowerBoundaryIndex();if(e<t)throw new Kr("underflow: "+e+" is < minimum lower boundary: "+t);var n=this._maxNormalLowerBoundaryIndex();if(e>n)throw new Kr("overflow: "+e+" is > maximum lower boundary: "+n);return Wi(1,e<<this._shift)},Object.defineProperty(r.prototype,"scale",{get:function(){return this._shift===0?0:-this._shift},enumerable:!1,configurable:!0}),r.prototype._minNormalLowerBoundaryIndex=function(){var e=Fs>>this._shift;return this._shift<2&&e--,e},r.prototype._maxNormalLowerBoundaryIndex=function(){return Bs>>this._shift},r.prototype._rightShift=function(e,t){return Math.floor(e*Math.pow(2,-t))},r}();var yy=function(){function r(e){this._scale=e,this._scaleFactor=Wi(Math.LOG2E,e),this._inverseFactor=Wi(Math.LN2,-e)}return r.prototype.mapToIndex=function(e){if(e<=ji)return this._minNormalLowerBoundaryIndex()-1;if(Gs(e)===0){var t=zs(e);return(t<<this._scale)-1}var n=Math.floor(Math.log(e)*this._scaleFactor),o=this._maxNormalLowerBoundaryIndex();return n>=o?o:n},r.prototype.lowerBoundary=function(e){var t=this._maxNormalLowerBoundaryIndex();if(e>=t){if(e===t)return 2*Math.exp((e-(1<<this._scale))/this._scaleFactor);throw new Kr("overflow: "+e+" is > maximum lower boundary: "+t)}var n=this._minNormalLowerBoundaryIndex();if(e<=n){if(e===n)return ji;if(e===n-1)return Math.exp((e+(1<<this._scale))/this._scaleFactor)/2;throw new Kr("overflow: "+e+" is < minimum lower boundary: "+n)}return Math.exp(e*this._inverseFactor)},Object.defineProperty(r.prototype,"scale",{get:function(){return this._scale},enumerable:!1,configurable:!0}),r.prototype._minNormalLowerBoundaryIndex=function(){return Fs<<this._scale},r.prototype._maxNormalLowerBoundaryIndex=function(){return(Bs+1<<this._scale)-1},r}();var Ey=-10,by=20,zI=Array.from({length:31},function(r,e){return e>10?new yy(e-10):new Sy(e-10)});function td(r){if(r>by||r<Ey)throw new Kr("expected scale >= "+Ey+" && <= "+by+", got: "+r);return zI[r+10]}var GI=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},Hs=function(){function r(e,t){this.low=e,this.high=t}return r.combine=function(e,t){return new r(Math.min(e.low,t.low),Math.max(e.high,t.high))},r}(),HI=20,VI=160,rd=2,jI=function(){function r(e,t,n,o,i,a,l,c,s,u,d){e===void 0&&(e=e),t===void 0&&(t=VI),n===void 0&&(n=!0),o===void 0&&(o=0),i===void 0&&(i=0),a===void 0&&(a=0),l===void 0&&(l=Number.POSITIVE_INFINITY),c===void 0&&(c=Number.NEGATIVE_INFINITY),s===void 0&&(s=new Zu),u===void 0&&(u=new Zu),d===void 0&&(d=td(HI)),this.startTime=e,this._maxSize=t,this._recordMinMax=n,this._sum=o,this._count=i,this._zeroCount=a,this._min=l,this._max=c,this._positive=s,this._negative=u,this._mapping=d,this._maxSize<rd&&(F.warn("Exponential Histogram Max Size set to "+this._maxSize+", changing to the minimum size of: "+rd),this._maxSize=rd)}return r.prototype.record=function(e){this.updateByIncrement(e,1)},r.prototype.setStartTime=function(e){this.startTime=e},r.prototype.toPointValue=function(){return{hasMinMax:this._recordMinMax,min:this.min,max:this.max,sum:this.sum,positive:{offset:this.positive.offset,bucketCounts:this.positive.counts()},negative:{offset:this.negative.offset,bucketCounts:this.negative.counts()},count:this.count,scale:this.scale,zeroCount:this.zeroCount}},Object.defineProperty(r.prototype,"sum",{get:function(){return this._sum},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"min",{get:function(){return this._min},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"max",{get:function(){return this._max},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"count",{get:function(){return this._count},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"zeroCount",{get:function(){return this._zeroCount},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"scale",{get:function(){return this._count===this._zeroCount?0:this._mapping.scale},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"positive",{get:function(){return this._positive},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"negative",{get:function(){return this._negative},enumerable:!1,configurable:!0}),r.prototype.updateByIncrement=function(e,t){if(!Number.isNaN(e)){if(e>this._max&&(this._max=e),e<this._min&&(this._min=e),this._count+=t,e===0){this._zeroCount+=t;return}this._sum+=e*t,e>0?this._updateBuckets(this._positive,e,t):this._updateBuckets(this._negative,-e,t)}},r.prototype.merge=function(e){this._count===0?(this._min=e.min,this._max=e.max):e.count!==0&&(e.min<this.min&&(this._min=e.min),e.max>this.max&&(this._max=e.max)),this.startTime=e.startTime,this._sum+=e.sum,this._count+=e.count,this._zeroCount+=e.zeroCount;var t=this._minScale(e);this._downscale(this.scale-t),this._mergeBuckets(this.positive,e,e.positive,t),this._mergeBuckets(this.negative,e,e.negative,t)},r.prototype.diff=function(e){this._min=1/0,this._max=-1/0,this._sum-=e.sum,this._count-=e.count,this._zeroCount-=e.zeroCount;var t=this._minScale(e);this._downscale(this.scale-t),this._diffBuckets(this.positive,e,e.positive,t),this._diffBuckets(this.negative,e,e.negative,t)},r.prototype.clone=function(){return new r(this.startTime,this._maxSize,this._recordMinMax,this._sum,this._count,this._zeroCount,this._min,this._max,this.positive.clone(),this.negative.clone(),this._mapping)},r.prototype._updateBuckets=function(e,t,n){var o=this._mapping.mapToIndex(t),i=!1,a=0,l=0;if(e.length===0?(e.indexStart=o,e.indexEnd=e.indexStart,e.indexBase=e.indexStart):o<e.indexStart&&e.indexEnd-o>=this._maxSize?(i=!0,l=o,a=e.indexEnd):o>e.indexEnd&&o-e.indexStart>=this._maxSize&&(i=!0,l=e.indexStart,a=o),i){var c=this._changeScale(a,l);this._downscale(c),o=this._mapping.mapToIndex(t)}this._incrementIndexBy(e,o,n)},r.prototype._incrementIndexBy=function(e,t,n){if(n!==0){if(e.length===0&&(e.indexStart=e.indexEnd=e.indexBase=t),t<e.indexStart){var o=e.indexEnd-t;o>=e.backing.length&&this._grow(e,o+1),e.indexStart=t}else if(t>e.indexEnd){var o=t-e.indexStart;o>=e.backing.length&&this._grow(e,o+1),e.indexEnd=t}var i=t-e.indexBase;i<0&&(i+=e.backing.length),e.incrementBucket(i,n)}},r.prototype._grow=function(e,t){var n=e.backing.length,o=e.indexBase-e.indexStart,i=n-o,a=hy(t);a>this._maxSize&&(a=this._maxSize);var l=a-o;e.backing.growTo(a,i,l)},r.prototype._changeScale=function(e,t){for(var n=0;e-t>=this._maxSize;)e>>=1,t>>=1,n++;return n},r.prototype._downscale=function(e){if(e!==0){if(e<0)throw new Error("impossible change of scale: "+this.scale);var t=this._mapping.scale-e;this._positive.downscale(e),this._negative.downscale(e),this._mapping=td(t)}},r.prototype._minScale=function(e){var t=Math.min(this.scale,e.scale),n=Hs.combine(this._highLowAtScale(this.positive,this.scale,t),this._highLowAtScale(e.positive,e.scale,t)),o=Hs.combine(this._highLowAtScale(this.negative,this.scale,t),this._highLowAtScale(e.negative,e.scale,t));return Math.min(t-this._changeScale(n.high,n.low),t-this._changeScale(o.high,o.low))},r.prototype._highLowAtScale=function(e,t,n){if(e.length===0)return new Hs(0,-1);var o=t-n;return new Hs(e.indexStart>>o,e.indexEnd>>o)},r.prototype._mergeBuckets=function(e,t,n,o){for(var i=n.offset,a=t.scale-o,l=0;l<n.length;l++)this._incrementIndexBy(e,i+l>>a,n.at(l))},r.prototype._diffBuckets=function(e,t,n,o){for(var i=n.offset,a=t.scale-o,l=0;l<n.length;l++){var c=i+l>>a,s=c-e.indexBase;s<0&&(s+=e.backing.length),e.decrementBucket(s,n.at(l))}e.trim()},r}();var Ty=function(){function r(e,t){this._maxSize=e,this._recordMinMax=t,this.kind=Gt.EXPONENTIAL_HISTOGRAM}return r.prototype.createAccumulation=function(e){return new jI(e,this._maxSize,this._recordMinMax)},r.prototype.merge=function(e,t){var n=t.clone();return n.merge(e),n},r.prototype.diff=function(e,t){var n=t.clone();return n.diff(e),n},r.prototype.toMetricData=function(e,t,n,o){return{descriptor:e,aggregationTemporality:t,dataPointType:ct.EXPONENTIAL_HISTOGRAM,dataPoints:n.map(function(i){var a=GI(i,2),l=a[0],c=a[1],s=c.toPointValue(),u=e.type===ee.GAUGE||e.type===ee.UP_DOWN_COUNTER||e.type===ee.OBSERVABLE_GAUGE||e.type===ee.OBSERVABLE_UP_DOWN_COUNTER;return{attributes:l,startTime:c.startTime,endTime:o,value:{min:s.hasMinMax?s.min:void 0,max:s.hasMinMax?s.max:void 0,sum:u?void 0:s.sum,positive:{offset:s.positive.offset,bucketCounts:s.positive.bucketCounts},negative:{offset:s.negative.offset,bucketCounts:s.negative.bucketCounts},count:s.count,scale:s.scale,zeroCount:s.zeroCount}}})}},r}();var WI=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},nd=function(){function r(e,t,n){t===void 0&&(t=0),n===void 0&&(n=[0,0]),this.startTime=e,this._current=t,this.sampleTime=n}return r.prototype.record=function(e){this._current=e,this.sampleTime=sy(Date.now())},r.prototype.setStartTime=function(e){this.startTime=e},r.prototype.toPointValue=function(){return this._current},r}();var vy=function(){function r(){this.kind=Gt.LAST_VALUE}return r.prototype.createAccumulation=function(e){return new nd(e)},r.prototype.merge=function(e,t){var n=Vi(t.sampleTime)>=Vi(e.sampleTime)?t:e;return new nd(e.startTime,n.toPointValue(),n.sampleTime)},r.prototype.diff=function(e,t){var n=Vi(t.sampleTime)>=Vi(e.sampleTime)?t:e;return new nd(t.startTime,n.toPointValue(),n.sampleTime)},r.prototype.toMetricData=function(e,t,n,o){return{descriptor:e,aggregationTemporality:t,dataPointType:ct.GAUGE,dataPoints:n.map(function(i){var a=WI(i,2),l=a[0],c=a[1];return{attributes:l,startTime:c.startTime,endTime:o,value:c.toPointValue()}})}},r}();var $I=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},$i=function(){function r(e,t,n,o){n===void 0&&(n=0),o===void 0&&(o=!1),this.startTime=e,this.monotonic=t,this._current=n,this.reset=o}return r.prototype.record=function(e){this.monotonic&&e<0||(this._current+=e)},r.prototype.setStartTime=function(e){this.startTime=e},r.prototype.toPointValue=function(){return this._current},r}();var od=function(){function r(e){this.monotonic=e,this.kind=Gt.SUM}return r.prototype.createAccumulation=function(e){return new $i(e,this.monotonic)},r.prototype.merge=function(e,t){var n=e.toPointValue(),o=t.toPointValue();return t.reset?new $i(t.startTime,this.monotonic,o,t.reset):new $i(e.startTime,this.monotonic,n+o)},r.prototype.diff=function(e,t){var n=e.toPointValue(),o=t.toPointValue();return this.monotonic&&n>o?new $i(t.startTime,this.monotonic,o,!0):new $i(t.startTime,this.monotonic,o-n)},r.prototype.toMetricData=function(e,t,n,o){return{descriptor:e,aggregationTemporality:t,dataPointType:ct.SUM,dataPoints:n.map(function(i){var a=$I(i,2),l=a[0],c=a[1];return{attributes:l,startTime:c.startTime,endTime:o,value:c.toPointValue()}}),isMonotonic:this.monotonic}},r}();var Mn=function(){var r=function(e,t){return r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,o){n.__proto__=o}||function(n,o){for(var i in o)Object.prototype.hasOwnProperty.call(o,i)&&(n[i]=o[i])},r(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");r(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}}(),pr=function(){function r(){}return r.Drop=function(){return Iy},r.Sum=function(){return Py},r.LastValue=function(){return Oy},r.Histogram=function(){return Ly},r.ExponentialHistogram=function(){return qI},r.Default=function(){return KI},r}();var Ay=function(r){Mn(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.createAggregator=function(t){return e.DEFAULT_INSTANCE},e.DEFAULT_INSTANCE=new py,e}(pr);var Ry=function(r){Mn(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.createAggregator=function(t){switch(t.type){case ee.COUNTER:case ee.OBSERVABLE_COUNTER:case ee.HISTOGRAM:return e.MONOTONIC_INSTANCE;default:return e.NON_MONOTONIC_INSTANCE}},e.MONOTONIC_INSTANCE=new od(!0),e.NON_MONOTONIC_INSTANCE=new od(!1),e}(pr);var wy=function(r){Mn(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.createAggregator=function(t){return e.DEFAULT_INSTANCE},e.DEFAULT_INSTANCE=new vy,e}(pr);var Cy=function(r){Mn(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.createAggregator=function(t){return e.DEFAULT_INSTANCE},e.DEFAULT_INSTANCE=new Xu([0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4],!0),e}(pr);var xy=function(r){Mn(e,r);function e(t,n){n===void 0&&(n=!0);var o=r.call(this)||this;if(o._recordMinMax=n,t==null)throw new Error("ExplicitBucketHistogramAggregation should be created with explicit boundaries, if a single bucket histogram is required, please pass an empty array");t=t.concat(),t=t.sort(function(l,c){return l-c});var i=t.lastIndexOf(-1/0),a=t.indexOf(1/0);return a===-1&&(a=void 0),o._boundaries=t.slice(i+1,a),o}return e.prototype.createAggregator=function(t){return new Xu(this._boundaries,this._recordMinMax)},e}(pr);var _y=function(r){Mn(e,r);function e(t,n){t===void 0&&(t=160),n===void 0&&(n=!0);var o=r.call(this)||this;return o._maxSize=t,o._recordMinMax=n,o}return e.prototype.createAggregator=function(t){return new Ty(this._maxSize,this._recordMinMax)},e}(pr);var My=function(r){Mn(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype._resolve=function(t){switch(t.type){case ee.COUNTER:case ee.UP_DOWN_COUNTER:case ee.OBSERVABLE_COUNTER:case ee.OBSERVABLE_UP_DOWN_COUNTER:return Py;case ee.GAUGE:case ee.OBSERVABLE_GAUGE:return Oy;case ee.HISTOGRAM:return t.advice.explicitBucketBoundaries?new xy(t.advice.explicitBucketBoundaries):Ly}return F.warn("Unable to recognize instrument type: "+t.type),Iy},e.prototype.createAggregator=function(t){return this._resolve(t).createAggregator(t)},e}(pr);var Iy=new Ay,Py=new Ry,Oy=new wy,Ly=new Cy,qI=new _y,KI=new My;he();function Vs(){return"unknown_service:"+process.argv0}var Yr=function(){return Yr=Object.assign||function(r){for(var e,t=1,n=arguments.length;t<n;t++){e=arguments[t];for(var o in e)Object.prototype.hasOwnProperty.call(e,o)&&(r[o]=e[o])}return r},Yr.apply(this,arguments)},YI=function(r,e,t,n){function o(i){return i instanceof t?i:new t(function(a){a(i)})}return new(t||(t=Promise))(function(i,a){function l(u){try{s(n.next(u))}catch(d){a(d)}}function c(u){try{s(n.throw(u))}catch(d){a(d)}}function s(u){u.done?i(u.value):o(u.value).then(l,c)}s((n=n.apply(r,e||[])).next())})},XI=function(r,e){var t={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},n,o,i,a;return a={next:l(0),throw:l(1),return:l(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function l(s){return function(u){return c([s,u])}}function c(s){if(n)throw new TypeError("Generator is already executing.");for(;t;)try{if(n=1,o&&(i=s[0]&2?o.return:s[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,s[1])).done)return i;switch(o=0,i&&(s=[s[0]&2,i.value]),s[0]){case 0:case 1:i=s;break;case 4:return t.label++,{value:s[1],done:!1};case 5:t.label++,o=s[1],s=[0];continue;case 7:s=t.ops.pop(),t.trys.pop();continue;default:if(i=t.trys,!(i=i.length>0&&i[i.length-1])&&(s[0]===6||s[0]===2)){t=0;continue}if(s[0]===3&&(!i||s[1]>i[0]&&s[1]<i[3])){t.label=s[1];break}if(s[0]===6&&t.label<i[1]){t.label=i[1],i=s;break}if(i&&t.label<i[2]){t.label=i[2],t.ops.push(s);break}i[2]&&t.ops.pop(),t.trys.pop();continue}s=e.call(r,t)}catch(u){s=[6,u],o=0}finally{n=i=0}if(s[0]&5)throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}},JI=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},id=function(){function r(e,t){var n=this,o;this._attributes=e,this.asyncAttributesPending=t!=null,this._syncAttributes=(o=this._attributes)!==null&&o!==void 0?o:{},this._asyncAttributesPromise=t?.then(function(i){return n._attributes=Object.assign({},n._attributes,i),n.asyncAttributesPending=!1,i},function(i){return F.debug("a resource's async attributes promise rejected: %s",i),n.asyncAttributesPending=!1,{}})}return r.empty=function(){return r.EMPTY},r.default=function(){var e;return new r((e={},e[ks]=Vs(),e[Gi]=Us[Gi],e[zi]=Us[zi],e[Hi]=Us[Hi],e))},Object.defineProperty(r.prototype,"attributes",{get:function(){var e;return this.asyncAttributesPending&&F.error("Accessing resource attributes before async attributes settled"),(e=this._attributes)!==null&&e!==void 0?e:{}},enumerable:!1,configurable:!0}),r.prototype.waitForAsyncAttributes=function(){return YI(this,void 0,void 0,function(){return XI(this,function(e){switch(e.label){case 0:return this.asyncAttributesPending?[4,this._asyncAttributesPromise]:[3,2];case 1:e.sent(),e.label=2;case 2:return[2]}})})},r.prototype.merge=function(e){var t=this,n;if(!e)return this;var o=Yr(Yr({},this._syncAttributes),(n=e._syncAttributes)!==null&&n!==void 0?n:e.attributes);if(!this._asyncAttributesPromise&&!e._asyncAttributesPromise)return new r(o);var i=Promise.all([this._asyncAttributesPromise,e._asyncAttributesPromise]).then(function(a){var l,c=JI(a,2),s=c[0],u=c[1];return Yr(Yr(Yr(Yr({},t._syncAttributes),s),(l=e._syncAttributes)!==null&&l!==void 0?l:e.attributes),u)});return new r(o,i)},r.EMPTY=new r({}),r}();var In;(function(r){r[r.DELTA=0]="DELTA",r[r.CUMULATIVE=1]="CUMULATIVE",r[r.LOWMEMORY=2]="LOWMEMORY"})(In||(In={}));he();var QI=function(r,e,t,n){function o(i){return i instanceof t?i:new t(function(a){a(i)})}return new(t||(t=Promise))(function(i,a){function l(u){try{s(n.next(u))}catch(d){a(d)}}function c(u){try{s(n.throw(u))}catch(d){a(d)}}function s(u){u.done?i(u.value):o(u.value).then(l,c)}s((n=n.apply(r,e||[])).next())})},ZI=function(r,e){var t={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},n,o,i,a;return a={next:l(0),throw:l(1),return:l(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function l(s){return function(u){return c([s,u])}}function c(s){if(n)throw new TypeError("Generator is already executing.");for(;t;)try{if(n=1,o&&(i=s[0]&2?o.return:s[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,s[1])).done)return i;switch(o=0,i&&(s=[s[0]&2,i.value]),s[0]){case 0:case 1:i=s;break;case 4:return t.label++,{value:s[1],done:!1};case 5:t.label++,o=s[1],s=[0];continue;case 7:s=t.ops.pop(),t.trys.pop();continue;default:if(i=t.trys,!(i=i.length>0&&i[i.length-1])&&(s[0]===6||s[0]===2)){t=0;continue}if(s[0]===3&&(!i||s[1]>i[0]&&s[1]<i[3])){t.label=s[1];break}if(s[0]===6&&t.label<i[1]){t.label=i[1],i=s;break}if(i&&t.label<i[2]){t.label=i[2],t.ops.push(s);break}i[2]&&t.ops.pop(),t.trys.pop();continue}s=e.call(r,t)}catch(u){s=[6,u],o=0}finally{n=i=0}if(s[0]&5)throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}},ad=function(){return zt.CUMULATIVE},Ny=function(r){switch(r){case ee.COUNTER:case ee.OBSERVABLE_COUNTER:case ee.GAUGE:case ee.HISTOGRAM:case ee.OBSERVABLE_GAUGE:return zt.DELTA;case ee.UP_DOWN_COUNTER:case ee.OBSERVABLE_UP_DOWN_COUNTER:return zt.CUMULATIVE}},Dy=function(r){switch(r){case ee.COUNTER:case ee.HISTOGRAM:return zt.DELTA;case ee.GAUGE:case ee.UP_DOWN_COUNTER:case ee.OBSERVABLE_UP_DOWN_COUNTER:case ee.OBSERVABLE_COUNTER:case ee.OBSERVABLE_GAUGE:return zt.CUMULATIVE}};function eP(){var r=ot(),e=r.OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE.trim().toLowerCase();return e==="cumulative"?ad:e==="delta"?Ny:e==="lowmemory"?Dy:(F.warn("OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE is set to '"+r.OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE+"', but only 'cumulative' and 'delta' are allowed. Using default ('cumulative') instead."),ad)}function tP(r){return r!=null?r===In.DELTA?Ny:r===In.LOWMEMORY?Dy:ad:eP()}function rP(r){return r?.aggregationPreference?r.aggregationPreference:function(e){return pr.Default()}}var ky=function(){function r(e,t){this._otlpExporter=e,this._aggregationSelector=rP(t),this._aggregationTemporalitySelector=tP(t?.temporalityPreference)}return r.prototype.export=function(e,t){this._otlpExporter.export([e],t)},r.prototype.shutdown=function(){return QI(this,void 0,void 0,function(){return ZI(this,function(e){switch(e.label){case 0:return[4,this._otlpExporter.shutdown()];case 1:return e.sent(),[2]}})})},r.prototype.forceFlush=function(){return Promise.resolve()},r.prototype.selectAggregation=function(e){return this._aggregationSelector(e)},r.prototype.selectAggregationTemporality=function(e){return this._aggregationTemporalitySelector(e)},r}();he();he();var nP=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},Uy=1e4,Fy=5,By=1e3,zy=5e3,Gy=1.5;function qi(r){r===void 0&&(r={});var e={};return Object.entries(r).forEach(function(t){var n=nP(t,2),o=n[0],i=n[1];typeof i<"u"?e[o]=String(i):F.warn('Header "'+o+'" has invalid value ('+i+") and will be ignored")}),e}function sd(r,e){return r.endsWith("/")||(r=r+"/"),r+e}function ld(r){try{var e=new URL(r);return e.pathname===""&&(e.pathname=e.pathname+"/"),e.toString()}catch{return F.warn("Could not parse export URL: '"+r+"'"),r}}function cd(r){return typeof r=="number"?r<=0?ud(r,Uy):r:oP()}function oP(){var r,e=Number((r=ot().OTEL_EXPORTER_OTLP_TRACES_TIMEOUT)!==null&&r!==void 0?r:ot().OTEL_EXPORTER_OTLP_TIMEOUT);return e<=0?ud(e,Uy):e}function ud(r,e){return F.warn("Timeout must be greater than 0",r),e}function Hy(r){var e=[429,502,503,504];return e.includes(r)}function Vy(r){if(r==null)return-1;var e=Number.parseInt(r,10);if(Number.isInteger(e))return e>0?e*1e3:-1;var t=new Date(r).getTime()-Date.now();return t>=0?t:0}var jy=function(){function r(e){e===void 0&&(e={}),this._sendingPromises=[],this.url=this.getDefaultUrl(e),typeof e.hostname=="string"&&(this.hostname=e.hostname),this.shutdown=this.shutdown.bind(this),this._shutdownOnce=new uy(this._shutdown,this),this._concurrencyLimit=typeof e.concurrencyLimit=="number"?e.concurrencyLimit:30,this.timeoutMillis=cd(e.timeoutMillis),this.onInit(e)}return r.prototype.export=function(e,t){if(this._shutdownOnce.isCalled){t({code:_n.FAILED,error:new Error("Exporter has been shutdown")});return}if(this._sendingPromises.length>=this._concurrencyLimit){t({code:_n.FAILED,error:new Error("Concurrent export limit reached")});return}this._export(e).then(function(){t({code:_n.SUCCESS})}).catch(function(n){t({code:_n.FAILED,error:n})})},r.prototype._export=function(e){var t=this;return new Promise(function(n,o){try{F.debug("items to be sent",e),t.send(e,n,o)}catch(i){o(i)}})},r.prototype.shutdown=function(){return this._shutdownOnce.call()},r.prototype.forceFlush=function(){return Promise.all(this._sendingPromises).then(function(){})},r.prototype._shutdown=function(){return F.debug("shutdown started"),this.onShutdown(),this.forceFlush()},r}();he();import*as dd from"url";import*as Ws from"http";import*as $s from"https";import*as Wy from"zlib";import{Readable as aP}from"stream";var Xr;(function(r){r.NONE="none",r.GZIP="gzip"})(Xr||(Xr={}));var iP=function(){var r=function(e,t){return r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,o){n.__proto__=o}||function(n,o){for(var i in o)Object.prototype.hasOwnProperty.call(o,i)&&(n[i]=o[i])},r(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");r(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}}(),Ro=function(r){iP(e,r);function e(t,n,o){var i=r.call(this,t)||this;return i.name="OTLPExporterError",i.data=o,i.code=n,i}return e}(Error);var js=function(){return js=Object.assign||function(r){for(var e,t=1,n=arguments.length;t<n;t++){e=arguments[t];for(var o in e)Object.prototype.hasOwnProperty.call(e,o)&&(r[o]=e[o])}return r},js.apply(this,arguments)};function pd(r,e,t,n,o){var i=r.timeoutMillis,a=new dd.URL(r.url),l=Number(process.versions.node.split(".")[0]),c,s,u=!1,d=setTimeout(function(){if(clearTimeout(c),u=!0,s.destroyed){var h=new Ro("Request Timeout");o(h)}else l>=14?s.destroy():s.abort()},i),p={hostname:a.hostname,port:a.port,path:a.pathname,method:"POST",headers:js({"Content-Type":t},r.headers),agent:r.agent},m=a.protocol==="http:"?Ws.request:$s.request,g=function(h,f){switch(h===void 0&&(h=Fy),f===void 0&&(f=By),s=m(p,function(b){var v="";b.on("data",function(A){return v+=A}),b.on("aborted",function(){if(u){var A=new Ro("Request Timeout");o(A)}}),b.on("end",function(){if(u===!1)if(b.statusCode&&b.statusCode<299)F.debug("statusCode: "+b.statusCode,v),n(),clearTimeout(d),clearTimeout(c);else if(b.statusCode&&Hy(b.statusCode)&&h>0){var A=void 0;f=Gy*f,b.headers["retry-after"]?A=Vy(b.headers["retry-after"]):A=Math.round(Math.random()*(zy-f)+f),c=setTimeout(function(){g(h-1,f)},A)}else{var T=new Ro(b.statusMessage,b.statusCode,v);o(T),clearTimeout(d),clearTimeout(c)}})}),s.on("error",function(b){if(u){var v=new Ro("Request Timeout",b.code);o(v)}else o(b);clearTimeout(d),clearTimeout(c)}),s.on("abort",function(){if(u){var b=new Ro("Request Timeout");o(b)}clearTimeout(d),clearTimeout(c)}),r.compression){case Xr.GZIP:{s.setHeader("Content-Encoding","gzip");var E=sP(e);E.on("error",o).pipe(Wy.createGzip()).on("error",o).pipe(s);break}default:s.end(Buffer.from(e));break}};g()}function sP(r){var e=new aP;return e.push(r),e.push(null),e}function md(r){if(r.httpAgentOptions&&r.keepAlive===!1){F.warn("httpAgentOptions is used only when keepAlive is true");return}if(!(r.keepAlive===!1||!r.url))try{var e=new dd.URL(r.url),t=e.protocol==="http:"?Ws.Agent:$s.Agent;return new t(js({keepAlive:!0},r.httpAgentOptions))}catch(n){F.error("collector exporter failed to create http agent. err: "+n.message);return}}function gd(r){if(r)return r;var e=ot().OTEL_EXPORTER_OTLP_TRACES_COMPRESSION||ot().OTEL_EXPORTER_OTLP_COMPRESSION;return e===Xr.GZIP?Xr.GZIP:Xr.NONE}he();var lP=function(){var r=function(e,t){return r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,o){n.__proto__=o}||function(n,o){for(var i in o)Object.prototype.hasOwnProperty.call(o,i)&&(n[i]=o[i])},r(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");r(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}}(),qs=function(r){lP(e,r);function e(t,n,o){t===void 0&&(t={});var i=r.call(this,t)||this;return i.DEFAULT_HEADERS={},i._contentType=o,t.metadata&&F.warn("Metadata cannot be set when using http"),i.headers=Object.assign(i.DEFAULT_HEADERS,qi(t.headers),vo.parseKeyPairsIntoRecord(ot().OTEL_EXPORTER_OTLP_HEADERS)),i.agent=md(t),i.compression=gd(t.compression),i._serializer=n,i}return e.prototype.onInit=function(t){},e.prototype.send=function(t,n,o){var i=this;if(this._shutdownOnce.isCalled){F.debug("Shutdown already started. Cannot send objects");return}var a=new Promise(function(c,s){var u;pd(i,(u=i._serializer.serializeRequest(t))!==null&&u!==void 0?u:new Uint8Array,i._contentType,c,s)}).then(n,o);this._sendingPromises.push(a);var l=function(){var c=i._sendingPromises.indexOf(a);i._sendingPromises.splice(c,1)};a.then(l,l)},e.prototype.onShutdown=function(){},e}(jy);function qy(r){var e=BigInt(1e9);return BigInt(r[0])*e+BigInt(r[1])}function cP(r){var e=Number(BigInt.asUintN(32,r)),t=Number(BigInt.asUintN(32,r>>BigInt(32)));return{low:e,high:t}}function Ky(r){var e=qy(r);return cP(e)}function uP(r){var e=qy(r);return e.toString()}var dP=typeof BigInt<"u"?uP:ly;function $y(r){return r}function Yy(r){if(r!==void 0)return Ds(r)}var pP={encodeHrTime:Ky,encodeSpanContext:Ds,encodeOptionalSpanContext:Yy};function Xy(r){var e,t;if(r===void 0)return pP;var n=(e=r.useLongBits)!==null&&e!==void 0?e:!0,o=(t=r.useHex)!==null&&t!==void 0?t:!1;return{encodeHrTime:n?Ky:dP,encodeSpanContext:o?$y:Ds,encodeOptionalSpanContext:o?$y:Yy}}var mP=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i};function Jy(r){return{name:r.name,version:r.version}}function wo(r){return Object.keys(r).map(function(e){return Qy(e,r[e])})}function Qy(r,e){return{key:r,value:Zy(e)}}function Zy(r){var e=typeof r;return e==="string"?{stringValue:r}:e==="number"?Number.isInteger(r)?{intValue:r}:{doubleValue:r}:e==="boolean"?{boolValue:r}:r instanceof Uint8Array?{bytesValue:r}:Array.isArray(r)?{arrayValue:{values:r.map(Zy)}}:e==="object"&&r!=null?{kvlistValue:{values:Object.entries(r).map(function(t){var n=mP(t,2),o=n[0],i=n[1];return Qy(o,i)})}}:{}}function eE(r){return{attributes:wo(r.attributes),droppedAttributesCount:0}}he();function rE(r,e){var t=Xy(e);return{resource:eE(r.resource),schemaUrl:void 0,scopeMetrics:gP(r.scopeMetrics,t)}}function gP(r,e){return Array.from(r.map(function(t){return{scope:Jy(t.scope),metrics:t.metrics.map(function(n){return hP(n,e)}),schemaUrl:t.scope.schemaUrl}}))}function hP(r,e){var t={name:r.descriptor.name,description:r.descriptor.description,unit:r.descriptor.unit},n=EP(r.aggregationTemporality);switch(r.dataPointType){case ct.SUM:t.sum={aggregationTemporality:n,isMonotonic:r.isMonotonic,dataPoints:tE(r,e)};break;case ct.GAUGE:t.gauge={dataPoints:tE(r,e)};break;case ct.HISTOGRAM:t.histogram={aggregationTemporality:n,dataPoints:SP(r,e)};break;case ct.EXPONENTIAL_HISTOGRAM:t.exponentialHistogram={aggregationTemporality:n,dataPoints:yP(r,e)};break}return t}function fP(r,e,t){var n={attributes:wo(r.attributes),startTimeUnixNano:t.encodeHrTime(r.startTime),timeUnixNano:t.encodeHrTime(r.endTime)};switch(e){case _t.INT:n.asInt=r.value;break;case _t.DOUBLE:n.asDouble=r.value;break}return n}function tE(r,e){return r.dataPoints.map(function(t){return fP(t,r.descriptor.valueType,e)})}function SP(r,e){return r.dataPoints.map(function(t){var n=t.value;return{attributes:wo(t.attributes),bucketCounts:n.buckets.counts,explicitBounds:n.buckets.boundaries,count:n.count,sum:n.sum,min:n.min,max:n.max,startTimeUnixNano:e.encodeHrTime(t.startTime),timeUnixNano:e.encodeHrTime(t.endTime)}})}function yP(r,e){return r.dataPoints.map(function(t){var n=t.value;return{attributes:wo(t.attributes),count:n.count,min:n.min,max:n.max,sum:n.sum,positive:{offset:n.positive.offset,bucketCounts:n.positive.bucketCounts},negative:{offset:n.negative.offset,bucketCounts:n.negative.bucketCounts},scale:n.scale,zeroCount:n.zeroCount,startTimeUnixNano:e.encodeHrTime(t.startTime),timeUnixNano:e.encodeHrTime(t.endTime)}})}function EP(r){switch(r){case zt.DELTA:return 1;case zt.CUMULATIVE:return 2}}function nE(r,e){return{resourceMetrics:r.map(function(t){return rE(t,e)})}}var hd={serializeRequest:function(r){var e=nE(r,{useLongBits:!1}),t=new TextEncoder;return t.encode(JSON.stringify(e))},deserializeResponse:function(r){var e=new TextDecoder;return JSON.parse(e.decode(r))}};var oE="0.52.1";var iE=function(){var r=function(e,t){return r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,o){n.__proto__=o}||function(n,o){for(var i in o)Object.prototype.hasOwnProperty.call(o,i)&&(n[i]=o[i])},r(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");r(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}}(),Co=function(){return Co=Object.assign||function(r){for(var e,t=1,n=arguments.length;t<n;t++){e=arguments[t];for(var o in e)Object.prototype.hasOwnProperty.call(e,o)&&(r[o]=e[o])}return r},Co.apply(this,arguments)},aE="v1/metrics",bP="http://localhost:4318/"+aE,TP={"User-Agent":"OTel-OTLP-Exporter-JavaScript/"+oE},vP=function(r){iE(e,r);function e(t){var n=r.call(this,t,hd,"application/json")||this;return n.headers=Co(Co(Co(Co({},n.headers),TP),vo.parseKeyPairsIntoRecord(ot().OTEL_EXPORTER_OTLP_METRICS_HEADERS)),qi(t?.headers)),n}return e.prototype.getDefaultUrl=function(t){return typeof t.url=="string"?t.url:ot().OTEL_EXPORTER_OTLP_METRICS_ENDPOINT.length>0?ld(ot().OTEL_EXPORTER_OTLP_METRICS_ENDPOINT):ot().OTEL_EXPORTER_OTLP_ENDPOINT.length>0?sd(ot().OTEL_EXPORTER_OTLP_ENDPOINT,aE):bP},e}(qs),sE=function(r){iE(e,r);function e(t){return r.call(this,new vP(t),t)||this}return e}(ky);var xo;(function(r){r[r.DELTA=0]="DELTA",r[r.CUMULATIVE=1]="CUMULATIVE"})(xo||(xo={}));var mr;(function(r){r[r.HISTOGRAM=0]="HISTOGRAM",r[r.EXPONENTIAL_HISTOGRAM=1]="EXPONENTIAL_HISTOGRAM",r[r.GAUGE=2]="GAUGE",r[r.SUM=3]="SUM"})(mr||(mr={}));he();var AP=function(){var r=function(e,t){return r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,o){n.__proto__=o}||function(n,o){for(var i in o)Object.prototype.hasOwnProperty.call(o,i)&&(n[i]=o[i])},r(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");r(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}}(),lE=function(r,e,t,n){function o(i){return i instanceof t?i:new t(function(a){a(i)})}return new(t||(t=Promise))(function(i,a){function l(u){try{s(n.next(u))}catch(d){a(d)}}function c(u){try{s(n.throw(u))}catch(d){a(d)}}function s(u){u.done?i(u.value):o(u.value).then(l,c)}s((n=n.apply(r,e||[])).next())})},cE=function(r,e){var t={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},n,o,i,a;return a={next:l(0),throw:l(1),return:l(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function l(s){return function(u){return c([s,u])}}function c(s){if(n)throw new TypeError("Generator is already executing.");for(;t;)try{if(n=1,o&&(i=s[0]&2?o.return:s[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,s[1])).done)return i;switch(o=0,i&&(s=[s[0]&2,i.value]),s[0]){case 0:case 1:i=s;break;case 4:return t.label++,{value:s[1],done:!1};case 5:t.label++,o=s[1],s=[0];continue;case 7:s=t.ops.pop(),t.trys.pop();continue;default:if(i=t.trys,!(i=i.length>0&&i[i.length-1])&&(s[0]===6||s[0]===2)){t=0;continue}if(s[0]===3&&(!i||s[1]>i[0]&&s[1]<i[3])){t.label=s[1];break}if(s[0]===6&&t.label<i[1]){t.label=i[1],i=s;break}if(i&&t.label<i[2]){t.label=i[2],t.ops.push(s);break}i[2]&&t.ops.pop(),t.trys.pop();continue}s=e.call(r,t)}catch(u){s=[6,u],o=0}finally{n=i=0}if(s[0]&5)throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}},RP=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},wP=function(r,e,t){if(t||arguments.length===2)for(var n=0,o=e.length,i;n<o;n++)(i||!(n in e))&&(i||(i=Array.prototype.slice.call(e,0,n)),i[n]=e[n]);return r.concat(i||Array.prototype.slice.call(e))},CP=function(r){var e=typeof Symbol=="function"&&Symbol.iterator,t=e&&r[e],n=0;if(t)return t.call(r);if(r&&typeof r.length=="number")return{next:function(){return r&&n>=r.length&&(r=void 0),{value:r&&r[n++],done:!r}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")};function uE(r){return r!=null}function Ks(r){var e=Object.keys(r);return e.length===0?"":(e=e.sort(),JSON.stringify(e.map(function(t){return[t,r[t]]})))}function dE(r){var e,t;return r.name+":"+((e=r.version)!==null&&e!==void 0?e:"")+":"+((t=r.schemaUrl)!==null&&t!==void 0?t:"")}var fd=function(r){AP(e,r);function e(t){var n=r.call(this,t)||this;return Object.setPrototypeOf(n,e.prototype),n}return e}(Error);function Jr(r,e){var t,n=new Promise(function(i,a){t=setTimeout(function(){a(new fd("Operation timed out."))},e)});return Promise.race([r,n]).then(function(o){return clearTimeout(t),o},function(o){throw clearTimeout(t),o})}function pE(r){return lE(this,void 0,void 0,function(){var e=this;return cE(this,function(t){return[2,Promise.all(r.map(function(n){return lE(e,void 0,void 0,function(){var o,i;return cE(this,function(a){switch(a.label){case 0:return a.trys.push([0,2,,3]),[4,n];case 1:return o=a.sent(),[2,{status:"fulfilled",value:o}];case 2:return i=a.sent(),[2,{status:"rejected",reason:i}];case 3:return[2]}})})}))]})})}function mE(r){return r.status==="rejected"}function Sd(r,e){var t=[];return r.forEach(function(n){t.push.apply(t,wP([],RP(e(n)),!1))}),t}function gE(r,e){var t,n;if(r.size!==e.size)return!1;try{for(var o=CP(r),i=o.next();!i.done;i=o.next()){var a=i.value;if(!e.has(a))return!1}}catch(l){t={error:l}}finally{try{i&&!i.done&&(n=o.return)&&n.call(o)}finally{if(t)throw t.error}}return!0}function hE(r,e){for(var t=0,n=r.length-1,o=r.length;n>=t;){var i=t+Math.trunc((n-t)/2);r[i]<e?t=i+1:(o=i,n=i-1)}return o}function fE(r,e){return r.toLowerCase()===e.toLowerCase()}he();var Ht;(function(r){r[r.DROP=0]="DROP",r[r.SUM=1]="SUM",r[r.LAST_VALUE=2]="LAST_VALUE",r[r.HISTOGRAM=3]="HISTOGRAM",r[r.EXPONENTIAL_HISTOGRAM=4]="EXPONENTIAL_HISTOGRAM"})(Ht||(Ht={}));var yd=function(){function r(){this.kind=Ht.DROP}return r.prototype.createAccumulation=function(){},r.prototype.merge=function(e,t){},r.prototype.diff=function(e,t){},r.prototype.toMetricData=function(e,t,n,o){},r}();he();var oe;(function(r){r.COUNTER="COUNTER",r.GAUGE="GAUGE",r.HISTOGRAM="HISTOGRAM",r.UP_DOWN_COUNTER="UP_DOWN_COUNTER",r.OBSERVABLE_COUNTER="OBSERVABLE_COUNTER",r.OBSERVABLE_GAUGE="OBSERVABLE_GAUGE",r.OBSERVABLE_UP_DOWN_COUNTER="OBSERVABLE_UP_DOWN_COUNTER"})(oe||(oe={}));function gr(r,e,t){var n,o,i,a;return _P(r)||F.warn('Invalid metric name: "'+r+'". The metric name should be a ASCII string with a length no greater than 255 characters.'),{name:r,type:e,description:(n=t?.description)!==null&&n!==void 0?n:"",unit:(o=t?.unit)!==null&&o!==void 0?o:"",valueType:(i=t?.valueType)!==null&&i!==void 0?i:_t.DOUBLE,advice:(a=t?.advice)!==null&&a!==void 0?a:{}}}function SE(r,e){var t,n;return{name:(t=r.name)!==null&&t!==void 0?t:e.name,description:(n=r.description)!==null&&n!==void 0?n:e.description,type:e.type,unit:e.unit,valueType:e.valueType,advice:e.advice}}function yE(r,e){return fE(r.name,e.name)&&r.unit===e.unit&&r.type===e.type&&r.valueType===e.valueType}var xP=/^[a-z][a-z0-9_.\-/]{0,254}$/i;function _P(r){return r.match(xP)!=null}var MP=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i};function IP(r){var e=r.map(function(){return 0});return e.push(0),{buckets:{boundaries:r,counts:e},sum:0,count:0,hasMinMax:!1,min:1/0,max:-1/0}}var Ys=function(){function r(e,t,n,o){n===void 0&&(n=!0),o===void 0&&(o=IP(t)),this.startTime=e,this._boundaries=t,this._recordMinMax=n,this._current=o}return r.prototype.record=function(e){if(!Number.isNaN(e)){this._current.count+=1,this._current.sum+=e,this._recordMinMax&&(this._current.min=Math.min(e,this._current.min),this._current.max=Math.max(e,this._current.max),this._current.hasMinMax=!0);var t=hE(this._boundaries,e);this._current.buckets.counts[t]+=1}},r.prototype.setStartTime=function(e){this.startTime=e},r.prototype.toPointValue=function(){return this._current},r}();var Xs=function(){function r(e,t){this._boundaries=e,this._recordMinMax=t,this.kind=Ht.HISTOGRAM}return r.prototype.createAccumulation=function(e){return new Ys(e,this._boundaries,this._recordMinMax)},r.prototype.merge=function(e,t){for(var n=e.toPointValue(),o=t.toPointValue(),i=n.buckets.counts,a=o.buckets.counts,l=new Array(i.length),c=0;c<i.length;c++)l[c]=i[c]+a[c];var s=1/0,u=-1/0;return this._recordMinMax&&(n.hasMinMax&&o.hasMinMax?(s=Math.min(n.min,o.min),u=Math.max(n.max,o.max)):n.hasMinMax?(s=n.min,u=n.max):o.hasMinMax&&(s=o.min,u=o.max)),new Ys(e.startTime,n.buckets.boundaries,this._recordMinMax,{buckets:{boundaries:n.buckets.boundaries,counts:l},count:n.count+o.count,sum:n.sum+o.sum,hasMinMax:this._recordMinMax&&(n.hasMinMax||o.hasMinMax),min:s,max:u})},r.prototype.diff=function(e,t){for(var n=e.toPointValue(),o=t.toPointValue(),i=n.buckets.counts,a=o.buckets.counts,l=new Array(i.length),c=0;c<i.length;c++)l[c]=a[c]-i[c];return new Ys(t.startTime,n.buckets.boundaries,this._recordMinMax,{buckets:{boundaries:n.buckets.boundaries,counts:l},count:o.count-n.count,sum:o.sum-n.sum,hasMinMax:!1,min:1/0,max:-1/0})},r.prototype.toMetricData=function(e,t,n,o){return{descriptor:e,aggregationTemporality:t,dataPointType:mr.HISTOGRAM,dataPoints:n.map(function(i){var a=MP(i,2),l=a[0],c=a[1],s=c.toPointValue(),u=e.type===oe.GAUGE||e.type===oe.UP_DOWN_COUNTER||e.type===oe.OBSERVABLE_GAUGE||e.type===oe.OBSERVABLE_UP_DOWN_COUNTER;return{attributes:l,startTime:c.startTime,endTime:o,value:{min:s.hasMinMax?s.min:void 0,max:s.hasMinMax?s.max:void 0,sum:u?void 0:s.sum,buckets:s.buckets,count:s.count}}})}},r}();he();var Ed=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},bd=function(r,e,t){if(t||arguments.length===2)for(var n=0,o=e.length,i;n<o;n++)(i||!(n in e))&&(i||(i=Array.prototype.slice.call(e,0,n)),i[n]=e[n]);return r.concat(i||Array.prototype.slice.call(e))},Td=function(){function r(e,t,n,o){e===void 0&&(e=new PP),t===void 0&&(t=0),n===void 0&&(n=0),o===void 0&&(o=0),this.backing=e,this.indexBase=t,this.indexStart=n,this.indexEnd=o}return Object.defineProperty(r.prototype,"offset",{get:function(){return this.indexStart},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"length",{get:function(){return this.backing.length===0||this.indexEnd===this.indexStart&&this.at(0)===0?0:this.indexEnd-this.indexStart+1},enumerable:!1,configurable:!0}),r.prototype.counts=function(){var e=this;return Array.from({length:this.length},function(t,n){return e.at(n)})},r.prototype.at=function(e){var t=this.indexBase-this.indexStart;return e<t&&(e+=this.backing.length),e-=t,this.backing.countAt(e)},r.prototype.incrementBucket=function(e,t){this.backing.increment(e,t)},r.prototype.decrementBucket=function(e,t){this.backing.decrement(e,t)},r.prototype.trim=function(){for(var e=0;e<this.length;e++)if(this.at(e)!==0){this.indexStart+=e;break}else if(e===this.length-1){this.indexStart=this.indexEnd=this.indexBase=0;return}for(var e=this.length-1;e>=0;e--)if(this.at(e)!==0){this.indexEnd-=this.length-e-1;break}this._rotate()},r.prototype.downscale=function(e){this._rotate();for(var t=1+this.indexEnd-this.indexStart,n=1<<e,o=0,i=0,a=this.indexStart;a<=this.indexEnd;){var l=a%n;l<0&&(l+=n);for(var c=l;c<n&&o<t;c++)this._relocateBucket(i,o),o++,a++;i++}this.indexStart>>=e,this.indexEnd>>=e,this.indexBase=this.indexStart},r.prototype.clone=function(){return new r(this.backing.clone(),this.indexBase,this.indexStart,this.indexEnd)},r.prototype._rotate=function(){var e=this.indexBase-this.indexStart;e!==0&&(e>0?(this.backing.reverse(0,this.backing.length),this.backing.reverse(0,e),this.backing.reverse(e,this.backing.length)):(this.backing.reverse(0,this.backing.length),this.backing.reverse(0,this.backing.length+e)),this.indexBase=this.indexStart)},r.prototype._relocateBucket=function(e,t){e!==t&&this.incrementBucket(e,this.backing.emptyBucket(t))},r}();var PP=function(){function r(e){e===void 0&&(e=[0]),this._counts=e}return Object.defineProperty(r.prototype,"length",{get:function(){return this._counts.length},enumerable:!1,configurable:!0}),r.prototype.countAt=function(e){return this._counts[e]},r.prototype.growTo=function(e,t,n){var o=new Array(e).fill(0);o.splice.apply(o,bd([n,this._counts.length-t],Ed(this._counts.slice(t)),!1)),o.splice.apply(o,bd([0,t],Ed(this._counts.slice(0,t)),!1)),this._counts=o},r.prototype.reverse=function(e,t){for(var n=Math.floor((e+t)/2)-e,o=0;o<n;o++){var i=this._counts[e+o];this._counts[e+o]=this._counts[t-o-1],this._counts[t-o-1]=i}},r.prototype.emptyBucket=function(e){var t=this._counts[e];return this._counts[e]=0,t},r.prototype.increment=function(e,t){this._counts[e]+=t},r.prototype.decrement=function(e,t){this._counts[e]>=t?this._counts[e]-=t:this._counts[e]=0},r.prototype.clone=function(){return new r(bd([],Ed(this._counts),!1))},r}();var EE=52,OP=2146435072,LP=1048575,vd=1023,Js=-vd+1,Qs=vd,Ki=Math.pow(2,-1022);function Zs(r){var e=new DataView(new ArrayBuffer(8));e.setFloat64(0,r);var t=e.getUint32(0),n=(t&OP)>>20;return n-vd}function el(r){var e=new DataView(new ArrayBuffer(8));e.setFloat64(0,r);var t=e.getUint32(0),n=e.getUint32(4),o=(t&LP)*Math.pow(2,32);return o+n}function Yi(r,e){return r===0||r===Number.POSITIVE_INFINITY||r===Number.NEGATIVE_INFINITY||Number.isNaN(r)?r:r*Math.pow(2,e)}function TE(r){return r--,r|=r>>1,r|=r>>2,r|=r>>4,r|=r>>8,r|=r>>16,r++,r}var NP=function(){var r=function(e,t){return r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,o){n.__proto__=o}||function(n,o){for(var i in o)Object.prototype.hasOwnProperty.call(o,i)&&(n[i]=o[i])},r(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");r(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}}(),Qr=function(r){NP(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(Error);var AE=function(){function r(e){this._shift=-e}return r.prototype.mapToIndex=function(e){if(e<Ki)return this._minNormalLowerBoundaryIndex();var t=Zs(e),n=this._rightShift(el(e)-1,EE);return t+n>>this._shift},r.prototype.lowerBoundary=function(e){var t=this._minNormalLowerBoundaryIndex();if(e<t)throw new Qr("underflow: "+e+" is < minimum lower boundary: "+t);var n=this._maxNormalLowerBoundaryIndex();if(e>n)throw new Qr("overflow: "+e+" is > maximum lower boundary: "+n);return Yi(1,e<<this._shift)},Object.defineProperty(r.prototype,"scale",{get:function(){return this._shift===0?0:-this._shift},enumerable:!1,configurable:!0}),r.prototype._minNormalLowerBoundaryIndex=function(){var e=Js>>this._shift;return this._shift<2&&e--,e},r.prototype._maxNormalLowerBoundaryIndex=function(){return Qs>>this._shift},r.prototype._rightShift=function(e,t){return Math.floor(e*Math.pow(2,-t))},r}();var RE=function(){function r(e){this._scale=e,this._scaleFactor=Yi(Math.LOG2E,e),this._inverseFactor=Yi(Math.LN2,-e)}return r.prototype.mapToIndex=function(e){if(e<=Ki)return this._minNormalLowerBoundaryIndex()-1;if(el(e)===0){var t=Zs(e);return(t<<this._scale)-1}var n=Math.floor(Math.log(e)*this._scaleFactor),o=this._maxNormalLowerBoundaryIndex();return n>=o?o:n},r.prototype.lowerBoundary=function(e){var t=this._maxNormalLowerBoundaryIndex();if(e>=t){if(e===t)return 2*Math.exp((e-(1<<this._scale))/this._scaleFactor);throw new Qr("overflow: "+e+" is > maximum lower boundary: "+t)}var n=this._minNormalLowerBoundaryIndex();if(e<=n){if(e===n)return Ki;if(e===n-1)return Math.exp((e+(1<<this._scale))/this._scaleFactor)/2;throw new Qr("overflow: "+e+" is < minimum lower boundary: "+n)}return Math.exp(e*this._inverseFactor)},Object.defineProperty(r.prototype,"scale",{get:function(){return this._scale},enumerable:!1,configurable:!0}),r.prototype._minNormalLowerBoundaryIndex=function(){return Js<<this._scale},r.prototype._maxNormalLowerBoundaryIndex=function(){return(Qs+1<<this._scale)-1},r}();var wE=-10,CE=20,DP=Array.from({length:31},function(r,e){return e>10?new RE(e-10):new AE(e-10)});function Ad(r){if(r>CE||r<wE)throw new Qr("expected scale >= "+wE+" && <= "+CE+", got: "+r);return DP[r+10]}var kP=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},tl=function(){function r(e,t){this.low=e,this.high=t}return r.combine=function(e,t){return new r(Math.min(e.low,t.low),Math.max(e.high,t.high))},r}(),UP=20,FP=160,Rd=2,xE=function(){function r(e,t,n,o,i,a,l,c,s,u,d){e===void 0&&(e=e),t===void 0&&(t=FP),n===void 0&&(n=!0),o===void 0&&(o=0),i===void 0&&(i=0),a===void 0&&(a=0),l===void 0&&(l=Number.POSITIVE_INFINITY),c===void 0&&(c=Number.NEGATIVE_INFINITY),s===void 0&&(s=new Td),u===void 0&&(u=new Td),d===void 0&&(d=Ad(UP)),this.startTime=e,this._maxSize=t,this._recordMinMax=n,this._sum=o,this._count=i,this._zeroCount=a,this._min=l,this._max=c,this._positive=s,this._negative=u,this._mapping=d,this._maxSize<Rd&&(F.warn("Exponential Histogram Max Size set to "+this._maxSize+", changing to the minimum size of: "+Rd),this._maxSize=Rd)}return r.prototype.record=function(e){this.updateByIncrement(e,1)},r.prototype.setStartTime=function(e){this.startTime=e},r.prototype.toPointValue=function(){return{hasMinMax:this._recordMinMax,min:this.min,max:this.max,sum:this.sum,positive:{offset:this.positive.offset,bucketCounts:this.positive.counts()},negative:{offset:this.negative.offset,bucketCounts:this.negative.counts()},count:this.count,scale:this.scale,zeroCount:this.zeroCount}},Object.defineProperty(r.prototype,"sum",{get:function(){return this._sum},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"min",{get:function(){return this._min},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"max",{get:function(){return this._max},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"count",{get:function(){return this._count},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"zeroCount",{get:function(){return this._zeroCount},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"scale",{get:function(){return this._count===this._zeroCount?0:this._mapping.scale},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"positive",{get:function(){return this._positive},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"negative",{get:function(){return this._negative},enumerable:!1,configurable:!0}),r.prototype.updateByIncrement=function(e,t){if(!Number.isNaN(e)){if(e>this._max&&(this._max=e),e<this._min&&(this._min=e),this._count+=t,e===0){this._zeroCount+=t;return}this._sum+=e*t,e>0?this._updateBuckets(this._positive,e,t):this._updateBuckets(this._negative,-e,t)}},r.prototype.merge=function(e){this._count===0?(this._min=e.min,this._max=e.max):e.count!==0&&(e.min<this.min&&(this._min=e.min),e.max>this.max&&(this._max=e.max)),this.startTime=e.startTime,this._sum+=e.sum,this._count+=e.count,this._zeroCount+=e.zeroCount;var t=this._minScale(e);this._downscale(this.scale-t),this._mergeBuckets(this.positive,e,e.positive,t),this._mergeBuckets(this.negative,e,e.negative,t)},r.prototype.diff=function(e){this._min=1/0,this._max=-1/0,this._sum-=e.sum,this._count-=e.count,this._zeroCount-=e.zeroCount;var t=this._minScale(e);this._downscale(this.scale-t),this._diffBuckets(this.positive,e,e.positive,t),this._diffBuckets(this.negative,e,e.negative,t)},r.prototype.clone=function(){return new r(this.startTime,this._maxSize,this._recordMinMax,this._sum,this._count,this._zeroCount,this._min,this._max,this.positive.clone(),this.negative.clone(),this._mapping)},r.prototype._updateBuckets=function(e,t,n){var o=this._mapping.mapToIndex(t),i=!1,a=0,l=0;if(e.length===0?(e.indexStart=o,e.indexEnd=e.indexStart,e.indexBase=e.indexStart):o<e.indexStart&&e.indexEnd-o>=this._maxSize?(i=!0,l=o,a=e.indexEnd):o>e.indexEnd&&o-e.indexStart>=this._maxSize&&(i=!0,l=e.indexStart,a=o),i){var c=this._changeScale(a,l);this._downscale(c),o=this._mapping.mapToIndex(t)}this._incrementIndexBy(e,o,n)},r.prototype._incrementIndexBy=function(e,t,n){if(n!==0){if(e.length===0&&(e.indexStart=e.indexEnd=e.indexBase=t),t<e.indexStart){var o=e.indexEnd-t;o>=e.backing.length&&this._grow(e,o+1),e.indexStart=t}else if(t>e.indexEnd){var o=t-e.indexStart;o>=e.backing.length&&this._grow(e,o+1),e.indexEnd=t}var i=t-e.indexBase;i<0&&(i+=e.backing.length),e.incrementBucket(i,n)}},r.prototype._grow=function(e,t){var n=e.backing.length,o=e.indexBase-e.indexStart,i=n-o,a=TE(t);a>this._maxSize&&(a=this._maxSize);var l=a-o;e.backing.growTo(a,i,l)},r.prototype._changeScale=function(e,t){for(var n=0;e-t>=this._maxSize;)e>>=1,t>>=1,n++;return n},r.prototype._downscale=function(e){if(e!==0){if(e<0)throw new Error("impossible change of scale: "+this.scale);var t=this._mapping.scale-e;this._positive.downscale(e),this._negative.downscale(e),this._mapping=Ad(t)}},r.prototype._minScale=function(e){var t=Math.min(this.scale,e.scale),n=tl.combine(this._highLowAtScale(this.positive,this.scale,t),this._highLowAtScale(e.positive,e.scale,t)),o=tl.combine(this._highLowAtScale(this.negative,this.scale,t),this._highLowAtScale(e.negative,e.scale,t));return Math.min(t-this._changeScale(n.high,n.low),t-this._changeScale(o.high,o.low))},r.prototype._highLowAtScale=function(e,t,n){if(e.length===0)return new tl(0,-1);var o=t-n;return new tl(e.indexStart>>o,e.indexEnd>>o)},r.prototype._mergeBuckets=function(e,t,n,o){for(var i=n.offset,a=t.scale-o,l=0;l<n.length;l++)this._incrementIndexBy(e,i+l>>a,n.at(l))},r.prototype._diffBuckets=function(e,t,n,o){for(var i=n.offset,a=t.scale-o,l=0;l<n.length;l++){var c=i+l>>a,s=c-e.indexBase;s<0&&(s+=e.backing.length),e.decrementBucket(s,n.at(l))}e.trim()},r}();var wd=function(){function r(e,t){this._maxSize=e,this._recordMinMax=t,this.kind=Ht.EXPONENTIAL_HISTOGRAM}return r.prototype.createAccumulation=function(e){return new xE(e,this._maxSize,this._recordMinMax)},r.prototype.merge=function(e,t){var n=t.clone();return n.merge(e),n},r.prototype.diff=function(e,t){var n=t.clone();return n.diff(e),n},r.prototype.toMetricData=function(e,t,n,o){return{descriptor:e,aggregationTemporality:t,dataPointType:mr.EXPONENTIAL_HISTOGRAM,dataPoints:n.map(function(i){var a=kP(i,2),l=a[0],c=a[1],s=c.toPointValue(),u=e.type===oe.GAUGE||e.type===oe.UP_DOWN_COUNTER||e.type===oe.OBSERVABLE_GAUGE||e.type===oe.OBSERVABLE_UP_DOWN_COUNTER;return{attributes:l,startTime:c.startTime,endTime:o,value:{min:s.hasMinMax?s.min:void 0,max:s.hasMinMax?s.max:void 0,sum:u?void 0:s.sum,positive:{offset:s.positive.offset,bucketCounts:s.positive.bucketCounts},negative:{offset:s.negative.offset,bucketCounts:s.negative.bucketCounts},count:s.count,scale:s.scale,zeroCount:s.zeroCount}}})}},r}();he();var BP=ku("OpenTelemetry SDK Context Key SUPPRESS_TRACING");function _E(r){return r.setValue(BP,!0)}he();function ME(){return function(r){F.error(zP(r))}}function zP(r){return typeof r=="string"?r:JSON.stringify(GP(r))}function GP(r){for(var e={},t=r;t!==null;)Object.getOwnPropertyNames(t).forEach(function(n){if(!e[n]){var o=t[n];o&&(e[n]=String(o))}}),t=Object.getPrototypeOf(t);return e}var HP=ME();function rl(r){try{HP(r)}catch{}}var IE="1.30.1";var VP="process.runtime.name";var jP="service.name";var WP="telemetry.sdk.name",$P="telemetry.sdk.language",qP="telemetry.sdk.version";var PE=VP;var OE=jP;var Xi=WP,Ji=$P,Qi=qP;var KP="nodejs";var LE=KP;var _o,Pn=(_o={},_o[Xi]="opentelemetry",_o[PE]="node",_o[Ji]=LE,_o[Qi]=IE,_o);function Zi(r){r.unref()}var tO=9,rO=6,nO=Math.pow(10,rO),Dee=Math.pow(10,tO);function On(r){var e=r/1e3,t=Math.trunc(e),n=Math.round(r%1e3*nO);return[t,n]}function Mo(r){return r[0]*1e6+r[1]/1e3}var ea;(function(r){r[r.SUCCESS=0]="SUCCESS",r[r.FAILED=1]="FAILED"})(ea||(ea={}));he();function NE(r,e){return new Promise(function(t){To.with(_E(To.active()),function(){r.export(e,function(n){t(n)})})})}var DE={_export:NE};var oO=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},nl=function(){function r(e,t,n){t===void 0&&(t=0),n===void 0&&(n=[0,0]),this.startTime=e,this._current=t,this.sampleTime=n}return r.prototype.record=function(e){this._current=e,this.sampleTime=On(Date.now())},r.prototype.setStartTime=function(e){this.startTime=e},r.prototype.toPointValue=function(){return this._current},r}();var Cd=function(){function r(){this.kind=Ht.LAST_VALUE}return r.prototype.createAccumulation=function(e){return new nl(e)},r.prototype.merge=function(e,t){var n=Mo(t.sampleTime)>=Mo(e.sampleTime)?t:e;return new nl(e.startTime,n.toPointValue(),n.sampleTime)},r.prototype.diff=function(e,t){var n=Mo(t.sampleTime)>=Mo(e.sampleTime)?t:e;return new nl(t.startTime,n.toPointValue(),n.sampleTime)},r.prototype.toMetricData=function(e,t,n,o){return{descriptor:e,aggregationTemporality:t,dataPointType:mr.GAUGE,dataPoints:n.map(function(i){var a=oO(i,2),l=a[0],c=a[1];return{attributes:l,startTime:c.startTime,endTime:o,value:c.toPointValue()}})}},r}();var iO=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},Io=function(){function r(e,t,n,o){n===void 0&&(n=0),o===void 0&&(o=!1),this.startTime=e,this.monotonic=t,this._current=n,this.reset=o}return r.prototype.record=function(e){this.monotonic&&e<0||(this._current+=e)},r.prototype.setStartTime=function(e){this.startTime=e},r.prototype.toPointValue=function(){return this._current},r}();var ol=function(){function r(e){this.monotonic=e,this.kind=Ht.SUM}return r.prototype.createAccumulation=function(e){return new Io(e,this.monotonic)},r.prototype.merge=function(e,t){var n=e.toPointValue(),o=t.toPointValue();return t.reset?new Io(t.startTime,this.monotonic,o,t.reset):new Io(e.startTime,this.monotonic,n+o)},r.prototype.diff=function(e,t){var n=e.toPointValue(),o=t.toPointValue();return this.monotonic&&n>o?new Io(t.startTime,this.monotonic,o,!0):new Io(t.startTime,this.monotonic,o-n)},r.prototype.toMetricData=function(e,t,n,o){return{descriptor:e,aggregationTemporality:t,dataPointType:mr.SUM,dataPoints:n.map(function(i){var a=iO(i,2),l=a[0],c=a[1];return{attributes:l,startTime:c.startTime,endTime:o,value:c.toPointValue()}}),isMonotonic:this.monotonic}},r}();var Ln=function(){var r=function(e,t){return r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,o){n.__proto__=o}||function(n,o){for(var i in o)Object.prototype.hasOwnProperty.call(o,i)&&(n[i]=o[i])},r(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");r(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}}(),Vt=function(){function r(){}return r.Drop=function(){return HE},r.Sum=function(){return VE},r.LastValue=function(){return jE},r.Histogram=function(){return WE},r.ExponentialHistogram=function(){return aO},r.Default=function(){return sO},r}();var kE=function(r){Ln(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.createAggregator=function(t){return e.DEFAULT_INSTANCE},e.DEFAULT_INSTANCE=new yd,e}(Vt);var UE=function(r){Ln(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.createAggregator=function(t){switch(t.type){case oe.COUNTER:case oe.OBSERVABLE_COUNTER:case oe.HISTOGRAM:return e.MONOTONIC_INSTANCE;default:return e.NON_MONOTONIC_INSTANCE}},e.MONOTONIC_INSTANCE=new ol(!0),e.NON_MONOTONIC_INSTANCE=new ol(!1),e}(Vt);var FE=function(r){Ln(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.createAggregator=function(t){return e.DEFAULT_INSTANCE},e.DEFAULT_INSTANCE=new Cd,e}(Vt);var BE=function(r){Ln(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.createAggregator=function(t){return e.DEFAULT_INSTANCE},e.DEFAULT_INSTANCE=new Xs([0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4],!0),e}(Vt);var il=function(r){Ln(e,r);function e(t,n){n===void 0&&(n=!0);var o=r.call(this)||this;if(o._recordMinMax=n,t==null)throw new Error("ExplicitBucketHistogramAggregation should be created with explicit boundaries, if a single bucket histogram is required, please pass an empty array");t=t.concat(),t=t.sort(function(l,c){return l-c});var i=t.lastIndexOf(-1/0),a=t.indexOf(1/0);return a===-1&&(a=void 0),o._boundaries=t.slice(i+1,a),o}return e.prototype.createAggregator=function(t){return new Xs(this._boundaries,this._recordMinMax)},e}(Vt);var zE=function(r){Ln(e,r);function e(t,n){t===void 0&&(t=160),n===void 0&&(n=!0);var o=r.call(this)||this;return o._maxSize=t,o._recordMinMax=n,o}return e.prototype.createAggregator=function(t){return new wd(this._maxSize,this._recordMinMax)},e}(Vt);var GE=function(r){Ln(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype._resolve=function(t){switch(t.type){case oe.COUNTER:case oe.UP_DOWN_COUNTER:case oe.OBSERVABLE_COUNTER:case oe.OBSERVABLE_UP_DOWN_COUNTER:return VE;case oe.GAUGE:case oe.OBSERVABLE_GAUGE:return jE;case oe.HISTOGRAM:return t.advice.explicitBucketBoundaries?new il(t.advice.explicitBucketBoundaries):WE}return F.warn("Unable to recognize instrument type: "+t.type),HE},e.prototype.createAggregator=function(t){return this._resolve(t).createAggregator(t)},e}(Vt);var HE=new kE,VE=new UE,jE=new FE,WE=new BE,aO=new zE,sO=new GE;var $E=function(r){return Vt.Default()},qE=function(r){return xo.CUMULATIVE};var xd=function(r,e,t,n){function o(i){return i instanceof t?i:new t(function(a){a(i)})}return new(t||(t=Promise))(function(i,a){function l(u){try{s(n.next(u))}catch(d){a(d)}}function c(u){try{s(n.throw(u))}catch(d){a(d)}}function s(u){u.done?i(u.value):o(u.value).then(l,c)}s((n=n.apply(r,e||[])).next())})},_d=function(r,e){var t={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},n,o,i,a;return a={next:l(0),throw:l(1),return:l(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function l(s){return function(u){return c([s,u])}}function c(s){if(n)throw new TypeError("Generator is already executing.");for(;t;)try{if(n=1,o&&(i=s[0]&2?o.return:s[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,s[1])).done)return i;switch(o=0,i&&(s=[s[0]&2,i.value]),s[0]){case 0:case 1:i=s;break;case 4:return t.label++,{value:s[1],done:!1};case 5:t.label++,o=s[1],s=[0];continue;case 7:s=t.ops.pop(),t.trys.pop();continue;default:if(i=t.trys,!(i=i.length>0&&i[i.length-1])&&(s[0]===6||s[0]===2)){t=0;continue}if(s[0]===3&&(!i||s[1]>i[0]&&s[1]<i[3])){t.label=s[1];break}if(s[0]===6&&t.label<i[1]){t.label=i[1],i=s;break}if(i&&t.label<i[2]){t.label=i[2],t.ops.push(s);break}i[2]&&t.ops.pop(),t.trys.pop();continue}s=e.call(r,t)}catch(u){s=[6,u],o=0}finally{n=i=0}if(s[0]&5)throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}},KE=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},lO=function(r,e,t){if(t||arguments.length===2)for(var n=0,o=e.length,i;n<o;n++)(i||!(n in e))&&(i||(i=Array.prototype.slice.call(e,0,n)),i[n]=e[n]);return r.concat(i||Array.prototype.slice.call(e))},YE=function(){function r(e){var t,n,o;this._shutdown=!1,this._aggregationSelector=(t=e?.aggregationSelector)!==null&&t!==void 0?t:$E,this._aggregationTemporalitySelector=(n=e?.aggregationTemporalitySelector)!==null&&n!==void 0?n:qE,this._metricProducers=(o=e?.metricProducers)!==null&&o!==void 0?o:[],this._cardinalitySelector=e?.cardinalitySelector}return r.prototype.setMetricProducer=function(e){if(this._sdkMetricProducer)throw new Error("MetricReader can not be bound to a MeterProvider again.");this._sdkMetricProducer=e,this.onInitialized()},r.prototype.selectAggregation=function(e){return this._aggregationSelector(e)},r.prototype.selectAggregationTemporality=function(e){return this._aggregationTemporalitySelector(e)},r.prototype.selectCardinalityLimit=function(e){return this._cardinalitySelector?this._cardinalitySelector(e):2e3},r.prototype.onInitialized=function(){},r.prototype.collect=function(e){return xd(this,void 0,void 0,function(){var t,n,o,i,a,l;return _d(this,function(c){switch(c.label){case 0:if(this._sdkMetricProducer===void 0)throw new Error("MetricReader is not bound to a MetricProducer");if(this._shutdown)throw new Error("MetricReader is shutdown");return[4,Promise.all(lO([this._sdkMetricProducer.collect({timeoutMillis:e?.timeoutMillis})],KE(this._metricProducers.map(function(s){return s.collect({timeoutMillis:e?.timeoutMillis})})),!1))];case 1:return t=KE.apply(void 0,[c.sent()]),n=t[0],o=t.slice(1),i=n.errors.concat(Sd(o,function(s){return s.errors})),a=n.resourceMetrics.resource,l=n.resourceMetrics.scopeMetrics.concat(Sd(o,function(s){return s.resourceMetrics.scopeMetrics})),[2,{resourceMetrics:{resource:a,scopeMetrics:l},errors:i}]}})})},r.prototype.shutdown=function(e){return xd(this,void 0,void 0,function(){return _d(this,function(t){switch(t.label){case 0:return this._shutdown?(F.error("Cannot call shutdown twice."),[2]):e?.timeoutMillis!=null?[3,2]:[4,this.onShutdown()];case 1:return t.sent(),[3,4];case 2:return[4,Jr(this.onShutdown(),e.timeoutMillis)];case 3:t.sent(),t.label=4;case 4:return this._shutdown=!0,[2]}})})},r.prototype.forceFlush=function(e){return xd(this,void 0,void 0,function(){return _d(this,function(t){switch(t.label){case 0:return this._shutdown?(F.warn("Cannot forceFlush on already shutdown MetricReader."),[2]):e?.timeoutMillis!=null?[3,2]:[4,this.onForceFlush()];case 1:return t.sent(),[2];case 2:return[4,Jr(this.onForceFlush(),e.timeoutMillis)];case 3:return t.sent(),[2]}})})},r}();he();var cO=function(){var r=function(e,t){return r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,o){n.__proto__=o}||function(n,o){for(var i in o)Object.prototype.hasOwnProperty.call(o,i)&&(n[i]=o[i])},r(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");r(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}}(),al=function(r,e,t,n){function o(i){return i instanceof t?i:new t(function(a){a(i)})}return new(t||(t=Promise))(function(i,a){function l(u){try{s(n.next(u))}catch(d){a(d)}}function c(u){try{s(n.throw(u))}catch(d){a(d)}}function s(u){u.done?i(u.value):o(u.value).then(l,c)}s((n=n.apply(r,e||[])).next())})},sl=function(r,e){var t={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},n,o,i,a;return a={next:l(0),throw:l(1),return:l(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function l(s){return function(u){return c([s,u])}}function c(s){if(n)throw new TypeError("Generator is already executing.");for(;t;)try{if(n=1,o&&(i=s[0]&2?o.return:s[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,s[1])).done)return i;switch(o=0,i&&(s=[s[0]&2,i.value]),s[0]){case 0:case 1:i=s;break;case 4:return t.label++,{value:s[1],done:!1};case 5:t.label++,o=s[1],s=[0];continue;case 7:s=t.ops.pop(),t.trys.pop();continue;default:if(i=t.trys,!(i=i.length>0&&i[i.length-1])&&(s[0]===6||s[0]===2)){t=0;continue}if(s[0]===3&&(!i||s[1]>i[0]&&s[1]<i[3])){t.label=s[1];break}if(s[0]===6&&t.label<i[1]){t.label=i[1],i=s;break}if(i&&t.label<i[2]){t.label=i[2],t.ops.push(s);break}i[2]&&t.ops.pop(),t.trys.pop();continue}s=e.call(r,t)}catch(u){s=[6,u],o=0}finally{n=i=0}if(s[0]&5)throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}},uO=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},dO=function(r,e,t){if(t||arguments.length===2)for(var n=0,o=e.length,i;n<o;n++)(i||!(n in e))&&(i||(i=Array.prototype.slice.call(e,0,n)),i[n]=e[n]);return r.concat(i||Array.prototype.slice.call(e))},Md=function(r){cO(e,r);function e(t){var n,o,i,a,l=r.call(this,{aggregationSelector:(n=t.exporter.selectAggregation)===null||n===void 0?void 0:n.bind(t.exporter),aggregationTemporalitySelector:(o=t.exporter.selectAggregationTemporality)===null||o===void 0?void 0:o.bind(t.exporter),metricProducers:t.metricProducers})||this;if(t.exportIntervalMillis!==void 0&&t.exportIntervalMillis<=0)throw Error("exportIntervalMillis must be greater than 0");if(t.exportTimeoutMillis!==void 0&&t.exportTimeoutMillis<=0)throw Error("exportTimeoutMillis must be greater than 0");if(t.exportTimeoutMillis!==void 0&&t.exportIntervalMillis!==void 0&&t.exportIntervalMillis<t.exportTimeoutMillis)throw Error("exportIntervalMillis must be greater than or equal to exportTimeoutMillis");return l._exportInterval=(i=t.exportIntervalMillis)!==null&&i!==void 0?i:6e4,l._exportTimeout=(a=t.exportTimeoutMillis)!==null&&a!==void 0?a:3e4,l._exporter=t.exporter,l}return e.prototype._runOnce=function(){return al(this,void 0,void 0,function(){var t;return sl(this,function(n){switch(n.label){case 0:return n.trys.push([0,2,,3]),[4,Jr(this._doRun(),this._exportTimeout)];case 1:return n.sent(),[3,3];case 2:return t=n.sent(),t instanceof fd?(F.error("Export took longer than %s milliseconds and timed out.",this._exportTimeout),[2]):(rl(t),[3,3]);case 3:return[2]}})})},e.prototype._doRun=function(){var t,n;return al(this,void 0,void 0,function(){var o,i,a,l,c,s;return sl(this,function(u){switch(u.label){case 0:return[4,this.collect({timeoutMillis:this._exportTimeout})];case 1:if(o=u.sent(),i=o.resourceMetrics,a=o.errors,a.length>0&&(s=F).error.apply(s,dO(["PeriodicExportingMetricReader: metrics collection errors"],uO(a),!1)),!i.resource.asyncAttributesPending)return[3,5];u.label=2;case 2:return u.trys.push([2,4,,5]),[4,(n=(t=i.resource).waitForAsyncAttributes)===null||n===void 0?void 0:n.call(t)];case 3:return u.sent(),[3,5];case 4:return l=u.sent(),F.debug("Error while resolving async portion of resource: ",l),rl(l),[3,5];case 5:return i.scopeMetrics.length===0?[2]:[4,DE._export(this._exporter,i)];case 6:if(c=u.sent(),c.code!==ea.SUCCESS)throw new Error("PeriodicExportingMetricReader: metrics export failed (error "+c.error+")");return[2]}})})},e.prototype.onInitialized=function(){var t=this;this._interval=setInterval(function(){t._runOnce()},this._exportInterval),Zi(this._interval)},e.prototype.onForceFlush=function(){return al(this,void 0,void 0,function(){return sl(this,function(t){switch(t.label){case 0:return[4,this._runOnce()];case 1:return t.sent(),[4,this._exporter.forceFlush()];case 2:return t.sent(),[2]}})})},e.prototype.onShutdown=function(){return al(this,void 0,void 0,function(){return sl(this,function(t){switch(t.label){case 0:return this._interval&&clearInterval(this._interval),[4,this.onForceFlush()];case 1:return t.sent(),[4,this._exporter.shutdown()];case 2:return t.sent(),[2]}})})},e}(YE);he();he();function ll(){return"unknown_service:"+process.argv0}var Zr=function(){return Zr=Object.assign||function(r){for(var e,t=1,n=arguments.length;t<n;t++){e=arguments[t];for(var o in e)Object.prototype.hasOwnProperty.call(e,o)&&(r[o]=e[o])}return r},Zr.apply(this,arguments)},pO=function(r,e,t,n){function o(i){return i instanceof t?i:new t(function(a){a(i)})}return new(t||(t=Promise))(function(i,a){function l(u){try{s(n.next(u))}catch(d){a(d)}}function c(u){try{s(n.throw(u))}catch(d){a(d)}}function s(u){u.done?i(u.value):o(u.value).then(l,c)}s((n=n.apply(r,e||[])).next())})},mO=function(r,e){var t={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},n,o,i,a;return a={next:l(0),throw:l(1),return:l(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function l(s){return function(u){return c([s,u])}}function c(s){if(n)throw new TypeError("Generator is already executing.");for(;t;)try{if(n=1,o&&(i=s[0]&2?o.return:s[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,s[1])).done)return i;switch(o=0,i&&(s=[s[0]&2,i.value]),s[0]){case 0:case 1:i=s;break;case 4:return t.label++,{value:s[1],done:!1};case 5:t.label++,o=s[1],s=[0];continue;case 7:s=t.ops.pop(),t.trys.pop();continue;default:if(i=t.trys,!(i=i.length>0&&i[i.length-1])&&(s[0]===6||s[0]===2)){t=0;continue}if(s[0]===3&&(!i||s[1]>i[0]&&s[1]<i[3])){t.label=s[1];break}if(s[0]===6&&t.label<i[1]){t.label=i[1],i=s;break}if(i&&t.label<i[2]){t.label=i[2],t.ops.push(s);break}i[2]&&t.ops.pop(),t.trys.pop();continue}s=e.call(r,t)}catch(u){s=[6,u],o=0}finally{n=i=0}if(s[0]&5)throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}},gO=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},cl=function(){function r(e,t){var n=this,o;this._attributes=e,this.asyncAttributesPending=t!=null,this._syncAttributes=(o=this._attributes)!==null&&o!==void 0?o:{},this._asyncAttributesPromise=t?.then(function(i){return n._attributes=Object.assign({},n._attributes,i),n.asyncAttributesPending=!1,i},function(i){return F.debug("a resource's async attributes promise rejected: %s",i),n.asyncAttributesPending=!1,{}})}return r.empty=function(){return r.EMPTY},r.default=function(){var e;return new r((e={},e[OE]=ll(),e[Ji]=Pn[Ji],e[Xi]=Pn[Xi],e[Qi]=Pn[Qi],e))},Object.defineProperty(r.prototype,"attributes",{get:function(){var e;return this.asyncAttributesPending&&F.error("Accessing resource attributes before async attributes settled"),(e=this._attributes)!==null&&e!==void 0?e:{}},enumerable:!1,configurable:!0}),r.prototype.waitForAsyncAttributes=function(){return pO(this,void 0,void 0,function(){return mO(this,function(e){switch(e.label){case 0:return this.asyncAttributesPending?[4,this._asyncAttributesPromise]:[3,2];case 1:e.sent(),e.label=2;case 2:return[2]}})})},r.prototype.merge=function(e){var t=this,n;if(!e)return this;var o=Zr(Zr({},this._syncAttributes),(n=e._syncAttributes)!==null&&n!==void 0?n:e.attributes);if(!this._asyncAttributesPromise&&!e._asyncAttributesPromise)return new r(o);var i=Promise.all([this._asyncAttributesPromise,e._asyncAttributesPromise]).then(function(a){var l,c=gO(a,2),s=c[0],u=c[1];return Zr(Zr(Zr(Zr({},t._syncAttributes),s),(l=e._syncAttributes)!==null&&l!==void 0?l:e.attributes),u)});return new r(o,i)},r.EMPTY=new r({}),r}();var XE=function(){function r(){this._registeredViews=[]}return r.prototype.addView=function(e){this._registeredViews.push(e)},r.prototype.findViews=function(e,t){var n=this,o=this._registeredViews.filter(function(i){return n._matchInstrument(i.instrumentSelector,e)&&n._matchMeter(i.meterSelector,t)});return o},r.prototype._matchInstrument=function(e,t){return(e.getType()===void 0||t.type===e.getType())&&e.getNameFilter().match(t.name)&&e.getUnitFilter().match(t.unit)},r.prototype._matchMeter=function(e,t){return e.getNameFilter().match(t.name)&&(t.version===void 0||e.getVersionFilter().match(t.version))&&(t.schemaUrl===void 0||e.getSchemaUrlFilter().match(t.schemaUrl))},r}();he();var Nn=function(){var r=function(e,t){return r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,o){n.__proto__=o}||function(n,o){for(var i in o)Object.prototype.hasOwnProperty.call(o,i)&&(n[i]=o[i])},r(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");r(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}}(),ul=function(){function r(e,t){this._writableMetricStorage=e,this._descriptor=t}return r.prototype._record=function(e,t,n){if(t===void 0&&(t={}),n===void 0&&(n=To.active()),typeof e!="number"){F.warn("non-number value provided to metric "+this._descriptor.name+": "+e);return}this._descriptor.valueType===_t.INT&&!Number.isInteger(e)&&(F.warn("INT value type cannot accept a floating-point value for "+this._descriptor.name+", ignoring the fractional digits."),e=Math.trunc(e),!Number.isInteger(e))||this._writableMetricStorage.record(e,t,n,On(Date.now()))},r}();var JE=function(r){Nn(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.add=function(t,n,o){this._record(t,n,o)},e}(ul);var QE=function(r){Nn(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.add=function(t,n,o){if(t<0){F.warn("negative value provided to counter "+this._descriptor.name+": "+t);return}this._record(t,n,o)},e}(ul);var ZE=function(r){Nn(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.record=function(t,n,o){this._record(t,n,o)},e}(ul);var eb=function(r){Nn(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.record=function(t,n,o){if(t<0){F.warn("negative value provided to histogram "+this._descriptor.name+": "+t);return}this._record(t,n,o)},e}(ul);var dl=function(){function r(e,t,n){this._observableRegistry=n,this._descriptor=e,this._metricStorages=t}return r.prototype.addCallback=function(e){this._observableRegistry.addCallback(e,this)},r.prototype.removeCallback=function(e){this._observableRegistry.removeCallback(e,this)},r}();var tb=function(r){Nn(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(dl);var rb=function(r){Nn(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(dl);var nb=function(r){Nn(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(dl);function ta(r){return r instanceof dl}var ob=function(){function r(e){this._meterSharedState=e}return r.prototype.createGauge=function(e,t){var n=gr(e,oe.GAUGE,t),o=this._meterSharedState.registerMetricStorage(n);return new ZE(o,n)},r.prototype.createHistogram=function(e,t){var n=gr(e,oe.HISTOGRAM,t),o=this._meterSharedState.registerMetricStorage(n);return new eb(o,n)},r.prototype.createCounter=function(e,t){var n=gr(e,oe.COUNTER,t),o=this._meterSharedState.registerMetricStorage(n);return new QE(o,n)},r.prototype.createUpDownCounter=function(e,t){var n=gr(e,oe.UP_DOWN_COUNTER,t),o=this._meterSharedState.registerMetricStorage(n);return new JE(o,n)},r.prototype.createObservableGauge=function(e,t){var n=gr(e,oe.OBSERVABLE_GAUGE,t),o=this._meterSharedState.registerAsyncMetricStorage(n);return new rb(n,o,this._meterSharedState.observableRegistry)},r.prototype.createObservableCounter=function(e,t){var n=gr(e,oe.OBSERVABLE_COUNTER,t),o=this._meterSharedState.registerAsyncMetricStorage(n);return new tb(n,o,this._meterSharedState.observableRegistry)},r.prototype.createObservableUpDownCounter=function(e,t){var n=gr(e,oe.OBSERVABLE_UP_DOWN_COUNTER,t),o=this._meterSharedState.registerAsyncMetricStorage(n);return new nb(n,o,this._meterSharedState.observableRegistry)},r.prototype.addBatchObservableCallback=function(e,t){this._meterSharedState.observableRegistry.addBatchCallback(e,t)},r.prototype.removeBatchObservableCallback=function(e,t){this._meterSharedState.observableRegistry.removeBatchCallback(e,t)},r}();var pl=function(){function r(e){this._instrumentDescriptor=e}return r.prototype.getInstrumentDescriptor=function(){return this._instrumentDescriptor},r.prototype.updateDescription=function(e){this._instrumentDescriptor=gr(this._instrumentDescriptor.name,this._instrumentDescriptor.type,{description:e,valueType:this._instrumentDescriptor.valueType,unit:this._instrumentDescriptor.unit,advice:this._instrumentDescriptor.advice})},r}();var hO=function(){var r=function(e,t){return r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,o){n.__proto__=o}||function(n,o){for(var i in o)Object.prototype.hasOwnProperty.call(o,i)&&(n[i]=o[i])},r(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");r(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}}(),ib=function(r,e){var t={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},n,o,i,a;return a={next:l(0),throw:l(1),return:l(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function l(s){return function(u){return c([s,u])}}function c(s){if(n)throw new TypeError("Generator is already executing.");for(;t;)try{if(n=1,o&&(i=s[0]&2?o.return:s[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,s[1])).done)return i;switch(o=0,i&&(s=[s[0]&2,i.value]),s[0]){case 0:case 1:i=s;break;case 4:return t.label++,{value:s[1],done:!1};case 5:t.label++,o=s[1],s=[0];continue;case 7:s=t.ops.pop(),t.trys.pop();continue;default:if(i=t.trys,!(i=i.length>0&&i[i.length-1])&&(s[0]===6||s[0]===2)){t=0;continue}if(s[0]===3&&(!i||s[1]>i[0]&&s[1]<i[3])){t.label=s[1];break}if(s[0]===6&&t.label<i[1]){t.label=i[1],i=s;break}if(i&&t.label<i[2]){t.label=i[2],t.ops.push(s);break}i[2]&&t.ops.pop(),t.trys.pop();continue}s=e.call(r,t)}catch(u){s=[6,u],o=0}finally{n=i=0}if(s[0]&5)throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}},fO=function(){function r(e){this._hash=e,this._valueMap=new Map,this._keyMap=new Map}return r.prototype.get=function(e,t){return t??(t=this._hash(e)),this._valueMap.get(t)},r.prototype.getOrDefault=function(e,t){var n=this._hash(e);if(this._valueMap.has(n))return this._valueMap.get(n);var o=t();return this._keyMap.has(n)||this._keyMap.set(n,e),this._valueMap.set(n,o),o},r.prototype.set=function(e,t,n){n??(n=this._hash(e)),this._keyMap.has(n)||this._keyMap.set(n,e),this._valueMap.set(n,t)},r.prototype.has=function(e,t){return t??(t=this._hash(e)),this._valueMap.has(t)},r.prototype.keys=function(){var e,t;return ib(this,function(n){switch(n.label){case 0:e=this._keyMap.entries(),t=e.next(),n.label=1;case 1:return t.done===!0?[3,3]:[4,[t.value[1],t.value[0]]];case 2:return n.sent(),t=e.next(),[3,1];case 3:return[2]}})},r.prototype.entries=function(){var e,t;return ib(this,function(n){switch(n.label){case 0:e=this._valueMap.entries(),t=e.next(),n.label=1;case 1:return t.done===!0?[3,3]:[4,[this._keyMap.get(t.value[0]),t.value[1],t.value[0]]];case 2:return n.sent(),t=e.next(),[3,1];case 3:return[2]}})},Object.defineProperty(r.prototype,"size",{get:function(){return this._valueMap.size},enumerable:!1,configurable:!0}),r}();var Jt=function(r){hO(e,r);function e(){return r.call(this,Ks)||this}return e}(fO);var SO=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},ml=function(){function r(e,t){this._aggregator=e,this._activeCollectionStorage=new Jt,this._cumulativeMemoStorage=new Jt,this._overflowAttributes={"otel.metric.overflow":!0},this._cardinalityLimit=(t??2e3)-1,this._overflowHashCode=Ks(this._overflowAttributes)}return r.prototype.record=function(e,t,n,o){var i=this,a=this._activeCollectionStorage.get(t);if(!a){if(this._activeCollectionStorage.size>=this._cardinalityLimit){var l=this._activeCollectionStorage.getOrDefault(this._overflowAttributes,function(){return i._aggregator.createAccumulation(o)});l?.record(e);return}a=this._aggregator.createAccumulation(o),this._activeCollectionStorage.set(t,a)}a?.record(e)},r.prototype.batchCumulate=function(e,t){var n=this;Array.from(e.entries()).forEach(function(o){var i=SO(o,3),a=i[0],l=i[1],c=i[2],s=n._aggregator.createAccumulation(t);s?.record(l);var u=s;if(n._cumulativeMemoStorage.has(a,c)){var d=n._cumulativeMemoStorage.get(a,c);u=n._aggregator.diff(d,s)}else if(n._cumulativeMemoStorage.size>=n._cardinalityLimit&&(a=n._overflowAttributes,c=n._overflowHashCode,n._cumulativeMemoStorage.has(a,c))){var d=n._cumulativeMemoStorage.get(a,c);u=n._aggregator.diff(d,s)}if(n._activeCollectionStorage.has(a,c)){var p=n._activeCollectionStorage.get(a,c);u=n._aggregator.merge(p,u)}n._cumulativeMemoStorage.set(a,s,c),n._activeCollectionStorage.set(a,u,c)})},r.prototype.collect=function(){var e=this._activeCollectionStorage;return this._activeCollectionStorage=new Jt,e},r}();var Id=function(r){var e=typeof Symbol=="function"&&Symbol.iterator,t=e&&r[e],n=0;if(t)return t.call(r);if(r&&typeof r.length=="number")return{next:function(){return r&&n>=r.length&&(r=void 0),{value:r&&r[n++],done:!r}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")},ab=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},gl=function(){function r(e,t){var n=this;this._aggregator=e,this._unreportedAccumulations=new Map,this._reportHistory=new Map,t.forEach(function(o){n._unreportedAccumulations.set(o,[])})}return r.prototype.buildMetrics=function(e,t,n,o){this._stashAccumulations(n);var i=this._getMergedUnreportedAccumulations(e),a=i,l;if(this._reportHistory.has(e)){var c=this._reportHistory.get(e),s=c.collectionTime;l=c.aggregationTemporality,l===xo.CUMULATIVE?a=r.merge(c.accumulations,i,this._aggregator):a=r.calibrateStartTime(c.accumulations,i,s)}else l=e.selectAggregationTemporality(t.type);this._reportHistory.set(e,{accumulations:a,collectionTime:o,aggregationTemporality:l});var u=yO(a);if(u.length!==0)return this._aggregator.toMetricData(t,l,u,o)},r.prototype._stashAccumulations=function(e){var t,n,o=this._unreportedAccumulations.keys();try{for(var i=Id(o),a=i.next();!a.done;a=i.next()){var l=a.value,c=this._unreportedAccumulations.get(l);c===void 0&&(c=[],this._unreportedAccumulations.set(l,c)),c.push(e)}}catch(s){t={error:s}}finally{try{a&&!a.done&&(n=i.return)&&n.call(i)}finally{if(t)throw t.error}}},r.prototype._getMergedUnreportedAccumulations=function(e){var t,n,o=new Jt,i=this._unreportedAccumulations.get(e);if(this._unreportedAccumulations.set(e,[]),i===void 0)return o;try{for(var a=Id(i),l=a.next();!l.done;l=a.next()){var c=l.value;o=r.merge(o,c,this._aggregator)}}catch(s){t={error:s}}finally{try{l&&!l.done&&(n=a.return)&&n.call(a)}finally{if(t)throw t.error}}return o},r.merge=function(e,t,n){for(var o=e,i=t.entries(),a=i.next();a.done!==!0;){var l=ab(a.value,3),c=l[0],s=l[1],u=l[2];if(e.has(c,u)){var d=e.get(c,u),p=n.merge(d,s);o.set(c,p,u)}else o.set(c,s,u);a=i.next()}return o},r.calibrateStartTime=function(e,t,n){var o,i;try{for(var a=Id(e.keys()),l=a.next();!l.done;l=a.next()){var c=ab(l.value,2),s=c[0],u=c[1],d=t.get(s,u);d?.setStartTime(n)}}catch(p){o={error:p}}finally{try{l&&!l.done&&(i=a.return)&&i.call(a)}finally{if(o)throw o.error}}return t},r}();function yO(r){return Array.from(r.entries())}var EO=function(){var r=function(e,t){return r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,o){n.__proto__=o}||function(n,o){for(var i in o)Object.prototype.hasOwnProperty.call(o,i)&&(n[i]=o[i])},r(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");r(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}}(),bO=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},sb=function(r){EO(e,r);function e(t,n,o,i,a){var l=r.call(this,t)||this;return l._attributesProcessor=o,l._aggregationCardinalityLimit=a,l._deltaMetricStorage=new ml(n,l._aggregationCardinalityLimit),l._temporalMetricStorage=new gl(n,i),l}return e.prototype.record=function(t,n){var o=this,i=new Jt;Array.from(t.entries()).forEach(function(a){var l=bO(a,2),c=l[0],s=l[1];i.set(o._attributesProcessor.process(c),s)}),this._deltaMetricStorage.batchCumulate(i,n)},e.prototype.collect=function(t,n){var o=this._deltaMetricStorage.collect();return this._temporalMetricStorage.buildMetrics(t,this._instrumentDescriptor,o,n)},e}(pl);he();function Pd(r,e){var t="";return r.unit!==e.unit&&(t+=" - Unit '"+r.unit+"' does not match '"+e.unit+`'
13
14
  `),r.type!==e.type&&(t+=" - Type '"+r.type+"' does not match '"+e.type+`'
14
15
  `),r.valueType!==e.valueType&&(t+=" - Value Type '"+r.valueType+"' does not match '"+e.valueType+`'
15
16
  `),r.description!==e.description&&(t+=" - Description '"+r.description+"' does not match '"+e.description+`'
16
- `),t}function oP(r,e){return" - use valueType '"+r.valueType+"' on instrument creation or use an instrument name other than '"+e.name+"'"}function iP(r,e){return" - use unit '"+r.unit+"' on instrument creation or use an instrument name other than '"+e.name+"'"}function aP(r,e){var t={name:e.name,type:e.type,unit:e.unit},n=JSON.stringify(t);return" - create a new view with a name other than '"+r.name+"' and InstrumentSelector '"+n+"'"}function sP(r,e){var t={name:e.name,type:e.type,unit:e.unit},n=JSON.stringify(t);return" - create a new view with a name other than '"+r.name+"' and InstrumentSelector '"+n+`'
17
+ `),t}function TO(r,e){return" - use valueType '"+r.valueType+"' on instrument creation or use an instrument name other than '"+e.name+"'"}function vO(r,e){return" - use unit '"+r.unit+"' on instrument creation or use an instrument name other than '"+e.name+"'"}function AO(r,e){var t={name:e.name,type:e.type,unit:e.unit},n=JSON.stringify(t);return" - create a new view with a name other than '"+r.name+"' and InstrumentSelector '"+n+"'"}function RO(r,e){var t={name:e.name,type:e.type,unit:e.unit},n=JSON.stringify(t);return" - create a new view with a name other than '"+r.name+"' and InstrumentSelector '"+n+`'
17
18
  - OR - create a new view with the name `+r.name+" and description '"+r.description+"' and InstrumentSelector "+n+`
18
- - OR - create a new view with the name `+e.name+" and description '"+r.description+"' and InstrumentSelector "+n}function nd(r,e){return r.valueType!==e.valueType?oP(r,e):r.unit!==e.unit?iP(r,e):r.type!==e.type?aP(r,e):r.description!==e.description?sP(r,e):""}var od=function(r){var e=typeof Symbol=="function"&&Symbol.iterator,t=e&&r[e],n=0;if(t)return t.call(r);if(r&&typeof r.length=="number")return{next:function(){return r&&n>=r.length&&(r=void 0),{value:r&&r[n++],done:!r}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")},KE=function(){function r(){this._sharedRegistry=new Map,this._perCollectorRegistry=new Map}return r.create=function(){return new r},r.prototype.getStorages=function(e){var t,n,o,i,a=[];try{for(var l=od(this._sharedRegistry.values()),c=l.next();!c.done;c=l.next()){var s=c.value;a=a.concat(s)}}catch(p){t={error:p}}finally{try{c&&!c.done&&(n=l.return)&&n.call(l)}finally{if(t)throw t.error}}var u=this._perCollectorRegistry.get(e);if(u!=null)try{for(var d=od(u.values()),m=d.next();!m.done;m=d.next()){var s=m.value;a=a.concat(s)}}catch(p){o={error:p}}finally{try{m&&!m.done&&(i=d.return)&&i.call(d)}finally{if(o)throw o.error}}return a},r.prototype.register=function(e){this._registerStorage(e,this._sharedRegistry)},r.prototype.registerForCollector=function(e,t){var n=this._perCollectorRegistry.get(e);n==null&&(n=new Map,this._perCollectorRegistry.set(e,n)),this._registerStorage(t,n)},r.prototype.findOrUpdateCompatibleStorage=function(e){var t=this._sharedRegistry.get(e.name);return t===void 0?null:this._findOrUpdateCompatibleStorage(e,t)},r.prototype.findOrUpdateCompatibleCollectorStorage=function(e,t){var n=this._perCollectorRegistry.get(e);if(n===void 0)return null;var o=n.get(t.name);return o===void 0?null:this._findOrUpdateCompatibleStorage(t,o)},r.prototype._registerStorage=function(e,t){var n=e.getInstrumentDescriptor(),o=t.get(n.name);if(o===void 0){t.set(n.name,[e]);return}o.push(e)},r.prototype._findOrUpdateCompatibleStorage=function(e,t){var n,o,i=null;try{for(var a=od(t),l=a.next();!l.done;l=a.next()){var c=l.value,s=c.getInstrumentDescriptor();oE(s,e)?(s.description!==e.description&&(e.description.length>s.description.length&&c.updateDescription(e.description),F.warn("A view or instrument with the name ",e.name,` has already been registered, but has a different description and is incompatible with another registered view.
19
+ - OR - create a new view with the name `+e.name+" and description '"+r.description+"' and InstrumentSelector "+n}function Od(r,e){return r.valueType!==e.valueType?TO(r,e):r.unit!==e.unit?vO(r,e):r.type!==e.type?AO(r,e):r.description!==e.description?RO(r,e):""}var Ld=function(r){var e=typeof Symbol=="function"&&Symbol.iterator,t=e&&r[e],n=0;if(t)return t.call(r);if(r&&typeof r.length=="number")return{next:function(){return r&&n>=r.length&&(r=void 0),{value:r&&r[n++],done:!r}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")},lb=function(){function r(){this._sharedRegistry=new Map,this._perCollectorRegistry=new Map}return r.create=function(){return new r},r.prototype.getStorages=function(e){var t,n,o,i,a=[];try{for(var l=Ld(this._sharedRegistry.values()),c=l.next();!c.done;c=l.next()){var s=c.value;a=a.concat(s)}}catch(m){t={error:m}}finally{try{c&&!c.done&&(n=l.return)&&n.call(l)}finally{if(t)throw t.error}}var u=this._perCollectorRegistry.get(e);if(u!=null)try{for(var d=Ld(u.values()),p=d.next();!p.done;p=d.next()){var s=p.value;a=a.concat(s)}}catch(m){o={error:m}}finally{try{p&&!p.done&&(i=d.return)&&i.call(d)}finally{if(o)throw o.error}}return a},r.prototype.register=function(e){this._registerStorage(e,this._sharedRegistry)},r.prototype.registerForCollector=function(e,t){var n=this._perCollectorRegistry.get(e);n==null&&(n=new Map,this._perCollectorRegistry.set(e,n)),this._registerStorage(t,n)},r.prototype.findOrUpdateCompatibleStorage=function(e){var t=this._sharedRegistry.get(e.name);return t===void 0?null:this._findOrUpdateCompatibleStorage(e,t)},r.prototype.findOrUpdateCompatibleCollectorStorage=function(e,t){var n=this._perCollectorRegistry.get(e);if(n===void 0)return null;var o=n.get(t.name);return o===void 0?null:this._findOrUpdateCompatibleStorage(t,o)},r.prototype._registerStorage=function(e,t){var n=e.getInstrumentDescriptor(),o=t.get(n.name);if(o===void 0){t.set(n.name,[e]);return}o.push(e)},r.prototype._findOrUpdateCompatibleStorage=function(e,t){var n,o,i=null;try{for(var a=Ld(t),l=a.next();!l.done;l=a.next()){var c=l.value,s=c.getInstrumentDescriptor();yE(s,e)?(s.description!==e.description&&(e.description.length>s.description.length&&c.updateDescription(e.description),F.warn("A view or instrument with the name ",e.name,` has already been registered, but has a different description and is incompatible with another registered view.
19
20
  `,`Details:
20
- `,rd(s,e),`The longer description will be used.
21
- To resolve the conflict:`,nd(s,e))),i=c):F.warn("A view or instrument with the name ",e.name,` has already been registered and is incompatible with another registered view.
21
+ `,Pd(s,e),`The longer description will be used.
22
+ To resolve the conflict:`,Od(s,e))),i=c):F.warn("A view or instrument with the name ",e.name,` has already been registered and is incompatible with another registered view.
22
23
  `,`Details:
23
- `,rd(s,e),`To resolve the conflict:
24
- `,nd(s,e))}}catch(u){n={error:u}}finally{try{l&&!l.done&&(o=a.return)&&o.call(a)}finally{if(n)throw n.error}}return i},r}();var YE=function(){function r(e){this._backingStorages=e}return r.prototype.record=function(e,t,n,o){this._backingStorages.forEach(function(i){i.record(e,t,n,o)})},r}();he();he();var XE=function(){function r(e,t){this._instrumentName=e,this._valueType=t,this._buffer=new $t}return r.prototype.observe=function(e,t){if(t===void 0&&(t={}),typeof e!="number"){F.warn("non-number value provided to metric "+this._instrumentName+": "+e);return}this._valueType===Ct.INT&&!Number.isInteger(e)&&(F.warn("INT value type cannot accept a floating-point value for "+this._instrumentName+", ignoring the fractional digits."),e=Math.trunc(e),!Number.isInteger(e))||this._buffer.set(t,e)},r}();var JE=function(){function r(){this._buffer=new Map}return r.prototype.observe=function(e,t,n){if(n===void 0&&(n={}),!!Hi(e)){var o=this._buffer.get(e);if(o==null&&(o=new $t,this._buffer.set(e,o)),typeof t!="number"){F.warn("non-number value provided to metric "+e._descriptor.name+": "+t);return}e._descriptor.valueType===Ct.INT&&!Number.isInteger(t)&&(F.warn("INT value type cannot accept a floating-point value for "+e._descriptor.name+", ignoring the fractional digits."),t=Math.trunc(t),!Number.isInteger(t))||o.set(n,t)}},r}();var id=function(r,e,t,n){function o(i){return i instanceof t?i:new t(function(a){a(i)})}return new(t||(t=Promise))(function(i,a){function l(u){try{s(n.next(u))}catch(d){a(d)}}function c(u){try{s(n.throw(u))}catch(d){a(d)}}function s(u){u.done?i(u.value):o(u.value).then(l,c)}s((n=n.apply(r,e||[])).next())})},ad=function(r,e){var t={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},n,o,i,a;return a={next:l(0),throw:l(1),return:l(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function l(s){return function(u){return c([s,u])}}function c(s){if(n)throw new TypeError("Generator is already executing.");for(;t;)try{if(n=1,o&&(i=s[0]&2?o.return:s[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,s[1])).done)return i;switch(o=0,i&&(s=[s[0]&2,i.value]),s[0]){case 0:case 1:i=s;break;case 4:return t.label++,{value:s[1],done:!1};case 5:t.label++,o=s[1],s=[0];continue;case 7:s=t.ops.pop(),t.trys.pop();continue;default:if(i=t.trys,!(i=i.length>0&&i[i.length-1])&&(s[0]===6||s[0]===2)){t=0;continue}if(s[0]===3&&(!i||s[1]>i[0]&&s[1]<i[3])){t.label=s[1];break}if(s[0]===6&&t.label<i[1]){t.label=i[1],i=s;break}if(i&&t.label<i[2]){t.label=i[2],t.ops.push(s);break}i[2]&&t.ops.pop(),t.trys.pop();continue}s=e.call(r,t)}catch(u){s=[6,u],o=0}finally{n=i=0}if(s[0]&5)throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}},QE=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},ZE=function(r,e,t){if(t||arguments.length===2)for(var n=0,o=e.length,i;n<o;n++)(i||!(n in e))&&(i||(i=Array.prototype.slice.call(e,0,n)),i[n]=e[n]);return r.concat(i||Array.prototype.slice.call(e))},ey=function(){function r(){this._callbacks=[],this._batchCallbacks=[]}return r.prototype.addCallback=function(e,t){var n=this._findCallback(e,t);n>=0||this._callbacks.push({callback:e,instrument:t})},r.prototype.removeCallback=function(e,t){var n=this._findCallback(e,t);n<0||this._callbacks.splice(n,1)},r.prototype.addBatchCallback=function(e,t){var n=new Set(t.filter(Hi));if(n.size===0){F.error("BatchObservableCallback is not associated with valid instruments",t);return}var o=this._findBatchCallback(e,n);o>=0||this._batchCallbacks.push({callback:e,instruments:n})},r.prototype.removeBatchCallback=function(e,t){var n=new Set(t.filter(Hi)),o=this._findBatchCallback(e,n);o<0||this._batchCallbacks.splice(o,1)},r.prototype.observe=function(e,t){return id(this,void 0,void 0,function(){var n,o,i,a;return ad(this,function(l){switch(l.label){case 0:return n=this._observeCallbacks(e,t),o=this._observeBatchCallbacks(e,t),[4,QS(ZE(ZE([],QE(n),!1),QE(o),!1))];case 1:return i=l.sent(),a=i.filter(ZS).map(function(c){return c.reason}),[2,a]}})})},r.prototype._observeCallbacks=function(e,t){var n=this;return this._callbacks.map(function(o){var i=o.callback,a=o.instrument;return id(n,void 0,void 0,function(){var l,c;return ad(this,function(s){switch(s.label){case 0:return l=new XE(a._descriptor.name,a._descriptor.valueType),c=Promise.resolve(i(l)),t!=null&&(c=Vr(c,t)),[4,c];case 1:return s.sent(),a._metricStorages.forEach(function(u){u.record(l._buffer,e)}),[2]}})})})},r.prototype._observeBatchCallbacks=function(e,t){var n=this;return this._batchCallbacks.map(function(o){var i=o.callback,a=o.instruments;return id(n,void 0,void 0,function(){var l,c;return ad(this,function(s){switch(s.label){case 0:return l=new JE,c=Promise.resolve(i(l)),t!=null&&(c=Vr(c,t)),[4,c];case 1:return s.sent(),a.forEach(function(u){var d=l._buffer.get(u);d!=null&&u._metricStorages.forEach(function(m){m.record(d,e)})}),[2]}})})})},r.prototype._findCallback=function(e,t){return this._callbacks.findIndex(function(n){return n.callback===e&&n.instrument===t})},r.prototype._findBatchCallback=function(e,t){return this._batchCallbacks.findIndex(function(n){return n.callback===e&&eE(n.instruments,t)})},r}();var lP=function(){var r=function(e,t){return r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,o){n.__proto__=o}||function(n,o){for(var i in o)Object.prototype.hasOwnProperty.call(o,i)&&(n[i]=o[i])},r(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");r(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}}(),ty=function(r){lP(e,r);function e(t,n,o,i,a){var l=r.call(this,t)||this;return l._attributesProcessor=o,l._aggregationCardinalityLimit=a,l._deltaMetricStorage=new Bs(n,l._aggregationCardinalityLimit),l._temporalMetricStorage=new zs(n,i),l}return e.prototype.record=function(t,n,o,i){n=this._attributesProcessor.process(n,o),this._deltaMetricStorage.record(t,n,o,i)},e.prototype.collect=function(t,n){var o=this._deltaMetricStorage.collect();return this._temporalMetricStorage.buildMetrics(t,this._instrumentDescriptor,o,n)},e}(Fs);var ry=function(){var r=function(e,t){return r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,o){n.__proto__=o}||function(n,o){for(var i in o)Object.prototype.hasOwnProperty.call(o,i)&&(n[i]=o[i])},r(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");r(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}}(),Eo=function(){function r(){}return r.Noop=function(){return uP},r}();var cP=function(r){ry(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.process=function(t,n){return t},e}(Eo);var ny=function(r){ry(e,r);function e(t){var n=r.call(this)||this;return n._allowedAttributeNames=t,n}return e.prototype.process=function(t,n){var o=this,i={};return Object.keys(t).filter(function(a){return o._allowedAttributeNames.includes(a)}).forEach(function(a){return i[a]=t[a]}),i},e}(Eo);var uP=new cP;var dP=function(r,e,t,n){function o(i){return i instanceof t?i:new t(function(a){a(i)})}return new(t||(t=Promise))(function(i,a){function l(u){try{s(n.next(u))}catch(d){a(d)}}function c(u){try{s(n.throw(u))}catch(d){a(d)}}function s(u){u.done?i(u.value):o(u.value).then(l,c)}s((n=n.apply(r,e||[])).next())})},mP=function(r,e){var t={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},n,o,i,a;return a={next:l(0),throw:l(1),return:l(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function l(s){return function(u){return c([s,u])}}function c(s){if(n)throw new TypeError("Generator is already executing.");for(;t;)try{if(n=1,o&&(i=s[0]&2?o.return:s[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,s[1])).done)return i;switch(o=0,i&&(s=[s[0]&2,i.value]),s[0]){case 0:case 1:i=s;break;case 4:return t.label++,{value:s[1],done:!1};case 5:t.label++,o=s[1],s=[0];continue;case 7:s=t.ops.pop(),t.trys.pop();continue;default:if(i=t.trys,!(i=i.length>0&&i[i.length-1])&&(s[0]===6||s[0]===2)){t=0;continue}if(s[0]===3&&(!i||s[1]>i[0]&&s[1]<i[3])){t.label=s[1];break}if(s[0]===6&&t.label<i[1]){t.label=i[1],i=s;break}if(i&&t.label<i[2]){t.label=i[2],t.ops.push(s);break}i[2]&&t.ops.pop(),t.trys.pop();continue}s=e.call(r,t)}catch(u){s=[6,u],o=0}finally{n=i=0}if(s[0]&5)throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}},pP=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},oy=function(){function r(e,t){this._meterProviderSharedState=e,this._instrumentationScope=t,this.metricStorageRegistry=new KE,this.observableRegistry=new ey,this.meter=new jE(this)}return r.prototype.registerMetricStorage=function(e){var t=this._registerMetricStorage(e,ty);return t.length===1?t[0]:new YE(t)},r.prototype.registerAsyncMetricStorage=function(e){var t=this._registerMetricStorage(e,qE);return t},r.prototype.collect=function(e,t,n){return dP(this,void 0,void 0,function(){var o,i,a;return mP(this,function(l){switch(l.label){case 0:return[4,this.observableRegistry.observe(t,n?.timeoutMillis)];case 1:return o=l.sent(),i=this.metricStorageRegistry.getStorages(e),i.length===0?[2,null]:(a=i.map(function(c){return c.collect(e,t)}).filter(XS),a.length===0?[2,{errors:o}]:[2,{scopeMetrics:{scope:this._instrumentationScope,metrics:a},errors:o}])}})})},r.prototype._registerMetricStorage=function(e,t){var n=this,o=this._meterProviderSharedState.viewRegistry.findViews(e,this._instrumentationScope),i=o.map(function(c){var s=nE(c,e),u=n.metricStorageRegistry.findOrUpdateCompatibleStorage(s);if(u!=null)return u;var d=c.aggregation.createAggregator(s),m=new t(s,d,c.attributesProcessor,n._meterProviderSharedState.metricCollectors,c.aggregationCardinalityLimit);return n.metricStorageRegistry.register(m),m});if(i.length===0){var a=this._meterProviderSharedState.selectAggregations(e.type),l=a.map(function(c){var s=pP(c,2),u=s[0],d=s[1],m=n.metricStorageRegistry.findOrUpdateCompatibleCollectorStorage(u,e);if(m!=null)return m;var p=d.createAggregator(e),g=u.selectCardinalityLimit(e.type),h=new t(e,p,Eo.Noop(),[u],g);return n.metricStorageRegistry.registerForCollector(u,h),h});i=i.concat(l)}return i},r}();var gP=function(r){var e=typeof Symbol=="function"&&Symbol.iterator,t=e&&r[e],n=0;if(t)return t.call(r);if(r&&typeof r.length=="number")return{next:function(){return r&&n>=r.length&&(r=void 0),{value:r&&r[n++],done:!r}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")},iy=function(){function r(e){this.resource=e,this.viewRegistry=new kE,this.metricCollectors=[],this.meterSharedStates=new Map}return r.prototype.getMeterSharedState=function(e){var t=JS(e),n=this.meterSharedStates.get(t);return n==null&&(n=new oy(this,e),this.meterSharedStates.set(t,n)),n},r.prototype.selectAggregations=function(e){var t,n,o=[];try{for(var i=gP(this.metricCollectors),a=i.next();!a.done;a=i.next()){var l=a.value;o.push([l,l.selectAggregation(e)])}}catch(c){t={error:c}}finally{try{a&&!a.done&&(n=i.return)&&n.call(i)}finally{if(t)throw t.error}}return o},r}();var Gs=function(r,e,t,n){function o(i){return i instanceof t?i:new t(function(a){a(i)})}return new(t||(t=Promise))(function(i,a){function l(u){try{s(n.next(u))}catch(d){a(d)}}function c(u){try{s(n.throw(u))}catch(d){a(d)}}function s(u){u.done?i(u.value):o(u.value).then(l,c)}s((n=n.apply(r,e||[])).next())})},Hs=function(r,e){var t={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},n,o,i,a;return a={next:l(0),throw:l(1),return:l(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function l(s){return function(u){return c([s,u])}}function c(s){if(n)throw new TypeError("Generator is already executing.");for(;t;)try{if(n=1,o&&(i=s[0]&2?o.return:s[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,s[1])).done)return i;switch(o=0,i&&(s=[s[0]&2,i.value]),s[0]){case 0:case 1:i=s;break;case 4:return t.label++,{value:s[1],done:!1};case 5:t.label++,o=s[1],s=[0];continue;case 7:s=t.ops.pop(),t.trys.pop();continue;default:if(i=t.trys,!(i=i.length>0&&i[i.length-1])&&(s[0]===6||s[0]===2)){t=0;continue}if(s[0]===3&&(!i||s[1]>i[0]&&s[1]<i[3])){t.label=s[1];break}if(s[0]===6&&t.label<i[1]){t.label=i[1],i=s;break}if(i&&t.label<i[2]){t.label=i[2],t.ops.push(s);break}i[2]&&t.ops.pop(),t.trys.pop();continue}s=e.call(r,t)}catch(u){s=[6,u],o=0}finally{n=i=0}if(s[0]&5)throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}},hP=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},fP=function(r,e,t){if(t||arguments.length===2)for(var n=0,o=e.length,i;n<o;n++)(i||!(n in e))&&(i||(i=Array.prototype.slice.call(e,0,n)),i[n]=e[n]);return r.concat(i||Array.prototype.slice.call(e))},ay=function(){function r(e,t){this._sharedState=e,this._metricReader=t}return r.prototype.collect=function(e){return Gs(this,void 0,void 0,function(){var t,n,o,i,a=this;return Hs(this,function(l){switch(l.label){case 0:return t=Sn(Date.now()),n=[],o=[],i=Array.from(this._sharedState.meterSharedStates.values()).map(function(c){return Gs(a,void 0,void 0,function(){var s;return Hs(this,function(u){switch(u.label){case 0:return[4,c.collect(this,t,e)];case 1:return s=u.sent(),s?.scopeMetrics!=null&&n.push(s.scopeMetrics),s?.errors!=null&&o.push.apply(o,fP([],hP(s.errors),!1)),[2]}})})}),[4,Promise.all(i)];case 1:return l.sent(),[2,{resourceMetrics:{resource:this._sharedState.resource,scopeMetrics:n},errors:o}]}})})},r.prototype.forceFlush=function(e){return Gs(this,void 0,void 0,function(){return Hs(this,function(t){switch(t.label){case 0:return[4,this._metricReader.forceFlush(e)];case 1:return t.sent(),[2]}})})},r.prototype.shutdown=function(e){return Gs(this,void 0,void 0,function(){return Hs(this,function(t){switch(t.label){case 0:return[4,this._metricReader.shutdown(e)];case 1:return t.sent(),[2]}})})},r.prototype.selectAggregationTemporality=function(e){return this._metricReader.selectAggregationTemporality(e)},r.prototype.selectAggregation=function(e){return this._metricReader.selectAggregation(e)},r.prototype.selectCardinalityLimit=function(e){var t,n,o;return(o=(n=(t=this._metricReader).selectCardinalityLimit)===null||n===void 0?void 0:n.call(t,e))!==null&&o!==void 0?o:2e3},r}();var sy=function(r,e,t,n){function o(i){return i instanceof t?i:new t(function(a){a(i)})}return new(t||(t=Promise))(function(i,a){function l(u){try{s(n.next(u))}catch(d){a(d)}}function c(u){try{s(n.throw(u))}catch(d){a(d)}}function s(u){u.done?i(u.value):o(u.value).then(l,c)}s((n=n.apply(r,e||[])).next())})},ly=function(r,e){var t={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},n,o,i,a;return a={next:l(0),throw:l(1),return:l(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function l(s){return function(u){return c([s,u])}}function c(s){if(n)throw new TypeError("Generator is already executing.");for(;t;)try{if(n=1,o&&(i=s[0]&2?o.return:s[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,s[1])).done)return i;switch(o=0,i&&(s=[s[0]&2,i.value]),s[0]){case 0:case 1:i=s;break;case 4:return t.label++,{value:s[1],done:!1};case 5:t.label++,o=s[1],s=[0];continue;case 7:s=t.ops.pop(),t.trys.pop();continue;default:if(i=t.trys,!(i=i.length>0&&i[i.length-1])&&(s[0]===6||s[0]===2)){t=0;continue}if(s[0]===3&&(!i||s[1]>i[0]&&s[1]<i[3])){t.label=s[1];break}if(s[0]===6&&t.label<i[1]){t.label=i[1],i=s;break}if(i&&t.label<i[2]){t.label=i[2],t.ops.push(s);break}i[2]&&t.ops.pop(),t.trys.pop();continue}s=e.call(r,t)}catch(u){s=[6,u],o=0}finally{n=i=0}if(s[0]&5)throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}},cy=function(r){var e=typeof Symbol=="function"&&Symbol.iterator,t=e&&r[e],n=0;if(t)return t.call(r);if(r&&typeof r.length=="number")return{next:function(){return r&&n>=r.length&&(r=void 0),{value:r&&r[n++],done:!r}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")};function SP(r,e){var t=e??Ds.empty();return r?Ds.default().merge(t):t}var sd=function(){function r(e){var t,n,o,i,a;if(this._shutdown=!1,this._sharedState=new iy(SP((a=e?.mergeResourceWithDefaults)!==null&&a!==void 0?a:!0,e?.resource)),e?.views!=null&&e.views.length>0)try{for(var l=cy(e.views),c=l.next();!c.done;c=l.next()){var s=c.value;this._sharedState.viewRegistry.addView(s)}}catch(p){t={error:p}}finally{try{c&&!c.done&&(n=l.return)&&n.call(l)}finally{if(t)throw t.error}}if(e?.readers!=null&&e.readers.length>0)try{for(var u=cy(e.readers),d=u.next();!d.done;d=u.next()){var m=d.value;this.addMetricReader(m)}}catch(p){o={error:p}}finally{try{d&&!d.done&&(i=u.return)&&i.call(u)}finally{if(o)throw o.error}}}return r.prototype.getMeter=function(e,t,n){return t===void 0&&(t=""),n===void 0&&(n={}),this._shutdown?(F.warn("A shutdown MeterProvider cannot provide a Meter"),mu()):this._sharedState.getMeterSharedState({name:e,version:t,schemaUrl:n.schemaUrl}).meter},r.prototype.addMetricReader=function(e){var t=new ay(this._sharedState,e);e.setMetricProducer(t),this._sharedState.metricCollectors.push(t)},r.prototype.shutdown=function(e){return sy(this,void 0,void 0,function(){return ly(this,function(t){switch(t.label){case 0:return this._shutdown?(F.warn("shutdown may only be called once per MeterProvider"),[2]):(this._shutdown=!0,[4,Promise.all(this._sharedState.metricCollectors.map(function(n){return n.shutdown(e)}))]);case 1:return t.sent(),[2]}})})},r.prototype.forceFlush=function(e){return sy(this,void 0,void 0,function(){return ly(this,function(t){switch(t.label){case 0:return this._shutdown?(F.warn("invalid attempt to force flush after MeterProvider shutdown"),[2]):[4,Promise.all(this._sharedState.metricCollectors.map(function(n){return n.forceFlush(e)}))];case 1:return t.sent(),[2]}})})},r}();var EP=/[\^$\\.+?()[\]{}|]/g,Vs=function(){function r(e){e==="*"?(this._matchAll=!0,this._regexp=/.*/):(this._matchAll=!1,this._regexp=new RegExp(r.escapePattern(e)))}return r.prototype.match=function(e){return this._matchAll?!0:this._regexp.test(e)},r.escapePattern=function(e){return"^"+e.replace(EP,"\\$&").replace("*",".*")+"$"},r.hasWildcard=function(e){return e.includes("*")},r}();var yo=function(){function r(e){this._matchAll=e===void 0,this._pattern=e}return r.prototype.match=function(e){return!!(this._matchAll||e===this._pattern)},r}();var uy=function(){function r(e){var t;this._nameFilter=new Vs((t=e?.name)!==null&&t!==void 0?t:"*"),this._type=e?.type,this._unitFilter=new yo(e?.unit)}return r.prototype.getType=function(){return this._type},r.prototype.getNameFilter=function(){return this._nameFilter},r.prototype.getUnitFilter=function(){return this._unitFilter},r}();var dy=function(){function r(e){this._nameFilter=new yo(e?.name),this._versionFilter=new yo(e?.version),this._schemaUrlFilter=new yo(e?.schemaUrl)}return r.prototype.getNameFilter=function(){return this._nameFilter},r.prototype.getVersionFilter=function(){return this._versionFilter},r.prototype.getSchemaUrlFilter=function(){return this._schemaUrlFilter},r}();function yP(r){return r.instrumentName==null&&r.instrumentType==null&&r.instrumentUnit==null&&r.meterName==null&&r.meterVersion==null&&r.meterSchemaUrl==null}var ld=function(){function r(e){var t;if(yP(e))throw new Error("Cannot create view with no selector arguments supplied");if(e.name!=null&&(e?.instrumentName==null||Vs.hasWildcard(e.instrumentName)))throw new Error("Views with a specified name must be declared with an instrument selector that selects at most one instrument per meter.");e.attributeKeys!=null?this.attributesProcessor=new ny(e.attributeKeys):this.attributesProcessor=Eo.Noop(),this.name=e.name,this.description=e.description,this.aggregation=(t=e.aggregation)!==null&&t!==void 0?t:Gt.Default(),this.instrumentSelector=new uy({name:e.instrumentName,type:e.instrumentType,unit:e.instrumentUnit}),this.meterSelector=new dy({name:e.meterName,version:e.meterVersion,schemaUrl:e.meterSchemaUrl}),this.aggregationCardinalityLimit=e.aggregationCardinalityLimit}return r}();var TQ=process.env.APP||"unknown";he();import{v4 as TP}from"uuid";function bP(){return new qS({url:"https://us-west.metrics.momentic.ai/v1/metrics",headers:{"x-momentic-metrics-api-key":"c60c6a0f-60da-41a7-a61b-07969a0aa303"},temporalityPreference:hn.DELTA})}var vP=[new ld({instrumentName:"test_operation_duration_ms",instrumentType:ne.HISTOGRAM,aggregation:new Ps([100,500,1e3,5e3,1e4,2e4])})],js=class{globalAttributes;provider;meter;counterCache=new Map;histogramCache=new Map;observableGaugeCache=new Map;gaugeValues=new Map;getCounter(e){let t=this.counterCache.get(e);if(t)return t;let n=this.meter.createCounter(e);return this.counterCache.set(e,n),n}getHistogram(e){let t=this.histogramCache.get(e);if(t)return t;let n=this.meter.createHistogram(e);return this.histogramCache.set(e,n),n}ensureObservableGauge(e){let t=this.observableGaugeCache.get(e);if(t)return t;let n=this.meter.createObservableGauge(e);return n.addCallback(o=>{let i=this.gaugeValues.get(e);i!==void 0&&o.observe(i,this.globalAttributes)}),this.observableGaugeCache.set(e,n),n}constructor(e){this.globalAttributes={...e.globalAttributes??{}};let t=typeof process<"u"?"production":"unknown",n=new Iu({[ls]:e.serviceName,[Vf]:t,[Wf]:typeof process<"u"&&process.env.SERVICE_INSTANCE_ID?process.env.SERVICE_INSTANCE_ID:TP()}),o=bP(),i=new ed({exporter:o,exportIntervalMillis:e.exportIntervalMs??15e3});this.provider=new sd({resource:n,readers:[i],views:vP}),os.setGlobalMeterProvider(this.provider),this.meter=os.getMeter("momentic-serverless")}increment(e,t,n){try{let o=ts(n,this.globalAttributes);this.getCounter(e).add(typeof t=="number"?t:1,o)}catch{}}gauge(e,t){try{this.ensureObservableGauge(e),this.gaugeValues.set(e,t)}catch{}}distribution(e,t,n){try{let o=ts(n,this.globalAttributes);this.getHistogram(e).record(t,o)}catch{}}async flush(){try{await this.provider.forceFlush()}catch{}}async recordDuration({fn:e,name:t,tags:n}){let o=Date.now();try{return await Promise.resolve(e())}finally{this.distribution(t,Date.now()-o,n)}}};var xt=new es;function my(r){r.disabled||(xt=new js(r))}import{tmpdir as SN}from"os";import Qd from"path";import{diff as A9}from"deep-object-diff";import{cloneDeep as a9}from"lodash-es";import{v4 as E9}from"uuid";function gy({steps:r,topLevel:e=!0,...t}){let{stepCacheEntries:n,logger:o,keyPrefix:i}=t,a=[],l=[],c=[],s=0,u=(m,p)=>{try{let g=Pr.parse(p.value);if(g.type!==m.type){o.warn({parsedCacheEntry:g,command:m},"Not using step cache due to type mismatch"),l.push(p.key);return}m.cache=g.cache,a.push(p.key),c.push(p.uniqueKey)}catch(g){l.push(p.key),o.error({err:g,cacheEntry:p},"Not using step cache due to parsing error")}},d=(m,p)=>{let g=RP(m.id,p),h=g.find(f=>!!n[f]);if(h)u(m,n[h]);else{if(m.type==="AI_CHECK")return;l.push(g[0])}};for(let m of r)switch(m.type){case"MOBILE_PRESET_STEP":{if(!Da(m.command)||m.command.type==="TYPE"&&!m.command.target||"cache"in m.command&&m.command.cache)continue;s++,d(m.command,i);break}default:return(g=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(m.type)}return e&&s&&l.length>0&&o.warn({totalSteps:s,cacheKeysMissed:l,cacheKeysHit:a,uniqueKeysHit:c,cacheEntries:n.length},"Step cache did not fully resolve"),{cacheKeysHit:a,cacheKeysMissed:l,uniqueKeysHit:c}}function wP(r,e){return e?`${e}:${r}`:r}function RP(r,e){let t=[],n=e?.split(":")??[];for(let o=n.length;o>=0;o--){let i=[...n.slice(o),r];t.push(i.join(":"))}return t.reverse(),t}function cd(r){let{moduleStepParents:e=[],moduleIdParents:t=[]}=r;if(e.length!==t.length)throw new Error(`Invalid cache entry parent length: ${JSON.stringify(e)}
25
- ${JSON.stringify(t)}`);let n=[];return n.push({key:wP(r.id,e.join(":")),organizationId:r.orgId,value:r.value,testId:r.testId}),n}function Tn({cmd:r,newTarget:e,key:t,logger:n}){r.type==="DRAG"?t!=="fromTarget"&&t!=="toTarget"?n.error({cmd:r,newTarget:e,key:t},"Attempted to apply invalid cache to DRAG command"):r.cache={...r.cache,[t]:e}:t==="target"&&cp(r)?r.cache={...r.cache,target:e}:n.error({cmd:r,newTarget:e,key:t},"Invalid target cache application")}function Ws(r,e,t){let n=r.cache&&"memory"in r.cache?r.cache.memory?.traces:void 0;return JSON.stringify(n)===JSON.stringify(e)?{changed:!1}:(t.info({updatedTraces:e,oldCmd:r},"Wrote new memory to assertion command"),r.cache={...r.cache,memory:{type:"GCS_TRACES",traces:e}},{changed:!0})}function ht(r,e,t=!1){return r.length<e?r:r.slice(0,e-3)+(t?"...TRUNCATED...":"[...]")}var bn={EQUALS:"equals",CONTAINS:"contains",STARTS_WITH:"starts with",EXISTS:"exists"},vn={EQUALS:"does not equal",CONTAINS:"does not contain",STARTS_WITH:"does not start with",EXISTS:"does not exist"},hy={EXISTS:"exists",VISIBLE:"is visible",ENABLED:"is enabled",EDITABLE:"is editable",FOCUSED:"is focused"},fy={EXISTS:"does not exist",VISIBLE:"is not visible",ENABLED:"is disabled",EDITABLE:"is not editable",FOCUSED:"is not focused"};var t7={CONTENT:"The page"};function Sy(r){switch(r.type){case"SUBSTRING":return`match substring '${r.url}'`;case"REGEX":return`match regex '${r.regex}'`;case"GLOB":return`match glob '${r.glob}'`;case"DOMAIN":return`match domain '${r.domain}'`;default:return(t=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(r)}}function Ey(r){switch(r.type){case"OPEN_APP":return`Open app: ${r.packageName}`;case"AI_CHECK":return`AI check: ${r.assertion}`;case"TAP":return`Tap on element: ${Dc(r.target)}`;case"TYPE":return`Type ${r.text} ${r.target?`into ${Dc(r.target)}`:""}`;case"PRESS":return`Press ${r.key}`;case"JAVASCRIPT":return`Execute JavaScript: ${r.code}`;case"OPEN_NOTIFICATION_DRAWER":return"Open notification drawer";case"ADB":return`ADB command: ${r.command}`;case"STATE":return"Get state";default:{let e=r;throw new Error("If Typescript complains about the line above, you missed a case or break in the switch above")}}}import{cloneDeep as CP}from"lodash-es";import{v4 as yy}from"uuid";async function To(r){let e=new Map,t=new Set,n=CP(r.steps),o=await xP({...r,steps:n,moduleStepParents:[],moduleIdParents:[],moduleIdReplacements:e,seenModules:t});return{stepsToSave:o.stepsToSave,cachesToSave:o.cachesToSave}}async function xP({steps:r,...e}){let{cacheCreationParams:t,moduleIdParents:n,moduleStepParents:o,createNewCacheIds:i}=e,a={cachesToSave:[],stepsToSave:[]};for(let l of r)switch(l.id=i?yy():l.id,l.type){case"MOBILE_PRESET_STEP":{let s=l.command;s.id=i?yy():s.id,"cache"in s&&s.cache&&(t&&(a.cachesToSave=a.cachesToSave.concat(cd({id:s.id,orgId:t.orgId,testId:t.testId,value:Pr.parse(s),moduleIdParents:n,moduleStepParents:o}))),delete s.cache),a.stepsToSave.push({...l,command:s});break}default:return(s=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(l.type)}return a}import{cloneDeep as w7}from"lodash-es";import C7 from"truncate-json";import{v4 as D7}from"uuid";import{cloneDeep as g7,unset as h7}from"lodash-es";import{cloneDeep as z7}from"lodash-es";import{cloneDeep as cee}from"lodash-es";import IZ from"diff-lines";import dd,{gte as OZ}from"semver";var Ty={name:"Migrate to ai step v2",fromVersion:"1.0.4",toVersion:"1.0.5",recursiveKeys:new Set(["results","commands"]),stopOnFailure:!0,execute:async r=>(r=r.filter(e=>!(e.status!==void 0&&e.type==="AI_ACTION")),r=r.map(e=>(e.status===void 0||e.type==="PRESET_ACTION"&&(e.results=e.commands??e.results??[]),e)),r)};var by={name:"Make sure ai step v2 has done command",fromVersion:"1.0.5",toVersion:"1.0.6",recursiveKeys:new Set(["results","commands"]),stopOnFailure:!0,execute:async r=>r.map(e=>{if(e.type!=="AI_ACTION"||e.status!==void 0||!e.commands||!e.commands.length)return e;let t=e.commands,n=t[t.length-1];return n&&n.type!=="SUCCESS"&&t.push({type:"SUCCESS"}),e})};var _P=["target","fromTarget","toTarget"];function vy(r){for(let e of _P){if(r[e]===void 0)continue;let t=r[e];t.elementDescriptor!==void 0?t.type="description":r[e]={type:"description",elementDescriptor:""}}}var Ay={name:"Migrate element target to discriminated union",fromVersion:"1.0.6",toVersion:"1.0.7",recursiveKeys:new Set(["results","steps"]),stopOnFailure:!0,execute:async r=>r.map(e=>{switch(e.type){case"PRESET_ACTION":return vy(e.command),e;case"AI_ACTION":{let t=e.commands;for(let n of t??[])vy(n);return e}default:return e}})};import{v4 as MP}from"uuid";var wy={name:"Ensure module steps have ids",fromVersion:"1.0.7",toVersion:"1.0.8",recursiveKeys:new Set(["results","steps"]),stopOnFailure:!0,execute:async r=>r.map(e=>{switch(e.type){case"MODULE":return e.id||(e.id=MP()),e;default:return e}})};import{v4 as Ry}from"uuid";var Cy={name:"Ensure module steps have ids",fromVersion:"1.0.8",toVersion:"1.0.9",recursiveKeys:new Set(["results","steps"]),stopOnFailure:!0,execute:async r=>r.map(e=>{switch(e.type){case"PRESET_ACTION":{if(!e.command)return e;let t=e.command;return t.id=t.id??Ry(),e}case"AI_ACTION":return e.commands&&(e.steps=e.commands.map(t=>({type:"PRESET_ACTION",command:{...t,id:t.id??Ry()}})),delete e.commands),e;default:return e}})};var xy={name:"Migrate ai waits to checks",fromVersion:"1.0.9",toVersion:"1.0.10",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!0,execute:async r=>r.map(e=>{switch(e.type){case"PRESET_ACTION":{if(!e.command)return e;let t=e.command;return typeof t.type!="string"||t.type!=="AI_WAIT"||(t.type="AI_ASSERTION",t.timeout||(t.timeout=10)),e}default:return e}})};import{v4 as IP}from"uuid";var _y={name:"Add ids to all steps",fromVersion:"1.0.10",toVersion:"1.0.11",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!0,execute:async r=>r.map(e=>("id"in e&&typeof e.id=="string"||(e.id=IP()),e))};import{v4 as My}from"uuid";var Iy={name:"Add ids to all steps",fromVersion:"1.0.11",toVersion:"1.0.12",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!0,execute:async r=>r.map(e=>{if("id"in e&&typeof e.id=="string")return e;if("condition"in e&&typeof e.condition=="object"&&e.condition){let t=e.condition;t.id||(t.id=My())}return e.id=My(),e})};var Py={name:"Move env key to steps",fromVersion:"1.0.12",toVersion:"1.0.13",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!0,execute:async r=>r.map(e=>{if(e.type!=="PRESET_ACTION")return e;let t=e.command;return!t||typeof t.envKey!="string"||(e.envKey=t.envKey,delete t.envKey),e})};import{v4 as PP}from"uuid";var Oy={name:"Redo last two migrations",fromVersion:"1.0.13",toVersion:"1.0.14",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!0,execute:async r=>r.map(e=>{if((!("id"in e)||typeof e.id!="string")&&(e.id=PP()),e.type!=="PRESET_ACTION")return e;let t=e.command;return!t||typeof t.envKey!="string"||(e.envKey=t.envKey,delete t.envKey),e})};var Ly={name:"Migrate select choice",fromVersion:"1.0.14",toVersion:"1.0.15",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!0,execute:async r=>r.map(e=>{if(e.type!=="PRESET_ACTION")return e;let t=e.command;return!t||t.type!=="SELECT_OPTION"||e.option===void 0||(e.choice={type:"VALUE",value:t.option},e.option=void 0),e})};var Ny={name:"Migrate select choice",fromVersion:"1.0.15",toVersion:"1.0.16",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!0,execute:async r=>r.map(e=>{if(e.type!=="PRESET_ACTION")return e;let t=e.command;return t&&Dy(t),e})};function Dy(r){r&&Object.keys(r).forEach(e=>{if(typeof r[e]=="object"&&r[e]){Dy(r[e]);return}if(typeof r[e]!="string")return;let t=r[e];e==="code"?r[e]=t.replace(/inputs\./g,"env."):t.includes("{{")&&t.includes("}}")&&(r[e]=t.replace(/inputs\./g,"env."))})}var ky={name:"Migrate switch tab choice",fromVersion:"1.0.16",toVersion:"1.0.17",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!0,execute:async r=>r.map(e=>{if(e.type!=="PRESET_ACTION")return e;let t=e.command;return!t||t.type!=="TAB"||t.url===void 0||(t.action={type:"SUBSTRING",substring:t.url},t.url=void 0),e})};var Uy={name:"Remove press keys sequentially",fromVersion:"1.0.17",toVersion:"1.0.18",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!1,execute:async r=>r.map(e=>{if(e.type!=="PRESET_ACTION")return e;let t=e.command;return!t||t.type!=="TYPE"?e:t.pressKeysSequentially===void 0?(t.delay=0,e):(t.pressKeysSequentially&&(t.pressKeysSequentially=void 0,t.delay=50),e)})};var Fy={name:"Migrate wait for URL to matcher",fromVersion:"1.0.18",toVersion:"1.0.19",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!1,execute:async r=>r.map(e=>{if(e.type!=="PRESET_ACTION")return e;let t=e.command;return!t||t.type!=="WAIT_FOR_URL"||t.url===void 0||(t.matcher={type:"GLOB",glob:t.url},t.url=void 0),e})};var By={name:"Migrate select choice round 2",fromVersion:"1.0.19",toVersion:"1.0.20",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!0,execute:async r=>r.map(e=>{if(e.type!=="PRESET_ACTION")return e;let t=e.command;if(!t)return e;if(t.type==="SELECT_OPTION"){if(t.option===void 0)return e;t.choice={type:"VALUE",value:t.option},t.option=void 0}else if(t.type==="TAB"){if(t.url===void 0)return e;t.action={type:"SUBSTRING",substring:t.url},t.url=void 0}else if(t.type==="WAIT_FOR_URL"){if(t.url===void 0)return e;t.matcher={type:"GLOB",glob:t.url},t.url=void 0}else t.type==="AI_WAIT"&&(t.type="AI_ASSERTION",t.timeout||(t.timeout=10));return e})};var zy={name:"Migrate ",fromVersion:"1.0.20",toVersion:"1.0.21",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!1,execute:async r=>r.map(e=>{if(e.type!=="PRESET_ACTION")return e;let t=e.command;return!t||t.type!=="MOCK_ROUTE"&&t.type!=="SET_HEADER"&&t.type!=="RECORD_REQUESTS"&&t.type!=="REGISTER_REQUEST_LISTENER"||(t.type==="REGISTER_REQUEST_LISTENER"||t.type==="RECORD_REQUESTS"?t.requestMatcher={urlMatcher:{type:"REGEX",regex:t.pattern}}:(t.type==="SET_HEADER"||t.type==="MOCK_ROUTE")&&t.urlPattern&&(t.requestMatcher={urlMatcher:{type:"REGEX",regex:t.urlPattern}})),e})};var Gy={name:"Migrate AI checks to preset actions",fromVersion:"1.0.0",toVersion:"1.0.1",recursiveKeys:new Set,execute:async r=>r.map(e=>{if(e.type!=="AI_ASSERTION")return e;let n={type:"PRESET_ACTION",command:{type:"AI_ASSERTION",assertion:e.text,useVision:!1,disableCache:!0}},o={...e,...n};return delete o.text,o}),stopOnFailure:!0};var $s=new Set(["CLICK","TYPE","SELECT_OPTION"]),Hy={name:"Migrate element descriptor to live in a target object",fromVersion:"1.0.3",toVersion:"1.0.4",recursiveKeys:new Set,execute:async r=>r.map(e=>{let t=e.command,n=t?.type,o=t?.elementDescriptor;return(o!==void 0||$s.has(n))&&(t.target={elementDescriptor:o??""}),e.commands&&Array.isArray(e.commands)&&e.commands.forEach(a=>{let l=a?.elementDescriptor,c=a?.type;(l!==void 0||$s.has(c))&&(a.target={elementDescriptor:l??""})}),e.results&&Array.isArray(e.results)&&e.results.forEach(a=>{let l=a.command,c=l?.elementDescriptor,s=l?.type;(c!==void 0||$s.has(s))&&(l.target={elementDescriptor:c??""}),a.commands&&Array.isArray(a.commands)&&a.commands.forEach(d=>{let m=d?.elementDescriptor,p=d?.type;(m!==void 0||$s.has(p))&&(d.target={elementDescriptor:m??""})})}),e}),stopOnFailure:!0};var Vy={name:"Migrate FAILURE status to FAILED",fromVersion:"1.0.1",toVersion:"1.0.2",recursiveKeys:new Set,execute:async r=>r.map(e=>{let t=e;return t.status==="FAILURE"&&(t.status="FAILED"),typeof t.commands=="object"&&Array.isArray(t.commands)&&t.commands.forEach(n=>{if(n&&typeof n=="object"){let o=n;o?.status==="FAILURE"&&(o.status="FAILED")}}),t}),stopOnFailure:!0};var jy={name:"Migrate preset step types to use the same",fromVersion:"1.0.2",toVersion:"1.0.3",recursiveKeys:new Set,execute:async r=>r.map(e=>{let t=e.command,n=t?.type;return n?.startsWith("PRESET_")&&(t.type=n.slice(7)),e.commands&&Array.isArray(e.commands)&&e.commands.forEach(i=>{let a=i.type;a?.startsWith("PRESET_")&&(i.type=a.slice(7))}),e.results&&Array.isArray(e.results)&&e.results.forEach(i=>{let a=i.command,l=a?.type;l?.startsWith("PRESET_")&&(a.type=l.slice(7)),i.commands&&Array.isArray(i.commands)&&i.commands.forEach(s=>{let u=s.type;u?.startsWith("PRESET_")&&(s.type=u.slice(7))})}),e}),stopOnFailure:!0};var qs=[Gy,Vy,jy,Hy,Ty,by,Ay,wy,Cy,xy,_y,Iy,Py,Oy,Ly,Ny,ky,Uy,Fy,By,zy];if(Wn!==qs[qs.length-1].toVersion)throw new Error("Please bump LATEST_SCHEMA_VERSION in types package after adding a migration");qs.forEach((r,e)=>{if(!dd.valid(r.toVersion)||!dd.valid(r.fromVersion))throw new Error(`Migration '${r.name}' has invalid version`);if(!dd.gt(r.toVersion,r.fromVersion))throw new Error(`Migration '${r.name}' has toVersion <= fromVersion`);if(e===0)return;if(qs[e-1].toVersion!==r.fromVersion)throw new Error(`Migration '${r.name}' at index ${e} is not contiguous with previous migration`)});import{cloneDeep as Ree}from"lodash-es";import{stringify as Uee}from"yaml";async function q(r,e){if(!(r<=0))return new Promise((t,n)=>{if(e?.aborted){n(e.reason);return}e?.addEventListener("abort",i);let o=setTimeout(()=>{e?.removeEventListener("abort",i),t()},r);function i(){clearTimeout(o),e?.removeEventListener("abort",i),n(e?.reason)}})}async function md({promiseGenerator:r,signal:e,codePath:t,logger:n}){let i=Date.now(),a=setInterval(()=>{if(e?.aborted){clearInterval(a);return}n?.warn({codePath:t,startTime:i,elapsedMilliseconds:Date.now()-i},`Asynchronous operation is taking a long time (${t})`)},5e3);return new Promise((l,c)=>{function s(){clearInterval(a),e?.removeEventListener("abort",s),c(e?.reason)}if(e?.aborted){c(e?.reason),clearInterval(a);return}e?.addEventListener("abort",s),(async()=>{try{l(await r())}catch(u){c(u)}finally{clearInterval(a),e?.removeEventListener("abort",s)}})()})}async function An({promiseGenerator:r,timeoutMs:e,codePath:t,logger:n,signal:o}){let i=!1,a=new AbortController,l=()=>{a.abort()},c=setTimeout(()=>{i||a.abort()},e);o?.addEventListener("abort",l);try{return await md({promiseGenerator:r,signal:a.signal,codePath:t,logger:n})}finally{i=!0,o?.removeEventListener("abort",l),clearTimeout(c)}}function Ks(r){let e;return r>10*60*1e3?e=2*60*1e3:r>60*1e3?e=20*1e3:r>10*1e3?e=2*1e3:e=1e3,e}import OP from"picomatch";var Ys=(r,e,t)=>{t?.caseInsensitive&&(r=r.toLowerCase());let n;switch(e.type){case"SUBSTRING":{let o=t?.caseInsensitive?e.url.toLowerCase():e.url;n=r.includes(o);break}case"GLOB":{let o=t?.caseInsensitive?e.glob.toLowerCase():e.glob;n=r===e.glob||OP(o)(r);break}case"REGEX":{n=new RegExp(e.regex).test(r);break}case"DOMAIN":{let o=t?.caseInsensitive?e.domain.toLowerCase():e.domain;n=new URL(r).hostname===o;break}}return t?.negated?!n:n},Xs=(r,e)=>{try{let{hostname:t,pathname:n}=new URL(r),{hostname:o,pathname:i}=new URL(e);return t!==o||n!==i}catch{return!1}},bo=r=>{try{return new URL(r),!0}catch{return!1}},Wy=r=>!r.toLowerCase().startsWith("http"),vo=(r,e)=>{try{return new URL(r,e),!0}catch{return!1}};function wn(r,e){try{return!!new URL(r).origin.trim()}catch(t){return e?.error({url:r,err:t},"Invalid URL in check"),!1}}import{v4 as $y}from"uuid";function pd(r,e){return{...r,testId:e?.testId??"",testName:e?.testName??"",suiteId:e?.suiteId??"",suiteName:e?.suiteName??""}}var Js=class{reporter;asyncWork;metadata;creditsUsedV1=0;creditsUsedV2=0;constructor({logger:e,reporter:t,runType:n,runId:o,testMetadata:i,suiteMetadata:a}){this.reporter=t,this.metadata={testId:i.id,testName:i.name,suiteId:a?.id,suiteName:a?.name},this.asyncWork=[t.reportBillableEvents(e,[{event:n,timestamp:new Date().toISOString(),transactionId:o,properties:pd({},this.metadata)}]).catch(l=>e.error({err:l},"Failed to report billable event"))]}trackStepExecution(e){if(e.type==="MOBILE_PRESET_STEP"){this.creditsUsedV2+=1;return}let t=Mc(e.type);if(this.creditsUsedV1+=t??0,e.type==="PRESET_ACTION"){this.creditsUsedV2+=1;let n=Ic(e.command);this.creditsUsedV1+=n??0}}async flush(e){this.creditsUsedV1>0&&this.asyncWork.push(this.reporter.reportBillableEvents(e,[{event:"credits-used",timestamp:new Date().toISOString(),transactionId:$y(),properties:pd({creditsUsed:this.creditsUsedV1},this.metadata)}]).catch(t=>e.error({err:t},"Failed to report credits used"))),this.creditsUsedV2>0&&this.asyncWork.push(this.reporter.reportBillableEvents(e,[{event:"credits-used-v2",timestamp:new Date().toISOString(),transactionId:$y(),properties:pd({creditsUsed:this.creditsUsedV2},this.metadata)}]).catch(t=>e.error({err:t},"Failed to report credits used"))),await Promise.allSettled(this.asyncWork)}};import Yy from"fontoxpath";import{DOMParser as LP,XMLSerializer as NP}from"slimdom";function gd(r){return r.toLowerCase().endsWith("webview")}function DP(r){let e=["android.widget.","android.view.","android.webkit.","android.app.","android.support.","androidx.","com.android.inputmethod."];for(let t of e)if(r.startsWith(t))return r.substring(t.length);return r}var kP=new Set(["index","package","a11y-important"]),UP=new Set(["selected","checked","checkable","clickable","enabled","focusable","focused","long-clickable","password","scrollable","selected","showing-hint","context-clickable","text-entry-key","heading","dismissable","screen-reader-focusable","content-invalid","a11y-focused"]),FP=new Set(["live-region","drawing-order"]),BP=new Set(["displayed","enabled"]);function zP(r,e){let t={};for(let[n,o]of Object.entries(e))kP.has(n)||n==="class"&&r===o||UP.has(n)&&o==="false"||n==="text"&&o===""||BP.has(n)&&o==="true"||FP.has(n)&&o==="0"||n!=="id"&&(t[n]=o);return t}function qy(r,e,t){let{prunedDocument:n,idToElement:o,prunedIdToElement:i,idCounter:a,opts:l}=r,c=a.value++;t.setAttribute("id",String(c));let s={};for(let m of e.attributes){let p=m.name,g=m.value;g!=null&&(s[p]=String(g))}let u=zP(e.tagName,s);for(let[m,p]of Object.entries(u))t.setAttribute(m,p);if(o.set(c,e),i.set(c,t),gd(e.tagName)&&l?.disallowAccessibilityBridgeForWebviews){for(;t.firstChild;)t.removeChild(t.firstChild);let m=l.injectedWebviewContent??"";m.trim().length>0&&t.appendChild(n.createTextNode(m));return}let d=Array.from(e.childNodes??[]);for(let m of d){let p=m.nodeType;if(p===3){let g=m.nodeValue;g&&g.trim().length>0&&t.appendChild(n.createTextNode(g));continue}if(p===1){let g=m,h=n.createElement(DP(g.tagName));qy(r,g,h),t.appendChild(h)}}}function GP(r,e,t,n){let o=r.parseFromString("<hierarchy/>","text/xml"),i=new Map,a={prunedDocument:o,idToElement:t,prunedIdToElement:i,idCounter:{value:0},opts:n},l=o.documentElement;qy(a,e,l);let c=new NP().serializeToString(o);return{prunedDocument:o,prunedIdToElement:i,xml:c}}async function Ky(r,e){let t=new LP,n=t.parseFromString(r,"text/xml"),o=new Map,i=n.documentElement;if(!i)throw new Error("No root element found in XML");if(i.tagName!=="hierarchy")throw new Error("No hierarchy element found in XML");let{prunedDocument:a,prunedIdToElement:l,xml:c}=GP(t,i,o,e);return{xml:c,originalXml:r,document:n,idToElement:o,prunedDocument:a,prunedIdToElement:l}}function HP(r){let e=[],t=r;for(;t;){let n=t.tagName,o=t.parentElement,i=1;if(o){let a=Array.from(o.children).filter(l=>l.tagName===n);for(let l=0;l<a.length;l++)if(a[l]===t){i=l+1;break}}e.unshift(`${n}[${i}]`),t=o}return`/${e.join("/")}`}function Qs(r,e){let t=r.idToElement.get(e);if(t)return HP(t)}function hd(r,e){let t=r.idToElement.get(e);if(!t)return;let n=t.cloneNode(!0);for(let o of Array.from(n.children)){let i=o;for(let a of Array.from(i.children))i.removeChild(a)}return n.outerHTML}function Zs(r){if(!r.hasAttribute("bounds"))return;let e=r.getAttribute("bounds");if(!e)return;let t=e.match(/\[(\d+),(\d+)\]\[(\d+),(\d+)\]/);if(t){let n=parseInt(t[1],10),o=parseInt(t[2],10),i=parseInt(t[3],10),a=parseInt(t[4],10);if(Number.isFinite(n)&&Number.isFinite(o)&&Number.isFinite(i)&&Number.isFinite(a))return[n,o,i,a]}}function fd(r,e){if(r&&!(!e||e.length===0))return Object.fromEntries(e.map(t=>[t,r.getAttribute(t)]).filter(([,t])=>t!==null))}function Jy({aiResponse:r,description:e,emulatorState:t}){let n=t.graph.idToElement.get(r.id);if(!n)throw new Error(`Could not find node with id: ${r.id}`);let o=Zs(n);if(!o)throw new Error(`Node ${r.id} has no bounding box: ${n.outerHTML}`);let i=Qs(t.graph,r.id)??"",a=hd(t.graph,r.id)??"",l=t.graph.idToElement.get(r.id),c=fd(l,r.requirements?.attributesRequired),u={requiredText:r.requirements?.textRequired?l?.getAttribute("text")??void 0:void 0,requiredAttributes:c,requiredBounds:r.requirements?.boundsRequired},d=[];r.additionalElements&&(d=r.additionalElements.map(({id:p,requirements:g})=>{let h=t.graph.idToElement.get(p);if(!h)return;let f=Qs(t.graph,p);return f?{xPath:f,requirements:{requiredText:g.textRequired?h.getAttribute("text")??void 0:void 0,requiredAttributes:fd(h,g.attributesRequired),requiredBounds:g.boundsRequired}}:void 0}).filter(p=>!!p));let m;return gd(n.tagName)?m={type:"WEBVIEW",resolvedDescription:e,xPath:i}:m={type:"NATIVE",bounds:o,resolvedDescription:e,xPath:i,elementOnlySerializedXml:a,requirements:u,requiredRelatedElements:d},m}var Xy=(r,e,t)=>{if(!e)return;let{requiredAttributes:n,requiredText:o,requiredBounds:i}=e;if(o!==void 0){let a=r.getAttribute("text")??void 0;if(a!==o)throw new Error(`ActionFailureError: Resolved element text mismatch: expected ${o}, got ${a}`)}if(n)for(let[a,l]of Object.entries(n)){let c=r.getAttribute(a)??void 0;if(c!==l)throw new Error(`ActionFailureError: Attribute ${a} mismatch: expected ${l}, got ${c}`)}if(i&&t){let a=Zs(r);if(!a||a.length!==t.length)throw new Error("ActionFailureError: Resolved element has no bounds or unexpected bounds format");if(!a.every((c,s)=>c===t[s]))throw new Error(`ActionFailureError: Bounds changed from [${t.join(",")} ] to [${a.join(",")} ]`)}};async function Qy(r){let{target:e,domState:t,stateManager:n,logger:o,signal:i}=r,{graph:a}=t,{document:l}=a;if(e.type==="WEBVIEW"){let g=await n.getActiveWebview();if(!g||!g.browserController)throw new Error("No browser controller is attached to the requested webview");if(!e.browserCache)throw new Error("No browser target available on cache");let h=await g.browserController.browser.resolveTarget(null,e.browserCache,{logger:o,signal:i});return{resolvedTarget:{...e,controller:g.browserController,resolution:h}}}let c=Yy.evaluateXPathToFirstNode(e.xPath,l,null,null);if(!c)throw new Error(`ActionFailureError: Could not resolve cached target via XPath: ${e.xPath}`);if(e.requiredRelatedElements)for(let g of e.requiredRelatedElements){let h=Yy.evaluateXPathToFirstNode(g.xPath,l);if(!h)throw new Error(`ActionFailureError: Required related element not found for XPath: ${g.xPath}`);Xy(h,g.requirements)}let s=Zs(c);if(!s)throw new Error("ActionFailureError: Resolved native element has no bounding box");Xy(c,e.requirements,e.bounds);let u;for(let[g,h]of a.idToElement.entries())if(h===c){u=g;break}let d=e.elementOnlySerializedXml,m=e.xPath;return u!==void 0&&(d=hd(a,u)??d,m=Qs(a,u)??m),{resolvedTarget:{...e,bounds:s,elementOnlySerializedXml:d,xPath:m}}}function Sd(r){let{command:e,cacheKey:t="cache",targetName:n="target",updatedCache:o}=r;Da(e)&&(e[t]={...e[t],[n]:o})}function Zy(r){return r.type==="WEBVIEW"?{type:"WEBVIEW",resolvedDescription:r.resolvedDescription,xPath:r.xPath,browserCache:r.browserCache}:r}import{execSync as kb}from"child_process";import{_android as dN,chromium as mN}from"playwright";var eT={vimiumJs:'var D=Object.defineProperty;var P=(t,e,n)=>e in t?D(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n;var b=(t,e,n)=>(P(t,typeof e!="symbol"?e+"":e,n),n);var y=t=>function(e){return e&&e.isTrusted?t.apply(this,arguments):!0};globalThis.forTrusted==null&&(globalThis.forTrusted=y);var E={create(t,e,n,o){return{bottom:o,top:e,left:t,right:n,width:n-t,height:o-e}},copy(t){return{bottom:t.bottom,top:t.top,left:t.left,right:t.right,width:t.width,height:t.height}},translate(t,e,n){return e==null&&(e=0),n==null&&(n=0),{bottom:t.bottom+n,top:t.top+n,left:t.left+e,right:t.right+e,width:t.width,height:t.height}},subtract(t,e){return e=this.create(Math.max(t.left,e.left),Math.max(t.top,e.top),Math.min(t.right,e.right),Math.min(t.bottom,e.bottom)),e.width<0||e.height<0?[E.copy(t)]:[this.create(t.left,t.top,e.left,e.top),this.create(e.left,t.top,e.right,e.top),this.create(e.right,t.top,t.right,e.top),this.create(t.left,e.top,e.left,e.bottom),this.create(e.right,e.top,t.right,e.bottom),this.create(t.left,e.bottom,e.left,t.bottom),this.create(e.left,e.bottom,e.right,t.bottom),this.create(e.right,e.bottom,t.right,t.bottom)].filter(o=>o.height>0&&o.width>0)},intersects(t,e){return t.right>e.left&&t.left<e.right&&t.bottom>e.top&&t.top<e.bottom},intersectsStrict(t,e){return t.right>=e.left&&t.left<=e.right&&t.bottom>=e.top&&t.top<=e.bottom},equals(t,e){for(let n of["top","bottom","left","right","width","height"])if(t[n]!==e[n])return!1;return!0},intersect(t,e){return this.create(Math.max(t.left,e.left),Math.max(t.top,e.top),Math.min(t.right,e.right),Math.min(t.bottom,e.bottom))}};var T={_browserInfoLoaded:!0,_firefoxVersion:null,_isFirefox:!1,isFirefox(){if(!this._browserInfoLoaded)throw Error("browserInfo has not yet loaded.");return this._isFirefox},firefoxVersion(){if(!this._browserInfoLoaded)throw Error("browserInfo has not yet loaded.");return this._firefoxVersion},isString(t){return typeof t=="string"||t instanceof String}};var f={isReady(){return document.readyState!=="loading"},documentReady:function(){let t=document.readyState!=="loading",e=[];if(!t){let n;globalThis.addEventListener("DOMContentLoaded",n=y(function(){globalThis.removeEventListener("DOMContentLoaded",n,!0),t=!0;for(let o of e)o();e=null}),!0)}return function(n){if(t)return n();e.push(n)}}(),documentComplete:function(){let t=document.readyState==="complete",e=[];if(!t){let n;globalThis.addEventListener("load",n=y(function(o){if(o.target===document){globalThis.removeEventListener("load",n,!0),t=!0;for(let r of e)r();e=null}}),!0)}return function(n){t?n():e.push(n)}}(),createElement(t){let e=document.createElement(t);return e instanceof HTMLElement?(this.createElement=n=>document.createElement(n),e):(this.createElement=n=>document.createElementNS("http://www.w3.org/1999/xhtml",n),this.createElement(t))},addElementsToPage(t,e){let n=this.createElement("div");e.id!=null&&(n.id=e.id),e.className!=null&&(n.className=e.className);for(let o of t)n.appendChild(o);return document.body.appendChild(n),n},removeElement(t){return t.parentNode.removeChild(t)},isTopFrame(){return globalThis.top===globalThis.self},makeXPath(t){let e=[];for(let n of t)e.push(".//"+n,".//xhtml:"+n);return e.join(" | ")},evaluateXPath(t,e){let n=document.webkitIsFullScreen?document.webkitFullscreenElement:document.documentElement,o=function(r){return r==="xhtml"?"http://www.w3.org/1999/xhtml":null};return document.evaluate(t,n,o,e,null)},getVisibleClientRect(t,e){let n;e==null&&(e=!1);let o=(()=>{let i=[];for(n of t.getClientRects())i.push(E.copy(n));return i})(),r=function(){let i=window.getComputedStyle(t,null),h=i.getPropertyValue("display").indexOf("inline")===0&&i.getPropertyValue("font-size")==="0px";return r=()=>h,h};for(n of o){let i;if((n.width===0||n.height===0)&&e)for(let h of Array.from(t.children)){i=window.getComputedStyle(h,null);let m=i.getPropertyValue("position");if(i.getPropertyValue("float")==="none"&&!["absolute","fixed"].includes(m)&&!(n.height===0&&r()&&i.getPropertyValue("display").indexOf("inline")===0))continue;let s=this.getVisibleClientRect(h,!0);if(!(s===null||s.width<3||s.height<3))return s}else{if(n=this.cropRectToVisible(n),n===null||n.width<3||n.height<3||(i=window.getComputedStyle(t,null),i.getPropertyValue("visibility")!=="visible"))continue;return n}}return null},cropRectToVisible(t){let e=E.create(Math.max(t.left,0),Math.max(t.top,0),t.right,t.bottom);return e.top>=window.innerHeight-4||e.left>=window.innerWidth-4?null:e},getClientRectsForAreas(t,e){let n=[];for(let o of e){let r,i,h,m,s=o.coords.split(",").map(l=>parseInt(l,10)),a=o.shape.toLowerCase();if(["rect","rectangle"].includes(a))s.length==4&&([r,h,i,m]=s);else if(["circle","circ"].includes(a)){if(s.length==3){let[l,c,d]=s,p=d/Math.sqrt(2);r=l-p,i=l+p,h=c-p,m=c+p}}else a==="default"?s.length==2&&([r,h,i,m]=[0,0,t.width,t.height]):s.length>=4&&([r,h,i,m]=s);let u=E.translate(E.create(r,h,i,m),t.left,t.top);u=this.cropRectToVisible(u),u&&!isNaN(u.top)&&!isNaN(u.left)&&!isNaN(u.width)&&!isNaN(u.height)&&n.push({element:o,rect:u})}return n},isSelectable(t){if(!(t instanceof Element))return!1;let e=["button","checkbox","color","file","hidden","image","radio","reset","submit"];return t.nodeName.toLowerCase()==="input"&&e.indexOf(t.type)===-1||t.nodeName.toLowerCase()==="textarea"||t.isContentEditable},isEditable(t){return this.isSelectable(t)||(t.nodeName!=null?t.nodeName.toLowerCase():void 0)==="select"},isEmbed(t){let e=t.nodeName!=null?t.nodeName.toLowerCase():null;return["embed","object"].includes(e)},isFocusable(t){return t&&(this.isEditable(t)||this.isEmbed(t))},isDOMDescendant(t,e){let n=e;for(;n!==null;){if(n===t)return!0;n=n.parentNode}return!1},isSelected(t){let e=document.getSelection();if(t.isContentEditable){let n=e.anchorNode;return n&&this.isDOMDescendant(t,n)}else if(f.getSelectionType(e)==="Range"&&e.isCollapsed){let n=e.anchorNode.childNodes[e.anchorOffset];return t===n}else return!1},simulateSelect(t){if(t===document.activeElement&&f.isEditable(document.activeElement))return handlerStack.bubbleEvent("click",{target:t});if(t.focus(),t.tagName.toLowerCase()!=="textarea"||t.value.indexOf(`\n`)<0)try{if(t.selectionStart===0&&t.selectionEnd===0)return t.setSelectionRange(t.value.length,t.value.length)}catch{}},simulateClick(t,e){e==null&&(e={});let n=["mouseover","mousedown","mouseup","click"],o=[];for(let r of n){let i=this.simulateMouseEvent(r,t,e);o.push(i)}return o},simulateMouseEvent(t,e,n){if(n==null&&(n={}),t==="mouseout"){if(e==null&&(e=this.lastHoveredElement),this.lastHoveredElement=void 0,e==null)return}else t==="mouseover"&&(this.simulateMouseEvent("mouseout",void 0,n),this.lastHoveredElement=e);let o=new MouseEvent(t,{bubbles:!0,cancelable:!0,composed:!0,view:window,detail:1,ctrlKey:n.ctrlKey,altKey:n.altKey,shiftKey:n.shiftKey,metaKey:n.metaKey});return e.dispatchEvent(o)},simulateClickDefaultAction(t,e){let n;if(e==null&&(e={}),(t.tagName!=null?t.tagName.toLowerCase():void 0)!=="a"||!t.href)return;let{ctrlKey:o,shiftKey:r,metaKey:i,altKey:h}=e;KeyboardUtils.platform==="Mac"?n=i===!0&&o===!1:n=i===!1&&o===!0,n?chrome.runtime.sendMessage({handler:"openUrlInNewTab",url:t.href,active:r===!0}):r===!0&&i===!1&&o===!1&&h===!1?chrome.runtime.sendMessage({handler:"openUrlInNewWindow",url:t.href}):t.target==="_blank"&&chrome.runtime.sendMessage({handler:"openUrlInNewTab",url:t.href,active:!0})},simulateHover(t,e){return e==null&&(e={}),this.simulateMouseEvent("mouseover",t,e)},simulateUnhover(t,e){return e==null&&(e={}),this.simulateMouseEvent("mouseout",t,e)},addFlashRect(t){let e=this.createElement("div");return e.classList.add("vimiumReset"),e.classList.add("vimiumFlash"),e.style.left=t.left+"px",e.style.top=t.top+"px",e.style.width=t.width+"px",e.style.height=t.height+"px",document.documentElement.appendChild(e),e},getViewportTopLeft(){let t=document.documentElement,e=getComputedStyle(t),n=t.getBoundingClientRect();if(e.position==="static"&&!/content|paint|strict/.test(e.contain||"")){let o=parseInt(e.marginTop),r=parseInt(e.marginLeft);return{top:-n.top+o,left:-n.left+r}}else{let o,r;return T.isFirefox()?(r=parseInt(e.borderTopWidth),o=parseInt(e.borderLeftWidth)):{clientTop:r,clientLeft:o}=t,{top:-n.top-r,left:-n.left-o}}},suppressPropagation(t){t.stopImmediatePropagation()},suppressEvent(t){t.preventDefault(),this.suppressPropagation(t)},consumeKeyup:function(){let t=null;return function(e,n=null,o){if(!e.repeat){t!=null&&handlerStack.remove(t);let{code:r}=e;t=handlerStack.push({_name:"dom_utils/consumeKeyup",keyup(i){return i.code!==r||(this.remove(),o?f.suppressPropagation(i):f.suppressEvent(i)),handlerStack.continueBubbling},blur(i){return i.target===window&&this.remove(),handlerStack.continueBubbling}})}return typeof n=="function"&&n(),o?(f.suppressPropagation(e),handlerStack.suppressPropagation):(f.suppressEvent(e),handlerStack.suppressEvent)}}(),getSelectionType(t){return t==null&&(t=document.getSelection()),t.type?t.type:t.rangeCount===0?"None":t.isCollapsed?"Caret":"Range"},getElementWithFocus(t,e){let n,o=n=t.getRangeAt(0);f.getSelectionType(t)==="Range"&&(o=n.cloneRange(),o.collapse(e)),n=o.startContainer,n.nodeType===1&&(n=n.childNodes[o.startOffset]);let r=n;for(;r&&r.nodeType!==1;)r=r.previousSibling;return n=r||n?.parentNode,n},getSelectionFocusElement(){let t=window.getSelection(),e=t.focusNode;return e==null?null:(e===t.anchorNode&&t.focusOffset===t.anchorOffset&&(e=e.childNodes[t.focusOffset]||e),e.nodeType!==Node.ELEMENT_NODE?e.parentElement:e)},getContainingElement(t){return(typeof t.getDestinationInsertionPoints=="function"?t.getDestinationInsertionPoints()[0]:void 0)||t.parentElement},windowIsTooSmall(){return window.innerWidth<3||window.innerHeight<3},injectUserCss(){let t=document.createElement("style");t.type="text/css",t.textContent=Settings.get("userDefinedLinkHintCss"),document.head.appendChild(t)}};var R={MAX_CONTENT_LENGTH:1e3,MAX_ATTRIBUTE_LENGTH:500,MAX_NUM_DATA_ATTRIBUTES:10,commonAttributes:["id","className","title","aria-label","aria-labelledby"],attributeNamesMapping:new Map([["a",["href","title","rel","target"]],["label",["for"]],["input",["type","name","placeholder","checked","maximumLength"]],["textarea",["placeholder","maximumLength"]],["button",["type"]],["select",["name","multiple"]],["div",["role"]],["iframe",["src"]],["img",["src","alt"]]]),describe(t){let e={};this.addAttributes(t,this.commonAttributes,e);let n=t.tagName.toLowerCase?.()||"";this.attributeNamesMapping.has(n)&&this.addAttributes(t,this.attributeNamesMapping.get(n),e),this.addDataAttrs(t,e);let o=this.getContent(t);return this.additionalHandling(t,{tag:n,attributes:e,...o&&{content:o}})},getContent(t){let e=t.tagName.toLowerCase?.()||"";return["input","textarea"].includes(e)?t.value:["div","iframe","img","body"].includes(e)?null:(["a","button","select","label"].includes(e),t.innerText)},additionalHandling(t,e){if((t.tagName.toLowerCase?.()||"")=="label"&&t.hasAttribute("for")){let o=t.getAttribute("for"),r=document.getElementById(o);r&&(e.target=this.describe(r))}return e},addAttributes(t,e,n){n||(n={});for(let o of e)t.hasAttribute(o)&&(n[o]=t.getAttribute(o).substring(0,this.MAX_ATTRIBUTE_LENGTH));return n},addDataAttrs(t,e){let n=0;for(let o in t.dataset)if(e[`data-${o}`]=t.dataset[o].substring(0,this.MAX_ATTRIBUTE_LENGTH),n++,n>this.MAX_NUM_DATA_ATTRIBUTES)return e;return e}};var C=null,k=()=>j()||document.scrollingElement||document.body,_=function(t){return t?t<0?-1:1:0},F={x:{axisName:"scrollLeft",max:"scrollWidth",viewSize:"clientWidth"},y:{axisName:"scrollTop",max:"scrollHeight",viewSize:"clientHeight"}},O=function(t,e,n){if(T.isString(n)){let o=n;return o==="viewSize"&&t===k()?e==="x"?window.innerWidth:window.innerHeight:t[F[e][o]]}else return n},I=function(t,e,n){let o=F[e].axisName,r=t[o];if(t.scrollBy){let i={behavior:"instant"};i[e==="x"?"left":"top"]=n,t.scrollBy(i)}else t[o]+=n;return t[o]!==r},V=function(t,e){let n=window.getComputedStyle(t);return!(n.getPropertyValue(`overflow-${e}`)==="hidden"||["hidden","collapse"].includes(n.getPropertyValue("visibility"))||n.getPropertyValue("display")==="none")},v=function(t,e,n,o){let r=o*O(t,e,n)||-1;return r=_(r),I(t,e,r)&&I(t,e,-r)},U=function(t,e,n,o){return e==null&&(e="y"),n==null&&(n=1),o==null&&(o=1),v(t,e,n,o)&&V(t,e)},H=function(t=null){let e;if(!t){let n=k();if(v(n,"y",1,1)||v(n,"y",-1,1))return n;t=document.body||k()}if(v(t,"y",1,1)||v(t,"y",-1,1))return t;{let n=Array.from(t.children).map(o=>({element:o,rect:f.getVisibleClientRect(o)})).filter(o=>o.rect);n.map(o=>o.area=o.rect.width*o.rect.height);for(e of n.sort((o,r)=>r.area-o.area)){let o=H(e.element);if(o)return o}return null}},M={init(){C=null},isScrollableElement(t){return C||(C=k()&&H()||k()),t!==C&&U(t)}},j=function(){let t=K[window.location.host];if(t)return document.querySelector(t)},K={"twitter.com":"div.permalink-container div.permalink[role=main]","reddit.com":"#overlayScrollContainer","new.reddit.com":"#overlayScrollContainer","www.reddit.com":"#overlayScrollContainer","web.telegram.org":".MessageList"};window.Scroller=M;var x=function(){let t=null;return f.documentReady(()=>t=document.hasFocus()),globalThis.addEventListener("focus",y(function(e){return e.target===window&&(t=!0),!0}),!0),globalThis.addEventListener("blur",y(function(e){return e.target===window&&(t=!1),!0}),!0),()=>t}();Object.assign(globalThis,{windowIsFocused:x});var L=class{constructor(e){b(this,"element");b(this,"image");b(this,"rect");b(this,"linkText");b(this,"showLinkText");b(this,"reason");b(this,"secondClassCitizen");b(this,"possibleFalsePositive");Object.seal(this),e&&Object.assign(this,e)}},S={getLocalHintsForElement(t){let e=t.tagName.toLowerCase?.()||"",n=!1,o=!1,r=!1,i=[],h=[],m=null;if(e==="img"){let l=t.getAttribute("usemap");if(l){let c=t.getClientRects();l=l.replace(/^#/,"").replace(\'"\',\'\\\\"\');let d=document.querySelector(`map[name="${l}"]`);if(d&&c.length>0){n=!0;let p=d.getElementsByTagName("area"),g=f.getClientRectsForAreas(c[0],p);g=g.map(N=>Object.assign(N,{image:t})),h.push(...g)}}}let s=t.getAttribute("aria-disabled");if(s&&["","true"].includes(s.toLowerCase()))return[];if(this.checkForAngularJs||(this.checkForAngularJs=function(){if(document.getElementsByClassName("ng-scope").length===0)return()=>!1;{let c=[];for(let d of["","data-","x-"])for(let p of["-",":","_"])c.push(`${d}ng${p}click`);return function(d){for(let p of c)if(d.hasAttribute(p))return!0;return!1}}}()),n||(n=this.checkForAngularJs(t)),t.hasAttribute("onclick"))n=!0;else{let l=t.getAttribute("role"),c=["button","tab","link","checkbox","menuitem","menuitemcheckbox","menuitemradio","radio"];if(l!=null&&c.includes(l.toLowerCase()))n=!0;else{let d=t.getAttribute("contentEditable");d!=null&&["","contenteditable","true","plaintext-only"].includes(d.toLowerCase())&&(n=!0)}}if(!n&&t.hasAttribute("jsaction")){let l=t.getAttribute("jsaction").split(";");for(let c of l){let d=c.trim().split(":");if(d.length>=1&&d.length<=2){let[p,g,N]=d.length===1?["click",...d[0].trim().split("."),"_"]:[d[0],...d[1].trim().split("."),"_"];n||(n=p==="click"&&g!=="none"&&N!=="_")}}}switch(e){case"a":n=!0;break;case"textarea":n||=!t.disabled&&!t.readOnly;break;case"input":n||=!(t.getAttribute("type")?.toLowerCase()=="hidden"||t.disabled||t.readOnly&&f.isSelectable(t));break;case"button":case"select":n||=!t.disabled;break;case"object":case"embed":n=!0;break;case"label":n||=t.control!=null&&!t.control.disabled&&this.getLocalHintsForElement(t.control).length===0;break;case"body":n||=t===document.body&&!x()&&window.innerWidth>3&&window.innerHeight>3&&(document.body!=null?document.body.tagName.toLowerCase():void 0)!=="frameset"?m="Frame.":void 0,n||=t===document.body&&x()&&M.isScrollableElement(t)?m="Scroll.":void 0;break;case"img":n||=["zoom-in","zoom-out"].includes(t.style.cursor);break;case"div":case"ol":case"ul":n||=t.clientHeight<t.scrollHeight&&M.isScrollableElement(t)?m="Scroll.":void 0;break;case"details":n=!0,m="Open.";break}let a=t.getAttribute("class");!n&&a?.toLowerCase().includes("button")&&(n=!0,r=!0);let u=t.getAttribute("tabindex"),w=u?parseInt(u):-1;if(!n&&!(w<0)&&!isNaN(w)&&(n=!0,o=!0),n)if(h.length>0){let l=h.map(c=>new L({element:c.element,image:t,rect:c.rect,secondClassCitizen:o,possibleFalsePositive:r,reason:m}));i.push(...l)}else{let l=f.getVisibleClientRect(t,!0);if(l!==null){let c=new L({element:t,rect:l,secondClassCitizen:o,possibleFalsePositive:r,reason:m});i.push(c)}}return i},getElementFromPoint(t,e,n,o){n==null&&(n=document),o==null&&(o=[]);let r=n.elementsFromPoint?n.elementsFromPoint(t,e)[0]:n.elementFromPoint(t,e);return o.includes(r)?r:(o.push(r),r&&r.shadowRoot?S.getElementFromPoint(t,e,r.shadowRoot,o):r)},getLocalHints(t){if(!document.body)return[];let e=(s,a)=>{a==null&&(a=[]);for(let u of Array.from(s.querySelectorAll("*")))a.push(u),u.shadowRoot&&e(u.shadowRoot,a);return a},n=e(document.body),o=[];for(let s of Array.from(n))if(!t||s.href){let a=this.getLocalHintsForElement(s);o.push(...a)}o=o.reverse();let r=[1,2,3];o=o.filter((s,a)=>{if(!s.possibleFalsePositive)return!0;let w=Math.max(0,a-6);for(;w<a;){let l=o[w].element;for(let c of r)if(l=l?.parentElement,l===s.element)return!1;w+=1}return!0});let i=o.filter(s=>{if(s.secondClassCitizen)return!1;let a=s.rect,u=S.getElementFromPoint(a.left+a.width*.5,a.top+a.height*.5);if(u&&(s.element.contains(u)||u.contains(s.element))||s.element.localName=="area"&&u==s.image)return!0;let l=[a.top+.1,a.bottom-.1],c=[a.left+.1,a.right-.1];for(let d of l)for(let p of c){let g=S.getElementFromPoint(p,d);if(g&&(s.element.contains(g)||g.contains(s.element)))return!0}});i.reverse();let{top:h,left:m}=f.getViewportTopLeft();for(let s of i)s.rect.top+=h,s.rect.left+=m;return i}};var A=class{constructor(){this.hints=null;this.hintMarkers=null;this.markersDiv=null;this.enrichedMarkers=null}reset(){this.removeMarkers(),this.hints=null,this.hintMarkers=null,this.markersDiv=null}async capture(){this.reset(),this.createMarkers(),this.displayMarkers()}createMarkers(){this.hints=S.getLocalHints(),this.hintMarkers=new Map,this.hints.forEach((e,n)=>{let o=f.createElement("div"),r=e.element.attributes["data-momentic-id"]?.value??void 0;if(!r){console.warn(`[MOMENTIC] No data-momentic-id found for interactive element ${e.element.outerHTML}`);return}o.style.left=e.rect.left+"px",o.style.top=e.rect.top+"px",o.style.zIndex=214e7+n,o.className="vimiumReset internalVimiumHintMarker vimiumHintMarker",z(o,r),this.hintMarkers.set(r,{hint:e,marker:o})})}enrichMarkers(){if(this.hintMarkers){this.enrichedMarkers=[];for(let[e,n]of this.hintMarkers)this.enrichedMarkers.push(Object.assign(R.describe(n.hint.element),{hintString:e}))}}displayMarkers(){this.hintMarkers&&(this.markersDiv||(this.markersDiv=f.addElementsToPage(Array.from(this.hintMarkers.values()).map(e=>e.marker),{id:"vimiumHintMarkerContainer",className:"vimiumReset"})))}removeMarkers(){this.markersDiv&&(f.removeElement(this.markersDiv),this.markersDiv=null)}toggleMarkers(){this.markersDiv?this.removeMarkers():this.displayMarkers()}},z=(t,e)=>{for(let n of e){let o=document.createElement("span");o.className="vimiumReset",o.textContent=n,t.appendChild(o)}};window.HintManager=A;\n',vimiumCss:'.vimiumReset,a.vimiumReset,a:hover.vimiumReset,a:link.vimiumReset,a:visited.vimiumReset,div.vimiumReset,span.vimiumReset,table.vimiumReset,td.vimiumReset,tr.vimiumReset{background:none;border:none;bottom:auto;box-shadow:none;color:#000;cursor:auto;display:inline;float:none;font-family:Helvetica Neue,Helvetica,Arial,sans-serif;font-size:inherit;font-style:normal;font-variant:normal;font-weight:400;height:auto;left:auto;letter-spacing:0;line-height:100%;margin:0;max-height:none;max-width:none;min-height:0;min-width:0;opacity:1;padding:0;position:static;right:auto;text-align:left;text-decoration:none;text-indent:0;text-shadow:none;text-transform:none;top:auto;vertical-align:baseline;white-space:normal;width:auto;z-index:2140000000}tbody.vimiumReset,thead.vimiumReset{display:table-header-group}tbody.vimiumReset{display:table-row-group}div.internalVimiumHintMarker{background:linear-gradient(180deg,#fff785 0,#ffc542);border:1px solid #c38a22;border-radius:3px;box-shadow:0 3px 7px 0 rgba(0,0,0,.3);display:block;font-size:11px;left:-1px;overflow:hidden;padding:1px 3px 0;position:absolute;top:-1px;white-space:nowrap}div.internalVimiumHintMarker span{color:#302505;font-family:Helvetica,Arial,sans-serif;font-size:11px;font-weight:700;text-shadow:0 1px 0 hsla(0,0%,100%,.6)}div.internalVimiumHintMarker>.matchingCharacter{color:#d4ac3a}div>.vimiumActiveHintMarker span{color:#a07555!important}div.internalVimiumInputHint{background-color:rgba(255,247,133,.3);border:1px solid #c38a22;display:block;pointer-events:none;position:absolute}div.internalVimiumSelectedInputHint{background-color:hsla(0,100%,70%,.3);border:1px solid #933!important}div.internalVimiumSelectedInputHint span{color:#fff!important}div.vimiumHighlightedFrame{border:5px solid #ff0;box-sizing:border-box;margin:0;pointer-events:none}div.vimiumHighlightedFrame,iframe.vimiumHelpDialogFrame{height:100%;left:0;padding:0;position:fixed;top:0;width:100%}iframe.vimiumHelpDialogFrame{background-color:hsla(0,0%,4%,.6);border:none;display:block;z-index:2139999997}div#vimiumHelpDialogContainer{background-color:#fff;border:2px solid #b3b3b3;border-radius:6px;margin:50px auto;max-height:calc(100% - 100px);max-width:calc(100% - 100px);opacity:1;overflow-x:auto;overflow-y:auto;width:840px}div#vimiumHelpDialog{min-width:600px;padding:8px 12px}span#vimiumTitle,span#vimiumTitle *,span#vimiumTitle span{font-size:20px}#vimiumTitle{display:block;line-height:130%;white-space:nowrap}td.vimiumHelpDialogTopButtons{text-align:right;width:100%}#helpDialogOptionsPage,#helpDialogWikiPage{font-size:14px;padding-left:5px;padding-right:5px}div.vimiumColumn{float:left;font-size:11px;line-height:130%;width:50%}div.vimiumColumn tr{display:table-row}div.vimiumColumn td{display:table-cell;font-size:11px;line-height:130%}div.vimiumColumn table,div.vimiumColumn td,div.vimiumColumn tr{margin:0;padding:0}div.vimiumColumn table{table-layout:auto;width:100%}div.vimiumColumn td{padding:1px;vertical-align:top}div#vimiumHelpDialog div.vimiumColumn tr>td:first-of-type{font-family:Helvetica Neue,Helvetica,Arial,sans-serif;font-size:14px;text-align:right;white-space:nowrap}span.vimiumHelpDialogKey{background-color:#f3f3f3;border:1px solid;border-color:#ccc #ccc #bbb;border-radius:3px;box-shadow:inset 0 -1px 0 #bbb;color:#212121;font-family:monospace;font-size:11px;margin-left:2px;padding:1px 4px}div#vimiumHelpDialog div.vimiumColumn tr>td:nth-of-type(3){width:100%}div#vimiumHelpDialog div.vimiumDivider{background-color:#9a9a9a;display:block;height:1px;margin:10px auto;width:100%}div#vimiumHelpDialog td.vimiumHelpSectionTitle{font-family:Helvetica Neue,Helvetica,Arial,sans-serif;font-size:16px;font-weight:700;padding-top:3px}div#vimiumHelpDialog td.vimiumHelpDescription{font-family:Helvetica Neue,Helvetica,Arial,sans-serif;font-size:14px}div#vimiumHelpDialog span.vimiumCopyCommandNameName{cursor:pointer;font-size:12px;font-style:italic}div#vimiumHelpDialog tr.advanced{display:none}div#vimiumHelpDialog.showAdvanced tr.advanced{display:table-row}div#vimiumHelpDialog div.advanced td:nth-of-type(3){color:#555}div#vimiumHelpDialog a.closeButton{color:#555;cursor:pointer;font-family:courier new;font-size:24px;font-weight:700;padding-left:5px;position:relative;text-decoration:none;top:3px}div#vimiumHelpDialog a{text-decoration:underline}div#vimiumHelpDialog a.closeButton:hover{color:#000;-webkit-user-select:none}div#vimiumHelpDialogFooter{display:block;margin-bottom:37px;position:relative}table.helpDialogBottom{width:100%}td.helpDialogBottomRight{float:right;text-align:right;width:100%}td.helpDialogBottomLeft,td.helpDialogBottomRight{padding:0}div#vimiumHelpDialogFooter *{font-size:10px}a#toggleAdvancedCommands,span#help-dialog-tip{font-size:10px;position:relative;top:19px;white-space:nowrap}a#toggleAdvancedCommands,a:active.vimiumHelDialogLink,a:hover.vimiumHelDialogLink,a:link.vimiumHelDialogLink,a:visited.vimiumHelDialogLink{color:#2f508e;cursor:pointer;text-decoration:underline}div.vimiumHUD{background:#f1f1f1;border:1px solid #aaa;border-radius:4px;bottom:8px;box-shadow:0 2px 10px rgba(0,0,0,.8);display:block;left:8px;position:fixed;text-align:left;width:calc(100% - 20px);z-index:2139999999}iframe.vimiumHUDFrame{background-color:transparent;border:none;bottom:-14px;display:block;height:58px;margin:0 0 0 -40%;min-width:300px;opacity:0;overflow:hidden;padding:0;position:fixed;right:20px;width:20%;z-index:2139999998}div.vimiumHUD .vimiumHUDSearchArea{background-color:#f1f1f1;border-radius:4px 4px 0 0;display:block;padding:3px}div.vimiumHUD .vimiumHUDSearchAreaInner{border-radius:3px;box-sizing:border-box;color:#777;font-family:Helvetica Neue,Helvetica,Arial,sans-serif;font-size:14px;height:30px;line-height:20px;margin-bottom:0;outline:none;padding:2px 4px;width:100%}div.vimiumHUD .hud-find{background:#fff;border:1px solid #ccc}div.vimiumHUD span#hud-find-input,div.vimiumHUD span#hud-match-count{color:#000;display:inline;outline:none;overflow-y:hidden;white-space:nowrap}div.vimiumHUD span#hud-find-input:before{content:"/"}div.vimiumHUD span#hud-match-count{color:#aaa;font-size:12px}div.vimiumHUD span#hud-find-input br{display:none}div.vimiumHUD span#hud-find-input *{display:inline;white-space:nowrap}body.vimiumFindMode ::selection{background:#ff9632}iframe.vomnibarFrame{background-color:transparent;border:none;display:block;font-family:sans-serif;height:calc(100% - 70px);left:50%;margin:0 0 0 -40%;min-width:400px;overflow:hidden;padding:0;position:fixed;top:70px;width:calc(80% + 20px);z-index:2139999998}div.vimiumFlash{background-color:transparent;box-shadow:0 0 4px 2px #4183c4;padding:1px;position:absolute;z-index:2140000000}iframe.vimiumUIComponentHidden{display:none}iframe.vimiumUIComponentVisible{color-scheme:light dark;display:block}iframe.vimiumUIComponentReactivated{border:5px solid #ff0}iframe.vimiumNonClickable{pointer-events:none}@media (prefers-color-scheme:dark){iframe.reverseDarkReaderFilter{-webkit-filter:invert(100%) hue-rotate(180deg)!important;filter:invert(100%) hue-rotate(180deg)!important}body.vimiumBody{background-color:#292a2d;color:#fff}body.vimiumBody a,body.vimiumBody a:visited{color:#8ab4f8}body.vimiumBody input,body.vimiumBody textarea{background-color:#1d1d1f;border-color:#1d1d1f;color:#e8eaed}body.vimiumBody div.example{color:#9aa0a6}body.vimiumBody div#footer,body.vimiumBody div#state,div#vimiumHelpDialogContainer{background-color:#202124;border-color:hsla(0,0%,100%,.1)}div#vimiumHelpDialog{background-color:#292a2d;color:#fff}div#vimiumHelpDialog td.vimiumHelpDescription{color:#c9cccf}div#vimiumHelpDialog td.vimiumHelpSectionTitle,span#vimiumTitle{color:#fff}#vimiumTitle>span:first-child{color:#8ab4f8!important}div#vimiumHelpDialog a{color:#8ab4f8}div#vimiumHelpDialog div.vimiumDivider{background-color:hsla(0,0%,100%,.1)}span.vimiumHelpDialogKey{background-color:#1d1d1f;border:1px solid #000;box-shadow:none;color:#fff}}',htmlUtilsLibJs:`// src/html/constants.ts
24
+ `,Pd(s,e),`To resolve the conflict:
25
+ `,Od(s,e))}}catch(u){n={error:u}}finally{try{l&&!l.done&&(o=a.return)&&o.call(a)}finally{if(n)throw n.error}}return i},r}();var cb=function(){function r(e){this._backingStorages=e}return r.prototype.record=function(e,t,n,o){this._backingStorages.forEach(function(i){i.record(e,t,n,o)})},r}();he();he();var ub=function(){function r(e,t){this._instrumentName=e,this._valueType=t,this._buffer=new Jt}return r.prototype.observe=function(e,t){if(t===void 0&&(t={}),typeof e!="number"){F.warn("non-number value provided to metric "+this._instrumentName+": "+e);return}this._valueType===_t.INT&&!Number.isInteger(e)&&(F.warn("INT value type cannot accept a floating-point value for "+this._instrumentName+", ignoring the fractional digits."),e=Math.trunc(e),!Number.isInteger(e))||this._buffer.set(t,e)},r}();var db=function(){function r(){this._buffer=new Map}return r.prototype.observe=function(e,t,n){if(n===void 0&&(n={}),!!ta(e)){var o=this._buffer.get(e);if(o==null&&(o=new Jt,this._buffer.set(e,o)),typeof t!="number"){F.warn("non-number value provided to metric "+e._descriptor.name+": "+t);return}e._descriptor.valueType===_t.INT&&!Number.isInteger(t)&&(F.warn("INT value type cannot accept a floating-point value for "+e._descriptor.name+", ignoring the fractional digits."),t=Math.trunc(t),!Number.isInteger(t))||o.set(n,t)}},r}();var Nd=function(r,e,t,n){function o(i){return i instanceof t?i:new t(function(a){a(i)})}return new(t||(t=Promise))(function(i,a){function l(u){try{s(n.next(u))}catch(d){a(d)}}function c(u){try{s(n.throw(u))}catch(d){a(d)}}function s(u){u.done?i(u.value):o(u.value).then(l,c)}s((n=n.apply(r,e||[])).next())})},Dd=function(r,e){var t={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},n,o,i,a;return a={next:l(0),throw:l(1),return:l(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function l(s){return function(u){return c([s,u])}}function c(s){if(n)throw new TypeError("Generator is already executing.");for(;t;)try{if(n=1,o&&(i=s[0]&2?o.return:s[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,s[1])).done)return i;switch(o=0,i&&(s=[s[0]&2,i.value]),s[0]){case 0:case 1:i=s;break;case 4:return t.label++,{value:s[1],done:!1};case 5:t.label++,o=s[1],s=[0];continue;case 7:s=t.ops.pop(),t.trys.pop();continue;default:if(i=t.trys,!(i=i.length>0&&i[i.length-1])&&(s[0]===6||s[0]===2)){t=0;continue}if(s[0]===3&&(!i||s[1]>i[0]&&s[1]<i[3])){t.label=s[1];break}if(s[0]===6&&t.label<i[1]){t.label=i[1],i=s;break}if(i&&t.label<i[2]){t.label=i[2],t.ops.push(s);break}i[2]&&t.ops.pop(),t.trys.pop();continue}s=e.call(r,t)}catch(u){s=[6,u],o=0}finally{n=i=0}if(s[0]&5)throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}},pb=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},mb=function(r,e,t){if(t||arguments.length===2)for(var n=0,o=e.length,i;n<o;n++)(i||!(n in e))&&(i||(i=Array.prototype.slice.call(e,0,n)),i[n]=e[n]);return r.concat(i||Array.prototype.slice.call(e))},gb=function(){function r(){this._callbacks=[],this._batchCallbacks=[]}return r.prototype.addCallback=function(e,t){var n=this._findCallback(e,t);n>=0||this._callbacks.push({callback:e,instrument:t})},r.prototype.removeCallback=function(e,t){var n=this._findCallback(e,t);n<0||this._callbacks.splice(n,1)},r.prototype.addBatchCallback=function(e,t){var n=new Set(t.filter(ta));if(n.size===0){F.error("BatchObservableCallback is not associated with valid instruments",t);return}var o=this._findBatchCallback(e,n);o>=0||this._batchCallbacks.push({callback:e,instruments:n})},r.prototype.removeBatchCallback=function(e,t){var n=new Set(t.filter(ta)),o=this._findBatchCallback(e,n);o<0||this._batchCallbacks.splice(o,1)},r.prototype.observe=function(e,t){return Nd(this,void 0,void 0,function(){var n,o,i,a;return Dd(this,function(l){switch(l.label){case 0:return n=this._observeCallbacks(e,t),o=this._observeBatchCallbacks(e,t),[4,pE(mb(mb([],pb(n),!1),pb(o),!1))];case 1:return i=l.sent(),a=i.filter(mE).map(function(c){return c.reason}),[2,a]}})})},r.prototype._observeCallbacks=function(e,t){var n=this;return this._callbacks.map(function(o){var i=o.callback,a=o.instrument;return Nd(n,void 0,void 0,function(){var l,c;return Dd(this,function(s){switch(s.label){case 0:return l=new ub(a._descriptor.name,a._descriptor.valueType),c=Promise.resolve(i(l)),t!=null&&(c=Jr(c,t)),[4,c];case 1:return s.sent(),a._metricStorages.forEach(function(u){u.record(l._buffer,e)}),[2]}})})})},r.prototype._observeBatchCallbacks=function(e,t){var n=this;return this._batchCallbacks.map(function(o){var i=o.callback,a=o.instruments;return Nd(n,void 0,void 0,function(){var l,c;return Dd(this,function(s){switch(s.label){case 0:return l=new db,c=Promise.resolve(i(l)),t!=null&&(c=Jr(c,t)),[4,c];case 1:return s.sent(),a.forEach(function(u){var d=l._buffer.get(u);d!=null&&u._metricStorages.forEach(function(p){p.record(d,e)})}),[2]}})})})},r.prototype._findCallback=function(e,t){return this._callbacks.findIndex(function(n){return n.callback===e&&n.instrument===t})},r.prototype._findBatchCallback=function(e,t){return this._batchCallbacks.findIndex(function(n){return n.callback===e&&gE(n.instruments,t)})},r}();var wO=function(){var r=function(e,t){return r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,o){n.__proto__=o}||function(n,o){for(var i in o)Object.prototype.hasOwnProperty.call(o,i)&&(n[i]=o[i])},r(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");r(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}}(),hb=function(r){wO(e,r);function e(t,n,o,i,a){var l=r.call(this,t)||this;return l._attributesProcessor=o,l._aggregationCardinalityLimit=a,l._deltaMetricStorage=new ml(n,l._aggregationCardinalityLimit),l._temporalMetricStorage=new gl(n,i),l}return e.prototype.record=function(t,n,o,i){n=this._attributesProcessor.process(n,o),this._deltaMetricStorage.record(t,n,o,i)},e.prototype.collect=function(t,n){var o=this._deltaMetricStorage.collect();return this._temporalMetricStorage.buildMetrics(t,this._instrumentDescriptor,o,n)},e}(pl);var fb=function(){var r=function(e,t){return r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,o){n.__proto__=o}||function(n,o){for(var i in o)Object.prototype.hasOwnProperty.call(o,i)&&(n[i]=o[i])},r(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");r(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}}(),Po=function(){function r(){}return r.Noop=function(){return xO},r}();var CO=function(r){fb(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.process=function(t,n){return t},e}(Po);var Sb=function(r){fb(e,r);function e(t){var n=r.call(this)||this;return n._allowedAttributeNames=t,n}return e.prototype.process=function(t,n){var o=this,i={};return Object.keys(t).filter(function(a){return o._allowedAttributeNames.includes(a)}).forEach(function(a){return i[a]=t[a]}),i},e}(Po);var xO=new CO;var _O=function(r,e,t,n){function o(i){return i instanceof t?i:new t(function(a){a(i)})}return new(t||(t=Promise))(function(i,a){function l(u){try{s(n.next(u))}catch(d){a(d)}}function c(u){try{s(n.throw(u))}catch(d){a(d)}}function s(u){u.done?i(u.value):o(u.value).then(l,c)}s((n=n.apply(r,e||[])).next())})},MO=function(r,e){var t={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},n,o,i,a;return a={next:l(0),throw:l(1),return:l(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function l(s){return function(u){return c([s,u])}}function c(s){if(n)throw new TypeError("Generator is already executing.");for(;t;)try{if(n=1,o&&(i=s[0]&2?o.return:s[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,s[1])).done)return i;switch(o=0,i&&(s=[s[0]&2,i.value]),s[0]){case 0:case 1:i=s;break;case 4:return t.label++,{value:s[1],done:!1};case 5:t.label++,o=s[1],s=[0];continue;case 7:s=t.ops.pop(),t.trys.pop();continue;default:if(i=t.trys,!(i=i.length>0&&i[i.length-1])&&(s[0]===6||s[0]===2)){t=0;continue}if(s[0]===3&&(!i||s[1]>i[0]&&s[1]<i[3])){t.label=s[1];break}if(s[0]===6&&t.label<i[1]){t.label=i[1],i=s;break}if(i&&t.label<i[2]){t.label=i[2],t.ops.push(s);break}i[2]&&t.ops.pop(),t.trys.pop();continue}s=e.call(r,t)}catch(u){s=[6,u],o=0}finally{n=i=0}if(s[0]&5)throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}},IO=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},yb=function(){function r(e,t){this._meterProviderSharedState=e,this._instrumentationScope=t,this.metricStorageRegistry=new lb,this.observableRegistry=new gb,this.meter=new ob(this)}return r.prototype.registerMetricStorage=function(e){var t=this._registerMetricStorage(e,hb);return t.length===1?t[0]:new cb(t)},r.prototype.registerAsyncMetricStorage=function(e){var t=this._registerMetricStorage(e,sb);return t},r.prototype.collect=function(e,t,n){return _O(this,void 0,void 0,function(){var o,i,a;return MO(this,function(l){switch(l.label){case 0:return[4,this.observableRegistry.observe(t,n?.timeoutMillis)];case 1:return o=l.sent(),i=this.metricStorageRegistry.getStorages(e),i.length===0?[2,null]:(a=i.map(function(c){return c.collect(e,t)}).filter(uE),a.length===0?[2,{errors:o}]:[2,{scopeMetrics:{scope:this._instrumentationScope,metrics:a},errors:o}])}})})},r.prototype._registerMetricStorage=function(e,t){var n=this,o=this._meterProviderSharedState.viewRegistry.findViews(e,this._instrumentationScope),i=o.map(function(c){var s=SE(c,e),u=n.metricStorageRegistry.findOrUpdateCompatibleStorage(s);if(u!=null)return u;var d=c.aggregation.createAggregator(s),p=new t(s,d,c.attributesProcessor,n._meterProviderSharedState.metricCollectors,c.aggregationCardinalityLimit);return n.metricStorageRegistry.register(p),p});if(i.length===0){var a=this._meterProviderSharedState.selectAggregations(e.type),l=a.map(function(c){var s=IO(c,2),u=s[0],d=s[1],p=n.metricStorageRegistry.findOrUpdateCompatibleCollectorStorage(u,e);if(p!=null)return p;var m=d.createAggregator(e),g=u.selectCardinalityLimit(e.type),h=new t(e,m,Po.Noop(),[u],g);return n.metricStorageRegistry.registerForCollector(u,h),h});i=i.concat(l)}return i},r}();var PO=function(r){var e=typeof Symbol=="function"&&Symbol.iterator,t=e&&r[e],n=0;if(t)return t.call(r);if(r&&typeof r.length=="number")return{next:function(){return r&&n>=r.length&&(r=void 0),{value:r&&r[n++],done:!r}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")},Eb=function(){function r(e){this.resource=e,this.viewRegistry=new XE,this.metricCollectors=[],this.meterSharedStates=new Map}return r.prototype.getMeterSharedState=function(e){var t=dE(e),n=this.meterSharedStates.get(t);return n==null&&(n=new yb(this,e),this.meterSharedStates.set(t,n)),n},r.prototype.selectAggregations=function(e){var t,n,o=[];try{for(var i=PO(this.metricCollectors),a=i.next();!a.done;a=i.next()){var l=a.value;o.push([l,l.selectAggregation(e)])}}catch(c){t={error:c}}finally{try{a&&!a.done&&(n=i.return)&&n.call(i)}finally{if(t)throw t.error}}return o},r}();var hl=function(r,e,t,n){function o(i){return i instanceof t?i:new t(function(a){a(i)})}return new(t||(t=Promise))(function(i,a){function l(u){try{s(n.next(u))}catch(d){a(d)}}function c(u){try{s(n.throw(u))}catch(d){a(d)}}function s(u){u.done?i(u.value):o(u.value).then(l,c)}s((n=n.apply(r,e||[])).next())})},fl=function(r,e){var t={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},n,o,i,a;return a={next:l(0),throw:l(1),return:l(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function l(s){return function(u){return c([s,u])}}function c(s){if(n)throw new TypeError("Generator is already executing.");for(;t;)try{if(n=1,o&&(i=s[0]&2?o.return:s[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,s[1])).done)return i;switch(o=0,i&&(s=[s[0]&2,i.value]),s[0]){case 0:case 1:i=s;break;case 4:return t.label++,{value:s[1],done:!1};case 5:t.label++,o=s[1],s=[0];continue;case 7:s=t.ops.pop(),t.trys.pop();continue;default:if(i=t.trys,!(i=i.length>0&&i[i.length-1])&&(s[0]===6||s[0]===2)){t=0;continue}if(s[0]===3&&(!i||s[1]>i[0]&&s[1]<i[3])){t.label=s[1];break}if(s[0]===6&&t.label<i[1]){t.label=i[1],i=s;break}if(i&&t.label<i[2]){t.label=i[2],t.ops.push(s);break}i[2]&&t.ops.pop(),t.trys.pop();continue}s=e.call(r,t)}catch(u){s=[6,u],o=0}finally{n=i=0}if(s[0]&5)throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}},OO=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},LO=function(r,e,t){if(t||arguments.length===2)for(var n=0,o=e.length,i;n<o;n++)(i||!(n in e))&&(i||(i=Array.prototype.slice.call(e,0,n)),i[n]=e[n]);return r.concat(i||Array.prototype.slice.call(e))},bb=function(){function r(e,t){this._sharedState=e,this._metricReader=t}return r.prototype.collect=function(e){return hl(this,void 0,void 0,function(){var t,n,o,i,a=this;return fl(this,function(l){switch(l.label){case 0:return t=On(Date.now()),n=[],o=[],i=Array.from(this._sharedState.meterSharedStates.values()).map(function(c){return hl(a,void 0,void 0,function(){var s;return fl(this,function(u){switch(u.label){case 0:return[4,c.collect(this,t,e)];case 1:return s=u.sent(),s?.scopeMetrics!=null&&n.push(s.scopeMetrics),s?.errors!=null&&o.push.apply(o,LO([],OO(s.errors),!1)),[2]}})})}),[4,Promise.all(i)];case 1:return l.sent(),[2,{resourceMetrics:{resource:this._sharedState.resource,scopeMetrics:n},errors:o}]}})})},r.prototype.forceFlush=function(e){return hl(this,void 0,void 0,function(){return fl(this,function(t){switch(t.label){case 0:return[4,this._metricReader.forceFlush(e)];case 1:return t.sent(),[2]}})})},r.prototype.shutdown=function(e){return hl(this,void 0,void 0,function(){return fl(this,function(t){switch(t.label){case 0:return[4,this._metricReader.shutdown(e)];case 1:return t.sent(),[2]}})})},r.prototype.selectAggregationTemporality=function(e){return this._metricReader.selectAggregationTemporality(e)},r.prototype.selectAggregation=function(e){return this._metricReader.selectAggregation(e)},r.prototype.selectCardinalityLimit=function(e){var t,n,o;return(o=(n=(t=this._metricReader).selectCardinalityLimit)===null||n===void 0?void 0:n.call(t,e))!==null&&o!==void 0?o:2e3},r}();var Tb=function(r,e,t,n){function o(i){return i instanceof t?i:new t(function(a){a(i)})}return new(t||(t=Promise))(function(i,a){function l(u){try{s(n.next(u))}catch(d){a(d)}}function c(u){try{s(n.throw(u))}catch(d){a(d)}}function s(u){u.done?i(u.value):o(u.value).then(l,c)}s((n=n.apply(r,e||[])).next())})},vb=function(r,e){var t={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},n,o,i,a;return a={next:l(0),throw:l(1),return:l(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function l(s){return function(u){return c([s,u])}}function c(s){if(n)throw new TypeError("Generator is already executing.");for(;t;)try{if(n=1,o&&(i=s[0]&2?o.return:s[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,s[1])).done)return i;switch(o=0,i&&(s=[s[0]&2,i.value]),s[0]){case 0:case 1:i=s;break;case 4:return t.label++,{value:s[1],done:!1};case 5:t.label++,o=s[1],s=[0];continue;case 7:s=t.ops.pop(),t.trys.pop();continue;default:if(i=t.trys,!(i=i.length>0&&i[i.length-1])&&(s[0]===6||s[0]===2)){t=0;continue}if(s[0]===3&&(!i||s[1]>i[0]&&s[1]<i[3])){t.label=s[1];break}if(s[0]===6&&t.label<i[1]){t.label=i[1],i=s;break}if(i&&t.label<i[2]){t.label=i[2],t.ops.push(s);break}i[2]&&t.ops.pop(),t.trys.pop();continue}s=e.call(r,t)}catch(u){s=[6,u],o=0}finally{n=i=0}if(s[0]&5)throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}},Ab=function(r){var e=typeof Symbol=="function"&&Symbol.iterator,t=e&&r[e],n=0;if(t)return t.call(r);if(r&&typeof r.length=="number")return{next:function(){return r&&n>=r.length&&(r=void 0),{value:r&&r[n++],done:!r}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")};function NO(r,e){var t=e??cl.empty();return r?cl.default().merge(t):t}var kd=function(){function r(e){var t,n,o,i,a;if(this._shutdown=!1,this._sharedState=new Eb(NO((a=e?.mergeResourceWithDefaults)!==null&&a!==void 0?a:!0,e?.resource)),e?.views!=null&&e.views.length>0)try{for(var l=Ab(e.views),c=l.next();!c.done;c=l.next()){var s=c.value;this._sharedState.viewRegistry.addView(s)}}catch(m){t={error:m}}finally{try{c&&!c.done&&(n=l.return)&&n.call(l)}finally{if(t)throw t.error}}if(e?.readers!=null&&e.readers.length>0)try{for(var u=Ab(e.readers),d=u.next();!d.done;d=u.next()){var p=d.value;this.addMetricReader(p)}}catch(m){o={error:m}}finally{try{d&&!d.done&&(i=u.return)&&i.call(u)}finally{if(o)throw o.error}}}return r.prototype.getMeter=function(e,t,n){return t===void 0&&(t=""),n===void 0&&(n={}),this._shutdown?(F.warn("A shutdown MeterProvider cannot provide a Meter"),Gu()):this._sharedState.getMeterSharedState({name:e,version:t,schemaUrl:n.schemaUrl}).meter},r.prototype.addMetricReader=function(e){var t=new bb(this._sharedState,e);e.setMetricProducer(t),this._sharedState.metricCollectors.push(t)},r.prototype.shutdown=function(e){return Tb(this,void 0,void 0,function(){return vb(this,function(t){switch(t.label){case 0:return this._shutdown?(F.warn("shutdown may only be called once per MeterProvider"),[2]):(this._shutdown=!0,[4,Promise.all(this._sharedState.metricCollectors.map(function(n){return n.shutdown(e)}))]);case 1:return t.sent(),[2]}})})},r.prototype.forceFlush=function(e){return Tb(this,void 0,void 0,function(){return vb(this,function(t){switch(t.label){case 0:return this._shutdown?(F.warn("invalid attempt to force flush after MeterProvider shutdown"),[2]):[4,Promise.all(this._sharedState.metricCollectors.map(function(n){return n.forceFlush(e)}))];case 1:return t.sent(),[2]}})})},r}();var DO=/[\^$\\.+?()[\]{}|]/g,Sl=function(){function r(e){e==="*"?(this._matchAll=!0,this._regexp=/.*/):(this._matchAll=!1,this._regexp=new RegExp(r.escapePattern(e)))}return r.prototype.match=function(e){return this._matchAll?!0:this._regexp.test(e)},r.escapePattern=function(e){return"^"+e.replace(DO,"\\$&").replace("*",".*")+"$"},r.hasWildcard=function(e){return e.includes("*")},r}();var Oo=function(){function r(e){this._matchAll=e===void 0,this._pattern=e}return r.prototype.match=function(e){return!!(this._matchAll||e===this._pattern)},r}();var Rb=function(){function r(e){var t;this._nameFilter=new Sl((t=e?.name)!==null&&t!==void 0?t:"*"),this._type=e?.type,this._unitFilter=new Oo(e?.unit)}return r.prototype.getType=function(){return this._type},r.prototype.getNameFilter=function(){return this._nameFilter},r.prototype.getUnitFilter=function(){return this._unitFilter},r}();var wb=function(){function r(e){this._nameFilter=new Oo(e?.name),this._versionFilter=new Oo(e?.version),this._schemaUrlFilter=new Oo(e?.schemaUrl)}return r.prototype.getNameFilter=function(){return this._nameFilter},r.prototype.getVersionFilter=function(){return this._versionFilter},r.prototype.getSchemaUrlFilter=function(){return this._schemaUrlFilter},r}();function kO(r){return r.instrumentName==null&&r.instrumentType==null&&r.instrumentUnit==null&&r.meterName==null&&r.meterVersion==null&&r.meterSchemaUrl==null}var Ud=function(){function r(e){var t;if(kO(e))throw new Error("Cannot create view with no selector arguments supplied");if(e.name!=null&&(e?.instrumentName==null||Sl.hasWildcard(e.instrumentName)))throw new Error("Views with a specified name must be declared with an instrument selector that selects at most one instrument per meter.");e.attributeKeys!=null?this.attributesProcessor=new Sb(e.attributeKeys):this.attributesProcessor=Po.Noop(),this.name=e.name,this.description=e.description,this.aggregation=(t=e.aggregation)!==null&&t!==void 0?t:Vt.Default(),this.instrumentSelector=new Rb({name:e.instrumentName,type:e.instrumentType,unit:e.instrumentUnit}),this.meterSelector=new wb({name:e.meterName,version:e.meterVersion,schemaUrl:e.meterSchemaUrl}),this.aggregationCardinalityLimit=e.aggregationCardinalityLimit}return r}();var hne=process.env.APP||"unknown";he();import{v4 as UO}from"uuid";function FO(){return new sE({url:"https://us-west.metrics.momentic.ai/v1/metrics",headers:{"x-momentic-metrics-api-key":"c60c6a0f-60da-41a7-a61b-07969a0aa303"},temporalityPreference:In.DELTA})}var BO=[new Ud({instrumentName:"test_operation_duration_ms",instrumentType:oe.HISTOGRAM,aggregation:new il([100,500,1e3,5e3,1e4,2e4])})],yl=class{globalAttributes;provider;meter;counterCache=new Map;histogramCache=new Map;observableGaugeCache=new Map;gaugeValues=new Map;getCounter(e){let t=this.counterCache.get(e);if(t)return t;let n=this.meter.createCounter(e);return this.counterCache.set(e,n),n}getHistogram(e){let t=this.histogramCache.get(e);if(t)return t;let n=this.meter.createHistogram(e);return this.histogramCache.set(e,n),n}ensureObservableGauge(e){let t=this.observableGaugeCache.get(e);if(t)return t;let n=this.meter.createObservableGauge(e);return n.addCallback(o=>{let i=this.gaugeValues.get(e);i!==void 0&&o.observe(i,this.globalAttributes)}),this.observableGaugeCache.set(e,n),n}constructor(e){this.globalAttributes={...e.globalAttributes??{}};let t=typeof process<"u"?"production":"unknown",n=new id({[ks]:e.serviceName,[ny]:t,[iy]:typeof process<"u"&&process.env.SERVICE_INSTANCE_ID?process.env.SERVICE_INSTANCE_ID:UO()}),o=FO(),i=new Md({exporter:o,exportIntervalMillis:e.exportIntervalMs??15e3});this.provider=new kd({resource:n,readers:[i],views:BO}),Os.setGlobalMeterProvider(this.provider),this.meter=Os.getMeter("momentic-serverless")}increment(e,t,n){try{let o=Ms(n,this.globalAttributes);this.getCounter(e).add(typeof t=="number"?t:1,o)}catch{}}gauge(e,t){try{this.ensureObservableGauge(e),this.gaugeValues.set(e,t)}catch{}}distribution(e,t,n){try{let o=Ms(n,this.globalAttributes);this.getHistogram(e).record(t,o)}catch{}}async flush(){try{await this.provider.forceFlush()}catch{}}async recordDuration({fn:e,name:t,tags:n}){let o=Date.now();try{return await Promise.resolve(e())}finally{this.distribution(t,Date.now()-o,n)}}};var Mt=new _s;function Cb(r){r.disabled||(Mt=new yl(r))}import Mb from"fontoxpath";import{DOMParser as zO,XMLSerializer as GO}from"slimdom";function Fd(r){return r.toLowerCase().endsWith("webview")}function HO(r){let e=["android.widget.","android.view.","android.webkit.","android.app.","android.support.","androidx.","com.android.inputmethod."];for(let t of e)if(r.startsWith(t))return r.substring(t.length);return r}var VO=new Set(["index","package","a11y-important"]),jO=new Set(["selected","checked","checkable","clickable","enabled","focusable","focused","long-clickable","password","scrollable","selected","showing-hint","context-clickable","text-entry-key","heading","dismissable","screen-reader-focusable","content-invalid","a11y-focused"]),WO=new Set(["live-region","drawing-order"]),$O=new Set(["displayed","enabled"]);function qO(r,e){let t={};for(let[n,o]of Object.entries(e))VO.has(n)||n==="class"&&r===o||jO.has(n)&&o==="false"||n==="text"&&o===""||$O.has(n)&&o==="true"||WO.has(n)&&o==="0"||n!=="id"&&(t[n]=o);return t}function xb(r,e,t){let{prunedDocument:n,idToElement:o,prunedIdToElement:i,idCounter:a,opts:l}=r,c=a.value++;t.setAttribute("id",String(c));let s={};for(let p of e.attributes){let m=p.name,g=p.value;g!=null&&(s[m]=String(g))}let u=qO(e.tagName,s);for(let[p,m]of Object.entries(u))t.setAttribute(p,m);if(o.set(c,e),i.set(c,t),Fd(e.tagName)&&l?.disallowAccessibilityBridgeForWebviews){for(;t.firstChild;)t.removeChild(t.firstChild);let p=l.injectedWebviewContent??"";p.trim().length>0&&t.appendChild(n.createTextNode(p));return}let d=Array.from(e.childNodes??[]);for(let p of d){let m=p.nodeType;if(m===3){let g=p.nodeValue;g&&g.trim().length>0&&t.appendChild(n.createTextNode(g));continue}if(m===1){let g=p,h=n.createElement(HO(g.tagName));xb(r,g,h),t.appendChild(h)}}}function KO(r,e,t,n){let o=r.parseFromString("<hierarchy/>","text/xml"),i=new Map,a={prunedDocument:o,idToElement:t,prunedIdToElement:i,idCounter:{value:0},opts:n},l=o.documentElement;xb(a,e,l);let c=new GO().serializeToString(o);return{prunedDocument:o,prunedIdToElement:i,xml:c}}async function _b(r,e){let t=new zO,n=t.parseFromString(r,"text/xml"),o=new Map,i=n.documentElement;if(!i)throw new Error("No root element found in XML");if(i.tagName!=="hierarchy")throw new Error("No hierarchy element found in XML");let{prunedDocument:a,prunedIdToElement:l,xml:c}=KO(t,i,o,e);return{xml:c,originalXml:r,document:n,idToElement:o,prunedDocument:a,prunedIdToElement:l}}function YO(r){let e=[],t=r;for(;t;){let n=t.tagName,o=t.parentElement,i=1;if(o){let a=Array.from(o.children).filter(l=>l.tagName===n);for(let l=0;l<a.length;l++)if(a[l]===t){i=l+1;break}}e.unshift(`${n}[${i}]`),t=o}return`/${e.join("/")}`}function El(r,e){let t=r.idToElement.get(e);if(t)return YO(t)}function Bd(r,e){let t=r.idToElement.get(e);if(!t)return;let n=t.cloneNode(!0);for(let o of Array.from(n.children)){let i=o;for(let a of Array.from(i.children))i.removeChild(a)}return n.outerHTML}function bl(r){if(!r.hasAttribute("bounds"))return;let e=r.getAttribute("bounds");if(!e)return;let t=e.match(/\[(\d+),(\d+)\]\[(\d+),(\d+)\]/);if(t){let n=parseInt(t[1],10),o=parseInt(t[2],10),i=parseInt(t[3],10),a=parseInt(t[4],10);if(Number.isFinite(n)&&Number.isFinite(o)&&Number.isFinite(i)&&Number.isFinite(a))return[n,o,i,a]}}function zd(r,e){if(r&&!(!e||e.length===0))return Object.fromEntries(e.map(t=>[t,r.getAttribute(t)]).filter(([,t])=>t!==null))}function Pb({aiResponse:r,description:e,emulatorState:t}){let n=t.graph.idToElement.get(r.id);if(!n)throw new Error(`Could not find node with id: ${r.id}`);let o=bl(n);if(!o)throw new Error(`Node ${r.id} has no bounding box: ${n.outerHTML}`);let i=El(t.graph,r.id)??"",a=Bd(t.graph,r.id)??"",l=t.graph.idToElement.get(r.id),c=zd(l,r.requirements?.attributesRequired),u={requiredText:r.requirements?.textRequired?l?.getAttribute("text")??void 0:void 0,requiredAttributes:c,requiredBounds:r.requirements?.boundsRequired},d=[];r.additionalElements&&(d=r.additionalElements.map(({id:m,requirements:g})=>{let h=t.graph.idToElement.get(m);if(!h)return;let f=El(t.graph,m);return f?{xPath:f,requirements:{requiredText:g.textRequired?h.getAttribute("text")??void 0:void 0,requiredAttributes:zd(h,g.attributesRequired),requiredBounds:g.boundsRequired}}:void 0}).filter(m=>!!m));let p;return Fd(n.tagName)?p={type:"WEBVIEW",resolvedDescription:e,xPath:i}:p={type:"NATIVE",bounds:o,resolvedDescription:e,xPath:i,elementOnlySerializedXml:a,requirements:u,requiredRelatedElements:d},p}var Ib=(r,e,t)=>{if(!e)return;let{requiredAttributes:n,requiredText:o,requiredBounds:i}=e;if(o!==void 0){let a=r.getAttribute("text")??void 0;if(a!==o)throw new Error(`ActionFailureError: Resolved element text mismatch: expected ${o}, got ${a}`)}if(n)for(let[a,l]of Object.entries(n)){let c=r.getAttribute(a)??void 0;if(c!==l)throw new Error(`ActionFailureError: Attribute ${a} mismatch: expected ${l}, got ${c}`)}if(i&&t){let a=bl(r);if(!a||a.length!==t.length)throw new Error("ActionFailureError: Resolved element has no bounds or unexpected bounds format");if(!a.every((c,s)=>c===t[s]))throw new Error(`ActionFailureError: Bounds changed from [${t.join(",")} ] to [${a.join(",")} ]`)}};async function Ob(r){let{target:e,domState:t,stateManager:n,logger:o,signal:i}=r,{graph:a}=t,{document:l}=a;if(e.type==="WEBVIEW"){let g=await n.getActiveWebview();if(!g||!g.browserController)throw new Error("No browser controller is attached to the requested webview");if(!e.browserCache)throw new Error("No browser target available on cache");let h=await g.browserController.browser.resolveTarget(null,e.browserCache,{logger:o,signal:i});return{resolvedTarget:{...e,controller:g.browserController,resolution:h}}}let c=Mb.evaluateXPathToFirstNode(e.xPath,l,null,null);if(!c)throw new Error(`ActionFailureError: Could not resolve cached target via XPath: ${e.xPath}`);if(e.requiredRelatedElements)for(let g of e.requiredRelatedElements){let h=Mb.evaluateXPathToFirstNode(g.xPath,l);if(!h)throw new Error(`ActionFailureError: Required related element not found for XPath: ${g.xPath}`);Ib(h,g.requirements)}let s=bl(c);if(!s)throw new Error("ActionFailureError: Resolved native element has no bounding box");Ib(c,e.requirements,e.bounds);let u;for(let[g,h]of a.idToElement.entries())if(h===c){u=g;break}let d=e.elementOnlySerializedXml,p=e.xPath;return u!==void 0&&(d=Bd(a,u)??d,p=El(a,u)??p),{resolvedTarget:{...e,bounds:s,elementOnlySerializedXml:d,xPath:p}}}function Gd(r){let{command:e,cacheKey:t="cache",targetName:n="target",updatedCache:o}=r;Ja(e)&&(e[t]={...e[t],[n]:o},r.updatedWithAI&&(e[t].updatedAt=new Date))}function Lb(r){return r.type==="WEBVIEW"?{type:"WEBVIEW",resolvedDescription:r.resolvedDescription,xPath:r.xPath,browserCache:r.browserCache}:r}var Lo=class{driver;stateManager;generator;logger;fixtures;aborter;orgId;constructor(e){this.stateManager=e.stateManager,this.generator=e.generator,this.driver=e.driver,this.logger=e.logger,this.fixtures=e.fixtures,this.aborter=e.aborter,this.orgId=e.orgId}async findElement({description:e,tracer:t}){await this.stateManager.waitForScreenshotStability({timeoutMs:5e3,signal:this.aborter.controller?.signal,tracer:t,reason:"Waiting for stability before locating an element with AI"});let n=await t.startAsyncSpan("GET_EMULATOR_STATE",async()=>{try{await this.stateManager.refreshWebviews()}catch(d){this.throwIfAborted(),this.logger.warn({err:d},"Failed to refresh webviews, continuing...")}let s=await this.stateManager.getDomState(),u=await this.stateManager.getCurrentScreenshot();return{emulatorState:s,screenshot:u}}),o=Date.now(),i;try{i=await this.generator.getElementLocation({description:e,screenXml:n.emulatorState.graph.xml,screenshot:n.screenshot},{logger:this.logger,loggerTags:pe(this.logger),abortSignal:this.aborter.controller?.signal})}catch(s){throw this.throwIfAborted(),this.logger.error({err:s},"Failed to locate element"),new Error(`ActionFailureError: Failed to locate element: ${s instanceof Error?s.message:s}`)}if(i.id===-1)throw t.addSpan({type:"AI_LOCATOR_CALL",startTime:o,endTime:Date.now(),error:`No matching element found: ${i.thoughts}`}),new Error(`ActionFailureError: No matching element found: ${i.thoughts}`);let a=Pb({aiResponse:i,description:e,emulatorState:n.emulatorState});if(a.type==="NATIVE")return t.addSpan({type:"AI_LOCATOR_CALL",startTime:o,endTime:Date.now(),result:{serializedElement:a.elementOnlySerializedXml,id:i.id,thoughts:i.thoughts}}),{resolvedTarget:a,thoughts:i.thoughts};let l=await this.stateManager.getActiveWebview();if(!l||!l.browserController)throw new Error("No browser controller is attached to the requested webview");let c=await l.browserController.locateElement({description:e,disableCache:!1,logger:this.logger});return t.addSpan({type:"AI_LOCATOR_CALL",startTime:o,endTime:Date.now(),result:{serializedElement:c.target.nodeOnlySerializedHtml??"Unknown HTML element in webview",id:c.target.id,thoughts:c.thoughts}}),{resolvedTarget:{...a,controller:l.browserController,resolution:c.resolution,browserCache:c.target},thoughts:c.thoughts}}async wrapTargetingAction(e){let{action:t,description:n,command:o,cacheKey:i="cache",targetName:a="target",cacheIsInvalidAfterResolution:l,tracer:c}=e,s=i in o&&o[i]&&a in o[i]?o[i][a]:void 0,u=e.retriesWithAI??1,d=!1,p=JO(s),m;if(o.disableCache&&(this.logger.debug({command:o},"Cache explicitly disabled for command"),d=!0,p=void 0),l&&(d=!0,p=void 0),p&&p?.resolvedDescription!==n&&(this.logger.info({cache:p,description:n},"Cache description mismatch, clearing it automatically"),d=!0,p=void 0),!p){u--,this.logger.info({description:n,cacheBustedBeforeAction:d},"Prompting AI for a new element location");let h=await this.findElement({description:n,tracer:c});return m=h.thoughts,Gd({command:o,cacheKey:i,targetName:a,updatedCache:h.resolvedTarget,updatedWithAI:!0}),{result:await t(h.resolvedTarget),thoughts:m}}let g;try{await this.stateManager.waitForScreenshotStability({timeoutMs:5e3,signal:this.aborter.controller?.signal,tracer:c,reason:"Waiting for stability before cache resolution"}),g=await c.startAsyncSpan("GET_EMULATOR_STATE",async()=>{try{await this.stateManager.refreshWebviews()}catch(E){this.logger.warn({err:E},"Failed to refresh webviews, continuing...")}return await this.stateManager.getDomState()});let h=await c.startAsyncSpan("RESOLVE_TARGET_CACHE",async E=>{let{resolvedTarget:b}=await Ob({target:p,domState:g,stateManager:this.stateManager,logger:this.logger}),v=Lb(b),A=XO(p,v);return this.logger.info({cacheDiffs:A},"Successfully resolved and updated target"),Gd({command:o,cacheKey:i,targetName:a,updatedCache:v,updatedWithAI:!1}),E.result={serializedElement:b.type==="WEBVIEW"?b.browserCache?.nodeOnlySerializedHtml??"Unknown HTML element in webview":b.elementOnlySerializedXml},b}),f=await t(h);return p.type!=="WEBVIEW"&&Mt.increment("cache_target_resolution_v2",1,["outcome:hit","platform:native",`hasRequirements:${!!p.requirements}`,`hasAdditionalElements:${!!p.requiredRelatedElements?.length}`]),{result:f,thoughts:"Successfully executed preset action with cache."}}catch(h){if(p.type!=="WEBVIEW"&&Mt.increment("cache_target_resolution_v2",1,["outcome:miss","platform:native",`hasRequirements:${!!p.requirements}`,`hasAdditionalElements:${!!p.requiredRelatedElements?.length}`]),this.throwIfAborted(),u>0)return this.logger.warn({err:h,domState:g?.graph.originalXml},"Failed to resolve target cache, retrying with AI"),this.wrapTargetingAction({...e,cacheIsInvalidAfterResolution:!0,retriesWithAI:u-1});throw new Error(`ActionFailureError: ${h instanceof Error?h.message:h}`,{cause:h})}}throwIfAborted(){this.aborter.controller?.signal.throwIfAborted()}};var Tl=class extends Lo{async tapOnAbsoluteCoordinates(e){return e.longPress?await this.driver.execute("mobile: longClickGesture",{x:e.x,y:e.y,duration:e.longPressDurationMs??2e3}):await this.driver.tap({x:e.x,y:e.y})}async tapOnTarget({target:e,command:t}){if("type"in e&&e.type==="NATIVE"){let[n,o,i,a]=e.bounds,l=n+(i-n)/2,c=o+(a-o)/2;await this.tapOnAbsoluteCoordinates({x:l,y:c,longPress:t.longPress,longPressDurationMs:t.longPressDurationMs})}else{let{controller:n}=e;await n.browser.click(e.resolution,{createIsolatedFolder:()=>{let o=Math.random().toString(36).substring(4),i=Nb.join(ZO(),"momentic","downloads"),a=Nb.join(i,this.orgId,o);return QO(a,{recursive:!0}),a}},{delayMs:t.longPressDurationMs})}}async executeTap({command:e,tracer:t}){if(e.target.type==="coordinates"){let o=await this.driver.getWindowSize(),i=e.target.xPercent*o.width,a=e.target.yPercent*o.height;return await this.tapOnAbsoluteCoordinates({x:i,y:a,longPress:e.longPress,longPressDurationMs:e.longPressDurationMs}),{success:!0,message:`Tapped at ${i}, ${a}`}}let{thoughts:n}=await this.wrapTargetingAction({command:e,tracer:t,action:o=>this.tapOnTarget({target:o,command:e}),description:e.target.description});return{success:!0,message:n}}};import{execSync as yv}from"child_process";import{_android as bD,chromium as TD}from"playwright";var Db={vimiumJs:'var D=Object.defineProperty;var P=(t,e,n)=>e in t?D(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n;var b=(t,e,n)=>(P(t,typeof e!="symbol"?e+"":e,n),n);var y=t=>function(e){return e&&e.isTrusted?t.apply(this,arguments):!0};globalThis.forTrusted==null&&(globalThis.forTrusted=y);var E={create(t,e,n,o){return{bottom:o,top:e,left:t,right:n,width:n-t,height:o-e}},copy(t){return{bottom:t.bottom,top:t.top,left:t.left,right:t.right,width:t.width,height:t.height}},translate(t,e,n){return e==null&&(e=0),n==null&&(n=0),{bottom:t.bottom+n,top:t.top+n,left:t.left+e,right:t.right+e,width:t.width,height:t.height}},subtract(t,e){return e=this.create(Math.max(t.left,e.left),Math.max(t.top,e.top),Math.min(t.right,e.right),Math.min(t.bottom,e.bottom)),e.width<0||e.height<0?[E.copy(t)]:[this.create(t.left,t.top,e.left,e.top),this.create(e.left,t.top,e.right,e.top),this.create(e.right,t.top,t.right,e.top),this.create(t.left,e.top,e.left,e.bottom),this.create(e.right,e.top,t.right,e.bottom),this.create(t.left,e.bottom,e.left,t.bottom),this.create(e.left,e.bottom,e.right,t.bottom),this.create(e.right,e.bottom,t.right,t.bottom)].filter(o=>o.height>0&&o.width>0)},intersects(t,e){return t.right>e.left&&t.left<e.right&&t.bottom>e.top&&t.top<e.bottom},intersectsStrict(t,e){return t.right>=e.left&&t.left<=e.right&&t.bottom>=e.top&&t.top<=e.bottom},equals(t,e){for(let n of["top","bottom","left","right","width","height"])if(t[n]!==e[n])return!1;return!0},intersect(t,e){return this.create(Math.max(t.left,e.left),Math.max(t.top,e.top),Math.min(t.right,e.right),Math.min(t.bottom,e.bottom))}};var T={_browserInfoLoaded:!0,_firefoxVersion:null,_isFirefox:!1,isFirefox(){if(!this._browserInfoLoaded)throw Error("browserInfo has not yet loaded.");return this._isFirefox},firefoxVersion(){if(!this._browserInfoLoaded)throw Error("browserInfo has not yet loaded.");return this._firefoxVersion},isString(t){return typeof t=="string"||t instanceof String}};var f={isReady(){return document.readyState!=="loading"},documentReady:function(){let t=document.readyState!=="loading",e=[];if(!t){let n;globalThis.addEventListener("DOMContentLoaded",n=y(function(){globalThis.removeEventListener("DOMContentLoaded",n,!0),t=!0;for(let o of e)o();e=null}),!0)}return function(n){if(t)return n();e.push(n)}}(),documentComplete:function(){let t=document.readyState==="complete",e=[];if(!t){let n;globalThis.addEventListener("load",n=y(function(o){if(o.target===document){globalThis.removeEventListener("load",n,!0),t=!0;for(let r of e)r();e=null}}),!0)}return function(n){t?n():e.push(n)}}(),createElement(t){let e=document.createElement(t);return e instanceof HTMLElement?(this.createElement=n=>document.createElement(n),e):(this.createElement=n=>document.createElementNS("http://www.w3.org/1999/xhtml",n),this.createElement(t))},addElementsToPage(t,e){let n=this.createElement("div");e.id!=null&&(n.id=e.id),e.className!=null&&(n.className=e.className);for(let o of t)n.appendChild(o);return document.body.appendChild(n),n},removeElement(t){return t.parentNode.removeChild(t)},isTopFrame(){return globalThis.top===globalThis.self},makeXPath(t){let e=[];for(let n of t)e.push(".//"+n,".//xhtml:"+n);return e.join(" | ")},evaluateXPath(t,e){let n=document.webkitIsFullScreen?document.webkitFullscreenElement:document.documentElement,o=function(r){return r==="xhtml"?"http://www.w3.org/1999/xhtml":null};return document.evaluate(t,n,o,e,null)},getVisibleClientRect(t,e){let n;e==null&&(e=!1);let o=(()=>{let i=[];for(n of t.getClientRects())i.push(E.copy(n));return i})(),r=function(){let i=window.getComputedStyle(t,null),h=i.getPropertyValue("display").indexOf("inline")===0&&i.getPropertyValue("font-size")==="0px";return r=()=>h,h};for(n of o){let i;if((n.width===0||n.height===0)&&e)for(let h of Array.from(t.children)){i=window.getComputedStyle(h,null);let m=i.getPropertyValue("position");if(i.getPropertyValue("float")==="none"&&!["absolute","fixed"].includes(m)&&!(n.height===0&&r()&&i.getPropertyValue("display").indexOf("inline")===0))continue;let s=this.getVisibleClientRect(h,!0);if(!(s===null||s.width<3||s.height<3))return s}else{if(n=this.cropRectToVisible(n),n===null||n.width<3||n.height<3||(i=window.getComputedStyle(t,null),i.getPropertyValue("visibility")!=="visible"))continue;return n}}return null},cropRectToVisible(t){let e=E.create(Math.max(t.left,0),Math.max(t.top,0),t.right,t.bottom);return e.top>=window.innerHeight-4||e.left>=window.innerWidth-4?null:e},getClientRectsForAreas(t,e){let n=[];for(let o of e){let r,i,h,m,s=o.coords.split(",").map(l=>parseInt(l,10)),a=o.shape.toLowerCase();if(["rect","rectangle"].includes(a))s.length==4&&([r,h,i,m]=s);else if(["circle","circ"].includes(a)){if(s.length==3){let[l,c,d]=s,p=d/Math.sqrt(2);r=l-p,i=l+p,h=c-p,m=c+p}}else a==="default"?s.length==2&&([r,h,i,m]=[0,0,t.width,t.height]):s.length>=4&&([r,h,i,m]=s);let u=E.translate(E.create(r,h,i,m),t.left,t.top);u=this.cropRectToVisible(u),u&&!isNaN(u.top)&&!isNaN(u.left)&&!isNaN(u.width)&&!isNaN(u.height)&&n.push({element:o,rect:u})}return n},isSelectable(t){if(!(t instanceof Element))return!1;let e=["button","checkbox","color","file","hidden","image","radio","reset","submit"];return t.nodeName.toLowerCase()==="input"&&e.indexOf(t.type)===-1||t.nodeName.toLowerCase()==="textarea"||t.isContentEditable},isEditable(t){return this.isSelectable(t)||(t.nodeName!=null?t.nodeName.toLowerCase():void 0)==="select"},isEmbed(t){let e=t.nodeName!=null?t.nodeName.toLowerCase():null;return["embed","object"].includes(e)},isFocusable(t){return t&&(this.isEditable(t)||this.isEmbed(t))},isDOMDescendant(t,e){let n=e;for(;n!==null;){if(n===t)return!0;n=n.parentNode}return!1},isSelected(t){let e=document.getSelection();if(t.isContentEditable){let n=e.anchorNode;return n&&this.isDOMDescendant(t,n)}else if(f.getSelectionType(e)==="Range"&&e.isCollapsed){let n=e.anchorNode.childNodes[e.anchorOffset];return t===n}else return!1},simulateSelect(t){if(t===document.activeElement&&f.isEditable(document.activeElement))return handlerStack.bubbleEvent("click",{target:t});if(t.focus(),t.tagName.toLowerCase()!=="textarea"||t.value.indexOf(`\n`)<0)try{if(t.selectionStart===0&&t.selectionEnd===0)return t.setSelectionRange(t.value.length,t.value.length)}catch{}},simulateClick(t,e){e==null&&(e={});let n=["mouseover","mousedown","mouseup","click"],o=[];for(let r of n){let i=this.simulateMouseEvent(r,t,e);o.push(i)}return o},simulateMouseEvent(t,e,n){if(n==null&&(n={}),t==="mouseout"){if(e==null&&(e=this.lastHoveredElement),this.lastHoveredElement=void 0,e==null)return}else t==="mouseover"&&(this.simulateMouseEvent("mouseout",void 0,n),this.lastHoveredElement=e);let o=new MouseEvent(t,{bubbles:!0,cancelable:!0,composed:!0,view:window,detail:1,ctrlKey:n.ctrlKey,altKey:n.altKey,shiftKey:n.shiftKey,metaKey:n.metaKey});return e.dispatchEvent(o)},simulateClickDefaultAction(t,e){let n;if(e==null&&(e={}),(t.tagName!=null?t.tagName.toLowerCase():void 0)!=="a"||!t.href)return;let{ctrlKey:o,shiftKey:r,metaKey:i,altKey:h}=e;KeyboardUtils.platform==="Mac"?n=i===!0&&o===!1:n=i===!1&&o===!0,n?chrome.runtime.sendMessage({handler:"openUrlInNewTab",url:t.href,active:r===!0}):r===!0&&i===!1&&o===!1&&h===!1?chrome.runtime.sendMessage({handler:"openUrlInNewWindow",url:t.href}):t.target==="_blank"&&chrome.runtime.sendMessage({handler:"openUrlInNewTab",url:t.href,active:!0})},simulateHover(t,e){return e==null&&(e={}),this.simulateMouseEvent("mouseover",t,e)},simulateUnhover(t,e){return e==null&&(e={}),this.simulateMouseEvent("mouseout",t,e)},addFlashRect(t){let e=this.createElement("div");return e.classList.add("vimiumReset"),e.classList.add("vimiumFlash"),e.style.left=t.left+"px",e.style.top=t.top+"px",e.style.width=t.width+"px",e.style.height=t.height+"px",document.documentElement.appendChild(e),e},getViewportTopLeft(){let t=document.documentElement,e=getComputedStyle(t),n=t.getBoundingClientRect();if(e.position==="static"&&!/content|paint|strict/.test(e.contain||"")){let o=parseInt(e.marginTop),r=parseInt(e.marginLeft);return{top:-n.top+o,left:-n.left+r}}else{let o,r;return T.isFirefox()?(r=parseInt(e.borderTopWidth),o=parseInt(e.borderLeftWidth)):{clientTop:r,clientLeft:o}=t,{top:-n.top-r,left:-n.left-o}}},suppressPropagation(t){t.stopImmediatePropagation()},suppressEvent(t){t.preventDefault(),this.suppressPropagation(t)},consumeKeyup:function(){let t=null;return function(e,n=null,o){if(!e.repeat){t!=null&&handlerStack.remove(t);let{code:r}=e;t=handlerStack.push({_name:"dom_utils/consumeKeyup",keyup(i){return i.code!==r||(this.remove(),o?f.suppressPropagation(i):f.suppressEvent(i)),handlerStack.continueBubbling},blur(i){return i.target===window&&this.remove(),handlerStack.continueBubbling}})}return typeof n=="function"&&n(),o?(f.suppressPropagation(e),handlerStack.suppressPropagation):(f.suppressEvent(e),handlerStack.suppressEvent)}}(),getSelectionType(t){return t==null&&(t=document.getSelection()),t.type?t.type:t.rangeCount===0?"None":t.isCollapsed?"Caret":"Range"},getElementWithFocus(t,e){let n,o=n=t.getRangeAt(0);f.getSelectionType(t)==="Range"&&(o=n.cloneRange(),o.collapse(e)),n=o.startContainer,n.nodeType===1&&(n=n.childNodes[o.startOffset]);let r=n;for(;r&&r.nodeType!==1;)r=r.previousSibling;return n=r||n?.parentNode,n},getSelectionFocusElement(){let t=window.getSelection(),e=t.focusNode;return e==null?null:(e===t.anchorNode&&t.focusOffset===t.anchorOffset&&(e=e.childNodes[t.focusOffset]||e),e.nodeType!==Node.ELEMENT_NODE?e.parentElement:e)},getContainingElement(t){return(typeof t.getDestinationInsertionPoints=="function"?t.getDestinationInsertionPoints()[0]:void 0)||t.parentElement},windowIsTooSmall(){return window.innerWidth<3||window.innerHeight<3},injectUserCss(){let t=document.createElement("style");t.type="text/css",t.textContent=Settings.get("userDefinedLinkHintCss"),document.head.appendChild(t)}};var R={MAX_CONTENT_LENGTH:1e3,MAX_ATTRIBUTE_LENGTH:500,MAX_NUM_DATA_ATTRIBUTES:10,commonAttributes:["id","className","title","aria-label","aria-labelledby"],attributeNamesMapping:new Map([["a",["href","title","rel","target"]],["label",["for"]],["input",["type","name","placeholder","checked","maximumLength"]],["textarea",["placeholder","maximumLength"]],["button",["type"]],["select",["name","multiple"]],["div",["role"]],["iframe",["src"]],["img",["src","alt"]]]),describe(t){let e={};this.addAttributes(t,this.commonAttributes,e);let n=t.tagName.toLowerCase?.()||"";this.attributeNamesMapping.has(n)&&this.addAttributes(t,this.attributeNamesMapping.get(n),e),this.addDataAttrs(t,e);let o=this.getContent(t);return this.additionalHandling(t,{tag:n,attributes:e,...o&&{content:o}})},getContent(t){let e=t.tagName.toLowerCase?.()||"";return["input","textarea"].includes(e)?t.value:["div","iframe","img","body"].includes(e)?null:(["a","button","select","label"].includes(e),t.innerText)},additionalHandling(t,e){if((t.tagName.toLowerCase?.()||"")=="label"&&t.hasAttribute("for")){let o=t.getAttribute("for"),r=document.getElementById(o);r&&(e.target=this.describe(r))}return e},addAttributes(t,e,n){n||(n={});for(let o of e)t.hasAttribute(o)&&(n[o]=t.getAttribute(o).substring(0,this.MAX_ATTRIBUTE_LENGTH));return n},addDataAttrs(t,e){let n=0;for(let o in t.dataset)if(e[`data-${o}`]=t.dataset[o].substring(0,this.MAX_ATTRIBUTE_LENGTH),n++,n>this.MAX_NUM_DATA_ATTRIBUTES)return e;return e}};var C=null,k=()=>j()||document.scrollingElement||document.body,_=function(t){return t?t<0?-1:1:0},F={x:{axisName:"scrollLeft",max:"scrollWidth",viewSize:"clientWidth"},y:{axisName:"scrollTop",max:"scrollHeight",viewSize:"clientHeight"}},O=function(t,e,n){if(T.isString(n)){let o=n;return o==="viewSize"&&t===k()?e==="x"?window.innerWidth:window.innerHeight:t[F[e][o]]}else return n},I=function(t,e,n){let o=F[e].axisName,r=t[o];if(t.scrollBy){let i={behavior:"instant"};i[e==="x"?"left":"top"]=n,t.scrollBy(i)}else t[o]+=n;return t[o]!==r},V=function(t,e){let n=window.getComputedStyle(t);return!(n.getPropertyValue(`overflow-${e}`)==="hidden"||["hidden","collapse"].includes(n.getPropertyValue("visibility"))||n.getPropertyValue("display")==="none")},v=function(t,e,n,o){let r=o*O(t,e,n)||-1;return r=_(r),I(t,e,r)&&I(t,e,-r)},U=function(t,e,n,o){return e==null&&(e="y"),n==null&&(n=1),o==null&&(o=1),v(t,e,n,o)&&V(t,e)},H=function(t=null){let e;if(!t){let n=k();if(v(n,"y",1,1)||v(n,"y",-1,1))return n;t=document.body||k()}if(v(t,"y",1,1)||v(t,"y",-1,1))return t;{let n=Array.from(t.children).map(o=>({element:o,rect:f.getVisibleClientRect(o)})).filter(o=>o.rect);n.map(o=>o.area=o.rect.width*o.rect.height);for(e of n.sort((o,r)=>r.area-o.area)){let o=H(e.element);if(o)return o}return null}},M={init(){C=null},isScrollableElement(t){return C||(C=k()&&H()||k()),t!==C&&U(t)}},j=function(){let t=K[window.location.host];if(t)return document.querySelector(t)},K={"twitter.com":"div.permalink-container div.permalink[role=main]","reddit.com":"#overlayScrollContainer","new.reddit.com":"#overlayScrollContainer","www.reddit.com":"#overlayScrollContainer","web.telegram.org":".MessageList"};window.Scroller=M;var x=function(){let t=null;return f.documentReady(()=>t=document.hasFocus()),globalThis.addEventListener("focus",y(function(e){return e.target===window&&(t=!0),!0}),!0),globalThis.addEventListener("blur",y(function(e){return e.target===window&&(t=!1),!0}),!0),()=>t}();Object.assign(globalThis,{windowIsFocused:x});var L=class{constructor(e){b(this,"element");b(this,"image");b(this,"rect");b(this,"linkText");b(this,"showLinkText");b(this,"reason");b(this,"secondClassCitizen");b(this,"possibleFalsePositive");Object.seal(this),e&&Object.assign(this,e)}},S={getLocalHintsForElement(t){let e=t.tagName.toLowerCase?.()||"",n=!1,o=!1,r=!1,i=[],h=[],m=null;if(e==="img"){let l=t.getAttribute("usemap");if(l){let c=t.getClientRects();l=l.replace(/^#/,"").replace(\'"\',\'\\\\"\');let d=document.querySelector(`map[name="${l}"]`);if(d&&c.length>0){n=!0;let p=d.getElementsByTagName("area"),g=f.getClientRectsForAreas(c[0],p);g=g.map(N=>Object.assign(N,{image:t})),h.push(...g)}}}let s=t.getAttribute("aria-disabled");if(s&&["","true"].includes(s.toLowerCase()))return[];if(this.checkForAngularJs||(this.checkForAngularJs=function(){if(document.getElementsByClassName("ng-scope").length===0)return()=>!1;{let c=[];for(let d of["","data-","x-"])for(let p of["-",":","_"])c.push(`${d}ng${p}click`);return function(d){for(let p of c)if(d.hasAttribute(p))return!0;return!1}}}()),n||(n=this.checkForAngularJs(t)),t.hasAttribute("onclick"))n=!0;else{let l=t.getAttribute("role"),c=["button","tab","link","checkbox","menuitem","menuitemcheckbox","menuitemradio","radio"];if(l!=null&&c.includes(l.toLowerCase()))n=!0;else{let d=t.getAttribute("contentEditable");d!=null&&["","contenteditable","true","plaintext-only"].includes(d.toLowerCase())&&(n=!0)}}if(!n&&t.hasAttribute("jsaction")){let l=t.getAttribute("jsaction").split(";");for(let c of l){let d=c.trim().split(":");if(d.length>=1&&d.length<=2){let[p,g,N]=d.length===1?["click",...d[0].trim().split("."),"_"]:[d[0],...d[1].trim().split("."),"_"];n||(n=p==="click"&&g!=="none"&&N!=="_")}}}switch(e){case"a":n=!0;break;case"textarea":n||=!t.disabled&&!t.readOnly;break;case"input":n||=!(t.getAttribute("type")?.toLowerCase()=="hidden"||t.disabled||t.readOnly&&f.isSelectable(t));break;case"button":case"select":n||=!t.disabled;break;case"object":case"embed":n=!0;break;case"label":n||=t.control!=null&&!t.control.disabled&&this.getLocalHintsForElement(t.control).length===0;break;case"body":n||=t===document.body&&!x()&&window.innerWidth>3&&window.innerHeight>3&&(document.body!=null?document.body.tagName.toLowerCase():void 0)!=="frameset"?m="Frame.":void 0,n||=t===document.body&&x()&&M.isScrollableElement(t)?m="Scroll.":void 0;break;case"img":n||=["zoom-in","zoom-out"].includes(t.style.cursor);break;case"div":case"ol":case"ul":n||=t.clientHeight<t.scrollHeight&&M.isScrollableElement(t)?m="Scroll.":void 0;break;case"details":n=!0,m="Open.";break}let a=t.getAttribute("class");!n&&a?.toLowerCase().includes("button")&&(n=!0,r=!0);let u=t.getAttribute("tabindex"),w=u?parseInt(u):-1;if(!n&&!(w<0)&&!isNaN(w)&&(n=!0,o=!0),n)if(h.length>0){let l=h.map(c=>new L({element:c.element,image:t,rect:c.rect,secondClassCitizen:o,possibleFalsePositive:r,reason:m}));i.push(...l)}else{let l=f.getVisibleClientRect(t,!0);if(l!==null){let c=new L({element:t,rect:l,secondClassCitizen:o,possibleFalsePositive:r,reason:m});i.push(c)}}return i},getElementFromPoint(t,e,n,o){n==null&&(n=document),o==null&&(o=[]);let r=n.elementsFromPoint?n.elementsFromPoint(t,e)[0]:n.elementFromPoint(t,e);return o.includes(r)?r:(o.push(r),r&&r.shadowRoot?S.getElementFromPoint(t,e,r.shadowRoot,o):r)},getLocalHints(t){if(!document.body)return[];let e=(s,a)=>{a==null&&(a=[]);for(let u of Array.from(s.querySelectorAll("*")))a.push(u),u.shadowRoot&&e(u.shadowRoot,a);return a},n=e(document.body),o=[];for(let s of Array.from(n))if(!t||s.href){let a=this.getLocalHintsForElement(s);o.push(...a)}o=o.reverse();let r=[1,2,3];o=o.filter((s,a)=>{if(!s.possibleFalsePositive)return!0;let w=Math.max(0,a-6);for(;w<a;){let l=o[w].element;for(let c of r)if(l=l?.parentElement,l===s.element)return!1;w+=1}return!0});let i=o.filter(s=>{if(s.secondClassCitizen)return!1;let a=s.rect,u=S.getElementFromPoint(a.left+a.width*.5,a.top+a.height*.5);if(u&&(s.element.contains(u)||u.contains(s.element))||s.element.localName=="area"&&u==s.image)return!0;let l=[a.top+.1,a.bottom-.1],c=[a.left+.1,a.right-.1];for(let d of l)for(let p of c){let g=S.getElementFromPoint(p,d);if(g&&(s.element.contains(g)||g.contains(s.element)))return!0}});i.reverse();let{top:h,left:m}=f.getViewportTopLeft();for(let s of i)s.rect.top+=h,s.rect.left+=m;return i}};var A=class{constructor(){this.hints=null;this.hintMarkers=null;this.markersDiv=null;this.enrichedMarkers=null}reset(){this.removeMarkers(),this.hints=null,this.hintMarkers=null,this.markersDiv=null}async capture(){this.reset(),this.createMarkers(),this.displayMarkers()}createMarkers(){this.hints=S.getLocalHints(),this.hintMarkers=new Map,this.hints.forEach((e,n)=>{let o=f.createElement("div"),r=e.element.attributes["data-momentic-id"]?.value??void 0;if(!r){console.warn(`[MOMENTIC] No data-momentic-id found for interactive element ${e.element.outerHTML}`);return}o.style.left=e.rect.left+"px",o.style.top=e.rect.top+"px",o.style.zIndex=214e7+n,o.className="vimiumReset internalVimiumHintMarker vimiumHintMarker",z(o,r),this.hintMarkers.set(r,{hint:e,marker:o})})}enrichMarkers(){if(this.hintMarkers){this.enrichedMarkers=[];for(let[e,n]of this.hintMarkers)this.enrichedMarkers.push(Object.assign(R.describe(n.hint.element),{hintString:e}))}}displayMarkers(){this.hintMarkers&&(this.markersDiv||(this.markersDiv=f.addElementsToPage(Array.from(this.hintMarkers.values()).map(e=>e.marker),{id:"vimiumHintMarkerContainer",className:"vimiumReset"})))}removeMarkers(){this.markersDiv&&(f.removeElement(this.markersDiv),this.markersDiv=null)}toggleMarkers(){this.markersDiv?this.removeMarkers():this.displayMarkers()}},z=(t,e)=>{for(let n of e){let o=document.createElement("span");o.className="vimiumReset",o.textContent=n,t.appendChild(o)}};window.HintManager=A;\n',vimiumCss:'.vimiumReset,a.vimiumReset,a:hover.vimiumReset,a:link.vimiumReset,a:visited.vimiumReset,div.vimiumReset,span.vimiumReset,table.vimiumReset,td.vimiumReset,tr.vimiumReset{background:none;border:none;bottom:auto;box-shadow:none;color:#000;cursor:auto;display:inline;float:none;font-family:Helvetica Neue,Helvetica,Arial,sans-serif;font-size:inherit;font-style:normal;font-variant:normal;font-weight:400;height:auto;left:auto;letter-spacing:0;line-height:100%;margin:0;max-height:none;max-width:none;min-height:0;min-width:0;opacity:1;padding:0;position:static;right:auto;text-align:left;text-decoration:none;text-indent:0;text-shadow:none;text-transform:none;top:auto;vertical-align:baseline;white-space:normal;width:auto;z-index:2140000000}tbody.vimiumReset,thead.vimiumReset{display:table-header-group}tbody.vimiumReset{display:table-row-group}div.internalVimiumHintMarker{background:linear-gradient(180deg,#fff785 0,#ffc542);border:1px solid #c38a22;border-radius:3px;box-shadow:0 3px 7px 0 rgba(0,0,0,.3);display:block;font-size:11px;left:-1px;overflow:hidden;padding:1px 3px 0;position:absolute;top:-1px;white-space:nowrap}div.internalVimiumHintMarker span{color:#302505;font-family:Helvetica,Arial,sans-serif;font-size:11px;font-weight:700;text-shadow:0 1px 0 hsla(0,0%,100%,.6)}div.internalVimiumHintMarker>.matchingCharacter{color:#d4ac3a}div>.vimiumActiveHintMarker span{color:#a07555!important}div.internalVimiumInputHint{background-color:rgba(255,247,133,.3);border:1px solid #c38a22;display:block;pointer-events:none;position:absolute}div.internalVimiumSelectedInputHint{background-color:hsla(0,100%,70%,.3);border:1px solid #933!important}div.internalVimiumSelectedInputHint span{color:#fff!important}div.vimiumHighlightedFrame{border:5px solid #ff0;box-sizing:border-box;margin:0;pointer-events:none}div.vimiumHighlightedFrame,iframe.vimiumHelpDialogFrame{height:100%;left:0;padding:0;position:fixed;top:0;width:100%}iframe.vimiumHelpDialogFrame{background-color:hsla(0,0%,4%,.6);border:none;display:block;z-index:2139999997}div#vimiumHelpDialogContainer{background-color:#fff;border:2px solid #b3b3b3;border-radius:6px;margin:50px auto;max-height:calc(100% - 100px);max-width:calc(100% - 100px);opacity:1;overflow-x:auto;overflow-y:auto;width:840px}div#vimiumHelpDialog{min-width:600px;padding:8px 12px}span#vimiumTitle,span#vimiumTitle *,span#vimiumTitle span{font-size:20px}#vimiumTitle{display:block;line-height:130%;white-space:nowrap}td.vimiumHelpDialogTopButtons{text-align:right;width:100%}#helpDialogOptionsPage,#helpDialogWikiPage{font-size:14px;padding-left:5px;padding-right:5px}div.vimiumColumn{float:left;font-size:11px;line-height:130%;width:50%}div.vimiumColumn tr{display:table-row}div.vimiumColumn td{display:table-cell;font-size:11px;line-height:130%}div.vimiumColumn table,div.vimiumColumn td,div.vimiumColumn tr{margin:0;padding:0}div.vimiumColumn table{table-layout:auto;width:100%}div.vimiumColumn td{padding:1px;vertical-align:top}div#vimiumHelpDialog div.vimiumColumn tr>td:first-of-type{font-family:Helvetica Neue,Helvetica,Arial,sans-serif;font-size:14px;text-align:right;white-space:nowrap}span.vimiumHelpDialogKey{background-color:#f3f3f3;border:1px solid;border-color:#ccc #ccc #bbb;border-radius:3px;box-shadow:inset 0 -1px 0 #bbb;color:#212121;font-family:monospace;font-size:11px;margin-left:2px;padding:1px 4px}div#vimiumHelpDialog div.vimiumColumn tr>td:nth-of-type(3){width:100%}div#vimiumHelpDialog div.vimiumDivider{background-color:#9a9a9a;display:block;height:1px;margin:10px auto;width:100%}div#vimiumHelpDialog td.vimiumHelpSectionTitle{font-family:Helvetica Neue,Helvetica,Arial,sans-serif;font-size:16px;font-weight:700;padding-top:3px}div#vimiumHelpDialog td.vimiumHelpDescription{font-family:Helvetica Neue,Helvetica,Arial,sans-serif;font-size:14px}div#vimiumHelpDialog span.vimiumCopyCommandNameName{cursor:pointer;font-size:12px;font-style:italic}div#vimiumHelpDialog tr.advanced{display:none}div#vimiumHelpDialog.showAdvanced tr.advanced{display:table-row}div#vimiumHelpDialog div.advanced td:nth-of-type(3){color:#555}div#vimiumHelpDialog a.closeButton{color:#555;cursor:pointer;font-family:courier new;font-size:24px;font-weight:700;padding-left:5px;position:relative;text-decoration:none;top:3px}div#vimiumHelpDialog a{text-decoration:underline}div#vimiumHelpDialog a.closeButton:hover{color:#000;-webkit-user-select:none}div#vimiumHelpDialogFooter{display:block;margin-bottom:37px;position:relative}table.helpDialogBottom{width:100%}td.helpDialogBottomRight{float:right;text-align:right;width:100%}td.helpDialogBottomLeft,td.helpDialogBottomRight{padding:0}div#vimiumHelpDialogFooter *{font-size:10px}a#toggleAdvancedCommands,span#help-dialog-tip{font-size:10px;position:relative;top:19px;white-space:nowrap}a#toggleAdvancedCommands,a:active.vimiumHelDialogLink,a:hover.vimiumHelDialogLink,a:link.vimiumHelDialogLink,a:visited.vimiumHelDialogLink{color:#2f508e;cursor:pointer;text-decoration:underline}div.vimiumHUD{background:#f1f1f1;border:1px solid #aaa;border-radius:4px;bottom:8px;box-shadow:0 2px 10px rgba(0,0,0,.8);display:block;left:8px;position:fixed;text-align:left;width:calc(100% - 20px);z-index:2139999999}iframe.vimiumHUDFrame{background-color:transparent;border:none;bottom:-14px;display:block;height:58px;margin:0 0 0 -40%;min-width:300px;opacity:0;overflow:hidden;padding:0;position:fixed;right:20px;width:20%;z-index:2139999998}div.vimiumHUD .vimiumHUDSearchArea{background-color:#f1f1f1;border-radius:4px 4px 0 0;display:block;padding:3px}div.vimiumHUD .vimiumHUDSearchAreaInner{border-radius:3px;box-sizing:border-box;color:#777;font-family:Helvetica Neue,Helvetica,Arial,sans-serif;font-size:14px;height:30px;line-height:20px;margin-bottom:0;outline:none;padding:2px 4px;width:100%}div.vimiumHUD .hud-find{background:#fff;border:1px solid #ccc}div.vimiumHUD span#hud-find-input,div.vimiumHUD span#hud-match-count{color:#000;display:inline;outline:none;overflow-y:hidden;white-space:nowrap}div.vimiumHUD span#hud-find-input:before{content:"/"}div.vimiumHUD span#hud-match-count{color:#aaa;font-size:12px}div.vimiumHUD span#hud-find-input br{display:none}div.vimiumHUD span#hud-find-input *{display:inline;white-space:nowrap}body.vimiumFindMode ::selection{background:#ff9632}iframe.vomnibarFrame{background-color:transparent;border:none;display:block;font-family:sans-serif;height:calc(100% - 70px);left:50%;margin:0 0 0 -40%;min-width:400px;overflow:hidden;padding:0;position:fixed;top:70px;width:calc(80% + 20px);z-index:2139999998}div.vimiumFlash{background-color:transparent;box-shadow:0 0 4px 2px #4183c4;padding:1px;position:absolute;z-index:2140000000}iframe.vimiumUIComponentHidden{display:none}iframe.vimiumUIComponentVisible{color-scheme:light dark;display:block}iframe.vimiumUIComponentReactivated{border:5px solid #ff0}iframe.vimiumNonClickable{pointer-events:none}@media (prefers-color-scheme:dark){iframe.reverseDarkReaderFilter{-webkit-filter:invert(100%) hue-rotate(180deg)!important;filter:invert(100%) hue-rotate(180deg)!important}body.vimiumBody{background-color:#292a2d;color:#fff}body.vimiumBody a,body.vimiumBody a:visited{color:#8ab4f8}body.vimiumBody input,body.vimiumBody textarea{background-color:#1d1d1f;border-color:#1d1d1f;color:#e8eaed}body.vimiumBody div.example{color:#9aa0a6}body.vimiumBody div#footer,body.vimiumBody div#state,div#vimiumHelpDialogContainer{background-color:#202124;border-color:hsla(0,0%,100%,.1)}div#vimiumHelpDialog{background-color:#292a2d;color:#fff}div#vimiumHelpDialog td.vimiumHelpDescription{color:#c9cccf}div#vimiumHelpDialog td.vimiumHelpSectionTitle,span#vimiumTitle{color:#fff}#vimiumTitle>span:first-child{color:#8ab4f8!important}div#vimiumHelpDialog a{color:#8ab4f8}div#vimiumHelpDialog div.vimiumDivider{background-color:hsla(0,0%,100%,.1)}span.vimiumHelpDialogKey{background-color:#1d1d1f;border:1px solid #000;box-shadow:none;color:#fff}}',htmlUtilsLibJs:`// src/html/constants.ts
26
26
  var momenticConstants = {
27
27
  bannedClassSubstrings: [
28
28
  "relative",
@@ -1457,9 +1457,6 @@ function addAddIdsScript() {
1457
1457
  customWindow.nextAvailableMomenticId ?? 0,
1458
1458
  currentId
1459
1459
  );
1460
- if (!customWindow.idMaintainer) {
1461
- customWindow.addIdMaintainer?.();
1462
- }
1463
1460
  return currentId;
1464
1461
  };
1465
1462
  }
@@ -1482,83 +1479,6 @@ function addGetNextElementScript() {
1482
1479
  return null;
1483
1480
  };
1484
1481
  }
1485
- function addIdMaintainerScript() {
1486
- const customWindow = window;
1487
- if (customWindow.addIdMaintainer || customWindow.idMaintainer) {
1488
- return;
1489
- }
1490
- const callback = (mutationList) => {
1491
- if (!customWindow.addIdsToElement || !customWindow.nextAvailableMomenticId) {
1492
- return;
1493
- }
1494
- for (const mutation of mutationList) {
1495
- if (mutation.type === "childList" && mutation.addedNodes.length > 0) {
1496
- for (const nodeRef of mutation.addedNodes) {
1497
- if (nodeRef.nodeType !== Node.ELEMENT_NODE) {
1498
- continue;
1499
- }
1500
- const node = nodeRef;
1501
- if (node.getAttribute("data-momentic-id")) {
1502
- continue;
1503
- }
1504
- const nodeBefore = node.previousElementSibling ?? node.parentElement;
1505
- if (!nodeBefore) {
1506
- continue;
1507
- }
1508
- const nodeAfter = customWindow.getNextElement?.(node);
1509
- if (!nodeAfter) {
1510
- continue;
1511
- }
1512
- const beforeId = nodeBefore.getAttribute("data-momentic-id");
1513
- const afterId = nodeAfter.getAttribute("data-momentic-id");
1514
- if (beforeId === null || afterId === null) {
1515
- continue;
1516
- }
1517
- const beforeIdNum = parseInt(beforeId);
1518
- const afterIdNum = parseInt(afterId);
1519
- if (beforeIdNum >= afterIdNum - 1) {
1520
- continue;
1521
- }
1522
- customWindow.addIdsToElement?.(node, beforeIdNum + 1, afterIdNum);
1523
- }
1524
- } else if (mutation.type === "attributes") {
1525
- const target = mutation.target;
1526
- if (target.nodeType !== Node.ELEMENT_NODE) {
1527
- continue;
1528
- }
1529
- const ele = target;
1530
- try {
1531
- const oldId = parseInt(mutation.oldValue ?? "");
1532
- const newAttr = ele.getAttribute("data-momentic-id");
1533
- if (!newAttr) {
1534
- ele.setAttribute("data-momentic-id", \`\${oldId}\`);
1535
- ele.setAttribute("aria-keyshortcuts", \`\${oldId}\`);
1536
- }
1537
- } catch (err) {
1538
- console.error(\`[MOMENTIC] Failed to update ID in maintainer: \${err}\`);
1539
- }
1540
- }
1541
- }
1542
- };
1543
- customWindow.addIdMaintainer = () => {
1544
- if (customWindow.idMaintainer) {
1545
- return;
1546
- }
1547
- try {
1548
- const observer = new MutationObserver(callback);
1549
- customWindow.idMaintainer = observer;
1550
- observer.observe(document.body, {
1551
- attributeFilter: ["data-momentic-id"],
1552
- attributeOldValue: true
1553
- });
1554
- } catch (_err) {
1555
- window.setTimeout(() => {
1556
- customWindow.addIdMaintainer?.();
1557
- }, 1e3);
1558
- return;
1559
- }
1560
- };
1561
- }
1562
1482
 
1563
1483
  // src/html/element-location.ts
1564
1484
  function addFindElementInBodyOrShadowDomScript() {
@@ -3293,6 +3213,36 @@ function addMPathScripts() {
3293
3213
  customWindow.getMPathSelector = getMPathSelector;
3294
3214
  }
3295
3215
 
3216
+ // src/html/performance-observer.ts
3217
+ function addPerformanceObserver() {
3218
+ const customWindow = window;
3219
+ if (customWindow.performanceObserver) {
3220
+ return;
3221
+ }
3222
+ const obs = new PerformanceObserver((list) => {
3223
+ for (const e of list.getEntriesByType("longtask")) {
3224
+ try {
3225
+ console.warn("[MOMENTIC] Long-running task detected", {
3226
+ start: e.startTime.toFixed(1),
3227
+ dur: e.duration.toFixed(1),
3228
+ // https://developer.mozilla.org/en-US/docs/Web/API/PerformanceLongTaskTiming/attribution
3229
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
3230
+ attribution: e.attribution?.map((a) => ({
3231
+ name: a.name,
3232
+ entryType: a.entryType,
3233
+ containerType: a.containerType,
3234
+ containerSrc: a.containerSrc,
3235
+ scriptUrl: a.containerSrc || a.name
3236
+ }))
3237
+ });
3238
+ } catch (err) {
3239
+ console.error(\`[MOMENTIC] Failed to log long task: \${err}\`);
3240
+ }
3241
+ }
3242
+ });
3243
+ obs.observe({ entryTypes: ["longtask"] });
3244
+ }
3245
+
3296
3246
  // src/html/recording-listeners.ts
3297
3247
  function addResolveRecordingTarget() {
3298
3248
  const customWindow = window;
@@ -3960,10 +3910,10 @@ function addTargetRedirectionScript() {
3960
3910
 
3961
3911
  // src/html/registration.ts
3962
3912
  function registerAllMomenticListeners() {
3913
+ addPerformanceObserver();
3963
3914
  addMd5Hash();
3964
3915
  addAddIdsScript();
3965
3916
  addGetNextElementScript();
3966
- addIdMaintainerScript();
3967
3917
  addMPathScripts();
3968
3918
  addIndexDbScripts();
3969
3919
  addMomenticConstantsToWindow();
@@ -3986,46 +3936,45 @@ function registerAllMomenticListeners() {
3986
3936
 
3987
3937
  // src/html/index.ts
3988
3938
  registerAllMomenticListeners();
3989
- `};var Ht={bannedClassSubstrings:["relative","flex","center","justify","auto","sticky","absolute","top","right","left","bottom","items-center","notion-selectable","notion-page-block","notion-collection-item","MuiSvgIcon","css-","rt-"],nonDynamicInputTypes:["button","file","hidden","image","radio","reset","submit"],generalStateAttributes:["aria-expanded","aria-haspopup","aria-checked","aria-pressed","aria-selected","aria-invalid","checked","open","aria-busy"],bannedElementTagNames:["html","head","meta","script","style","path","br","::marker","noscript","polygon","defs"],bannedElementAttributes:["data-momentic-id","aria-keyshortcuts","data-ved","aria-controls","d"],relevantElementAttributes:["name","id","value","type","class","height","width","target","title","href","src","alt","role","headers","scope","checked","required","action","tooltip","min","max","minlength","maxlength","multiple","pattern","placeholder","accept","contenteditable","data-value","data-testid","data-cy","data-pw","data-test-id","data-test","data-role","data-type","data-key","data-action","data-qa","data-aria-hidden","data-hidden","data-automation-id","data-overlay","data-content-editable-leaf","data-wf-icon","data-tns","data-sticky-stack-name","data-popup-origin","data-handleid","data-handlepos","data-col-index","data-row-index","data-row","data-col","col-index","row-index","row","col","data-momentic-description","aria-label","aria-role","aria-selected","aria-disabled","aria-hidden","aria-describedby","aria-labelledby","aria-valuenow","aria-valuemin","aria-valuemax"],alwaysUsefulAttributesForCssSelectorGeneration:["src","href","aria-describedby","aria-labelledby","aria-label"],stronglyIdentifyingAttributes:["aria-label","data-testid","id","name","href","aria-describedby","aria-labelledby","aria-description","data-row","data-col","data-row-index","data-col-index","for","aria-modal"],alwaysInterestingClassNames:["cm-line","cm-activeLine","cm-content"],alwaysInterestingClassPrefixes:["notion-",".w-"],alwaysInterestingTruthyPropertyNames:["contenteditable"],visualAttributesForSvgSerialization:["fill","stroke","color","patternContentUnits","xlink:href","transform","path","d","points","viewBox","preserveAspectRatio","r","rx","ry","cx","cy","x1","y1","x2","y2","font","text-anchor","dominant-baseline","gradient","pattern","stop-color"],bannedAiRequiredCacheAttributes:["id","data-momentic-id","href","name","x","y","width","height","data-momentic-id","aria-keyshortcuts","data-ved","aria-controls","d"],ineligibleElementAttribute:"momentic-ineligible"};var tT="BoundingBoxMovedError",rT="ZeroOpacityError",el="visual_actions",Er="data-momentic-id";function nT(r,e,t){if(r.length<t)return r;let n=r.indexOf(e);if(n===-1)return r;let o=Math.max(0,n-t/3),i=Math.min(n+t/3,r.length),a=r.indexOf(`
3939
+ `};var jt={bannedClassSubstrings:["relative","flex","center","justify","auto","sticky","absolute","top","right","left","bottom","items-center","notion-selectable","notion-page-block","notion-collection-item","MuiSvgIcon","css-","rt-"],nonDynamicInputTypes:["button","file","hidden","image","radio","reset","submit"],generalStateAttributes:["aria-expanded","aria-haspopup","aria-checked","aria-pressed","aria-selected","aria-invalid","checked","open","aria-busy"],bannedElementTagNames:["html","head","meta","script","style","path","br","::marker","noscript","polygon","defs"],bannedElementAttributes:["data-momentic-id","aria-keyshortcuts","data-ved","aria-controls","d"],relevantElementAttributes:["name","id","value","type","class","height","width","target","title","href","src","alt","role","headers","scope","checked","required","action","tooltip","min","max","minlength","maxlength","multiple","pattern","placeholder","accept","contenteditable","data-value","data-testid","data-cy","data-pw","data-test-id","data-test","data-role","data-type","data-key","data-action","data-qa","data-aria-hidden","data-hidden","data-automation-id","data-overlay","data-content-editable-leaf","data-wf-icon","data-tns","data-sticky-stack-name","data-popup-origin","data-handleid","data-handlepos","data-col-index","data-row-index","data-row","data-col","col-index","row-index","row","col","data-momentic-description","aria-label","aria-role","aria-selected","aria-disabled","aria-hidden","aria-describedby","aria-labelledby","aria-valuenow","aria-valuemin","aria-valuemax"],alwaysUsefulAttributesForCssSelectorGeneration:["src","href","aria-describedby","aria-labelledby","aria-label"],stronglyIdentifyingAttributes:["aria-label","data-testid","id","name","href","aria-describedby","aria-labelledby","aria-description","data-row","data-col","data-row-index","data-col-index","for","aria-modal"],alwaysInterestingClassNames:["cm-line","cm-activeLine","cm-content"],alwaysInterestingClassPrefixes:["notion-",".w-"],alwaysInterestingTruthyPropertyNames:["contenteditable"],visualAttributesForSvgSerialization:["fill","stroke","color","patternContentUnits","xlink:href","transform","path","d","points","viewBox","preserveAspectRatio","r","rx","ry","cx","cy","x1","y1","x2","y2","font","text-anchor","dominant-baseline","gradient","pattern","stop-color"],bannedAiRequiredCacheAttributes:["id","data-momentic-id","href","name","x","y","width","height","data-momentic-id","aria-keyshortcuts","data-ved","aria-controls","d"],ineligibleElementAttribute:"momentic-ineligible"};var kb="BoundingBoxMovedError",Ub="ZeroOpacityError",vl="visual_actions",_r="data-momentic-id";function Fb(r,e,t){if(r.length<t)return r;let n=r.indexOf(e);if(n===-1)return r;let o=Math.max(0,n-t/3),i=Math.min(n+t/3,r.length),a=r.indexOf(`
3990
3940
  `,o);a>0&&a<n&&(o=a);let l=i,c=0;for(;c<1e3&&l>n&&r[l]!==`
3991
3941
  `;)c++,l--;return l>n&&r[l]===`
3992
- `&&(i=l),r.slice(o,i)}function qt(r){let e=typeof r=="string"?r:r.toString();return`[${Er}="${e}"]`}import{execSync as bL}from"child_process";import{randomUUID as jd}from"crypto";import{diff as Wd}from"deep-object-diff";import{existsSync as dl,mkdirSync as vL,readFileSync as AL,writeFileSync as wL}from"fs";import{Jimp as lb}from"jimp";import RL from"js-beautify";import{cloneDeep as Ro}from"lodash-es";import CL from"mime";import{homedir as qd,hostname as xL,platform as _L}from"os";import{basename as ML,extname as IL,join as Co,resolve as PL}from"path";import{chromium as ub,devices as OL}from"playwright";import{addExtra as LL}from"playwright-extra";import NL from"puppeteer-extra-plugin-recaptcha";import{v4 as DL}from"uuid";import{rmSync as RT}from"fs";import{basename as SO,join as EO}from"path";import{errors as yO}from"playwright-core";var oT=new Set(["about:blank","chrome-error://chromewebdata/"]);var Ed=["button","image","generic","graphics-symbol","tab","link","menuitem","group"],yd=1e4,Vi=500;import{mkdirSync as jP,rmSync as iT,statSync as WP}from"fs";import*as Ad from"node:fs";import $P from"nodejs-file-downloader";import{tmpdir as qP}from"os";import $r,{basename as KP,dirname as YP}from"path";var wd="file://",vd=$r.join(qP(),"momentic","downloads"),bd=1e4,XP=50*1024*1024;async function aT(r){let{uri:e}=r;if(e.startsWith(wd))return QP(r);if(e.startsWith("http"))return eO(r);if(Yg)return ZP(r);throw new A("UserConfigurationError","The source URI for the file upload step must be a valid URL or a previously downloaded file beginning with 'file://'")}function JP(r,e){let t=$r.join(vd,r,e.slice(wd.length)),n=$r.join(vd,r),o=t.startsWith(n);if(!Ad.existsSync(t)||!o)throw new A("UserConfigurationError",`The referenced file (${e}) does not exist. Please make sure that it has been downloaded successfully.`);return t}async function QP({uri:r,orgId:e}){let t=JP(e,r);return{filePath:t,cleanup:()=>{iT(YP(t),{recursive:!0,force:!0})}}}async function ZP({uri:r}){let e=$r.resolve(r);if(!Ad.existsSync(e))throw new A("UserConfigurationError",`The referenced file (${r}) does not exist on disk. Please make sure that it has been downloaded successfully.`);return{filePath:e,cleanup:()=>{}}}async function eO({uri:r,logger:e,orgId:t}){let n=new URL(r);n.search&&(n.search="");let o=KP(n.href),i=Cd(o),a=$r.extname(i);if(Vg.includes(a))throw new Error(`Downloading files with extension ${a} is not allowed.`);let l=Rd(t),c=new $P({url:r,fileName:i,directory:l,maxAttempts:2,headers:{"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.82 Safari/537.36"},timeout:bd}),{downloadStatus:s,filePath:u}=await B(c.download(),{milliseconds:bd,message:`Download timed out after ${bd}ms`});if(s!=="COMPLETE")throw new Error(`Download ended in non-success status: ${s}`);if(!u)throw new Error("File path of successfully downloaded file was empty");let m=WP(u).size;if(m>XP)throw new Error("File size exceeds the maximum limit of 50MB");e.info({fileSizeInBytes:m,filePath:u,fileName:i},"Downloaded file to disk");let p;return{filePath:u,cleanup:()=>{clearTimeout(p),p=setTimeout(()=>iT(l,{recursive:!0,force:!0}),10*60*1e3)}}}function sT(r,e){return`${wd}${r}/${e}`}function Rd(r){let e=Math.random().toString(36).substring(4),t=$r.join(vd,r,e);return jP(t,{recursive:!0}),t}function Cd(r){let e=$r.extname(r),t=$r.basename(r,e);return r=(t.length>100?t.slice(t.length-100):t)+e,r=r.trim().replaceAll(" ","_"),r}async function yr(r,e){try{return await r.evaluate(n=>window.serializeElementOnlyWithText?.(n,{truncateToLength:500}),void 0,{timeout:1e3})}catch(t){e.debug({err:t},"Failed to get HTML from locator for Playwright error translation");return}}var tl=class{limit;windowMs;userActions;constructor(e,t){this.limit=e,this.windowMs=t,this.userActions=new Map}_cleanup(e,t="DEFAULT_USER"){let n=Date.now(),o=`${t}:${e}`;if(this.userActions.has(o)){let a=this.userActions.get(o)?.filter(l=>n-l<=this.windowMs)??[];a.length>0?this.userActions.set(o,a):this.userActions.delete(o)}}increment(e,t="DEFAULT_USER"){let n=Date.now(),o=`${t}:${e}`;this._cleanup(t,e),this.userActions.has(o)||this.userActions.set(o,[]);let i=this.userActions.get(o);return i.length>=this.limit?!0:(i.push(n),!1)}};async function lT(r,e){let t=r.evaluate(async()=>{let i=window,a={};try{let l=await indexedDB.databases();for(let c of l){if(!c.name)continue;let s=await i.exportIdbToObject?.(c.name,c.version);s&&(a[c.name]=s)}return[a,void 0]}catch(l){return[void 0,l.message]}}),[n,o]=await B(t,{milliseconds:3e3});return o&&e.warn({err:o},"Failed to fetch indexedDB data"),n}async function cT(r,e,t){if(e){t.debug("Importing indexedDB data");try{let n=r.evaluate(async o=>{let i=window;for(let[a,l]of Object.entries(o))await i.importObjectToIdb?.(a,l)},e);await B(n,{milliseconds:3e3})}catch(n){t.warn({err:n},"Failed to import indexedDB data")}}}async function uT(r,e){try{let t=r.evaluate(async()=>{window.localStorage.clear(),window.sessionStorage.clear(),await indexedDB.databases().then(n=>{n.forEach(o=>{o.name&&indexedDB.deleteDatabase(o.name)})})});await B(t,{milliseconds:3e3})}catch(t){e.debug({err:t},"Failed clearing index db data, continuing...")}}async function dT(r,e,t,n,o){try{await tO(r,e,t,n)}catch(i){o.error({err:i,tabIndex:e},"Error handling new console log")}}async function tO(r,e,t,n){let o=n.text();o.length>Vi&&(o=o.slice(0,Vi)+"...(TRUNCATED)");let i=[];for(let a of n.args())try{let l=await a.jsonValue(),c=JSON.stringify(l);c.length>Vi?i.push(c.slice(0,Vi)+"...(TRUNCATED)"):(typeof l!="object"||Object.keys(l).length>0)&&i.push(l)}catch{}xd(r,t,e,{url:r.url(),location:n.location(),type:n.type(),text:n.text(),args:i})}function xd(r,e,t,n){let o=Date.now(),i=e.logsPerPage;if(i.length<=t||i[t]===void 0){i[t]=[];for(let a=0;a<t;a++)i[a]===void 0&&(i[a]=[])}i[t].length>yd&&(i[t]=i[t].slice(Math.floor(yd/2)),i[t]?.push({url:r.url(),timestamp:o,type:"warning",text:"[MOMENTIC] Truncated console logs due to buffer overflow",tabIndex:t})),i[t].push({...n,tabIndex:t,timestamp:o})}async function Vt({fn:r,codePath:e,logObject:t,signal:n,logger:o}){n?.throwIfAborted();let i=Date.now(),a=await md({promiseGenerator:r,signal:n,codePath:e,logger:o}),l=Date.now();return t[e]=l-i,a}import rO from"truncate-json";var nO="[redacted due to size]",mT=5e3,oO=5e3;async function gT(r,e,t){let n=new Date().toISOString();e.harPages||(e.harPages={}),e.harPages[r]={id:r,startedDateTime:n,title:void 0,pageTimings:{}}}async function _d(r,e){let t=e.timing(),n=new URL(e.url()),o=[...n.searchParams.entries()].map(([l,c])=>({name:l,value:c})),i={...await fT(e),url:n.toString(),method:e.method(),queryString:o,postData:await aO(e)};return{pageref:r,_resourceType:e.resourceType(),startedDateTime:new Date().toISOString(),request:i,timings:ST(t).timings}}async function hT(r,e,t){await t.finished();let n={};try{n=await uO(t)}catch{}let o={...await fT(t),status:t.status(),statusText:t.statusText(),content:n,redirectURL:t.headers().location,_mocked:!1};r.response=o;let i;try{i=await e.sizes(),r.request.bodySize=i.requestBodySize,r.request.headersSize=i.requestHeadersSize}catch{}r.response&&i&&(r.response.bodySize=i.responseBodySize,r.response.headersSize=i.responseHeadersSize,r.response.content.size=i.responseBodySize);let a=e.timing();r.startedDateTime=new Date(a.startTime).toISOString();let{timings:l,total:c}=ST(a);r.time=c,r.timings=l}function ji(r,e,t){r.harEntries||(r.harEntries={}),r.harEntries[t]=e}function pT(r){try{return new Date(r).toISOString()}catch{return}}function iO(r){let e={name:"",value:""},t=!0;for(let n of r.split(/; */)){let o=n.indexOf("="),i=o!==-1?n.substring(0,o).trim():n.trim(),a=o!==-1?n.substring(o+1,n.length).trim():"";if(t){t=!1,e.name=ar(i),e.value=ar(a);continue}i==="Domain"&&(e.domain=ar(a)),i==="Expires"&&(e.expires=pT(a)),i==="HttpOnly"&&(e.httpOnly=!0),i==="Max-Age"&&(e.expires=pT(Date.now()+ +a*1e3)),i==="Path"&&(e.path=ar(a)),i==="Secure"&&(e.secure=!0)}return e}async function fT(r){let e=await r.allHeaders(),t=e.cookie?.split(";").map(iO)??[];return{headers:Object.entries(e).map(([n,o])=>({name:ar(n),value:ar(o)})),cookies:t}}async function aO(r){let e=r.postData();if(!e)return;let t=await r.headerValue("content-type"),n={mimeType:t??"application/octet-stream",text:ar(e),params:[]};if(t==="application/x-www-form-urlencoded"){let o=new URLSearchParams(e.toString());for(let[i,a]of o.entries())n.params.push({name:ar(i),value:a?ar(a):void 0})}return n}var sO=["text"],lO=["json","xml","html","javascript"];function cO(r){let[e,t]=r.split("/");return e?sO.includes(e)?!0:t?!!lO.some(n=>t?.includes(n)):!1:!1}async function uO(r){let t=((await r.headerValue("content-type"))?.toLowerCase()??void 0)?.split(";")[0]??void 0,n={mimeType:t,encoding:await r.headerValue("content-encoding")??void 0};return t&&cO(t)&&(n.text=ar(await r.text())),n}function ar(r){try{let e=JSON.parse(r),{jsonString:t}=rO(r,oO);return t}catch{return r.length>mT?r.slice(0,mT)+nO:r}}function Rn(r){return r<0?0:r}function ST(r){return{timings:{blocked:Rn(r.domainLookupStart),dns:Rn(r.domainLookupEnd-r.domainLookupStart),connect:Rn(r.connectEnd-r.connectStart),send:Rn(r.responseStart-r.requestStart),wait:0,receive:Rn(r.responseEnd-r.responseStart),ssl:Rn(r.connectEnd-r.secureConnectionStart)},total:Rn(r.responseEnd)}}function ET(){return async r=>{let{fragment:e,code:t,context:n}=r,{env:o}=n||{},i=Object.getPrototypeOf(async function(){}).constructor;return{result:await Promise.resolve(new i("env",e?`return ${t}`:t)(o))}}}async function He({root:r,fn:e,arg:t,timeout:n,waitForPageLoad:o,codePath:i}){return await o(),await B(r.evaluate(e,t),{milliseconds:n,message:`Timed out ${i} after ${n}ms. This indicates that either the page is unresponsive or your machine is severely resource constrained.`})}function Md(){return window.lastCursorPos}import{errors as dO}from"playwright-core";async function Cn({func:r,action:e,logger:t,callbacks:n,retryTimeoutMs:o,targetingResult:i}){let a=Date.now(),l;for(;Date.now()-a<o;)try{return await r(i)}catch(c){if(c instanceof dO.TimeoutError)t.warn({err:c,rootUrl:(await n.state.getRoot()).url()},`Encountered Playwright error while performing ${e}`),l=await mO(c,i.locator,n,t);else throw c}throw l instanceof A?l:new A("ActionFailureError",`Failed to interact with targeted element. Error: ${l.message}`,{errOptions:{cause:l}})}async function mO(r,e,t,n){return r.message.includes("attempt #")?pO(r,e,t,n):gO(r)}async function pO(r,e,t,n){let o=r.message.split(/- retrying \w+ action, attempt #\d+/).filter(c=>c.length>0);if(!o.length)return n.warn({err:r},"Failed to parse Playwright error message for translation, returning raw message"),r;let i=o.length>2?o[o.length-2]:o[0];i=i.replace(/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g,"").replaceAll(" - ","").trim().replaceAll(`
3993
- `,";").replace(/\s+/g," ");let a="",l=await yr(e,n);if(l&&(a=`Target element HTML: ${ht(l,100,!0)}`),i.includes("element is not enabled"))return new A("ActionFailureError",`The element you attempted to interact with was disabled for the entire timeout duration. Please explicitly wait for the element to be enabled, change the element description to target an interactive element, or turn on the 'disable stability checks' option. ${a}`,{errOptions:{cause:r}});if(i.includes("intercepts pointer events")){let c="",s=i.match(/<.*?data-momentic-id="(\d+)".*?intercepts pointer events/)?.[1];if(s){let u=(await t.state.getRoot()).locator(qt(s)),d=await yr(u,n);d&&(c=`Covering element HTML: ${ht(d,100,!0)}`)}return new A("ActionFailureError",`The element you attempted to interact with was covered by another element such as dropdown, popup, or dialog for the entire timeout duration. Please add a step to hide the covering element or turn on the 'disable stability checks' option. ${a}
3994
- ${c}`,{errOptions:{cause:r}})}if(i.includes("element is not visible")){let c="The element you attempted to interact with has no bounding box or is explicitly hidden.";try{let s=await e.boundingBox({timeout:3e3});s?s.height===0?c="The element you attempted to interact with has zero height.":s.width===0&&(c="The element you attempted to interact with has zero width."):c="The element you attempted to interact with has no bounding box."}catch{}return new A("ActionFailureError",`${c} Please explicitly wait for the element to be visible or turn on the 'disable stability checks' option. ${a}`,{errOptions:{cause:r}})}return i.includes("element is outside of the viewport")?new A("ActionFailureError",`The element requested was outside of the browser viewport for the entire duration of the action. Please ensure you are not using non-standard zoom settings and the element is visible on the page. ${a}`):r}function gO(r){let e=r.message;if(e.includes("waiting for locator")&&e.includes("data-momentic-id")&&!e.match(/attempting \w+ action/)&&!e.includes("locator.evaluate"))throw new A("ActionFailureError",`Interacting with the element timed out. This is usually caused by the web page itself performing too many CPU-intensive operations or a lack of resources on your machine. Error: ${e}`,{errOptions:{cause:r}});return r}async function yT(r){try{return await hO(r)}catch(e){r.logger.warn({err:e},"Failed to transform locator for Chakra click, continuing...");return}}async function hO({locator:r,logger:e}){let[t,n]=await r.evaluate(c=>[c.id,c.tagName.toLowerCase()],{timeout:1e3}),o=await yr(r,e),i=await r.boundingBox({timeout:1e3});if(i===null){e.warn({elementDisplayString:o},"Attempting to click on element with no bounding box, not performing Chakra redirection");return}if(i.width>5||i.height>5||n!=="input")return;if(t)try{let c=r.page().locator(`label[for=${JSON.stringify(t)}]`);return await c.waitFor({state:"visible",timeout:1e3}),{locator:c,relativePoint:void 0}}catch{}let a=await r.evaluate(c=>{let s=window,u=c.parentElement;if(!u)return{type:"error",error:"Input click target has no parent for redirection"};let d=c.getBoundingClientRect(),m=u.getBoundingClientRect();if(m.width===0||m.height===0)return{type:"error",error:"Parent element has no width or height"};let p={x:Math.min(Math.max(1,d.left-m.left),m.width-1),y:Math.min(Math.max(1,d.top-m.top),m.height-1)},g=s._MOMENTIC_FEATURE_FLAGS?.[el],h=c.getAttribute(Er),f=!g&&h?qt(h):s.getMPath?.(c)?.join(" >");return f?{type:"result",selector:f,relativePoint:p,serializedForm:u.outerHTML.slice(0,500)}:{type:"error",error:"Could not generate selector for parent element"}},{timeout:1e3});if(a.type==="error")throw new Error(a.error);let l=r.page().locator(a.selector);return await l.waitFor({state:"visible",timeout:1e3}),e.info({parentElementResult:a,originalElementDisplayString:o},`Redirected click to parent element with selector: ${a.selector}`),{locator:l,relativePoint:a.relativePoint}}var bT=["date","datetime-local","month","time","week"],TT={date:/^\d{4}-\d{2}-\d{2}$/,"datetime-local":/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}$/,month:/^\d{4}-\d{2}$/,time:/^\d{2}:\d{2}$/,week:/^\d{4}-W\d{2}$/};async function vT(r){try{await B(fO(r),{milliseconds:3e3})}catch(e){r.logger.warn({err:e},"Failed to transform native datetime input, continuing...")}}async function fO({root:r,text:e,options:t,logger:n,callbacks:o}){let i=(await He({root:r,fn:()=>document.activeElement?.getAttribute("type")??"",timeout:1e3,arg:void 0,waitForPageLoad:o.waitForPageLoad,codePath:"transforming native datetime input"})).toLowerCase();if(!TT[i])return;TT[i].test(e)&&n.warn(`Detected datetime input (${e}) in normalized format - this may fail to fill correctly as it is not how the user would input the value`),t.clearContent=!1,n.info("Transforming datetime input to use sequential key presses")}import{z as At}from"zod";var AT=At.object({doubleClick:At.boolean().optional(),rightClick:At.boolean().optional(),force:At.boolean().optional(),waitForDownload:At.boolean().optional(),delayMs:At.number().optional(),downloadTimeoutMs:At.number().optional(),relativePosition:At.object({x:At.number(),y:At.number()}).optional()}),Sne=At.object({repeat:At.number().optional(),convertMeta:At.boolean().optional().describe("misleading name due to backcompat. converts keyshortcuts + meta/control to platform-specific combos. defaults to true"),delayMs:At.number().optional()});async function rl({locator:r,callbacks:e,logger:t,timeoutMs:n=1e3}){try{await Id(e,n);let o=r.evaluate(i=>{let a=window;a.momenticIsEligible=d=>{let p=window.getComputedStyle(d,null).getPropertyValue("display");if(p==="none"||p==="contents")return!1;let g=d.getBoundingClientRect();return!(!g.height||!g.width)},a.removeHighlightTimers=a.removeHighlightTimers||[],a.removeHighlightFunctions=a.removeHighlightFunctions||{};let l=0;for(;!a.momenticIsEligible(i)&&l<3;){if(!i.parentElement)throw new Error("No eligible non-empty parent found for highlighting");i=i.parentElement,l++}let c=i.style.getPropertyValue("outline"),s=i.style.getPropertyPriority("outline");i.style.setProperty("outline","5px dashed rgb(255, 0, 153)","important");let u=`momentic${Math.floor(Math.random()*1e7)}`;a[u]=()=>{i.style.removeProperty("outline"),i.style.setProperty("outline",c,s),i.getAttribute("style")||i.removeAttribute("style")},a.removeHighlightTimers.push(setTimeout(()=>{a[u](),a.removeHighlightFunctions?.[u]&&delete a.removeHighlightFunctions[u]},5e3)),a.removeHighlightFunctions[u]=a[u]},void 0,{timeout:n});return await B(o,{milliseconds:n}),!0}catch(o){return t.debug({err:o},"Failed to add node highlight, a page navigation likely occurred. This is non-fatal for tests."),!1}}async function Id(r,e=1e3){let t=await r.state.getRoot();await He({root:t,fn:()=>{let o=window,i=o.removeHighlightTimers||[];for(;i.length;){let a=i.pop();clearTimeout(a)}Object.values(o.removeHighlightFunctions??{}).forEach(a=>{a()})},timeout:e,arg:void 0,waitForPageLoad:r.waitForPageLoad,codePath:"removing element highlights"})}async function Pd(r){let e=!!r.browserCallbacks.state.userBrowserSettings.visualActions;return Cn({action:"clicking element",targetingResult:r.targetingResult,logger:r.logger,retryTimeoutMs:r.retryTimeoutMs,callbacks:r.browserCallbacks,func:async t=>CT({...r,targetingResult:t,useVisualClick:e})})}async function TO(r,e){let{redirectionAttempts:t=0}=e;if(t>=2)throw r;try{return await bO(r,e)}catch(n){throw e.redirectionAttempts===0?(e.logger.error({redirectionAttemptError:n,originalError:r},"Error handling click error, rethrowing original error"),r):n}}async function bO(r,e){let{logger:t,redirectionAttempts:n=0}=e,o=e.targetingResult.locator;if(r.message.includes("label")&&r.message.includes("for=")&&r.message.includes("intercepts pointer events")){let i=await o.getAttribute("id",{timeout:1e3});if(!i)throw r;let a=o.page().locator(`[for=${JSON.stringify(i)}]`);return await a.waitFor({state:"visible",timeout:1e3}),t.warn({err:r},"Attempting locator redirection due to input being covered by label"),CT({...e,targetingResult:{locator:a},redirectionAttempts:n+1})}else throw t.error({err:r},"Click error does not match any known recoverable patterns, rethrowing"),r}async function vO(r){let{browserCallbacks:e,logger:t,targetingResult:n,position:o,options:i}=r,a=await e.state.getRoot(),l=a&&a!==n.locator.page()&&"frameElement"in a?await a.frameElement():null,c;try{c=l?await An({promiseGenerator:async()=>l.boundingBox(),timeoutMs:3e3,logger:t}):null}catch(g){throw new A("UserInfrastructureError",`The frame containing the element Momentic was instructed to interact with was removed. Error: ${g.message}`)}finally{await l?.dispose()}let s=Date.now(),{clickX:u,clickY:d,reason:m}=await RO({frameCoordinates:c,logger:t,targetingResult:n,position:o,options:i}),p=AT.safeParse(i);t.info({frameCoordinates:c,position:o,options:p.success?p.data:void 0,clickLocation:{clickX:u,clickY:d,reason:m},duration:Date.now()-s},"Visual click")}async function AO(r){let{actionSource:e,targetingResult:t,options:n,logger:o}=r,i=r.targetingResult.locator,a=n?.relativePosition??r.position;if(e==="click"&&!a){let c=await yT({locator:i,logger:o});c&&(i=c.locator,a=c.relativePoint??a)}let l=n?.force||t.hints?.force||!1;try{n?.doubleClick?await i.dblclick({button:n.rightClick?"right":"left",timeout:3e3,position:a,delay:n?.delayMs??25,force:l}):await i.click({button:n?.rightClick?"right":"left",timeout:3e3,position:a,delay:n?.delayMs??25,force:l})}catch(c){let s=c;if(xO(s))o.warn({err:s},"Click action timed out while waiting for navigation after completion, continuing...");else return o.error({err:s},"Error clicking on locator, attempting to recover..."),TO(s,{...r,targetingResult:{...i,locator:i}})}}async function CT(r){let{options:e,logger:t,browserCallbacks:n,controllerCallbacks:o,useVisualClick:i,targetingResult:a}=r,l;e?.waitForDownload&&(l=(async()=>{let c=e.downloadTimeoutMs??3e4;try{return await a.locator.page().waitForEvent("download",{timeout:c})}catch(s){return s instanceof yO.TimeoutError?new A("ActionFailureError",`Download did not complete in ${c}ms`):new A("ActionFailureError",`Download failed: ${s.message}`)}})());try{await rl({locator:a.locator,callbacks:n,logger:t,timeoutMs:1e3})}catch(c){t.warn({err:c},"Error highlighting locator in click, continuing...")}if(i?await vO(r):await AO(r),e?.waitForDownload)if(l){if(!o?.createIsolatedFolder)throw new A("InternalWebAgentError","Cannot wait for download without a callback to create an isolated folder");t.info("Waiting for download to start and complete");let c=await B(l,{milliseconds:e.downloadTimeoutMs??3e4});if(c instanceof Error)throw c;return{downloadedFile:await CO(c,o.createIsolatedFolder,t)}}else throw new Error("No download promise or error but the step requested to wait for a download")}async function wO(r,e){if(e.hints?.clickableXY){let i=(r?.x??0)+e.hints.clickableXY.x,a=(r?.y??0)+e.hints.clickableXY.y;return[{x:i,y:a},"targeting hint"]}let t=await e.locator.boundingBox({timeout:3e3});if(!t)throw new A("ActionFailureError","Element does not have a bounding box");let n=t.x+t.width/2,o=t.y+t.height/2;return[{x:n,y:o},"halfway point"]}async function RO({frameCoordinates:r,logger:e,options:t,targetingResult:n,position:o}){let i,a,l;if(o){let d=await n.locator.boundingBox({timeout:3e3});i=(r?.x??0)+(d?.x??0)+o.x,a=(r?.y??0)+(d?.y??0)+o.y,l="predefined position"}else{let[d,m]=await wO(r,n);i=d.x,a=d.y,l=m}let c=n.locator.page(),s=t?.rightClick?"right":"left",u=t?.delayMs??25;return t?.doubleClick?await c.mouse.dblclick(i,a,{button:s,delay:u}):await c.mouse.click(i,a,{button:s,delay:u}),{clickX:i,clickY:a,reason:l}}async function CO(r,e,t){t.info("Download detected, saving file to disk");let n=await r.path(),o=Cd(r.suggestedFilename()),i=e();await r.saveAs(EO(i,o)),RT(n,{force:!0}),setTimeout(()=>{RT(i,{recursive:!0,force:!0})},5*60*1e3);let a=sT(SO(i),o);return t.info({uri:a,downloadFolder:i},"Saved download to isolated folder"),a}function xO(r){return r.message.includes("locator.click: Timeout")&&r.message.includes("click action done")}import{platform as _O}from"os";var MO={goToNextWord:{win32:"Control+ArrowRight",darwin:"Alt+ArrowRight",linux:"Control+ArrowRight"},goToPreviousWord:{win32:"Control+ArrowLeft",darwin:"Alt+ArrowLeft",linux:"Control+ArrowLeft"},selectNextWord:{win32:"Control+Shift+ArrowRight",darwin:"Alt+Shift+ArrowRight",linux:"Control+Shift+ArrowRight"},selectPreviousWord:{win32:"Control+Shift+ArrowLeft",darwin:"Alt+Shift+ArrowLeft",linux:"Control+Shift+ArrowLeft"},selectToStartOfLine:{win32:"Shift+Home",darwin:"Meta+Shift+LeftArrow",linux:"Shift+Home"},selectToEndOfLine:{win32:"Shift+End",darwin:"Meta+Shift+RightArrow",linux:"Shift+End"},deleteNextWord:{win32:"Control+Delete",darwin:"Alt+Fn+Delete",linux:"Control+Delete"},deletePreviousWord:{win32:"Control+Backspace",darwin:"Alt+Delete",linux:"Control+Backspace"}};function IO(){let r=_O();return r==="win32"?"win32":r==="darwin"?"darwin":"linux"}function xT(r){return JSON.stringify(r.split("+").sort())}function nl(r){let e=IO(),t=xT(r);for(let n of Object.values(MO))if(Object.values(n).some(o=>xT(o)===t))return n[e];return process.platform==="darwin"?r=r.replaceAll("Control","Meta"):r=r.replaceAll("Meta","Control"),r}async function Od({frame:r,page:e,deltaX:t,directionX:n,deltaY:o,directionY:i,signal:a,callbacks:l,logger:c}){if(!t&&!o)return;let s=n==="left"?-1:1,u=i==="up"?-1:1;if(r)await He({root:r,fn:([d,m,p,g])=>window.scrollTo(window.scrollX+(d??window.innerWidth)*p,window.scrollY+(m??window.innerHeight)*g),arg:[t,o,s,u],waitForPageLoad:l.waitForPageLoad,timeout:2e3,codePath:"scrolling page"});else{let d=e.viewportSize()||Ir,m=await He({root:e,fn:()=>document.body.scrollHeight,arg:void 0,waitForPageLoad:l.waitForPageLoad,timeout:2e3,codePath:"computing page height"}),[p,g,h]=await He({root:e,fn:()=>{let f=document.activeElement;if(!f)return[void 0,void 0,void 0];let y=f.getBoundingClientRect();return[f.scrollTop,y.x,y.y]},arg:void 0,waitForPageLoad:l.waitForPageLoad,timeout:2e3,codePath:"computing active element position"});await e.mouse.wheel((t??d.width)*s,(o??d.height)*u);try{let f=Date.now();for(;Date.now()-f<2e3;){a?.throwIfAborted();let y=await B(e.evaluate(()=>document.body.scrollHeight),{milliseconds:1e3}),[T,v,R]=await B(e.evaluate(()=>{let b=document.activeElement;if(!b)return[void 0,void 0,void 0];let x=b.getBoundingClientRect();return[b.scrollTop,x.x,x.y]}),{milliseconds:1e3});if(y===m&&T===p&&v===g&&R===h)break;m=y,p=T,g=v,h=R,await q(500)}}catch(f){c.warn({err:f},"Failed to wait for scroll to complete, continuing...")}}}async function Ld(r,e){let t,n;for(let o=0;o<4;o++)try{return t=r.pages(),await Promise.all(t.map(async i=>{let a="";try{a=e?.getTitles?await i.title():""}catch{a="Unknown page"}return{title:a,url:i.url()}}))}catch(i){n=i,await q(500)}throw new Error(`Failed to get tab titles after all retries: ${n?.message}`)}import{randomUUID as BO}from"crypto";import{cloneDeep as Dd}from"lodash-es";function qr(r,e){let t=r.findIndex(n=>n===e);if(!(t===-1||!r[t+1]))return r[t+1]}import{createHash as PO}from"crypto";var OO="v1";function ol(r,e){if(r.tagName.toLowerCase()==="svg"&&!NO(r))try{let t=_T(r,e),n=LO(JSON.stringify(t));return{version:OO,json:t,hash:n}}catch{return}}function LO(r){return PO("md5").update(r).digest("hex")}function _T(r,e){let t=r.tagName.toLowerCase(),n=DO(r);if(t==="image"&&n["xlink:href"])throw new Error("Image tags within SVGs are not supported");let o={type:t,props:n,children:[]};for(let i of r.childrenBackendIds){let a=e.backendIdToNode[i];if(a&&a.nodeType===1){let l=_T(a,e);l&&o.children.push(l)}}return o}function NO(r){let e=r.computedStyles.display,t=r.computedStyles.visibility,n=r.computedStyles.opacity;return e==="none"||t==="hidden"||n==="0"}function DO(r){let e={},t=r.attributes;for(let n of Object.keys(t))Ht.visualAttributesForSvgSerialization.includes(n)&&(e[n]=t[n]);return t.id&&r.tagName.toLowerCase()!=="svg"&&(e.id=t.id),e}var xn={r:147,g:196,b:125,a:.55},IT={showRulers:!1,showStyles:!1,showExtensionLines:!1,contrastAlgorithm:"aa",contentColor:xn,paddingColor:xn,borderColor:xn,marginColor:xn,eventTargetColor:xn,shapeColor:xn,shapeMarginColor:xn,showInfo:!0,showAccessibilityInfo:!0};function PT({snapshot:r,devicePixelRatio:e,computedStylesToFetch:t,logger:n}){let o=r.strings,i=r.documents,a={},l={},c={roots:[],backendIdToNode:a,frameIndexToIframeNode:l};return i.forEach((s,u)=>{let d=kO({allDocuments:i,stringConstants:o,computedStylesToFetch:t,devicePixelRatio:e,frameIndex:u,backendIdToNode:a,frameIndexToIframeNode:l,logger:n});c.roots.push(d)}),c}function kO({allDocuments:r,stringConstants:e,computedStylesToFetch:t,devicePixelRatio:n,frameIndex:o,frameIndexToIframeNode:i,backendIdToNode:a,logger:l}){let c=r[o],s=c.layout,u={};s.nodeIndex.forEach((N,k)=>{u[N]=k});let d=s.styles,m=s.bounds??[],p=c.nodes,g=p.contentDocumentIndex??{index:[],value:[]},h=p.backendNodeId??[],f=p.attributes??[],y=p.parentIndex??[],T=p.nodeName??[],v=p.nodeType??[],R=p.pseudoType??{index:[],value:[]},b=p.inputChecked??{index:[]},x=e[c.frameId];for(let N=0;N<h.length;N++){let k=h[N],$=v[N],De=f[N]??[],ee=y[N]!==void 0&&y[N]>=0?y[N]:void 0,oe=ee!==void 0?h[ee]:void 0,lt=oe!==void 0?a[oe]:void 0,M=R.index.indexOf(N),V=M!==-1?e[R.value[M]]:void 0,te=u[N],Re;te?Re=m[te]??[]:Re=[];let _e=T[N]!==void 0?e[T[N]]?.toLowerCase():void 0;if(!_e){l.warn({backendNodeId:k,frameId:x,frameIndex:o,nodeBounds:Re},"DOM node has no tag name");continue}let ve={backendNodeId:k,psuedoType:V,nodeType:$,frameIndex:o,parentFrameId:x,ownedFrameId:void 0,bounds:{x:Re[0]??null,y:Re[1]??null,width:Re[2]??null,height:Re[3]??null},computedStyles:{},attributes:{},parentBackendNodeId:oe??null,tagName:_e,parent:lt??void 0,childrenBackendIds:[],momenticIgnored:void 0,mPathSelector:void 0};lt&&lt.childrenBackendIds.push(k);let Rt=g.index.indexOf(N);if(Rt!==-1){let Ae=g.value[Rt];i[Ae]=ve;let Ve=r[Ae]?.frameId;ve.ownedFrameId=Ve!==void 0?e[Ve]:void 0}for(let Ae of Object.keys(ve.bounds)){let Ve=Ae;ve.bounds[Ve]!==null&&(ve.bounds[Ve]/=n)}let ct=te!==void 0?d[te]??[]:[];for(let Ae=0;Ae<ct.length&&!(Ae>=t.length);Ae++){let Ve=ct[Ae];if(Ve===void 0||isNaN(Ve))continue;let Jr=e[Ve];if(Jr===void 0)continue;let dr=t[Ae];ve.computedStyles[dr]=Jr}for(let Ae=0;Ae<De.length;Ae+=2){let Ve=De[Ae],Jr=De[Ae+1];if(!Ve||!Jr)continue;let dr=e[Ve],Go=e[Jr];!dr||!Go||(ve.attributes[dr]=Go)}b.index.includes(N)&&(ve.attributes.checked="true"),a[ve.backendNodeId]=ve}return a[h[0]]}function Nd(r,e){if(r.mPathSelector)return r.mPathSelector;let t=r.parent,n;if(!t)n=r.tagName;else if(r.tagName==="body")n="body";else{let i=t.childrenBackendIds.filter(c=>e.backendIdToNode[c]?.nodeType===1&&!e.backendIdToNode[c]?.psuedoType).indexOf(r.backendNodeId),a=` > ${r.tagName}:nth-child(${i+1})`;n=`${Nd(t,e)}${a}`}return r.mPathSelector=n,n}function MT(r,e){return r.parentBackendNodeId!==null?e.backendIdToNode[r.parentBackendNodeId]:r.frameIndex===0?void 0:e.frameIndexToIframeNode[r.frameIndex]}var UO=["html","#document","#document-fragment"];function OT({node:r,domGraph:e}){let t=[],n=r,o=MT(r,e);if(!o)return[r.tagName];let i=()=>{if(n=o,o=MT(o,e),!o&&n.frameIndex!==0)throw new Error("No parent node but not in main frame")},a=0;for(;o&&a<1e6;){if(a++,UO.includes(n.tagName)){i();continue}if(n.tagName==="body")t.push("body");else{let c=!1,s=1;for(let u=0;u<o.childrenBackendIds.length;u++){let d=o.childrenBackendIds[u],m=e.backendIdToNode[d];if(d===n.backendNodeId){t.push(`${n.tagName}:nth-child(${s})`),c=!0;break}else m?.nodeType===1&&!m.psuedoType&&s++}if(!c)throw new Error(`Could not find child (${n.tagName}) in parent's children list (${o.tagName})`)}i()}return t.reverse()}function LT(r,e){let t=r.locator("html"),n=[];for(let o=0;o<e.length;o++){let i=e[o];if(n.push(i),i.startsWith("iframe")){let a=n.join(" > ");n=[],o<e.length-1?t=t.frameLocator(a):t=t.locator(a)}}if(n.length&&(t=t.locator(n.join(" > "))),"owner"in t)throw new Error("Final locator from mpath is a frame locator");return t}async function NT(r,e){await r.send({method:"DOM.getDocument",params:{depth:0},timeout:2e3});let t=await r.send({method:"DOM.requestNode",params:{objectId:e},timeout:2e3}),o=(await r.send({method:"DOM.getAttributes",params:{nodeId:t.nodeId},timeout:2e3})).attributes,i=qr(o,Er);if(!i)throw new Error(`Could not find attribute ${Er} for object ${e}`);return i}function DT(r){let e=[];for(let t=0;t<r.domGraph.roots.length;t++){let n=r.domGraph.roots[t],o=FO({root:n,domGraph:r.domGraph,existingHashes:r.existingHashes,flagStore:r.flagStore,logger:r.logger});e=e.concat(o)}return e}function FO(r){let{root:e,domGraph:t,existingHashes:n}=r,o=[],i=[e];for(;i.length;){let a=i.pop();if(a.nodeType===1&&a.tagName.toLowerCase()==="svg"){let l=ol(a,t);l&&!n[l.hash]&&o.push(l)}for(let l of a.childrenBackendIds){let c=t.backendIdToNode[l];c&&i.push(c)}}return o}var zO=["focusable","keyshortcuts","controls","live","relevant","orientation"],GO=["selected","readonly","modal","required","invalid"],HO=["id","name","role","content"],kT=["absolute","fixed","sticky"],VO=["i"],jO=["path"],WO=["statictext","textbox","checkbox","combobox","iframe","rootwebarea","table","caption","columnheader","rowheader","gridcell","grid","row","rowgroup","cell","image","graphics-symbol","graphics-document","graphics-object","svgroot","button","link","list","listitem","tablist","tabpanel","tab","searchbox","menu","menubar","form","dialog","alertdialog","banner","navigation","main","menuitem","menuitemcheckbox","menuitemradio","option","radio","progressbar","switch","tree","treeitem","separator"],BT=["ariaHiddenElement","ariaHiddenSubtree","hiddenByChildTree","inertElement","inertSubtree","notRendered","notVisible"],zT=["activeAriaModalDialog","activeFullscreenElement","activeModalDialog"],$O=["menulistpopup","statictext","inlinetextbox"],qO=80,UT=100,GT=50,Fd=["StaticText","ListMarker","RootWebArea","LineBreak","emphasis","::before","::after"],KO=["cite"],YO={LabelText:["label"],listitem:["li"],image:["img","svg"],link:["a"],RootWebArea:["#document"],paragraph:["p"],LineBreak:["br"],separator:["hr"],"graphics-symbol":["svg","rect"],gridcell:["td","th"],SvgRoot:["svg"],navigation:["nav"],cell:["td","th"],row:["tr"],list:["ul"],heading:["h1","h2","h3","h4","h5","h6"]},XO={name:!0,value:!0,title:!0,alt:!0,placeholder:!0,checked:!0,selected:!0,contenteditable:!0},FT={indentLevel:0},kd=class r{id;role;name;nameSources;tagName;content;properties;internalProperties;ignoredReasons;dataMomenticId;importantProperties;pathFromRoot;mPathSelector;parent;children;parentFrame;domNode;backendNodeId;ignoredByCDP;flagNotActionableNodes;constructor(e){if(this.id=e.id,this.role=e.role,this.name=e.name,this.nameSources=e.nameSources,this.content=e.content,this.properties={},this.pathFromRoot=e.pathFromRoot,this.children=e.children,this.backendNodeId=e.backendNodeID,this.ignoredByCDP=e.ignoredByCDP,this.internalProperties=e.internalProperties??{},this.parentFrame=e.parentFrame,this.ignoredReasons=e.ignoredReasons,this.importantProperties=e.importantProperties,this.flagNotActionableNodes=e.flagNotActionableNodes,e.properties&&e.properties.forEach(t=>{t.name==="keyshortcuts"?this.dataMomenticId=parseInt(t.value.value):this.properties[t.name]=t.value.value}),e.domNode){this.domNode=e.domNode,this.tagName=e.domNode.tagName||void 0;let t=e.domNode.attributes.id;this.name=this.name||e.domNode.attributes.name||(t&&t.length<GT?t:""),this.role=this.role||(e.domNode.attributes.role??""),eL(this.properties,e.domNode,e.importantProperties)}rL(this)}getSerializedFormWithContext(){return this.serialize({noId:!0,maxLevel:1,neighbors:1})}getNodeOnlySerializedForm(){return this.serialize({noId:!0,noChildren:!0,noContent:!0})}getLogForm(){return JSON.stringify({id:this.id,name:this.name??"",role:this.role??"",backendNodeId:this.backendNodeId})}isInteresting(e){if(this.domNode&&jO.includes(this.domNode.tagName)||this.domNode?.computedStyles.display==="contents"||this.ignoredReasons.some(n=>zT.includes(n)))return!1;if(e){if(Object.keys(this.domNode?.attributes??{}).some(o=>$T(o,e)))return!0;let n=this.domNode?.attributes.class?.split(" ");if(n&&n.length>0&&n.some(o=>qT(o,e))||e.styles?.some(o=>{let i=o.split(":");if(i.length!==2)return!1;let a=i[0]?.trim(),l=i[1]?.trim();if(a===void 0||l===void 0)return!1;let c=this.domNode?.computedStyles[a];return c!==void 0&&(c===l||l==="*")}))return!0}if(this.domNode&&VO.includes(this.domNode.tagName)||WO.includes(this.role.toLowerCase())||this.role.toLowerCase()==="inlinetextbox"&&this.tagName||!this.properties.hidden&&(this.properties.focusable||this.properties.settable)||Ht.alwaysInterestingTruthyPropertyNames.some(n=>!!this.properties[n]))return!0;let t=this.properties.class;return typeof t=="string"&&t.split(" ").some(n=>WT(n))?!0:this.children.every(n=>n.role==="StaticText")&&this.internalProperties?.inCodeMirrorEditor?!1:this.children.some(n=>n.role==="StaticText")||this.children.length>1&&this.children.some(n=>n.tagName==="input")?!0:this.domNode&&(this.domNode.bounds.x===null||this.domNode.bounds.y===null||!this.domNode.bounds.width||!this.domNode.bounds.height)?!1:!!this.name.trim()||!!this.content||Object.keys(this.properties).some(n=>n.startsWith("data"))}shouldSerializeBounds(){let e=this.domNode?.computedStyles.position;return!!(e&&(e==="absolute"||e==="fixed"||e==="sticky"))}isNotActionable(){return!!(this.domNode?.computedStyles.display==="contents"||this.domNode&&(this.domNode.bounds.x===null||this.domNode.bounds.y===null||!this.domNode.bounds.width||!this.domNode.bounds.height))}serialize(e=FT){let t=Object.assign({},FT,e),{indentLevel:n,noChildren:o,noProperties:i,noId:a,noContent:l,condensedMode:c}=t,s=Dd(this.properties),u=" ".repeat(n),d=this.role||"",m=this.tagName??"unknown",p=this.name;d==="heading"&&p==="heading"&&(p=""),this.nameSources?.find(b=>!b.superseded&&b.type==="contents")&&this.children.length>0&&(p="");let h=this.nameSources?.find(b=>!b.superseded);if(h&&!h.nativeSource&&h.type==="relatedElement"){let b=h.attributeValue?.relatedNodes??[];b.length===1&&b[0].text&&b[0].text===p&&(p="")}let f=Fd.includes(this.role)||KO.includes(this.tagName||"");if(this.role==="StaticText"||this.role==="ListMarker")return`${u}${p}
3995
- `;let y=`${u}<${m}`;!a&&!f&&(y+=` id="${this.id}"`);let T=l??!1;if((s.multiline||s.contenteditable)&&this.children.length>0&&(T=!0),d&&d!=="generic"&&d!==m&&!(YO[d]??[]).includes(m)&&(y+=` role=${JSON.stringify(d)}`),p&&(y+=` name=${JSON.stringify(p)}`),this.content&&!T&&(y+=` content=${JSON.stringify(this.content)}`),this.flagNotActionableNodes&&this.tagName!=="#document"&&this.isNotActionable()&&(y+=` ${Ht.ineligibleElementAttribute}`),this.shouldSerializeBounds()&&this.domNode?.bounds){let b=this.domNode.bounds,x=Math.round(b.x??0),N=Math.round(b.y??0),k=Math.round((b.x??0)+(b.width??0)),$=Math.round((b.y??0)+(b.height??0));y+=` bounds=[${x} ${N} ${k} ${$}]`}let v=Date.now();if(Object.keys(s).length>0&&!i){if(Date.now()-v>1e3)throw new Error(`Serialization for the HTML element with tag ${m} and internal ID ${this.id} took too long. Please ensure your machine has enough resources to run Momentic.`);Object.entries(s).forEach(([b,x])=>{if(!zO.includes(b)){{if(GO.includes(b)&&(!x||x==="false"))return;if(b==="value"&&T&&(s.type==="text"||this.role==="textbox"))return;if(b==="level"&&`${x}`=="1")return;if(b==="url"&&s.src&&m==="img")return;if(b==="url"&&s.href&&m==="a")return;if(b==="editable"&&x==="plaintext")return;if(b==="type"&&x===m)return;if(c&&!XO[b])return}typeof x=="string"?y+=` ${b}="${ht(x,UT,!0)}"`:typeof x=="boolean"?x?y+=` ${b}`:y+=` ${b}={false}`:typeof x<"u"&&(y+=` ${b}={${ht(JSON.stringify(x),UT,!0)}}`)}})}if(m==="::before"||m==="::after"){let b="";for(let x of this.children)b+=x.serialize({...e,indentLevel:n,neighbors:0});return b}let R=e.maxLevel!==void 0&&n/2>=e.maxLevel;if(this.children.length===0||o||R)y+=` />
3996
- `;else{let b="";for(let N of this.children)b+=N.serialize({...e,indentLevel:n+2,neighbors:0});let x=b.trim();x.length<=qO&&!x.includes(`
3997
- `)?y+=`>${x}</${m}>
3998
- `:y+=`>
3999
- ${b}${u}</${m}>
4000
- `}if(e.neighbors!==void 0&&e.neighbors>0&&this.parent){let b=this.parent.children.findIndex(k=>k.id===this.id),x=b>0?this.parent.children[b-1]?.serialize({...e,neighbors:0}):"",N=b<this.parent.children.length-1?this.parent.children[b+1]?.serialize({...e,neighbors:0}):"";return`${x||""}
4001
- ${y}
4002
- ${N||""}`}return y}shallowClone(){let e=new r({id:this.id,role:this.role,name:this.name,nameSources:this.nameSources,content:this.content,properties:[],pathFromRoot:this.pathFromRoot,children:[],ignoredReasons:this.ignoredReasons,backendNodeID:this.backendNodeId,ignoredByCDP:this.ignoredByCDP,internalProperties:Dd(this.internalProperties),importantProperties:this.importantProperties,parentFrame:this.parentFrame,flagNotActionableNodes:this.flagNotActionableNodes});return e.tagName=this.tagName,e.dataMomenticId=this.dataMomenticId,e.properties=Dd(this.properties),e}},Ud=class r{constructor(e,t,n,o){this.root=e;this.a11yIdNodeMap=t;this.dataMomenticIdMap=n;this.selectorToNodeMap=o}serialize(e){return this.root.serialize(e)}pruneUsingSummaries(e){let t=this.root;if(!t)throw new Error("Cannot prune a11y tree with no root");let n={},o={},i={},a=c=>{let s=c.shallowClone();if(e[c.id])return s.properties["data-momentic-summary"]=e[c.id],n[c.id]=s,c.dataMomenticId&&(o[c.dataMomenticId]=s),c.mPathSelector&&(i[c.mPathSelector]=s),s;let u=[];for(let d of c.children){let m=a(d);m&&(u.push(m),m.parent=s)}return s.children=u,n[c.id]=s,c.dataMomenticId&&(o[c.dataMomenticId]=s),c.mPathSelector&&(i[c.mPathSelector]=s),s},l=a(t);return new r(l,n,o,i)}pruneUsingRelevantIds(e){let t=this.root;if(!t)throw new Error("Cannot prune a11y tree with no root");function n(i,a=!1){let l=e.has(`${i.id}`)||i.id===t?.id,c=i.shallowClone(),s=i.children,u=!1,d=[];for(let m of s){let p=n(m,l||u);p&&(d.push(p),p.parent=c,u=!0)}if(c.children=d,l||u)return c;if(Fd.includes(i.role)&&a)return c}let o=n(t);return new r(o,this.a11yIdNodeMap,this.dataMomenticIdMap,this.selectorToNodeMap)}pruneToSerializedCharLimit(e){let t=this.root;if(!t)throw new Error("Cannot prune a11y tree with no root");let n=t.shallowClone(),o=()=>n.serialize().length,i=(a,l)=>{l.children=[];for(let c of a.children){let s=c.shallowClone();if(s.parent=l,l.children.push(s),o()>e){l.children.pop();break}if(i(c,s),o()>e){for(;s.children.length>0&&o()>e;)s.children.pop();if(o()>e){l.children.pop();break}}}};for(i(t,n);n.children.length>0&&o()>e;)n.children.pop();return new r(n,this.a11yIdNodeMap,this.dataMomenticIdMap,this.selectorToNodeMap)}};function JO(r){return r.name?.value?`"${r.name.value}"`:r.role?.value&&r.role.value!=="none"&&r.role.value!=="generic"?`"${r.role.value}"`:`"${r.nodeId}"`}function QO(r,e,t,n){return r.bounds.x===null||r.bounds.y===null||r.bounds.height===null||r.bounds.width===null||r.bounds.width===0||r.bounds.height===0?!0:r.bounds.x+r.bounds.width<e.leftBound||r.bounds.x>e.rightBound?(Ka({logger:t,logKey:n,maxCount:5,intervalMs:3e3},{domNode:r,logKey:n},"Filtering out node since it is not in the viewport horizontally"),!1):r.bounds.y+r.bounds.height<e.upperBound||r.bounds.y>e.lowerBound?(Ka({logger:t,logKey:n,maxCount:5,intervalMs:3e3},{domNode:r,logKey:n},"Filtering out node since it is not in the viewport vertically"),!1):r.computedStyles.display==="none"?(t.debug({domNode:r},"Filtering out node since it has display none"),!1):!0}async function HT({node:r,parent:e,frameId:t,frameContext:n,axGraph:o,domGraph:i,inputNodeMap:a,flagNotActionableNodes:l,showZeroOpacityElements:c,filterByViewport:s,viewportDetails:u,useMPaths:d,importantProperties:m,cdpClient:p,logger:g,callId:h}){if(!e&&r.parentId)throw new Error(`Got no parent for accessibility node ${r.nodeId}: ${JSON.stringify(r)}`);let f=(M,V={})=>{},y=r.backendDOMNodeId,T=$O.includes(r.role?.value?.toLowerCase()??"");if(!T&&y===void 0)return f("Filtering out node since it doesn't exist in the DOM"),[];let v=y?i.backendIdToNode[y]:void 0;if(!T&&!v)try{let M=await B(p.send({method:"DOM.describeNode",params:{backendNodeId:y}}),{milliseconds:750,fallback:()=>{g.debug("Timeout getting node from CDP while processing a11y tree")}});if(M&&M.node.nodeName.toLowerCase()==="slot"&&M.node.distributedNodes?.length)g.debug({redirectedDomNode:v,parentAXNode:e?.getNodeOnlySerializedForm(),originalAXNode:r,cdpResult:M},"Redirecting node to assigned slot");else return f("Filtering out node since it doesn't exist in the DOM",{cdpResult:M}),[]}catch(M){return f("Filtering out node since it doesn't exist in the DOM",{err:M}),[]}if(v&&e&&s&&u&&r.backendDOMNodeId&&!QO(v,u,g,h))return v.momenticIgnored=!0,[];if(v&&v.computedStyles.display==="none")return v.momenticIgnored=!0,[];if(v&&v.computedStyles.opacity==="0"&&c!==!0){if(c==="inputs-only"&&v.tagName.toLowerCase()!=="input")return v.momenticIgnored=!0,[];if(c===!1)return v.momenticIgnored=!0,[]}let R=r.name?.value?typeof r.name.value=="string"?r.name.value:`${r.name.value}`:"",b=r.value?.value?typeof r.value.value=="string"?r.value.value:`${r.value.value}`:"",x=new kd({domNode:v,id:parseInt(r.nodeId),role:r.role?.value||"",name:R,nameSources:r.name?.sources,content:b,properties:r.properties,children:[],ignoredReasons:r.ignoredReasons?.filter(M=>BT.includes(M.name)||zT.includes(M.name))??[],pathFromRoot:(e?`${e.pathFromRoot} `:"")+JO(r),backendNodeID:r.backendDOMNodeId,ignoredByCDP:r.ignored,internalProperties:{inCodeMirrorEditor:e?.internalProperties?.inCodeMirrorEditor},importantProperties:m,parentFrame:n.type==="root"?void 0:n,flagNotActionableNodes:l}),N=n,k=a[t],$=t;if(v?.tagName.toLowerCase()==="iframe"&&v.ownedFrameId){let M=n.childFrames.find(Re=>Re.frameId===v.ownedFrameId),V=o[M?.frameId??""]?.root,te=a[M?.frameId??""];if(M&&V&&te){r.childIds&&r.childIds.length>0&&g.debug("Replacing existing node's children with children from the iframe");let Re=V;r.childIds=Re.childIds,N=M,k=te,$=M.frameId}}let De=v?.childrenBackendIds?.length??0,ee=(r.childIds??[]).filter(M=>!!k.get(parseInt(M))).length;if(De>ee){let M=r.childIds?.map(te=>k.get(parseInt(te))).filter(Boolean).map(te=>te?.backendDOMNodeId).filter(te=>te!==void 0)??[],V=0;for(let te of v?.childrenBackendIds??[]){if(M.includes(te)){V=(r.childIds?.findIndex(ct=>k.get(parseInt(ct))?.backendDOMNodeId===te)??0)+1;continue}let Re=i.backendIdToNode[te];if(!Re||Re?.tagName.toLowerCase()!=="svg")continue;let _e=Math.floor(-1*Math.random()*1e7),ve={nodeId:_e.toString(),parentId:r.nodeId,ignored:!1,backendDOMNodeId:te,frameId:$,role:{type:"string",value:"graphics-symbol"}};k.set(_e,ve),r.childIds||(r.childIds=[]),r.childIds.splice(V,0,_e.toString()),V++}}if(r.childIds?.length===1&&v){let M=k.get(parseInt(r.childIds[0])),V=M?.role?.value,te=v.childrenBackendIds;if(M&&V==="StaticText"&&te.length===1){let Re=i.backendIdToNode[te[0]];if(Re?.tagName?.toLowerCase()==="span"){let _e=Math.floor(-1*Math.random()*1e7).toString(),ve={nodeId:_e,parentId:r.nodeId,ignored:!1,backendDOMNodeId:Re.backendNodeId,frameId:$,childIds:[M.nodeId]};M.parentId=_e,k.set(parseInt(_e),ve),r.childIds=[_e]}}}for(let M of r.childIds??[]){if(!M)continue;let V=k.get(parseInt(M));if(!V)continue;let te=await HT({node:V,parent:x,domGraph:i,axGraph:o,frameId:$,frameContext:N,inputNodeMap:a,cdpClient:p,logger:g,callId:h,filterByViewport:s,showZeroOpacityElements:c,importantProperties:m,viewportDetails:u,useMPaths:d,flagNotActionableNodes:l});te.length&&(x.children=x.children.concat(te))}if(x.role==="StaticText"&&(x.children=[]),x.children.length===1&&x.children[0].role==="StaticText"){let M=x.name,V=x.children[0]?.name;(M===V||!V)&&(x.children=[])}let oe=[];for(let M=x.children.length-1;M>=0;M--){let V=x.children[M];if(V.role!=="StaticText"){oe.push(V);continue}if(M===0||x.children[M-1].role!=="StaticText"){oe.push(V);continue}x.children[M-1].name+=V.name}if(x.children=oe.reverse(),!x.isInteresting(m)&&r.parentId)return v&&(v.momenticIgnored=!0),x.children;for(let M of x.children)M.parent=x;return tL(x),v&&d&&Nd(v,i),[x]}function VT({node:r,a11yIdNodeMap:e,dataMomenticIdMap:t,logger:n,callId:o,domGraph:i,useMPaths:a,selectorToNodeMap:l,iconKnowledgeBase:c,startId:s=1}){r.id=s,s+=1,e[r.id]=r,r.dataMomenticId?t[r.dataMomenticId]=r:Fd.includes(r.role);let u=r.backendNodeId,d=u!==void 0?i.backendIdToNode[u]:void 0;if(a&&d&&d.mPathSelector&&(l[d.mPathSelector]=r,r.mPathSelector=d.mPathSelector),c&&d&&d.tagName?.toLowerCase()==="svg"){let m=ol(d,i),p=m?c[m.hash]:void 0,g=p?p.description:void 0;p&&(r.properties["data-momentic-description"]=g)}for(let m of r.children)s=VT({node:m,a11yIdNodeMap:e,dataMomenticIdMap:t,logger:n,callId:o,startId:s,useMPaths:a,domGraph:i,selectorToNodeMap:l,iconKnowledgeBase:c});return s}async function jT({rawA11yGraph:r,domGraph:e,startingFrameId:t,logger:n,cdpClient:o,filterByViewport:i,showZeroOpacityElements:a,flagNotActionableNodes:l,importantProperties:c,viewportDetails:s,useMPaths:u,frameContext:d,iconKnowledgeBase:m}){let p=t??"root",g=r[p]?.root;if(!g)throw new Error("A11y tree has no root");let h=BO(),f=x=>{let N=x.allNodes.filter($=>!$.ignoredReasons?.find(ee=>BT.includes(ee.name))),k=new Map;return N.forEach($=>{k.set(parseInt($.nodeId),$)}),k},y={};Object.entries(r).forEach(([x,N])=>{y[x]=f(N)});let T=await HT({node:g,domGraph:e,parent:null,inputNodeMap:y,axGraph:r,frameId:p,frameContext:d,cdpClient:o,logger:n,callId:h,showZeroOpacityElements:a,importantProperties:c,filterByViewport:i,viewportDetails:s,useMPaths:u,flagNotActionableNodes:l});if(T.length>1)throw new Error(`Something went horribly wrong processing the a11y tree, we got: ${JSON.stringify(T)}`);if(T.length===0)throw new Error("There are no accessible elements on this page or frame. Are you sure this website loads properly?");let v={},R={},b={};return VT({node:T[0],a11yIdNodeMap:v,dataMomenticIdMap:R,selectorToNodeMap:b,domGraph:e,logger:n,callId:h,useMPaths:u,iconKnowledgeBase:m}),new Ud(T[0],v,R,b)}function ZO(r,e,t,n){if(r==="class"){if(t.tagName?.toLowerCase()==="svg")return e.split(" ").filter(a=>a.length<GT&&!Ht.bannedClassSubstrings.some(l=>a.includes(l))).slice(0,3).join(" ");let o=e.split(" "),i=[];for(let a of o)if(WT(a,n)){i.push(a);continue}return i.length?i.join(" "):null}if(e==="true")return!0;if(e==="false")return!1;try{let o=parseInt(e);if(!isNaN(o))return o}catch{}return r==="src"&&e.includes("base64")?e.slice(0,e.indexOf("base64")+6)+"...":e.length>60?e.slice(0,50)+"...":e}function eL(r,e,t){if(!e)return;Object.entries(e.attributes).forEach(([a,l])=>{let c=r[a]||a.startsWith("aria")||HO.includes(a);if((Ht.relevantElementAttributes.includes(a)||$T(a,t))&&!c){let u=ZO(a,l,e,t);u!==null&&(r[a]=u)}});let n,o=[];if(e.computedStyles.position&&kT.includes(e.computedStyles.position))n=e.computedStyles.position;else if(e.attributes.style){for(let a of kT)if(e.attributes.style.includes(`position: ${a}`)){n=a;break}}n&&o.push(`position: ${n}`);let i;e.computedStyles.opacity&&e.computedStyles.opacity==="0"&&(i="opacity: 0"),i&&o.push(i);for(let a of t?.styles??[]){let l=a.split(":"),c=l[0]?.trim(),s=l[1]?.trim(),u=e.computedStyles[c??""];if(c!==void 0&&s!==void 0&&u!==void 0&&(s==="*"||u===s)){let d=e.computedStyles[c],m=`${c}: ${d}`;o.includes(m)||o.push(m)}}o.length>0&&(r.style=o.join("; "))}function tL(r){let e=r.properties.class;if(typeof e=="string"&&e.includes("cm-content")){r.children.forEach((i,a)=>{i.properties["cm-line-number"]=`${a+1}`});return}if(typeof e=="string"&&e.includes("notion-page-content")){r.children.forEach((i,a)=>{i.properties["block-number"]=`${a+1}`}),r.children.length>0&&(r.children[r.children.length-1].properties.description="This is the last block in the document. Click here to add new text to the end.");return}if(r.tagName==="table"){let i=[],a=r.children.find(c=>c.tagName==="thead");if(a){let c=a.children.find(s=>s.tagName==="tr");if(c){let s=c.children.filter(u=>u.tagName==="th");s.forEach((u,d)=>{u.properties["col-index"]||(u.properties["col-index"]=d+1),i?.push(ht(u.name,100,!1))}),i?.length!==s.length&&(i=void 0)}}let l=0;for(let c of r.children)if(c.tagName==="tbody")for(let s=0;s<c.children.length;s++){let u=c.children[s];if(u.tagName!=="tr")continue;if(s===0&&!i?.length){let p=u.children.filter(g=>g.tagName==="th");if(p.length){if(i=p.map(g=>ht(g.name,100,!1)),i.length===p.length)continue;i=void 0}}l+=1,u.properties["row-index"]||(u.properties["row-index"]=l);let d=u.children.filter(p=>p.tagName==="td"||p.tagName==="th"),m=d.length===i?.length;d.forEach((p,g)=>{p.tagName!=="th"&&(p.properties["col-index"]||(p.properties["col-index"]=g+1),m&&(p.properties.col||(p.properties.col=i[g])))})}}}function rL(r){let e=r.properties.class,t=typeof e=="string"&&e.includes("cm-content");r.internalProperties.inCodeMirrorEditor=r.internalProperties?.inCodeMirrorEditor||t}function WT(r,e){if(e&&qT(r,e))return!0;if(Ht.bannedClassSubstrings.some(t=>r.includes(t)))return!1;if(Ht.alwaysInterestingClassNames.includes(r))return!0;for(let t of Ht.alwaysInterestingClassPrefixes)if(r.startsWith(t))return!0;return!1}function $T(r,e){if(e?.attributes?.includes(r))return!0;for(let t of e?.attributes??[])if(t.endsWith("*")){let n=t.slice(0,-1);if(r.startsWith(n))return!0}return!1}function qT(r,e){if(e?.classes?.includes(r))return!0;for(let t of e?.classes??[])if(t.endsWith("*")){let n=t.slice(0,-1);if(r.startsWith(n))return!0}return!1}var il=class r{constructor(e,t,n,o,i){this.session=e;this.logger=t;this.contextGetter=n;this.pageGetter=o;this.defaultTimeoutMs=i}cdpInitializingPromise=void 0;cdpCrashDetails=void 0;cdpFullyDead=!1;loadEventLogs=[];static async init({logger:e,contextGetter:t,pageGetter:n,defaultTimeoutMs:o}){let i=t(),a=n(),l,c;for(let u=0;u<2;u++)try{l=await B(i.newCDPSession(a),{milliseconds:o*u,fallback:()=>{throw new A("UserInfrastructureError",`Failed to initialize Chrome session within the page load timeout (${a.url()})`)}});break}catch(d){await q(500),c=d}if(!l)throw c;let s=new r(l,e,t,n,o);try{await B(s.registerHandlers(l),{milliseconds:o,message:`CDP handler registration timed out after ${o}ms`})}catch(u){throw s.cdpFullyDead=!0,new A("UserInfrastructureError",`Failed to initialize CDP client: ${u}`)}return s}async registerHandlers(e){e.on("Target.attachedToTarget",async()=>{try{await e.send("Runtime.runIfWaitingForDebugger")}catch(t){this.logger.warn({err:t},"Failed to run Runtime.runIfWaitingForDebugger")}}),e.on("Target.targetCrashed",t=>{this.cdpCrashDetails={...this.cdpCrashDetails??{},targetCrashDetails:JSON.stringify(t)},this.logger.error({payload:t},"CDP session crashed, Momentic will likely not function correctly")}),e.on("Inspector.targetCrashed",t=>{this.cdpCrashDetails={...this.cdpCrashDetails??{},inspectorCrashDetails:JSON.stringify(t)},this.logger.error({payload:t},"CDP inspector session crashed, Momentic will likely not function correctly")}),e.on("Page.frameRequestedNavigation",t=>{this.loadEventLogs.push(`[${new Date(Date.now()).toLocaleString("en-US",{timeZone:"America/Los_Angeles"})}] Frame requested navigation: ${JSON.stringify(t)}`)}),e.on("Page.navigatedWithinDocument",t=>{this.loadEventLogs.push(`[${new Date(Date.now()).toLocaleString("en-US",{timeZone:"America/Los_Angeles"})}] Navigated within document: ${JSON.stringify(t)}`)}),e.on("Page.lifecycleEvent",t=>{this.loadEventLogs.push(`[${new Date(Date.now()).toLocaleString("en-US",{timeZone:"America/Los_Angeles"})}] Page lifecycle event: ${JSON.stringify(t)}`)}),e.on("Page.loadEventFired",()=>{this.loadEventLogs.push(`[${new Date(Date.now()).toLocaleString("en-US",{timeZone:"America/Los_Angeles"})}] Page load event fired`)}),await e.send("Accessibility.enable"),await e.send("Page.enable"),await e.send("DOM.enable"),await e.send("Overlay.enable"),await e.send("DOMSnapshot.enable"),await e.send("CSS.enable")}async send({method:e,params:t,timeout:n=this.defaultTimeoutMs,timeoutMsg:o}){for(;this.cdpInitializingPromise;)await B(this.cdpInitializingPromise,{milliseconds:n});if(this.cdpCrashDetails){if(this.cdpFullyDead)throw new A("UserInfrastructureError",`The browser inspector session encountered a critical crash: ${JSON.stringify(this.cdpCrashDetails)}`);this.logger.warn(`Detected crashed CDP client before method ${e}, reinitializing before proceeding...`),await this.reinitialize()}try{return await B(this.session.send(e,t),{milliseconds:n,message:o??`Chrome command ${e} timed out after ${n}ms. This is likely an infrastructure issue caused by a lack of compute resources or a crash at the browser level.`})}catch(i){throw["Internal error","Target crashed"].some(a=>i.message.includes(a))&&!this.cdpInitializingPromise&&(this.logger.warn({err:i},`CDP crashed during CDP method ${e}, re-initializing client`),await this.reinitialize()),i}}async createRawCDPSession(e=this.defaultTimeoutMs){let t=e,n=this.pageGetter(),o=await B(this.contextGetter().newCDPSession(n),{milliseconds:t,fallback:()=>{throw this.logger.error(`Failed to initialize CDP session within the page load timeout (${n.url()})`),new A("UserInfrastructureError",`Failed to initialize CDP session within the page load timeout (${n.url()})`)}});return this.logger.debug(`Created new CDP session for ${n.url()}`),o}async reinitialize(e=this.defaultTimeoutMs){await this.cdpInitializingPromise,this.cdpInitializingPromise=(async()=>{try{let t=this.session;this.session=await this.createRawCDPSession(e),await B(this.registerHandlers(this.session),{milliseconds:e,message:`Failed to register CDP handlers within ${e}ms`}),this.logger.debug("Successfully reinitialized and attached new handlers to CDP session");try{await B(t.detach(),{milliseconds:1e3})}catch(n){this.logger.warn({err:n},"Failed to detach old CDP session after reinitialization, continuing...")}this.cdpCrashDetails=void 0,this.cdpFullyDead=!1}catch(t){this.cdpCrashDetails={...this.cdpCrashDetails??{},reinitializeError:`${t}`},this.cdpFullyDead=!0}finally{this.cdpInitializingPromise=void 0}})(),await this.cdpInitializingPromise}on(e,t){return this.session.on(e,t),this.session}off(e,t){return this.session.off(e,t),this.session}addListener(e,t){return this.session.addListener(e,t),this.session}removeListener(e,t){return this.session.removeListener(e,t),this.session}};var Ao="<empty>";function nL(r){return r.includes("doubleclick.net")||r.includes("googletagmanager.com")||r.includes("googlesyndication.com")||r.includes("s.amazon-adsystem.com")||r.includes("smartadserver.com")||r.includes("omnitagjs.com")||r.includes("x.adroll.com")}function YT(r){let e=r.adFrameStatus?.adFrameType;return e==="child"||e==="root"||nL(r.url)}async function oL(r,e){let t=await r.send({timeout:3e3,method:"DOM.getFrameOwner",params:{frameId:e}}),o=(await r.send({timeout:3e3,method:"DOM.pushNodesByBackendIdsToFrontend",params:{backendNodeIds:[t.backendNodeId]}})).nodeIds[0],a=(await r.send({timeout:3e3,method:"DOM.describeNode",params:{backendNodeId:t.backendNodeId}})).node;return a.nodeId=o,a}async function wo({cdpClient:r,page:e,logger:t}){let n={type:"root",childFrames:[],page:e},o=[],[i,a]=await Promise.all([r.send({timeout:3e3,method:"Page.getFrameTree",params:{}}),r.send({timeout:3e3,method:"DOM.getDocument",params:{depth:0}})]),s=(i.frameTree.childFrames??[]).map(async(d,m)=>{if(YT(d.frame))return null;try{return await XT({cdpClient:r,rawFrameTree:d,indices:[m],parent:n,warnings:o,logger:t})}catch(p){return o.push(`Failed to get child frame: ${p}`),null}}),u=await Promise.all(s);return n.childFrames=u.filter(d=>d!==null),o.length&&t?.warn({warnings:o},"Got warnings when fetching frame tree"),n}async function XT({cdpClient:r,rawFrameTree:e,indices:t,parent:n,warnings:o,logger:i}){let a=e.frame.id,l=await oL(r,a),c=l.attributes??[],s=null,u=[];for(let g of["src","name","id","title","srcdoc","sandbox"]){let h=qr(c,g);h&&(u.push(`${g}=${JSON.stringify(h)}`),g==="src"&&(s=h))}let d={type:"frame",cdpFrame:e.frame,url:e.frame.url,frameId:a,locationData:{indices:t,attributeSelectors:u},src:s,childFrames:[],parent:n,domNode:l},p=(e.childFrames??[]).map(async(g,h)=>{if(YT(g.frame))return null;try{return await XT({cdpClient:r,rawFrameTree:g,indices:[...t,h],parent:d,warnings:o,logger:i})}catch(f){return o.push(`Failed to get child frame (child ${h} of frame with url ${e.frame.url}): ${f}`),null}});return d.childFrames=(await Promise.all(p)).filter(g=>g!==null),d}async function iL(r){try{return await r.owner().count()===1}catch{return!1}}async function aL(r){try{return await r.count()===1}catch{return!1}}async function sr(r,e){let t=[],n=r;for(;n.parent.type==="frame";)t.push(n.parent),n=n.parent;t.reverse();let o=e,i=[];for(let s of t){let u=!1;for(let d of[...s.locationData.attributeSelectors,Ao]){let m=o.frameLocator(d===Ao?"iframe":`iframe[${d}]`);if(await iL(m)){u=!0,o=m,i.push(d);break}}if(!u)throw new A("ActionFailureError",`Failed to find a unique attribute to identify intermediate frame with url matching '${s.url}'. Please attach a unique 'id', 'name', 'title', or 'src' attribute to the frame.`)}let a;for(let s of[...r.locationData.attributeSelectors,Ao]){let u=o.locator(s===Ao?"iframe":`iframe[${s}]`);if(await aL(u)){a=u,i.push(s);break}}if(!a)throw new A("ActionFailureError",`Failed to find a unique attribute to identify target frame with url matching '${r.url}'. Please attach a unique 'id', 'name', 'title', or 'src' attribute to the frame.`);let l=await a.evaluateHandle(s=>s,{timeout:1e3}),c=await l.asElement().contentFrame();if(!c)throw new A("InternalWebAgentError",`Failed to load Playwright Frame for iframe with url '${r.url}'`);return await l.dispose(),{frame:c,mPathSelectorTokens:i}}function KT(r,e){let t=[...r],n=[];for(;t.length;){let o=t.shift();e(o)&&n.push(o),t.push(...o.childFrames)}return n}async function JT({page:r,frameTree:e,cache:t}){let n,o=e.childFrames,i=[];if(t.mPathSelectorTokens.length){let l=o;for(let u=0;u<t.mPathSelectorTokens.length-1;u++){let d=t.mPathSelectorTokens[u];d===Ao?l=l.length===1?l[0].childFrames:[]:l=l.filter(m=>m.locationData.attributeSelectors.includes(d)).map(m=>m.childFrames).flat()}let c=[],s=t.mPathSelectorTokens[t.mPathSelectorTokens.length-1];if(s===Ao?c=l:c=l.filter(u=>u.locationData.attributeSelectors.includes(s)),c.length===1)return n=c[0],i.push(`Found unique frame with mpath ${t.mPathSelectorTokens.join(" > ")}`),{resolution:{type:"auto",frame:(await sr(n,r)).frame,handle:n,mPathSelectorTokens:t.mPathSelectorTokens,frameTree:e},logs:i};i.push(`Found ${c.length} frames with mpath ${t.mPathSelectorTokens.join(" > ")}`)}if(t.frameSrcRegex){let l=new RegExp(t.frameSrcRegex),c=KT(o,s=>!!s.src&&l.test(s.src));if(c.length===1)return n=c[0],i.push(`Found unique frame with src regex ${t.frameSrcRegex}`),{resolution:{type:"auto",frame:(await sr(n,r)).frame,handle:n,mPathSelectorTokens:t.mPathSelectorTokens,frameTree:e},logs:i};i.push(`Found ${c.length} frames with src regex ${t.frameSrcRegex}`),t.frameSrcRegex=void 0}if(t.frameUrlRegex){let l=new RegExp(t.frameUrlRegex),c=KT(o,s=>!!s.url&&l.test(s.url));if(c.length===1)return n=c[0],i.push(`Found unique frame with url regex ${t.frameUrlRegex}`),{resolution:{type:"auto",frame:(await sr(n,r)).frame,handle:n,mPathSelectorTokens:t.mPathSelectorTokens,frameTree:e},logs:i};i.push(`Found ${c.length} frames with url regex ${t.frameUrlRegex}`),t.frameUrlRegex=void 0}let a=o;for(let l=0;l<t.indices.length-1;l++)a=a[t.indices[l]]?.childFrames??[];if(n=a[t.indices[t.indices.length-1]],n)return i.push(`Found unique frame with indices ${t.indices.join(" > ")}`),{resolution:{type:"auto",frame:(await sr(n,r)).frame,handle:n,mPathSelectorTokens:t.mPathSelectorTokens,frameTree:e},logs:i};throw i.push(`Found ${a.length} frames with indices ${t.indices}`),new Nr("Failed to find the iframe that previously contained this element",[{type:"AUTO_FRAME",matched:!1,logs:i}])}function al(r){return r.type==="auto"?JSON.stringify({type:"auto",frameId:r.handle.frameId}):JSON.stringify(r)}function Bd(r){for(;r.parent.type==="frame";)r=r.parent;return r.parent}function QT(r){let e=Bd(r),t=r.src??"",n=r.url??"",o=[],i=[],a=[...e.childFrames];for(;a.length;){let l=a.shift();l.src&&o.push(l.src),l.url&&i.push(l.url),a.push(...l.childFrames)}return{srcs:o,urls:i,desiredSrc:t,desiredUrl:n}}function ZT(r){return r.type==="auto"?{type:"auto",frameId:r.handle.frameId,url:r.handle.url,src:r.handle.src??"",mPathSelectorTokens:r.mPathSelectorTokens.join(" > ")}:{type:"url",url:r.url}}async function eb({frame:r,logger:e,signal:t}){let n;try{n=await r.frameElement(),await sL({frameElementHandle:n,logger:e,signal:t})}catch(o){n?e.warn({err:o},"Failed to scroll iframe into view, trying with raw JS"):e.warn("Failed to scroll iframe into view - no frame element")}finally{await n?.dispose()}}async function sL({frameElementHandle:r,logger:e,signal:t}){let n=await r.boundingBox();await An({promiseGenerator:async()=>r.evaluate(async i=>{let a=i.scrollTop;i.scrollIntoView({behavior:"instant",block:"center",inline:"center"}),await new Promise(c=>setTimeout(c,250));let l=Date.now();for(;Date.now()-l<1e3;){let c=i.scrollTop;if(c===a)break;a=c,await new Promise(s=>setTimeout(s,250))}}),timeoutMs:2e3,codePath:"scrollIframeIntoView",signal:t}),e.info({oldBb:n,newBb:await r.boundingBox()},"Successfully scrolled iframe into view")}function tb(r,e){return async(t,n)=>{try{let o=await n.allHeaders();for(let{key:i,value:a,matcher:l}of r)(!l||l.matches({url:n.url(),method:n.method()}))&&(o[i]=a);await t.fallback({headers:o})}catch(o){e.warn({err:o},"Failed to apply custom headers to request, continuing")}}}import{randomUUID as cL}from"crypto";function rb(r,e){for(let t of Object.values(e))if(t.matcher.matches({url:r.url(),method:r.method()}))return t}async function nb(r){let{route:e,mock:t,entry:n,debugData:o,requestId:i,requestRecorders:a,logger:l}=r,c={url:n.request.url,options:{method:n.request.method,headers:n.request.headers.map(p=>[p.name,p.value]),body:n.request.postData?.text}},s;if(t.fetchOriginalResponse){let p=await e.fetch();s={body:await p.text(),options:{status:p.status(),statusText:p.statusText(),headers:Object.entries(await p.headers())}}}let u=await lL(t,c,s),d={};u.headers.forEach((p,g)=>{d[g]=p});let m={body:await u.text(),contentType:u.headers.get("content-type")||"text/plain",headers:d,status:u.status};await e.fulfill(m);try{n.response={status:m.status,statusText:u.statusText,headers:Object.entries(m.headers).map(([p,g])=>({name:p,value:g})),cookies:[],content:{mimeType:m.contentType,text:m.body},_mocked:!0},ji(o,n,i);for(let p of Object.values(a))p.onRequestComplete(i,n)}catch(p){p.message.includes("has been closed")||l.warn({err:p},"Failed to add response to HAR")}}async function lL(r,e,t){try{return await r.generateResponse(e,t)}catch(n){let o=n instanceof Error?n.message:`${n}`;return new Response(o,{status:500,headers:{"Content-Type":"text/plain"}})}}async function zd(r){try{await uL(r)}catch(e){r.logger.warn({err:e},"Error handling intercepted request, continuing...")}}async function uL(r){let{pageId:e,route:t,request:n,debugData:o,logger:i,requestRecorders:a,mocks:l}=r,c=cL(),s=await _d(e,n);try{ji(o,s,c);for(let d of Object.values(a))d.onRequestStart(c,s)}catch(d){i.warn({err:d},"Failed to add request to HAR")}let u=rb(n,l);u?await nb({logger:i,route:t,mock:u,entry:s,debugData:o,requestId:c,requestRecorders:a}):await dL({route:t,request:n,debugData:o,logger:i,requestRecorders:a,entry:s,requestId:c})}async function dL({route:r,request:e,debugData:t,logger:n,requestRecorders:o,entry:i,requestId:a}){await r.continue();try{let l=await e.response();if(!l||!i)return;await hT(i,e,l),ji(t,i,a);for(let c of Object.values(o))c.onRequestComplete(a,i)}catch(l){l.message.includes("has been closed")||n.warn({err:l},"Failed to add response to HAR")}}async function mL(r){let e=r.postData();if(e){if((await r.headerValue("content-type"))?.includes("json"))try{return{json:r.postDataJSON()}}catch{return{}}else if((await r.headerValue("content-type"))?.includes("text"))return{text:e}}return{}}async function pL(r){let e=await r.text();if(e){if((await r.headerValue("content-type"))?.includes("json"))try{return{json:await r.json()}}catch{return{}}else if((await r.headerValue("content-type"))?.includes("text"))return{text:e}}return{}}function sl(r){return{request:{url:r.request.url,method:r.request.method,headers:r.request.headers.reduce((e,t)=>({...e,[t.name]:t.value}),{}),...r.request.postData?r.request.postData.mimeType.includes("json")?{json:JSON.parse(r.request.postData.text)}:{text:r.request.postData.text}:{}},response:r.response?{status:r.response.status,headers:r.response.headers.reduce((e,t)=>({...e,[t.name]:t.value}),{}),...r.response.content?r.response.content.mimeType?.includes("json")&&r.response.content.text?{json:JSON.parse(r.response.content.text)}:{text:r.response.content.text}:{}}:void 0}}async function Gd(r){let e=r.request(),t=r.status(),n=r.headers(),o=await pL(r);return{request:{url:e.url(),method:e.method(),headers:e.headers(),...await mL(e)},response:{status:t,headers:n,...o},status:t,headers:n,...o}}var Kr=class{requestMatcher;constructor(e){this.requestMatcher=e}matches(e){let{url:t,method:n}=e;return this.requestMatcher.method&&this.requestMatcher.method.toLowerCase()!==n.toLowerCase()?!1:Ys(t,this.requestMatcher.urlMatcher)}};function ll(r){let e=new URL(r.request().url());return/^127\./.test(e.hostname)||/^192\.168\./.test(e.hostname)||/^10\./.test(e.hostname)||/^172\.(1[6-9]|2\d|3[0-1])\./.test(e.hostname)||e.hostname==="localhost"?r.abort():r.fallback()}async function ob({event:r,transformer:e,enricher:t,frame:n,lastScreenshotForRecording:o,logger:i}){let{warnings:a,error:l,properties:c}=r.target;if(l){i.error({error:l,warnings:a},"Error while capturing passive click");return}if(a.length&&i.warn({warnings:a},"Warnings while capturing passive click"),!c)return;let s=n.parentFrame()?n.url():void 0,d=n.page().frames().map(g=>g.url());i.debug({frameUrl:s,...r},"Passive click event captured on element");let m,p;if(s)try{let g=await n.frameElement();m=await B(g?.boundingBox(),{milliseconds:3e3})??void 0;let h=await t.constructIframeRegex({urls:d,srcs:[],desiredUrl:s});if(h.urlRegex)p={type:"url",url:`/${h.urlRegex}/`};else throw new Error(`Got no url regex options: ${JSON.stringify(h)}`)}catch(g){i.warn({err:g},"Failed to construct iframe details for recorded action, using hardcoded URL only"),p={type:"url",url:s}}(async()=>{try{await e.recordElementAction({...r,screenshotBase64:o,frameConfig:p,frameBoundingBox:m})}catch(g){i.error({err:g},"Failed to transform passive click action")}})()}import{randomUUID as lr}from"crypto";import gL from"js-beautify";var hL=["Dead"],cl=class{recordedSteps=new Map;callbacks;signal;generator;testId;orgId;nextStepOffset=0;logger;constructor({signal:e,callbacks:t,generator:n,testId:o,orgId:i,logger:a}){this.signal=e,this.logger=a,this.testId=o,this.orgId=i,this.callbacks={onStepRecorded:(l,c)=>{this.recordedSteps.set(c,{step:l}),t.onStepRecorded(l,c)},onActionReceived:(l,c)=>{this.recordedSteps.set(c,{step:l}),t.onActionReceived?.(l,c)}},this.generator=n}reserveIndexForCommand(e){let t=this.nextStepOffset;return this.recordedSteps.set(t,{step:{id:lr(),type:"PRESET_ACTION",command:mr(e)}}),this.nextStepOffset++,t}async recordElementAction(e){let{type:t,target:n,frameConfig:o}=e;if(this.signal.aborted){this.logger.debug("Transformer was already cleaned up, ignoring click...");return}let i,a,l=n.properties.attributes.nodeOnlySerializedHtml.trim(),c=l,s;switch(e.frameConfig?e.frameBoundingBox?s={x:e.frameBoundingBox.x+n.properties.boundingBox.x,y:e.frameBoundingBox.y+n.properties.boundingBox.y,width:n.properties.boundingBox.width,height:n.properties.boundingBox.height}:this.logger.warn(e,"No frame bounding box found, refusing to write bounding box"):s=n.properties.boundingBox,t){case"CLICK":{i="CLICK";let h=mr(i);a={id:lr(),type:"PRESET_ACTION",command:{...h,target:{type:"description",elementDescriptor:c},iframeUrl:o?.url,cache:{target:{id:-1,...n.properties.attributes,targetSource:"RECORDING",targetUpdateTime:new Date().toUTCString(),boundingBox:s}}}};break}case"SELECT":{i="SELECT_OPTION";let h=mr(i);a={id:lr(),type:"PRESET_ACTION",command:{...h,type:"SELECT_OPTION",iframeUrl:o?.url,target:{type:"description",elementDescriptor:c},cache:{target:{id:-1,...n.properties.attributes,targetSource:"RECORDING",targetUpdateTime:new Date().toUTCString(),boundingBox:s}},choice:{type:"VALUE",value:e.selectedValue??"Unknown option"}}};break}case"MOUSE_DRAG":{i="MOUSE_DRAG";let h=mr(i);a={id:lr(),type:"PRESET_ACTION",command:{...h,target:{type:"description",elementDescriptor:c},deltaX:e.deltaX.toString(),deltaY:e.deltaY.toString(),iframeUrl:o?.url,cache:{target:{id:-1,...n.properties.attributes,targetSource:"RECORDING",targetUpdateTime:new Date().toUTCString(),targetUpdateLoggerTags:de(this.logger),boundingBox:s}}}};break}default:throw new Error(`Unknown action type: ${t}`)}let u;e.offset===void 0?(u=this.nextStepOffset,this.nextStepOffset++):u=e.offset,this.callbacks.onActionReceived?.(a,u);let d=e.target.browserState;try{d=gL.html(d,{indent_size:1,indent_with_tabs:!1,preserve_newlines:!1}),d=nT(d,"data-momentic-interacted",4e4)}catch{}let m;try{m=(await this.generator.getReverseMappedDescription({target:d,screenshot:e.screenshotBase64?`data:image/jpeg;base64,${e.screenshotBase64}`:void 0,boundingBox:n.properties.boundingBox},{disableCache:!1,loggerTags:{testId:this.testId,...de(this.logger)}})).phrase}catch(h){this.logger.error({err:h},"Error generating reverse mapping description"),m=l}let p=this.recordedSteps.get(u)?.step??a,g=p?.command;g&&"target"in g&&g.target?(g.target={type:"description",elementDescriptor:m},this.callbacks.onStepRecorded({...p,command:g},u)):this.logger.warn("Could not find existing command to update after description mapping")}recordKeystroke(e){let{key:t,combinable:n}=e;if(hL.includes(t)||this.signal.aborted)return;let o="normal";t.length>1&&(o="special");let i;if(o==="normal"){let d=mr("TYPE");i={id:lr(),type:"PRESET_ACTION",command:{...d,target:void 0,value:t,clearContent:!1}}}else{let d=mr("PRESS");i={id:lr(),type:"PRESET_ACTION",command:{...d,value:t}}}let a,l=this.nextStepOffset-1,c=this.recordedSteps.get(l),s=c?.step,u=s?.command;if(n){if(u?.type===i.command.type){let d=u.value,m=i.command.value;i={id:lr(),type:"PRESET_ACTION",command:{...u,value:i.command.type==="PRESS"?`${d}+${m}`:`${d}${m}`}},a=l}else if(u?.type==="CLICK"&&i.command.type==="TYPE")s.command={...i.command,target:u.target,cache:u.cache},i=c.step,a=l;else if(u?.type==="TYPE"&&i.command.type==="PRESS"&&i.command.value==="Backspace"){let d=u.value;i={id:lr(),type:"PRESET_ACTION",command:{...u,value:d.slice(0,d.length-1)}},a=l}}a===void 0&&(a=this.nextStepOffset,this.nextStepOffset++),this.callbacks.onStepRecorded(i,a)}recordScroll(e){if(this.signal.aborted)return;let t=()=>{let{deltaY:i}=e;if(!i)return;let a=this.nextStepOffset-1,l=this.recordedSteps.get(a)?.step.command,c;l?.type==="SCROLL_DOWN"&&l.deltaY?(i+=l.deltaY,c=a):l?.type==="SCROLL_UP"&&l.deltaY?(i-=l.deltaY,c=a):(c=this.nextStepOffset,this.nextStepOffset++);let s=i>0?"SCROLL_DOWN":"SCROLL_UP",u=mr(s);u.deltaY=Math.abs(i);let d={id:lr(),type:"PRESET_ACTION",command:u};this.callbacks.onStepRecorded(d,c)},n=()=>{let{deltaX:i}=e;if(!i)return;let a=this.nextStepOffset-1,l=this.recordedSteps.get(a)?.step.command,c;l?.type==="SCROLL_RIGHT"&&l.deltaX?(i+=l.deltaX,c=a):l?.type==="SCROLL_LEFT"&&l.deltaX?(i-=l.deltaX,c=a):(c=this.nextStepOffset,this.nextStepOffset++);let s=i>0?"SCROLL_RIGHT":"SCROLL_LEFT",u=mr(s);u.deltaX=Math.abs(i);let d={id:lr(),type:"PRESET_ACTION",command:u};this.callbacks.onStepRecorded(d,c)},o=this.recordedSteps.get(this.nextStepOffset-1);o?.step.command.type==="SCROLL_LEFT"||o?.step.command.type==="SCROLL_RIGHT"?(n(),e.deltaY>=20&&t()):(t(),e.deltaX>=20&&n())}};import{z as Hd}from"zod";var Die=Hd.object({type:Hd.literal("url"),url:Hd.string()});var ul=class{smartWaitingTimeoutMs;pageLoadTimeoutMs;allowPartialAccessibilityTree;logger;cdpClient;pageGetter;abortSignalGetter;userBrowserSettings;enricher;iconKnowledgeBase;computedStylesToFetch=["display","opacity","visibility","height","position"];activeFrameCache;activeFrameConfig;lastA11yIdToNodeMap={};lastDataMomenticIdToNodeMap={};lastSelectorToNodeMap={};lastA11yTreeRoot;lastDomGraph;constructor({smartWaitingTimeoutMs:e,pageLoadTimeoutMs:t,allowPartialAccessibilityTree:n,logger:o,cdpClient:i,pageGetter:a,abortSignalGetter:l,enricher:c,iconKnowledgeBase:s,userBrowserSettings:u}){if(this.smartWaitingTimeoutMs=e,this.pageLoadTimeoutMs=t,this.allowPartialAccessibilityTree=n,this.logger=o,this.cdpClient=i,this.pageGetter=a,this.abortSignalGetter=l,this.enricher=c,this.iconKnowledgeBase=s,this.userBrowserSettings=u,this.userBrowserSettings.importantStyles)for(let d of this.userBrowserSettings.importantStyles){let m=d.split(":");if(m.length!==2){this.logger.warn({style:d},"Invalid style property passed to importantStyles");continue}let p=m[0]?.trim(),g=m[1]?.trim();if(p===void 0||g===void 0){this.logger.warn({style:d},"Invalid style property passed to importantStyles");continue}this.computedStylesToFetch.includes(p)||this.computedStylesToFetch.push(p)}}get frameConfig(){return this.activeFrameConfig}get domGraph(){return this.lastDomGraph}get selectorToNodeMap(){return this.lastSelectorToNodeMap}get dataMomenticIdToNodeMap(){return this.lastDataMomenticIdToNodeMap}get a11yIdToNodeMap(){return this.lastA11yIdToNodeMap}get a11yTreeRoot(){return this.lastA11yTreeRoot}setActiveFrameConfig(e){e?(this.activeFrameConfig=e,this.activeFrameCache=void 0):(this.activeFrameConfig=void 0,this.activeFrameCache=void 0)}reset(){this.activeFrameCache=void 0,this.activeFrameConfig=void 0,this.lastA11yIdToNodeMap={},this.lastDataMomenticIdToNodeMap={},this.lastSelectorToNodeMap={},this.lastA11yTreeRoot=void 0,this.lastDomGraph=void 0}saveAutoFrameCacheDetails(e){if(!this.activeFrameConfig||this.activeFrameConfig.type!=="auto"||!this.userBrowserSettings.autoExpandIframes)return;let t={...e,indices:this.activeFrameConfig.handle.locationData.indices,mPathSelectorTokens:this.activeFrameConfig.mPathSelectorTokens};return this.constructIframeRegexAsync(this.activeFrameConfig.handle,t),t}async getAutoFrameDetailsFromHandle(e){let t=this.pageGetter(),n=Bd(e),{frame:o,mPathSelectorTokens:i}=await sr(e,t),a={indices:e.locationData.indices,mPathSelectorTokens:i};return this.constructIframeRegexAsync(e,a),{cache:a,config:{type:"auto",frame:o,handle:e,mPathSelectorTokens:i,frameTree:n,cache:a}}}async resolveAutoFrameCache(e){let t=this.pageGetter(),n=await wo({cdpClient:this.cdpClient,page:t,logger:this.logger}),{resolution:o,logs:i}=await JT({page:t,frameTree:n,cache:e});return this.logger.info({logs:i},"Resolved auto frame cache"),{...o,cache:e}}async resolveActiveFrameConfig({logger:e=this.logger,signal:t=this.abortSignalGetter()}){if(!this.frameConfig)return null;if(this.activeFrameCache)if(al(this.frameConfig)!==this.activeFrameCache.frameIdentifierStringified)this.activeFrameCache=void 0;else if(this.activeFrameCache.frame&&"isDetached"in this.activeFrameCache.frame&&this.activeFrameCache.frame.isDetached())this.activeFrameCache=void 0;else return this.activeFrameCache;let n;return this.frameConfig.type==="url"?n=await this.resolveUrlMatcherFrameConfig({config:this.frameConfig,logger:e,signal:t}):n={source:"auto",frame:this.frameConfig.frame,handle:this.frameConfig.handle,frameIdentifierStringified:al(this.frameConfig),cacheTime:Date.now(),frameTree:this.frameConfig.frameTree,mPathSelectorTokens:this.frameConfig.mPathSelectorTokens},await eb({frame:n.frame,logger:e,signal:t}),this.activeFrameCache=n,n}async executeFunctionInAllFrames(e,t){let n=this.pageGetter(),o=await wo({cdpClient:this.cdpClient,page:n,logger:this.logger}),i=[B(n.evaluate(e,t),{milliseconds:2e3})],a=Array.from(o.childFrames);for(;a.length>0;){let c=a.shift(),s=c.url;s==="about:blank"||s.startsWith("chrome-error://")||(a.push(...c.childFrames),i.push(sr(c,n).then(({frame:u})=>B(u.evaluate(e,t),{milliseconds:2e3})).catch(u=>(this.logger.warn({err:u,frameUrl:c.url},"Failed to evaluate function in frame"),"MOMENTIC_FRAME_EVAL_ERROR"))))}return(await Promise.all(i)).filter(c=>c!=="MOMENTIC_FRAME_EVAL_ERROR")}async getAllChildFrameUrls(){let e=this.pageGetter(),t=await wo({cdpClient:this.cdpClient,page:e,logger:this.logger}),n=Array.from(t.childFrames),o=[];for(;n.length>0;){let i=n.shift();n.push(...i.childFrames),o.push(i.src??i.url)}return o}async getDomGraph({devicePixelRatio:e,signal:t,logger:n}){return this.getDOMTree({devicePixelRatio:e??1,signal:t,logger:n??this.logger})}async getA11yTree(e){let t={},n=e.logger??this.logger,o=e.abortSignal??this.abortSignalGetter(),i=this.pageGetter(),a,l,c=null;if(this.frameConfig?.type==="url"){if(a=await Vt({fn:()=>this.resolveActiveFrameConfig({logger:n,signal:o}),codePath:"getActiveFrameDetails",logObject:t,signal:o,logger:n})??void 0,!a)throw new A("ActionFailureError","Got null frame details despite active frame config");l=a.handle,c=l.frameId}else this.userBrowserSettings.autoExpandIframes?(l=await Vt({fn:()=>wo({cdpClient:this.cdpClient,page:this.pageGetter(),logger:n}),codePath:"getMomenticFrameTree",logObject:t,signal:o,logger:n}),c=null):(l={type:"root",page:i,childFrames:[]},c=null);await Vt({fn:async()=>this.addMomenticIds({rootPage:i,childFrames:l.childFrames,frameFilter:a?.frame,logger:n}),codePath:"addIdsToElement",logObject:t,signal:o,logger:n});let s=await Vt({fn:()=>this.getDOMTree({devicePixelRatio:e.devicePixelRatio??1,signal:o,logger:n}),codePath:"domFetch",logObject:t,signal:o,logger:n}),u=await Vt({fn:()=>this.getRawA11yGraph({cdpClient:this.cdpClient,frameId:c,childFrames:l.childFrames,logTimings:t,logger:n,signal:o}),codePath:"totalA11yFetch",logObject:t,signal:o,logger:n}),{tree:d}=await Vt({fn:()=>this.composeA11yDomGraph({opts:e,a11yGraph:u,domGraph:s,startingFrameId:c,frameContext:l,logger:n,iconKnowledgeBase:this.iconKnowledgeBase,showZeroOpacityElements:e.showZeroOpacityElements,flagNotActionableNodes:e.flagNotActionableNodes}),codePath:"a11yProcess",logObject:t,signal:o,logger:n});return Object.values(t).some(m=>m>750)&&n.warn({logTimings:t},"A11y tree fetch component took a long time"),this.lastA11yIdToNodeMap=d.a11yIdNodeMap,this.lastDataMomenticIdToNodeMap=d.dataMomenticIdMap,this.lastA11yTreeRoot=d.root,this.lastDomGraph=s,this.lastSelectorToNodeMap=d.selectorToNodeMap,d}async fetchA11yTreeForRecording(e,t){if(await this.getA11yTree({devicePixelRatio:e,abortSignal:t,logger:dn,filterByViewport:!1,flagNotActionableNodes:!1}),Math.random()<.1){let n=this.lastA11yTreeRoot?.serialize();this.logger.debug({tree:n&&n.length>4e5?"REDACTED_DUE_TO_SIZE":n},"Refreshed a11y tree during recording")}}async getLocatorFromA11yNode({page:e,root:t,node:n}){if(n.backendNodeId===void 0)throw new Error(`Node with a11y id ${n.id} has no backend node ID: ${n.getNodeOnlySerializedForm()}`);if(this.userBrowserSettings.visualActions){let o=this.domGraph?.backendIdToNode[n.backendNodeId];if(!o)throw new Error(`Could not find DOM node for backend node ID ${n.backendNodeId}`);let i=OT({node:o,domGraph:this.domGraph});return LT(e,i)}else return this.getLocatorFromBackendId(t,n.backendNodeId)}async getLocatorFromBackendId(e,t){let n=await this.cdpClient.send({method:"DOM.resolveNode",params:{backendNodeId:t},timeout:2e3});if(!n||!n.object.objectId)throw new Error(`Could not resolve backend node ${t}`);let o;try{o=await NT(this.cdpClient,n.object.objectId)}catch(i){throw this.logger.debug({err:i,object:JSON.stringify(n.object)},"Failed to get ID attribute"),i}return e.locator(qt(o))}getNodeUsingMPathSelector(e){let t=this.selectorToNodeMap[e];if(t)return t;let n=e.split(" > "),o="";for(let i=n.length-1;i>=0;i--){let a=n.slice(i).join(" > ");if(this.selectorToNodeMap[a]){o=a;break}}this.logger.warn({selectorMapSize:Object.keys(this.selectorToNodeMap).length,selector:e,closestSelector:o},"Could not find a11y node using mpath selector")}async resolveUrlMatcherFrameConfig({config:e,signal:t=this.abortSignalGetter(),logger:n=this.logger}){let o=Date.now(),i,a,l,c=0;for(;Date.now()-o<this.smartWaitingTimeoutMs;)try{i=await wo({cdpClient:this.cdpClient,page:this.pageGetter(),logger:n}),a=await this.getMatchingFrameByUrlWithCdp(i,e),n.info({frameId:a.handle.frameId,url:a.handle.url,src:a.handle.src,locationData:a.handle.locationData},`Found matching frame using ${a.matchType}`);break}catch(s){if(l=s,s instanceof A&&s.reason==="UserInfrastructureError")throw s;c%3===0&&this.logger.warn({attempt:c,err:s},"Failed to resolve active frame, retrying..."),await q(500,t)}finally{c++}if(a)return{source:"url",frame:a.frame,handle:a.handle,frameIdentifierStringified:al(e),cacheTime:Date.now(),frameTree:i,mPathSelectorTokens:[]};throw l}async getMatchingFrameByUrlWithCdp(e,t){let n=t.url,o=this.pageGetter(),i=Array.from(e.childFrames),a=[];for(;i.length>0;){let l=i.shift(),c=l.domNode;i.push(...l.childFrames);let s=qr(c.attributes??[],"src"),u=c.contentDocument?.documentURL;if(!s&&!u){this.logger.debug("Skipping frame with no URL or src");continue}for(let d of[s,u])if(d){if(n.startsWith("/")&&n.endsWith("/")){if(new RegExp(n.slice(1,-1)).test(d)){a.push({handle:l,matchType:"regex",...await sr(l,o)});break}}else if(n.trim()===d.trim()){a.push({handle:l,matchType:"url",...await sr(l,o)});break}}}if(a.length===1){let l=a[0];return this.userBrowserSettings.autoExpandIframes||(l.handle.childFrames=[]),l}else throw a.length>1?new Error(`Found multiple frames with src matching '${n}'. Please use a more specific selector.`):new A("ActionFailureError",`Failed to find frame with src matching: ${n}`)}async composeA11yDomGraph({opts:e,a11yGraph:t,domGraph:n,startingFrameId:o,frameContext:i,logger:a,iconKnowledgeBase:l,showZeroOpacityElements:c,flagNotActionableNodes:s}){let u=await jT({rawA11yGraph:t,startingFrameId:o,frameContext:i,domGraph:n,logger:a,cdpClient:this.cdpClient,showZeroOpacityElements:c,flagNotActionableNodes:s,filterByViewport:e.filterByViewport,importantProperties:{attributes:this.userBrowserSettings.importantAttributes,classes:this.userBrowserSettings.importantClasses,styles:this.userBrowserSettings.importantStyles},viewportDetails:void 0,iconKnowledgeBase:l,useMPaths:this.userBrowserSettings.visualActions});if(!u||!u.root)throw new Error("Accessibility tree appears empty");return{tree:u}}async addMomenticIds({rootPage:e,childFrames:t,frameFilter:n,logger:o}){if(this.userBrowserSettings.visualActions)return;let i=await this.addMomenticIdsHelper(n??e,1);if(!this.userBrowserSettings.autoExpandIframes||n)return;let a=Array.from(t),l=[];for(;a.length>0;){let c=a.shift();a.push(...c.childFrames);let s=async()=>{try{let{frame:u}=await sr(c,e);i=await this.addMomenticIdsHelper(u,i)}catch(u){c.url!=="about:blank"&&o.warn({err:u},"Error adding momentic IDs to child frame, continuing...")}};l.push(s())}await Promise.all(l)}async addMomenticIdsHelper(e,t){if(this.userBrowserSettings.visualActions)return t;let n=this.logger;return await He({root:e,fn:i=>window.addIdsToElement?.(document.body,i),arg:t,timeout:2e3,waitForPageLoad:async()=>{try{await e.waitForLoadState("domcontentloaded",{timeout:this.smartWaitingTimeoutMs})}catch(i){n.warn({err:i},"Error loading frame root adding momentic ids, continuing...")}},codePath:"adding Momentic element IDs to the page"})??t}getPageDomain(e){try{let t=new URL(e);if(!t.hostname)return null;let n=t.hostname.split("."),o=n.length>2?n.slice(-2).join("."):t.hostname;return`${t.protocol}//${o}`}catch{return null}}async decideChildFrameUnrollEligibility({logger:e,warnings:t,handle:n}){try{let{shouldUnroll:o,reason:i}=await this.decideChildFrameUnrollEligibilityHelper({domNode:n.domNode});return{shouldUnroll:o,reason:i}}catch(o){if(o.message.includes("Could not compute box model"))return{shouldUnroll:!1};let i=`Got error when determining whether to filter frame ${n.frameId} with url ${n.url}, allowing it to be fetched: ${o}`;return t?.push(i),e?.warn({err:o},i),{shouldUnroll:!0}}}async decideChildFrameUnrollEligibilityHelper({domNode:e}){let t=e.attributes??[];if(qr(t,"aria-hidden")==="true")return{shouldUnroll:!1,reason:"aria-hidden"};let n=qr(t,"style");if(n?.includes("display: none")||n?.includes("visibility: hidden"))return{shouldUnroll:!1,reason:"hidden CSS style"};await this.cdpClient.send({timeout:3e3,method:"DOM.pushNodesByBackendIdsToFrontend",params:{backendNodeIds:[e.backendNodeId]}});let[o,i]=await Promise.all([this.cdpClient.send({timeout:3e3,method:"DOM.getBoxModel",params:{backendNodeId:e.backendNodeId}}),this.cdpClient.send({timeout:3e3,method:"CSS.getComputedStyleForNode",params:{nodeId:e.nodeId}})]);if(!o.model||!o.model.height||!o.model.width)return{shouldUnroll:!1,reason:"no bounding box"};if(o.model.height<10||o.model.width<10)return{shouldUnroll:!1,reason:"small bounding box"};for(let a of i.computedStyle){if(a.name==="display"&&a.value==="none")return{shouldUnroll:!1,reason:"display: none"};if(a.name==="visibility"&&a.value==="hidden")return{shouldUnroll:!1,reason:"visibility: hidden"};if(a.name==="opacity"&&a.value==="0")return{shouldUnroll:!1,reason:"opacity: 0"}}return{shouldUnroll:!0}}async getRawA11yGraph({cdpClient:e,frameId:t,childFrames:n,logTimings:o,logger:i=this.logger,signal:a=this.abortSignalGetter()}){let l=[];try{await this.pageGetter().waitForLoadState("load",{timeout:this.pageLoadTimeoutMs})}catch(p){i.warn({err:p},"Failed to wait for page load event before a11y tree fetch, attempting to continue without it..."),await this.cdpClient.reinitialize()}let c,s;for(let p=0;p<3;p++)try{s=await Vt({fn:()=>this.getRawA11yTreeForFrame({frameId:t,timeoutMs:this.pageLoadTimeoutMs,logTimings:o}),codePath:"a11y-tree-fetch-root",logObject:o,signal:a,logger:i});break}catch(g){c=g,i.warn({err:g},"Reinitializing CDP client before retrying a11y graph fetch"),await this.cdpClient.reinitialize()}if(!s)throw new Error(`Failed to fetch accessibility tree for root page: ${c}`);let u={};if(u[t??"root"]=s,!this.userBrowserSettings.autoExpandIframes)return u;let d=Array.from(n),m=[];for(;d.length>0;){let p=d.shift();try{let{shouldUnroll:h}=await this.decideChildFrameUnrollEligibility({handle:p,warnings:l});if(!h)continue}catch(h){if(h.message.includes("Could not compute box model"))continue;l.push(`Got error when determining whether to filter frame ${p.frameId} with url ${p.url}, allowing it to be fetched: ${h}`)}d.push(...p.childFrames);let g=async()=>{try{let h=await Vt({fn:()=>this.getRawA11yTreeForFrame({frameId:p.frameId,timeoutMs:this.smartWaitingTimeoutMs,logTimings:o}),codePath:`a11y-tree-fetch-child-${p.frameId}`,logObject:o,signal:a,logger:i});u[p.frameId]=h}catch(h){i.warn({err:h,url:p.url,src:p.src},`Error getting raw a11y tree for child frame ${p.frameId}, continuing...`)}};m.push(g())}return await Promise.all(m),l.length>0&&this.logger.warn({warnings:l},"Got warnings when fetching the raw a11y graph"),u}async getRawA11yTreeForFrame({frameId:e,timeoutMs:t,logTimings:n}){let o;if(this.allowPartialAccessibilityTree)o=(await Vt({fn:()=>this.cdpClient.send({method:"Accessibility.getFullAXTree",params:{frameId:e??void 0},timeout:t,timeoutMsg:`Fetching the document tree took over ${t}ms. This usually indicates that the current page is too large to be loaded at once, or your machine is severely resource constrained.`}),codePath:"cdp-query-ax-tree",logObject:n,signal:this.abortSignalGetter(),logger:this.logger})).nodes;else{let a=(await Vt({fn:()=>this.cdpClient.send({method:"Accessibility.getRootAXNode",params:{frameId:e??void 0},timeout:2e3}),codePath:"cdp-get-root-ax-node",logObject:n,signal:this.abortSignalGetter(),logger:this.logger})).node.backendDOMNodeId;o=(await Vt({fn:()=>this.cdpClient.send({method:"Accessibility.queryAXTree",params:{backendNodeId:a},timeout:t,timeoutMsg:`Fetching the document tree took over ${t}ms. This usually indicates that the current page is too large to be loaded at once, or your machine is severely resource constrained.`}),codePath:"cdp-query-ax-tree",logObject:n,signal:this.abortSignalGetter(),logger:this.logger})).nodes}if(!o||o.length<=1)throw new Error("Document is entirely empty");return{root:o[0],allNodes:o}}async getDOMTree({devicePixelRatio:e,signal:t,logger:n}){let o,i=0,a;for(;!o&&i<3;)try{if(o=await this.cdpClient.send({method:"DOMSnapshot.captureSnapshot",params:{computedStyles:this.computedStylesToFetch},timeout:3e3}),!o||!o.documents.length)throw new Error("Got empty DOM tree")}catch(l){await q(500,t),i++,a=l}if(!o||!o.documents.length)throw n.error({err:a},"Fatal error fetching DOM tree"),new A("UserInfrastructureError",`Received an empty HTML snapshot from the browser. This usually indicates the page has crashed due to resource consumption issues or hanging client-side JavaScript code: ${a?.message}`);return PT({snapshot:o,devicePixelRatio:e,computedStylesToFetch:this.computedStylesToFetch,logger:n})}constructIframeRegexAsync(e,t){if(t.frameSrcRegex||t.frameUrlRegex)return;let n=QT(e);(async()=>{try{let o=await this.enricher?.constructIframeRegex(n);o?.srcRegex&&(t.frameSrcRegex=o.srcRegex),o?.urlRegex&&(t.frameUrlRegex=o.urlRegex),this.logger.debug({result:o,params:n},"Constructed iframe regex for cache")}catch(o){this.logger.warn({err:o},"Failed to construct iframe regex, skipping...")}})()}};function Vd(r){let e=[],t="";for(let n of r)n==="+"&&t?(e.push(t),t=""):t+=n;return e.push(t),e}var $d=Co(qd(),"momentic","chromium"),kL=Co(qd(),"video"),ml=process.env.TWO_CAPTCHA_KEY,db=LL(ub);db.use(NL({provider:{id:"2captcha",token:ml},visualFeedback:!0}));var $i=class r{static USER_AGENT=OL["Desktop Chrome"].userAgent;abortSignal=void 0;contextInitialized=!1;browser;context;properties;page;userControlledBrowserSettings;pageLoadPromises={};lastTabChangeEventTimeout=void 0;clientCallbacks;iconKnowledgeBase;lastIconKnowledgeBaseUpdateTime=0;cdpClient;debugData={logsPerPage:[],harPages:{},harEntries:{}};recentFrameNavigations={};requestRecorders={};mocks={};customHeaders=[];enricher;storage;flagStore;logger;stateManager;transformer;lastScreenshotForRecording=void 0;originsVisited=new Set;viewport;videos=[];baseUrl;constructor({storage:e,flagStore:t,enricher:n,browser:o,context:i,page:a,baseUrl:l,logger:c,userBrowserSettings:s,viewport:u,properties:d,clientCallbacks:m,iconKnowledgeBase:p}){if(Wh(s),this.storage=e,this.flagStore=t,this.enricher=n,this.browser=o,this.context=i,this.page=a,this.baseUrl=l,this.logger=c,this.userControlledBrowserSettings=s,this.viewport=u,this.properties=d,this.clientCallbacks=m,d.recordVideo){let g=this.page.video();g&&this.videos.push(g)}this.iconKnowledgeBase=p}registerAbortSignal(e){this.abortSignal=e}async initialize({grantPermissions:e,runInitScripts:t}){if(this.contextInitialized)return;this.userControlledBrowserSettings.extraHeaders&&await this.context.setExtraHTTPHeaders(this.userControlledBrowserSettings.extraHeaders),e&&await this.context.grantPermissions(["clipboard-read","clipboard-write","microphone","camera","geolocation"]);let n={[el]:this.userBrowserSettings.visualActions},o=[this.context.addInitScript({content:eT.htmlUtilsLibJs}),this.context.addInitScript({content:`window._MOMENTIC_BROWSER = true; window._MOMENTIC_FEATURE_FLAGS = ${JSON.stringify(n)}; window.addEventListener('load', (event) => { console.log('[MOMENTIC] Page loaded'); });`})];t&&await this.page.reload();let i=l=>this.handleNewPageEvent(l);this.context.on("page",i),this.handleNewPageEventHelper(this.page),this.context.on("close",()=>{this.context.off("page",i)});let a=Promise.all(o);await Promise.all([a]),this.properties.systemDevicePixelRatio||(process.env.MOMENTIC_LOCAL_DEV==="1"&&_L()==="darwin"&&bL("system_profiler SPDisplaysDataType").toString().includes("Retina")?(w.warn("[DEV] Setting device pixel ratio to 2 in local dev since a Retina display was detected"),this.properties.systemDevicePixelRatio=2):this.properties.systemDevicePixelRatio=await this.page.evaluate(()=>window.devicePixelRatio)),this.cdpClient=await il.init({logger:this.logger,contextGetter:()=>this.context,pageGetter:()=>this.page,defaultTimeoutMs:this.pageLoadTimeout}),await this.initializeScreencast(),this.stateManager=new ul({smartWaitingTimeoutMs:this.smartWaitingTimeout,pageLoadTimeoutMs:this.pageLoadTimeout,allowPartialAccessibilityTree:this.userControlledBrowserSettings.allowPartialAccessibilityTree??!1,logger:this.logger,cdpClient:this.cdpClient,pageGetter:()=>this.page,abortSignalGetter:()=>this.abortSignal,enricher:this.enricher,iconKnowledgeBase:this.iconKnowledgeBase,userBrowserSettings:this.userBrowserSettings}),this.contextInitialized=!0}async fixViewportForNewHeadless(){this.properties.isNewHeadless&&this.viewport&&await this.cdpClient.send({method:"Emulation.setDeviceMetricsOverride",params:{width:this.viewport.width,height:this.viewport.height,deviceScaleFactor:0,mobile:this.viewport.width<1e3}})}async initializeScreencast(){await this.fixViewportForNewHeadless(),this.clientCallbacks?.onScreencastFrame&&this.viewport&&(await this.cdpClient.send({method:"Page.startScreencast",params:{format:"jpeg",quality:75,maxWidth:this.viewport.width,maxHeight:this.viewport.height}}),this.cdpClient.on("Page.screencastFrame",e=>{let t=e.sessionId,n=Buffer.from(e.data,"base64");this.lastScreenshotForRecording=n,this.clientCallbacks?.onScreencastFrame?.(n,()=>{(async()=>{try{await this.cdpClient.send({method:"Page.screencastFrameAck",params:{sessionId:t}})}catch{}})()})}))}static async init({baseUrl:e,logger:t,storage:n,flagStore:o,enricher:i,userBrowserSettings:a,contextArgs:l,recordVideo:c,iconKnowledgeBase:s,callbacks:u}){process.env.PW_TEST_SCREENSHOT_NO_FONTS_READY="1";let d;switch(a.browserType){case"Google Chrome":d="chrome";break;case"Chrome for Testing":d=void 0;break;case"Chromium":d="chromium";break;default:d="chromium";break}let m={headless:process.env.MOMENTIC_HEADFUL_BROWSER!=="true",handleSIGTERM:!1,chromiumSandbox:!1,channel:d},p={...l??{},geolocation:l?.geolocation||Fp,locale:l?.locale||kp,timezoneId:l?.timezoneId||Up,colorScheme:l?.colorScheme,httpCredentials:a.basicAuthorization?{username:a.basicAuthorization.username??"",password:a.basicAuthorization.password??""}:void 0,javaScriptEnabled:a.disableJavaScript?!1:void 0,ignoreHTTPSErrors:a.ignoreHttpsErrors??!1,userAgent:a.userAgent??r.USER_AGENT,viewport:l?.viewport??Ir},g=["--disable-dev-shm-usage","--no-first-run","--renderer-process-limit=3","--browser-test","--disable-site-isolation-for-policy","--disable-site-isolation-trials","--disable-backgrounding-occluded-windows","--disable-background-timer-throttling","--disable-renderer-backgrounding","--autoplay-policy=user-gesture-required","--disable-add-to-shelf","--disable-desktop-notifications","--use-fake-device-for-media-stream","--use-fake-ui-for-media-stream"],h=null,f,y,T={systemDevicePixelRatio:l?.deviceScaleFactor,recordVideo:c,isNewHeadless:!1};(d==="chrome"||d==="chromium")&&(T.isNewHeadless=!0,m.headless&&g.push("--headless=new")),process.env.BROWSER_MEMORY_MB&&g.push(`--js-flags=--max_old_space_size=${process.env.BROWSER_MEMORY_MB}`),a.disableGpu&&g.push("--disable-3d-apis","--disable-gpu","--disable-software-rasterizer","--disable-accelerated-2d-canvas","--disable-accelerated-mjpeg-decode","--disable-accelerated-video-decode","--disable-accelerated-video-encode","--disable-gl-drawing-for-tests","--disable-webgl","--disable-audio-input","--disable-audio-output");let v=a.localChromeExtensionPaths?.map(b=>b.startsWith("~")?Co(qd(),b.slice(1)):b);if(v?.length){if(d===void 0)throw new A("UserConfigurationError","Chrome extensions are only supported on Chromium and Google Chrome.");for(let k of v){let $=Co(k,"manifest.json");if(!dl($))throw new A("UserConfigurationError",`Chrome extension path ${$} does not exist.`)}if(fi)throw new A("UserConfigurationError","Cannot use persistent browser context on Momentic Cloud");let b=Co($d,`momentic-session-${Date.now()}`);if(!dl(b))try{vL(b,{recursive:!0})}catch(k){throw new A("UserConfigurationError",`Failed to create browser cache directory. Please make sure you have sufficient permissions to create the ${$d} folder: ${k}`)}let x=[...g],N=v.map(k=>PL(k)).join(",");x.push(`--disable-extensions-except=${N}`),p?.deviceScaleFactor&&x.push(`--force-device-scale-factor=${p.deviceScaleFactor}`,`--device-scale-factor=${p.deviceScaleFactor}`),p.viewport&&x.push(`--window-size=${p.viewport.width},${p.viewport.height}`),f=await ub.launchPersistentContext(Co($d,`momentic-session-${Date.now()}`),{...m,...p,ignoreDefaultArgs:["--disable-extensions","--disable-component-extensions-with-background-pages"],args:x,baseURL:e}),t.debug({sharedContextOptions:p,sharedBrowserOptions:m,userBrowserSettings:a,chromeArgs:x,flags:o.getAllFlags(),properties:T,baseUrl:e},"Browser initialization context args (persistent)"),y=f.pages()[0]}else{h=await db.launch({...m,args:g});let b={...p,baseURL:e,recordVideo:c?{dir:kL}:void 0};f=await h.newContext(b),t.debug({contextArgs:b,sharedBrowserOptions:m,chromeArgs:g,userBrowserSettings:a,flags:o.getAllFlags(),properties:T,baseUrl:e},"Browser initialization context args (standard)"),y=await f.newPage()}fi&&await f.route("**",ll);let R=new r({browser:h,context:f,page:y,baseUrl:e,logger:t,storage:n,flagStore:o,enricher:i,userBrowserSettings:a,viewport:p.viewport||Ir,properties:T,clientCallbacks:u,iconKnowledgeBase:s});return await R.initialize({grantPermissions:!0,runInitScripts:!1}),R}static async fromExistingContext({context:e,storage:t,flagStore:n,enricher:o,userBrowserSettings:i,logger:a}){let l=e.pages()[0];if(!l)throw new Error("No page found in existing context");let c=l.viewportSize(),s=l?.url(),u=new r({browser:e.browser(),context:e,page:l,baseUrl:s,logger:a,storage:t,flagStore:n,enricher:o,userBrowserSettings:i,viewport:c,properties:{isNewHeadless:!0},clientCallbacks:void 0,iconKnowledgeBase:null});return await u.initialize({grantPermissions:!1,runInitScripts:!0}),u}async handleAvailableTabsChangeHelper(){try{let e=await Ld(this.context,{getTitles:!0}),t=this.page.url();this.clientCallbacks?.onTabsChange?.(e,t)}catch(e){this.logger.error({err:e},"Error sending available tabs to frontend")}}handleAvailableTabsChange(){try{clearTimeout(this.lastTabChangeEventTimeout),this.lastTabChangeEventTimeout=setTimeout(()=>this.handleAvailableTabsChangeHelper(),500)}catch(e){this.logger.warn({err:e},"Error handling available tabs change")}}addToPageLoadPromises(e,t){let n=jd(),o=`${e}-${n}`,i=Date.now(),a=!1,l=async()=>{try{await B(t(),{signal:this.abortSignal,milliseconds:this.pageLoadTimeout,message:`Page load promise for code path ${e} timed out after ${this.pageLoadTimeout}ms`})}catch(c){c.name!=="AbortError"&&this.logger.error({err:c,promiseKey:o,codePath:e,duration:Date.now()-i},`Page load promise for code path ${e} encountered error`)}finally{delete this.pageLoadPromises[o],a=!0}};this.pageLoadPromises[o]=l().catch(()=>{}),a&&delete this.pageLoadPromises[o]}handlePageClosedEvent(e){if(this.page!==e){this.logger.debug({url:e.url()},"Detected background page was closed, just updating available tabs only"),this.handleAvailableTabsChange();return}let t=async()=>{if(this.closed)return;this.logger.info({url:e.url()},"Detected active page was closed, switching to another tab");let n=this.context.pages();for(let o=n.length-1;o>=0;o--){let i=n[o];if(!(!i||i.isClosed()||!wn(i.url()))){this.logger.info(`Automatically switching to tab ${o} after close: ${i.url()}`),await this.switchToPage({type:"INDEX",index:String(o)});break}}};this.addToPageLoadPromises("page closed handler",async()=>t())}handleNewPageEvent(e){let t=e.url();if(this.logger.info({url:t},"Detected new page event, registering handlers and waiting for load to complete"),this.properties.recordVideo){let n=e.video();n&&this.videos.push(n)}try{this.handleNewPageEventHelper(e)}catch(n){this.logger.warn({err:n},"Error handling new page open, continuing....")}}handleNewPageEventHelper(e){let t=jd(),n="new-page-load-handler";e.on("close",a=>this.handlePageClosedEvent(a)),e.on("framenavigated",a=>this.handleFrameNavigationEvent(a)),e.on("crash",()=>{this.logger.error("Page crashed at the Playwright level!")});let o=this.context.pages().indexOf(e);e.on("console",a=>{dT(e,o,this.debugData,a,this.logger)});let i=async()=>{await gT(t,this.debugData,e),await e.route("**/*",async(a,l)=>{await zd({pageId:t,route:a,request:l,debugData:this.debugData,logger:this.logger,requestRecorders:this.requestRecorders,mocks:this.mocks})}),await e.route("**/*",tb(this.customHeaders,this.logger)),fi&&await e.route("**/*",ll),await this.loadFrameAndRecordUrl({root:e,codePath:n}),this.handleAvailableTabsChange()};this.addToPageLoadPromises(n,async()=>i())}async handleCollectSvgs(e){if(!this.flagStore.isBooleanFlagEnabled("icon_knowledge_base")||this.page.isClosed()||this.page.mainFrame()!==e||!this.iconKnowledgeBase||!this.clientCallbacks?.onSvgsCollected||Date.now()-this.lastIconKnowledgeBaseUpdateTime<5e3)return;this.lastIconKnowledgeBaseUpdateTime=Date.now();let t=await this.stateManager.getDomGraph({devicePixelRatio:this.devicePixelRatio}),n=DT({domGraph:t,flagStore:this.flagStore,logger:this.logger,existingHashes:this.iconKnowledgeBase});if(n.forEach(l=>{this.iconKnowledgeBase[l.hash]=l}),!n.length)return;let o=de(this.logger),i={pageUrl:e.url(),firstSeenTime:Date.now(),hostname:xL()};for(let l of["runId","testId"])o[l]&&(i[l]=o[l]);let a={metadata:i,newSvgs:n};this.clientCallbacks.onSvgsCollected(a)}handleFrameNavigationEvent(e){let t=e.url(),n=e.parentFrame()?"has-parent":"no-parent",o=`frame-navigation-handler-${t.slice(0,50)}-${n}`;if(!t||t==="about:blank"||!wn(t)||this.recentFrameNavigations[o]&&Date.now()-this.recentFrameNavigations[o]<1e3)return;this.recentFrameNavigations[o]=Date.now();let i=async()=>{try{if(e.isDetached())return;await this.loadFrameAndRecordUrl({root:e,codePath:o,signal:this.abortSignal}),this.handleAvailableTabsChange(),!e.parentFrame()&&!e.isDetached()&&this.clientCallbacks?.onSvgsCollected&&(setTimeout(()=>{(async()=>{try{await this.handleCollectSvgs(e)}catch(l){this.logger.warn({err:l},"Failed to collect SVGs on page, continuing...")}})()},5e3),this.transformer&&await this.injectKnowledgeBaseIntoBrowser(e))}catch(a){a.name!=="AbortError"&&this.logger.warn({err:a},"Failed to handle frame navigation event, continuing...")}};this.addToPageLoadPromises(o,async()=>i())}async injectKnowledgeBaseIntoBrowser(e){try{if(!this.iconKnowledgeBase||await e.evaluate(()=>!!window._MOMENTIC_ICON_KNOWLEDGE_BASE))return;let n={};Object.keys(this.iconKnowledgeBase).forEach(o=>{this.iconKnowledgeBase[o]?.description&&(n[o]=this.iconKnowledgeBase[o].description)}),await e.evaluate(o=>{let i=window;i._MOMENTIC_ICON_KNOWLEDGE_BASE=o},n)}catch(t){this.logger.warn({err:t},"Failed to inject icon knowledge base into browser, continuing...")}}getBrowserCallbacks(){return{waitForPageLoad:()=>this.waitForPageLoad(),waitForUrl:e=>this.waitForUrl(e),getBrowserState:e=>this.getBrowserState(e),waitForDomStability:e=>this.waitForDOMStability(e),state:{url:()=>this.url(),getDomGraph:()=>this.stateManager.domGraph,getOpenPages:()=>this.getOpenPages(),getRoot:()=>this.getActivePageOrFrame(),userBrowserSettings:this.userBrowserSettings},pageLoadTimeoutMs:this.pageLoadTimeout,signal:this.abortSignal}}ping(){if(this.closed)throw new Error("Page has been closed")}setActiveFrameConfig(e){this.stateManager.setActiveFrameConfig(e)}async reset(e){for(this.abortSignal=void 0,this.debugData.logsPerPage=[],this.debugData.harPages={},this.debugData.harEntries={},this.pageLoadPromises={};this.videos.length>0;)this.videos.pop();await this.clearAuthState({closeNonActiveTabs:!0}),await this.stopScreencast(),await this.reinitializeCDPClient(),await this.navigate({url:e.newUrl??this.baseUrl,initialNavigation:!0,loadTimeoutMs:e.timeout}),this.stateManager.reset()}async clearHighlights(){try{await B(Id(this.getBrowserCallbacks()),{milliseconds:1e3})}catch(e){this.logger.debug({err:e},"Failed to clear highlights, continuing...")}}async cleanup(){this.abortSignal=void 0;try{this.originsVisited.clear(),await this.context.close(),await this.browser?.close(),this.browser=null}catch(e){this.logger.warn({err:e},"Error cleaning up browser, continuing...")}finally{this.browser=null}}get closed(){return this.context.pages().every(e=>e.isClosed())||!!this.browser&&!this.browser.isConnected()}async ensureMomenticBrowserScriptsLoaded(e,t,n){let o=Date.now(),i=0,a=0;for(;Date.now()-o<8e3;){a++,n?.throwIfAborted();try{if(await He({fn:()=>{let c=window;return!!(c.generateCssSelectors&&c.evaluateCssSelectors&&c.evaluatePrimaryCaches&&c.generateHtmlCacheAttributes&&c.ldist)},timeout:1e3,arg:void 0,waitForPageLoad:()=>this.waitForPageLoad(),root:e,codePath:"ensuring Momentic system scripts are loaded"}))return}catch(l){if(i++,i>=3){t.warn({err:l},"Multiple errors checking if Momentic scripts are loaded, aborting...");return}}await q(500),a%2===0&&t.warn("Still waiting for momentic browser scripts to load...")}throw new Error(`Failed to load momentic browser scripts on page ${e.url()}`)}async html(){let e=await this.getActivePageOrFrame();return await this.ensureMomenticBrowserScriptsLoaded(e,this.logger),He({root:e,fn:()=>{let t=window;if(!t?.getFullHtmlTree)throw new Error("Missing Momentic HTML library when fetching page HTML");return t.getFullHtmlTree()},arg:void 0,timeout:3e3,waitForPageLoad:()=>this.waitForPageLoad(),codePath:"getting the full HTML tree"})}url(){return this.page.url()}async stabilizePageForScreenshot(){try{await this.evaluateFunctionInPage(()=>{let e=window,t=[],n=new Map;document.querySelectorAll("input,textarea,[contenteditable]").forEach(o=>{n.set(o,{value:o.style.getPropertyValue("caret-color"),priority:o.style.getPropertyPriority("caret-color")}),o.style.setProperty("caret-color","transparent","important")}),t.push(()=>{for(let[o,i]of n)o.style.setProperty("caret-color",i.value,i.priority)}),e._MOMENTIC_SCREENSHOT_CLEANUP=()=>{for(let o of t)o();delete e._MOMENTIC_SCREENSHOT_CLEANUP}},void 0,"stabilizing page for screenshot")}catch(e){(!(e instanceof Error)||!e.message.includes("Execution context was destroyed"))&&this.logger.warn({err:e},"Failed to stabilize page before screenshot, continuing...")}}async removeScreenshotStabilization(){try{await this.evaluateFunctionInPage(()=>{window._MOMENTIC_SCREENSHOT_CLEANUP?.()},void 0,"removing screenshot stabilization")}catch{}}async screenshot(e){let{retries:t=1,stabilizeBeforeScreenshot:n=!1}=e,o=this.page.url();n&&await this.stabilizePageForScreenshot();let i=Date.now();try{await this.fixViewportForNewHeadless();let a=await this.screenshotHelper({...e,retries:t});if(a.byteLength>5e6)this.logger.error("Page screenshot is greater than 5MB, which may cause performance issues with some AI models");else if(a.length===0)throw new Error("Got empty screenshot");return a}catch(a){if(t<=0||a.message.includes("has been closed"))throw a;return this.logger.warn({err:a,pageUrl:o},"Failed taking screenshot, retrying..."),await q(250),this.screenshot({...e,retries:t-1})}finally{Date.now()-i>1e3&&this.logger.warn({pageUrl:o,duration:Date.now()-i},"Screenshot took longer than expected"),n&&await this.removeScreenshotStabilization()}}async screenshotHelper({locator:e,quality:t,saveToDiskPath:n,timeout:o,respectActiveFrame:i,clearHighlights:a=!1}){a&&await this.clearHighlights(),i&&this.stateManager.frameConfig&&(e=await(await this.getActivePageOrFrame()).frameElement());let l=await this.cdpClient.send({method:"Page.captureScreenshot",params:{format:"jpeg",quality:t,optimizeForSpeed:!0},timeout:o??2e3}),c=Buffer.from(l.data,"base64"),s=await lb.fromBuffer(c),{width:u,height:d}=this.getViewport()??{};if(u&&d&&(s.bitmap.width!==u||s.bitmap.height!==d)&&(c=await s.resize({w:u,h:d}).getBuffer("image/jpeg")),n&&wL(n,c),this.lastScreenshotForRecording=c,!e)return c;let m=await e.boundingBox({timeout:3e3});if(!m)throw new Error("Attempted to screenshot an element that is not visible on the page");let{x:p,y:g,width:h,height:f}=m;if(!h||!f)throw new Error("Attempted to screenshot an element with zero width or height");p=Math.floor(p),g=Math.floor(g),h=Math.floor(h),f=Math.floor(f);try{let y=await lb.fromBuffer(c),T=y.bitmap.width,v=y.bitmap.height;p=Math.max(0,Math.min(p,T-1)),g=Math.max(0,Math.min(g,v-1)),h=Math.max(1,Math.min(h,T-p)),f=Math.max(1,Math.min(f,v-g)),c=await y.crop({x:p,y:g,w:h,h:f}).getBuffer("image/jpeg")}catch(y){throw new Error(`Failed taking element screenshot at coordinates (${p}, ${g}) with size (${h}, ${f}): ${y}`)}finally{"dispose"in e&&await e?.dispose()}return c}getViewport(){return this.viewport?this.viewport:this.page.viewportSize()}async navigate({url:e,initialNavigation:t=!1,loadTimeoutMs:n=this.pageLoadTimeout}){Wy(e)&&(e=new URL(e,this.baseUrl).toString());let o=Date.now();t||(await this.waitForPageLoad(),await this.waitForDOMStability());let i=!1,a;for(let c=0;c<3;c++)try{await this.page.goto(e,{timeout:n,waitUntil:"domcontentloaded"}),i=!0;break}catch(s){if(a=s,this.abortSignal?.throwIfAborted(),this.logger.warn({err:s},`Error occurred during navigation${c===0?", retrying...":" (fatal)"}`),await q(500),a.message.includes("Timeout")&&a.message.includes("exceeded")||a.message.includes("net::ERR_CONNECTION_REFUSED"))break;await this.cdpClient.send({method:"Page.stopLoading",params:{},timeout:1e3})}if(!i)throw new A("UserInfrastructureError",a?.message??"Failed to load page");await this.loadFrameAndRecordUrl({root:this.page,signal:this.abortSignal,codePath:"navigate-step-wait-for-load"}),this.logger.info({url:e},`Navigation complete in ${Math.floor(Date.now()-o)}ms`);let l=this.url();if(oT.has(l))throw new A("UserInfrastructureError",`${e} took too long to load \u{1F61E}. Please ensure the site is accessible and returns content within the page load timeout.`);if(t)try{await this.exposeRecordingBindings()}catch(c){c instanceof Error&&c.message.includes("already registered")||this.logger.error({err:c},"Failed to install Momentic libraries for action recording")}await this.fixViewportForNewHeadless()}async type(e,t={},n=!1){await this.directTypeHelper(e,t,n)}async getActiveElement(e){try{return await He({root:e,fn:()=>{let n=document.activeElement?.textContent??void 0;return n&&n.length>100&&(n=n.slice(0,100)+"...[TRUNCATED]"),document.activeElement?{tag:document.activeElement.tagName.toLowerCase(),contentEditable:document.activeElement.getAttribute("contenteditable")??void 0,textContent:n}:void 0},arg:void 0,timeout:1e3,waitForPageLoad:()=>this.waitForPageLoad(),codePath:"getting the active element"})}catch(t){this.logger.warn({err:t},"Failed to get active element");return}}async directTypeHelper(e,t={},n=!1){let o=await this.getActivePageOrFrame();await vT({root:o,text:e,options:t,logger:this.logger,callbacks:this.getBrowserCallbacks()});let i=await this.getActiveElement(o);if(n){let a=Date.now();for(;Date.now()-a<this.smartWaitingTimeout&&(!i||i.tag==="body");)await q(250),this.abortSignal?.throwIfAborted(),i=await this.getActiveElement(o);i||this.logger.warn("No active element found to type into, attempting anyways")}t.clearContent&&(t.forceClearContent||i?.tag==="input"||i?.tag==="textarea"?(process.platform==="darwin"?await this.page.keyboard.press("Meta+A"):await this.page.keyboard.press("Control+A"),await this.page.keyboard.press("Backspace"),await this.page.waitForTimeout(25)):this.logger.info({activeElementDetails:i},"Currently active element is not eligible for replace content, skipping...")),await this.page.keyboard.type(e,{delay:t.delay??ap}),t.pressEnter&&await this.press("Enter",{})}async scrollIntoViewIfNeeded(e){try{await e.scrollIntoViewIfNeeded({timeout:2e3})}catch(t){this.logger.warn({err:t},"Failed to scroll into view, trying with raw JS");try{await e.evaluate(async n=>{let o=n.scrollTop;n.scrollIntoView(),await new Promise(a=>setTimeout(a,250));let i=Date.now();for(;Date.now()-i<1e3;){let a=n.scrollTop;if(a===o)break;o=a,await new Promise(l=>setTimeout(l,250))}},void 0,{timeout:2e3})}catch(n){this.logger.warn({err:n},"Failed to scroll into view using JS, continuing...")}}}async highlightA11yId(e){try{let{resolution:t}=await this.createTargetFromA11yId({id:e,description:null,targetSource:"AI",skipSaveToCache:!0});return await this.highlight(t.locator),!0}catch(t){return this.logger.debug({err:t,id:e},"Failed to highlight target"),!1}}async highlight(e){return rl({locator:e,callbacks:this.getBrowserCallbacks(),logger:this.logger})}recordUrlVisited(e){try{let t=new URL(e).origin;if(t==="null")return;this.originsVisited.add(t)}catch(t){this.logger.warn({err:t},"Failed to record origin visited")}}async waitForPageLoad(){let e=Date.now(),t=Object.values(this.pageLoadPromises),n=Object.keys(this.pageLoadPromises),o=-1,i=0;for(;t.length!==0;){if(Date.now()-e>this.pageLoadTimeout&&this.logger.error({outstandingPromiseKeys:n,outstandingPromises:t},"Still waiting on page load promises"),Date.now()-o<20&&(i++,i>2)){this.logger.error({outstandingPromiseKeys:n,outstandingPromises:t},"Synchronous waiting loop detected, exiting page load wait");return}o=Date.now(),await Promise.allSettled(t),t=Object.values(this.pageLoadPromises),n=Object.keys(this.pageLoadPromises)}}async clearAuthState(e){await this.context.clearCookies();for(let o of this.originsVisited)this.logger.debug({origin:o},`Clearing data using CDP for origin ${o}`),await this.cdpClient.send({method:"Storage.clearDataForOrigin",params:{origin:o,storageTypes:"all"},timeout:1e3}),this.originsVisited.delete(o);let t=this.context.pages().indexOf(this.page),n=[...this.context.pages()];for(let o=0;o<n.length;o++){let i=n[o];if(i.isClosed())continue;let a=i.url();try{this.originsVisited.delete(new URL(a).origin)}catch{}await uT(i,this.logger),o!==t&&e.closeNonActiveTabs&&(this.logger.info(`Closing tab ${o} with URL ${a}`),await i.close())}}async loadAuthState(e){await this.waitForPageLoad(),await this.waitForDOMStability(),!e||Object.keys(e).length===0?await this.clearAuthState({closeNonActiveTabs:!1}):await this.loadAuthStateHelper(e),await this.refresh(),await this.waitForDOMStability()}async loadAuthStateHelper(e){let t=[];for(let i of e.cookies??[]){let a=await this.setCookie(i);t=t.concat(a)}this.logger.info(`Loaded ${e.cookies?.length??0} cookies`),await this.cdpClient.send({method:"DOMStorage.enable",params:void 0,timeout:1e3});let n=0;for(let i of e.origins??[])for(let a of i.localStorage)try{await this.cdpClient.send({timeout:1e3,method:"DOMStorage.setDOMStorageItem",params:{storageId:{securityOrigin:new URL(i.origin).origin,isLocalStorage:!0},key:a.name,value:a.value}}),n++}catch(l){this.logger.warn({err:l,origin:i},"Failed to set local storage entry, continuing...");break}this.logger.info(`Loaded ${n} local storage entries`);let o=e.idb;o&&Object.keys(o).length>0&&(await cT(this.page,o,this.logger),this.logger.info(`Loaded ${Object.keys(o??{}).length} indexedDB databases`))}async saveAuthState(){let t=0,n=null;for(;t<=2;)try{await this.waitForPageLoad(),await this.waitForDOMStability();let o=await this.context.storageState();return o.idb=await lT(this.page,this.logger),o}catch(o){if(n=o,t++,t<=2){this.logger.warn({err:o,retryCount:t,maxRetries:2},`Error saving auth state, retrying (${t}/2)...`);let i=Math.pow(2,t)*100;await new Promise(a=>setTimeout(a,i))}}throw this.logger.error({err:n},"Failed to save auth state after 2 retries"),new A("ActionFailureError",`Failed to save auth state: ${n?.message}`)}async getOpenPages(e){return Ld(this.context,e)}saveA11yDetailsToCache(e,t){t.content=e.content,t.name=e.name,t.role=e.role,t.numChildren=e.children.length,delete t.serializedForm,delete t.nodeOnlySerializedForm}async updateCacheWithNewNodeDetails({node:e,target:t,locator:n,forceSaveNewCssSelectors:o,startingBoundingBox:i,allowNotActionableNodesOverride:a,logger:l=this.logger}){if(e&&this.saveA11yDetailsToCache(e,t),t.frameCache=this.stateManager.saveAutoFrameCacheDetails(t.frameCache),n)try{let c=await this.fetchHtmlAttributes({locator:n,logger:l,startingBoundingBox:i,allowNotActionableNodesOverride:a}),s=!1;for(let u of["generatedSelectors","serializedHtml","nodeOnlySerializedHtml","hybridSelector"]){let d=c?.[u];if(d&&!t[u]){s=!0;break}if(d&&JSON.stringify(d)!==JSON.stringify(t[u])){s=!0;break}}c&&(o||s)&&(t.generatedSelectors=c.generatedSelectors,t.serializedHtml=c.serializedHtml,t.nodeOnlySerializedHtml=c.nodeOnlySerializedHtml,t.hybridSelector=c.hybridSelector)}catch(c){if(c instanceof Zt)throw c;l.warn({err:c},"Failed to fetch HTML attributes for target, continuing...")}try{await this.saveElementVisualAttributes({target:t,locator:n,logger:l,boundingBox:i})}catch(c){l.debug({err:c},"Failed to save element visual details, continuing...")}}async saveElementVisualAttributes({target:e,locator:t,logger:n,boundingBox:o}){if(!t)return{scrollPerformed:!1};if(!Ed.includes(e?.role??""))return{scrollPerformed:!1};if(await this.scrollIntoViewIfNeeded(t),o||(o=await t.boundingBox({timeout:3e3})),!o||!o.width||!o.height)return n.debug("Skipping visual attributes saving for element with no bounding box after action"),e.boundingBox=void 0,e.screenshotUrl=void 0,{scrollPerformed:!0};let{x:i=0,y:a=0,width:l=0,height:c=0}=o;if(e.boundingBox&&Math.abs(e.boundingBox.width-l)<1&&Math.abs(e.boundingBox.height-c)<1&&Math.abs((e.boundingBox.x??0)-i)<1&&Math.abs((e.boundingBox.y??0)-a)<1)return{scrollPerformed:!0};e.boundingBox=o;let s=await this.screenshot({locator:t,quality:75,retries:0});return e.screenshotUrl=await this.storage.uploadScreenshot(s),{scrollPerformed:!0}}async resolveAutoFrameCache(e){return this.stateManager.resolveAutoFrameCache(e)}async getElementRequiredValues({locator:e,requirements:t}){let n={};if(t?.boundingBox){let o=await e.boundingBox({timeout:3e3});if(!o||!o.width||!o.height)throw new A("ActionFailureError","Element does not have a bounding box as required");n.boundingBox=o??void 0}if(t?.text){let o=await e.innerText({timeout:3e3});n.text=o?.trim()}if(t?.attributes&&t.attributes.length>0){let o={};for(let i of t.attributes){let a=i.trim().toLowerCase();if(!(!a||Ht.bannedAiRequiredCacheAttributes.includes(a)))try{let l=await e.getAttribute(a,{timeout:3e3});l!==null&&(o[i]=l)}catch(l){this.logger.warn({err:l,attr:i},"Failed to fetch required attribute, continuing...")}}n.attributes=o}return n}async getAdditionalElementDetails({mainLocator:e,additionalElement:t,root:n,logger:o}){let i=this.stateManager.a11yIdToNodeMap[t.id];if(!i)return;let a=await this.stateManager.getLocatorFromA11yNode({page:this.page,root:n,node:i});if(e.contentFrame!==a.contentFrame)return;let l=await this.fetchHtmlAttributes({locator:a,logger:o});if(!l?.generatedSelectors||l.generatedSelectors.length===0)return;let c={selectors:l.generatedSelectors};return t.requirements&&(c.requirements=await this.getElementRequiredValues({locator:a,requirements:t.requirements})),c}async getAdditionalElementsDetails({mainElementId:e,mainLocator:t,additionalElements:n,root:o,logger:i}){let a=new Set,l=[];for(let c of n)try{if(c.id===e||a.has(c.id))continue;let s=await this.getAdditionalElementDetails({mainLocator:t,additionalElement:c,root:o,logger:i});if(a.add(c.id),!s)continue;l.push(s)}catch(s){this.logger.warn({err:s,additionalElement:c},"Failed to fetch additional element details, continuing...")}return l}async updateCacheWithAdditionalRequirements({mainElementId:e,requirements:t,additionalElements:n,target:o,locator:i,root:a,logger:l}){t&&(o.requirements=await this.getElementRequiredValues({locator:i,requirements:t})),n&&(o.additionalElements=await this.getAdditionalElementsDetails({mainElementId:e,mainLocator:i,additionalElements:n,root:a,logger:l}))}async createTargetFromA11yId({id:e,description:t,targetSource:n,skipSaveToCache:o,logger:i=this.logger,requirements:a,additionalElements:l}){if(e<0)throw new A("InternalWebAgentError","Only positive IDs should be passed to resolveAllyIdToTarget");let c=this.stateManager.a11yIdToNodeMap[e];if(!c)throw new A("InternalWebAgentError",`Resolving target failed because id ${e} does not exist on the page. This generally indicates an incorrect element was targeted.`);let s=this.stateManager.frameConfig,u,d,m,p;if(this.userBrowserSettings.autoExpandIframes&&!s&&c.parentFrame){let T=c.parentFrame,{cache:v,config:R}=await this.stateManager.getAutoFrameDetailsFromHandle(T);d=v,m=R,u=R.frame,p="auto iframe"}else c.parentFrame&&s?(m=s,u=await this.getActivePageOrFrame(),p="hardcoded url already on the state manager"):(u=await this.getActivePageOrFrame(),p="should not be possible");let g=await this.stateManager.getLocatorFromA11yNode({page:this.page,root:u,node:c}),h={id:e,inputDescription:t??void 0,targetSource:n,targetUpdateTime:new Date().toISOString(),targetUpdateLoggerTags:de(i),frameCache:d},f,y=!1;o||(m&&(i.info({frameConfigSource:p,frameConfig:ZT(m)},"A11y node was resolved to a target within an iframe"),f=this.stateManager.frameConfig,this.stateManager.setActiveFrameConfig(m),y=!0),await this.updateCacheWithNewNodeDetails({node:c,target:h,locator:g,logger:i,forceSaveNewCssSelectors:!0,allowNotActionableNodesOverride:!0}),await this.updateCacheWithAdditionalRequirements({mainElementId:e,requirements:a,additionalElements:l,target:h,root:u,locator:g,logger:i}));try{return{resolution:{locator:g,a11yNode:c,displayString:c.getNodeOnlySerializedForm(),decisions:[]},target:h,frameConfig:m,frameConfigSource:p}}finally{y&&this.stateManager.setActiveFrameConfig(f)}}async resolveTarget(e,t,n={}){let{targetName:o,logger:i=this.logger,signal:a=this.abortSignal,allowNotActionableNodesOverride:l}=n;if(t.frameCache&&this.userBrowserSettings.autoExpandIframes){let p,g=!1,h=Date.now();for(;Date.now()-h<this.smartWaitingTimeout;)try{let f=await this.stateManager.resolveAutoFrameCache(t.frameCache);this.setActiveFrameConfig(f),g=!0;break}catch(f){p=f,await q(500,a)}if(!g)throw p}let c=await this.getActivePageOrFrame();await this.ensureMomenticBrowserScriptsLoaded(c,i,a);let s=Date.now(),u=0,d=0,m;for(;Date.now()-s<this.smartWaitingTimeout;){this.abortSignal?.throwIfAborted(),u++;let p=u===2||Date.now()-s>this.smartWaitingTimeout-2e3&&u%2===0;try{m=await this.resolveTargetHelper({root:c,target:t,primaryOnly:!0,logger:p?i:dn,allowNotActionableNodesOverride:l,signal:a});break}catch(g){if(g instanceof hi)break;if(g instanceof Zt){if(d++,d>2)throw i.error({err:g},"Got multiple cache disqualification errors, giving up"),g;i.warn({err:g},"Got cache disqualification error, waiting and retrying resolution"),await q(500,a)}a?.throwIfAborted(),p&&i.info({err:g},`Could not resolve target using primary cache only (x${u})`),await q(500,a)}}return m||(m=await this.resolveTargetHelper({root:c,target:t,primaryOnly:!1,logger:i,signal:a,allowNotActionableNodesOverride:l}),t.targetSource="HEURISTIC_HEALED",t.targetUpdateTime=new Date().toISOString(),t.targetUpdateLoggerTags=de(i),i.info({decisions:m.decisions},"Target resolution succeeded after waiting")),e?.details?.push({type:"TARGETING",name:o,elementLocationDecisions:m?.decisions??[],pageState:void 0,targetSource:t.targetSource,targetUpdateTime:t.targetUpdateTime}),m}async resolveTargetHelper({root:e,target:t,primaryOnly:n,logger:o,signal:i,allowNotActionableNodesOverride:a}){let l=Ro(t),c=[],s=(await this.getBrowserState({logger:o,abortSignal:i,skipWait:!0,allowNotActionableNodesOverride:a})).serialize(),u;if(t.generatedSelectors||t.hybridSelector){let d;try{d=await this.resolveTargetWithPrimaryMethods({root:e,target:t,logger:o,allowNotActionableNodesOverride:a})}catch(m){u=m,m instanceof Nr&&c.push(...m.decisions)}if(d)return{...d,pageState:void 0,decisions:[...c,...d.decisions]};n||(c.push({type:"CSS_SELECTOR",matched:!1,reason:u?.message,selectors:Ro(t.generatedSelectors??[])}),t.generatedSelectors=void 0,t.hybridSelector=void 0)}if(n)throw u;if(!this.userBrowserSettings.disableSecondaryCacheResolution){let d=await this.resolveTargetWithSecondaryMethods({root:e,tree:s,target:t,decisions:c,logger:o,signal:i,allowNotActionableNodesOverride:a});if(d)return d}throw new Nr(`Could not find any relevant node given target: ${JSON.stringify(l)}`,c)}async resolveTargetWithPrimaryMethods({root:e,target:t,logger:n,allowNotActionableNodesOverride:o}){if(!t.nodeOnlySerializedHtml)throw new hi("Insufficient data to resolve target using primary methods (missing node HTML)");let i=this.userControlledBrowserSettings.hybridSelectorMode,a={ldistThreshold:.05,requireBoundingBox:!o,ignoreHrefForCaching:this.userControlledBrowserSettings.ignoreHrefForCaching,requireMatchingBoundingBox:this.userControlledBrowserSettings.bustCacheOnBoundingBoxChange?t.boundingBox:void 0,requirements:t.requirements,additionalElements:t.additionalElements},{css:l,hybrid:c}=await He({fn:T=>window.evaluatePrimaryCaches(T),arg:{cssParams:{selectors:t.generatedSelectors??[],cachedElementSerialized:t.nodeOnlySerializedHtml,opts:a},hybridParams:i&&t.hybridSelector?{nodes:t.hybridSelector,cachedElementSerialized:t.nodeOnlySerializedHtml,opts:a}:void 0},root:e,timeout:3e3,waitForPageLoad:()=>this.waitForPageLoad(),codePath:"evaluating target caches"}),s,u,d=[];if(i==="prefer"&&c?.result){s=c.result;let T={type:"HYBRID_SELECTOR",matched:!0,logs:c.logs,reason:"Discovered a match using Momentic's hybrid text and CSS selector approach"};d.push(T),u="HYBRID_SELECTOR"}else if(l?.result){s=l.result;let T=`${s.workingSelectors.length} CSS selectors matched the following element: ${s.serializedElement}`,v=s.workingSelectors.slice(0,5);d.push({type:"CSS_SELECTOR",matched:!0,logs:l.logs,reason:T,selectors:v}),n.debug({reason:T,workingSelectors:v},"Resolved with CSS selectors"),u="CSS_SELECTOR"}else throw d.push({type:"CSS_SELECTOR",matched:!1,reason:l.logs.length===1?"CSS evaluation failed":"No CSS selectors matched",selectors:[],logs:l.logs}),c&&d.push({type:"HYBRID_SELECTOR",matched:!1,reason:c.logs.length===1?"Hybrid evaluation failed":"No hybrid selectors matched",logs:c.logs}),new Nr("Cache evaluation failed",d);let m,p,g,h=!1;if(this.userBrowserSettings.visualActions){let T=s.mPath;if(!T)throw new Error("Found element did not have an mPath despite using visual actions");let v=T.join(" > ");m=e.locator(v),p=this.stateManager.getNodeUsingMPathSelector(v)}else if(s.dataMomenticId!==void 0)g=parseInt(s.dataMomenticId),p=this.stateManager.dataMomenticIdToNodeMap[g],"workingSelectors"in s?(m=e.locator(s.workingSelectors[0]),h=s.workingSelectors.length<5):m=e.locator(qt(g));else throw new A("InternalWebAgentError","Received an element resolution result with no identifying attributes");i&&t.hybridSelector&&(c?.logs.length===1?n.warn({hybridResult:c,cssResult:l,hybridMode:i},"Hybrid selector resolution rejected, continuing..."):c?.result?l?.result&&c?.result&&c.result.serializedElement!==l.result.serializedElement&&(this.userBrowserSettings.visualActions&&JSON.stringify(l.result.mPath)!==JSON.stringify(c.result.mPath)?n.warn({originalCache:t,hybridResult:c,cssResult:l,hybridMode:i,mode:"visualActions"},"Hybrid selector resolution returned a different element than CSS selector resolution, continuing..."):l.result.dataMomenticId!==c.result.dataMomenticId&&n.warn({originalCache:t,hybridResult:c,cssResult:l,hybridMode:i,mode:"dataMomenticId"},"Hybrid selector resolution returned a different element than CSS selector resolution, continuing...")):n.warn({originalCache:t,hybridResult:c,cssResult:l,hybridMode:i},"Hybrid selector resolution returned no eligible elements while CSS resolution did, continuing..."));let f=Ro(t);await this.updateCacheWithNewNodeDetails({node:p,target:t,locator:m,logger:n,startingBoundingBox:s.boundingBox,forceSaveNewCssSelectors:h,allowNotActionableNodesOverride:o});let y=Wd(f,t);return y&&Object.keys(y).length>0&&(t.cacheResolutionUpdateTime=new Date().toISOString(),t.cacheResolutionUpdateLoggerTags=de(n),t.cacheResolutionUpdateSource=u,n.debug({diffs:y},"Updated cache")),{a11yNode:p,displayString:s.serializedElement,locator:m,decisions:d}}async resolveHardcodedCssSelector(e){let{ctx:t,selector:n,logger:o=this.logger,signal:i=this.abortSignal,timeoutMs:a=this.smartWaitingTimeout}=e,l=await this.getActivePageOrFrame(),c=Date.now(),s=0,u,d=[];for(;Date.now()-c<a;){i?.throwIfAborted(),s++;let m=l.locator(n),p;try{return await m.waitFor({state:"attached",timeout:1e3}),p=await yr(m,o)??"",d.push({type:"USER_SELECTOR",matched:!0,reason:`The user-provided CSS selector ${n} matched an element on the page.`}),t?.details?.push({type:"TARGETING",name:e.targetName,elementLocationDecisions:d,targetSource:"USER_CSS_SELECTOR",targetUpdateTime:new Date().toISOString()}),{locator:m,displayString:p,decisions:d}}catch(g){let h=g.message;u=new A("ActionFailureError",`CSS selector '${n}' failed to resolve after ${s} attempts: ${h.includes("locator.waitFor: Timeout")?"the selector did not match any element on the page":h}`),await q(500,i)}}throw u}async resolveTargetWithSecondaryMethods(e){if(!e.target.boundingBox)return;let{x:t,y:n,width:o,height:i}=e.target.boundingBox,a=await this.resolveTargetWithSecondaryMethodsHelper(e);if(!a)return;let l=await a.locator.boundingBox({timeout:3e3});if(!l){this.logger.debug({proposedNode:a.displayString},"Rejecting secondary matching result due to lack of a bounding box");return}let{x:c,y:s,width:u,height:d}=l;if(Math.abs(u-o)>10||Math.abs(d-i)>10){this.logger.debug({newW:u,oldW:o,newH:d,oldH:i,proposedNode:a.displayString},"Rejecting secondary matching result due to difference in dimensions");return}else if(!t||!n||!c||!s){this.logger.debug({oldX:t,oldY:n,newX:c,newY:s,proposedNode:a.displayString},"Rejecting secondary matching result due to missing x/y coords");return}else if(Math.abs(c-t)>100||Math.abs(s-n)>100){this.logger.debug({newX:c,newY:s,oldX:t,oldY:n,proposedNode:a.displayString},"Rejecting secondary matching result due to large difference in x/y coords");return}return a}async resolveTargetWithSecondaryMethodsHelper({root:e,target:t,decisions:n,logger:o,signal:i,allowNotActionableNodesOverride:a}){if(t.nodeOnlySerializedHtml&&t.nodeOnlySerializedHtml.trim().length<10){let s="Refusing to attempt HTML comparison since the saved element is too short.";n.push({type:"HTML_DISTANCE",matched:!1,reason:s})}else if(t.nodeOnlySerializedHtml&&t.nodeOnlySerializedHtml.length>50)try{let s=await He({fn:d=>window.findClosestElementByLDist?.(d),arg:{nodeOnlySerializedHtml:t.nodeOnlySerializedHtml},timeout:2e3,root:e,waitForPageLoad:()=>this.waitForPageLoad(),codePath:"finding the closest element on the page"}),u=Math.floor(.05*t.nodeOnlySerializedHtml.length);if(s&&s.closestDistance&&s.closestDistance>=u){let d=`Closest HTML candidate still has too far distance (${s.closestDistance}) from threshold (${u})`;n.push({type:"HTML_DISTANCE",matched:!1,reason:d,distance:s.closestDistance,closestElement:s.closestNodeSerialized})}else{if(s?.error)throw new Error(s.error);if(s?.dataMomenticId||s?.mPathSelector){let d=s.dataMomenticId?parseInt(s.dataMomenticId):void 0,m,p;if(d)m=this.stateManager.dataMomenticIdToNodeMap[d],p=e.locator(qt(d));else if(s.mPathSelector)m=this.stateManager.getNodeUsingMPathSelector(s.mPathSelector),p=e.locator(s.mPathSelector);else throw new Error("HTML ldist comparison returned no error, data momentic id, or mPath selector");let g=s.closestNodeSerialized??await yr(p,o)??"unknown element";o.warn({result:s,originalTarget:t,displayString:g},"Resolved cached target to new node with pure html levenshtein distance");let h=Ro(t);await this.updateCacheWithNewNodeDetails({node:m,target:t,locator:p,logger:o,startingBoundingBox:s.boundingBox,allowNotActionableNodesOverride:a,forceSaveNewCssSelectors:!0});let f=Wd(h,t);return f&&Object.keys(f).length>0&&(t.cacheResolutionUpdateTime=new Date().toISOString(),t.cacheResolutionUpdateLoggerTags=de(o),t.cacheResolutionUpdateSource="HTML_DISTANCE",o.info({diffs:f,result:s},"Updated cache after l-dist resolution")),n.push({type:"HTML_DISTANCE",matched:!0,reason:`Found an element on the page within ${u} string comparison distance of the saved element.`,logs:s.logs,distance:s.closestDistance,closestElement:g,savedElement:t.nodeOnlySerializedHtml}),{locator:p,a11yNode:m,displayString:g,decisions:n,pageState:void 0}}else throw new Error(`Got invalid HTML evaluation result: ${JSON.stringify(s)}`)}}catch(s){o.info({err:s},"Failed to find closest HTML node using levenshtein distance"),n.push({type:"HTML_DISTANCE",matched:!1,reason:`Error finding closest HTML node by string distance: ${s}`})}let l=t.screenshotUrl,c=t.role??"";if(l&&Ed.includes(c))try{let s=await this.resolveTargetWithTemplateMatching({root:e,oldTarget:t,screenshotUrl:l,signal:i,allowNotActionableNodesOverride:a});return{...s,decisions:[...n,...s.decisions],pageState:void 0}}catch(s){i?.throwIfAborted(),n.push({type:"TEMPLATE_MATCHING",matched:!1,reason:`Error finding closest element using saved screenshot: ${s}`,elementImageUrl:l}),o.warn({err:s},"Did not find any close element using saved screenshot")}}async resolveTargetWithTemplateMatching({root:e,screenshotUrl:t,oldTarget:n,signal:o,allowNotActionableNodesOverride:i}){let a;if(!this.enricher)throw new Error("Enricher not available for screenshot resolution");let l=await this.screenshot({retries:0}),s=await(await fetch(t)).arrayBuffer(),u=DL(),d=await this.enricher.runTemplateMatching({id:u,searchImageBase64String:Buffer.from(s).toString("base64"),pageImageBase64String:l.toString("base64")},{signal:o}),{target:m,locator:p}=await this.getTargetFromPositionPercentages({percentX:d.x,percentY:d.y,allowNotActionableNodesOverride:i}),g=m.boundingBox?.width,h=m.boundingBox?.height;if(!g||!h)throw a="Rejecting target from screenshot due to no bounding box",new Error(a);let f=m.id,y=this.stateManager.a11yIdToNodeMap[f],T=Ro(n);await this.updateCacheWithNewNodeDetails({target:n,node:y,locator:p,forceSaveNewCssSelectors:!0,allowNotActionableNodesOverride:i});let v=Wd(T,n);return v&&Object.keys(v).length>0&&(n.cacheResolutionUpdateTime=new Date().toISOString(),n.cacheResolutionUpdateLoggerTags=de(this.logger),n.cacheResolutionUpdateSource="TEMPLATE_MATCHING",this.logger.info({id:u,diffs:v,templateMatch:d},"Updated cache after template matching resolution")),{locator:p,a11yNode:y,displayString:m.nodeOnlySerializedHtml??"",decisions:[{type:"TEMPLATE_MATCHING",matched:!0,reason:"Found element using screenshot",elementImageUrl:t}]}}async typeIntoTarget(e,t,n={}){await this.highlight(t.locator);let o=await t.locator.getAttribute("type",{timeout:1e3})??"",i=bT.some(a=>a===o.toLowerCase());return await Pd({targetingResult:t,options:{force:n.force},logger:this.logger,retryTimeoutMs:this.smartWaitingTimeout,position:i?{x:1,y:1}:void 0,actionSource:"type",browserCallbacks:this.getBrowserCallbacks()}),await this.page.waitForTimeout(150),this.directTypeHelper(e,n)}async click(e,t,n={}){return Pd({targetingResult:e,options:n,logger:this.logger,actionSource:"click",retryTimeoutMs:this.smartWaitingTimeout,controllerCallbacks:t,browserCallbacks:this.getBrowserCallbacks()})}async waitForUrl({beforeUrl:e,matcher:t},n){let o=n?.timeout??this.pageLoadTimeout,i=Date.now(),a=!1,l=e;for(;Date.now()-i<o;){if(this.abortSignal?.throwIfAborted(),l=this.url(),Ys(l,t,n)){a=!0;break}await q(500,this.abortSignal)}if(!a)throw new A("ActionFailureError",`The active page URL ${n?.negated?"still does":"does not"} ${Sy(t)} in ${o}ms.
4003
- Current tab: ${l}`);try{await this.loadFrameAndRecordUrl({root:this.page,signal:this.abortSignal,codePath:"wait-for-url-step"})}catch(c){this.logger.warn({err:c},"Failed waiting for page load after URL change, continuing...")}}async dragAndDrop(e,t,n={}){await this.hover({locator:e}),await this.page.mouse.down();let o=await t.boundingBox({timeout:3e3});if(!o)throw new A("ActionFailureError","Could not get bounding box of target element");let i=o.x+o.width/2,a=o.y+o.height/2,l=n.steps??5;await this.page.mouse.move(i,a,{steps:l}),await q(n.hoverSeconds?Math.min(n.hoverSeconds*1e3,2e3):500),await this.page.mouse.up()}async mouseDrag(e,t,n,o){o&&await this.hover({locator:o});let i=await(await this.getActivePageOrFrame()).evaluate(Md);i||(this.logger.warn("Could not get current mouse position before mouse drag action, defaulting to 0,0"),i={left:0,top:0}),await this.page.mouse.down(),await this.page.mouse.move(e+i.left,t+i.top,{steps:n}),await q(250),await this.page.mouse.up()}async hover(e){await this.highlight(e.locator),await Cn({func:async t=>{await this.scrollIntoViewIfNeeded(t.locator);let n=await t.locator.boundingBox({timeout:3e3});if(!n)throw new Error("Attempted to hover over element with no bounding box");await this.page.mouse.move(n.x+n.width/2,n.y+n.height/2,{steps:3})},action:"hovering over element",logger:this.logger,retryTimeoutMs:this.smartWaitingTimeout,targetingResult:e,callbacks:this.getBrowserCallbacks()})}async focus(e){await this.highlight(e.locator),await Cn({func:t=>t.locator.focus({timeout:2e3}),action:"focusing element",logger:this.logger,retryTimeoutMs:this.smartWaitingTimeout,callbacks:this.getBrowserCallbacks(),targetingResult:e})}async blur(e){if(!e){let t=await this.getActivePageOrFrame();await He({fn:()=>{let n=document.activeElement;n&&n.nodeType===1&&n.blur()},root:t,arg:void 0,waitForPageLoad:()=>this.waitForPageLoad(),timeout:1e3,codePath:"blurring the active element"});return}await this.highlight(e.locator),await Cn({func:t=>t.locator.blur({timeout:2e3}),action:"blurring element",logger:this.logger,retryTimeoutMs:this.smartWaitingTimeout,callbacks:this.getBrowserCallbacks(),targetingResult:e})}async selectOption(e,t,n=!1){await this.highlight(e.locator),await Cn({action:"selecting option from dropdown",logger:this.logger,retryTimeoutMs:this.smartWaitingTimeout,callbacks:this.getBrowserCallbacks(),func:async o=>{if(t.type==="INDEX"){let i=Number(t.index);if(isNaN(i))throw new A("UserConfigurationError",`Page index ${t.index} is not a number`)}await o.locator.selectOption({value:t.type==="VALUE"?t.value:void 0,label:t.type==="LABEL"?t.label:void 0,index:t.type==="INDEX"?Number(t.index):void 0},{force:n,timeout:3e3})},targetingResult:e})}async press(e,t){let n=t.repeat??1;if(t.convertMeta){let o=nl(e);o!==e&&(this.logger.info({key:e,convertedKey:o},"Converted platform dependent keys"),e=o)}for(let o=0;o<n;o++)await this.page.keyboard.press(e,{delay:t.delayMs??0})}async keyDown(e,t){if(t.convertMeta){let n=nl(e);n!==e&&(this.logger.info({keyString:e,convertedKey:n},"Converted platform dependent keys"),e=n)}for(let n of Vd(e))await this.page.keyboard.down(n)}async keyUp(e,t){if(t.convertMeta){let n=nl(e);n!==e&&(this.logger.info({keyString:e,convertedKey:n},"Converted platform dependent keys"),e=n)}for(let n of Vd(e))await this.page.keyboard.up(n)}async refresh(e){let t=e?.loadTimeoutMs??this.pageLoadTimeout;await this.waitForPageLoad();let n=0,o=2;for(;n<o;){n++;try{await this.page.reload({waitUntil:"domcontentloaded",timeout:t});break}catch(i){this.logger.warn({err:i,attempt:n},`Failed to reload page${n<o?", retrying...":", continuing..."}`)}}await this.loadFrameAndRecordUrl({root:this.page,signal:this.abortSignal,codePath:"reload-step"}),await this.waitForDOMStability()}async getBrowserState(e){let{maxAttempts:t=2,logger:n=this.logger,skipWaitForPageLoad:o,allowNotActionableNodesOverride:i}=e,a=e.abortSignal??this.abortSignal,l=!i,c=i?!0:this.userControlledBrowserSettings.showZeroOpacityElements;o||await this.waitForPageLoad(),e.skipWait||await this.waitForDOMStability({logger:n,signal:a});let s=0,u;for(;s<t;){s++;try{return await B(this.stateManager.getA11yTree({devicePixelRatio:this.devicePixelRatio,abortSignal:a,logger:n,filterByViewport:e.filterByViewport,showZeroOpacityElements:c,flagNotActionableNodes:l}),{milliseconds:this.pageLoadTimeout*s,signal:a,message:"Getting browser state took too long"})}catch(d){if(a?.throwIfAborted(),u=d instanceof Error?d.message:`${d}`,s>=t)throw d;n.warn({err:d,url:this.url()},"Error getting a11y tree, retrying...")}}throw new A("ActionFailureError",`Getting page content failed after ${t} attempts. Error: ${u}`)}async getViewportOffsetDetails(e){let[t,n,o,i,a]=await He({root:e,fn:()=>[window.scrollY,window.scrollX,window.screen.width,window.screen.height,window.devicePixelRatio],arg:void 0,timeout:3e3,waitForPageLoad:async()=>{},codePath:"getting current viewport details"});return{upperBound:t,lowerBound:t+i,leftBound:n,rightBound:n+o,width:o,height:i,devicePixelRatio:this.properties.systemDevicePixelRatio??a}}async waitForDOMStability(e){let{logger:t=this.logger,timeout:n=this.smartWaitingTimeout,signal:o}=e??{},i={value:Date.now()},a=m=>{i.value=Date.now()},l=()=>a("DOM.documentUpdated");this.cdpClient.addListener("DOM.documentUpdated",l);let c=()=>a("Page.frameDetached");this.cdpClient.addListener("Page.frameDetached",()=>c);let s=()=>a("Page.frameStartedLoading");this.cdpClient.addListener("Page.frameStartedLoading",s);let u=()=>a("Page.navigatedWithinDocument");this.cdpClient.addListener("Page.navigatedWithinDocument",u);let d=()=>a("frameRequestedNavListener");this.cdpClient.addListener("Page.frameRequestedNavigation",d);try{await this.waitForDOMStabilityHelper(i,t,n,o)}finally{this.cdpClient.removeListener("DOM.documentUpdated",l),this.cdpClient.removeListener("Page.frameDetached",c),this.cdpClient.removeListener("Page.frameStartedLoading",s),this.cdpClient.removeListener("Page.navigatedWithinDocument",u),this.cdpClient.removeListener("Page.frameRequestedNavigation",d)}}async waitForDOMStabilityHelper(e,t,n,o){let i=!1,a=Date.now(),l,c={quality:25,retries:0,stabilizeBeforeScreenshot:!0},s=!1,u=0;for(;Date.now()-a<n;){if(o?.throwIfAborted(),await q(250,this.abortSignal),l)try{let d=await this.screenshot(c);if(!d.equals(l)){l=d,s=!1;continue}s=!0}catch(d){u++,u%3===0&&t.warn({err:d,screenshotErrors:u},"Failed to take screenshot for DOM stability check"),o?.throwIfAborted()}else try{l=await this.screenshot(c)}catch(d){u++,u%3===0&&t.warn({err:d,screenshotErrors:u},"Failed to take screenshot for DOM stability check"),o?.throwIfAborted()}if(!(Date.now()-e.value<250)){i=!0;break}}i||t.warn({duration:Date.now()-a,stable:{a11y:i,screenshot:s}},"A11y wait phase completed due to timeout, continuing...")}async clickUsingVisualCoordinates(e,t){let{x:n,y:o}=e;this.logger.debug({x:n,y:o},"Executing mouse click with visual coordinates"),await this.waitForPageLoad(),await this.page.mouse.click(n,o,{button:t.rightClick?"right":"left",clickCount:t.doubleClick?2:1})}async dragAndDropUsingVisualCoordinates(e,t,n){await this.page.mouse.move(e.x,e.y,{steps:3}),await this.page.mouse.down(),await this.page.mouse.move(t.x,t.y,{steps:3}),await q(n.hoverSeconds?Math.min(n.hoverSeconds*1e3,8e3):500),await this.page.mouse.up()}async hoverUsingVisualCoordinates(e){await this.page.mouse.move(e.x,e.y)}async mouseDragUsingVisualCoordinates(e,t,n,o){await this.hoverUsingVisualCoordinates(o);let i=await(await this.getActivePageOrFrame()).evaluate(Md);i||(this.logger.warn("Could not get current mouse position before mouse drag action, defaulting to 0,0"),i={left:0,top:0}),await this.page.mouse.down(),await this.page.mouse.move(e+i.left,t+i.top,{steps:n}),await q(250),await this.page.mouse.up()}async getElementLocation(e){let t=await this.cdpClient.send({method:"DOMSnapshot.captureSnapshot",params:{computedStyles:[],includeDOMRects:!0,includePaintOrder:!0},timeout:3e3}),n=await B(this.page.evaluate(()=>window.devicePixelRatio),{milliseconds:2e3});process.platform==="darwin"&&n===1&&(n=2);let o=t.documents[0],i=o.layout,a=o.nodes,l=a.nodeName||[],c=a.backendNodeId||[],s=i.nodeIndex,u=i.bounds,d=-1;for(let T=0;T<l.length;T++)if(c[T]===e){d=s.indexOf(T);break}if(d===-1)throw new Error(`Could not find any backend node with ID ${e}`);let[m=0,p=0,g=0,h=0]=u[d];m/=n,p/=n,g/=n,h/=n;let f=m+g/2,y=p+h/2;return{centerX:f,centerY:y}}async scrollVertical(e){return Od({frame:this.stateManager.frameConfig?await this.getActivePageOrFrame():null,page:this.page,deltaX:0,directionX:null,deltaY:e?Math.abs(e):null,directionY:e&&e>0?"down":"up",signal:this.abortSignal,callbacks:this.getBrowserCallbacks(),logger:this.logger})}async scrollHorizontal(e){return Od({frame:this.stateManager.frameConfig?await this.getActivePageOrFrame():null,page:this.page,deltaX:e?Math.abs(e):null,directionX:e&&e>0?"right":"left",deltaY:0,directionY:null,signal:this.abortSignal,callbacks:this.getBrowserCallbacks(),logger:this.logger})}async goForward(){await this.waitForPageLoad(),await this.page.goForward({waitUntil:"domcontentloaded",timeout:this.pageLoadTimeout}),await this.loadFrameAndRecordUrl({root:this.page,signal:this.abortSignal,codePath:"go-forward"})}async goBack(){await this.waitForPageLoad(),await this.page.goBack({waitUntil:"domcontentloaded",timeout:this.pageLoadTimeout}),await this.loadFrameAndRecordUrl({root:this.page,signal:this.abortSignal,codePath:"go-back"})}async createRawCDPSession(e){let t=await B(this.context.newCDPSession(this.page),{milliseconds:e??this.pageLoadTimeout,fallback:()=>{throw this.logger.error(`Timed out creating new CDP session for ${this.page.url()}`),new A("UserInfrastructureError",`Failed to initialize Chrome session within the page load timeout (${this.page.url()})`)}});return this.logger.info(`Created new CDP session for ${this.page.url()}`),t}async reinitializeCDPClient(e){await this.cdpClient.reinitialize(e),await this.initializeScreencast()}async stopScreencast(){if(this.clientCallbacks?.onScreencastFrame)try{await this.cdpClient.send({method:"Page.stopScreencast",params:{}})}catch{}}async changeActivePage(e,t){await this.stopScreencast(),this.recordUrlVisited(e.url()),this.page=e,await this.reinitializeCDPClient(t??this.pageLoadTimeout)}async createNewTab(e,t){let n=await this.context.newPage();await this.changeActivePage(n,t?.loadTimeoutMs),await this.navigate({url:e,initialNavigation:!0,...t}),this.handleAvailableTabsChange()}async switchToPage(e,t){let n=!0,o,i=Date.now();for(;n||t?.retry&&Date.now()-i<this.smartWaitingTimeout;){n=!1;try{await this.switchToPageHelper(e,t);return}catch(a){this.logger.warn({err:a},"Error switching to page, retrying..."),o=a,await q(500)}}throw o}async switchToPageHelper(e,t){let n=this.context.pages().map((i,a)=>({page:i,url:i.url(),index:a})),o;if(e.type==="INDEX"){let i=Number(e.index);if(isNaN(i))throw new A("UserConfigurationError",`Page index ${e.index} is not a number`);if(i<0||i>=n.length)throw new Error(`Page index ${e.index} exceeds the number of available pages: ${JSON.stringify(n.map(a=>a.url))}`);o=n[i]}else{let i=n.filter(a=>e.type==="SUBSTRING"?a.url.includes(e.substring):a.url.match(e.pattern));i.length>1&&this.logger.warn(`More than one page matches the page switch criteria: ${JSON.stringify(i.map(a=>a.url))}`),o=i[i.length-1]}if(!o)throw new Error(`Could not find matching page using criteria: ${JSON.stringify(e)}.
4004
- Available pages:${JSON.stringify(n.map(i=>i.url))}`);if(!wn(o.url,this.logger)){this.logger.error(`Refusing to switch to page with invalid URL: ${o.url}`);return}this.logger.info(`Switching to tab ${o.index} with url ${o.url}`),await this.changeActivePage(o.page,t?.loadTimeoutMs),await this.loadFrameAndRecordUrl({root:o.page,signal:this.abortSignal,codePath:"switch-to-tab-step"}),this.handleAvailableTabsChange()}async setCookie(e){let t;return typeof e=="string"?t=Na(e):t=[e],await this.context.addCookies(t),t}async setLocalStorage(e,t){let n;for(let o=0;o<2;o++)try{await this.evaluateFunctionInPage(([i,a])=>{i&&localStorage.setItem(i,a||"")},[e,t],`setting local storage key ${e}`);return}catch(i){n=i}if(n)throw n}async solveCaptcha(){await this.getBrowserState({allowNotActionableNodesOverride:!0});let e;for(let l of Object.values(this.stateManager.a11yIdToNodeMap))if(l.role==="image"&&l.name.toLowerCase().includes("captcha")){if(!l.backendNodeId)continue;e=await this.stateManager.getLocatorFromBackendId(this.page,l.backendNodeId);break}if(!e){let l=await(await this.getActivePageOrFrame()).solveRecaptchas();if(!l.captchas||!l.captchas.length)throw new Error("No captchas found on the page");return}let t=await e.screenshot({type:"jpeg",animations:"allow",caret:"hide",quality:100,timeout:3e3}),n=await fetch("https://api.2captcha.com/createTask",{method:"POST",body:JSON.stringify({clientKey:ml,task:{type:"ImageToTextTask",body:t.toString("base64"),case:!0},languagePool:"en"})});if(!n.ok){let l=`Captcha solver API returned error response: ${n.statusText}`;throw this.logger.error({text:await n.text()},l),new Error(l)}let{taskId:o}=await n.json(),i=Date.now(),a="";for(;Date.now()-i<6e4;){await q(2500);let l=await fetch("https://api.2captcha.com/getTaskResult",{method:"POST",body:JSON.stringify({clientKey:ml,taskId:o})});if(!l.ok){let s=`Captcha solution API returned error response: ${l.statusText}`;throw this.logger.error({text:await l.text()},s),new Error(s)}let c=await l.json();if(c.errorId){let s=`Captcha solution API returned error ID ${c.errorId}`;throw this.logger.error(s),new Error(s)}if(c.status==="ready"){a=c.solution.text;break}}if(!a)throw new Error("Captcha solution timed out");return a}getActiveFrameConfig(){return this.stateManager.frameConfig}async exposeRecordingBindings(){await this.context.exposeBinding("isRecordingActive",()=>this.transformer!==void 0,{handle:!1}),await this.context.exposeBinding("captureTargetedEvent",({frame:e},t)=>{this.transformer&&ob({event:t,frame:e,transformer:this.transformer,enricher:this.enricher,lastScreenshotForRecording:this.lastScreenshotForRecording?.toString("base64"),logger:this.logger})},{handle:!1}),await this.context.exposeBinding("captureKeystroke",async(e,t)=>{this.transformer&&this.transformer.recordKeystroke(t)})}async startRecordingCrons(e){if(e.aborted)return;let t,n=(await this.getOpenPages()).map(l=>l.url),o=0,i=!1,a=async()=>{if(e.aborted||o>8){clearTimeout(t);return}i=!0;let l;try{l=(await this.getOpenPages()).map(s=>s.url),o=0}catch(s){this.logger.debug({err:s},"Failed getting new open pages during recording tab switch cron, skipping..."),o++;return}let c=this.url();for(let s=l.length-1;s>=n.length;s--){let u=l[s];wn(u,this.logger)&&u!==c&&this.logger.info({lastActivePages:n,currentUrl:c,newOpenPages:l},"Auto-following new tab during recording"),await this.switchToPage({type:"INDEX",index:String(s)});break}n=l};t=setInterval(async()=>{if(!i){i=!0;try{await a()}catch(l){this.logger.error({err:l},"Error while checking pages during recording")}finally{i=!1}}},500),e.addEventListener("abort",async()=>{clearInterval(t)})}async startRecording(e,t,n){this.logger.debug({isClickToRecord:n},"Starting recording mode in Chrome browser"),await this.startRecordingCrons(e),await this.page.evaluate(o=>{let i=window;i._MOMENTIC_RECORDING_ACTIVE=!0,i._MOMENTIC_CLICK_RECORD_ACTIVE=o},n),this.transformer=t,await this.injectKnowledgeBaseIntoBrowser(this.page),e.addEventListener("abort",async()=>{this.transformer=void 0,this.lastScreenshotForRecording=void 0;try{await this.page.evaluate(()=>{let o=window;o._MOMENTIC_RECORDING_ACTIVE=!1,o._MOMENTIC_CLICK_RECORD_ACTIVE=!1})}catch{}})}async getSelectOptions(e){return await e.evaluate(n=>Array.from(n.querySelectorAll("option")).map(i=>({value:i.value,label:i.label})),void 0,{timeout:1e3})}getActivePage(){return this.page}async getActivePageOrFrame(){let e=await this.stateManager.resolveActiveFrameConfig({});return e?(await this.loadFrameAndRecordUrl({root:e.frame,signal:this.abortSignal,codePath:"get-active-frame-locator"}),e.frame):this.page}async loadFrameAndRecordUrl({root:e,signal:t,codePath:n}){let o=this.pageLoadTimeout,i=e.url();if(!i.includes("chrome-error://")){try{await An({promiseGenerator:async()=>e.waitForLoadState("domcontentloaded",{timeout:o}),signal:t,codePath:`loadFrameAndRecordUrlDomContentLoad-${n}`,logger:this.logger,timeoutMs:this.pageLoadTimeout})}catch(a){let l=a;if(l.name==="AbortError")throw new A("UserInfrastructureError",`The page with URL ${ht(i,50)} did not load within the configured timeout (${o}ms): ${l}`);if(!l.message.includes("detached"))throw l}try{await An({promiseGenerator:async()=>e.waitForLoadState("load",{timeout:o}),signal:t,codePath:`loadFrameAndRecordUrlPageLoad-${n}`,logger:this.logger,timeoutMs:this.pageLoadTimeout})}catch(a){this.logger.warn({err:a,codePath:n,url:i},"Failed waiting for current frame to load, continuing...")}this.recordUrlVisited(e.url())}}async getCondensedHtml(e){let{skipWait:t=!1}=e??{};return t||(await this.waitForPageLoad(),await this.waitForDOMStability()),this.getCondensedHtmlHelper()}async getCondensedHtmlHelper(){let e=await this.getRawCondensedHtml();return RL.html(e,{indent_size:1,indent_with_tabs:!1,preserve_newlines:!1})}async getRawCondensedHtml(){let e=await this.getActivePageOrFrame();await this.ensureMomenticBrowserScriptsLoaded(e,this.logger,this.abortSignal);let{result:t,error:n}=await He({fn:()=>window.getCondensedHtmlTree(),root:e,arg:void 0,timeout:2e3,waitForPageLoad:()=>this.waitForPageLoad(),codePath:"getting condensed HTML tree"});if(n)throw new Error(`Failed to process page HTML: ${n}`);if(!t)throw new A("InternalWebAgentError","Got empty HTML tree - are you sure the page is fully loaded?");return t}registerDialogHandler(e){let t=async n=>{try{e==="ACCEPT"?await n.accept():await n.dismiss()}catch(o){this.logger.warn({err:o},"Failed to handle dialog")}};this.page.once("dialog",t)}async evaluateFunctionInAllFrames(e,t){return this.stateManager.executeFunctionInAllFrames(e,t)}async evaluateFunctionInPage(e,t,n,o=2e3){let i=await this.getActivePageOrFrame();return He({root:i,fn:e,arg:t,timeout:o,waitForPageLoad:()=>this.waitForPageLoad(),codePath:n})}async evaluateCodeInPage({code:e,fragment:t,context:n,timeoutMs:o=Lr}){let i=ET(),a={code:e,fragment:t,context:n},{result:l}=await B(this.page.evaluate(i,a),{milliseconds:o,fallback:()=>{throw this.abortSignal?.throwIfAborted(),new A("ActionFailureError",`Code evaluation in browser exceeded the allowed timeout of ${o/1e3} seconds`)},signal:this.abortSignal});return l}async getDomNodeFromPixelPosition(e,t){await this.cdpClient.send({method:"DOM.getDocument",params:{depth:0},timeout:2e3});let n;try{n=await this.cdpClient.send({method:"DOM.getNodeForLocation",params:{x:e,y:t},timeout:1e3})}catch(o){throw this.logger.error({err:o,x:e,y:t},"Failed to get DOM node from position percents"),new Error("No element was found at the given location")}return n}async getDomNodeFromPositionPercentages(e,{percentX:t,percentY:n}){if(t<0||t>1||n<0||n>1)throw new A("UserConfigurationError","Invalid percent passed to percentage location");let{width:o,height:i,upperBound:a,leftBound:l}=await this.getViewportOffsetDetails(e),c=Math.round(a),s=Math.round(l),u=Math.ceil(o*t),d=Math.ceil(i*n),m=u+s,p=d+c;return this.getDomNodeFromPixelPosition(m,p)}async highlightFromPositionPercentages(e){let t=await this.getActivePageOrFrame(),n;try{n=await this.getDomNodeFromPositionPercentages(t,e)}catch{}return n?(await this.cdpClient.send({method:"Overlay.highlightNode",timeout:1e3,params:{highlightConfig:IT,backendNodeId:n.backendNodeId}}),async()=>{try{await this.cdpClient.send({timeout:1e3,method:"Overlay.hideHighlight",params:{backendNodeId:n?.backendNodeId}})}catch{}}):async()=>{}}async clearAllCdpHighlights(){try{await this.cdpClient.send({method:"Overlay.hideHighlight",params:void 0,timeout:1e3})}catch{}}async getTargetFromPositionPercentages(e){let t=await this.getActivePageOrFrame(),n=await this.getDomNodeFromPositionPercentages(t,e);return this.getTargetFromBackendNodeId({root:t,backendNodeId:n.backendNodeId,allowNotActionableNodesOverride:e.allowNotActionableNodesOverride})}async getTargetFromBackendNodeId({root:e,backendNodeId:t,allowNotActionableNodesOverride:n}){let o=this.stateManager.domGraph?.backendIdToNode[t];if(!o)throw new Error("No DOM node was found with the given backend ID");let i=o?.attributes[Er],a=parseInt(i??"");if(!i||isNaN(a))throw new Error("No data-momentic-id was found on the DOM node");let l=e.locator(qt(a)),c;o.bounds.x!==null&&o.bounds.y!==null&&(c={x:o.bounds.x,y:o.bounds.y,width:o.bounds.width??0,height:o.bounds.height??0});let s=await this.fetchHtmlAttributes({locator:l,logger:this.logger,startingBoundingBox:c,allowNotActionableNodesOverride:n}),u={id:-1,dataMomenticId:a,targetSource:"XY_PERCENT",targetUpdateTime:new Date().toUTCString(),...s};return this.logger.debug({target:u},"Tied backend ID to HTML node"),{target:u,locator:l}}async performTargetRedirection(e,t,n){try{return await this.scrollIntoViewIfNeeded(e),await B(this.performTargetRedirectionHelper(e,t,n),{milliseconds:3e3})??{locator:e}}catch(o){return t.warn({err:o},"Error performing target redirection, using original element"),{locator:e}}}async performTargetRedirectionHelper(e,t,n){let o=Date.now(),i=await yr(e,t);if(n===void 0&&(n=await e.boundingBox({timeout:3e3})??void 0),!n){t.error(`Attempted to click on element with no bounding box: ${i}`);return}let{x:a,y:l,width:c,height:s}=n,u=this.getViewport();if(a<0||l<0||!u||a+c>u.width||l+s>u.height){t.info("Skipping locator redirection because the element is outside the viewport");return}let d=await this.getActivePageOrFrame(),{dataMomenticId:m,mPathSelector:p,error:g,serializedElement:h,point:f,force:y,logs:T}=await e.evaluate(R=>{let b=window;if(!b.performTargetRedirection)throw new Error("performTargetRedirection script is not defined");return b.performTargetRedirection(R)},void 0,{timeout:1e3}),v=Date.now()-o;if(g){t.warn({error:g,serializedElement:h,duration:v,force:y,logs:T},"Got error from target redirection with bounding box");return}else{if(m)return t.info({newDataMomenticId:m,serializedElement:h,duration:v,force:y,logs:T},"Redirected target to new element with bounding box with data-momentic-id"),{locator:d.locator(qt(m)),hints:{clickableXY:f,force:y}};if(p)return t.info({newMPathSelector:p,serializedElement:h,duration:v,force:y,logs:T},"Redirected target to new element with bounding box with mPath"),{locator:d.locator(p),hints:{clickableXY:f,force:y}};if(f)return t.info({point:f,serializedElement:h,duration:v,force:y,logs:T},"Chose specific visible point on original element"),{locator:e,hints:{clickableXY:f,force:y}};if(y)return t.info({serializedElement:h,duration:v,force:y,logs:T},"Forcing click on original element"),{locator:e,hints:{force:y}}}}async fetchHtmlAttributes({locator:e,logger:t=this.logger,startingBoundingBox:n,allowNotActionableNodesOverride:o}){let{hybridSelectorMode:i,showZeroOpacityElements:a}=this.userControlledBrowserSettings,l=await e.evaluate((c,s)=>{let u=window;return u.generateHtmlCacheAttributes?u.generateHtmlCacheAttributes(c,s):{warnings:[],error:"generateHtmlCacheAttributes is not defined"}},{generateHybridSelector:i==="test"||i==="prefer",startingBoundingBox:n,showZeroOpacityElements:o?!0:a},{timeout:2e3});if("error"in l&&l.error)throw l.error.startsWith(tT)?new Ba(l.error):l.error.startsWith(rT)?new za(l.error):new Error(l.error);return l.warnings.length&&t.warn(l,"Got warnings while generating HTML attributes for target"),l.attributes}async moveMouseFromPositionPercentages(e,t){let n=this.getViewport();if(!n)throw new Error("Cannot move mouse using percentages without viewport");let o=Math.ceil(n.width*e),i=Math.ceil(n.height*t);return await this.cdpClient.send({method:"Input.dispatchMouseEvent",params:{type:"mouseMoved",x:o,y:i,button:"left",clickCount:0}}),{x:o,y:i}}async clickMouseFromPositionPercentages(e,t,n){let o=this.getViewport();if(!o)throw new Error("Cannot click mouse using percentages without viewport");let i=Math.ceil(o.width*t),a=Math.ceil(o.height*n);await this.cdpClient.send({method:"Input.dispatchMouseEvent",params:{type:e==="down"?"mousePressed":"mouseReleased",x:i,y:a,button:"left",clickCount:e==="down"?1:0},timeout:1e3})}async scrollFromPositionPercentages(e,t,n,o){let i=this.getViewport();if(!i)throw new Error("Cannot scroll using percentages without viewport");let a=Math.ceil(i.width*e),l=Math.ceil(i.height*t);return await this.cdpClient.send({method:"Input.dispatchMouseEvent",params:{type:"mouseWheel",deltaX:a,deltaY:l,x:n,y:o}}),{deltaX:a,deltaY:l}}canSolveCaptchas(){return!!ml}async getAllFrameUrls(){return await this.stateManager.getAllChildFrameUrls()}async setFileChooserHandler(e){setTimeout(()=>{try{e.cleanup()}catch(t){this.logger.debug({err:t,filePath:e.filePath},"Failed cleaning up file after upload")}},3e4),await this.setFileChooserHandlerHelper(e)}logToUserConsole(e,t,n,...o){let i=this.context.pages().indexOf(e);i=i===-1?0:i,xd(e,this.debugData,i,{type:t,text:`[MOMENTIC] ${n}`,args:o})}async setFileChooserHandlerHelper({filePath:e,filename:t}){if(!dl(e)){let c=`File chooser triggered after the source file ${e} has been cleaned up, ignoring...`;this.logger.error(c),this.logToUserConsole(this.page,"error",c);return}let n=t?.trim()||ML(e),o=AL(e),i=IL(e),a=jc[i];this.page.once("filechooser",async c=>{this.logger.info({filePath:e,fileName:n},"File chooser triggered");try{if(!dl(e))throw new Error(`File chooser triggered after the source file ${e} has been cleaned up, ignoring...`);await c.setFiles({name:n,buffer:o,mimeType:CL.getType(e)||"application/octet-stream"},{timeout:8e3})}catch(s){this.logger.error({err:s},"Error handling file chooser"),this.logToUserConsole(this.page,"error",s.message)}});let l=o.toString("base64");await this.evaluateFunctionInPage(({fileName:c,base64Data:s,mimeType:u})=>{let d=window;d.momenticFileName=c,d.momenticFileBase64=s;let m=atob(s),p=new Array(m.length);for(let h=0;h<m.length;h++)p[h]=m.charCodeAt(h);let g=new Uint8Array(p);d.MomenticFile=class extends Blob{kind="file";name=d.momenticFileName;constructor(){super([g],{type:u})}isSameEntry(h){return h.name===this.name}queryPermission(h){return console.info("[MOMENTIC] MomenticFile.queryPermission called"),Promise.resolve("granted")}remove(){return console.info("[MOMENTIC] MomenticFile.remove called"),Promise.resolve()}async requestPermission(h){return console.info("[MOMENTIC] MomenticFile.requestPermission called"),Promise.resolve("granted")}async getFile(){console.info("[MOMENTIC] MomenticFile.getFile called");let h=new Blob([g]);return new File([h],d.momenticFileName,{type:u})}async createSyncAccessHandle(){throw console.error("[MOMENTIC] Not implemented"),new Error("Not implemented")}async createWritable(){throw console.error("[MOMENTIC] Not implemented"),new Error("Not implemented")}},d.showOpenFilePicker=async()=>(console.info("[MOMENTIC] showOpenFilePicker called"),[new d.MomenticFile])},{fileName:n,base64Data:l,mimeType:a},"set-file-chooser-handler",5e3)}getSerializedFormFromA11yId(e){return this.stateManager.a11yIdToNodeMap[e]?.getNodeOnlySerializedForm()}retrieveAndClearDebugData(){this.cdpClient.loadEventLogs.length>0&&(this.cdpClient.loadEventLogs=[]);let t={...this.debugData};return this.debugData={logsPerPage:[],harPages:{},harEntries:{}},t}async copy(e){try{await this.evaluateFunctionInPage(t=>navigator.clipboard.writeText(t),e,"copying text to clipboard")}catch(t){if(t instanceof Error&&t.message.includes("Document is not focused")){await this.evaluateFunctionInPage(()=>{document.activeElement||document.body.focus()},void 0,"focusing on body element before copying to clipboard"),await this.press("Tab",{}),await this.press("Shift+Tab",{}),await this.evaluateFunctionInPage(n=>navigator.clipboard.writeText(n),e,"copying text to clipboard");return}throw t}}async paste(){await this.waitForPageLoad(),await this.press("Meta+V",{convertMeta:!0})}async registerRequestListener(e){return this.page.waitForResponse(t=>{let n=t.request();return e.matches({url:n.url(),method:n.method()})})}registerRequestRecorder(e,t,n){this.requestRecorders[e]={onRequestStart:(o,i)=>{t.matches({url:i.request.url,method:i.request.method})&&n.onRequestStart(o,i)},onRequestComplete:(o,i)=>{t.matches({url:i.request.url,method:i.request.method})&&n.onRequestComplete(o,i)}}}removeRequestRecorder(e){delete this.requestRecorders[e]}setHeader(e,t,n){this.customHeaders.push({key:e.toLowerCase(),value:t,matcher:n})}registerMock(e,t,n,o){let i=e??jd();return this.mocks[i]={matcher:t,generateResponse:n,fetchOriginalResponse:o},i}removeMock(e){if(!e){this.mocks={};return}delete this.mocks[e]}async setOfflineMode(e){await this.context.setOffline(e)}get smartWaitingTimeout(){return this.userControlledBrowserSettings.smartWaitingTimeoutMs??5e3}get userBrowserSettings(){return Ro(this.userControlledBrowserSettings)}get pageLoadTimeout(){return this.userControlledBrowserSettings.pageLoadTimeoutMs??8e3}get isInPageLoad(){return Object.values(this.pageLoadPromises).length>0}get devicePixelRatio(){return this.properties.systemDevicePixelRatio??1}};import lN from"fetch-cookie";import{cloneDeep as Nb}from"lodash-es";import{CookieJar as cN}from"tough-cookie";async function Yr(r,e={}){let t=await r.getBrowserState(e);return{serializedTree:t.serialize(),tree:t}}async function cr({frameConfig:r,action:e,browser:t}){let n=t.getActiveFrameConfig();r?t.setActiveFrameConfig(r):n?.type==="auto"&&t.setActiveFrameConfig(void 0);try{return await e()}finally{t.setActiveFrameConfig(n)}}var UL=["NAVIGATE","NEW_TAB","TAB","REFRESH","WAIT_FOR_URL"];async function mb({beforeUrl:r,beforePages:e,browser:t,command:n,logger:o}){if(UL.includes(n.type))return;let l=("cache"in n&&n.cache&&"target"in n.cache?n.cache.target:void 0)?.nodeOnlySerializedHtml?.includes("<a")??!1?300:3e3,c=Date.now(),s=0;for(;s===0||Date.now()-c<l;){await q(250),s++;let u=(await t.getOpenPages()).map(m=>m.url),d=t.url();if(u.length!==e.length)for(let m=u.length-1;m>=e.length;m--){let p=u[m];if(wn(p,o)&&p!==r&&p!==d){o.info({beforePages:e,afterPages:u,beforeUrl:r},"Auto-following new tab after preset action"),await t.switchToPage({type:"INDEX",index:String(m)});break}}}}var _n=3.1783027;function FL(r){let e=0;for(let t=0;t<r.length;t++){let n=r.charCodeAt(t);!(n>=48&&n<=57)&&!(n>=65&&n<=90)&&!(n>=97&&n<=122)&&e++}return e}function Tr(r){return Math.ceil(Kd(r)/_n)}function Kd(r){let e=0;if(typeof r=="string"){let t=r;t=t.replaceAll(`
4005
- `,""),t=t.replaceAll(" ","");let n=FL(t);return t.length-n+_n*n}if(typeof r>"u")return 0;if(typeof r=="number")return String(r).length;if(Array.isArray(r))return r.forEach(t=>{e+=Kd(t)}),e;if(typeof r=="object"){let t=r;return Object.keys(t).forEach(n=>{e+=String(n).length,n==="image_url"?(t[n]??{}).detail==="high"?e+=1105*_n:e+=85*_n:e+=Kd(t[n])}),e}if(typeof r=="boolean")return r?4:5;throw new Error(`Unsupported type passed to token length calculator '${typeof r}': ${r}`)}var gb={minChunkTokenCount:500,acceptableChunkTokenCount:3e3,maxChunkTokenCount:8e3,maxLineLength:4e3},hb={minChunkTokenCount:5e3,acceptableChunkTokenCount:15e3,maxChunkTokenCount:5e4,maxLineLength:500},pb=/<(\S+) id="(\d+)".*?>/g,BL=/(<\/(\S+)>)|(<(\S+).*?\/>)/g,fb=["h1","h2","section","footer","nav","aside","form","label","dialog"],zL=[...fb,"span","div","h3"],GL=["table","select","form","ul","ol","menu","pre","code","dialog"],HL=["table","form","dialog","nav","section","ul","select"];function pl(r){return VL(r)}function VL({serializedTree:r,options:e,logger:t}){let{minChunkTokenCount:n,acceptableChunkTokenCount:o,maxChunkTokenCount:i,maxLineLength:a}=e,l=[],c=r.split(`
4006
- `),s=0,u=[],d=0,m=[],p=[],g=!1;for(;s<c.length;){g&&(l.push({ids:m,content:u.join(`
4007
- `),tokenLength:d}),u=[],d=0,m=p.length?[p[p.length-1].id]:[],g=!1);let h=c[s],f=Tr(h);d+=f,h.length>a&&(h=h.slice(0,a));let v=Array.from(h.matchAll(pb)).map(M=>M&&M.length>=3?{tagName:M[1],id:M[2]}:void 0).filter(M=>!!M),b=Array.from(h.matchAll(BL)).map(M=>M&&(M[2]||M[4])).filter(M=>!!M);b.reverse();let x=h.replace(/ id="[0-9]+"/g,"");u.push(x);for(let M of v)m.push(M.id),p.push(M);for(let M of b){let V=p[p.length-1];V&&V.tagName===M&&p.pop()}let N=p.some(M=>GL.includes(M.tagName)),k=c[s+1]??"",$=Tr(k),ee=Array.from(k.matchAll(pb)).map(M=>M&&M.length>2?M[1]:void 0).filter(M=>!!M),oe=ee.some(M=>fb.includes(M)),lt=ee.some(M=>zL.includes(M));d+$>=i&&(g=!0),d>=n&&(oe&&!N||b.some(M=>HL.includes(M)))&&(g=!0),d>=o&&lt&&!N&&(g=!0),s++}return u.length&&l.push({ids:m,content:u.join(`
4008
- `),tokenLength:d}),l.forEach((h,f)=>{t.debug({chunk:h},`Chunk for page filtering (index ${f+1}/${l.length})`)}),{chunks:l}}var jL=9e5,gl=3e5,WL=5e3;async function Mn(r){let{options:e,fixtures:t,screenshot:n}=r,{aiPageFiltering:o}=e,{logger:i,generator:a,orgId:l,signal:c}=t,s=r.tree,u=r.serializedTree,d=Tr(u);if(d>jL)try{let m=pl({serializedTree:u,options:{minChunkTokenCount:1e4,maxChunkTokenCount:1e5,acceptableChunkTokenCount:5e4,maxLineLength:4e3},logger:i});s=await qL({...r,tokenLimit:gl-1e4,chunks:m.chunks}),u=s.serialize();let p=Tr(u);i.info({oldTokens:d,newTokens:p},"Filtered page using keywords"),d=p}catch(m){i.warn({err:m},"Error filtering page using keyword matching, using naive truncation"),s=s.pruneToSerializedCharLimit(gl*_n),u=s.serialize(),i.info("Filtered page using naive truncation")}if(d>gl)try{if(o){let m=pl({serializedTree:u,options:hb,logger:i});s=await B($L({...r,chunks:m.chunks}),{milliseconds:12e3}),u=s.serialize();let p=Tr(u);i.info({oldTokens:d,newTokens:p},"Filtered page using AI chunk ranking"),d=p}else{let m=pl({serializedTree:u,options:gb,logger:i});s=await B(KL({...r,chunkResult:m,tokenLimit:4e4}),{milliseconds:12e3,signal:c}),u=s.serialize();let p=Tr(u);i.info({oldTokens:d,newTokens:p},"Filtered page using RAG"),d=p}}catch(m){i.warn({err:m},"Error filtering page using RAG/AI, using naive truncation"),s=s.pruneToSerializedCharLimit(gl*_n),u=s.serialize(),i.info("Filtered page using naive truncation")}if(o&&d>WL&&r.type==="locator"&&(l==="org_01HMSCJQBCCG51M2ZF65YC5B8W"||l==="org_01HMJTX4GT1KG94KZRCT8MZ6YB"))try{let m=await a.getPageSummary({browserContext:u,currentStep:r.description,screenshot:n,type:r.type},{logger:i,loggerTags:de(i),abortSignal:c});i.info(m,"Got AI summaries");let p=new Set;for(let h of m.relevantSections){let f=Math.min(h.startId,h.endId),y=Math.max(h.startId,h.endId);for(let T=f;T<=y;T++)p.add(T.toString())}s=s.pruneUsingRelevantIds(p),u=s.serialize();let g=Tr(u);i.info({newTokens:g,oldTokens:d},"Filtered page using AI summary"),d=g}catch(m){i.warn({err:m},"Error filtering page using AI summary, continuing...")}return u}async function $L({type:r,chunks:e,description:t,fixtures:n,tree:o}){let{generator:i,signal:a,logger:l}=n,c=await i.rankChunksWithAi({chunks:e,description:t,type:r,softTokenLimit:4e4,hardTokenLimit:8e4},{abortSignal:a,logger:l,loggerTags:de(l)}),s=[];return e.forEach((d,m)=>{c.indices.includes(m)&&(s=s.concat(d.ids))}),o.pruneUsingRelevantIds(new Set(s))}async function qL(r){let{description:e,fixtures:t,tree:n}=r,{generator:o,logger:i,signal:a}=t;if(!e.trim())throw new Error("Empty description passed to page filtering");let l=await o.getExtractedKeywords({goal:e},{logger:i,loggerTags:de(i),abortSignal:a});i.info({keywordsResult:l},"Got keywords for page filtering");for(let c of l.keywords){let s=r.chunks.filter(p=>p.content.toLowerCase().includes(c.toLowerCase()));if(!s.length||s.reduce((p,g)=>p+g.tokenLength,0)>r.tokenLimit&&s.length>1)continue;let d=s.flatMap(p=>p.ids);return n.pruneUsingRelevantIds(new Set(d))}throw new Error("No keywords were unique enough for page filtering")}async function KL(r){let{description:e,fixtures:t,chunkResult:n,tokenLimit:o,tree:i}=r,{generator:a,logger:l,signal:c}=t,s=await a.rankChunksWithRag({description:e,chunks:n.chunks,tokenLimit:o},{abortSignal:c,logger:l,loggerTags:de(l)});if(s.ids.length===0)throw new Error("RAG returned no important ids");return i.pruneUsingRelevantIds(new Set(s.ids.map(d=>`${d}`)))}async function Xd(r,e){if(!r.description)throw new A("UserConfigurationError","Cannot locate element with empty description");return cr({action:async()=>YL(r,e),frameConfig:r.iframeUrl?{type:"url",url:r.iframeUrl}:void 0,browser:e.browser,logger:r.logger})}async function YL(r,e){let{disableCache:t,testContext:n,filterByViewport:o,skipWait:i,source:a,memory:l,aiPageFiltering:c,logger:s,allowNotActionableNodesOverride:u}=r,{ctx:d,orgId:m,browser:p,localCodeEvalTools:g,generator:h,abortSignal:f}=e,y=r.description,T=r.useMemory&&!t;n&&(y=await ou({orgId:m,s:y,context:n,localTools:g,signal:f,logger:s})),a&&(y=JL(y,a));let{serializedTree:v,tree:R}=await Yr(p,{allowNotActionableNodesOverride:u,filterByViewport:o,abortSignal:f,skipWait:i,logger:s}),b,x=Date.now(),N;for(;!b&&Date.now()-x<3e3;){f.throwIfAborted();try{b=await p.screenshot({clearHighlights:!0,respectActiveFrame:!0,retries:2})}catch(Re){N=Re}}if(!b)throw new A("ActionFailureError",`Failed to take screenshot of page to locate element. The page may be unresponsive, or your machine might be severely resource constrained. Error: ${N?.message}`);let k=v,$=!1,ee=`data:image/jpeg;base64,${b.toString("base64")}`;k=await Mn({type:"locator",description:y,screenshot:ee,serializedTree:v,options:{aiPageFiltering:c},tree:R,fixtures:{generator:h,signal:f,logger:s,orgId:m}}),k!==v&&($=!0);let oe=await h.getElementLocation({browserState:k,goal:y,screenshot:ee,source:a,memory:T?l:void 0},{disableCache:t,abortSignal:f,loggerTags:de(s),useMemory:T});s.debug({usedRag:$,result:oe},"Got locator result");let lt=oe.id>0;if(d?.details?.push({type:"AI_LOCATION",matched:lt,pageState:k,ragUsed:$,thoughts:oe.thoughts}),!lt)throw new ro(`Could not find any relevant element: ${oe.thoughts}`,oe.updatedMemory?{type:"GCS_TRACES",traces:oe.updatedMemory}:void 0);let{resolution:M,target:V,frameConfig:te}=await p.createTargetFromA11yId({id:oe.id,requirements:oe.requirements,additionalElements:oe.additionalElements,description:y,targetSource:"AI",logger:s});if(M.a11yNode?.properties?.hidden&&M.a11yNode?.properties?.hidden!=="false")throw new A("ActionFailureError",`Momentic's AI found a relevant element to interact with, but it is explicitly marked with an 'aria-hidden' attribute. Please remove this attribute or adjust the element description to locate a different element. Element chosen: ${M.displayString}`);return T&&(oe.updatedMemory?V.memory={type:"GCS_TRACES",traces:oe.updatedMemory}:l&&(V.memory=l)),{thoughts:oe.thoughts,target:V,resolution:M,frameConfig:te,screenshot:ee}}var XL=["Element exactly matching the description below. Interpret the description narrowly and do not assume there are any typos or errors. Err on the side of returning -1 unless there is a perfect match. Description:","Element closely matching the description below. Interpret the description narrowly and do not return elements that are merely loosely related. Description:","Element matching the description below. This element is being located as part of a negative check step (i.e. we are trying to verify the element does not exist). Therefore, interpret the description narrowly, do not assume there are typos, and err on the side of returning -1 unless there is a perfect match. Description:"],Sb="<select> element:",Eb="text input or contenteditable element:",yb="Element matching the description below. It is possible the element is hidden or doesn't exist. Interpret the description narrowly and do not assume there are typos. Return -1 unless there is an straightforward match. Description:",Tb="Element matching the description below. This element is being located as part of a check step (i.e. we are trying to verify certain properties about the element). Interpret the description narrowly and do not return elements that are merely loosely related. Description:",Yd=[Sb,Eb,yb,Tb,...XL];function bb(r,e){if(r===e)return!0;for(let t of Yd){if(!r.startsWith(t))continue;let n=r.slice(t.length).trim();if(Yd.some(o=>e.startsWith(o)&&e.slice(o.length).trim()===n)||n===e.trim())return!0}return!!Yd.some(t=>e.startsWith(t)&&e.slice(t.length).trim()===r.trim())}function JL(r,e){if(!r||!e)return r;switch(e){case"SELECT_OPTION":return`${Sb} ${r}`;case"TYPE":return`${Eb} ${r}`;case"NEGATED_ELEMENT_VISIBLE_CHECK":return`${yb}
4009
- ${r}`;case"ELEMENT_CHECK":return`${Tb}
4010
- ${r}`;default:return r}}var QL=15;async function hl({command:r,aiPageFiltering:e,logger:t,fixtures:n,source:o,useMemory:i,maxRetries:a=QL}){if(!r.assertion.trim())throw new A("ActionFailureError","Assertion command is missing the assertion content");let{browser:l}=n,c=r.timeout?r.timeout*1e3:l.smartWaitingTimeout,s=Ks(c),u=0,d=Date.now(),m,p,g;try{await cr({action:()=>l.clearHighlights(),frameConfig:r.iframeUrl?{type:"url",url:r.iframeUrl}:void 0,browser:l,logger:t})}catch(f){t.warn({err:f},"Failed to clear highlights before AI check, continuing...")}let h;for(;u<a&&(!h||h-d<c);){n.abortSignal.throwIfAborted(),u!==0&&await q(s,n.abortSignal),h=Date.now();try{if(m=await cr({action:async()=>{let y=await vb(l,t,n.abortSignal);return p&&p.serializedTree===y.serializedTree&&p.screenshotBuff.equals(y.screenshotBuff)?m:(p=y,Ab({command:r,state:y,fixtures:n,useMemory:i,useConsensus:!1,highlightElementsOnFailure:!1,attemptNumber:u,aiPageFiltering:e,logger:t,source:o}))},frameConfig:r.iframeUrl?{type:"url",url:r.iframeUrl}:void 0,logger:t,browser:l}),m?.updatedMemory&&Ws(r,m.updatedMemory,t),m?.success)break;throw m?.thoughts?new A("AssertionFailureError",m.thoughts):new A("InternalPlatformError","No thoughts were provided for AI assertion failure")}catch(f){n.abortSignal.throwIfAborted(),g=f instanceof Error?f:new Error(`${f}`),t.info({err:f},`AI check assert attempt ${u} failed, retrying...`)}finally{u++}}if(!m?.success)try{m=await cr({action:async()=>Ab({command:r,state:await vb(l,t,n.abortSignal),fixtures:n,useMemory:i,useConsensus:!0,highlightElementsOnFailure:!0,attemptNumber:u,aiPageFiltering:e,logger:t}),frameConfig:r.iframeUrl?{type:"url",url:r.iframeUrl}:void 0,logger:t,browser:l})}catch(f){n.abortSignal.throwIfAborted(),g=f instanceof Error?f:new Error(`${f}`)}finally{u++}if(!m?.success){let f=`AI check still failing after ${u} attempts.`;throw g&&(f+=` Latest result: ${g.message}`),new A("AssertionFailureError",f)}return{...m,succeedImmediately:!1,urlAfterCommand:l.url()}}async function vb(r,e,t){let[n,o]=await Promise.all([Yr(r,{abortSignal:t,skipWait:!0,skipWaitForPageLoad:!0,logger:e}),r.screenshot({retries:1,respectActiveFrame:!0})]);return{...n,screenshotBuff:o}}async function Ab({command:r,state:e,fixtures:t,useConsensus:n,useMemory:o,highlightElementsOnFailure:i,aiPageFiltering:a,attemptNumber:l,source:c,logger:s}){let{browser:u,generator:d,abortSignal:m}=t,p={type:"ASSERTION"},{serializedTree:g,tree:h}=e,f=e.screenshotBuff,y=f.toString("base64"),T=u.url(),v=r.contextChoice??"MULTIMODAL",R=g;v!=="VISION_ONLY"&&(R=await Mn({type:"assertion",serializedTree:g,tree:h,description:r.assertion,screenshot:y,options:{aiPageFiltering:a},fixtures:{generator:d,signal:m,logger:s,orgId:t.orgId}}),R!==g&&(p.ragUsed=!0),p.pageState=R);let b={goal:r.assertion,url:T,memory:o?r.cache?.memory:void 0,browserState:R,screenshot:y,contextChoice:v,source:c},N=await(v==="VISION_ONLY"?(k,$)=>d.getVisualAssertionResult(k,$):(k,$)=>d.getAssertionResult(k,$))(b,{useConsensus:n,attemptNumber:l,useMemory:o,disableCache:!!r.disableCache,abortSignal:m,logger:s,loggerTags:de(s)});return(N.result||i)&&N.relevantElements&&(p.relevantElementsSerialized=N.relevantElements.map(k=>u.getSerializedFormFromA11yId(k)).filter(k=>!!k),await ZL(N.relevantElements,u,s)),{success:N.result,thoughts:N.thoughts,afterScreenshotOverride:f,updatedMemory:o?N.updatedMemory:void 0}}async function ZL(r,e,t){let n=Date.now();for(let o of r){if(Date.now()-n>2e3){t.debug("Highlighting relevant elements took over 2s, aborting...");return}try{let i=new AbortController;await B(e.highlightA11yId(o),{milliseconds:1e3,fallback:()=>{throw i.abort(),new Error("Timed out waiting for highlighting to complete")}})}catch(i){t.debug({err:i},"Failed to highlight relevant element after assertion, continuing...");return}}}import{cloneDeep as eN}from"lodash-es";async function Rb(r){let{command:e,timeoutMs:t,fixtures:n}=r,{logger:o,abortSignal:i}=n,a=op(e.cache)?e.cache:void 0,l=Date.now(),c=0,s,u=500,d=!1;for(;c<2||Date.now()-l<t;){c++,c>1&&await q(u,i),i?.throwIfAborted();let{result:m,updatedCache:p,elementWasFound:g}=await wb({cacheToUse:a,params:r});if(s=m,d=g,m.success){p?.target&&Tn({cmd:e,key:"target",newTarget:p?.target,logger:o});break}p?.target?.memory&&a?.target&&(a.target.memory=p.target.memory),u=Math.min(u*2,1e4)}if(!s)throw new A("InternalPlatformError",`Failed to evaluate manual element assertion in ${t}ms.`);if(i?.throwIfAborted(),!s.success&&a?.target&&da(a.target)){let m=a?.target?.memory?{target:{id:-1,memory:a.target.memory}}:void 0,{result:p,updatedCache:g}=await wb({cacheToUse:m,params:r});s=p,p.success&&g?.target&&Tn({cmd:e,key:"target",newTarget:g.target,logger:o})}return s.success&&a?.target&&!d&&Jm(a.target),s}async function wb({cacheToUse:r,params:e}){let{command:t,disableCache:n,fixtures:o,tracer:i,targetingWrapper:a}=e,{logger:l}=o;if(t.target&&!Rr(t.target))throw new Error("Element assertion with x/y is not supported yet");let c=rN(t.assertion),s,u=!1,d=eN(r);try{let{elementInteractedDisplayString:m,result:p,thoughts:g}=await a({ctx:o.ctx,tracer:i,command:t,target:t.target,cache:d?.target,action:async h=>tN(h.locator,e),options:{...t,allowNotActionableNodesOverride:!0,disableCache:n,memory:d?.target?.memory,disableGlobalLocatorRedirect:!0,source:ni(t),targetName:"target"}});return s={success:p.success,data:p.data,err:p.err,elementInteractedDisplayString:m,thoughts:g},u=!0,p.success||(l.warn({aiThoughts:g,elementString:m,err:p.err},"Element check found an element but failed"),s={...p,thoughts:g}),{result:s,elementWasFound:u,updatedCache:d}}catch(m){if(c)return s={success:!0,thoughts:`The element described does not exist on the page: ${m.message}`,err:void 0,data:void 0},{result:s,elementWasFound:u,updatedCache:d};if(!(m instanceof A)||m.reason!="ActionFailureError")throw m;return s={success:!1,err:m,data:void 0,thoughts:void 0},l.warn({err:m},"Element check did not find an element and failed"),{result:s,elementWasFound:u,updatedCache:d}}}async function tN(r,{command:e,fixtures:t}){let n=e.assertion;await t.browser.highlight(r);let o=!0,i,a;switch(n.type){case"ELEMENT_CONTENT":{let c=await r.textContent()??"";if(a={elementTextContent:ht(c,500,!0)},!fl(c,n.value,n.operation,!!n.negated)){let s=n.negated?bn[n.operation]:vn[n.operation];o=!1,i=new A("AssertionFailureError",`The content ${s} '${n.value}': ${c}`)}break}case"ELEMENT_ATTRIBUTE":{a={elementOuterHtml:ht(await r.evaluate(s=>s.cloneNode(!1).outerHTML),500,!0)};let c;try{c=await r.getAttribute(n.attr,{timeout:3e3})??""}catch(s){i=new A("AssertionFailureError",`The element does not have an attribute named ${n.attr}: ${s}`),o=!1;break}if(!fl(c,n.value,n.operation,!!n.negated)){let s=n.negated?bn[n.operation]:vn[n.operation];o=!1,n.operation==="EXISTS"?i=new A("AssertionFailureError",`The attribute ${n.attr} ${s}`):i=new A("AssertionFailureError",`The attribute ${n.attr} ${s} '${n.value}': ${c}`)}break}case"ELEMENT_EXISTENCE":{switch(n.condition){case"VISIBLE":{o=await r.evaluate(async(s,u)=>{let d=Date.now();for(;Date.now()-d<u;){await new Promise(p=>setTimeout(p,250));let m=s.getBoundingClientRect();if(!(m.width===0||m.height===0)&&window.getComputedStyle(s).visibility!=="hidden"&&window.getComputedStyle(s).display!=="none")return!0}return!1},xr*1e3);break}case"EDITABLE":{o=await r.isEditable({timeout:xr*1e3});break}case"EXISTS":{o=!0;break}case"ENABLED":{o=await r.isEnabled({timeout:xr*1e3});break}case"FOCUSED":{o=await r.evaluate(s=>s===document.activeElement);break}default:return(s=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(n.condition)}if(o=n.negated?!o:o,!o){let c=n.negated?hy[n.condition]:fy[n.condition];i=new A("AssertionFailureError",`The element ${c}`)}break}case"ELEMENT_NAME":{let c=await r.evaluate(s=>s.tagName);if(!fl(c,n.value,n.operation,!!n.negated)){let s=n.negated?bn[n.operation]:vn[n.operation];o=!1,i=new A("AssertionFailureError",`The element tag name ${s} '${n.value}': ${c}`)}break}case"ELEMENT_STYLE":{let c=await r.evaluate((s,u)=>window.getComputedStyle(s).getPropertyValue(u),n.property);if(!fl(c,n.value,n.operation,!!n.negated)){let s=n.negated?bn[n.operation]:vn[n.operation];o=!1,n.operation==="EXISTS"?i=new A("AssertionFailureError",`The style property ${n.property} ${s}`):i=new A("AssertionFailureError",`The style property ${n.property} ${s} '${n.value}': ${c}`)}break}default:return(c=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(n)}return{success:o,data:a,err:i}}function fl(r,e,t,n){let o;switch(t){case"CONTAINS":{o=r.includes(e);break}case"EQUALS":{o=r.trim()===e.trim();break}case"STARTS_WITH":{o=r.trim().startsWith(e);break}case"EXISTS":{o=r.trim().length>0;break}default:return(a=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(t)}return n?!o:o}function rN(r){return r.type==="ELEMENT_EXISTENCE"&&r.negated&&(r.condition==="EXISTS"||r.condition==="VISIBLE")}function Cb(r){return r.type==="ELEMENT_EXISTENCE"&&r.negated&&r.condition==="EXISTS"}import{Jimp as nN}from"jimp";async function qi(r,e){let t=await r.screenshot(e),n=await nN.fromBuffer(t);return{buffer:t,width:Math.ceil(n.bitmap.width??0),height:Math.ceil(n.bitmap.height??0)}}import{Jimp as xb}from"jimp";import Jd from"jpeg-js";import oN from"pixelmatch";async function _b({ctx:r,tracer:e,command:t,disableCache:n,browser:o,targetingWrapper:i,logger:a,screenshotStorage:l}){if(t.target&&!Rr(t.target))throw new Error("Visual Diff with x/y is not supported yet");await o.waitForDOMStability({logger:a});let c={clearHighlights:!0,hideCaret:!0},s;t.target?.elementDescriptor?s=(await i({ctx:r,tracer:e,command:t,target:t.target,cache:t.cache?.target,action:async ee=>qi(o,{locator:ee.locator,...c}),options:{...t,disableCache:n,disableGlobalLocatorRedirect:!0,memory:t.cache?.target?.memory,targetName:"target"}})).result:s=await qi(o,c);let u=await l.prepareGoldenScreenshotForComparison(a,t,s);if((s.height!==u.height||s.width!==u.width)&&a.warn({currHeight:s.height,currWidth:s.width,savedHeight:u.height,savedWidth:u.width},"Mismatched before and after visual diff screenshot sizes"),Math.abs(s.height-u.height)>10||Math.abs(s.width-u.width)>10){let De=`${s.width}x${s.height}`,ee=`${u.width}x${u.height}`;return{fail:!0,thoughts:`Current screenshot (${De}) does not match saved screenshot dimensions (${ee}) - did you change the size of the target or the viewport?`,beforeScreenshotOverride:u.buffer,afterScreenshotOverride:s.buffer,succeedImmediately:!1,urlAfterCommand:o.url()}}let d=await xb.fromBuffer(s.buffer),m={width:s.width,height:s.height},p=await xb.fromBuffer(u.buffer),g={width:u.width,height:u.height},h,f=m.width*m.height,y=g.width*g.height,T=Math.abs(m.height-g.height),v=Math.abs(m.width-g.width);if(f>y){let De=d.cover({w:g.width,h:g.height});s.buffer=await De.getBuffer("image/jpeg"),h="current",s.width=g.width,s.height=g.height}else if(y>f){let De=p.cover({w:m.width,h:m.height});u.buffer=await De.getBuffer("image/jpeg"),h="saved"}let R={data:Buffer.alloc(s.width*s.height*4),width:s.width,height:s.height},b=t.threshold??.1,N=oN(Jd.decode(u.buffer).data,Jd.decode(s.buffer).data,R.data,s.width,s.height,{threshold:b,diffColorAlt:[0,255,0]})/(s.width*s.height)*100,k=N>b*100,$=`Visual diff of ${N.toFixed(2)}% detected, which is ${k?"over":"under"} the threshold of ${b*100}%.`;if(h&&($+=` The ${h} screenshot was cropped since it was taller by ${T} pixels and wider by ${v} pixels.`),k)throw new A("ActionFailureError",$);return{fail:k,thoughts:$,beforeScreenshotOverride:s.buffer,afterScreenshotOverride:Jd.encode(R,75).data,succeedImmediately:!1,urlAfterCommand:o.url()}}var iN=3e4;async function Mb({command:r,logger:e,baseUrl:t,fetchImplementation:n=fetch}){let o=r.timeout??iN/1e3,i=Object.fromEntries(Object.entries(r.headers||{}).filter(([p,g])=>p&&g)),a=new URLSearchParams;Object.entries(r.params||{}).filter(([p,g])=>p&&g).forEach(([p,g])=>{a.append(p,g)});let l=a.toString(),c;if(bo(r.url)&&(c=r.url),t&&vo(r.url,t)&&(c=new URL(r.url,t).toString()),!c)throw new A("ActionFailureError",`Invalid URL: ${r.url}`);e.info({url:c,searchParams:l,headers:i,body:r.body,method:r.method},"Making HTTP request");let u=await B((async()=>{let p=l?`${c}?${l}`:c;try{return await n(p,{headers:i,method:r.method,body:r.body})}catch(g){throw e.error({err:g},"Failed to make HTTP request"),new Error(`Failed to make HTTP request: ${g}`)}})(),{milliseconds:o*1e3,fallback:()=>{throw new A("ActionFailureError",`Fetch request timed out after ${o} seconds`)}});if(!u.ok){let p;try{p=await u.text()}catch(g){p=`Failed to read response body: ${g}`}throw new A("ActionFailureError",`Fetch request failed with status ${u.status}: ${p}`)}let d={};u.headers.forEach((p,g)=>{d[g]=p});let m={status:u.status,headers:d};if(u.headers.get("content-type")?.includes("json"))try{m.json=await u.json()}catch{}else u.headers.get("content-type")?.includes("text")&&(m.text=await u.text());return m}var aN=5e3;async function Ob({timeout:r=xr,...e}){let t=Date.now(),n=r*1e3,o=n+1e4,i,a=0,l=500;for(;a-t<n;){if(Date.now()-t>o){e.logger.warn("Exceeded max system timeout for page assertion, exiting...");break}e.signal.throwIfAborted();let c=Date.now();i=await Ib(e),a=Date.now();let s=a-c;if(s>1e3&&e.logger.warn({pageAssertDuration:s},"Page assertion took longer than expected"),!i.success)await q(l,e.signal),l=Math.min(Math.floor(l*1.5),aN);else return i}return i=await Ib(e),i}async function Ib({assertion:r,browser:e,autoExpandIframes:t}){switch(r.type){case"CONTENT":{let o,i=!1,a;try{let l;if(t){let c=await e.evaluateFunctionInAllFrames(Pb,{value:r.value,negated:!!r.negated,returnHtml:!1});i=r.negated?c.every(s=>s.evaluation):c.some(s=>s.evaluation),l=c.find(s=>s.pageHtml)?.pageHtml}else({evaluation:i,pageHtml:l}=await e.evaluateFunctionInPage(Pb,{value:r.value,negated:!!r.negated,returnHtml:!0},"checking page content"));if(!i){let c=r.negated?bn.CONTAINS:vn.CONTAINS;a=new A("AssertionFailureError",`The page ${c} '${r.value}'.`),o=l}}catch(l){a=new A("AssertionFailureError",`Failed to evaluate page content assertion: ${l instanceof Error?l.message:`${l}`}`)}return{success:i,err:a,data:i||!o?void 0:{pageContent:o}}}default:return(o=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(r.type)}}function Pb({value:r,negated:e,returnHtml:t}){let n=document.documentElement.outerHTML,o=n.includes(r)===!e;return n.length>1e4&&(n=n.slice(0,1e4)+"...TRUNCATED"),{evaluation:o,pageHtml:!o&&t?n:void 0}}var sN=3e4;async function Lb({command:r,logger:e,baseUrl:t,fetchImplementation:n=fetch}){let o=r.timeout??sN/1e3,i=new AbortController,a=Object.fromEntries(Object.entries(r.headers||{}).filter(([d,m])=>d&&m));a["Content-Type"]="application/json";let l;if(bo(r.url)&&(l=r.url),t&&vo(r.url,t)&&(l=new URL(r.url,t).toString()),!l)throw new A("ActionFailureError",`Invalid URL: ${r.url}`);let s=await B((async()=>{try{return await n(l,{headers:a,method:"POST",body:JSON.stringify({query:r.query,variables:r.variables?JSON.parse(r.variables):void 0}),signal:i.signal})}catch(d){e.error({err:d},"Failed to make HTTP request")}})(),{milliseconds:o*1e3});if(!s)throw new A("ActionFailureError",`GraphQL request timed out after ${o} seconds`);if(!s.ok){let d,m=await s.text();try{d=JSON.parse(m)}catch{throw new A("ActionFailureError",`GraphQL request failed with status ${s.status}: ${m}`)}throw d?.errors?.length&&d?.errors[0]?.message?new A("ActionFailureError",`GraphQL request failed with status ${s.status}: ${d.errors[0].message}`):new A("ActionFailureError",`GraphQL request failed with status ${s.status}: ${m}`)}let u={};return s.headers.forEach((d,m)=>{u[m]=d}),{status:s.status,headers:u,json:await s.json()}}var Sl=class{flagStore;orgId;options;storage;localCodeEvalTools;uploadedFileStorage;visualDiffScreenshotStorage;browser;generator;executeAbortController=new AbortController;logger;recordAbortController=null;registeredListeners={};recordedRequests={};constructor({browser:e,generator:t,logger:n,flagStore:o,storage:i,orgId:a,localCodeEvalTools:l,uploadedFileStorage:c,visualDiffScreenshotStorage:s,options:u}){this.orgId=a,this.options=u,this.browser=e,this.browser.registerAbortSignal(this.executeAbortController.signal),this.storage=i,this.uploadedFileStorage=c,this.visualDiffScreenshotStorage=s,this.localCodeEvalTools=l,this.generator=t,this.logger=n,this.flagStore=o}setOpen(){this.executeAbortController=new AbortController,this.browser.registerAbortSignal(this.executeAbortController.signal)}setClosed(){this.executeAbortController.abort()}throwIfClosed(){this.executeAbortController.signal.throwIfAborted()}get closed(){return this.executeAbortController.signal.aborted}async evaluateAiAction({goal:e,startingScreenshot:t,history:n,disableCache:o,langfuseSessionId:i,lastError:a,logger:l=this.logger}){let[c,s]=await Promise.all([Yr(this.browser,{abortSignal:this.executeAbortController.signal,skipWait:!0,skipWaitForPageLoad:!0,logger:l}),this.browser.screenshot({retries:1,clearHighlights:!0})]),u=`data:image/jpeg;base64,${s.toString("base64")}`,d=await Mn({type:"ai-action",description:e,screenshot:u,serializedTree:c.serializedTree,tree:c.tree,options:{aiPageFiltering:!!this.options?.aiPageFiltering},fixtures:{generator:this.generator,signal:this.executeAbortController.signal,logger:l,orgId:this.orgId}}),m={url:this.browser.url(),browserState:d,startingScreenshot:t,history:n,goal:e,screenshot:u,lastError:a};return await this.generator.getMultiturnAiActionEvaluation(m,{disableCache:o,abortSignal:this.executeAbortController.signal,loggerTags:{...de(l)},langfuseSessionId:i})}async promptToCommand({goal:e,startingScreenshot:t,history:n,actionHint:o,disableCache:i,logger:a=this.logger,langfuseSessionId:l}){let c=this.browser.url(),[s,u]=await Promise.all([Yr(this.browser,{abortSignal:this.executeAbortController.signal,skipWait:!0,skipWaitForPageLoad:!0,logger:a}),this.browser.screenshot({retries:1,clearHighlights:!0})]),d=`data:image/jpeg;base64,${u.toString("base64")}`,m=await Mn({type:"ai-action",description:e,screenshot:d,serializedTree:s.serializedTree,tree:s.tree,options:{aiPageFiltering:!!this.options?.aiPageFiltering},fixtures:{generator:this.generator,signal:this.executeAbortController.signal,logger:a,orgId:this.orgId}}),p={url:c,browserState:m,startingScreenshot:t,history:n,goal:e,actionHint:o,screenshot:d};try{return await this.generator.getMultiturnAiActionCommand(p,{disableCache:i,abortSignal:this.executeAbortController.signal,loggerTags:{...de(a)},langfuseSessionId:l})}catch(g){throw new A("InternalWebAgentError",`Error generating command: ${g instanceof Error?g.message:g}`,{errOptions:{cause:g}})}}async getBrowserState(e){return Yr(this.browser,e)}async locateElement(e){return await Xd({...e,aiPageFiltering:!!this.options?.aiPageFiltering},this.getControllerFixtures())}async locateElementWithSelector(e,t){return cr({action:async()=>{let n=await this.browser.resolveHardcodedCssSelector({ctx:null,selector:e,timeoutMs:2e3,logger:this.logger});return{thoughts:"Located element with selector",target:{id:-1,selector:e,targetSource:"USER_CSS_SELECTOR",targetUpdateTime:new Date().toUTCString()},resolution:n}},frameConfig:t?{type:"url",url:t}:void 0,browser:this.browser,logger:this.logger})}getControllerFixtures(e){return{ctx:e??null,browser:this.browser,generator:this.generator,logger:this.logger,orgId:this.orgId,flagStore:this.flagStore,storage:this.storage,localCodeEvalTools:this.localCodeEvalTools,abortSignal:this.executeAbortController.signal}}shouldUseMemory(){return this.options?.useMemory??(this.orgId==="org_01HMSCJQBCCG51M2ZF65YC5B8W"||this.orgId==="org_01HMJTX4GT1KG94KZRCT8MZ6YB")}async wrapMultiElementTargetingCommand({ctx:e,tracer:t,command:n,targetNames:o,descriptions:i,caches:a,action:l,options:c,retriesWithAI:s=1}){let u=[];for(let d=0;d<i.length;d++){let m=i[d],p=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:m,cache:a[d],action:async g=>g,options:{...c,targetName:o[d]}});u.push(p)}try{let d=await l(...u.map(g=>g.result)),m=g=>g==="fromTarget"?"From Target":g==="toTarget"?"To Target":"Target",p=u.map((g,h)=>g.thoughts?`${m(o[h])}: ${g.thoughts}`:void 0).filter(g=>!!g).join(" -------------- ")||void 0;return{result:d,elementInteractedDisplayStrings:u.map(g=>g.elementInteractedDisplayString),thoughts:p}}catch(d){if(this.throwIfClosed(),s>0)return this.logger.warn({err:d},"Failed to execute action with multiple cached targets, retrying with AI"),this.wrapMultiElementTargetingCommand({ctx:e,tracer:t,command:n,targetNames:o,descriptions:i,caches:i.map(()=>{}),action:l,options:c,retriesWithAI:s-1});throw new A("ActionFailureError",d.message,{errOptions:{cause:d}})}}async wrapElementTargetingCommand(e){let t=this.logger.child({commandId:e.command.id}),n;for(let o=0;o<2;o++)try{return await cr({action:()=>this.wrapElementTargetingCommandHelper({...e,originalCache:e.originalCache??e.cache}),frameConfig:e.options.iframeUrl?{type:"url",url:e.options.iframeUrl}:void 0,browser:this.browser,logger:t})}catch(i){if(n=i,this.browser.userBrowserSettings.visualActions&&Bc(i)){t.warn({err:i},"Invalid mpath error, retrying element targeting command");continue}if(!this.browser.userBrowserSettings.visualActions&&(Gc(i)||zc(i))){t.warn({err:i},"Invalid momentic id error, retrying element targeting command");continue}if(Hc(i)){t.warn({err:i},"Invalid backend node id error, retrying element targeting command");continue}if(i instanceof Zt&&i.retryableWithAI){t.warn({err:i},"Element cache disqualification error, retrying element targeting command");continue}throw i}throw n instanceof A?n:new A("ActionFailureError",n?.message??"An unknown error occurred during element targeting")}async wrapHardcodedCssTargetingCommandHelper({ctx:e,target:t,action:n,options:o,command:i}){let a=this.logger.child({commandId:i.id}),{targetName:l}=o;if(t.type!=="description")throw new A("ActionFailureError","Cannot use selector with non-description target");let c,s=Date.now(),u=Date.now();for(;Date.now()-u<this.browser.smartWaitingTimeout;){s=Date.now();try{let d=await this.browser.resolveHardcodedCssSelector({ctx:e,selector:t.elementDescriptor,targetName:l,logger:a});return{result:await n({locator:d.locator}),elementInteractedDisplayString:d.displayString}}catch(d){if(d.name==="AbortError")throw d;c=d,a.warn({err:d},"Failed to action on hardcoded css selector"),Date.now()-s<500&&await q(500)}}throw c}async wrapElementTargetingCommandHelper(e){let{ctx:t,tracer:n,target:o,originalCache:i,action:a,options:l,command:c}=e,{disableCache:s,useSelector:u,targetName:d,targetHealingInProgress:m,source:p}=l,g=this.logger.child({commandId:c.id}),h=this.shouldUseMemory(),f=l.retriesWithAI??1,y=!1,T=Nb(e.cache);if((!T||s)&&!Yl(o))throw new A("ActionFailureError","Cannot target element with no cached data or element descriptor");if(u)return this.wrapHardcodedCssTargetingCommandHelper(e);s&&(g.info("Cache explicitly disabled for this step"),y=!0,T=void 0),T&&this.browser.userBrowserSettings.disableSecondaryCacheResolution&&T.targetSource==="HEURISTIC_HEALED"&&(y=!0,T=void 0),T?.inputDescription&&!bb(o.elementDescriptor,T.inputDescription)&&(g.warn({old:T.inputDescription,new:o.elementDescriptor},"Target cache was generated with a different description, clearing it automatically"),y=!0,T=void 0);let v=b=>!!b&&da(b),R=!0;if(!v(T)){R=!1,g.info({description:o.elementDescriptor,targetHealingInProgress:m,cacheBustedBeforeAction:y,memory:l.memory,useMemory:h},"Prompting AI for an updated element location"),y&&await q(this.browser.smartWaitingTimeout,this.executeAbortController.signal),f--;let b;try{b=await Xd({description:o.elementDescriptor,disableCache:!!l.disableCache,iframeUrl:l.iframeUrl,source:p,useMemory:h,memory:h?l.memory:void 0,aiPageFiltering:!!this.options?.aiPageFiltering,allowNotActionableNodesOverride:l.allowNotActionableNodesOverride,logger:g},this.getControllerFixtures(t))}catch(k){if(k instanceof ro&&k.updatedLocatorMemory){let $={id:-1,...i,memory:k.updatedLocatorMemory};Tn({cmd:c,key:d,newTarget:$,logger:g})}throw new A("ActionFailureError",k.message)}b.frameConfig&&this.browser.setActiveFrameConfig(b.frameConfig);let x=l.disableGlobalLocatorRedirect?{locator:b.resolution.locator}:await this.attemptLocatorRedirect(b.resolution.locator,g),N=await a(x);return Tn({cmd:c,key:d,newTarget:b.target,logger:g}),m&&(n.recordTargetAutoHeal({healType:"AI"}),b.target.targetSource="AI_HEALED",b.target.targetUpdateTime=new Date().toUTCString(),b.target.targetUpdateLoggerTags=de(g)),{result:N,elementInteractedDisplayString:b.resolution.displayString,thoughts:b.thoughts}}try{let b=await this.browser.resolveTarget(t,T,{allowNotActionableNodesOverride:l.allowNotActionableNodesOverride,targetName:d,logger:g,signal:this.executeAbortController.signal});(this.browser.userBrowserSettings.visualActions||this.browser.userBrowserSettings.globalLocatorRedirect)&&await this.browser.scrollIntoViewIfNeeded(b.locator);let x=l.disableGlobalLocatorRedirect?{locator:b.locator}:await this.attemptLocatorRedirect(b.locator,g),N=await a(x);if(xt.increment("cache_target_resolution_v2",1,["outcome:hit","platform:web",`hasRequirements:${!!T.requirements}`,`hasAdditionalElements:${!!T.additionalElements}`]),Tn({cmd:c,key:d,newTarget:T,logger:g}),R){let k=b.decisions.filter($=>$.matched);if(k.length!==1)g.warn({decisions:b.decisions},"Expected exactly 1 matching method for element location, got more or less");else{let $=k[0].type;n.recordTargetAutoHeal({healType:$})}}return{result:N,elementInteractedDisplayString:b.displayString}}catch(b){this.throwIfClosed(),xt.increment("cache_target_resolution_v2",1,["outcome:miss","platform:web",`hasRequirements:${!!T.requirements}`,`hasAdditionalElements:${!!T.additionalElements}`]);let x=!1;if((b instanceof Zt||Bc(b)||Gc(b)||Hc(b)||Gg(b)||zc(b))&&(x=!0),b instanceof A&&!x)throw g.error({err:b},"Failed to execute action with cached target (fatal)"),b;if(f>0&&o){g.info({err:b},"Failed to execute action with cached target, retrying with AI");let N;return T.memory&&Qm(T.memory)&&(N=T.memory),this.wrapElementTargetingCommand({ctx:t,tracer:n,command:c,target:o,cache:void 0,originalCache:i,action:a,options:{...l,memory:N,retriesWithAI:f,targetHealingInProgress:!0}})}throw new A("ActionFailureError",b.message,{errOptions:{cause:b}})}}async attemptLocatorRedirect(e,t){return this.browser.userBrowserSettings.globalLocatorRedirect?this.browser.performTargetRedirection(e,t):{locator:e}}async screenshotWithDimensions(e){return qi(this.browser,e)}async executePresetCommand(e,t,n,o,i){this.options?.slowMoMs&&await q(this.options.slowMoMs);let a=await this.browser.getOpenPages(),l=this.browser.url(),c;try{c=await this.resolveCommandTemplateStrings(n,o)}catch(s){throw this.throwIfClosed(),new A("ActionFailureError",`Failed to substitute template strings in command: ${s.message}`,{errOptions:{cause:s}})}try{let s=await this.executePresetCommandHelper(e,t,n,o,i);return this.browser.userBrowserSettings.visualActions&&lp(n)?await this.browser.waitForDOMStability({timeout:2e3}):!this.browser.userBrowserSettings.visualActions&&["PRESS","TYPE"].includes(n.type)&&await this.browser.waitForDOMStability({timeout:1e3}),this.options?.autoFollowNewTabs&&await mb({beforeUrl:l,command:n,beforePages:a.map(u=>u.url),browser:this.browser,logger:this.logger}),s}catch(s){throw s.name!=="AbortError"&&this.logger.error({err:s},"Error thrown in action controller"),s}finally{Za(n,c)}}createCallbacksForBrowser(e){return{createIsolatedFolder:()=>Rd(e)}}async resolveCommandTemplateStrings(e,t){return Qa({obj:e,context:t,bannedKeys:["type","a11yData","thoughts","cache","code"],orgId:this.orgId,logger:this.logger,signal:this.executeAbortController.signal,localTools:this.localCodeEvalTools})}async executePresetCommandHelper(e,t,n,o,i){i=i||"disableCache"in n&&!!n.disableCache;let a=this.logger.child({commandId:n.id});switch(n.type){case"SUCCESS":let l=n.condition;return l?.assertion.trim()?hl({command:l,fixtures:this.getControllerFixtures(e),useMemory:this.shouldUseMemory(),aiPageFiltering:!!this.options?.aiPageFiltering,logger:a}):{succeedImmediately:!1,urlAfterCommand:this.browser.url()};case"AI_ASSERTION":{if(!n.assertion.trim())throw new A("ActionFailureError","Missing assertion");if(n.timeout&&n.timeout>1800)throw new A("AssertionFailureError",`AI check timeout of ${n.timeout} exceeds the maximum allowed value of 30 minutes.`);return hl({command:n,fixtures:this.getControllerFixtures(e),useMemory:this.shouldUseMemory(),aiPageFiltering:!!this.options?.aiPageFiltering,logger:a})}case"AI_EXTRACT":{if(!n.goal.trim())throw new A("ActionFailureError","Cannot perform AI extraction without goal");if(n.schema){let f=jh(n.schema);if(f)throw new A("UserConfigurationError",f)}let g=await this.browser.getCondensedHtml(),h=await this.browser.screenshot({retries:2});try{let f=await this.generator.getTextExtraction({goal:n.goal,browserState:g,returnSchema:n.schema,screenshot:`data:image/jpeg;base64,${h.toString("base64")}`},{disableCache:i,abortSignal:this.executeAbortController.signal,loggerTags:de(a)});if(f.result==="NOT_FOUND")throw new A("ActionFailureError","No relevant data found for extraction goal on this page");if(f.thoughts?.includes("MaxGenerationLengthExceededError"))throw new A("UserConfigurationError",f.thoughts);return{thoughts:f.thoughts||void 0,data:f.result,succeedImmediately:!1,urlAfterCommand:this.browser.url()}}catch(f){let y=f.message;throw y.includes("MaxGenerationLengthExceededError")?new A("UserConfigurationError","You tried to extract too much data. Please rephrase your query to limit the results returned or use a JavaScript step in the browser instead."):y.includes("AIProviderError")&&y.includes("time")?new A("AIProviderError","The AI provider responded with an error. This may be because you tried to extract too much data. Please limit extraction results to 2000 characters.",{errOptions:{cause:f}}):f}}case"NAVIGATE":if(!bo(n.url)&&!vo(n.url,this.browser.baseUrl))throw new A("ActionFailureError",`Invalid URL provided to navigate command: ${n.url}`);await this.browser.navigate({url:n.url,loadTimeoutMs:n.loadTimeout?n.loadTimeout*1e3:void 0});break;case"DIALOG":this.browser.registerDialogHandler(n.action);break;case"CAPTCHA":if(!this.browser.canSolveCaptchas())break;let c=await this.browser.solveCaptcha();c&&(await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:{type:"description",elementDescriptor:"the captcha image solution input"},cache:void 0,action:g=>this.browser.click(g,this.createCallbacksForBrowser(this.orgId),{}),options:{...n,targetName:"target",disableCache:i}}),await this.browser.type(c,{clearContent:!0,pressEnter:!0},!0));break;case"GO_BACK":await this.browser.goBack();break;case"GO_FORWARD":await this.browser.goForward();break;case"SCROLL_LEFT":case"SCROLL_RIGHT":case"SCROLL_DOWN":case"SCROLL_UP":{let g,h;if(n.target&&Jt(n.target))await this.browser.hoverUsingVisualCoordinates(n.target.pixels);else if(n.target&&n.target.elementDescriptor.trim()){let{elementInteractedDisplayString:T,thoughts:v}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:n.target,cache:n.cache?.target,action:R=>this.browser.hover(R),options:{...n,targetName:"target",disableGlobalLocatorRedirect:!0,disableCache:i}});g=T,h=v}let f=this.browser.getViewport()?.height??Ir.height,y=this.browser.getViewport()?.width??Ir.width;switch(n.type){case"SCROLL_UP":await this.browser.scrollVertical(-(n.deltaY??f));break;case"SCROLL_DOWN":await this.browser.scrollVertical(n.deltaY??f);break;case"SCROLL_LEFT":await this.browser.scrollHorizontal(-(n.deltaX??y));break;case"SCROLL_RIGHT":await this.browser.scrollHorizontal(n.deltaX??y);break}return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:g,thoughts:h}}case"WAIT_FOR_URL":{if(n.timeout&&n.timeout>1800)throw new A("UserConfigurationError",`Wait for URL timeout of ${n.timeout} exceeds the maximum allowed value of 30 minutes.`);let g=n.matcher;await this.browser.waitForUrl({beforeUrl:this.browser.url(),matcher:g},{timeout:n.timeout?n.timeout*1e3:void 0,negated:n.negated,caseInsensitive:n.caseInsensitive});break}case"WAIT":if(n.delay>1800)throw new A("UserConfigurationError",`Wait timeout of ${n.delay} seconds exceeds the maximum allowed value of 30 minutes`);let s=n.delay*1e3;await q(s,this.executeAbortController.signal);break;case"REFRESH":await this.browser.refresh({loadTimeoutMs:n.loadTimeout?n.loadTimeout*1e3:void 0});break;case"CLICK":{if(Jt(n.target)){await this.browser.clickUsingVisualCoordinates(n.target.pixels,n);break}let g=this.browser.url(),{elementInteractedDisplayString:h,result:f,thoughts:y}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,target:n.target,command:n,cache:n.cache?.target,action:v=>this.browser.click(v,this.createCallbacksForBrowser(this.orgId),n),options:{disableCache:i,targetName:"target",...n}}),T={urlAfterCommand:this.browser.url(),succeedImmediately:!1,elementInteracted:h,thoughts:y,data:f};return Xs(g,T.urlAfterCommand)&&(T.succeedImmediately=!0,T.succeedImmediatelyReason="URL changed"),T}case"COPY":return await this.browser.copy(n.value),{succeedImmediately:!1,data:n.value,urlAfterCommand:this.browser.url()};case"PASTE":{await this.browser.paste();break}case"DRAG":{if(Jt(n.fromTarget)&&Jt(n.toTarget)){await this.browser.dragAndDropUsingVisualCoordinates(n.fromTarget.pixels,n.toTarget.pixels,{hoverSeconds:n.hoverSeconds});break}if(Jt(n.fromTarget)||Jt(n.toTarget))throw new Error("Drag and drop targets must be both coordinates or both descriptions");let{elementInteractedDisplayStrings:g,thoughts:h}=await this.wrapMultiElementTargetingCommand({ctx:e,tracer:t,command:n,targetNames:["fromTarget","toTarget"],descriptions:[n.fromTarget,n.toTarget],caches:[n.cache?.fromTarget,n.cache?.toTarget],action:(f,y)=>this.browser.dragAndDrop(f.locator,y.locator,{hoverSeconds:n.hoverSeconds,steps:n.steps}),options:{useSelector:!!n.useSelector,disableCache:i}});return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:g[0],thoughts:h}}case"MOUSE_DRAG":{let g=parseInt(n.deltaX),h=parseInt(n.deltaY),f=n.steps??5;if(isNaN(g)||isNaN(h))throw new A("ActionFailureError",`Invalid pixel values passed to mouse drag command: (${n.deltaX}, ${n.deltaY})`);if(n.target&&Jt(n.target)){await this.browser.mouseDragUsingVisualCoordinates(g,h,f,n.target.pixels,{force:n.force});break}let y,T,v;if(n.target?.elementDescriptor){let{elementInteractedDisplayString:R,result:b,thoughts:x}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:n.target,cache:n.cache?.target,action:async N=>N.locator,options:{disableCache:i,targetName:"target",...n}});y=b,T=R,v=x}return await this.browser.mouseDrag(g,h,f,y,{force:n.force}),{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:T,thoughts:v}}case"SELECT_OPTION":{if(!Rr(n.target))throw new Error("Select with x/y is not supported yet");let g=n.target.elementDescriptor,h=n.choice,{elementInteractedDisplayString:f,thoughts:y}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:{type:"description",elementDescriptor:g},cache:n.cache?.target,action:T=>this.browser.selectOption(T,h,n.force),options:{...n,targetName:"target",disableCache:i,source:ni(n)}});return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:f,thoughts:y}}case"TAB":{let g={loadTimeoutMs:n.loadTimeout?n.loadTimeout*1e3:void 0,retry:!0};await this.browser.switchToPage(n.action,g);break}case"NEW_TAB":await this.browser.createNewTab(n.url,{loadTimeoutMs:n.loadTimeout?n.loadTimeout*1e3:void 0});break;case"COOKIE":if(!n.value)break;let u=await this.browser.setCookie(n.value);a.debug({results:u},"Set cookies");break;case"LOCAL_STORAGE":if(!n.value||!n.key)break;await this.browser.setLocalStorage(n.key,n.value);break;case"JAVASCRIPT":{let g;try{n.environment==="BROWSER"?(g=await this.browser.evaluateCodeInPage({code:n.code,fragment:n.fragment??!1,context:o.toObjectCopy(),timeoutMs:n.timeout?n.timeout*1e3:void 0}),a.info({result:g},"Executed JavaScript in browser")):g=await Br({orgId:this.orgId,code:n.code,fragment:!!n.fragment,context:o,timeoutMs:n.timeout?n.timeout*1e3:void 0,logger:a,localTools:this.localCodeEvalTools,signal:this.executeAbortController.signal,callbacks:{onPersistentVariableUpdates:async h=>{if(!this.options?.scratchPadId){a.warn({updates:h},"Got persistent variable updates but scratch pad is not available");return}await this.storage.savePersistentVariables?.({scratchPadId:this.options?.scratchPadId,orgId:this.orgId,updates:h,logger:a})}}})}catch(h){throw this.throwIfClosed(),new A("ActionFailureError",h instanceof Error?h.message:`${h}`,{errOptions:{cause:h}})}try{JSON.stringify(g)}catch(h){throw new A("ActionFailureError",`Return value is not serializable: ${h instanceof Error?h.message:`${h}`}`,{errOptions:{cause:h}})}return{urlAfterCommand:this.browser.url(),succeedImmediately:!1,data:g}}case"TYPE":{if(n.target&&Jt(n.target)){await this.browser.clickUsingVisualCoordinates(n.target.pixels,n),await this.browser.type(n.value,{force:n.force,clearContent:n.clearContent,forceClearContent:n.forceClearContent,delay:n.delay,pressEnter:n.pressEnter},!0);break}let g=this.browser.url(),h,f,y=Nb(n.target);if(y){let{elementInteractedDisplayString:v,thoughts:R}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:y,cache:n.cache?.target,action:b=>this.browser.typeIntoTarget(n.value,b,{force:n.force,clearContent:n.clearContent,forceClearContent:n.forceClearContent,delay:n.delay,pressEnter:n.pressEnter}),options:{...n,targetName:"target",disableCache:i,disableGlobalLocatorRedirect:!0,source:ni(n)}});h=v,f=R}else await this.browser.type(n.value,{force:n.force,clearContent:n.clearContent,forceClearContent:n.forceClearContent,delay:n.delay,pressEnter:n.pressEnter},!0);let T={urlAfterCommand:this.browser.url(),succeedImmediately:!1,elementInteracted:h,thoughts:f};return Xs(g,T.urlAfterCommand)&&(T.succeedImmediately=!0,T.succeedImmediatelyReason="URL changed"),T}case"HOVER":{if(Jt(n.target)){await this.browser.hoverUsingVisualCoordinates(n.target.pixels);break}let{elementInteractedDisplayString:g,thoughts:h}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:n.target,cache:n.cache?.target,action:f=>this.browser.hover(f),options:{...n,targetName:"target",disableCache:i}});return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:g,thoughts:h}}case"FOCUS":{if(!Rr(n.target))throw new Error("Focus with x/y is not supported yet");let{elementInteractedDisplayString:g,thoughts:h}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:n.target,cache:n.cache?.target,action:f=>this.browser.focus(f),options:{...n,targetName:"target",disableCache:i}});return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:g,thoughts:h}}case"BLUR":{if(n.target&&!Rr(n.target))throw new Error("Blur with x/y is not supported yet");if(!n.target||!n.target.elementDescriptor)return await this.browser.blur(null),{succeedImmediately:!1,urlAfterCommand:this.browser.url()};let{elementInteractedDisplayString:g,thoughts:h}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,target:n.target,command:n,cache:n.cache?.target,action:f=>this.browser.blur(f),options:{...n,targetName:"target",disableCache:i}});return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:g,thoughts:h}}case"PRESS":let d=this.browser.url();await this.browser.press(n.value,{repeat:n.repeat,convertMeta:n.convertMeta??!0,delayMs:n.delayMs});let m={urlAfterCommand:this.browser.url(),succeedImmediately:!1};return Xs(d,m.urlAfterCommand)&&(m.succeedImmediately=!0,m.succeedImmediatelyReason="URL changed"),m;case"KEY_DOWN":return await this.browser.keyDown(n.value,{convertMeta:n.convertMeta??!0}),{urlAfterCommand:this.browser.url(),succeedImmediately:!1};case"KEY_UP":return await this.browser.keyUp(n.value,{convertMeta:n.convertMeta??!0}),{urlAfterCommand:this.browser.url(),succeedImmediately:!1};case"REQUEST":{let g=new cN,h=lN(fetch,g),f;try{f=new URL(n.url).hostname}catch{}return{data:{...await Mb({command:n,baseUrl:this.browser.baseUrl,logger:a,fetchImplementation:h}),cookies:Sg(g,f)},succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"GRAPHQL_REQUEST":return{data:await Lb({command:n,baseUrl:this.browser.baseUrl,logger:a}),succeedImmediately:!1,urlAfterCommand:this.browser.url()};case"VISUAL_DIFF":return _b({ctx:e,tracer:t,command:n,disableCache:i,browser:this.browser,logger:a,storage:this.storage,screenshotStorage:this.visualDiffScreenshotStorage,targetingWrapper:g=>this.wrapElementTargetingCommand(g)});case"FILE_UPLOAD":{let g,h;if(n.fileSource.type==="URL"?(h=n.fileSource.url,g=await aT({uri:n.fileSource.url,logger:a,orgId:this.orgId})):n.fileSource.type==="USER_FILE"&&(h=n.fileSource.name,g=await this.uploadedFileStorage?.getFileForUpload(n.fileSource.name,this.orgId)),!g)throw new A("UserConfigurationError",`Attempted to use non-existent file for upload step: ${h}`);await this.browser.setFileChooserHandler({...g,filename:n.filename});break}case"AUTH_SAVE":return{data:await this.browser.saveAuthState(),succeedImmediately:!1,urlAfterCommand:this.browser.url()};case"AUTH_LOAD":{let g;if(!n.storageState.trim())g=void 0;else if(g=await Br({orgId:this.orgId,code:n.storageState,fragment:!1,context:o,logger:a,localTools:this.localCodeEvalTools,signal:this.executeAbortController.signal}),typeof g!="object")throw new A("ActionFailureError",`Credentials must evaluate to an object (received ${typeof g} instead)`);let h;try{h=fg.optional().parse(g)}catch(f){throw new A("ActionFailureError",`Credentials provided do not follow the required format: ${f}`)}await this.browser.loadAuthState(h);break}case"ELEMENT_CHECK":{let g=(n.timeout??xr)*1e3,h=this.generator.getAgentConfig()?.assertion;if(Cb(n.assertion)&&!n.useSelector&&n.target.type==="description"&&h&&h!=="v1"){let y={id:n.id,type:"AI_ASSERTION",assertion:`There is no element on the page closely matches the following description. If the description has single quotes, remember that requires an exact text substring match. Description: ${n.target.elementDescriptor}`,iframeUrl:n.iframeUrl,timeout:n.timeout,cache:n.cache&&"memory"in n.cache?{memory:n.cache?.memory}:void 0};try{let T=await hl({command:y,logger:a,aiPageFiltering:!!this.options?.aiPageFiltering,fixtures:this.getControllerFixtures(e),useMemory:this.shouldUseMemory(),source:"NEGATED_CHECK"});return{succeedImmediately:!1,thoughts:`The element described does not exist on the page: ${T.thoughts}`,urlAfterCommand:this.browser.url(),afterScreenshotOverride:T.afterScreenshotOverride}}finally{y.cache?.memory&&Ws(n,y.cache?.memory.traces,a)}}let f=await Rb({command:n,tracer:t,timeoutMs:g,targetingWrapper:y=>this.wrapElementTargetingCommand(y),fixtures:this.getControllerFixtures(e),disableCache:i});return{fail:!f.success,data:f.data,elementInteracted:f.elementInteractedDisplayString,thoughts:f.err?.message??f.thoughts??`Element assertion ${f.success?"succeeded":"failed"}.`,succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"PAGE_CHECK":{let g=await cr({action:async()=>Ob({assertion:n.assertion,browser:this.browser,logger:a,timeout:n.timeout,signal:this.executeAbortController.signal,autoExpandIframes:!!this.browser.userBrowserSettings.autoExpandIframes}),frameConfig:n.iframeUrl?{type:"url",url:n.iframeUrl}:void 0,browser:this.browser,logger:a});return{fail:!g.success,data:g.data,thoughts:g.success?"Page assertion passed.":g.err?.message??`Page assertion still failing after ${n.timeout} seconds.`,urlAfterCommand:this.browser.url(),succeedImmediately:!1}}case"REGISTER_REQUEST_LISTENER":{let g=new Kr(n.requestMatcher),h=this.browser.registerRequestListener(g);return this.registeredListeners[n.key]=h.then(async f=>await Gd(f)).catch(f=>{a.error({err:f},"Failed to get request listener response")}),{succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"AWAIT_LISTENER":{let g=this.registeredListeners[n.key];if(!g)throw new A("ActionFailureError",`No listener registered with key: ${n.key}`);let h=n.timeout??10;return{data:await B(g,{milliseconds:h*1e3,message:`Request listener timed out after ${h} seconds`}),succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"RECORD_REQUESTS":{let g=new Kr(n.requestMatcher);return this.recordedRequests[n.key]={},this.browser.registerRequestRecorder(n.key,g,{onRequestStart:(h,f)=>{this.recordedRequests[n.key][h]=sl(f)},onRequestComplete:(h,f)=>{this.recordedRequests[n.key][h]=sl(f)}}),{succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"GET_RECORDED_REQUESTS":{let g=this.recordedRequests[n.key];if(!g)throw new A("ActionFailureError",`No recorder registered with key: ${n.key}`);return delete this.recordedRequests[n.key],{data:Object.values(g),succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"SET_HEADER":{let g;return n.requestMatcher&&(g=new Kr(n.requestMatcher)),this.browser.setHeader(n.name,n.value,g),{succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"MOCK_ROUTE":return{data:{key:this.browser.registerMock(n.key,new Kr(n.requestMatcher),async(h,f)=>{let y=await Br({orgId:this.orgId,code:n.responseGenerator,fragment:!1,context:o,timeoutMs:void 0,logger:a,localTools:this.localCodeEvalTools,mock:{request:h,response:f},disallowVariableUpdates:!0,responseSerialization:"RESPONSE"}),T=Pg.parse(y);return new Response(T.body,{status:T.status,headers:T.headers})},n.fetchOriginalResponse??!1)},succeedImmediately:!1,urlAfterCommand:this.browser.url()};case"REMOVE_ROUTE_MOCK":return this.browser.removeMock(n.key),{succeedImmediately:!1,urlAfterCommand:this.browser.url()};case"OFFLINE_MODE":return await this.browser.setOfflineMode(n.enable),{succeedImmediately:!1,urlAfterCommand:this.browser.url()};default:return(g=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(n)}return{succeedImmediately:!1,urlAfterCommand:this.browser.url()}}async getReverseMappedDescription({browserState:e,targetId:t,disableCache:n,screenshot:o}){return(await this.generator.getReverseMappedDescription({browserState:e,target:t,screenshot:o},{disableCache:n,abortSignal:this.executeAbortController.signal,loggerTags:de(this.logger)})).phrase}async stopRecordMode(){this.recordAbortController?.abort(),await this.browser.clearAllCdpHighlights()}async startRecordMode({params:e,abortController:t,isClickToRecord:n}){this.recordAbortController=t;let o=new cl({signal:t.signal,...e});return await this.browser.startRecording(this.recordAbortController.signal,o,n),o}async runSectionAutohealing(e){return this.generator.getAutohealingProposal(e,{disableCache:!0,abortSignal:this.executeAbortController.signal,loggerTags:de(this.logger)})}async getFailureRecoveryPlan(e){return this.generator.getFailureRecoveryPlan(e,{disableCache:!0,abortSignal:this.executeAbortController.signal,loggerTags:de(this.logger)})}};import{z as Ne}from"zod";var Db=Ne.array(Ne.object({proc:Ne.string(),webview:Ne.string(),info:Ne.object({"Android-Package":Ne.string(),Browser:Ne.string(),"Protocol-Version":Ne.string(),"User-Agent":Ne.string(),"V8-Version":Ne.string(),"WebKit-Version":Ne.string(),webSocketDebuggerUrl:Ne.string()}),pages:Ne.array(Ne.object({description:Ne.string(),devtoolsFrontendUrl:Ne.string(),id:Ne.string(),title:Ne.string(),type:Ne.string(),url:Ne.string(),webSocketDebuggerUrl:Ne.string()})),webviewName:Ne.string()}));var El=class r{driver;device;currentContext;logger;webviews=new Map;fixtures;orgId;options;aborter;constructor({driver:e,context:t,logger:n,device:o,fixtures:i,orgId:a,options:l,aborter:c}){this.driver=e,this.device=o,this.currentContext=t,this.logger=n,this.fixtures=i,this.orgId=a,this.options=l,this.aborter=c;for(let s of["SIGINT","SIGTERM"])process.on(s,async()=>{await this.cleanupWebviews()})}static async init({driver:e,logger:t,fixtures:n,orgId:o,adbPort:i,options:a,aborter:l}){let c=await e.getContext(),s=typeof c=="string"?c:c.id,u=(await dN.devices()).filter(p=>p._initializer?.serial?.endsWith(i.toString()));if(u.length!==1)throw new Error(`Playwright detected ${u.length} Android devices, expected 1. Please stop all other emulators and try again.`);let d=u[0];return new r({driver:e,context:s,logger:t,device:d,fixtures:n,orgId:o,options:a,aborter:l})}async getContexts(){let e=await this.driver.getContexts({}),t=Array.from(this.webviews.values());return{contexts:e,webviews:t.map(n=>({contextId:n.contextId,packageName:n.packageName,active:n.active,hasPlaywright:!!n.browserController,lastSeen:n.lastSeen,socketName:n.socketName}))}}async getCurrentScreenshot(){return`data:image/png;base64,${await this.driver.takeScreenshot()}`}async waitForScreenshotStability({timeoutMs:e,signal:t,reason:n,tracer:o}){await o.startAsyncSpan("WAIT_FOR_STABILITY",async()=>{let i=Date.now(),a,l=!1;for(;Date.now()-i<e;){if(t?.throwIfAborted(),!a){a=await this.getCurrentScreenshot();continue}if(await this.getCurrentScreenshot()===a){l=!0;break}await q(250,t)}l||this.logger.warn({reason:n},"Timed out waiting for screenshot stability")})}async getDomState(e){let t;if(e?.includeWebviews)try{let i=await this.getActiveWebview();i&&i.browserController&&(t=(await i.browserController.getBrowserState({abortSignal:this.aborter.controller?.signal})).serializedTree)}catch(i){this.logger.error({err:i},"Could not get webview info to get the nested DOM state")}this.throwIfAborted();let n=await this.driver.getPageSource();return this.throwIfAborted(),{graph:await Ky(n,{injectedWebviewContent:t,disallowAccessibilityBridgeForWebviews:this.options.disableDefaultWebviewAccessibilityTree}),context:this.currentContext}}async refreshWebviews(){await this.driver.getPageSource(),this.throwIfAborted();let e=await this.getDetailedContexts();if(!e){this.logger.warn("No context details, not proceeding with refreshing webviews");return}let t=Date.now(),n=new Set;for(let o of e){if(this.throwIfAborted(),o.webview==="NATIVE_APP")continue;let i=o.info["Android-Package"];if(n.add(o.webview),!this.webviews.has(o.webview)||!this.webviews.get(o.webview)?.active){let a={contextId:o.webview,packageName:i,active:!1,lastSeen:t,socketName:o.proc.startsWith("@")?o.proc.substring(1):o.proc};this.logger.info({contextId:a.contextId,packageName:a.packageName,socketName:a.socketName},"New webview detected"),this.webviews.set(o.webview,a);let l;if(i==="com.android.chrome"?(l=await this.connectPlaywrightToChrome(a),this.logger.info(`Connected Playwright to Android Chrome: ${o.webview}`)):(this.logger.info(`Attempting to connect Playwright to webview: ${o.webview}`),l=await this.connectPlaywrightToWebview(i,a.socketName),this.logger.info(`Connected Playwright to webview ${o.webview}`)),!l)continue;a.browserController=l,a.active=!0}}for(let[o,i]of this.webviews.entries())!n.has(o)&&i.active&&(this.logger.info(`Disconnecting dead webview ${o}`),this.disconnectPlaywrightFromWebview(i),i.active=!1)}async getActiveWebview(){await this.refreshWebviews();let e=await this.driver.getCurrentPackage(),t=[];for(let n of this.webviews.values())n.packageName===e&&n.active&&t.push(n);if(t.length!==0){if(t.length>1)throw new Error("Multiple active webviews in a single package is currently not supported");return t[0]}}async executeRawADBCommand(e){let t=this.driver.capabilities,n=t.deviceUDID||t.udid||t["appium:udid"]||t["appium:deviceUDID"],o=process.env.ANDROID_HOME?`${process.env.ANDROID_HOME}/platform-tools/adb`:"adb",i=n?`-s ${n}`:"",a=`${o} ${i} ${e}`;this.logger.info(`Executing ADB command: ${a}`);let l=kb(a,{encoding:"utf8"});return this.logger.info(`ADB command result: ${l}`),l}async cleanupWebviews(){for(let[e,t]of this.webviews.entries())this.logger.info(`Disconnecting webview ${e}`),this.disconnectPlaywrightFromWebview(t),t.active=!1}async getDetailedContexts(){let e=await this.driver.execute("mobile: getContexts");return this.aborter.controller?.signal.throwIfAborted(),Db.parse(e)}async createBrowserController({context:e}){let t=await $i.fromExistingContext({context:e,logger:this.logger,userBrowserSettings:{visualActions:!0},storage:this.fixtures.storage,flagStore:Vc,enricher:this.fixtures.browserEnricher});await t.getActivePage().waitForLoadState();let n=await t.getBrowserState({skipWait:!0,skipWaitForPageLoad:!0});return new Sl({browser:t,generator:this.fixtures.browserGenerator,logger:this.logger,flagStore:Vc,orgId:this.orgId,storage:this.fixtures.storage,localCodeEvalTools:this.fixtures.localCodeEvalTools,visualDiffScreenshotStorage:new Xa})}async connectPlaywrightToWebview(e,t){let o=this.device.webViews().find(a=>!(a.pkg()!==e||"_socketName"in a&&typeof a._socketName=="string"&&a._socketName!==t));if(!o){this.logger.warn(`[WebviewManager] Could not find webview for ${e} with socket name ${t}`);return}return this.logger.info({packageName:e,socketName:t},"Connecting Playwright to app webview"),await this.createBrowserController({context:(await o.page()).context()})}async connectPlaywrightToChrome(e){let{contextId:t,socketName:n}=e;try{this.logger.info({contextId:t,socketName:n},"Connecting to Chrome webview");let o;e.forwardedPort?(o=`http://127.0.0.1:${e.forwardedPort}`,this.logger.info({contextId:t,endpoint:o,socketName:n},"Using existing forwarded port")):(o=`http://127.0.0.1:${await this.forwardDevToolsSocket(e.socketName)}`,this.logger.info({contextId:t,endpoint:o,socketName:n},`Forwarding DevTools socket for ${e.socketName}`)),this.logger.info({endpoint:o,socketName:n},"Connecting to CDP endpoint");let i=await mN.connectOverCDP({endpointURL:o,timeout:12e3}),a=i.contexts()[0];if(!a){this.logger.warn("No browser context available after CDP connection"),await i.close();return}return this.createBrowserController({context:a})}catch(o){this.logger.error({err:o},`Error connecting Playwright to webview ${e.contextId}`);return}}async disconnectPlaywrightFromWebview(e){try{e.browserController&&(this.logger.info(`Disconnecting Playwright from webview: ${e.contextId}`),await e.browserController.browser.cleanup(),e.browserController=void 0),e.forwardedPort&&await this.removeDevToolsForwarding(e.forwardedPort)}catch(t){this.logger.error({err:t},`Error disconnecting Playwright from webview ${e.contextId}:`)}}async forwardDevToolsSocket(e){this.logger.info("Setting up port forwarding for DevTools");let t=1e4+Math.floor(Math.random()*1e4),n=this.driver.capabilities,o=n.deviceUDID||n.udid||n["appium:udid"]||n["appium:deviceUDID"];this.logger.info({deviceId:o},`Device ID from capabilities: ${o||"not found"}`);let i=process.env.ANDROID_HOME?`${process.env.ANDROID_HOME}/platform-tools/adb`:"adb",a=o?`-s ${o}`:"",l=`${i} ${a} forward tcp:${t} ${`localabstract:${e}`||"localabstract:chrome_devtools_remote"}`;this.logger.info(`Executing command: ${l}`);let c=kb(l,{encoding:"utf8"});return this.logger.info(`ADB command result: ${c}`),this.logger.info(`Successfully forwarded DevTools socket to port ${t}`),t}async removeDevToolsForwarding(e){await this.executeRawADBCommand(`forward --remove tcp:${e}`),this.logger.info("Successfully removed port forwarding")}throwIfAborted(){this.aborter.controller?.signal.throwIfAborted()}};var xo=class r{stateManager;generator;driver;logger;fixtures;options;aborter;appsWithGrantedPermissions=new Set;orgId;adbPort;constructor({driver:e,generator:t,stateManager:n,logger:o,fixtures:i,options:a,aborter:l,orgId:c,adbPort:s}){this.driver=e,this.generator=t,this.stateManager=n,this.logger=o,this.fixtures=i,this.options=a??{},this.aborter=l,this.orgId=c,this.adbPort=s}static async init({driver:e,generator:t,logger:n,fixtures:o,orgId:i,options:a,abortController:l,adbPort:c}){let s={controller:l},u=await El.init({driver:e,logger:n,fixtures:o,orgId:i,options:a?.emulator??{},aborter:s,adbPort:c}),d=new r({driver:e,generator:t,stateManager:u,logger:n,fixtures:o,options:a,aborter:s,orgId:i,adbPort:c});return await d.initializeSettings(),d}async installApp(e){await this.stateManager.executeRawADBCommand(`install ${Qd.resolve(e)}`)}throwIfAborted(){this.aborter.controller?.signal.throwIfAborted()}async wrapTargetingAction(e){let{action:t,description:n,command:o,cacheKey:i="cache",targetName:a="target",cacheIsInvalidAfterResolution:l,tracer:c}=e,s=i in o&&o[i]&&a in o[i]?o[i][a]:void 0,u=e.retriesWithAI??1,d=!1,m=fN(s),p;if(o.disableCache&&(this.logger.debug({command:o},"Cache explicitly disabled for command"),d=!0,m=void 0),l&&(d=!0,m=void 0),m&&m?.resolvedDescription!==n&&(this.logger.info({cache:m,description:n},"Cache description mismatch, clearing it automatically"),d=!0,m=void 0),!m){u--,this.logger.info({description:n,cacheBustedBeforeAction:d},"Prompting AI for a new element location");let h=await this.findElement({description:n,tracer:c});return p=h.thoughts,Sd({command:o,cacheKey:i,targetName:a,updatedCache:h.resolvedTarget}),{result:await t(h.resolvedTarget),thoughts:p}}let g;try{await this.stateManager.waitForScreenshotStability({timeoutMs:5e3,signal:this.aborter.controller?.signal,tracer:c,reason:"Waiting for stability before cache resolution"}),g=await c.startAsyncSpan("GET_EMULATOR_STATE",async()=>{try{await this.stateManager.refreshWebviews()}catch(y){this.logger.warn({err:y},"Failed to refresh webviews, continuing...")}return await this.stateManager.getDomState()});let h=await c.startAsyncSpan("RESOLVE_TARGET_CACHE",async y=>{let{resolvedTarget:T}=await Qy({target:m,domState:g,stateManager:this.stateManager,logger:this.logger}),v=Zy(T),R=gN(m,v);return this.logger.info({cacheDiffs:R},"Successfully resolved and updated target"),Sd({command:o,cacheKey:i,targetName:a,updatedCache:v}),y.result={serializedElement:T.type==="WEBVIEW"?T.browserCache?.nodeOnlySerializedHtml??"Unknown HTML element in webview":T.elementOnlySerializedXml},T});return m.type!=="WEBVIEW"&&xt.increment("cache_target_resolution_v2",1,["outcome:hit","platform:native",`hasRequirements:${!!m.requirements}`,`hasAdditionalElements:${!!m.requiredRelatedElements?.length}`]),{result:await t(h),thoughts:"Successfully executed preset action with cache."}}catch(h){if(m.type!=="WEBVIEW"&&xt.increment("cache_target_resolution_v2",1,["outcome:miss","platform:native",`hasRequirements:${!!m.requirements}`,`hasAdditionalElements:${!!m.requiredRelatedElements?.length}`]),this.throwIfAborted(),u>0)return this.logger.warn({err:h,domState:g?.graph.originalXml},"Failed to resolve target cache, retrying with AI"),this.wrapTargetingAction({...e,cacheIsInvalidAfterResolution:!0,retriesWithAI:u-1});throw new Error(`ActionFailureError: ${h instanceof Error?h.message:h}`,{cause:h})}}async findElement({description:e,tracer:t}){await this.stateManager.waitForScreenshotStability({timeoutMs:5e3,signal:this.aborter.controller?.signal,tracer:t,reason:"Waiting for stability before locating an element with AI"});let n=await t.startAsyncSpan("GET_EMULATOR_STATE",async()=>{try{await this.stateManager.refreshWebviews()}catch(d){this.throwIfAborted(),this.logger.warn({err:d},"Failed to refresh webviews, continuing...")}let s=await this.stateManager.getDomState(),u=await this.stateManager.getCurrentScreenshot();return{emulatorState:s,screenshot:u}}),o=Date.now(),i;try{i=await this.generator.getElementLocation({description:e,screenXml:n.emulatorState.graph.xml,screenshot:n.screenshot},{logger:this.logger,loggerTags:de(this.logger),abortSignal:this.aborter.controller?.signal})}catch(s){throw this.throwIfAborted(),this.logger.error({err:s},"Failed to locate element"),new Error(`ActionFailureError: Failed to locate element: ${s instanceof Error?s.message:s}`)}if(i.id===-1)throw t.addSpan({type:"AI_LOCATOR_CALL",startTime:o,endTime:Date.now(),error:`No matching element found: ${i.thoughts}`}),new Error(`ActionFailureError: No matching element found: ${i.thoughts}`);let a=Jy({aiResponse:i,description:e,emulatorState:n.emulatorState});if(a.type==="NATIVE")return t.addSpan({type:"AI_LOCATOR_CALL",startTime:o,endTime:Date.now(),result:{serializedElement:a.elementOnlySerializedXml,id:i.id,thoughts:i.thoughts}}),{resolvedTarget:a,thoughts:i.thoughts};let l=await this.stateManager.getActiveWebview();if(!l||!l.browserController)throw new Error("No browser controller is attached to the requested webview");let c=await l.browserController.locateElement({description:e,disableCache:!1,logger:this.logger});return t.addSpan({type:"AI_LOCATOR_CALL",startTime:o,endTime:Date.now(),result:{serializedElement:c.target.nodeOnlySerializedHtml??"Unknown HTML element in webview",id:c.target.id,thoughts:c.thoughts}}),{resolvedTarget:{...a,controller:l.browserController,resolution:c.resolution,browserCache:c.target},thoughts:c.thoughts}}async executeCommand(e){let t=["type","a11yData","thoughts","cache","code"],n;try{n=await Qa({obj:e.command,context:this.fixtures.testContext,bannedKeys:t,orgId:this.orgId,logger:this.logger,signal:this.aborter.controller?.signal,localTools:this.fixtures.localCodeEvalTools})}catch(o){throw this.throwIfAborted(),new Error(`ActionFailureError: Failed to substitute template strings in command: ${o.message}`,{cause:o})}try{return await this.executeCommandHelper(e)}catch(o){throw o.name!=="AbortError"&&this.logger.error({err:o},"Error thrown in action controller"),o}finally{Za(e.command,n)}}async executeCommandHelper({command:e,tracer:t}){switch(e.type){case"STATE":{await this.stateManager.refreshWebviews();let n=await this.stateManager.getDomState(),o=await this.stateManager.getContexts();return{output:{xml:n.graph.xml,contexts:o},success:!0}}case"TAP":{if(e.target.type==="coordinates"){let o=await this.driver.getWindowSize(),i=e.target.xPercent*o.width,a=e.target.yPercent*o.height;return await this.driver.tap({x:i,y:a}),{success:!0,message:`Tapped at ${i}, ${a}`}}let{thoughts:n}=await this.wrapTargetingAction({command:e,tracer:t,action:async o=>{if("type"in o&&o.type==="NATIVE"){let[i,a,l,c]=o.bounds,s=i+(l-i)/2,u=a+(c-a)/2;await this.driver.tap({x:s,y:u})}else{let{controller:i}=o;await i.browser.click(o.resolution,{createIsolatedFolder:()=>{let a=Math.random().toString(36).substring(4),l=Qd.join(SN(),"momentic","downloads"),c=Qd.join(l,this.orgId,a);return hN(c,{recursive:!0}),c}})}},description:e.target.description});return{success:!0,message:n}}case"TYPE":{let n;if(e.target){let o={type:"TAP",id:pN(),target:e.target,cache:e.cache};try{n=(await this.executeCommand({command:o,tracer:t})).message}finally{e.cache=o.cache}}return await this.stateManager.waitForScreenshotStability({timeoutMs:2e3,signal:this.aborter.controller?.signal,tracer:t,reason:"Waiting for keyboard to appear before typing"}),await this.driver.keys(e.text),{success:!0,message:n}}case"AI_CHECK":{let o=e.timeoutSecs?e.timeoutSecs*1e3:5e3,i=Ks(o),a=Date.now(),l=0,c,s=!1,u;for(;l<15&&!s;){this.throwIfAborted(),s||c&&c-a>=o&&(s=!0),l!==0&&await q(i,this.aborter.controller?.signal),c=Date.now();try{let d="",m="";await t.startAsyncSpan("GET_EMULATOR_STATE",async()=>{d=(await this.stateManager.getDomState({includeWebviews:!0})).graph.xml,m=await this.stateManager.getCurrentScreenshot()});let p=await t.startAsyncSpan("AI_ASSERTION_CALL",async g=>{let h=await this.generator.evaluateAssertion({assertion:e.assertion,screenXml:d,screenshot:m},{logger:this.logger,loggerTags:de(this.logger)});return g.result={thoughts:h.thoughts,result:h.result},h});if(p.result)return{success:p.result,message:p.thoughts};{let g=`AssertionFailureError: ${p.thoughts}`;u=new Error(g)}}catch(d){this.throwIfAborted(),this.logger.info({err:d},`AI check assert attempt ${l} failed, retrying...`),u=d instanceof Error?d:new Error(`${d}`)}finally{l++}}return{success:!1,message:u?.message}}case"JAVASCRIPT":{let n=await Br({orgId:this.orgId,code:e.code,fragment:!1,context:this.fixtures.testContext,timeoutMs:e.timeout?e.timeout*1e3:void 0,logger:this.logger,localTools:this.fixtures.localCodeEvalTools,signal:this.aborter.controller?.signal});try{JSON.stringify(n)}catch(o){throw new Error(`UserConfigurationError: Return value is not serializable: ${o instanceof Error?o.message:`${o}`}`)}return{success:!0,output:n}}case"OPEN_NOTIFICATION_DRAWER":return await this.driver.pressKeyCode(83),{success:!0};case"OPEN_APP":{let n=e.activityName;if(!n){let o=await B(this.driver.execute("mobile: shell",{command:"pm",args:["resolve-activity","--brief","-a","android.intent.action.MAIN","-c","android.intent.category.LAUNCHER",e.packageName]}),{signal:this.aborter.controller?.signal,milliseconds:1e4});if(typeof o!="string")throw new Error(`Could not find main activity name for package ${e.packageName}. Unexpected output: ${o}`);if(o.includes("No activity found"))throw new Error(`No activity found for package ${e.packageName}.`);if(n=o.trim().split(`
4011
- `).pop()?.replace(/^.*\//,""),!n)throw new Error(`Could not parse main activity name for package ${e.packageName}. Raw output: ${o}`)}if(this.options.emulator?.autoGrantPermissions&&!this.appsWithGrantedPermissions.has(e.packageName)){let o={permissions:"all",appPackage:e.packageName,action:"grant"};await this.driver.executeScript("mobile: changePermissions",[o]),this.appsWithGrantedPermissions.add(e.packageName)}return await this.driver.execute("mobile: shell",{command:"am",args:["start","-n",`${e.packageName}/${n}`]}),await this.stateManager.waitForScreenshotStability({timeoutMs:5e3,signal:this.aborter.controller?.signal,tracer:t,reason:"Waiting for stability after app launch"}),{success:!0}}case"PRESS":switch(e.key){case"HOME":await this.driver.pressKeyCode(3);break;case"BACK":await this.driver.pressKeyCode(4);break;case"APP_SWITCHER":await this.driver.pressKeyCode(187);break;case"POWER":await this.driver.pressKeyCode(26);break;case"SEARCH":await this.driver.pressKeyCode(84);break;case"VOLUME_UP":await this.driver.pressKeyCode(24);break;case"VOLUME_DOWN":await this.driver.pressKeyCode(25);break;case"VOLUME_MUTE":await this.driver.pressKeyCode(164);break}return{success:!0};case"ADB":return{success:!0,output:await this.driver.execute("mobile: shell",{command:e.command}),message:"ADB command executed successfully"};default:{let n=e;return{success:!0}}}}async initializeSettings(){}async screenshot(){return this.driver.takeScreenshot()}resetAbortController(e){this.aborter.controller=e??new AbortController}isAborted(){return this.aborter.controller?.signal.aborted}abort(){this.aborter.controller?.abort()}get context(){return this.fixtures.testContext}};async function Ub({socket:r,logger:e,androidDriverFactory:t,getOrgId:n,mobileGeneratorFactory:o,browserGeneratorFactory:i,browserEnricherFactory:a,storageFactory:l,localToolsFactory:c,globalStateManager:s,settingsFactory:u}){let d=r.id,m=r.handshake.query?.testMetadata,p=r.handshake.query?.fileName,g=p?.endsWith(Xe.TEST)?p.slice(0,-Xe.TEST.length):p,h=cn.parse(JSON.parse(m??"")),f=h.id,y=h.settings?.defaultChannel,T=h.settings?.defaultTag,v=await n({testId:f});e=e.child({sessionId:d,testId:f,orgId:v});let b={...(await u(v,e)).emulator,...h.settings?.emulator},x=Date.now(),{driver:N,cleanup:k,limbarToken:$,limbarUrl:De,emulatorName:ee,adbTunnelPort:oe}=await t({socket:r,logger:e,creationOpts:{region:b.region,apkToInstall:y?{channel:y,tag:T}:void 0}});e.info({adbTunnelPort:oe,apkChannel:y,apkTag:T,duration:Date.now()-x,emulatorName:ee},"Android emulator session initiated"),e=e.child({emulator:ee});let lt=await o(v,e),M=await i(v,e),V=await a(v,e),te=await l(v),Re=c?await c(v):void 0,_e={};h.settings?.defaultEnv&&(_e=(await te.fetchEnvironment(h.settings?.defaultEnv,e))?.variables??{});let ve=new Qn({variablesFromEnvironment:_e,envName:h.settings?.defaultEnv,testName:g}),Rt=await xo.init({driver:N,generator:lt,logger:e,options:{emulator:b},fixtures:{storage:te,browserEnricher:V,browserGenerator:M,localCodeEvalTools:Re,testContext:ve},orgId:v,adbPort:oe,abortController:new AbortController});if(!r.connected)throw await k(),new Error("Socket not connected anymore, not proceeding with Android session setup");let ct=EN({socket:r,testContext:ve}),Ae=async()=>{clearInterval(ct);try{await k()}catch(Ve){e.warn({err:Ve},"Failed to clean up emulator in socket server")}};return s.registerSession(d,{controller:Rt,cleanup:Ae,emulatorName:ee}),r.emit("session",{testId:f,sessionId:d,limbarUrl:De,limbarToken:$}),{sessionId:d,testId:f,orgId:v,emulatorName:ee,logger:e}}function EN({socket:r,testContext:e}){return setInterval(()=>{let t=e.toEditorDisplayCopy();r.emit("emulatorState",{context:t})},3e3)}async function Fb({socket:r,logger:e,globalStateManager:t}){await t.removeSession(r.id,e)}var yN=({socket:r,globalStateManager:e})=>async()=>{let t=e.getSession(r.id);if(!t)throw new Error("No active Android session found");t.controller.abort()},Bb={event:"cancel",createHandler:yN};import{diff as TN}from"deep-object-diff";import{cloneDeep as bN}from"lodash-es";import{randomUUID as zb}from"crypto";async function Gb({fixtures:r,step:e,inputs:t,stepTracer:n}){let o=Date.now(),{logger:i,controller:a}=r,l;if(!t.interactive)try{l=await a.screenshot()}catch(s){i.warn({err:s},"Failed to take before screenshot")}let c=n.startCommand();try{let s=await a.executeCommand({command:e.command,tracer:c}),u=c.getRootSpan(),d={...e,status:s.success?"SUCCESS":"FAILED",message:s.message,trace:u,startTime:o,endTime:Date.now(),data:s.output};if(!t.interactive){try{let m=zb(),p=await a.screenshot();d.afterSnapshot=m,n.attachAfterScreenshot({logger:i,snapshotId:m,screenshot:Buffer.from(p,"base64")})}catch(m){i.warn({err:m},"Failed to take after screenshot")}if(l){let m=zb();d.beforeSnapshot=m,n.attachBeforeScreenshot({logger:i,snapshotId:m,screenshot:Buffer.from(l,"base64")})}}return d}catch(s){let u=c.getRootSpan();return s instanceof Error&&s.name==="AbortError"||a.isAborted()?{...e,status:"CANCELLED",message:"Step cancelled.",startTime:o,endTime:Date.now(),trace:u}:(i.error({err:s},"Failed to execute preset step"),{...e,status:"FAILED",message:s instanceof Error?s.message:String(s),startTime:o,endTime:Date.now(),trace:u})}}async function Hb({fixtures:r,inputs:e,tracer:t}){let{logger:n,controller:o,usageTracker:i}=r,a=[],l,c="SUCCESS",{fromStep:s,toStep:u}=e,d=!!s;for(let m=0;m<e.steps.length;m++){let p=e.steps[m];if(n.info({step:p},`Executing step ${m+1} of ${e.steps.length}: ${Ey(p.command)}`),d&&s){let f=JSON.stringify([]);if(p.id===s.fromStepId&&f===JSON.stringify(s.parentStepIdChain))d=!1;else continue}let g=await t.startStep({logger:n,step:p,attempt:1,parentStepIdChain:[]});i.trackStepExecution(p);let h=await Gb({fixtures:r,inputs:e,step:p,stepTracer:g});if(a.push(h),await g.finish({parentStepIdChain:[],result:h}),h.status!=="SUCCESS"){c=h.status,l=h;break}if(p.envKey&&o.context.setVariable(p.envKey,h.data),u){let f=JSON.stringify([]);if(p.id===u.toStepId&&f===JSON.stringify(u.parentStepIdChain))break}}return{results:a,status:c,terminalResult:l}}async function Tl(r){let{tracer:e}=r,{steps:t,testMetadata:n}=r.inputs,{cacheStorage:o,logger:i}=r.fixtures;await o.resolveEntries({logger:i,testId:n.id,stepLists:{steps:t}});let a=bN(t);i.info({testMetadata:cn.parse(n)},"Starting mobile test execution");let l=await e.startMainStepList(),{status:c,results:s}=await Hb({...r,tracer:l});if(c==="SUCCESS"){let u=TN(a,t);if(u&&Object.keys(u).length>0){i.debug({diffs:u},"Saving mobile step cache entries post-success");let{cachesToSave:d}=await To({steps:t,cacheCreationParams:{orgId:r.inputs.orgId,testId:n.id}});await o.saveEntries({logger:i,testId:n.id,entries:d})}return{status:"PASSED",results:s}}return c==="CANCELLED"?{status:"CANCELLED",results:s}:{status:"FAILED",results:s}}var Zd=class{parentTracer=null;socket;step;commandTracer;constructor({step:e,socket:t,parentTracer:n}){this.socket=t,this.parentTracer=n,this.step=e,this.commandTracer=new oo("command")}attachBeforeScreenshot(){}attachAfterScreenshot(){}attachBeforeHtmlSnapshot(){}attachAfterHtmlSnapshot(){}async finish(e){switch(e.result.status){case"SUCCESS":this.socket.emit("success",e);break;case"FAILED":this.socket.emit("failure",e);break;case"CANCELLED":this.socket.emit("cancelled",e);break}return this.commandTracer.finish(),{trace:this.commandTracer.getRootSpan()}}startCommand(){return this.commandTracer}async startSubSteps(){return new _o({parentStep:this.step,socket:this.socket,parentTracer:this})}},_o=class{parentTracer;parentStep;socket;constructor({parentStep:e,socket:t,parentTracer:n}){this.parentTracer=n,this.parentStep=e,this.socket=t}async startStep(e){return this.socket.emit("started",{stepId:e.step.id,parentStepIdChain:e.parentStepIdChain,attempt:e.attempt}),new Zd({step:e.step,parentTracer:this,socket:this.socket})}},bl=class{constructor(e){this.socket=e}attachConsoleLogs(){}attachNetworkLogs(){}async finish(){this.socket.emit("finished")}async startBeforeStepList(){return new _o({parentStep:null,parentTracer:null,socket:this.socket})}async startMainStepList(){return new _o({parentStep:null,parentTracer:null,socket:this.socket})}async startAfterStepList(){return new _o({parentStep:null,parentTracer:null,socket:this.socket})}};var vN=({metadata:r,logger:e,globalStateManager:t,socket:n,cacheStorageFactory:o})=>async(i,a)=>{let l=t.getSession(n.id);if(!l)throw new Error("No active Android session found");let c=await o(r.orgId),s=l.controller;s.resetAbortController();let u=new bl(n),d=await Tl({fixtures:{controller:s,logger:e,cacheStorage:c,usageTracker:new La},inputs:{steps:i.steps,fromStep:i.fromStep,toStep:i.toStep,orgId:r.orgId,testMetadata:i.testMetadata,interactive:!0},tracer:u});await u.finish();let m={results:d.results,status:d.status},p=JSON.parse(Ur(m));a?.(p)},Vb={event:"execute",createHandler:vN};import{debounce as AN}from"ts-debounce";var wN=({socket:r,globalStateManager:e,keepSessionAlive:t})=>{let n=AN(t,3e4,{maxWait:6e4});return async()=>{let o=e.getSession(r.id);if(!o)throw new Error("No active Android session found");o.emulatorName&&n(o.emulatorName)}},jb={event:"keepalive",createHandler:wN};var Wb=[Vb,Bb,jb];function $b(r){let{logger:e,baseServer:t,globalStateManager:n}=r,o=new RN(t,{cors:{origin:"*",methods:["GET","POST"]},pingTimeout:15*60*1e3,pingInterval:15*60*1e3,maxHttpBufferSize:1e7,perMessageDeflate:!0}),i=async()=>{await n.removeAllSessions(e)};o.on("connection",async l=>{e.info({event:"connection",transport:l.conn.transport.name},"Android websocket connection initiated"),l.on("disconnect",async()=>{await Fb({socket:l,globalStateManager:n,logger:e})});let c;try{c=await Ub({...r,socket:l,globalStateManager:n})}catch(s){e.error({err:s},"Failed to setup Android connection"),l.emit("error",{message:s instanceof Error?s.message:JSON.stringify(s)}),l.disconnect(!0);return}Wb.forEach(s=>a(s,{...r,socket:l,metadata:c,logger:e}))});let a=(l,c)=>{let s=l.createHandler(c),u=(...d)=>{l.event!=="keepalive"&&c.logger.debug({event:l.event},`Websocket event (${l.event})`);let m=p=>{c.logger.error({event:l.event,err:p instanceof Error?p:new Error(`${p}`)},"Unhandled exception in socket handler"),c.socket.emit("error",{message:p instanceof Error?p.message:`${p}`})};try{let p=s.apply(this,d);p&&typeof p.catch=="function"&&p.catch(m)}catch(p){m(p)}};c.socket.on(l.event,u)};return{server:o,dispose:i}}import{cloneDeep as CN}from"lodash-es";import xN from"truncate-json";var qb=1e3,Kb=3e6;function _N(r,e){for(let t=0;t<r.length;t++){let n=r[t];try{if(n.data){let{jsonString:o}=xN(JSON.stringify(n.data),1e3);n.data=JSON.parse(o)}}catch(o){e.error({err:o},"Failed to serialize individual result output data"),n.data=`Result output data could not be serialized: ${o}`}switch(n.type){case"MOBILE_PRESET_STEP":MN(n);break;default:return(()=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})()}}}function MN(r){let e=r.command;"cache"in e&&e.cache&&(e.cache=void 0)}function Yb(r,e){let t=JSON.stringify(r),n=t.replaceAll("\\u0000","");if(t.length!==n.length){let o=t.indexOf("\\u0000");e.warn({input:t.slice(Math.max(0,o-500),Math.min(t.length,o+500))},"Database content violation: stripped unicode character from input")}return n}function vl(r,e){let t=CN(r);if(_N(t,e),t.length>qb)return e.error("Database content violation: results too long, truncating before insertion"),t.slice(0,qb);let n=Yb(t,e);if(n.length>Kb)for(e.error({serializedLength:n.length,resultsArrayLength:t.length},"Database content violation: results too large, truncating before insertion");n.length>Kb;)t.pop(),n=Yb(t,e);try{return eo.array().parse(JSON.parse(n))}catch(o){throw e.error({serialized:n,err:o},"Could not parse serialized results into JSON structure after processing"),o}}var Ki=!!process.env.CI||!!process.env.GITHUB_ACTIONS||!!process.env.GITHUB_RUN_ID||!!process.env.GITLAB_CI||!!process.env.CI_COMMIT_SHA||!!process.env.JENKINS_URL||!!process.env.BUILD_NUMBER||!!process.env.JENKINS_HOME||!!process.env.CIRCLECI||!!process.env.CIRCLE_BUILD_NUM||!!process.env.TRAVIS||!!process.env.TRAVIS_BUILD_NUMBER||!!process.env.BITBUCKET_BUILD_NUMBER||!!process.env.BITBUCKET_COMMIT||!!process.env.CODEBUILD_BUILD_ID||!!process.env.TF_BUILD||!!process.env.BUILD_BUILDID||!!process.env.AGENT_ID||!!process.env.BUILDER_SA_EMAIL||!!process.env.HEROKU_TEST_RUN_ID||!!process.env.CI_NODE_INDEX||!!process.env.TEAMCITY_VERSION||!!process.env.BUILD_VCS_NUMBER||!!process.env.BUILDKITE||!!process.env.BUILDKITE_BUILD_NUMBER||!!process.env.APPVEYOR||!!process.env.APPVEYOR_BUILD_NUMBER||!!process.env.DRONE||!!process.env.DRONE_BUILD_NUMBER||!!process.env.SHIPPABLE||!!process.env.BUILD_URL||!!process.env.SEMAPHORE||!!process.env.SEMAPHORE_EXECUTABLE_UUID||!!process.env.WOODPECKER||!!process.env.CI_BUILD_NUMBER||!!process.env.WERCKER_MAIN_PIPELINE_STARTED||!!process.env.BUDDY_EXECUTION_ID;import{confirm as GN,input as HN}from"@inquirer/prompts";import{existsSync as oge,mkdirSync as ige,statSync as VN}from"fs";import Io,{supportsColor as zN}from"chalk";import{Console as Xb}from"console";import{format as Yi}from"util";var em=class extends Error{constructor(e,t,n){let o=Error.stackTraceLimit;n&&(Error.stackTraceLimit=Math.max(n,o||10)),super(e),Error.captureStackTrace&&Error.captureStackTrace(this,t),Error.stackTraceLimit=o}},Al=class r extends Xb{_buffer=[];_groupDepth=0;Console=Xb;constructor(){super({write:e=>(r.write(this._buffer,"log",e),!0)})}static write(e,t,n,o=2){let i=new em(void 0,r.write).stack;if(!i)return e;let a=i.split(`
3942
+ `&&(i=l),r.slice(o,i)}function Qt(r){let e=typeof r=="string"?r:r.toString();return`[${_r}="${e}"]`}import{execSync as PN}from"child_process";import{randomUUID as hp}from"crypto";import{diff as fp}from"deep-object-diff";import{existsSync as Fn,mkdirSync as ON,readFileSync as LN,readdirSync as NN,rmSync as DN,statSync as HT,writeFileSync as kN}from"fs";import{Jimp as VT}from"jimp";import UN from"js-beautify";import{cloneDeep as ko}from"lodash-es";import FN from"mime";import{homedir as Uo,platform as Ol}from"os";import{basename as BN,extname as zN,join as yr,resolve as GN}from"path";import{chromium as WT,devices as HN}from"playwright";import{addExtra as VN}from"playwright-extra";import jN from"puppeteer-extra-plugin-recaptcha";import{v4 as WN}from"uuid";import{rmSync as aT}from"fs";import{basename as _L,join as ML}from"path";import{errors as IL}from"playwright-core";var Bb=new Set(["about:blank","chrome-error://chromewebdata/"]);var Hd=["button","image","generic","graphics-symbol","tab","link","menuitem","group"],Vd=1e4,na=500;import{mkdirSync as tL,rmSync as zb,statSync as rL}from"fs";import*as qd from"node:fs";import nL from"nodejs-file-downloader";import{tmpdir as oL}from"os";import en,{basename as iL,dirname as aL}from"path";var Kd="file://",$d=en.join(oL(),"momentic","downloads"),Wd=1e4,sL=50*1024*1024;async function Gb(r){let{uri:e}=r;if(e.startsWith(Kd))return cL(r);if(e.startsWith("http"))return dL(r);if(Ah)return uL(r);throw new w("UserConfigurationError","The source URI for the file upload step must be a valid URL or a previously downloaded file beginning with 'file://'")}function lL(r,e){let t=en.join($d,r,e.slice(Kd.length)),n=en.join($d,r),o=t.startsWith(n);if(!qd.existsSync(t)||!o)throw new w("UserConfigurationError",`The referenced file (${e}) does not exist. Please make sure that it has been downloaded successfully.`);return t}async function cL({uri:r,orgId:e}){let t=lL(e,r);return{filePath:t,cleanup:()=>{zb(aL(t),{recursive:!0,force:!0})}}}async function uL({uri:r}){let e=en.resolve(r);if(!qd.existsSync(e))throw new w("UserConfigurationError",`The referenced file (${r}) does not exist on disk. Please make sure that it has been downloaded successfully.`);return{filePath:e,cleanup:()=>{}}}async function dL({uri:r,logger:e,orgId:t}){let n=new URL(r);n.search&&(n.search="");let o=iL(n.href),i=Xd(o),a=en.extname(i);if(Sh.includes(a))throw new Error(`Downloading files with extension ${a} is not allowed.`);let l=Yd(t),c=new nL({url:r,fileName:i,directory:l,maxAttempts:2,headers:{"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.82 Safari/537.36"},timeout:Wd}),{downloadStatus:s,filePath:u}=await B(c.download(),{milliseconds:Wd,message:`Download timed out after ${Wd}ms`});if(s!=="COMPLETE")throw new Error(`Download ended in non-success status: ${s}`);if(!u)throw new Error("File path of successfully downloaded file was empty");let p=rL(u).size;if(p>sL)throw new Error("File size exceeds the maximum limit of 50MB");e.info({fileSizeInBytes:p,filePath:u,fileName:i},"Downloaded file to disk");let m;return{filePath:u,cleanup:()=>{clearTimeout(m),m=setTimeout(()=>zb(l,{recursive:!0,force:!0}),10*60*1e3)}}}function Hb(r,e){return`${Kd}${r}/${e}`}function Yd(r){let e=Math.random().toString(36).substring(4),t=en.join($d,r,e);return tL(t,{recursive:!0}),t}function Xd(r){let e=en.extname(r),t=en.basename(r,e);return r=(t.length>100?t.slice(t.length-100):t)+e,r=r.trim().replaceAll(" ","_"),r}async function Mr(r,e){try{return await r.evaluate(n=>window.serializeElementOnlyWithText?.(n,{truncateToLength:500}),void 0,{timeout:1e3})}catch(t){e.debug({err:t},"Failed to get HTML from locator for Playwright error translation");return}}var Al=class{limit;windowMs;userActions;constructor(e,t){this.limit=e,this.windowMs=t,this.userActions=new Map}_cleanup(e,t="DEFAULT_USER"){let n=Date.now(),o=`${t}:${e}`;if(this.userActions.has(o)){let a=this.userActions.get(o)?.filter(l=>n-l<=this.windowMs)??[];a.length>0?this.userActions.set(o,a):this.userActions.delete(o)}}increment(e,t="DEFAULT_USER"){let n=Date.now(),o=`${t}:${e}`;this._cleanup(t,e),this.userActions.has(o)||this.userActions.set(o,[]);let i=this.userActions.get(o);return i.length>=this.limit?!0:(i.push(n),!1)}};async function Vb(r,e){let t=r.evaluate(async()=>{let i=window,a={};try{let l=await indexedDB.databases();for(let c of l){if(!c.name)continue;let s=await i.exportIdbToObject?.(c.name,c.version);s&&(a[c.name]=s)}return[a,void 0]}catch(l){return[void 0,l.message]}}),[n,o]=await B(t,{milliseconds:3e3});return o&&e.warn({err:o},"Failed to fetch indexedDB data"),n}async function jb(r,e,t){if(e){t.debug("Importing indexedDB data");try{let n=r.evaluate(async o=>{let i=window;for(let[a,l]of Object.entries(o))await i.importObjectToIdb?.(a,l)},e);await B(n,{milliseconds:3e3})}catch(n){t.warn({err:n},"Failed to import indexedDB data")}}}async function Wb(r,e){try{let t=r.evaluate(async()=>{window.localStorage.clear(),window.sessionStorage.clear(),await indexedDB.databases().then(n=>{n.forEach(o=>{o.name&&indexedDB.deleteDatabase(o.name)})})});await B(t,{milliseconds:3e3})}catch(t){e.debug({err:t},"Failed clearing index db data, continuing...")}}async function $b(r,e,t,n,o){try{await pL(r,e,t,n)}catch(i){o.error({err:i,tabIndex:e},"Error handling new console log")}}async function pL(r,e,t,n){let o=n.text();o.length>na&&(o=o.slice(0,na)+"...(TRUNCATED)");let i=[];for(let a of n.args())try{let l=await a.jsonValue(),c=JSON.stringify(l);c.length>na?i.push(c.slice(0,na)+"...(TRUNCATED)"):(typeof l!="object"||Object.keys(l).length>0)&&i.push(l)}catch{}Jd(r,t,e,{url:r.url(),location:n.location(),type:n.type(),text:n.text(),args:i})}function Jd(r,e,t,n){let o=Date.now(),i=e.logsPerPage;if(i.length<=t||i[t]===void 0){i[t]=[];for(let a=0;a<t;a++)i[a]===void 0&&(i[a]=[])}i[t].length>Vd&&(i[t]=i[t].slice(Math.floor(Vd/2)),i[t]?.push({url:r.url(),timestamp:o,type:"warning",text:"[MOMENTIC] Truncated console logs due to buffer overflow",tabIndex:t})),i[t].push({...n,tabIndex:t,timestamp:o})}async function Wt({fn:r,codePath:e,logObject:t,signal:n,logger:o}){n?.throwIfAborted();let i=Date.now(),a=await Ou({promiseGenerator:r,signal:n,codePath:e,logger:o}),l=Date.now();return t[e]=l-i,a}import mL from"truncate-json";var gL="[redacted due to size]",qb=5e3,hL=5e3;async function Yb(r,e,t){let n=new Date().toISOString();e.harPages||(e.harPages={}),e.harPages[r]={id:r,startedDateTime:n,title:void 0,pageTimings:{}}}async function Qd(r,e){let t=e.timing(),n=new URL(e.url()),o=[...n.searchParams.entries()].map(([l,c])=>({name:l,value:c})),i={...await Jb(e),url:n.toString(),method:e.method(),queryString:o,postData:await SL(e)};return{pageref:r,_resourceType:e.resourceType(),startedDateTime:new Date().toISOString(),request:i,timings:Qb(t).timings}}async function Xb(r,e,t){await t.finished();let n={};try{n=await TL(t)}catch{}let o={...await Jb(t),status:t.status(),statusText:t.statusText(),content:n,redirectURL:t.headers().location,_mocked:!1};r.response=o;let i;try{i=await e.sizes(),r.request.bodySize=i.requestBodySize,r.request.headersSize=i.requestHeadersSize}catch{}r.response&&i&&(r.response.bodySize=i.responseBodySize,r.response.headersSize=i.responseHeadersSize,r.response.content.size=i.responseBodySize);let a=e.timing();r.startedDateTime=new Date(a.startTime).toISOString();let{timings:l,total:c}=Qb(a);r.time=c,r.timings=l}function oa(r,e,t){r.harEntries||(r.harEntries={}),r.harEntries[t]=e}function Kb(r){try{return new Date(r).toISOString()}catch{return}}function fL(r){let e={name:"",value:""},t=!0;for(let n of r.split(/; */)){let o=n.indexOf("="),i=o!==-1?n.substring(0,o).trim():n.trim(),a=o!==-1?n.substring(o+1,n.length).trim():"";if(t){t=!1,e.name=hr(i),e.value=hr(a);continue}i==="Domain"&&(e.domain=hr(a)),i==="Expires"&&(e.expires=Kb(a)),i==="HttpOnly"&&(e.httpOnly=!0),i==="Max-Age"&&(e.expires=Kb(Date.now()+ +a*1e3)),i==="Path"&&(e.path=hr(a)),i==="Secure"&&(e.secure=!0)}return e}async function Jb(r){let e=await r.allHeaders(),t=e.cookie?.split(";").map(fL)??[];return{headers:Object.entries(e).map(([n,o])=>({name:hr(n),value:hr(o)})),cookies:t}}async function SL(r){let e=r.postData();if(!e)return;let t=await r.headerValue("content-type"),n={mimeType:t??"application/octet-stream",text:hr(e),params:[]};if(t==="application/x-www-form-urlencoded"){let o=new URLSearchParams(e.toString());for(let[i,a]of o.entries())n.params.push({name:hr(i),value:a?hr(a):void 0})}return n}var yL=["text"],EL=["json","xml","html","javascript"];function bL(r){let[e,t]=r.split("/");return e?yL.includes(e)?!0:t?!!EL.some(n=>t?.includes(n)):!1:!1}async function TL(r){let t=((await r.headerValue("content-type"))?.toLowerCase()??void 0)?.split(";")[0]??void 0,n={mimeType:t,encoding:await r.headerValue("content-encoding")??void 0};return t&&bL(t)&&(n.text=hr(await r.text())),n}function hr(r){try{let e=JSON.parse(r),{jsonString:t}=mL(r,hL);return t}catch{return r.length>qb?r.slice(0,qb)+gL:r}}function Dn(r){return r<0?0:r}function Qb(r){return{timings:{blocked:Dn(r.domainLookupStart),dns:Dn(r.domainLookupEnd-r.domainLookupStart),connect:Dn(r.connectEnd-r.connectStart),send:Dn(r.responseStart-r.requestStart),wait:0,receive:Dn(r.responseEnd-r.responseStart),ssl:Dn(r.connectEnd-r.secureConnectionStart)},total:Dn(r.responseEnd)}}function Zb(){return async r=>{let{fragment:e,code:t,context:n}=r,{env:o}=n||{},i=Object.getPrototypeOf(async function(){}).constructor;return{result:await Promise.resolve(new i("env",e?`return ${t}`:t)(o))}}}async function je({root:r,fn:e,arg:t,timeout:n,waitForPageLoad:o,codePath:i}){return await o(),await B(r.evaluate(e,t),{milliseconds:n,message:`Timed out ${i} after ${n}ms. This indicates that either the page is unresponsive or your machine is severely resource constrained.`})}function Zd(){return window.lastCursorPos}import{errors as vL}from"playwright-core";async function kn({func:r,action:e,logger:t,callbacks:n,retryTimeoutMs:o,targetingResult:i}){let a=Date.now(),l;for(;Date.now()-a<o;)try{return await r(i)}catch(c){if(c instanceof vL.TimeoutError)t.warn({err:c,rootUrl:(await n.state.getRoot()).url()},`Encountered Playwright error while performing ${e}`),l=await AL(c,i.locator,n,t);else throw c}throw l instanceof w?l:new w("ActionFailureError",`Failed to interact with targeted element. Error: ${l.message}`,{errOptions:{cause:l}})}async function AL(r,e,t,n){return r.message.includes("attempt #")?RL(r,e,t,n):wL(r)}async function RL(r,e,t,n){let o=r.message.split(/- retrying \w+ action, attempt #\d+/).filter(c=>c.length>0);if(!o.length)return n.warn({err:r},"Failed to parse Playwright error message for translation, returning raw message"),r;let i=o.length>2?o[o.length-2]:o[0];i=i.replace(/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g,"").replaceAll(" - ","").trim().replaceAll(`
3943
+ `,";").replace(/\s+/g," ");let a="",l=await Mr(e,n);if(l&&(a=`Target element HTML: ${St(l,100,!0)}`),i.includes("element is not enabled"))return new w("ActionFailureError",`The element you attempted to interact with was disabled for the entire timeout duration. Please explicitly wait for the element to be enabled, change the element description to target an interactive element, or turn on the 'disable stability checks' option. ${a}`,{errOptions:{cause:r}});if(i.includes("intercepts pointer events")){let c="",s=i.match(/<.*?data-momentic-id="(\d+)".*?intercepts pointer events/)?.[1];if(s){let u=(await t.state.getRoot()).locator(Qt(s)),d=await Mr(u,n);d&&(c=`Covering element HTML: ${St(d,100,!0)}`)}return new w("ActionFailureError",`The element you attempted to interact with was covered by another element such as dropdown, popup, or dialog for the entire timeout duration. Please add a step to hide the covering element or turn on the 'disable stability checks' option. ${a}
3944
+ ${c}`,{errOptions:{cause:r}})}if(i.includes("element is not visible")){let c="The element you attempted to interact with has no bounding box or is explicitly hidden.";try{let s=await e.boundingBox({timeout:3e3});s?s.height===0?c="The element you attempted to interact with has zero height.":s.width===0&&(c="The element you attempted to interact with has zero width."):c="The element you attempted to interact with has no bounding box."}catch{}return new w("ActionFailureError",`${c} Please explicitly wait for the element to be visible or turn on the 'disable stability checks' option. ${a}`,{errOptions:{cause:r}})}return i.includes("element is outside of the viewport")?new w("ActionFailureError",`The element requested was outside of the browser viewport for the entire duration of the action. Please ensure you are not using non-standard zoom settings and the element is visible on the page. ${a}`):r}function wL(r){let e=r.message;if(e.includes("waiting for locator")&&e.includes("data-momentic-id")&&!e.match(/attempting \w+ action/)&&!e.includes("locator.evaluate"))throw new w("ActionFailureError",`Interacting with the element timed out. This is usually caused by the web page itself performing too many CPU-intensive operations or a lack of resources on your machine. Error: ${e}`,{errOptions:{cause:r}});return r}async function eT(r){try{return await CL(r)}catch(e){r.logger.warn({err:e},"Failed to transform locator for Chakra click, continuing...");return}}async function CL({locator:r,logger:e}){let[t,n]=await r.evaluate(c=>[c.id,c.tagName.toLowerCase()],{timeout:1e3}),o=await Mr(r,e),i=await r.boundingBox({timeout:1e3});if(i===null){e.warn({elementDisplayString:o},"Attempting to click on element with no bounding box, not performing Chakra redirection");return}if(i.width>5||i.height>5||n!=="input")return;if(t)try{let c=r.page().locator(`label[for=${JSON.stringify(t)}]`);return await c.waitFor({state:"visible",timeout:1e3}),{locator:c,relativePoint:void 0}}catch{}let a=await r.evaluate(c=>{let s=window,u=c.parentElement;if(!u)return{type:"error",error:"Input click target has no parent for redirection"};let d=c.getBoundingClientRect(),p=u.getBoundingClientRect();if(p.width===0||p.height===0)return{type:"error",error:"Parent element has no width or height"};let m={x:Math.min(Math.max(1,d.left-p.left),p.width-1),y:Math.min(Math.max(1,d.top-p.top),p.height-1)},g=s._MOMENTIC_FEATURE_FLAGS?.[vl],h=c.getAttribute(_r),f=!g&&h?Qt(h):s.getMPath?.(c)?.join(" >");return f?{type:"result",selector:f,relativePoint:m,serializedForm:u.outerHTML.slice(0,500)}:{type:"error",error:"Could not generate selector for parent element"}},{timeout:1e3});if(a.type==="error")throw new Error(a.error);let l=r.page().locator(a.selector);return await l.waitFor({state:"visible",timeout:1e3}),e.info({parentElementResult:a,originalElementDisplayString:o},`Redirected click to parent element with selector: ${a.selector}`),{locator:l,relativePoint:a.relativePoint}}var rT=["date","datetime-local","month","time","week"],tT={date:/^\d{4}-\d{2}-\d{2}$/,"datetime-local":/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}$/,month:/^\d{4}-\d{2}$/,time:/^\d{2}:\d{2}$/,week:/^\d{4}-W\d{2}$/};async function nT(r){try{await B(xL(r),{milliseconds:3e3})}catch(e){r.logger.warn({err:e},"Failed to transform native datetime input, continuing...")}}async function xL({root:r,text:e,options:t,logger:n,callbacks:o}){let i=(await je({root:r,fn:()=>document.activeElement?.getAttribute("type")??"",timeout:1e3,arg:void 0,waitForPageLoad:o.waitForPageLoad,codePath:"transforming native datetime input"})).toLowerCase();if(!tT[i])return;tT[i].test(e)&&n.warn(`Detected datetime input (${e}) in normalized format - this may fail to fill correctly as it is not how the user would input the value`),t.clearContent=!1,n.info("Transforming datetime input to use sequential key presses")}import{z as wt}from"zod";var oT=wt.object({doubleClick:wt.boolean().optional(),rightClick:wt.boolean().optional(),force:wt.boolean().optional(),waitForDownload:wt.boolean().optional(),delayMs:wt.number().optional(),downloadTimeoutMs:wt.number().optional(),relativePosition:wt.object({x:wt.number(),y:wt.number()}).optional()}),jie=wt.object({repeat:wt.number().optional(),convertMeta:wt.boolean().optional().describe("misleading name due to backcompat. converts keyshortcuts + meta/control to platform-specific combos. defaults to true"),delayMs:wt.number().optional()});async function Rl({locator:r,callbacks:e,logger:t,timeoutMs:n=1e3}){try{await ep(e,n);let o=r.evaluate(i=>{let a=window;a.momenticIsEligible=d=>{let m=window.getComputedStyle(d,null).getPropertyValue("display");if(m==="none"||m==="contents")return!1;let g=d.getBoundingClientRect();return!(!g.height||!g.width)},a.removeHighlightTimers=a.removeHighlightTimers||[],a.removeHighlightFunctions=a.removeHighlightFunctions||{};let l=0;for(;!a.momenticIsEligible(i)&&l<3;){if(!i.parentElement)throw new Error("No eligible non-empty parent found for highlighting");i=i.parentElement,l++}let c=i.style.getPropertyValue("outline"),s=i.style.getPropertyPriority("outline");i.style.setProperty("outline","5px dashed rgb(255, 0, 153)","important");let u=`momentic${Math.floor(Math.random()*1e7)}`;a[u]=()=>{i.style.removeProperty("outline"),i.style.setProperty("outline",c,s),i.getAttribute("style")||i.removeAttribute("style")},a.removeHighlightTimers.push(setTimeout(()=>{a[u](),a.removeHighlightFunctions?.[u]&&delete a.removeHighlightFunctions[u]},5e3)),a.removeHighlightFunctions[u]=a[u]},void 0,{timeout:n});return await B(o,{milliseconds:n}),!0}catch(o){return t.debug({err:o},"Failed to add node highlight, a page navigation likely occurred. This is non-fatal for tests."),!1}}async function ep(r,e=1e3){let t=await r.state.getRoot();await je({root:t,fn:()=>{let o=window,i=o.removeHighlightTimers||[];for(;i.length;){let a=i.pop();clearTimeout(a)}Object.values(o.removeHighlightFunctions??{}).forEach(a=>{a()})},timeout:e,arg:void 0,waitForPageLoad:r.waitForPageLoad,codePath:"removing element highlights"})}async function tp(r){let e=!!r.browserCallbacks.state.userBrowserSettings.visualActions;return kn({action:"clicking element",targetingResult:r.targetingResult,logger:r.logger,retryTimeoutMs:r.retryTimeoutMs,callbacks:r.browserCallbacks,func:async t=>sT({...r,targetingResult:t,useVisualClick:e})})}async function PL(r,e){let{redirectionAttempts:t=0}=e;if(t>=2)throw r;try{return await OL(r,e)}catch(n){throw e.redirectionAttempts===0?(e.logger.error({redirectionAttemptError:n,originalError:r},"Error handling click error, rethrowing original error"),r):n}}async function OL(r,e){let{logger:t,redirectionAttempts:n=0}=e,o=e.targetingResult.locator;if(r.message.includes("label")&&r.message.includes("for=")&&r.message.includes("intercepts pointer events")){let i=await o.getAttribute("id",{timeout:1e3});if(!i)throw r;let a=o.page().locator(`[for=${JSON.stringify(i)}]`);return await a.waitFor({state:"visible",timeout:1e3}),t.warn({err:r},"Attempting locator redirection due to input being covered by label"),sT({...e,targetingResult:{locator:a},redirectionAttempts:n+1})}else throw t.error({err:r},"Click error does not match any known recoverable patterns, rethrowing"),r}async function LL(r){let{browserCallbacks:e,logger:t,targetingResult:n,position:o,options:i}=r,a=await e.state.getRoot(),l=a&&a!==n.locator.page()&&"frameElement"in a?await a.frameElement():null,c;try{c=l?await wn({promiseGenerator:async()=>l.boundingBox(),timeoutMs:3e3,logger:t}):null}catch(g){throw new w("UserInfrastructureError",`The frame containing the element Momentic was instructed to interact with was removed. Error: ${g.message}`)}finally{await l?.dispose()}let s=Date.now(),{clickX:u,clickY:d,reason:p}=await kL({frameCoordinates:c,logger:t,targetingResult:n,position:o,options:i}),m=oT.safeParse(i);t.info({frameCoordinates:c,position:o,options:m.success?m.data:void 0,clickLocation:{clickX:u,clickY:d,reason:p},duration:Date.now()-s},"Visual click")}async function NL(r){let{actionSource:e,targetingResult:t,options:n,logger:o}=r,i=r.targetingResult.locator,a=n?.relativePosition??r.position;if(e==="click"&&!a){let c=await eT({locator:i,logger:o});c&&(i=c.locator,a=c.relativePoint??a)}let l=n?.force||t.hints?.force||!1;try{n?.doubleClick?await i.dblclick({button:n.rightClick?"right":"left",timeout:3e3,position:a,delay:n?.delayMs??25,force:l}):await i.click({button:n?.rightClick?"right":"left",timeout:3e3,position:a,delay:n?.delayMs??25,force:l})}catch(c){let s=c;if(FL(s))o.warn({err:s},"Click action timed out while waiting for navigation after completion, continuing...");else return o.error({err:s},"Error clicking on locator, attempting to recover..."),PL(s,{...r,targetingResult:{...i,locator:i}})}}async function sT(r){let{options:e,logger:t,browserCallbacks:n,controllerCallbacks:o,useVisualClick:i,targetingResult:a}=r,l;e?.waitForDownload&&(l=(async()=>{let c=e.downloadTimeoutMs??3e4;try{return await a.locator.page().waitForEvent("download",{timeout:c})}catch(s){return s instanceof IL.TimeoutError?new w("ActionFailureError",`Download did not complete in ${c}ms`):new w("ActionFailureError",`Download failed: ${s.message}`)}})());try{await Rl({locator:a.locator,callbacks:n,logger:t,timeoutMs:1e3})}catch(c){t.warn({err:c},"Error highlighting locator in click, continuing...")}if(i?await LL(r):await NL(r),e?.waitForDownload)if(l){if(!o?.createIsolatedFolder)throw new w("InternalWebAgentError","Cannot wait for download without a callback to create an isolated folder");t.info("Waiting for download to start and complete");let c=await B(l,{milliseconds:e.downloadTimeoutMs??3e4});if(c instanceof Error)throw c;return{downloadedFile:await UL(c,o.createIsolatedFolder,t)}}else throw new Error("No download promise or error but the step requested to wait for a download")}async function DL(r,e){if(e.hints?.clickableXY){let i=(r?.x??0)+e.hints.clickableXY.x,a=(r?.y??0)+e.hints.clickableXY.y;return[{x:i,y:a},"targeting hint"]}let t=await e.locator.boundingBox({timeout:3e3});if(!t)throw new w("ActionFailureError","Element does not have a bounding box");let n=t.x+t.width/2,o=t.y+t.height/2;return[{x:n,y:o},"halfway point"]}async function kL({frameCoordinates:r,logger:e,options:t,targetingResult:n,position:o}){let i,a,l;if(o){let d=await n.locator.boundingBox({timeout:3e3});i=(r?.x??0)+(d?.x??0)+o.x,a=(r?.y??0)+(d?.y??0)+o.y,l="predefined position"}else{let[d,p]=await DL(r,n);i=d.x,a=d.y,l=p}let c=n.locator.page(),s=t?.rightClick?"right":"left",u=t?.delayMs??25;return t?.doubleClick?await c.mouse.dblclick(i,a,{button:s,delay:u}):await c.mouse.click(i,a,{button:s,delay:u}),{clickX:i,clickY:a,reason:l}}async function UL(r,e,t){t.info("Download detected, saving file to disk");let n=await r.path(),o=Xd(r.suggestedFilename()),i=e();await r.saveAs(ML(i,o)),aT(n,{force:!0}),setTimeout(()=>{aT(i,{recursive:!0,force:!0})},5*60*1e3);let a=Hb(_L(i),o);return t.info({uri:a,downloadFolder:i},"Saved download to isolated folder"),a}function FL(r){return r.message.includes("locator.click: Timeout")&&r.message.includes("click action done")}import{platform as BL}from"os";var zL={goToNextWord:{win32:"Control+ArrowRight",darwin:"Alt+ArrowRight",linux:"Control+ArrowRight"},goToPreviousWord:{win32:"Control+ArrowLeft",darwin:"Alt+ArrowLeft",linux:"Control+ArrowLeft"},selectNextWord:{win32:"Control+Shift+ArrowRight",darwin:"Alt+Shift+ArrowRight",linux:"Control+Shift+ArrowRight"},selectPreviousWord:{win32:"Control+Shift+ArrowLeft",darwin:"Alt+Shift+ArrowLeft",linux:"Control+Shift+ArrowLeft"},selectToStartOfLine:{win32:"Shift+Home",darwin:"Meta+Shift+LeftArrow",linux:"Shift+Home"},selectToEndOfLine:{win32:"Shift+End",darwin:"Meta+Shift+RightArrow",linux:"Shift+End"},deleteNextWord:{win32:"Control+Delete",darwin:"Alt+Fn+Delete",linux:"Control+Delete"},deletePreviousWord:{win32:"Control+Backspace",darwin:"Alt+Delete",linux:"Control+Backspace"}};function GL(){let r=BL();return r==="win32"?"win32":r==="darwin"?"darwin":"linux"}function lT(r){return JSON.stringify(r.split("+").sort())}function wl(r){let e=GL(),t=lT(r);for(let n of Object.values(zL))if(Object.values(n).some(o=>lT(o)===t))return n[e];return process.platform==="darwin"?r=r.replaceAll("Control","Meta"):r=r.replaceAll("Meta","Control"),r}async function rp({frame:r,page:e,deltaX:t,directionX:n,deltaY:o,directionY:i,signal:a,callbacks:l,logger:c}){if(!t&&!o)return;let s=n==="left"?-1:1,u=i==="up"?-1:1;if(r)await je({root:r,fn:([d,p,m,g])=>window.scrollTo(window.scrollX+(d??window.innerWidth)*m,window.scrollY+(p??window.innerHeight)*g),arg:[t,o,s,u],waitForPageLoad:l.waitForPageLoad,timeout:2e3,codePath:"scrolling page"});else{let d=e.viewportSize()||Br,p=await je({root:e,fn:()=>document.body.scrollHeight,arg:void 0,waitForPageLoad:l.waitForPageLoad,timeout:2e3,codePath:"computing page height"}),[m,g,h]=await je({root:e,fn:()=>{let f=document.activeElement;if(!f)return[void 0,void 0,void 0];let E=f.getBoundingClientRect();return[f.scrollTop,E.x,E.y]},arg:void 0,waitForPageLoad:l.waitForPageLoad,timeout:2e3,codePath:"computing active element position"});await e.mouse.wheel((t??d.width)*s,(o??d.height)*u);try{let f=Date.now();for(;Date.now()-f<2e3;){a?.throwIfAborted();let E=await B(e.evaluate(()=>document.body.scrollHeight),{milliseconds:1e3}),[b,v,A]=await B(e.evaluate(()=>{let T=document.activeElement;if(!T)return[void 0,void 0,void 0];let x=T.getBoundingClientRect();return[T.scrollTop,x.x,x.y]}),{milliseconds:1e3});if(E===p&&b===m&&v===g&&A===h)break;p=E,m=b,g=v,h=A,await $(500)}}catch(f){c.warn({err:f},"Failed to wait for scroll to complete, continuing...")}}}async function np(r,e){let t,n;for(let o=0;o<4;o++)try{return t=r.pages(),await Promise.all(t.map(async i=>{let a="";try{a=e?.getTitles?await i.title():""}catch{a="Unknown page"}return{title:a,url:i.url()}}))}catch(i){n=i,await $(500)}throw new Error(`Failed to get tab titles after all retries: ${n?.message}`)}import{randomUUID as YL}from"crypto";import{cloneDeep as ap}from"lodash-es";function tn(r,e){let t=r.findIndex(n=>n===e);if(!(t===-1||!r[t+1]))return r[t+1]}import{createHash as HL}from"crypto";var VL="v1";function op(r,e){if(r.tagName.toLowerCase()==="svg"&&!WL(r))try{let t=cT(r,e),n=jL(JSON.stringify(t));return{version:VL,json:t,hash:n}}catch{return}}function jL(r){return HL("md5").update(r).digest("hex")}function cT(r,e){let t=r.tagName.toLowerCase(),n=$L(r);if(t==="image"&&n["xlink:href"])throw new Error("Image tags within SVGs are not supported");let o={type:t,props:n,children:[]};for(let i of r.childrenBackendIds){let a=e.backendIdToNode[i];if(a&&a.nodeType===1){let l=cT(a,e);l&&o.children.push(l)}}return o}function WL(r){let e=r.computedStyles.display,t=r.computedStyles.visibility,n=r.computedStyles.opacity;return e==="none"||t==="hidden"||n==="0"}function $L(r){let e={},t=r.attributes;for(let n of Object.keys(t))jt.visualAttributesForSvgSerialization.includes(n)&&(e[n]=t[n]);return t.id&&r.tagName.toLowerCase()!=="svg"&&(e.id=t.id),e}var Un={r:147,g:196,b:125,a:.55},dT={showRulers:!1,showStyles:!1,showExtensionLines:!1,contrastAlgorithm:"aa",contentColor:Un,paddingColor:Un,borderColor:Un,marginColor:Un,eventTargetColor:Un,shapeColor:Un,shapeMarginColor:Un,showInfo:!0,showAccessibilityInfo:!0};function pT({snapshot:r,devicePixelRatio:e,computedStylesToFetch:t,logger:n}){let o=r.strings,i=r.documents,a={},l={},c={roots:[],backendIdToNode:a,frameIndexToIframeNode:l};return i.forEach((s,u)=>{let d=qL({allDocuments:i,stringConstants:o,computedStylesToFetch:t,devicePixelRatio:e,frameIndex:u,backendIdToNode:a,frameIndexToIframeNode:l,logger:n});c.roots.push(d)}),c}function qL({allDocuments:r,stringConstants:e,computedStylesToFetch:t,devicePixelRatio:n,frameIndex:o,frameIndexToIframeNode:i,backendIdToNode:a,logger:l}){let c=r[o],s=c.layout,u={};s.nodeIndex.forEach((N,U)=>{u[N]=U});let d=s.styles,p=s.bounds??[],m=c.nodes,g=m.contentDocumentIndex??{index:[],value:[]},h=m.backendNodeId??[],f=m.attributes??[],E=m.parentIndex??[],b=m.nodeName??[],v=m.nodeType??[],A=m.pseudoType??{index:[],value:[]},T=m.inputChecked??{index:[]},x=e[c.frameId];for(let N=0;N<h.length;N++){let U=h[N],Y=v[N],ke=f[N]??[],te=E[N]!==void 0&&E[N]>=0?E[N]:void 0,ie=te!==void 0?h[te]:void 0,ut=ie!==void 0?a[ie]:void 0,M=A.index.indexOf(N),V=M!==-1?e[A.value[M]]:void 0,re=u[N],Ce;re?Ce=p[re]??[]:Ce=[];let Me=b[N]!==void 0?e[b[N]]?.toLowerCase():void 0;if(!Me){l.warn({backendNodeId:U,frameId:x,frameIndex:o,nodeBounds:Ce},"DOM node has no tag name");continue}let Ae={backendNodeId:U,psuedoType:V,nodeType:Y,frameIndex:o,parentFrameId:x,ownedFrameId:void 0,bounds:{x:Ce[0]??null,y:Ce[1]??null,width:Ce[2]??null,height:Ce[3]??null},computedStyles:{},attributes:{},parentBackendNodeId:ie??null,tagName:Me,parent:ut??void 0,childrenBackendIds:[],momenticIgnored:void 0,mPathSelector:void 0};ut&&ut.childrenBackendIds.push(U);let xt=g.index.indexOf(N);if(xt!==-1){let Re=g.value[xt];i[Re]=Ae;let We=r[Re]?.frameId;Ae.ownedFrameId=We!==void 0?e[We]:void 0}for(let Re of Object.keys(Ae.bounds)){let We=Re;Ae.bounds[We]!==null&&(Ae.bounds[We]/=n)}let dt=re!==void 0?d[re]??[]:[];for(let Re=0;Re<dt.length&&!(Re>=t.length);Re++){let We=dt[Re];if(We===void 0||isNaN(We))continue;let an=e[We];if(an===void 0)continue;let vr=t[Re];Ae.computedStyles[vr]=an}for(let Re=0;Re<ke.length;Re+=2){let We=ke[Re],an=ke[Re+1];if(!We||!an)continue;let vr=e[We],Qo=e[an];!vr||!Qo||(Ae.attributes[vr]=Qo)}T.index.includes(N)&&(Ae.attributes.checked="true"),a[Ae.backendNodeId]=Ae}return a[h[0]]}function ip(r,e){if(r.mPathSelector)return r.mPathSelector;let t=r.parent,n;if(!t)n=r.tagName;else if(r.tagName==="body")n="body";else{let i=t.childrenBackendIds.filter(c=>e.backendIdToNode[c]?.nodeType===1&&!e.backendIdToNode[c]?.psuedoType).indexOf(r.backendNodeId),a=` > ${r.tagName}:nth-child(${i+1})`;n=`${ip(t,e)}${a}`}return r.mPathSelector=n,n}function uT(r,e){return r.parentBackendNodeId!==null?e.backendIdToNode[r.parentBackendNodeId]:r.frameIndex===0?void 0:e.frameIndexToIframeNode[r.frameIndex]}var KL=["html","#document","#document-fragment"];function mT({node:r,domGraph:e}){let t=[],n=r,o=uT(r,e);if(!o)return[r.tagName];let i=()=>{if(n=o,o=uT(o,e),!o&&n.frameIndex!==0)throw new Error("No parent node but not in main frame")},a=0;for(;o&&a<1e6;){if(a++,KL.includes(n.tagName)){i();continue}if(n.tagName==="body")t.push("body");else{let c=!1,s=1;for(let u=0;u<o.childrenBackendIds.length;u++){let d=o.childrenBackendIds[u],p=e.backendIdToNode[d];if(d===n.backendNodeId){t.push(`${n.tagName}:nth-child(${s})`),c=!0;break}else p?.nodeType===1&&!p.psuedoType&&s++}if(!c)throw new Error(`Could not find child (${n.tagName}) in parent's children list (${o.tagName})`)}i()}return t.reverse()}function gT(r,e){let t=r.locator("html"),n=[];for(let o=0;o<e.length;o++){let i=e[o];if(n.push(i),i.startsWith("iframe")){let a=n.join(" > ");n=[],o<e.length-1?t=t.frameLocator(a):t=t.locator(a)}}if(n.length&&(t=t.locator(n.join(" > "))),"owner"in t)throw new Error("Final locator from mpath is a frame locator");return t}async function hT(r,e){await r.send({method:"DOM.getDocument",params:{depth:0},timeout:2e3});let t=await r.send({method:"DOM.requestNode",params:{objectId:e},timeout:2e3}),o=(await r.send({method:"DOM.getAttributes",params:{nodeId:t.nodeId},timeout:2e3})).attributes,i=tn(o,_r);if(!i)throw new Error(`Could not find attribute ${_r} for object ${e}`);return i}var XL=["focusable","keyshortcuts","controls","live","relevant","orientation"],JL=["selected","readonly","modal","required","invalid"],QL=["id","name","role","content"],fT=["absolute","fixed","sticky"],ZL=["i"],eN=["path"],tN=["statictext","textbox","checkbox","combobox","iframe","rootwebarea","table","caption","columnheader","rowheader","gridcell","grid","row","rowgroup","cell","image","graphics-symbol","graphics-document","graphics-object","svgroot","button","link","list","listitem","tablist","tabpanel","tab","searchbox","menu","menubar","form","dialog","alertdialog","banner","navigation","main","menuitem","menuitemcheckbox","menuitemradio","option","radio","progressbar","switch","tree","treeitem","separator"],ET=["ariaHiddenElement","ariaHiddenSubtree","hiddenByChildTree","inertElement","inertSubtree","notRendered","notVisible"],bT=["activeAriaModalDialog","activeFullscreenElement","activeModalDialog"],rN=["menulistpopup","statictext","inlinetextbox"],nN=80,ST=100,TT=50,cp=["StaticText","ListMarker","RootWebArea","LineBreak","emphasis","::before","::after"],oN=["cite"],iN={LabelText:["label"],listitem:["li"],image:["img","svg"],link:["a"],RootWebArea:["#document"],paragraph:["p"],LineBreak:["br"],separator:["hr"],"graphics-symbol":["svg","rect"],gridcell:["td","th"],SvgRoot:["svg"],navigation:["nav"],cell:["td","th"],row:["tr"],list:["ul"],heading:["h1","h2","h3","h4","h5","h6"]},aN={name:!0,value:!0,title:!0,alt:!0,placeholder:!0,checked:!0,selected:!0,contenteditable:!0},yT={indentLevel:0},sp=class r{id;role;name;nameSources;tagName;content;properties;internalProperties;ignoredReasons;dataMomenticId;importantProperties;pathFromRoot;mPathSelector;parent;children;parentFrame;domNode;backendNodeId;ignoredByCDP;flagNotActionableNodes;constructor(e){if(this.id=e.id,this.role=e.role,this.name=e.name,this.nameSources=e.nameSources,this.content=e.content,this.properties={},this.pathFromRoot=e.pathFromRoot,this.children=e.children,this.backendNodeId=e.backendNodeID,this.ignoredByCDP=e.ignoredByCDP,this.internalProperties=e.internalProperties??{},this.parentFrame=e.parentFrame,this.ignoredReasons=e.ignoredReasons,this.importantProperties=e.importantProperties,this.flagNotActionableNodes=e.flagNotActionableNodes,e.properties&&e.properties.forEach(t=>{t.name==="keyshortcuts"?this.dataMomenticId=parseInt(t.value.value):this.properties[t.name]=t.value.value}),e.domNode){this.domNode=e.domNode,this.tagName=e.domNode.tagName||void 0;let t=e.domNode.attributes.id;this.name=this.name||e.domNode.attributes.name||(t&&t.length<TT?t:""),this.role=this.role||(e.domNode.attributes.role??""),uN(this.properties,e.domNode,e.importantProperties)}pN(this)}getSerializedFormWithContext(){return this.serialize({noId:!0,maxLevel:1,neighbors:1})}getNodeOnlySerializedForm(){return this.serialize({noId:!0,noChildren:!0,noContent:!0})}getLogForm(){return JSON.stringify({id:this.id,name:this.name??"",role:this.role??"",backendNodeId:this.backendNodeId})}isInteresting(e){if(this.domNode&&eN.includes(this.domNode.tagName)||this.domNode?.computedStyles.display==="contents"||this.ignoredReasons.some(n=>bT.includes(n)))return!1;if(e){if(Object.keys(this.domNode?.attributes??{}).some(o=>CT(o,e)))return!0;let n=this.domNode?.attributes.class?.split(" ");if(n&&n.length>0&&n.some(o=>xT(o,e))||e.styles?.some(o=>{let i=o.split(":");if(i.length!==2)return!1;let a=i[0]?.trim(),l=i[1]?.trim();if(a===void 0||l===void 0)return!1;let c=this.domNode?.computedStyles[a];return c!==void 0&&(c===l||l==="*")}))return!0}if(this.domNode&&ZL.includes(this.domNode.tagName)||tN.includes(this.role.toLowerCase())||this.role.toLowerCase()==="inlinetextbox"&&this.tagName||!this.properties.hidden&&(this.properties.focusable||this.properties.settable)||jt.alwaysInterestingTruthyPropertyNames.some(n=>!!this.properties[n]))return!0;let t=this.properties.class;return typeof t=="string"&&t.split(" ").some(n=>wT(n))?!0:this.children.every(n=>n.role==="StaticText")&&this.internalProperties?.inCodeMirrorEditor?!1:this.children.some(n=>n.role==="StaticText")||this.children.length>1&&this.children.some(n=>n.tagName==="input")?!0:this.domNode&&(this.domNode.bounds.x===null||this.domNode.bounds.y===null||!this.domNode.bounds.width||!this.domNode.bounds.height)?!1:!!this.name.trim()||!!this.content||Object.keys(this.properties).some(n=>n.startsWith("data"))}shouldSerializeBounds(){let e=this.domNode?.computedStyles.position;return!!(e&&(e==="absolute"||e==="fixed"||e==="sticky"))}isNotActionable(){return!!(this.domNode?.computedStyles.display==="contents"||this.domNode&&(this.domNode.bounds.x===null||this.domNode.bounds.y===null||!this.domNode.bounds.width||!this.domNode.bounds.height))}serialize(e=yT){let t=Object.assign({},yT,e),{indentLevel:n,noChildren:o,noProperties:i,noId:a,noContent:l,condensedMode:c}=t,s=ap(this.properties),u=" ".repeat(n),d=this.role||"",p=this.tagName??"unknown",m=this.name;d==="heading"&&m==="heading"&&(m=""),this.nameSources?.find(T=>!T.superseded&&T.type==="contents")&&this.children.length>0&&(m="");let h=this.nameSources?.find(T=>!T.superseded);if(h&&!h.nativeSource&&h.type==="relatedElement"){let T=h.attributeValue?.relatedNodes??[];T.length===1&&T[0].text&&T[0].text===m&&(m="")}let f=cp.includes(this.role)||oN.includes(this.tagName||"");if(this.role==="StaticText"||this.role==="ListMarker")return`${u}${m}
3945
+ `;let E=`${u}<${p}`;!a&&!f&&(E+=` id="${this.id}"`);let b=l??!1;if((s.multiline||s.contenteditable)&&this.children.length>0&&(b=!0),d&&d!=="generic"&&d!==p&&!(iN[d]??[]).includes(p)&&(E+=` role=${JSON.stringify(d)}`),m&&(E+=` name=${JSON.stringify(m)}`),this.content&&!b&&(E+=` content=${JSON.stringify(this.content)}`),this.flagNotActionableNodes&&this.tagName!=="#document"&&this.isNotActionable()&&(E+=` ${jt.ineligibleElementAttribute}`),this.shouldSerializeBounds()&&this.domNode?.bounds){let T=this.domNode.bounds,x=Math.round(T.x??0),N=Math.round(T.y??0),U=Math.round((T.x??0)+(T.width??0)),Y=Math.round((T.y??0)+(T.height??0));E+=` bounds=[${x} ${N} ${U} ${Y}]`}let v=Date.now();if(Object.keys(s).length>0&&!i){if(Date.now()-v>1e3)throw new Error(`Serialization for the HTML element with tag ${p} and internal ID ${this.id} took too long. Please ensure your machine has enough resources to run Momentic.`);Object.entries(s).forEach(([T,x])=>{if(!XL.includes(T)){{if(JL.includes(T)&&(!x||x==="false"))return;if(T==="value"&&b&&(s.type==="text"||this.role==="textbox"))return;if(T==="level"&&`${x}`=="1")return;if(T==="url"&&s.src&&p==="img")return;if(T==="url"&&s.href&&p==="a")return;if(T==="editable"&&x==="plaintext")return;if(T==="type"&&x===p)return;if(c&&!aN[T])return}typeof x=="string"?E+=` ${T}="${St(x,ST,!0)}"`:typeof x=="boolean"?x?E+=` ${T}`:E+=` ${T}={false}`:typeof x<"u"&&(E+=` ${T}={${St(JSON.stringify(x),ST,!0)}}`)}})}if(p==="::before"||p==="::after"){let T="";for(let x of this.children)T+=x.serialize({...e,indentLevel:n,neighbors:0});return T}let A=e.maxLevel!==void 0&&n/2>=e.maxLevel;if(this.children.length===0||o||A)E+=` />
3946
+ `;else{let T="";for(let N of this.children)T+=N.serialize({...e,indentLevel:n+2,neighbors:0});let x=T.trim();x.length<=nN&&!x.includes(`
3947
+ `)?E+=`>${x}</${p}>
3948
+ `:E+=`>
3949
+ ${T}${u}</${p}>
3950
+ `}if(e.neighbors!==void 0&&e.neighbors>0&&this.parent){let T=this.parent.children.findIndex(U=>U.id===this.id),x=T>0?this.parent.children[T-1]?.serialize({...e,neighbors:0}):"",N=T<this.parent.children.length-1?this.parent.children[T+1]?.serialize({...e,neighbors:0}):"";return`${x||""}
3951
+ ${E}
3952
+ ${N||""}`}return E}shallowClone(){let e=new r({id:this.id,role:this.role,name:this.name,nameSources:this.nameSources,content:this.content,properties:[],pathFromRoot:this.pathFromRoot,children:[],ignoredReasons:this.ignoredReasons,backendNodeID:this.backendNodeId,ignoredByCDP:this.ignoredByCDP,internalProperties:ap(this.internalProperties),importantProperties:this.importantProperties,parentFrame:this.parentFrame,flagNotActionableNodes:this.flagNotActionableNodes});return e.tagName=this.tagName,e.dataMomenticId=this.dataMomenticId,e.properties=ap(this.properties),e}},lp=class r{constructor(e,t,n,o){this.root=e;this.a11yIdNodeMap=t;this.dataMomenticIdMap=n;this.selectorToNodeMap=o}serialize(e){return this.root.serialize(e)}pruneUsingSummaries(e){let t=this.root;if(!t)throw new Error("Cannot prune a11y tree with no root");let n={},o={},i={},a=c=>{let s=c.shallowClone();if(e[c.id])return s.properties["data-momentic-summary"]=e[c.id],n[c.id]=s,c.dataMomenticId&&(o[c.dataMomenticId]=s),c.mPathSelector&&(i[c.mPathSelector]=s),s;let u=[];for(let d of c.children){let p=a(d);p&&(u.push(p),p.parent=s)}return s.children=u,n[c.id]=s,c.dataMomenticId&&(o[c.dataMomenticId]=s),c.mPathSelector&&(i[c.mPathSelector]=s),s},l=a(t);return new r(l,n,o,i)}pruneUsingRelevantIds(e){let t=this.root;if(!t)throw new Error("Cannot prune a11y tree with no root");function n(i,a=!1){let l=e.has(`${i.id}`)||i.id===t?.id,c=i.shallowClone(),s=i.children,u=!1,d=[];for(let p of s){let m=n(p,l||u);m&&(d.push(m),m.parent=c,u=!0)}if(c.children=d,l||u)return c;if(cp.includes(i.role)&&a)return c}let o=n(t);return new r(o,this.a11yIdNodeMap,this.dataMomenticIdMap,this.selectorToNodeMap)}pruneToSerializedCharLimit(e){let t=this.root;if(!t)throw new Error("Cannot prune a11y tree with no root");let n=t.shallowClone(),o=()=>n.serialize().length,i=(a,l)=>{l.children=[];for(let c of a.children){let s=c.shallowClone();if(s.parent=l,l.children.push(s),o()>e){l.children.pop();break}if(i(c,s),o()>e){for(;s.children.length>0&&o()>e;)s.children.pop();if(o()>e){l.children.pop();break}}}};for(i(t,n);n.children.length>0&&o()>e;)n.children.pop();return new r(n,this.a11yIdNodeMap,this.dataMomenticIdMap,this.selectorToNodeMap)}};function sN(r){return r.name?.value?`"${r.name.value}"`:r.role?.value&&r.role.value!=="none"&&r.role.value!=="generic"?`"${r.role.value}"`:`"${r.nodeId}"`}function lN(r,e,t,n){return r.bounds.x===null||r.bounds.y===null||r.bounds.height===null||r.bounds.width===null||r.bounds.width===0||r.bounds.height===0?!0:r.bounds.x+r.bounds.width<e.leftBound||r.bounds.x>e.rightBound?(ms({logger:t,logKey:n,maxCount:5,intervalMs:3e3},{domNode:r,logKey:n},"Filtering out node since it is not in the viewport horizontally"),!1):r.bounds.y+r.bounds.height<e.upperBound||r.bounds.y>e.lowerBound?(ms({logger:t,logKey:n,maxCount:5,intervalMs:3e3},{domNode:r,logKey:n},"Filtering out node since it is not in the viewport vertically"),!1):r.computedStyles.display==="none"?(t.debug({domNode:r},"Filtering out node since it has display none"),!1):!0}async function vT({node:r,parent:e,frameId:t,frameContext:n,axGraph:o,domGraph:i,inputNodeMap:a,flagNotActionableNodes:l,showZeroOpacityElements:c,filterByViewport:s,viewportDetails:u,useMPaths:d,importantProperties:p,cdpClient:m,logger:g,callId:h}){if(!e&&r.parentId)throw new Error(`Got no parent for accessibility node ${r.nodeId}: ${JSON.stringify(r)}`);let f=(M,V={})=>{},E=r.backendDOMNodeId,b=rN.includes(r.role?.value?.toLowerCase()??"");if(!b&&E===void 0)return f("Filtering out node since it doesn't exist in the DOM"),[];let v=E?i.backendIdToNode[E]:void 0;if(!b&&!v)try{let M=await B(m.send({method:"DOM.describeNode",params:{backendNodeId:E}}),{milliseconds:750,fallback:()=>{g.debug("Timeout getting node from CDP while processing a11y tree")}});if(M&&M.node.nodeName.toLowerCase()==="slot"&&M.node.distributedNodes?.length)g.debug({redirectedDomNode:v,parentAXNode:e?.getNodeOnlySerializedForm(),originalAXNode:r,cdpResult:M},"Redirecting node to assigned slot");else return f("Filtering out node since it doesn't exist in the DOM",{cdpResult:M}),[]}catch(M){return f("Filtering out node since it doesn't exist in the DOM",{err:M}),[]}if(v&&e&&s&&u&&r.backendDOMNodeId&&!lN(v,u,g,h))return v.momenticIgnored=!0,[];if(v&&v.computedStyles.display==="none")return v.momenticIgnored=!0,[];if(v&&v.computedStyles.opacity==="0"&&c!==!0){if(c==="inputs-only"&&v.tagName.toLowerCase()!=="input")return v.momenticIgnored=!0,[];if(c===!1)return v.momenticIgnored=!0,[]}let A=r.name?.value?typeof r.name.value=="string"?r.name.value:`${r.name.value}`:"",T=r.value?.value?typeof r.value.value=="string"?r.value.value:`${r.value.value}`:"",x=new sp({domNode:v,id:parseInt(r.nodeId),role:r.role?.value||"",name:A,nameSources:r.name?.sources,content:T,properties:r.properties,children:[],ignoredReasons:r.ignoredReasons?.filter(M=>ET.includes(M.name)||bT.includes(M.name))??[],pathFromRoot:(e?`${e.pathFromRoot} `:"")+sN(r),backendNodeID:r.backendDOMNodeId,ignoredByCDP:r.ignored,internalProperties:{inCodeMirrorEditor:e?.internalProperties?.inCodeMirrorEditor},importantProperties:p,parentFrame:n.type==="root"?void 0:n,flagNotActionableNodes:l}),N=n,U=a[t],Y=t;if(v?.tagName.toLowerCase()==="iframe"&&v.ownedFrameId){let M=n.childFrames.find(Ce=>Ce.frameId===v.ownedFrameId),V=o[M?.frameId??""]?.root,re=a[M?.frameId??""];if(M&&V&&re){r.childIds&&r.childIds.length>0&&g.debug("Replacing existing node's children with children from the iframe");let Ce=V;r.childIds=Ce.childIds,N=M,U=re,Y=M.frameId}}let ke=v?.childrenBackendIds?.length??0,te=(r.childIds??[]).filter(M=>!!U.get(parseInt(M))).length;if(ke>te){let M=r.childIds?.map(re=>U.get(parseInt(re))).filter(Boolean).map(re=>re?.backendDOMNodeId).filter(re=>re!==void 0)??[],V=0;for(let re of v?.childrenBackendIds??[]){if(M.includes(re)){V=(r.childIds?.findIndex(dt=>U.get(parseInt(dt))?.backendDOMNodeId===re)??0)+1;continue}let Ce=i.backendIdToNode[re];if(!Ce||Ce?.tagName.toLowerCase()!=="svg")continue;let Me=Math.floor(-1*Math.random()*1e7),Ae={nodeId:Me.toString(),parentId:r.nodeId,ignored:!1,backendDOMNodeId:re,frameId:Y,role:{type:"string",value:"graphics-symbol"}};U.set(Me,Ae),r.childIds||(r.childIds=[]),r.childIds.splice(V,0,Me.toString()),V++}}if(r.childIds?.length===1&&v){let M=U.get(parseInt(r.childIds[0])),V=M?.role?.value,re=v.childrenBackendIds;if(M&&V==="StaticText"&&re.length===1){let Ce=i.backendIdToNode[re[0]];if(Ce?.tagName?.toLowerCase()==="span"){let Me=Math.floor(-1*Math.random()*1e7).toString(),Ae={nodeId:Me,parentId:r.nodeId,ignored:!1,backendDOMNodeId:Ce.backendNodeId,frameId:Y,childIds:[M.nodeId]};M.parentId=Me,U.set(parseInt(Me),Ae),r.childIds=[Me]}}}for(let M of r.childIds??[]){if(!M)continue;let V=U.get(parseInt(M));if(!V)continue;let re=await vT({node:V,parent:x,domGraph:i,axGraph:o,frameId:Y,frameContext:N,inputNodeMap:a,cdpClient:m,logger:g,callId:h,filterByViewport:s,showZeroOpacityElements:c,importantProperties:p,viewportDetails:u,useMPaths:d,flagNotActionableNodes:l});re.length&&(x.children=x.children.concat(re))}if(x.role==="StaticText"&&(x.children=[]),x.children.length===1&&x.children[0].role==="StaticText"){let M=x.name,V=x.children[0]?.name;(M===V||!V)&&(x.children=[])}let ie=[];for(let M=x.children.length-1;M>=0;M--){let V=x.children[M];if(V.role!=="StaticText"){ie.push(V);continue}if(M===0||x.children[M-1].role!=="StaticText"){ie.push(V);continue}x.children[M-1].name+=V.name}if(x.children=ie.reverse(),!x.isInteresting(p)&&r.parentId)return v&&(v.momenticIgnored=!0),x.children;for(let M of x.children)M.parent=x;return dN(x),v&&d&&ip(v,i),[x]}function AT({node:r,a11yIdNodeMap:e,dataMomenticIdMap:t,logger:n,callId:o,domGraph:i,useMPaths:a,selectorToNodeMap:l,iconKnowledgeBase:c,startId:s=1}){r.id=s,s+=1,e[r.id]=r,r.dataMomenticId?t[r.dataMomenticId]=r:cp.includes(r.role);let u=r.backendNodeId,d=u!==void 0?i.backendIdToNode[u]:void 0;if(a&&d&&d.mPathSelector&&(l[d.mPathSelector]=r,r.mPathSelector=d.mPathSelector),c&&d&&d.tagName?.toLowerCase()==="svg"){let p=op(d,i),m=p?c[p.hash]:void 0,g=m?m.description:void 0;m&&(r.properties["data-momentic-description"]=g)}for(let p of r.children)s=AT({node:p,a11yIdNodeMap:e,dataMomenticIdMap:t,logger:n,callId:o,startId:s,useMPaths:a,domGraph:i,selectorToNodeMap:l,iconKnowledgeBase:c});return s}async function RT({rawA11yGraph:r,domGraph:e,startingFrameId:t,logger:n,cdpClient:o,filterByViewport:i,showZeroOpacityElements:a,flagNotActionableNodes:l,importantProperties:c,viewportDetails:s,useMPaths:u,frameContext:d,iconKnowledgeBase:p}){let m=t??"root",g=r[m]?.root;if(!g)throw new Error("A11y tree has no root");let h=YL(),f=x=>{let N=x.allNodes.filter(Y=>!Y.ignoredReasons?.find(te=>ET.includes(te.name))),U=new Map;return N.forEach(Y=>{U.set(parseInt(Y.nodeId),Y)}),U},E={};Object.entries(r).forEach(([x,N])=>{E[x]=f(N)});let b=await vT({node:g,domGraph:e,parent:null,inputNodeMap:E,axGraph:r,frameId:m,frameContext:d,cdpClient:o,logger:n,callId:h,showZeroOpacityElements:a,importantProperties:c,filterByViewport:i,viewportDetails:s,useMPaths:u,flagNotActionableNodes:l});if(b.length>1)throw new Error(`Something went horribly wrong processing the a11y tree, we got: ${JSON.stringify(b)}`);if(b.length===0)throw new Error("There are no accessible elements on this page or frame. Are you sure this website loads properly?");let v={},A={},T={};return AT({node:b[0],a11yIdNodeMap:v,dataMomenticIdMap:A,selectorToNodeMap:T,domGraph:e,logger:n,callId:h,useMPaths:u,iconKnowledgeBase:p}),new lp(b[0],v,A,T)}function cN(r,e,t,n){if(r==="class"){if(t.tagName?.toLowerCase()==="svg")return e.split(" ").filter(a=>a.length<TT&&!jt.bannedClassSubstrings.some(l=>a.includes(l))).slice(0,3).join(" ");let o=e.split(" "),i=[];for(let a of o)if(wT(a,n)){i.push(a);continue}return i.length?i.join(" "):null}if(e==="true")return!0;if(e==="false")return!1;try{let o=parseInt(e);if(!isNaN(o))return o}catch{}return r==="src"&&e.includes("base64")?e.slice(0,e.indexOf("base64")+6)+"...":e.length>60?e.slice(0,50)+"...":e}function uN(r,e,t){if(!e)return;Object.entries(e.attributes).forEach(([a,l])=>{let c=r[a]||a.startsWith("aria")||QL.includes(a);if((jt.relevantElementAttributes.includes(a)||CT(a,t))&&!c){let u=cN(a,l,e,t);u!==null&&(r[a]=u)}});let n,o=[];if(e.computedStyles.position&&fT.includes(e.computedStyles.position))n=e.computedStyles.position;else if(e.attributes.style){for(let a of fT)if(e.attributes.style.includes(`position: ${a}`)){n=a;break}}n&&o.push(`position: ${n}`);let i;e.computedStyles.opacity&&e.computedStyles.opacity==="0"&&(i="opacity: 0"),i&&o.push(i);for(let a of t?.styles??[]){let l=a.split(":"),c=l[0]?.trim(),s=l[1]?.trim(),u=e.computedStyles[c??""];if(c!==void 0&&s!==void 0&&u!==void 0&&(s==="*"||u===s)){let d=e.computedStyles[c],p=`${c}: ${d}`;o.includes(p)||o.push(p)}}o.length>0&&(r.style=o.join("; "))}function dN(r){let e=r.properties.class;if(typeof e=="string"&&e.includes("cm-content")){r.children.forEach((i,a)=>{i.properties["cm-line-number"]=`${a+1}`});return}if(typeof e=="string"&&e.includes("notion-page-content")){r.children.forEach((i,a)=>{i.properties["block-number"]=`${a+1}`}),r.children.length>0&&(r.children[r.children.length-1].properties.description="This is the last block in the document. Click here to add new text to the end.");return}if(r.tagName==="table"){let i=[],a=r.children.find(c=>c.tagName==="thead");if(a){let c=a.children.find(s=>s.tagName==="tr");if(c){let s=c.children.filter(u=>u.tagName==="th");s.forEach((u,d)=>{u.properties["col-index"]||(u.properties["col-index"]=d+1),i?.push(St(u.name,100,!1))}),i?.length!==s.length&&(i=void 0)}}let l=0;for(let c of r.children)if(c.tagName==="tbody")for(let s=0;s<c.children.length;s++){let u=c.children[s];if(u.tagName!=="tr")continue;if(s===0&&!i?.length){let m=u.children.filter(g=>g.tagName==="th");if(m.length){if(i=m.map(g=>St(g.name,100,!1)),i.length===m.length)continue;i=void 0}}l+=1,u.properties["row-index"]||(u.properties["row-index"]=l);let d=u.children.filter(m=>m.tagName==="td"||m.tagName==="th"),p=d.length===i?.length;d.forEach((m,g)=>{m.tagName!=="th"&&(m.properties["col-index"]||(m.properties["col-index"]=g+1),p&&(m.properties.col||(m.properties.col=i[g])))})}}}function pN(r){let e=r.properties.class,t=typeof e=="string"&&e.includes("cm-content");r.internalProperties.inCodeMirrorEditor=r.internalProperties?.inCodeMirrorEditor||t}function wT(r,e){if(e&&xT(r,e))return!0;if(jt.bannedClassSubstrings.some(t=>r.includes(t)))return!1;if(jt.alwaysInterestingClassNames.includes(r))return!0;for(let t of jt.alwaysInterestingClassPrefixes)if(r.startsWith(t))return!0;return!1}function CT(r,e){if(e?.attributes?.includes(r))return!0;for(let t of e?.attributes??[])if(t.endsWith("*")){let n=t.slice(0,-1);if(r.startsWith(n))return!0}return!1}function xT(r,e){if(e?.classes?.includes(r))return!0;for(let t of e?.classes??[])if(t.endsWith("*")){let n=t.slice(0,-1);if(r.startsWith(n))return!0}return!1}var Cl=class r{constructor(e,t,n,o,i){this.session=e;this.logger=t;this.contextGetter=n;this.pageGetter=o;this.defaultTimeoutMs=i}cdpInitializingPromise=void 0;cdpCrashDetails=void 0;cdpFullyDead=!1;loadEventLogs=[];static async init({logger:e,contextGetter:t,pageGetter:n,defaultTimeoutMs:o}){let i=t(),a=n(),l,c;for(let u=0;u<2;u++)try{l=await B(i.newCDPSession(a),{milliseconds:o*u,fallback:()=>{throw new w("UserInfrastructureError",`Failed to initialize Chrome session within the page load timeout (${a.url()})`)}});break}catch(d){await $(500),c=d}if(!l)throw c;let s=new r(l,e,t,n,o);try{await B(s.registerHandlers(l),{milliseconds:o,message:`CDP handler registration timed out after ${o}ms`})}catch(u){throw s.cdpFullyDead=!0,new w("UserInfrastructureError",`Failed to initialize CDP client: ${u}`)}return s}async registerHandlers(e){e.on("Target.attachedToTarget",async()=>{try{await e.send("Runtime.runIfWaitingForDebugger")}catch(t){this.logger.warn({err:t},"Failed to run Runtime.runIfWaitingForDebugger")}}),e.on("Target.targetCrashed",t=>{this.cdpCrashDetails={...this.cdpCrashDetails??{},targetCrashDetails:JSON.stringify(t)},this.logger.error({payload:t},"CDP session crashed, Momentic will likely not function correctly")}),e.on("Inspector.targetCrashed",t=>{this.cdpCrashDetails={...this.cdpCrashDetails??{},inspectorCrashDetails:JSON.stringify(t)},this.logger.error({payload:t},"CDP inspector session crashed, Momentic will likely not function correctly")}),e.on("Page.frameRequestedNavigation",t=>{this.loadEventLogs.push(`[${new Date(Date.now()).toLocaleString("en-US",{timeZone:"America/Los_Angeles"})}] Frame requested navigation: ${JSON.stringify(t)}`)}),e.on("Page.navigatedWithinDocument",t=>{this.loadEventLogs.push(`[${new Date(Date.now()).toLocaleString("en-US",{timeZone:"America/Los_Angeles"})}] Navigated within document: ${JSON.stringify(t)}`)}),e.on("Page.lifecycleEvent",t=>{this.loadEventLogs.push(`[${new Date(Date.now()).toLocaleString("en-US",{timeZone:"America/Los_Angeles"})}] Page lifecycle event: ${JSON.stringify(t)}`)}),e.on("Page.loadEventFired",()=>{this.loadEventLogs.push(`[${new Date(Date.now()).toLocaleString("en-US",{timeZone:"America/Los_Angeles"})}] Page load event fired`)}),await e.send("Accessibility.enable"),await e.send("Page.enable"),await e.send("DOM.enable"),await e.send("Overlay.enable"),await e.send("DOMSnapshot.enable"),await e.send("CSS.enable")}async send({method:e,params:t,timeout:n=this.defaultTimeoutMs,timeoutMsg:o}){for(;this.cdpInitializingPromise;)await B(this.cdpInitializingPromise,{milliseconds:n});if(this.cdpCrashDetails){if(this.cdpFullyDead)throw new w("UserInfrastructureError",`The browser inspector session encountered a critical crash: ${JSON.stringify(this.cdpCrashDetails)}`);this.logger.warn(`Detected crashed CDP client before method ${e}, reinitializing before proceeding...`),await this.reinitialize()}try{return await B(this.session.send(e,t),{milliseconds:n,message:o??`Chrome command ${e} timed out after ${n}ms. This is likely an infrastructure issue caused by a lack of compute resources or a crash at the browser level.`})}catch(i){throw["Internal error","Target crashed"].some(a=>i.message.includes(a))&&!this.cdpInitializingPromise&&(this.logger.warn({err:i},`CDP crashed during CDP method ${e}, re-initializing client`),await this.reinitialize()),i}}async createRawCDPSession(e=this.defaultTimeoutMs){let t=e,n=this.pageGetter(),o=await B(this.contextGetter().newCDPSession(n),{milliseconds:t,fallback:()=>{throw this.logger.error(`Failed to initialize CDP session within the page load timeout (${n.url()})`),new w("UserInfrastructureError",`Failed to initialize CDP session within the page load timeout (${n.url()})`)}});return this.logger.debug(`Created new CDP session for ${n.url()}`),o}async reinitialize(e=this.defaultTimeoutMs){await this.cdpInitializingPromise,this.cdpInitializingPromise=(async()=>{try{let t=this.session;this.session=await this.createRawCDPSession(e),await B(this.registerHandlers(this.session),{milliseconds:e,message:`Failed to register CDP handlers within ${e}ms`}),this.logger.debug("Successfully reinitialized and attached new handlers to CDP session");try{await B(t.detach(),{milliseconds:1e3})}catch(n){this.logger.warn({err:n},"Failed to detach old CDP session after reinitialization, continuing...")}this.cdpCrashDetails=void 0,this.cdpFullyDead=!1}catch(t){this.cdpCrashDetails={...this.cdpCrashDetails??{},reinitializeError:`${t}`},this.cdpFullyDead=!0}finally{this.cdpInitializingPromise=void 0}})(),await this.cdpInitializingPromise}on(e,t){return this.session.on(e,t),this.session}off(e,t){return this.session.off(e,t),this.session}addListener(e,t){return this.session.addListener(e,t),this.session}removeListener(e,t){return this.session.removeListener(e,t),this.session}};var No="<empty>";function mN(r){return r.includes("doubleclick.net")||r.includes("googletagmanager.com")||r.includes("googlesyndication.com")||r.includes("s.amazon-adsystem.com")||r.includes("smartadserver.com")||r.includes("omnitagjs.com")||r.includes("x.adroll.com")}function MT(r){let e=r.adFrameStatus?.adFrameType;return e==="child"||e==="root"||mN(r.url)}async function gN(r,e){let t=await r.send({timeout:3e3,method:"DOM.getFrameOwner",params:{frameId:e}}),o=(await r.send({timeout:3e3,method:"DOM.pushNodesByBackendIdsToFrontend",params:{backendNodeIds:[t.backendNodeId]}})).nodeIds[0],a=(await r.send({timeout:3e3,method:"DOM.describeNode",params:{backendNodeId:t.backendNodeId}})).node;return a.nodeId=o,a}async function Do({cdpClient:r,page:e,logger:t}){let n={type:"root",childFrames:[],page:e},o=[],[i,a]=await Promise.all([r.send({timeout:3e3,method:"Page.getFrameTree",params:{}}),r.send({timeout:3e3,method:"DOM.getDocument",params:{depth:0}})]),s=(i.frameTree.childFrames??[]).map(async(d,p)=>{if(MT(d.frame))return null;try{return await IT({cdpClient:r,rawFrameTree:d,indices:[p],parent:n,warnings:o,logger:t})}catch(m){return o.push(`Failed to get child frame: ${m}`),null}}),u=await Promise.all(s);return n.childFrames=u.filter(d=>d!==null),o.length&&t?.warn({warnings:o},"Got warnings when fetching frame tree"),n}async function IT({cdpClient:r,rawFrameTree:e,indices:t,parent:n,warnings:o,logger:i}){let a=e.frame.id,l=await gN(r,a),c=l.attributes??[],s=null,u=[];for(let g of["src","name","id","title","srcdoc","sandbox"]){let h=tn(c,g);h&&(u.push(`${g}=${JSON.stringify(h)}`),g==="src"&&(s=h))}let d={type:"frame",cdpFrame:e.frame,url:e.frame.url,frameId:a,locationData:{indices:t,attributeSelectors:u},src:s,childFrames:[],parent:n,domNode:l},m=(e.childFrames??[]).map(async(g,h)=>{if(MT(g.frame))return null;try{return await IT({cdpClient:r,rawFrameTree:g,indices:[...t,h],parent:d,warnings:o,logger:i})}catch(f){return o.push(`Failed to get child frame (child ${h} of frame with url ${e.frame.url}): ${f}`),null}});return d.childFrames=(await Promise.all(m)).filter(g=>g!==null),d}async function hN(r){try{return await r.owner().count()===1}catch{return!1}}async function fN(r){try{return await r.count()===1}catch{return!1}}async function fr(r,e){let t=[],n=r;for(;n.parent.type==="frame";)t.push(n.parent),n=n.parent;t.reverse();let o=e,i=[];for(let s of t){let u=!1;for(let d of[...s.locationData.attributeSelectors,No]){let p=o.frameLocator(d===No?"iframe":`iframe[${d}]`);if(await hN(p)){u=!0,o=p,i.push(d);break}}if(!u)throw new w("ActionFailureError",`Failed to find a unique attribute to identify intermediate frame with url matching '${s.url}'. Please attach a unique 'id', 'name', 'title', or 'src' attribute to the frame.`)}let a;for(let s of[...r.locationData.attributeSelectors,No]){let u=o.locator(s===No?"iframe":`iframe[${s}]`);if(await fN(u)){a=u,i.push(s);break}}if(!a)throw new w("ActionFailureError",`Failed to find a unique attribute to identify target frame with url matching '${r.url}'. Please attach a unique 'id', 'name', 'title', or 'src' attribute to the frame.`);let l=await a.evaluateHandle(s=>s,{timeout:1e3}),c=await l.asElement().contentFrame();if(!c)throw new w("InternalWebAgentError",`Failed to load Playwright Frame for iframe with url '${r.url}'`);return await l.dispose(),{frame:c,mPathSelectorTokens:i}}function _T(r,e){let t=[...r],n=[];for(;t.length;){let o=t.shift();e(o)&&n.push(o),t.push(...o.childFrames)}return n}async function PT({page:r,frameTree:e,cache:t}){let n,o=e.childFrames,i=[];if(t.mPathSelectorTokens.length){let l=o;for(let u=0;u<t.mPathSelectorTokens.length-1;u++){let d=t.mPathSelectorTokens[u];d===No?l=l.length===1?l[0].childFrames:[]:l=l.filter(p=>p.locationData.attributeSelectors.includes(d)).map(p=>p.childFrames).flat()}let c=[],s=t.mPathSelectorTokens[t.mPathSelectorTokens.length-1];if(s===No?c=l:c=l.filter(u=>u.locationData.attributeSelectors.includes(s)),c.length===1)return n=c[0],i.push(`Found unique frame with mpath ${t.mPathSelectorTokens.join(" > ")}`),{resolution:{type:"auto",frame:(await fr(n,r)).frame,handle:n,mPathSelectorTokens:t.mPathSelectorTokens,frameTree:e},logs:i};i.push(`Found ${c.length} frames with mpath ${t.mPathSelectorTokens.join(" > ")}`)}if(t.frameSrcRegex){let l=new RegExp(t.frameSrcRegex),c=_T(o,s=>!!s.src&&l.test(s.src));if(c.length===1)return n=c[0],i.push(`Found unique frame with src regex ${t.frameSrcRegex}`),{resolution:{type:"auto",frame:(await fr(n,r)).frame,handle:n,mPathSelectorTokens:t.mPathSelectorTokens,frameTree:e},logs:i};i.push(`Found ${c.length} frames with src regex ${t.frameSrcRegex}`),t.frameSrcRegex=void 0}if(t.frameUrlRegex){let l=new RegExp(t.frameUrlRegex),c=_T(o,s=>!!s.url&&l.test(s.url));if(c.length===1)return n=c[0],i.push(`Found unique frame with url regex ${t.frameUrlRegex}`),{resolution:{type:"auto",frame:(await fr(n,r)).frame,handle:n,mPathSelectorTokens:t.mPathSelectorTokens,frameTree:e},logs:i};i.push(`Found ${c.length} frames with url regex ${t.frameUrlRegex}`),t.frameUrlRegex=void 0}let a=o;for(let l=0;l<t.indices.length-1;l++)a=a[t.indices[l]]?.childFrames??[];if(n=a[t.indices[t.indices.length-1]],n)return i.push(`Found unique frame with indices ${t.indices.join(" > ")}`),{resolution:{type:"auto",frame:(await fr(n,r)).frame,handle:n,mPathSelectorTokens:t.mPathSelectorTokens,frameTree:e},logs:i};throw i.push(`Found ${a.length} frames with indices ${t.indices}`),new Vr("Failed to find the iframe that previously contained this element",[{type:"AUTO_FRAME",matched:!1,logs:i}])}function xl(r){return r.type==="auto"?JSON.stringify({type:"auto",frameId:r.handle.frameId}):JSON.stringify(r)}function up(r){for(;r.parent.type==="frame";)r=r.parent;return r.parent}function OT(r){let e=up(r),t=r.src??"",n=r.url??"",o=[],i=[],a=[...e.childFrames];for(;a.length;){let l=a.shift();l.src&&o.push(l.src),l.url&&i.push(l.url),a.push(...l.childFrames)}return{srcs:o,urls:i,desiredSrc:t,desiredUrl:n}}function LT(r){return r.type==="auto"?{type:"auto",frameId:r.handle.frameId,url:r.handle.url,src:r.handle.src??"",mPathSelectorTokens:r.mPathSelectorTokens.join(" > ")}:{type:"url",url:r.url}}async function NT({frame:r,logger:e,signal:t}){let n;try{n=await r.frameElement(),await SN({frameElementHandle:n,logger:e,signal:t})}catch(o){n?e.warn({err:o},"Failed to scroll iframe into view, trying with raw JS"):e.warn("Failed to scroll iframe into view - no frame element")}finally{await n?.dispose()}}async function SN({frameElementHandle:r,logger:e,signal:t}){let n=await r.boundingBox();await wn({promiseGenerator:async()=>r.evaluate(async i=>{let a=i.scrollTop;i.scrollIntoView({behavior:"instant",block:"center",inline:"center"}),await new Promise(c=>setTimeout(c,250));let l=Date.now();for(;Date.now()-l<1e3;){let c=i.scrollTop;if(c===a)break;a=c,await new Promise(s=>setTimeout(s,250))}}),timeoutMs:2e3,codePath:"scrollIframeIntoView",signal:t}),e.info({oldBb:n,newBb:await r.boundingBox()},"Successfully scrolled iframe into view")}function DT(r,e){return async(t,n)=>{try{let o=await n.allHeaders();for(let{key:i,value:a,matcher:l}of r)(!l||l.matches({url:n.url(),method:n.method()}))&&(o[i]=a);await t.fallback({headers:o})}catch(o){e.warn({err:o},"Failed to apply custom headers to request, continuing")}}}import{randomUUID as EN}from"crypto";function kT(r,e){for(let t of Object.values(e))if(t.matcher.matches({url:r.url(),method:r.method()}))return t}async function UT(r){let{route:e,mock:t,entry:n,debugData:o,requestId:i,requestRecorders:a,logger:l}=r,c={url:n.request.url,options:{method:n.request.method,headers:n.request.headers.map(m=>[m.name,m.value]),body:n.request.postData?.text}},s;if(t.fetchOriginalResponse){let m=await e.fetch();s={body:await m.text(),options:{status:m.status(),statusText:m.statusText(),headers:Object.entries(await m.headers())}}}let u=await yN(t,c,s),d={};u.headers.forEach((m,g)=>{d[g]=m});let p={body:await u.text(),contentType:u.headers.get("content-type")||"text/plain",headers:d,status:u.status};await e.fulfill(p);try{n.response={status:p.status,statusText:u.statusText,headers:Object.entries(p.headers).map(([m,g])=>({name:m,value:g})),cookies:[],content:{mimeType:p.contentType,text:p.body},_mocked:!0},oa(o,n,i);for(let m of Object.values(a))m.onRequestComplete(i,n)}catch(m){m.message.includes("has been closed")||l.warn({err:m},"Failed to add response to HAR")}}async function yN(r,e,t){try{return await r.generateResponse(e,t)}catch(n){let o=n instanceof Error?n.message:`${n}`;return new Response(o,{status:500,headers:{"Content-Type":"text/plain"}})}}async function dp(r){try{await bN(r)}catch(e){r.logger.warn({err:e},"Error handling intercepted request, continuing...")}}async function bN(r){let{pageId:e,route:t,request:n,debugData:o,logger:i,requestRecorders:a,mocks:l}=r,c=EN(),s=await Qd(e,n);try{oa(o,s,c);for(let d of Object.values(a))d.onRequestStart(c,s)}catch(d){i.warn({err:d},"Failed to add request to HAR")}let u=kT(n,l);u?await UT({logger:i,route:t,mock:u,entry:s,debugData:o,requestId:c,requestRecorders:a}):await TN({route:t,request:n,debugData:o,logger:i,requestRecorders:a,entry:s,requestId:c})}async function TN({route:r,request:e,debugData:t,logger:n,requestRecorders:o,entry:i,requestId:a}){await r.continue();try{let l=await e.response();if(!l||!i)return;await Xb(i,e,l),oa(t,i,a);for(let c of Object.values(o))c.onRequestComplete(a,i)}catch(l){l.message.includes("has been closed")||n.warn({err:l},"Failed to add response to HAR")}}async function vN(r){let e=r.postData();if(e){if((await r.headerValue("content-type"))?.includes("json"))try{return{json:r.postDataJSON()}}catch{return{}}else if((await r.headerValue("content-type"))?.includes("text"))return{text:e}}return{}}async function AN(r){let e=await r.text();if(e){if((await r.headerValue("content-type"))?.includes("json"))try{return{json:await r.json()}}catch{return{}}else if((await r.headerValue("content-type"))?.includes("text"))return{text:e}}return{}}function _l(r){return{request:{url:r.request.url,method:r.request.method,headers:r.request.headers.reduce((e,t)=>({...e,[t.name]:t.value}),{}),...r.request.postData?r.request.postData.mimeType.includes("json")?{json:JSON.parse(r.request.postData.text)}:{text:r.request.postData.text}:{}},response:r.response?{status:r.response.status,headers:r.response.headers.reduce((e,t)=>({...e,[t.name]:t.value}),{}),...r.response.content?r.response.content.mimeType?.includes("json")&&r.response.content.text?{json:JSON.parse(r.response.content.text)}:{text:r.response.content.text}:{}}:void 0}}async function pp(r){let e=r.request(),t=r.status(),n=r.headers(),o=await AN(r);return{request:{url:e.url(),method:e.method(),headers:e.headers(),...await vN(e)},response:{status:t,headers:n,...o},status:t,headers:n,...o}}var rn=class{requestMatcher;constructor(e){this.requestMatcher=e}matches(e){let{url:t,method:n}=e;return this.requestMatcher.method&&this.requestMatcher.method.toLowerCase()!==n.toLowerCase()?!1:ws(t,this.requestMatcher.urlMatcher)}};function Ml(r){let e=new URL(r.request().url());return/^127\./.test(e.hostname)||/^192\.168\./.test(e.hostname)||/^10\./.test(e.hostname)||/^172\.(1[6-9]|2\d|3[0-1])\./.test(e.hostname)||e.hostname==="localhost"?r.abort():r.fallback()}async function FT({event:r,transformer:e,enricher:t,frame:n,lastScreenshotForRecording:o,logger:i}){let{warnings:a,error:l,properties:c}=r.target;if(l){i.error({error:l,warnings:a},"Error while capturing passive click");return}if(a.length&&i.warn({warnings:a},"Warnings while capturing passive click"),!c)return;let s=n.parentFrame()?n.url():void 0,d=n.page().frames().map(g=>g.url());i.debug({frameUrl:s,...r},"Passive click event captured on element");let p,m;if(s)try{let g=await n.frameElement();p=await B(g?.boundingBox(),{milliseconds:3e3})??void 0;let h=await t.constructIframeRegex({urls:d,srcs:[],desiredUrl:s});if(h.urlRegex)m={type:"url",url:`/${h.urlRegex}/`};else throw new Error(`Got no url regex options: ${JSON.stringify(h)}`)}catch(g){i.warn({err:g},"Failed to construct iframe details for recorded action, using hardcoded URL only"),m={type:"url",url:s}}(async()=>{try{await e.recordElementAction({...r,screenshotBase64:o,frameConfig:m,frameBoundingBox:p})}catch(g){i.error({err:g},"Failed to transform passive click action")}})()}import{randomUUID as Sr}from"crypto";import RN from"js-beautify";var wN=["Dead"],Il=class{recordedSteps=new Map;callbacks;signal;generator;testId;orgId;nextStepOffset=0;logger;constructor({signal:e,callbacks:t,generator:n,testId:o,orgId:i,logger:a}){this.signal=e,this.logger=a,this.testId=o,this.orgId=i,this.callbacks={onStepRecorded:(l,c)=>{this.recordedSteps.set(c,{step:l}),t.onStepRecorded(l,c)},onActionReceived:(l,c)=>{this.recordedSteps.set(c,{step:l}),t.onActionReceived?.(l,c)}},this.generator=n}reserveIndexForCommand(e){let t=this.nextStepOffset;return this.recordedSteps.set(t,{step:{id:Sr(),type:"PRESET_ACTION",command:Ar(e)}}),this.nextStepOffset++,t}async recordElementAction(e){let{type:t,target:n,frameConfig:o}=e;if(this.signal.aborted){this.logger.debug("Transformer was already cleaned up, ignoring click...");return}let i,a,l=n.properties.attributes.nodeOnlySerializedHtml.trim(),c=l,s;switch(e.frameConfig?e.frameBoundingBox?s={x:e.frameBoundingBox.x+n.properties.boundingBox.x,y:e.frameBoundingBox.y+n.properties.boundingBox.y,width:n.properties.boundingBox.width,height:n.properties.boundingBox.height}:this.logger.warn(e,"No frame bounding box found, refusing to write bounding box"):s=n.properties.boundingBox,t){case"CLICK":{i="CLICK";let h=Ar(i);a={id:Sr(),type:"PRESET_ACTION",command:{...h,target:{type:"description",elementDescriptor:c},iframeUrl:o?.url,cache:{target:{id:-1,...n.properties.attributes,targetSource:"RECORDING",targetUpdateTime:new Date().toUTCString(),boundingBox:s}}}};break}case"SELECT":{i="SELECT_OPTION";let h=Ar(i);a={id:Sr(),type:"PRESET_ACTION",command:{...h,type:"SELECT_OPTION",iframeUrl:o?.url,target:{type:"description",elementDescriptor:c},cache:{target:{id:-1,...n.properties.attributes,targetSource:"RECORDING",targetUpdateTime:new Date().toUTCString(),boundingBox:s}},choice:{type:"VALUE",value:e.selectedValue??"Unknown option"}}};break}case"MOUSE_DRAG":{i="MOUSE_DRAG";let h=Ar(i);a={id:Sr(),type:"PRESET_ACTION",command:{...h,target:{type:"description",elementDescriptor:c},deltaX:e.deltaX.toString(),deltaY:e.deltaY.toString(),iframeUrl:o?.url,cache:{target:{id:-1,...n.properties.attributes,targetSource:"RECORDING",targetUpdateTime:new Date().toUTCString(),targetUpdateLoggerTags:pe(this.logger),boundingBox:s}}}};break}default:throw new Error(`Unknown action type: ${t}`)}let u;e.offset===void 0?(u=this.nextStepOffset,this.nextStepOffset++):u=e.offset,this.callbacks.onActionReceived?.(a,u);let d=e.target.browserState;try{d=RN.html(d,{indent_size:1,indent_with_tabs:!1,preserve_newlines:!1}),d=Fb(d,"data-momentic-interacted",4e4)}catch{}let p;try{p=(await this.generator.getReverseMappedDescription({target:d,screenshot:e.screenshotBase64?`data:image/jpeg;base64,${e.screenshotBase64}`:void 0,boundingBox:n.properties.boundingBox},{disableCache:!1,loggerTags:{testId:this.testId,...pe(this.logger)}})).phrase}catch(h){this.logger.error({err:h},"Error generating reverse mapping description"),p=l}let m=this.recordedSteps.get(u)?.step??a,g=m?.command;g&&"target"in g&&g.target?(g.target={type:"description",elementDescriptor:p},this.callbacks.onStepRecorded({...m,command:g},u)):this.logger.warn("Could not find existing command to update after description mapping")}recordKeystroke(e){let{key:t,combinable:n}=e;if(wN.includes(t)||this.signal.aborted)return;let o="normal";t.length>1&&(o="special");let i;if(o==="normal"){let d=Ar("TYPE");i={id:Sr(),type:"PRESET_ACTION",command:{...d,target:void 0,value:t,clearContent:!1}}}else{let d=Ar("PRESS");i={id:Sr(),type:"PRESET_ACTION",command:{...d,value:t}}}let a,l=this.nextStepOffset-1,c=this.recordedSteps.get(l),s=c?.step,u=s?.command;if(n){if(u?.type===i.command.type){let d=u.value,p=i.command.value;i={id:Sr(),type:"PRESET_ACTION",command:{...u,value:i.command.type==="PRESS"?`${d}+${p}`:`${d}${p}`}},a=l}else if(u?.type==="CLICK"&&i.command.type==="TYPE")s.command={...i.command,target:u.target,cache:u.cache},i=c.step,a=l;else if(u?.type==="TYPE"&&i.command.type==="PRESS"&&i.command.value==="Backspace"){let d=u.value;i={id:Sr(),type:"PRESET_ACTION",command:{...u,value:d.slice(0,d.length-1)}},a=l}}a===void 0&&(a=this.nextStepOffset,this.nextStepOffset++),this.callbacks.onStepRecorded(i,a)}recordScroll(e){if(this.signal.aborted)return;let t=()=>{let{deltaY:i}=e;if(!i)return;let a=this.nextStepOffset-1,l=this.recordedSteps.get(a)?.step.command,c;l?.type==="SCROLL_DOWN"&&l.deltaY?(i+=l.deltaY,c=a):l?.type==="SCROLL_UP"&&l.deltaY?(i-=l.deltaY,c=a):(c=this.nextStepOffset,this.nextStepOffset++);let s=i>0?"SCROLL_DOWN":"SCROLL_UP",u=Ar(s);u.deltaY=Math.abs(i);let d={id:Sr(),type:"PRESET_ACTION",command:u};this.callbacks.onStepRecorded(d,c)},n=()=>{let{deltaX:i}=e;if(!i)return;let a=this.nextStepOffset-1,l=this.recordedSteps.get(a)?.step.command,c;l?.type==="SCROLL_RIGHT"&&l.deltaX?(i+=l.deltaX,c=a):l?.type==="SCROLL_LEFT"&&l.deltaX?(i-=l.deltaX,c=a):(c=this.nextStepOffset,this.nextStepOffset++);let s=i>0?"SCROLL_RIGHT":"SCROLL_LEFT",u=Ar(s);u.deltaX=Math.abs(i);let d={id:Sr(),type:"PRESET_ACTION",command:u};this.callbacks.onStepRecorded(d,c)},o=this.recordedSteps.get(this.nextStepOffset-1);o?.step.command.type==="SCROLL_LEFT"||o?.step.command.type==="SCROLL_RIGHT"?(n(),e.deltaY>=20&&t()):(t(),e.deltaX>=20&&n())}};import{z as mp}from"zod";var lle=mp.object({type:mp.literal("url"),url:mp.string()});var Pl=class{smartWaitingTimeoutMs;pageLoadTimeoutMs;allowPartialAccessibilityTree;logger;cdpClient;pageGetter;abortSignalGetter;userBrowserSettings;enricher;iconKnowledgeBase;computedStylesToFetch=["display","opacity","visibility","height","position"];activeFrameCache;activeFrameConfig;lastA11yIdToNodeMap={};lastDataMomenticIdToNodeMap={};lastSelectorToNodeMap={};lastA11yTreeRoot;lastDomGraph;constructor({smartWaitingTimeoutMs:e,pageLoadTimeoutMs:t,allowPartialAccessibilityTree:n,logger:o,cdpClient:i,pageGetter:a,abortSignalGetter:l,enricher:c,iconKnowledgeBase:s,userBrowserSettings:u}){if(this.smartWaitingTimeoutMs=e,this.pageLoadTimeoutMs=t,this.allowPartialAccessibilityTree=n,this.logger=o,this.cdpClient=i,this.pageGetter=a,this.abortSignalGetter=l,this.enricher=c,this.iconKnowledgeBase=s,this.userBrowserSettings=u,this.userBrowserSettings.importantStyles)for(let d of this.userBrowserSettings.importantStyles){let p=d.split(":");if(p.length!==2){this.logger.warn({style:d},"Invalid style property passed to importantStyles");continue}let m=p[0]?.trim(),g=p[1]?.trim();if(m===void 0||g===void 0){this.logger.warn({style:d},"Invalid style property passed to importantStyles");continue}this.computedStylesToFetch.includes(m)||this.computedStylesToFetch.push(m)}}get frameConfig(){return this.activeFrameConfig}get domGraph(){return this.lastDomGraph}get selectorToNodeMap(){return this.lastSelectorToNodeMap}get dataMomenticIdToNodeMap(){return this.lastDataMomenticIdToNodeMap}get a11yIdToNodeMap(){return this.lastA11yIdToNodeMap}get a11yTreeRoot(){return this.lastA11yTreeRoot}setActiveFrameConfig(e){e?(this.activeFrameConfig=e,this.activeFrameCache=void 0):(this.activeFrameConfig=void 0,this.activeFrameCache=void 0)}reset(){this.activeFrameCache=void 0,this.activeFrameConfig=void 0,this.lastA11yIdToNodeMap={},this.lastDataMomenticIdToNodeMap={},this.lastSelectorToNodeMap={},this.lastA11yTreeRoot=void 0,this.lastDomGraph=void 0}saveAutoFrameCacheDetails(e){if(!this.activeFrameConfig||this.activeFrameConfig.type!=="auto"||!this.userBrowserSettings.autoExpandIframes)return;let t={...e,indices:this.activeFrameConfig.handle.locationData.indices,mPathSelectorTokens:this.activeFrameConfig.mPathSelectorTokens};return this.constructIframeRegexAsync(this.activeFrameConfig.handle,t),t}async getAutoFrameDetailsFromHandle(e){let t=this.pageGetter(),n=up(e),{frame:o,mPathSelectorTokens:i}=await fr(e,t),a={indices:e.locationData.indices,mPathSelectorTokens:i};return this.constructIframeRegexAsync(e,a),{cache:a,config:{type:"auto",frame:o,handle:e,mPathSelectorTokens:i,frameTree:n,cache:a}}}async resolveAutoFrameCache(e){let t=this.pageGetter(),n=await Do({cdpClient:this.cdpClient,page:t,logger:this.logger}),{resolution:o,logs:i}=await PT({page:t,frameTree:n,cache:e});return this.logger.info({logs:i},"Resolved auto frame cache"),{...o,cache:e}}async resolveActiveFrameConfig({logger:e=this.logger,signal:t=this.abortSignalGetter()}){if(!this.frameConfig)return null;if(this.activeFrameCache)if(xl(this.frameConfig)!==this.activeFrameCache.frameIdentifierStringified)this.activeFrameCache=void 0;else if(this.activeFrameCache.frame&&"isDetached"in this.activeFrameCache.frame&&this.activeFrameCache.frame.isDetached())this.activeFrameCache=void 0;else return this.activeFrameCache;let n;return this.frameConfig.type==="url"?n=await this.resolveUrlMatcherFrameConfig({config:this.frameConfig,logger:e,signal:t}):n={source:"auto",frame:this.frameConfig.frame,handle:this.frameConfig.handle,frameIdentifierStringified:xl(this.frameConfig),cacheTime:Date.now(),frameTree:this.frameConfig.frameTree,mPathSelectorTokens:this.frameConfig.mPathSelectorTokens},await NT({frame:n.frame,logger:e,signal:t}),this.activeFrameCache=n,n}async executeFunctionInAllFrames(e,t){let n=this.pageGetter(),o=await Do({cdpClient:this.cdpClient,page:n,logger:this.logger}),i=[B(n.evaluate(e,t),{milliseconds:2e3})],a=Array.from(o.childFrames);for(;a.length>0;){let c=a.shift(),s=c.url;s==="about:blank"||s.startsWith("chrome-error://")||(a.push(...c.childFrames),i.push(fr(c,n).then(({frame:u})=>B(u.evaluate(e,t),{milliseconds:2e3})).catch(u=>(this.logger.warn({err:u,frameUrl:c.url},"Failed to evaluate function in frame"),"MOMENTIC_FRAME_EVAL_ERROR"))))}return(await Promise.all(i)).filter(c=>c!=="MOMENTIC_FRAME_EVAL_ERROR")}async getAllChildFrameUrls(){let e=this.pageGetter(),t=await Do({cdpClient:this.cdpClient,page:e,logger:this.logger}),n=Array.from(t.childFrames),o=[];for(;n.length>0;){let i=n.shift();n.push(...i.childFrames),o.push(i.src??i.url)}return o}async getDomGraph({devicePixelRatio:e,signal:t,logger:n}){return this.getDOMTree({devicePixelRatio:e??1,signal:t,logger:n??this.logger})}async getA11yTree(e){let t={},n=e.logger??this.logger,o=e.abortSignal??this.abortSignalGetter(),i=this.pageGetter(),a,l,c=null;if(this.frameConfig?.type==="url"){if(a=await Wt({fn:()=>this.resolveActiveFrameConfig({logger:n,signal:o}),codePath:"getActiveFrameDetails",logObject:t,signal:o,logger:n})??void 0,!a)throw new w("ActionFailureError","Got null frame details despite active frame config");l=a.handle,c=l.frameId}else this.userBrowserSettings.autoExpandIframes?(l=await Wt({fn:()=>Do({cdpClient:this.cdpClient,page:this.pageGetter(),logger:n}),codePath:"getMomenticFrameTree",logObject:t,signal:o,logger:n}),c=null):(l={type:"root",page:i,childFrames:[]},c=null);await Wt({fn:async()=>this.addMomenticIds({rootPage:i,childFrames:l.childFrames,frameFilter:a?.frame,logger:n}),codePath:"addIdsToElement",logObject:t,signal:o,logger:n});let s=await Wt({fn:()=>this.getDOMTree({devicePixelRatio:e.devicePixelRatio??1,signal:o,logger:n}),codePath:"domFetch",logObject:t,signal:o,logger:n}),u=await Wt({fn:()=>this.getRawA11yGraph({cdpClient:this.cdpClient,frameId:c,childFrames:l.childFrames,logTimings:t,logger:n,signal:o}),codePath:"totalA11yFetch",logObject:t,signal:o,logger:n}),{tree:d}=await Wt({fn:()=>this.composeA11yDomGraph({opts:e,a11yGraph:u,domGraph:s,startingFrameId:c,frameContext:l,logger:n,iconKnowledgeBase:this.iconKnowledgeBase,showZeroOpacityElements:e.showZeroOpacityElements,flagNotActionableNodes:e.flagNotActionableNodes}),codePath:"a11yProcess",logObject:t,signal:o,logger:n});return Object.values(t).some(p=>p>750)&&n.warn({logTimings:t},"A11y tree fetch component took a long time"),this.lastA11yIdToNodeMap=d.a11yIdNodeMap,this.lastDataMomenticIdToNodeMap=d.dataMomenticIdMap,this.lastA11yTreeRoot=d.root,this.lastDomGraph=s,this.lastSelectorToNodeMap=d.selectorToNodeMap,d}async fetchA11yTreeForRecording(e,t){if(await this.getA11yTree({devicePixelRatio:e,abortSignal:t,logger:bn,filterByViewport:!1,flagNotActionableNodes:!1}),Math.random()<.1){let n=this.lastA11yTreeRoot?.serialize();this.logger.debug({tree:n&&n.length>4e5?"REDACTED_DUE_TO_SIZE":n},"Refreshed a11y tree during recording")}}async getLocatorFromA11yNode({page:e,root:t,node:n}){if(n.backendNodeId===void 0)throw new Error(`Node with a11y id ${n.id} has no backend node ID: ${n.getNodeOnlySerializedForm()}`);if(this.userBrowserSettings.visualActions){let o=this.domGraph?.backendIdToNode[n.backendNodeId];if(!o)throw new Error(`Could not find DOM node for backend node ID ${n.backendNodeId}`);let i=mT({node:o,domGraph:this.domGraph});return gT(e,i)}else return this.getLocatorFromBackendId(t,n.backendNodeId)}async getLocatorFromBackendId(e,t){let n=await this.cdpClient.send({method:"DOM.resolveNode",params:{backendNodeId:t},timeout:2e3});if(!n||!n.object.objectId)throw new Error(`Could not resolve backend node ${t}`);let o;try{o=await hT(this.cdpClient,n.object.objectId)}catch(i){throw this.logger.debug({err:i,object:JSON.stringify(n.object)},"Failed to get ID attribute"),i}return e.locator(Qt(o))}getNodeUsingMPathSelector(e){let t=this.selectorToNodeMap[e];if(t)return t;let n=e.split(" > "),o="";for(let i=n.length-1;i>=0;i--){let a=n.slice(i).join(" > ");if(this.selectorToNodeMap[a]){o=a;break}}this.logger.warn({selectorMapSize:Object.keys(this.selectorToNodeMap).length,selector:e,closestSelector:o},"Could not find a11y node using mpath selector")}async resolveUrlMatcherFrameConfig({config:e,signal:t=this.abortSignalGetter(),logger:n=this.logger}){let o=Date.now(),i,a,l,c=0;for(;Date.now()-o<this.smartWaitingTimeoutMs;)try{i=await Do({cdpClient:this.cdpClient,page:this.pageGetter(),logger:n}),a=await this.getMatchingFrameByUrlWithCdp(i,e),n.info({frameId:a.handle.frameId,url:a.handle.url,src:a.handle.src,locationData:a.handle.locationData},`Found matching frame using ${a.matchType}`);break}catch(s){if(l=s,s instanceof w&&s.reason==="UserInfrastructureError")throw s;c%3===0&&this.logger.warn({attempt:c,err:s},"Failed to resolve active frame, retrying..."),await $(500,t)}finally{c++}if(a)return{source:"url",frame:a.frame,handle:a.handle,frameIdentifierStringified:xl(e),cacheTime:Date.now(),frameTree:i,mPathSelectorTokens:[]};throw l}async getMatchingFrameByUrlWithCdp(e,t){let n=t.url,o=this.pageGetter(),i=Array.from(e.childFrames),a=[];for(;i.length>0;){let l=i.shift(),c=l.domNode;i.push(...l.childFrames);let s=tn(c.attributes??[],"src"),u=c.contentDocument?.documentURL;if(!s&&!u){this.logger.debug("Skipping frame with no URL or src");continue}for(let d of[s,u])if(d){if(n.startsWith("/")&&n.endsWith("/")){if(new RegExp(n.slice(1,-1)).test(d)){a.push({handle:l,matchType:"regex",...await fr(l,o)});break}}else if(n.trim()===d.trim()){a.push({handle:l,matchType:"url",...await fr(l,o)});break}}}if(a.length===1){let l=a[0];return this.userBrowserSettings.autoExpandIframes||(l.handle.childFrames=[]),l}else throw a.length>1?new Error(`Found multiple frames with src matching '${n}'. Please use a more specific selector.`):new w("ActionFailureError",`Failed to find frame with src matching: ${n}`)}async composeA11yDomGraph({opts:e,a11yGraph:t,domGraph:n,startingFrameId:o,frameContext:i,logger:a,iconKnowledgeBase:l,showZeroOpacityElements:c,flagNotActionableNodes:s}){let u=await RT({rawA11yGraph:t,startingFrameId:o,frameContext:i,domGraph:n,logger:a,cdpClient:this.cdpClient,showZeroOpacityElements:c,flagNotActionableNodes:s,filterByViewport:e.filterByViewport,importantProperties:{attributes:this.userBrowserSettings.importantAttributes,classes:this.userBrowserSettings.importantClasses,styles:this.userBrowserSettings.importantStyles},viewportDetails:void 0,iconKnowledgeBase:l,useMPaths:this.userBrowserSettings.visualActions});if(!u||!u.root)throw new Error("Accessibility tree appears empty");return{tree:u}}async addMomenticIds({rootPage:e,childFrames:t,frameFilter:n,logger:o}){if(this.userBrowserSettings.visualActions)return;let i=await this.addMomenticIdsHelper(n??e,1);if(!this.userBrowserSettings.autoExpandIframes||n)return;let a=Array.from(t),l=[];for(;a.length>0;){let c=a.shift();a.push(...c.childFrames);let s=async()=>{try{let{frame:u}=await fr(c,e);i=await this.addMomenticIdsHelper(u,i)}catch(u){c.url!=="about:blank"&&o.warn({err:u},"Error adding momentic IDs to child frame, continuing...")}};l.push(s())}await Promise.all(l)}async addMomenticIdsHelper(e,t){if(this.userBrowserSettings.visualActions)return t;let n=this.logger;return await je({root:e,fn:i=>window.addIdsToElement?.(document.body,i),arg:t,timeout:2e3,waitForPageLoad:async()=>{try{await e.waitForLoadState("domcontentloaded",{timeout:this.smartWaitingTimeoutMs})}catch(i){n.warn({err:i},"Error loading frame root adding momentic ids, continuing...")}},codePath:"adding Momentic element IDs to the page"})??t}getPageDomain(e){try{let t=new URL(e);if(!t.hostname)return null;let n=t.hostname.split("."),o=n.length>2?n.slice(-2).join("."):t.hostname;return`${t.protocol}//${o}`}catch{return null}}async decideChildFrameUnrollEligibility({logger:e,warnings:t,handle:n}){try{let{shouldUnroll:o,reason:i}=await this.decideChildFrameUnrollEligibilityHelper({domNode:n.domNode});return{shouldUnroll:o,reason:i}}catch(o){if(o.message.includes("Could not compute box model"))return{shouldUnroll:!1};let i=`Got error when determining whether to filter frame ${n.frameId} with url ${n.url}, allowing it to be fetched: ${o}`;return t?.push(i),e?.warn({err:o},i),{shouldUnroll:!0}}}async decideChildFrameUnrollEligibilityHelper({domNode:e}){let t=e.attributes??[];if(tn(t,"aria-hidden")==="true")return{shouldUnroll:!1,reason:"aria-hidden"};let n=tn(t,"style");if(n?.includes("display: none")||n?.includes("visibility: hidden"))return{shouldUnroll:!1,reason:"hidden CSS style"};await this.cdpClient.send({timeout:3e3,method:"DOM.pushNodesByBackendIdsToFrontend",params:{backendNodeIds:[e.backendNodeId]}});let[o,i]=await Promise.all([this.cdpClient.send({timeout:3e3,method:"DOM.getBoxModel",params:{backendNodeId:e.backendNodeId}}),this.cdpClient.send({timeout:3e3,method:"CSS.getComputedStyleForNode",params:{nodeId:e.nodeId}})]);if(!o.model||!o.model.height||!o.model.width)return{shouldUnroll:!1,reason:"no bounding box"};if(o.model.height<10||o.model.width<10)return{shouldUnroll:!1,reason:"small bounding box"};for(let a of i.computedStyle){if(a.name==="display"&&a.value==="none")return{shouldUnroll:!1,reason:"display: none"};if(a.name==="visibility"&&a.value==="hidden")return{shouldUnroll:!1,reason:"visibility: hidden"};if(a.name==="opacity"&&a.value==="0")return{shouldUnroll:!1,reason:"opacity: 0"}}return{shouldUnroll:!0}}async getRawA11yGraph({cdpClient:e,frameId:t,childFrames:n,logTimings:o,logger:i=this.logger,signal:a=this.abortSignalGetter()}){let l=[];try{await this.pageGetter().waitForLoadState("load",{timeout:this.pageLoadTimeoutMs})}catch(m){i.warn({err:m},"Failed to wait for page load event before a11y tree fetch, attempting to continue without it..."),await this.cdpClient.reinitialize()}let c,s;for(let m=0;m<3;m++)try{s=await Wt({fn:()=>this.getRawA11yTreeForFrame({frameId:t,timeoutMs:this.pageLoadTimeoutMs,logTimings:o}),codePath:"a11y-tree-fetch-root",logObject:o,signal:a,logger:i});break}catch(g){c=g,i.warn({err:g},"Reinitializing CDP client before retrying a11y graph fetch"),await this.cdpClient.reinitialize()}if(!s)throw new Error(`Failed to fetch accessibility tree for root page: ${c}`);let u={};if(u[t??"root"]=s,!this.userBrowserSettings.autoExpandIframes)return u;let d=Array.from(n),p=[];for(;d.length>0;){let m=d.shift();try{let{shouldUnroll:h}=await this.decideChildFrameUnrollEligibility({handle:m,warnings:l});if(!h)continue}catch(h){if(h.message.includes("Could not compute box model"))continue;l.push(`Got error when determining whether to filter frame ${m.frameId} with url ${m.url}, allowing it to be fetched: ${h}`)}d.push(...m.childFrames);let g=async()=>{try{let h=await Wt({fn:()=>this.getRawA11yTreeForFrame({frameId:m.frameId,timeoutMs:this.smartWaitingTimeoutMs,logTimings:o}),codePath:`a11y-tree-fetch-child-${m.frameId}`,logObject:o,signal:a,logger:i});u[m.frameId]=h}catch(h){i.warn({err:h,url:m.url,src:m.src},`Error getting raw a11y tree for child frame ${m.frameId}, continuing...`)}};p.push(g())}return await Promise.all(p),l.length>0&&this.logger.warn({warnings:l},"Got warnings when fetching the raw a11y graph"),u}async getRawA11yTreeForFrame({frameId:e,timeoutMs:t,logTimings:n}){let o;if(this.allowPartialAccessibilityTree)o=(await Wt({fn:()=>this.cdpClient.send({method:"Accessibility.getFullAXTree",params:{frameId:e??void 0},timeout:t,timeoutMsg:`Fetching the document tree took over ${t}ms. This usually indicates that the current page is too large to be loaded at once, or your machine is severely resource constrained.`}),codePath:"cdp-query-ax-tree",logObject:n,signal:this.abortSignalGetter(),logger:this.logger})).nodes;else{let a=(await Wt({fn:()=>this.cdpClient.send({method:"Accessibility.getRootAXNode",params:{frameId:e??void 0},timeout:2e3}),codePath:"cdp-get-root-ax-node",logObject:n,signal:this.abortSignalGetter(),logger:this.logger})).node.backendDOMNodeId;o=(await Wt({fn:()=>this.cdpClient.send({method:"Accessibility.queryAXTree",params:{backendNodeId:a},timeout:t,timeoutMsg:`Fetching the document tree took over ${t}ms. This usually indicates that the current page is too large to be loaded at once, or your machine is severely resource constrained.`}),codePath:"cdp-query-ax-tree",logObject:n,signal:this.abortSignalGetter(),logger:this.logger})).nodes}if(!o||o.length<=1)throw new Error("Document is entirely empty");return{root:o[0],allNodes:o}}async getDOMTree({devicePixelRatio:e,signal:t,logger:n}){let o,i=0,a;for(;!o&&i<3;)try{if(o=await this.cdpClient.send({method:"DOMSnapshot.captureSnapshot",params:{computedStyles:this.computedStylesToFetch},timeout:3e3}),!o||!o.documents.length)throw new Error("Got empty DOM tree")}catch(l){await $(500,t),i++,a=l}if(!o||!o.documents.length)throw n.error({err:a},"Fatal error fetching DOM tree"),new w("UserInfrastructureError",`Received an empty HTML snapshot from the browser. This usually indicates the page has crashed due to resource consumption issues or hanging client-side JavaScript code: ${a?.message}`);return pT({snapshot:o,devicePixelRatio:e,computedStylesToFetch:this.computedStylesToFetch,logger:n})}constructIframeRegexAsync(e,t){if(t.frameSrcRegex||t.frameUrlRegex)return;let n=OT(e);(async()=>{try{let o=await this.enricher?.constructIframeRegex(n);o?.srcRegex&&(t.frameSrcRegex=o.srcRegex),o?.urlRegex&&(t.frameUrlRegex=o.urlRegex),this.logger.debug({result:o,params:n},"Constructed iframe regex for cache")}catch(o){this.logger.warn({err:o},"Failed to construct iframe regex, skipping...")}})()}};function gp(r){let e=[],t="";for(let n of r)n==="+"&&t?(e.push(t),t=""):t+=n;return e.push(t),e}var Sp=yr(Uo(),"momentic","chromium"),$N=yr(Uo(),"video"),Ll=process.env.TWO_CAPTCHA_KEY,$T=VN(WT);$T.use(jN({provider:{id:"2captcha",token:Ll},visualFeedback:!0}));var aa=class r{static USER_AGENT=HN["Desktop Chrome"].userAgent;abortSignal=void 0;contextInitialized=!1;browser;context;properties;page;userControlledBrowserSettings;pageLoadPromises={};lastTabChangeEventTimeout=void 0;clientCallbacks;iconKnowledgeBase;lastIconKnowledgeBaseUpdateTime=0;cdpClient;debugData={logsPerPage:[],harPages:{},harEntries:{}};recentFrameNavigations={};requestRecorders={};mocks={};customHeaders=[];enricher;storage;logger;stateManager;transformer;lastScreenshotForRecording=void 0;originsVisited=new Set;viewport;videos=[];baseUrl;constructor({storage:e,enricher:t,browser:n,context:o,page:i,baseUrl:a,logger:l,userBrowserSettings:c,viewport:s,properties:u,clientCallbacks:d,iconKnowledgeBase:p}){if(Tf(c),this.storage=e,this.enricher=t,this.browser=n,this.context=o,this.page=i,this.baseUrl=a,this.logger=l,this.userControlledBrowserSettings=c,this.viewport=s,this.properties=u,this.clientCallbacks=d,u.recordVideo){let m=this.page.video();m&&this.videos.push(m)}this.iconKnowledgeBase=p}registerAbortSignal(e){this.abortSignal=e}async initialize({grantPermissions:e,runInitScripts:t}){if(this.contextInitialized)return;this.userControlledBrowserSettings.extraHeaders&&await this.context.setExtraHTTPHeaders(this.userControlledBrowserSettings.extraHeaders),e&&await this.context.grantPermissions(["clipboard-read","clipboard-write","microphone","camera","geolocation"]);let n={[vl]:this.userBrowserSettings.visualActions},o=[this.context.addInitScript({content:Db.htmlUtilsLibJs}),this.context.addInitScript({content:`window._MOMENTIC_BROWSER = true; window._MOMENTIC_FEATURE_FLAGS = ${JSON.stringify(n)}; window.addEventListener('load', (event) => { console.log('[MOMENTIC] Page loaded'); });`})];t&&await this.page.reload();let i=l=>this.handleNewPageEvent(l);this.context.on("page",i),this.handleNewPageEventHelper(this.page),this.context.on("close",()=>{this.context.off("page",i)});let a=Promise.all(o);await Promise.all([a]),this.properties.systemDevicePixelRatio||(process.env.MOMENTIC_LOCAL_DEV==="1"&&Ol()==="darwin"&&PN("system_profiler SPDisplaysDataType").toString().includes("Retina")?(R.warn("[DEV] Setting device pixel ratio to 2 in local dev since a Retina display was detected"),this.properties.systemDevicePixelRatio=2):this.properties.systemDevicePixelRatio=await this.page.evaluate(()=>window.devicePixelRatio)),this.cdpClient=await Cl.init({logger:this.logger,contextGetter:()=>this.context,pageGetter:()=>this.page,defaultTimeoutMs:this.pageLoadTimeout}),await this.initializeScreencast(),this.stateManager=new Pl({smartWaitingTimeoutMs:this.smartWaitingTimeout,pageLoadTimeoutMs:this.pageLoadTimeout,allowPartialAccessibilityTree:this.userControlledBrowserSettings.allowPartialAccessibilityTree??!1,logger:this.logger,cdpClient:this.cdpClient,pageGetter:()=>this.page,abortSignalGetter:()=>this.abortSignal,enricher:this.enricher,iconKnowledgeBase:this.iconKnowledgeBase,userBrowserSettings:this.userBrowserSettings}),this.contextInitialized=!0}async fixViewportForNewHeadless(){this.properties.isNewHeadless&&this.viewport&&await this.cdpClient.send({method:"Emulation.setDeviceMetricsOverride",params:{width:this.viewport.width,height:this.viewport.height,deviceScaleFactor:0,mobile:this.viewport.width<1e3}})}async initializeScreencast(){await this.fixViewportForNewHeadless(),this.clientCallbacks?.onScreencastFrame&&this.viewport&&(await this.cdpClient.send({method:"Page.startScreencast",params:{format:"jpeg",quality:75,maxWidth:this.viewport.width,maxHeight:this.viewport.height}}),this.cdpClient.on("Page.screencastFrame",e=>{let t=e.sessionId,n=Buffer.from(e.data,"base64");this.lastScreenshotForRecording=n,this.clientCallbacks?.onScreencastFrame?.(n,()=>{(async()=>{try{await this.cdpClient.send({method:"Page.screencastFrameAck",params:{sessionId:t}})}catch{}})()})}))}static async init({baseUrl:e,logger:t,storage:n,enricher:o,userBrowserSettings:i,contextArgs:a,recordVideo:l,iconKnowledgeBase:c,callbacks:s}){r.clearCrashReportsDirs(),process.env.PW_TEST_SCREENSHOT_NO_FONTS_READY="1";let u;switch(i.browserType){case"Google Chrome":u="chrome";break;case"Chrome for Testing":u=void 0;break;case"Chromium":u="chromium";break;default:u="chromium";break}let d={headless:process.env.MOMENTIC_HEADFUL_BROWSER!=="true",handleSIGTERM:!1,chromiumSandbox:!1,channel:u},p={...a??{},geolocation:a?.geolocation||dg,locale:a?.locale||cg,timezoneId:a?.timezoneId||ug,colorScheme:a?.colorScheme,httpCredentials:i.basicAuthorization?{username:i.basicAuthorization.username??"",password:i.basicAuthorization.password??""}:void 0,javaScriptEnabled:i.disableJavaScript?!1:void 0,ignoreHTTPSErrors:i.ignoreHttpsErrors??!1,userAgent:i.userAgent??r.USER_AGENT,viewport:a?.viewport??Br},m=["--disable-dev-shm-usage","--no-first-run","--renderer-process-limit=3","--browser-test","--disable-site-isolation-for-policy","--disable-site-isolation-trials","--disable-backgrounding-occluded-windows","--disable-background-timer-throttling","--disable-renderer-backgrounding","--autoplay-policy=user-gesture-required","--disable-add-to-shelf","--disable-desktop-notifications","--use-fake-device-for-media-stream","--use-fake-ui-for-media-stream","--enable-logging=stderr","--log-level=2","--enable-crashpad","--crash-on-hang-threads"];process.env.MOMENTIC_CHROME_EXTRA_ARGS&&m.push(...process.env.MOMENTIC_CHROME_EXTRA_ARGS.split(","));let g=null,h,f,E={systemDevicePixelRatio:a?.deviceScaleFactor,recordVideo:l,isNewHeadless:!1};(u==="chrome"||u==="chromium")&&(E.isNewHeadless=!0,d.headless&&m.push("--headless=new")),process.env.BROWSER_MEMORY_MB&&m.push(`--js-flags=--max_old_space_size=${process.env.BROWSER_MEMORY_MB}`),i.disableGpu&&m.push("--disable-3d-apis","--disable-gpu","--disable-software-rasterizer","--disable-accelerated-2d-canvas","--disable-accelerated-mjpeg-decode","--disable-accelerated-video-decode","--disable-accelerated-video-encode","--disable-gl-drawing-for-tests","--disable-webgl","--disable-audio-input","--disable-audio-output");let b=i.localChromeExtensionPaths?.map(A=>A.startsWith("~")?yr(Uo(),A.slice(1)):A);if(b?.length){if(u===void 0)throw new w("UserConfigurationError","Chrome extensions are only supported on Chromium and Google Chrome.");for(let N of b){let U=yr(N,"manifest.json");if(!Fn(U))throw new w("UserConfigurationError",`Chrome extension path ${U} does not exist.`)}if(En)throw new w("UserConfigurationError","Cannot use persistent browser context on Momentic Cloud");let A=yr(Sp,`momentic-session-${Date.now()}`);if(!Fn(A))try{ON(A,{recursive:!0})}catch(N){throw new w("UserConfigurationError",`Failed to create browser cache directory. Please make sure you have sufficient permissions to create the ${Sp} folder: ${N}`)}let T=[...m],x=b.map(N=>GN(N)).join(",");T.push(`--disable-extensions-except=${x}`),p?.deviceScaleFactor&&T.push(`--force-device-scale-factor=${p.deviceScaleFactor}`,`--device-scale-factor=${p.deviceScaleFactor}`),p.viewport&&T.push(`--window-size=${p.viewport.width},${p.viewport.height}`),h=await WT.launchPersistentContext(yr(Sp,`momentic-session-${Date.now()}`),{...d,...p,ignoreDefaultArgs:["--disable-extensions","--disable-component-extensions-with-background-pages"],args:T,baseURL:e}),t.info({sharedContextOptions:p,sharedBrowserOptions:d,userBrowserSettings:i,chromeArgs:T,properties:E,baseUrl:e},"Browser initialization context args (persistent)"),f=h.pages()[0]}else{g=await $T.launch({...d,args:m});let A={...p,baseURL:e,recordVideo:l?{dir:$N}:void 0};h=await g.newContext(A),t.info({contextArgs:A,sharedBrowserOptions:d,chromeArgs:m,userBrowserSettings:i,properties:E,baseUrl:e},"Browser initialization context args (standard)"),f=await h.newPage()}En&&await h.route("**",Ml);let v=new r({browser:g,context:h,page:f,baseUrl:e,logger:t,storage:n,enricher:o,userBrowserSettings:i,viewport:p.viewport||Br,properties:E,clientCallbacks:s,iconKnowledgeBase:c});return await v.initialize({grantPermissions:!0,runInitScripts:!1}),v}static async fromExistingContext({context:e,storage:t,enricher:n,userBrowserSettings:o,logger:i}){let a=e.pages()[0];if(!a)throw new Error("No page found in existing context");let l=a.viewportSize(),c=a?.url(),s=new r({browser:e.browser(),context:e,page:a,baseUrl:c,logger:i,storage:t,enricher:n,userBrowserSettings:o,viewport:l,properties:{isNewHeadless:!0},clientCallbacks:void 0,iconKnowledgeBase:null});return await s.initialize({grantPermissions:!1,runInitScripts:!0}),s}async handleAvailableTabsChangeHelper(){try{let e=await np(this.context,{getTitles:!0}),t=this.page.url();this.clientCallbacks?.onTabsChange?.(e,t)}catch(e){this.logger.error({err:e},"Error sending available tabs to frontend")}}handleAvailableTabsChange(){try{clearTimeout(this.lastTabChangeEventTimeout),this.lastTabChangeEventTimeout=setTimeout(()=>this.handleAvailableTabsChangeHelper(),500)}catch(e){this.logger.warn({err:e},"Error handling available tabs change")}}addToPageLoadPromises(e,t){let n=hp(),o=`${e}-${n}`,i=Date.now(),a=!1,l=async()=>{try{await B(t(),{signal:this.abortSignal,milliseconds:this.pageLoadTimeout,message:`Page load promise for code path ${e} timed out after ${this.pageLoadTimeout}ms`})}catch(c){c.name!=="AbortError"&&this.logger.error({err:c,promiseKey:o,codePath:e,duration:Date.now()-i},`Page load promise for code path ${e} encountered error`)}finally{delete this.pageLoadPromises[o],a=!0}};this.pageLoadPromises[o]=l().catch(()=>{}),a&&delete this.pageLoadPromises[o]}handlePageClosedEvent(e){if(this.page!==e){this.logger.debug({url:e.url()},"Detected background page was closed, just updating available tabs only"),this.handleAvailableTabsChange();return}let t=async()=>{if(this.closed)return;this.logger.info({url:e.url()},"Detected active page was closed, switching to another tab");let n=this.context.pages();for(let o=n.length-1;o>=0;o--){let i=n[o];if(!(!i||i.isClosed()||!Cn(i.url()))){this.logger.info(`Automatically switching to tab ${o} after close: ${i.url()}`),await this.switchToPage({type:"INDEX",index:String(o)});break}}};this.addToPageLoadPromises("page closed handler",async()=>t())}handleNewPageEvent(e){let t=e.url();if(this.logger.info({url:t},"Detected new page event, registering handlers and waiting for load to complete"),this.properties.recordVideo){let n=e.video();n&&this.videos.push(n)}try{this.handleNewPageEventHelper(e)}catch(n){this.logger.warn({err:n},"Error handling new page open, continuing....")}}handleNewPageEventHelper(e){let t=hp(),n="new-page-load-handler";e.on("close",a=>this.handlePageClosedEvent(a)),e.on("framenavigated",a=>this.handleFrameNavigationEvent(a)),e.on("crash",()=>{this.logger.error("Page crashed at the Playwright level!")});let o=this.context.pages().indexOf(e);e.on("console",a=>{$b(e,o,this.debugData,a,this.logger)});let i=async()=>{await Yb(t,this.debugData,e),await e.route("**/*",async(a,l)=>{await dp({pageId:t,route:a,request:l,debugData:this.debugData,logger:this.logger,requestRecorders:this.requestRecorders,mocks:this.mocks})}),await e.route("**/*",DT(this.customHeaders,this.logger)),En&&await e.route("**/*",Ml),await this.loadFrameAndRecordUrl({root:e,codePath:n}),this.handleAvailableTabsChange()};this.addToPageLoadPromises(n,async()=>i())}async handleCollectSvgs(e){}handleFrameNavigationEvent(e){let t=e.url(),n=e.parentFrame()?"has-parent":"no-parent",o=`frame-navigation-handler-${t.slice(0,50)} (${n})`;if(!t||t==="about:blank"||!Cn(t)||this.recentFrameNavigations[o]&&Date.now()-this.recentFrameNavigations[o]<1e3)return;this.recentFrameNavigations[o]=Date.now();let i=async()=>{try{if(e.isDetached())return;await this.loadFrameAndRecordUrl({root:e,codePath:o,signal:this.abortSignal}),this.handleAvailableTabsChange(),!e.parentFrame()&&!e.isDetached()&&this.clientCallbacks?.onSvgsCollected&&(setTimeout(()=>{(async()=>{try{await this.handleCollectSvgs(e)}catch(l){this.logger.warn({err:l},"Failed to collect SVGs on page, continuing...")}})()},5e3),this.transformer&&await this.injectKnowledgeBaseIntoBrowser(e))}catch(a){a.name!=="AbortError"&&this.logger.warn({err:a,url:t,codePath:o},"Failed to handle frame navigation event, continuing...")}};this.addToPageLoadPromises(o,async()=>i())}async injectKnowledgeBaseIntoBrowser(e){try{if(!this.iconKnowledgeBase||await e.evaluate(()=>!!window._MOMENTIC_ICON_KNOWLEDGE_BASE))return;let n={};Object.keys(this.iconKnowledgeBase).forEach(o=>{this.iconKnowledgeBase[o]?.description&&(n[o]=this.iconKnowledgeBase[o].description)}),await e.evaluate(o=>{let i=window;i._MOMENTIC_ICON_KNOWLEDGE_BASE=o},n)}catch(t){this.logger.warn({err:t},"Failed to inject icon knowledge base into browser, continuing...")}}getBrowserCallbacks(){return{waitForPageLoad:()=>this.waitForPageLoad(),waitForUrl:e=>this.waitForUrl(e),getBrowserState:e=>this.getBrowserState(e),waitForDomStability:e=>this.waitForDOMStability(e),state:{url:()=>this.url(),getDomGraph:()=>this.stateManager.domGraph,getOpenPages:()=>this.getOpenPages(),getRoot:()=>this.getActivePageOrFrame(),userBrowserSettings:this.userBrowserSettings},pageLoadTimeoutMs:this.pageLoadTimeout,signal:this.abortSignal}}ping(){if(this.closed)throw new Error("Page has been closed")}setActiveFrameConfig(e){this.stateManager.setActiveFrameConfig(e)}async reset(e){for(this.abortSignal=void 0,this.debugData.logsPerPage=[],this.debugData.harPages={},this.debugData.harEntries={},this.pageLoadPromises={};this.videos.length>0;)this.videos.pop();await this.clearAuthState({closeNonActiveTabs:!0}),await this.stopScreencast(),await this.reinitializeCDPClient(),await this.navigate({url:e.newUrl??this.baseUrl,initialNavigation:!0,loadTimeoutMs:e.timeout}),this.stateManager.reset()}async clearHighlights(){try{await B(ep(this.getBrowserCallbacks()),{milliseconds:1e3})}catch(e){this.logger.debug({err:e},"Failed to clear highlights, continuing...")}}async cleanup(){this.abortSignal=void 0;try{this.originsVisited.clear(),await this.context.close(),await this.browser?.close(),this.browser=null}catch(e){this.logger.warn({err:e},"Error cleaning up browser, continuing...")}finally{this.browser=null}}get closed(){return this.context.pages().every(e=>e.isClosed())||!!this.browser&&!this.browser.isConnected()}async ensureMomenticBrowserScriptsLoaded(e,t,n){let o=Date.now(),i=0,a=0;for(;Date.now()-o<8e3;){a++,n?.throwIfAborted();try{if(await je({fn:()=>{let c=window;return!!(c.generateCssSelectors&&c.evaluateCssSelectors&&c.evaluatePrimaryCaches&&c.generateHtmlCacheAttributes&&c.ldist)},timeout:1e3,arg:void 0,waitForPageLoad:()=>this.waitForPageLoad(),root:e,codePath:"ensuring Momentic system scripts are loaded"}))return}catch(l){if(i++,i>=3){t.warn({err:l},"Multiple errors checking if Momentic scripts are loaded, aborting...");return}}await $(500),a%2===0&&t.warn("Still waiting for momentic browser scripts to load...")}throw new Error(`Failed to load momentic browser scripts on page ${e.url()}`)}async html(){let e=await this.getActivePageOrFrame();return await this.ensureMomenticBrowserScriptsLoaded(e,this.logger),je({root:e,fn:()=>{let t=window;if(!t?.getFullHtmlTree)throw new Error("Missing Momentic HTML library when fetching page HTML");return t.getFullHtmlTree()},arg:void 0,timeout:3e3,waitForPageLoad:()=>this.waitForPageLoad(),codePath:"getting the full HTML tree"})}url(){return this.page.url()}async stabilizePageForScreenshot(){try{await this.evaluateFunctionInPage(()=>{let e=window,t=[],n=new Map;document.querySelectorAll("input,textarea,[contenteditable]").forEach(o=>{n.set(o,{value:o.style.getPropertyValue("caret-color"),priority:o.style.getPropertyPriority("caret-color")}),o.style.setProperty("caret-color","transparent","important")}),t.push(()=>{for(let[o,i]of n)o.style.setProperty("caret-color",i.value,i.priority)}),e._MOMENTIC_SCREENSHOT_CLEANUP=()=>{for(let o of t)o();delete e._MOMENTIC_SCREENSHOT_CLEANUP}},void 0,"stabilizing page for screenshot")}catch(e){(!(e instanceof Error)||!e.message.includes("Execution context was destroyed"))&&this.logger.warn({err:e},"Failed to stabilize page before screenshot, continuing...")}}async removeScreenshotStabilization(){try{await this.evaluateFunctionInPage(()=>{window._MOMENTIC_SCREENSHOT_CLEANUP?.()},void 0,"removing screenshot stabilization")}catch{}}async screenshot(e){let{retries:t=1,stabilizeBeforeScreenshot:n=!1}=e,o=this.page.url();n&&await this.stabilizePageForScreenshot();let i=Date.now();try{await this.fixViewportForNewHeadless();let a=await this.screenshotHelper({...e,retries:t});if(a.byteLength>5e6)this.logger.error("Page screenshot is greater than 5MB, which may cause performance issues with some AI models");else if(a.length===0)throw new Error("Got empty screenshot");return a}catch(a){if(t<=0||a.message.includes("has been closed"))throw a;return this.logger.warn({err:a,pageUrl:o},"Failed taking screenshot, retrying..."),await $(250),this.screenshot({...e,retries:t-1})}finally{Date.now()-i>1e3&&this.logger.warn({pageUrl:o,duration:Date.now()-i},"Screenshot took longer than expected"),n&&await this.removeScreenshotStabilization()}}async screenshotHelper({locator:e,quality:t,saveToDiskPath:n,timeout:o,respectActiveFrame:i,clearHighlights:a=!1}){a&&await this.clearHighlights(),i&&this.stateManager.frameConfig&&(e=await(await this.getActivePageOrFrame()).frameElement());let l=await this.cdpClient.send({method:"Page.captureScreenshot",params:{format:"jpeg",quality:t,optimizeForSpeed:!0},timeout:o??2e3}),c=Buffer.from(l.data,"base64"),s=await VT.fromBuffer(c),{width:u,height:d}=this.getViewport()??{};if(u&&d&&(s.bitmap.width!==u||s.bitmap.height!==d)&&(c=await s.resize({w:u,h:d}).getBuffer("image/jpeg")),n&&kN(n,c),this.lastScreenshotForRecording=c,!e)return c;let p=await e.boundingBox({timeout:3e3});if(!p)throw new Error("Attempted to screenshot an element that is not visible on the page");let{x:m,y:g,width:h,height:f}=p;if(!h||!f)throw new Error("Attempted to screenshot an element with zero width or height");m=Math.floor(m),g=Math.floor(g),h=Math.floor(h),f=Math.floor(f);try{let E=await VT.fromBuffer(c),b=E.bitmap.width,v=E.bitmap.height;m=Math.max(0,Math.min(m,b-1)),g=Math.max(0,Math.min(g,v-1)),h=Math.max(1,Math.min(h,b-m)),f=Math.max(1,Math.min(f,v-g)),c=await E.crop({x:m,y:g,w:h,h:f}).getBuffer("image/jpeg")}catch(E){throw new Error(`Failed taking element screenshot at coordinates (${m}, ${g}) with size (${h}, ${f}): ${E}`)}finally{"dispose"in e&&await e?.dispose()}return c}getViewport(){return this.viewport?this.viewport:this.page.viewportSize()}async navigate({url:e,initialNavigation:t=!1,loadTimeoutMs:n=this.pageLoadTimeout}){AS(e)&&(e=new URL(e,this.baseUrl).toString());let o=Date.now();t||(await this.waitForPageLoad(),await this.waitForDOMStability());let i=!1,a;for(let c=0;c<3;c++)try{await this.page.goto(e,{timeout:n,waitUntil:"domcontentloaded"}),i=!0;break}catch(s){if(a=s,this.abortSignal?.throwIfAborted(),this.logger.warn({err:s},`Error occurred during navigation${c===0?", retrying...":" (fatal)"}`),await $(500),a.message.includes("Timeout")&&a.message.includes("exceeded")||a.message.includes("net::ERR_CONNECTION_REFUSED"))break;await this.cdpClient.send({method:"Page.stopLoading",params:{},timeout:1e3})}if(!i)throw new w("UserInfrastructureError",a?.message??"Failed to load page");await this.loadFrameAndRecordUrl({root:this.page,signal:this.abortSignal,codePath:"navigate-step-wait-for-load"}),this.logger.info({url:e},`Navigation complete in ${Math.floor(Date.now()-o)}ms`);let l=this.url();if(Bb.has(l))throw new w("UserInfrastructureError",`${e} took too long to load \u{1F61E}. Please ensure the site is accessible and returns content within the page load timeout.`);if(t)try{await this.exposeRecordingBindings()}catch(c){c instanceof Error&&c.message.includes("already registered")||this.logger.error({err:c},"Failed to install Momentic libraries for action recording")}await this.fixViewportForNewHeadless()}async type(e,t={},n=!1){await this.directTypeHelper(e,t,n)}async getActiveElement(e){try{return await je({root:e,fn:()=>{let n=document.activeElement?.textContent??void 0;return n&&n.length>100&&(n=n.slice(0,100)+"...[TRUNCATED]"),document.activeElement?{tag:document.activeElement.tagName.toLowerCase(),contentEditable:document.activeElement.getAttribute("contenteditable")??void 0,textContent:n}:void 0},arg:void 0,timeout:1e3,waitForPageLoad:()=>this.waitForPageLoad(),codePath:"getting the active element"})}catch(t){this.logger.warn({err:t},"Failed to get active element");return}}async directTypeHelper(e,t={},n=!1){let o=await this.getActivePageOrFrame();await nT({root:o,text:e,options:t,logger:this.logger,callbacks:this.getBrowserCallbacks()});let i=await this.getActiveElement(o);if(n){let a=Date.now();for(;Date.now()-a<this.smartWaitingTimeout&&(!i||i.tag==="body");)await $(250),this.abortSignal?.throwIfAborted(),i=await this.getActiveElement(o);i||this.logger.warn("No active element found to type into, attempting anyways")}t.clearContent&&(t.forceClearContent||i?.tag==="input"||i?.tag==="textarea"?(process.platform==="darwin"?await this.page.keyboard.press("Meta+A"):await this.page.keyboard.press("Control+A"),await this.page.keyboard.press("Backspace"),await this.page.waitForTimeout(25)):this.logger.info({activeElementDetails:i},"Currently active element is not eligible for replace content, skipping...")),await this.page.keyboard.type(e,{delay:t.delay??Lm}),t.pressEnter&&await this.press("Enter",{})}async scrollIntoViewIfNeeded(e){try{await e.scrollIntoViewIfNeeded({timeout:2e3})}catch(t){this.logger.warn({err:t},"Failed to scroll into view, trying with raw JS");try{await e.evaluate(async n=>{let o=n.scrollTop;n.scrollIntoView(),await new Promise(a=>setTimeout(a,250));let i=Date.now();for(;Date.now()-i<1e3;){let a=n.scrollTop;if(a===o)break;o=a,await new Promise(l=>setTimeout(l,250))}},void 0,{timeout:2e3})}catch(n){this.logger.warn({err:n},"Failed to scroll into view using JS, continuing...")}}}async highlightA11yId(e){try{let{resolution:t}=await this.createTargetFromA11yId({id:e,description:null,targetSource:"AI",skipSaveToCache:!0});return await this.highlight(t.locator),!0}catch(t){return this.logger.debug({err:t,id:e},"Failed to highlight target"),!1}}async highlight(e){return Rl({locator:e,callbacks:this.getBrowserCallbacks(),logger:this.logger})}recordUrlVisited(e){try{let t=new URL(e).origin;if(t==="null")return;this.originsVisited.add(t)}catch(t){this.logger.warn({err:t},"Failed to record origin visited")}}async waitForPageLoad(){let e=Date.now(),t=Object.values(this.pageLoadPromises),n=Object.keys(this.pageLoadPromises),o=-1,i=0;for(;t.length!==0;){if(Date.now()-e>this.pageLoadTimeout&&this.logger.error({outstandingPromiseKeys:n,outstandingPromises:t},"Still waiting on page load promises"),Date.now()-o<20&&(i++,i>2)){this.logger.error({outstandingPromiseKeys:n,outstandingPromises:t},"Synchronous waiting loop detected, exiting page load wait");return}o=Date.now(),await Promise.allSettled(t),t=Object.values(this.pageLoadPromises),n=Object.keys(this.pageLoadPromises)}}async clearAuthState(e){await this.context.clearCookies();for(let o of this.originsVisited)this.logger.debug({origin:o},`Clearing data using CDP for origin ${o}`),await this.cdpClient.send({method:"Storage.clearDataForOrigin",params:{origin:o,storageTypes:"all"},timeout:1e3}),this.originsVisited.delete(o);let t=this.context.pages().indexOf(this.page),n=[...this.context.pages()];for(let o=0;o<n.length;o++){let i=n[o];if(i.isClosed())continue;let a=i.url();try{this.originsVisited.delete(new URL(a).origin)}catch{}await Wb(i,this.logger),o!==t&&e.closeNonActiveTabs&&(this.logger.info(`Closing tab ${o} with URL ${a}`),await i.close())}}async loadAuthState(e){await this.waitForPageLoad(),await this.waitForDOMStability(),!e||Object.keys(e).length===0?await this.clearAuthState({closeNonActiveTabs:!1}):await this.loadAuthStateHelper(e),await this.refresh(),await this.waitForDOMStability()}async loadAuthStateHelper(e){let t=[];for(let i of e.cookies??[]){let a=await this.setCookie(i);t=t.concat(a)}this.logger.info(`Loaded ${e.cookies?.length??0} cookies`),await this.cdpClient.send({method:"DOMStorage.enable",params:void 0,timeout:1e3});let n=0;for(let i of e.origins??[])for(let a of i.localStorage)try{await this.cdpClient.send({timeout:1e3,method:"DOMStorage.setDOMStorageItem",params:{storageId:{securityOrigin:new URL(i.origin).origin,isLocalStorage:!0},key:a.name,value:a.value}}),n++}catch(l){this.logger.warn({err:l,origin:i},"Failed to set local storage entry, continuing...");break}this.logger.info(`Loaded ${n} local storage entries`);let o=e.idb;o&&Object.keys(o).length>0&&(await jb(this.page,o,this.logger),this.logger.info(`Loaded ${Object.keys(o??{}).length} indexedDB databases`))}async saveAuthState(){let t=0,n=null;for(;t<=2;)try{await this.waitForPageLoad(),await this.waitForDOMStability();let o=await this.context.storageState();return o.idb=await Vb(this.page,this.logger),o}catch(o){if(n=o,t++,t<=2){this.logger.warn({err:o,retryCount:t,maxRetries:2},`Error saving auth state, retrying (${t}/2)...`);let i=Math.pow(2,t)*100;await new Promise(a=>setTimeout(a,i))}}throw this.logger.error({err:n},"Failed to save auth state after 2 retries"),new w("ActionFailureError",`Failed to save auth state: ${n?.message}`)}async getOpenPages(e){return np(this.context,e)}saveA11yDetailsToCache(e,t){t.content=e.content,t.name=e.name,t.role=e.role,t.numChildren=e.children.length,delete t.serializedForm,delete t.nodeOnlySerializedForm}async updateCacheWithNewNodeDetails({node:e,target:t,locator:n,forceSaveNewCssSelectors:o,startingBoundingBox:i,allowNotActionableNodesOverride:a,logger:l=this.logger}){if(e&&this.saveA11yDetailsToCache(e,t),t.frameCache=this.stateManager.saveAutoFrameCacheDetails(t.frameCache),n)try{let c=await this.fetchHtmlAttributes({locator:n,logger:l,startingBoundingBox:i,allowNotActionableNodesOverride:a}),s=!1;for(let u of["generatedSelectors","serializedHtml","nodeOnlySerializedHtml","hybridSelector"]){let d=c?.[u];if(d&&!t[u]){s=!0;break}if(d&&JSON.stringify(d)!==JSON.stringify(t[u])){s=!0;break}}c&&(o||s)&&(t.generatedSelectors=c.generatedSelectors,t.serializedHtml=c.serializedHtml,t.nodeOnlySerializedHtml=c.nodeOnlySerializedHtml,t.hybridSelector=c.hybridSelector)}catch(c){if(c instanceof sr)throw c;l.warn({err:c},"Failed to fetch HTML attributes for target, continuing...")}try{await this.saveElementVisualAttributes({target:t,locator:n,logger:l,boundingBox:i})}catch(c){l.debug({err:c},"Failed to save element visual details, continuing...")}}async saveElementVisualAttributes({target:e,locator:t,logger:n,boundingBox:o}){if(!t)return{scrollPerformed:!1};if(!Hd.includes(e?.role??""))return{scrollPerformed:!1};if(await this.scrollIntoViewIfNeeded(t),o||(o=await t.boundingBox({timeout:3e3})),!o||!o.width||!o.height)return n.debug("Skipping visual attributes saving for element with no bounding box after action"),e.boundingBox=void 0,e.screenshotUrl=void 0,{scrollPerformed:!0};let{x:i=0,y:a=0,width:l=0,height:c=0}=o;if(e.boundingBox&&Math.abs(e.boundingBox.width-l)<1&&Math.abs(e.boundingBox.height-c)<1&&Math.abs((e.boundingBox.x??0)-i)<1&&Math.abs((e.boundingBox.y??0)-a)<1)return{scrollPerformed:!0};e.boundingBox=o;let s=await this.screenshot({locator:t,quality:75,retries:0});return e.screenshotUrl=await this.storage.uploadScreenshot(s),{scrollPerformed:!0}}async resolveAutoFrameCache(e){return this.stateManager.resolveAutoFrameCache(e)}async getElementRequiredValues({locator:e,requirements:t}){let n={};if(t?.boundingBox){let o=await e.boundingBox({timeout:3e3});if(!o||!o.width||!o.height)throw new w("ActionFailureError","Element does not have a bounding box as required");n.boundingBox=o??void 0}if(t?.text){let o=await e.innerText({timeout:3e3});n.text=o?.trim()}if(t?.attributes&&t.attributes.length>0){let o={};for(let i of t.attributes){let a=i.trim().toLowerCase();if(!(!a||jt.bannedAiRequiredCacheAttributes.includes(a)))try{let l=await e.getAttribute(a,{timeout:3e3});l!==null&&(o[i]=l)}catch(l){this.logger.warn({err:l,attr:i},"Failed to fetch required attribute, continuing...")}}n.attributes=o}return n}async getAdditionalElementDetails({mainLocator:e,additionalElement:t,root:n,logger:o}){let i=this.stateManager.a11yIdToNodeMap[t.id];if(!i)return;let a=await this.stateManager.getLocatorFromA11yNode({page:this.page,root:n,node:i});if(e.contentFrame!==a.contentFrame)return;let l=await this.fetchHtmlAttributes({locator:a,logger:o});if(!l?.generatedSelectors||l.generatedSelectors.length===0)return;let c={selectors:l.generatedSelectors};return t.requirements&&(c.requirements=await this.getElementRequiredValues({locator:a,requirements:t.requirements})),c}async getAdditionalElementsDetails({mainElementId:e,mainLocator:t,additionalElements:n,root:o,logger:i}){let a=new Set,l=[];for(let c of n)try{if(c.id===e||a.has(c.id))continue;let s=await this.getAdditionalElementDetails({mainLocator:t,additionalElement:c,root:o,logger:i});if(a.add(c.id),!s)continue;l.push(s)}catch(s){this.logger.warn({err:s,additionalElement:c},"Failed to fetch additional element details, continuing...")}return l}async updateCacheWithAdditionalRequirements({mainElementId:e,requirements:t,additionalElements:n,target:o,locator:i,root:a,logger:l}){t&&(o.requirements=await this.getElementRequiredValues({locator:i,requirements:t})),n&&(o.additionalElements=await this.getAdditionalElementsDetails({mainElementId:e,mainLocator:i,additionalElements:n,root:a,logger:l}))}async createTargetFromA11yId({id:e,description:t,targetSource:n,skipSaveToCache:o,logger:i=this.logger,requirements:a,additionalElements:l}){if(e<0)throw new w("InternalWebAgentError","Only positive IDs should be passed to resolveAllyIdToTarget");let c=this.stateManager.a11yIdToNodeMap[e];if(!c)throw new w("InternalWebAgentError",`Resolving target failed because id ${e} does not exist on the page. This generally indicates an incorrect element was targeted.`);let s=this.stateManager.frameConfig,u,d,p,m;if(this.userBrowserSettings.autoExpandIframes&&!s&&c.parentFrame){let b=c.parentFrame,{cache:v,config:A}=await this.stateManager.getAutoFrameDetailsFromHandle(b);d=v,p=A,u=A.frame,m="auto iframe"}else c.parentFrame&&s?(p=s,u=await this.getActivePageOrFrame(),m="hardcoded url already on the state manager"):(u=await this.getActivePageOrFrame(),m="should not be possible");let g=await this.stateManager.getLocatorFromA11yNode({page:this.page,root:u,node:c}),h={id:e,inputDescription:t??void 0,targetSource:n,targetUpdateTime:new Date().toISOString(),targetUpdateLoggerTags:pe(i),frameCache:d},f,E=!1;o||(p&&(i.info({frameConfigSource:m,frameConfig:LT(p)},"A11y node was resolved to a target within an iframe"),f=this.stateManager.frameConfig,this.stateManager.setActiveFrameConfig(p),E=!0),await this.updateCacheWithNewNodeDetails({node:c,target:h,locator:g,logger:i,forceSaveNewCssSelectors:!0,allowNotActionableNodesOverride:!0}),await this.updateCacheWithAdditionalRequirements({mainElementId:e,requirements:a,additionalElements:l,target:h,root:u,locator:g,logger:i}));try{return{resolution:{locator:g,a11yNode:c,displayString:c.getNodeOnlySerializedForm(),decisions:[]},target:h,frameConfig:p,frameConfigSource:m}}finally{E&&this.stateManager.setActiveFrameConfig(f)}}async resolveTarget(e,t,n={}){let{targetName:o,logger:i=this.logger,signal:a=this.abortSignal,allowNotActionableNodesOverride:l}=n;if(t.frameCache&&this.userBrowserSettings.autoExpandIframes){let m,g=!1,h=Date.now();for(;Date.now()-h<this.smartWaitingTimeout;)try{let f=await this.stateManager.resolveAutoFrameCache(t.frameCache);this.setActiveFrameConfig(f),g=!0;break}catch(f){m=f,await $(500,a)}if(!g)throw m}let c=await this.getActivePageOrFrame();await this.ensureMomenticBrowserScriptsLoaded(c,i,a);let s=Date.now(),u=0,d=0,p;for(;Date.now()-s<this.smartWaitingTimeout;){this.abortSignal?.throwIfAborted(),u++;let m=u===2||Date.now()-s>this.smartWaitingTimeout-2e3&&u%2===0;try{p=await this.resolveTargetHelper({root:c,target:t,primaryOnly:!0,logger:m?i:bn,allowNotActionableNodesOverride:l,signal:a});break}catch(g){if(g instanceof Mi)break;if(g instanceof sr){if(d++,d>2)throw i.error({err:g},"Got multiple cache disqualification errors, giving up"),g;i.warn({err:g},"Got cache disqualification error, waiting and retrying resolution"),await $(500,a)}a?.throwIfAborted(),m&&i.info({err:g},`Could not resolve target using primary cache only (x${u})`),await $(500,a)}}return p||(p=await this.resolveTargetHelper({root:c,target:t,primaryOnly:!1,logger:i,signal:a,allowNotActionableNodesOverride:l}),t.targetSource="HEURISTIC_HEALED",t.targetUpdateTime=new Date().toISOString(),t.targetUpdateLoggerTags=pe(i),i.info({decisions:p.decisions},"Target resolution succeeded after waiting")),e?.details?.push({type:"TARGETING",name:o,elementLocationDecisions:p?.decisions??[],pageState:void 0,targetSource:t.targetSource,targetUpdateTime:t.targetUpdateTime}),p}async resolveTargetHelper({root:e,target:t,primaryOnly:n,logger:o,signal:i,allowNotActionableNodesOverride:a}){let l=ko(t),c=[],s=(await this.getBrowserState({logger:o,abortSignal:i,skipWait:!0,allowNotActionableNodesOverride:a})).serialize(),u;if(t.generatedSelectors||t.hybridSelector){let d;try{d=await this.resolveTargetWithPrimaryMethods({root:e,target:t,logger:o,allowNotActionableNodesOverride:a})}catch(p){u=p,p instanceof Vr&&c.push(...p.decisions)}if(d)return{...d,pageState:void 0,decisions:[...c,...d.decisions]};n||(c.push({type:"CSS_SELECTOR",matched:!1,reason:u?.message,selectors:ko(t.generatedSelectors??[])}),t.generatedSelectors=void 0,t.hybridSelector=void 0)}if(n)throw u;if(!this.userBrowserSettings.disableSecondaryCacheResolution){let d=await this.resolveTargetWithSecondaryMethods({root:e,tree:s,target:t,decisions:c,logger:o,signal:i,allowNotActionableNodesOverride:a});if(d)return d}throw new Vr(`Could not find any relevant node given target: ${JSON.stringify(l)}`,c)}async resolveTargetWithPrimaryMethods({root:e,target:t,logger:n,allowNotActionableNodesOverride:o}){if(!t.nodeOnlySerializedHtml)throw new Mi("Insufficient data to resolve target using primary methods (missing node HTML)");let i=this.userControlledBrowserSettings.hybridSelectorMode,a={ldistThreshold:.05,requireBoundingBox:!o,ignoreHrefForCaching:this.userControlledBrowserSettings.ignoreHrefForCaching,requireMatchingBoundingBox:this.userControlledBrowserSettings.bustCacheOnBoundingBoxChange?t.boundingBox:void 0,requirements:t.requirements,additionalElements:t.additionalElements},{css:l,hybrid:c}=await je({fn:b=>window.evaluatePrimaryCaches(b),arg:{cssParams:{selectors:t.generatedSelectors??[],cachedElementSerialized:t.nodeOnlySerializedHtml,opts:a},hybridParams:i&&t.hybridSelector?{nodes:t.hybridSelector,cachedElementSerialized:t.nodeOnlySerializedHtml,opts:a}:void 0},root:e,timeout:3e3,waitForPageLoad:()=>this.waitForPageLoad(),codePath:"evaluating target caches"}),s,u,d=[];if(i==="prefer"&&c?.result){s=c.result;let b={type:"HYBRID_SELECTOR",matched:!0,logs:c.logs,reason:"Discovered a match using Momentic's hybrid text and CSS selector approach"};d.push(b),u="HYBRID_SELECTOR"}else if(l?.result){s=l.result;let b=`${s.workingSelectors.length} CSS selectors matched the following element: ${s.serializedElement}`,v=s.workingSelectors.slice(0,5);d.push({type:"CSS_SELECTOR",matched:!0,logs:l.logs,reason:b,selectors:v}),n.debug({reason:b,workingSelectors:v},"Resolved with CSS selectors"),u="CSS_SELECTOR"}else throw d.push({type:"CSS_SELECTOR",matched:!1,reason:l.logs.length===1?"CSS evaluation failed":"No CSS selectors matched",selectors:[],logs:l.logs}),c&&d.push({type:"HYBRID_SELECTOR",matched:!1,reason:c.logs.length===1?"Hybrid evaluation failed":"No hybrid selectors matched",logs:c.logs}),new Vr("Cache evaluation failed",d);let p,m,g,h=!1;if(this.userBrowserSettings.visualActions){let b=s.mPath;if(!b)throw new Error("Found element did not have an mPath despite using visual actions");let v=b.join(" > ");p=e.locator(v),m=this.stateManager.getNodeUsingMPathSelector(v)}else if(s.dataMomenticId!==void 0)g=parseInt(s.dataMomenticId),m=this.stateManager.dataMomenticIdToNodeMap[g],"workingSelectors"in s?(p=e.locator(s.workingSelectors[0]),h=s.workingSelectors.length<5):p=e.locator(Qt(g));else throw new w("InternalWebAgentError","Received an element resolution result with no identifying attributes");i&&t.hybridSelector&&(c?.logs.length===1?n.warn({hybridResult:c,cssResult:l,hybridMode:i},"Hybrid selector resolution rejected, continuing..."):c?.result?l?.result&&c?.result&&c.result.serializedElement!==l.result.serializedElement&&(this.userBrowserSettings.visualActions&&JSON.stringify(l.result.mPath)!==JSON.stringify(c.result.mPath)?n.warn({originalCache:t,hybridResult:c,cssResult:l,hybridMode:i,mode:"visualActions"},"Hybrid selector resolution returned a different element than CSS selector resolution, continuing..."):l.result.dataMomenticId!==c.result.dataMomenticId&&n.warn({originalCache:t,hybridResult:c,cssResult:l,hybridMode:i,mode:"dataMomenticId"},"Hybrid selector resolution returned a different element than CSS selector resolution, continuing...")):n.warn({originalCache:t,hybridResult:c,cssResult:l,hybridMode:i},"Hybrid selector resolution returned no eligible elements while CSS resolution did, continuing..."));let f=ko(t);await this.updateCacheWithNewNodeDetails({node:m,target:t,locator:p,logger:n,startingBoundingBox:s.boundingBox,forceSaveNewCssSelectors:h,allowNotActionableNodesOverride:o});let E=fp(f,t);return E&&Object.keys(E).length>0&&(t.cacheResolutionUpdateTime=new Date().toISOString(),t.cacheResolutionUpdateLoggerTags=pe(n),t.cacheResolutionUpdateSource=u,n.debug({diffs:E},"Updated cache")),{a11yNode:m,displayString:s.serializedElement,locator:p,decisions:d}}async resolveHardcodedCssSelector(e){let{ctx:t,selector:n,logger:o=this.logger,signal:i=this.abortSignal,timeoutMs:a=this.smartWaitingTimeout}=e,l=await this.getActivePageOrFrame(),c=Date.now(),s=0,u,d=[];for(;Date.now()-c<a;){i?.throwIfAborted(),s++;let p=l.locator(n),m;try{return await p.waitFor({state:"attached",timeout:1e3}),m=await Mr(p,o)??"",d.push({type:"USER_SELECTOR",matched:!0,reason:`The user-provided CSS selector ${n} matched an element on the page.`}),t?.details?.push({type:"TARGETING",name:e.targetName,elementLocationDecisions:d,targetSource:"USER_CSS_SELECTOR",targetUpdateTime:new Date().toISOString()}),{locator:p,displayString:m,decisions:d}}catch(g){let h=g.message;u=new w("ActionFailureError",`CSS selector '${n}' failed to resolve after ${s} attempts: ${h.includes("locator.waitFor: Timeout")?"the selector did not match any element on the page":h}`),await $(500,i)}}throw u}async resolveTargetWithSecondaryMethods(e){if(!e.target.boundingBox)return;let{x:t,y:n,width:o,height:i}=e.target.boundingBox,a=await this.resolveTargetWithSecondaryMethodsHelper(e);if(!a)return;let l=await a.locator.boundingBox({timeout:3e3});if(!l){this.logger.debug({proposedNode:a.displayString},"Rejecting secondary matching result due to lack of a bounding box");return}let{x:c,y:s,width:u,height:d}=l;if(Math.abs(u-o)>10||Math.abs(d-i)>10){this.logger.debug({newW:u,oldW:o,newH:d,oldH:i,proposedNode:a.displayString},"Rejecting secondary matching result due to difference in dimensions");return}else if(!t||!n||!c||!s){this.logger.debug({oldX:t,oldY:n,newX:c,newY:s,proposedNode:a.displayString},"Rejecting secondary matching result due to missing x/y coords");return}else if(Math.abs(c-t)>100||Math.abs(s-n)>100){this.logger.debug({newX:c,newY:s,oldX:t,oldY:n,proposedNode:a.displayString},"Rejecting secondary matching result due to large difference in x/y coords");return}return a}async resolveTargetWithSecondaryMethodsHelper({root:e,target:t,decisions:n,logger:o,signal:i,allowNotActionableNodesOverride:a}){if(t.nodeOnlySerializedHtml&&t.nodeOnlySerializedHtml.trim().length<10){let s="Refusing to attempt HTML comparison since the saved element is too short.";n.push({type:"HTML_DISTANCE",matched:!1,reason:s})}else if(t.nodeOnlySerializedHtml&&t.nodeOnlySerializedHtml.length>50)try{let s=await je({fn:d=>window.findClosestElementByLDist?.(d),arg:{nodeOnlySerializedHtml:t.nodeOnlySerializedHtml},timeout:2e3,root:e,waitForPageLoad:()=>this.waitForPageLoad(),codePath:"finding the closest element on the page"}),u=Math.floor(.05*t.nodeOnlySerializedHtml.length);if(s&&s.closestDistance&&s.closestDistance>=u){let d=`Closest HTML candidate still has too far distance (${s.closestDistance}) from threshold (${u})`;n.push({type:"HTML_DISTANCE",matched:!1,reason:d,distance:s.closestDistance,closestElement:s.closestNodeSerialized})}else{if(s?.error)throw new Error(s.error);if(s?.dataMomenticId||s?.mPathSelector){let d=s.dataMomenticId?parseInt(s.dataMomenticId):void 0,p,m;if(d)p=this.stateManager.dataMomenticIdToNodeMap[d],m=e.locator(Qt(d));else if(s.mPathSelector)p=this.stateManager.getNodeUsingMPathSelector(s.mPathSelector),m=e.locator(s.mPathSelector);else throw new Error("HTML ldist comparison returned no error, data momentic id, or mPath selector");let g=s.closestNodeSerialized??await Mr(m,o)??"unknown element";o.warn({result:s,originalTarget:t,displayString:g},"Resolved cached target to new node with pure html levenshtein distance");let h=ko(t);await this.updateCacheWithNewNodeDetails({node:p,target:t,locator:m,logger:o,startingBoundingBox:s.boundingBox,allowNotActionableNodesOverride:a,forceSaveNewCssSelectors:!0});let f=fp(h,t);return f&&Object.keys(f).length>0&&(t.cacheResolutionUpdateTime=new Date().toISOString(),t.cacheResolutionUpdateLoggerTags=pe(o),t.cacheResolutionUpdateSource="HTML_DISTANCE",o.info({diffs:f,result:s},"Updated cache after l-dist resolution")),n.push({type:"HTML_DISTANCE",matched:!0,reason:`Found an element on the page within ${u} string comparison distance of the saved element.`,logs:s.logs,distance:s.closestDistance,closestElement:g,savedElement:t.nodeOnlySerializedHtml}),{locator:m,a11yNode:p,displayString:g,decisions:n,pageState:void 0}}else throw new Error(`Got invalid HTML evaluation result: ${JSON.stringify(s)}`)}}catch(s){o.info({err:s},"Failed to find closest HTML node using levenshtein distance"),n.push({type:"HTML_DISTANCE",matched:!1,reason:`Error finding closest HTML node by string distance: ${s}`})}let l=t.screenshotUrl,c=t.role??"";if(l&&Hd.includes(c))try{let s=await this.resolveTargetWithTemplateMatching({root:e,oldTarget:t,screenshotUrl:l,signal:i,allowNotActionableNodesOverride:a});return{...s,decisions:[...n,...s.decisions],pageState:void 0}}catch(s){i?.throwIfAborted(),n.push({type:"TEMPLATE_MATCHING",matched:!1,reason:`Error finding closest element using saved screenshot: ${s}`,elementImageUrl:l}),o.warn({err:s},"Did not find any close element using saved screenshot")}}async resolveTargetWithTemplateMatching({root:e,screenshotUrl:t,oldTarget:n,signal:o,allowNotActionableNodesOverride:i}){let a;if(!this.enricher)throw new Error("Enricher not available for screenshot resolution");let l=await this.screenshot({retries:0}),s=await(await fetch(t)).arrayBuffer(),u=WN(),d=await this.enricher.runTemplateMatching({id:u,searchImageBase64String:Buffer.from(s).toString("base64"),pageImageBase64String:l.toString("base64")},{signal:o}),{target:p,locator:m}=await this.getTargetFromPositionPercentages({percentX:d.x,percentY:d.y,allowNotActionableNodesOverride:i}),g=p.boundingBox?.width,h=p.boundingBox?.height;if(!g||!h)throw a="Rejecting target from screenshot due to no bounding box",new Error(a);let f=p.id,E=this.stateManager.a11yIdToNodeMap[f],b=ko(n);await this.updateCacheWithNewNodeDetails({target:n,node:E,locator:m,forceSaveNewCssSelectors:!0,allowNotActionableNodesOverride:i});let v=fp(b,n);return v&&Object.keys(v).length>0&&(n.cacheResolutionUpdateTime=new Date().toISOString(),n.cacheResolutionUpdateLoggerTags=pe(this.logger),n.cacheResolutionUpdateSource="TEMPLATE_MATCHING",this.logger.info({id:u,diffs:v,templateMatch:d},"Updated cache after template matching resolution")),{locator:m,a11yNode:E,displayString:p.nodeOnlySerializedHtml??"",decisions:[{type:"TEMPLATE_MATCHING",matched:!0,reason:"Found element using screenshot",elementImageUrl:t}]}}async typeIntoTarget(e,t,n={}){await this.highlight(t.locator);let o=await t.locator.getAttribute("type",{timeout:1e3})??"",i=rT.some(a=>a===o.toLowerCase());return await tp({targetingResult:t,options:{force:n.force},logger:this.logger,retryTimeoutMs:this.smartWaitingTimeout,position:i?{x:1,y:1}:void 0,actionSource:"type",browserCallbacks:this.getBrowserCallbacks()}),await this.page.waitForTimeout(150),this.directTypeHelper(e,n)}async click(e,t,n={}){return tp({targetingResult:e,options:n,logger:this.logger,actionSource:"click",retryTimeoutMs:this.smartWaitingTimeout,controllerCallbacks:t,browserCallbacks:this.getBrowserCallbacks()})}async waitForUrl({beforeUrl:e,matcher:t},n){let o=n?.timeout??this.pageLoadTimeout,i=Date.now(),a=!1,l=e;for(;Date.now()-i<o;){if(this.abortSignal?.throwIfAborted(),l=this.url(),ws(l,t,n)){a=!0;break}await $(500,this.abortSignal)}if(!a)throw new w("ActionFailureError",`The active page URL ${n?.negated?"still does":"does not"} ${Gf(t)} in ${o}ms.
3953
+ Current tab: ${l}`);try{await this.loadFrameAndRecordUrl({root:this.page,signal:this.abortSignal,codePath:"wait-for-url-step"})}catch(c){this.logger.warn({err:c},"Failed waiting for page load after URL change, continuing...")}}async dragAndDrop(e,t,n={}){await this.hover({locator:e}),await this.page.mouse.down();let o=await t.boundingBox({timeout:3e3});if(!o)throw new w("ActionFailureError","Could not get bounding box of target element");let i=o.x+o.width/2,a=o.y+o.height/2,l=n.steps??5;await this.page.mouse.move(i,a,{steps:l}),await $(n.hoverSeconds?Math.min(n.hoverSeconds*1e3,2e3):500),await this.page.mouse.up()}async mouseDrag(e,t,n,o){o&&await this.hover({locator:o});let i=await(await this.getActivePageOrFrame()).evaluate(Zd);i||(this.logger.warn("Could not get current mouse position before mouse drag action, defaulting to 0,0"),i={left:0,top:0}),await this.page.mouse.down(),await this.page.mouse.move(e+i.left,t+i.top,{steps:n}),await $(250),await this.page.mouse.up()}async hover(e){await this.highlight(e.locator),await kn({func:async t=>{await this.scrollIntoViewIfNeeded(t.locator);let n=await t.locator.boundingBox({timeout:3e3});if(!n)throw new Error("Attempted to hover over element with no bounding box");await this.page.mouse.move(n.x+n.width/2,n.y+n.height/2,{steps:3})},action:"hovering over element",logger:this.logger,retryTimeoutMs:this.smartWaitingTimeout,targetingResult:e,callbacks:this.getBrowserCallbacks()})}async focus(e){await this.highlight(e.locator),await kn({func:t=>t.locator.focus({timeout:2e3}),action:"focusing element",logger:this.logger,retryTimeoutMs:this.smartWaitingTimeout,callbacks:this.getBrowserCallbacks(),targetingResult:e})}async blur(e){if(!e){let t=await this.getActivePageOrFrame();await je({fn:()=>{let n=document.activeElement;n&&n.nodeType===1&&n.blur()},root:t,arg:void 0,waitForPageLoad:()=>this.waitForPageLoad(),timeout:1e3,codePath:"blurring the active element"});return}await this.highlight(e.locator),await kn({func:t=>t.locator.blur({timeout:2e3}),action:"blurring element",logger:this.logger,retryTimeoutMs:this.smartWaitingTimeout,callbacks:this.getBrowserCallbacks(),targetingResult:e})}async selectOption(e,t,n=!1){await this.highlight(e.locator),await kn({action:"selecting option from dropdown",logger:this.logger,retryTimeoutMs:this.smartWaitingTimeout,callbacks:this.getBrowserCallbacks(),func:async o=>{if(t.type==="INDEX"){let i=Number(t.index);if(isNaN(i))throw new w("UserConfigurationError",`Page index ${t.index} is not a number`)}await o.locator.selectOption({value:t.type==="VALUE"?t.value:void 0,label:t.type==="LABEL"?t.label:void 0,index:t.type==="INDEX"?Number(t.index):void 0},{force:n,timeout:3e3})},targetingResult:e})}async press(e,t){let n=t.repeat??1;if(t.convertMeta){let o=wl(e);o!==e&&(this.logger.info({key:e,convertedKey:o},"Converted platform dependent keys"),e=o)}for(let o=0;o<n;o++)await this.page.keyboard.press(e,{delay:t.delayMs??0})}async keyDown(e,t){if(t.convertMeta){let n=wl(e);n!==e&&(this.logger.info({keyString:e,convertedKey:n},"Converted platform dependent keys"),e=n)}for(let n of gp(e))await this.page.keyboard.down(n)}async keyUp(e,t){if(t.convertMeta){let n=wl(e);n!==e&&(this.logger.info({keyString:e,convertedKey:n},"Converted platform dependent keys"),e=n)}for(let n of gp(e))await this.page.keyboard.up(n)}async refresh(e){let t=e?.loadTimeoutMs??this.pageLoadTimeout;await this.waitForPageLoad();let n=0,o=2;for(;n<o;){n++;try{await this.page.reload({waitUntil:"domcontentloaded",timeout:t});break}catch(i){this.logger.warn({err:i,attempt:n},`Failed to reload page${n<o?", retrying...":", continuing..."}`)}}await this.loadFrameAndRecordUrl({root:this.page,signal:this.abortSignal,codePath:"reload-step"}),await this.waitForDOMStability()}async getBrowserState(e){let{maxAttempts:t=2,logger:n=this.logger,skipWaitForPageLoad:o,allowNotActionableNodesOverride:i}=e,a=e.abortSignal??this.abortSignal,l=!i,c=i?!0:this.userControlledBrowserSettings.showZeroOpacityElements;o||await this.waitForPageLoad(),e.skipWait||await this.waitForDOMStability({logger:n,signal:a});let s=0,u;for(;s<t;){s++;try{return await B(this.stateManager.getA11yTree({devicePixelRatio:this.devicePixelRatio,abortSignal:a,logger:n,filterByViewport:e.filterByViewport,showZeroOpacityElements:c,flagNotActionableNodes:l}),{milliseconds:this.pageLoadTimeout*s,signal:a,message:"Getting browser state took too long"})}catch(d){if(a?.throwIfAborted(),u=d instanceof Error?d.message:`${d}`,s>=t)throw d;n.warn({err:d,url:this.url()},"Error getting a11y tree, retrying...")}}throw new w("ActionFailureError",`Getting page content failed after ${t} attempts. Error: ${u}`)}async getViewportOffsetDetails(e){let[t,n,o,i,a]=await je({root:e,fn:()=>[window.scrollY,window.scrollX,window.screen.width,window.screen.height,window.devicePixelRatio],arg:void 0,timeout:3e3,waitForPageLoad:async()=>{},codePath:"getting current viewport details"});return{upperBound:t,lowerBound:t+i,leftBound:n,rightBound:n+o,width:o,height:i,devicePixelRatio:this.properties.systemDevicePixelRatio??a}}async waitForDOMStability(e){let{logger:t=this.logger,timeout:n=this.smartWaitingTimeout,signal:o}=e??{},i={value:Date.now()},a=p=>{i.value=Date.now()},l=()=>a("DOM.documentUpdated");this.cdpClient.addListener("DOM.documentUpdated",l);let c=()=>a("Page.frameDetached");this.cdpClient.addListener("Page.frameDetached",()=>c);let s=()=>a("Page.frameStartedLoading");this.cdpClient.addListener("Page.frameStartedLoading",s);let u=()=>a("Page.navigatedWithinDocument");this.cdpClient.addListener("Page.navigatedWithinDocument",u);let d=()=>a("frameRequestedNavListener");this.cdpClient.addListener("Page.frameRequestedNavigation",d);try{await this.waitForDOMStabilityHelper(i,t,n,o)}finally{this.cdpClient.removeListener("DOM.documentUpdated",l),this.cdpClient.removeListener("Page.frameDetached",c),this.cdpClient.removeListener("Page.frameStartedLoading",s),this.cdpClient.removeListener("Page.navigatedWithinDocument",u),this.cdpClient.removeListener("Page.frameRequestedNavigation",d)}}async waitForDOMStabilityHelper(e,t,n,o){let i=!1,a=Date.now(),l,c={quality:25,retries:0,stabilizeBeforeScreenshot:!0},s=!1,u=0;for(;Date.now()-a<n;){if(o?.throwIfAborted(),await $(250,this.abortSignal),l)try{let d=await this.screenshot(c);if(!d.equals(l)){l=d,s=!1;continue}s=!0}catch(d){u++,u%3===0&&t.warn({err:d,screenshotErrors:u},"Failed to take screenshot for DOM stability check"),o?.throwIfAborted()}else try{l=await this.screenshot(c)}catch(d){u++,u%3===0&&t.warn({err:d,screenshotErrors:u},"Failed to take screenshot for DOM stability check"),o?.throwIfAborted()}if(!(Date.now()-e.value<250)){i=!0;break}}i||t.warn({duration:Date.now()-a,stable:{a11y:i,screenshot:s}},"A11y wait phase completed due to timeout, continuing...")}async clickUsingVisualCoordinates(e,t){let{x:n,y:o}=e;this.logger.debug({x:n,y:o},"Executing mouse click with visual coordinates"),await this.waitForPageLoad(),await this.page.mouse.click(n,o,{button:t.rightClick?"right":"left",clickCount:t.doubleClick?2:1})}async dragAndDropUsingVisualCoordinates(e,t,n){await this.page.mouse.move(e.x,e.y,{steps:3}),await this.page.mouse.down(),await this.page.mouse.move(t.x,t.y,{steps:3}),await $(n.hoverSeconds?Math.min(n.hoverSeconds*1e3,8e3):500),await this.page.mouse.up()}async hoverUsingVisualCoordinates(e){await this.page.mouse.move(e.x,e.y)}async mouseDragUsingVisualCoordinates(e,t,n,o){await this.hoverUsingVisualCoordinates(o);let i=await(await this.getActivePageOrFrame()).evaluate(Zd);i||(this.logger.warn("Could not get current mouse position before mouse drag action, defaulting to 0,0"),i={left:0,top:0}),await this.page.mouse.down(),await this.page.mouse.move(e+i.left,t+i.top,{steps:n}),await $(250),await this.page.mouse.up()}async getElementLocation(e){let t=await this.cdpClient.send({method:"DOMSnapshot.captureSnapshot",params:{computedStyles:[],includeDOMRects:!0,includePaintOrder:!0},timeout:3e3}),n=await B(this.page.evaluate(()=>window.devicePixelRatio),{milliseconds:2e3});process.platform==="darwin"&&n===1&&(n=2);let o=t.documents[0],i=o.layout,a=o.nodes,l=a.nodeName||[],c=a.backendNodeId||[],s=i.nodeIndex,u=i.bounds,d=-1;for(let b=0;b<l.length;b++)if(c[b]===e){d=s.indexOf(b);break}if(d===-1)throw new Error(`Could not find any backend node with ID ${e}`);let[p=0,m=0,g=0,h=0]=u[d];p/=n,m/=n,g/=n,h/=n;let f=p+g/2,E=m+h/2;return{centerX:f,centerY:E}}async scrollVertical(e){return rp({frame:this.stateManager.frameConfig?await this.getActivePageOrFrame():null,page:this.page,deltaX:0,directionX:null,deltaY:e?Math.abs(e):null,directionY:e&&e>0?"down":"up",signal:this.abortSignal,callbacks:this.getBrowserCallbacks(),logger:this.logger})}async scrollHorizontal(e){return rp({frame:this.stateManager.frameConfig?await this.getActivePageOrFrame():null,page:this.page,deltaX:e?Math.abs(e):null,directionX:e&&e>0?"right":"left",deltaY:0,directionY:null,signal:this.abortSignal,callbacks:this.getBrowserCallbacks(),logger:this.logger})}async goForward(){await this.waitForPageLoad(),await this.page.goForward({waitUntil:"domcontentloaded",timeout:this.pageLoadTimeout}),await this.loadFrameAndRecordUrl({root:this.page,signal:this.abortSignal,codePath:"go-forward"})}async goBack(){await this.waitForPageLoad(),await this.page.goBack({waitUntil:"domcontentloaded",timeout:this.pageLoadTimeout}),await this.loadFrameAndRecordUrl({root:this.page,signal:this.abortSignal,codePath:"go-back"})}async reinitializeCDPClient(e){await this.cdpClient.reinitialize(e),await this.initializeScreencast()}async stopScreencast(){if(this.clientCallbacks?.onScreencastFrame)try{await this.cdpClient.send({method:"Page.stopScreencast",params:{}})}catch{}}async changeActivePage(e,t){await this.stopScreencast(),this.recordUrlVisited(e.url()),this.page=e,await this.reinitializeCDPClient(t??this.pageLoadTimeout)}async createNewTab(e,t){let n=await this.context.newPage();await this.changeActivePage(n,t?.loadTimeoutMs),await this.navigate({url:e,initialNavigation:!0,...t}),this.handleAvailableTabsChange()}async switchToPage(e,t){let n=!0,o,i=Date.now();for(;n||t?.retry&&Date.now()-i<this.smartWaitingTimeout;){n=!1;try{await this.switchToPageHelper(e,t);return}catch(a){this.logger.warn({err:a},"Error switching to page, retrying..."),o=a,await $(500)}}throw o}async switchToPageHelper(e,t){let n=this.context.pages().map((i,a)=>({page:i,url:i.url(),index:a})),o;if(e.type==="INDEX"){let i=Number(e.index);if(isNaN(i))throw new w("UserConfigurationError",`Page index ${e.index} is not a number`);if(i<0||i>=n.length)throw new Error(`Page index ${e.index} exceeds the number of available pages: ${JSON.stringify(n.map(a=>a.url))}`);o=n[i]}else{let i=n.filter(a=>e.type==="SUBSTRING"?a.url.includes(e.substring):a.url.match(e.pattern));i.length>1&&this.logger.warn(`More than one page matches the page switch criteria: ${JSON.stringify(i.map(a=>a.url))}`),o=i[i.length-1]}if(!o)throw new Error(`Could not find matching page using criteria: ${JSON.stringify(e)}.
3954
+ Available pages:${JSON.stringify(n.map(i=>i.url))}`);if(!Cn(o.url,this.logger)){this.logger.error(`Refusing to switch to page with invalid URL: ${o.url}`);return}this.logger.info(`Switching to tab ${o.index} with url ${o.url}`),await this.changeActivePage(o.page,t?.loadTimeoutMs),await this.loadFrameAndRecordUrl({root:o.page,signal:this.abortSignal,codePath:"switch-to-tab-step"}),this.handleAvailableTabsChange()}async setCookie(e){let t;return typeof e=="string"?t=Xa(e):t=[e],await this.context.addCookies(t),t}async setLocalStorage(e,t){let n;for(let o=0;o<2;o++)try{await this.evaluateFunctionInPage(([i,a])=>{i&&localStorage.setItem(i,a||"")},[e,t],`setting local storage key ${e}`);return}catch(i){n=i}if(n)throw n}async solveCaptcha(){await this.getBrowserState({allowNotActionableNodesOverride:!0});let e;for(let l of Object.values(this.stateManager.a11yIdToNodeMap))if(l.role==="image"&&l.name.toLowerCase().includes("captcha")){if(!l.backendNodeId)continue;e=await this.stateManager.getLocatorFromBackendId(this.page,l.backendNodeId);break}if(!e){let l=await(await this.getActivePageOrFrame()).solveRecaptchas();if(!l.captchas||!l.captchas.length)throw new Error("No captchas found on the page");return}let t=await e.screenshot({type:"jpeg",animations:"allow",caret:"hide",quality:100,timeout:3e3}),n=await fetch("https://api.2captcha.com/createTask",{method:"POST",body:JSON.stringify({clientKey:Ll,task:{type:"ImageToTextTask",body:t.toString("base64"),case:!0},languagePool:"en"})});if(!n.ok){let l=`Captcha solver API returned error response: ${n.statusText}`;throw this.logger.error({text:await n.text()},l),new Error(l)}let{taskId:o}=await n.json(),i=Date.now(),a="";for(;Date.now()-i<6e4;){await $(2500);let l=await fetch("https://api.2captcha.com/getTaskResult",{method:"POST",body:JSON.stringify({clientKey:Ll,taskId:o})});if(!l.ok){let s=`Captcha solution API returned error response: ${l.statusText}`;throw this.logger.error({text:await l.text()},s),new Error(s)}let c=await l.json();if(c.errorId){let s=`Captcha solution API returned error ID ${c.errorId}`;throw this.logger.error(s),new Error(s)}if(c.status==="ready"){a=c.solution.text;break}}if(!a)throw new Error("Captcha solution timed out");return a}getActiveFrameConfig(){return this.stateManager.frameConfig}async exposeRecordingBindings(){await this.context.exposeBinding("isRecordingActive",()=>this.transformer!==void 0,{handle:!1}),await this.context.exposeBinding("captureTargetedEvent",({frame:e},t)=>{this.transformer&&FT({event:t,frame:e,transformer:this.transformer,enricher:this.enricher,lastScreenshotForRecording:this.lastScreenshotForRecording?.toString("base64"),logger:this.logger})},{handle:!1}),await this.context.exposeBinding("captureKeystroke",async(e,t)=>{this.transformer&&this.transformer.recordKeystroke(t)})}async startRecordingCrons(e){if(e.aborted)return;let t,n=(await this.getOpenPages()).map(l=>l.url),o=0,i=!1,a=async()=>{if(e.aborted||o>8){clearTimeout(t);return}i=!0;let l;try{l=(await this.getOpenPages()).map(s=>s.url),o=0}catch(s){this.logger.debug({err:s},"Failed getting new open pages during recording tab switch cron, skipping..."),o++;return}let c=this.url();for(let s=l.length-1;s>=n.length;s--){let u=l[s];Cn(u,this.logger)&&u!==c&&this.logger.info({lastActivePages:n,currentUrl:c,newOpenPages:l},"Auto-following new tab during recording"),await this.switchToPage({type:"INDEX",index:String(s)});break}n=l};t=setInterval(async()=>{if(!i){i=!0;try{await a()}catch(l){this.logger.error({err:l},"Error while checking pages during recording")}finally{i=!1}}},500),e.addEventListener("abort",async()=>{clearInterval(t)})}async startRecording(e,t,n){this.logger.debug({isClickToRecord:n},"Starting recording mode in Chrome browser"),await this.startRecordingCrons(e),await this.page.evaluate(o=>{let i=window;i._MOMENTIC_RECORDING_ACTIVE=!0,i._MOMENTIC_CLICK_RECORD_ACTIVE=o},n),this.transformer=t,await this.injectKnowledgeBaseIntoBrowser(this.page),e.addEventListener("abort",async()=>{this.transformer=void 0,this.lastScreenshotForRecording=void 0;try{await this.page.evaluate(()=>{let o=window;o._MOMENTIC_RECORDING_ACTIVE=!1,o._MOMENTIC_CLICK_RECORD_ACTIVE=!1})}catch{}})}async getSelectOptions(e){return await e.evaluate(n=>Array.from(n.querySelectorAll("option")).map(i=>({value:i.value,label:i.label})),void 0,{timeout:1e3})}getActivePage(){return this.page}async getActivePageOrFrame(){let e=await this.stateManager.resolveActiveFrameConfig({});return e?(await this.loadFrameAndRecordUrl({root:e.frame,signal:this.abortSignal,codePath:"get-active-frame-locator"}),e.frame):this.page}async loadFrameAndRecordUrl({root:e,signal:t,codePath:n}){let o=this.pageLoadTimeout,i=e.url();if(!i.includes("chrome-error://")){try{await wn({promiseGenerator:async()=>e.waitForLoadState("domcontentloaded",{timeout:o}),signal:t,codePath:`loadFrameAndRecordUrlDomContentLoad-${n}`,logger:this.logger,timeoutMs:this.pageLoadTimeout})}catch(a){let l=a;if(l.name==="AbortError")throw new w("UserInfrastructureError",`The page with URL ${St(i,50)} did not load within the configured timeout (${o}ms): ${l}`);if(!l.message.includes("detached"))throw l}try{await wn({promiseGenerator:async()=>e.waitForLoadState("load",{timeout:o}),signal:t,codePath:`loadFrameAndRecordUrlPageLoad-${n}`,logger:this.logger,timeoutMs:this.pageLoadTimeout})}catch(a){this.logger.warn({err:a,codePath:n,url:i},"Failed waiting for current frame to load, continuing...")}this.recordUrlVisited(e.url())}}async getCondensedHtml(e){let{skipWait:t=!1}=e??{};return t||(await this.waitForPageLoad(),await this.waitForDOMStability()),this.getCondensedHtmlHelper()}async getCondensedHtmlHelper(){let e=await this.getRawCondensedHtml();return UN.html(e,{indent_size:1,indent_with_tabs:!1,preserve_newlines:!1})}async getRawCondensedHtml(){let e=await this.getActivePageOrFrame();await this.ensureMomenticBrowserScriptsLoaded(e,this.logger,this.abortSignal);let{result:t,error:n}=await je({fn:()=>window.getCondensedHtmlTree(),root:e,arg:void 0,timeout:2e3,waitForPageLoad:()=>this.waitForPageLoad(),codePath:"getting condensed HTML tree"});if(n)throw new Error(`Failed to process page HTML: ${n}`);if(!t)throw new w("InternalWebAgentError","Got empty HTML tree - are you sure the page is fully loaded?");return t}registerDialogHandler(e){let t=async n=>{try{e==="ACCEPT"?await n.accept():await n.dismiss()}catch(o){this.logger.warn({err:o},"Failed to handle dialog")}};this.page.once("dialog",t)}async evaluateFunctionInAllFrames(e,t){return this.stateManager.executeFunctionInAllFrames(e,t)}async evaluateFunctionInPage(e,t,n,o=2e3){let i=await this.getActivePageOrFrame();return je({root:i,fn:e,arg:t,timeout:o,waitForPageLoad:()=>this.waitForPageLoad(),codePath:n})}async evaluateCodeInPage({code:e,fragment:t,context:n,timeoutMs:o=Hr}){let i=Zb(),a={code:e,fragment:t,context:n},{result:l}=await B(this.page.evaluate(i,a),{milliseconds:o,fallback:()=>{throw this.abortSignal?.throwIfAborted(),new w("ActionFailureError",`Code evaluation in browser exceeded the allowed timeout of ${o/1e3} seconds`)},signal:this.abortSignal});return l}async getDomNodeFromPixelPosition(e,t){await this.cdpClient.send({method:"DOM.getDocument",params:{depth:0},timeout:2e3});let n;try{n=await this.cdpClient.send({method:"DOM.getNodeForLocation",params:{x:e,y:t},timeout:1e3})}catch(o){throw this.logger.error({err:o,x:e,y:t},"Failed to get DOM node from position percents"),new Error("No element was found at the given location")}return n}async getDomNodeFromPositionPercentages(e,{percentX:t,percentY:n}){if(t<0||t>1||n<0||n>1)throw new w("UserConfigurationError","Invalid percent passed to percentage location");let{width:o,height:i,upperBound:a,leftBound:l}=await this.getViewportOffsetDetails(e),c=Math.round(a),s=Math.round(l),u=Math.ceil(o*t),d=Math.ceil(i*n),p=u+s,m=d+c;return this.getDomNodeFromPixelPosition(p,m)}async highlightFromPositionPercentages(e){let t=await this.getActivePageOrFrame(),n;try{n=await this.getDomNodeFromPositionPercentages(t,e)}catch{}return n?(await this.cdpClient.send({method:"Overlay.highlightNode",timeout:1e3,params:{highlightConfig:dT,backendNodeId:n.backendNodeId}}),async()=>{try{await this.cdpClient.send({timeout:1e3,method:"Overlay.hideHighlight",params:{backendNodeId:n?.backendNodeId}})}catch{}}):async()=>{}}async clearAllCdpHighlights(){try{await this.cdpClient.send({method:"Overlay.hideHighlight",params:void 0,timeout:1e3})}catch{}}async getTargetFromPositionPercentages(e){let t=await this.getActivePageOrFrame(),n=await this.getDomNodeFromPositionPercentages(t,e);return this.getTargetFromBackendNodeId({root:t,backendNodeId:n.backendNodeId,allowNotActionableNodesOverride:e.allowNotActionableNodesOverride})}async getTargetFromBackendNodeId({root:e,backendNodeId:t,allowNotActionableNodesOverride:n}){let o=this.stateManager.domGraph?.backendIdToNode[t];if(!o)throw new Error("No DOM node was found with the given backend ID");let i=o?.attributes[_r],a=parseInt(i??"");if(!i||isNaN(a))throw new Error("No data-momentic-id was found on the DOM node");let l=e.locator(Qt(a)),c;o.bounds.x!==null&&o.bounds.y!==null&&(c={x:o.bounds.x,y:o.bounds.y,width:o.bounds.width??0,height:o.bounds.height??0});let s=await this.fetchHtmlAttributes({locator:l,logger:this.logger,startingBoundingBox:c,allowNotActionableNodesOverride:n}),u={id:-1,dataMomenticId:a,targetSource:"XY_PERCENT",targetUpdateTime:new Date().toUTCString(),...s};return this.logger.debug({target:u},"Tied backend ID to HTML node"),{target:u,locator:l}}async performTargetRedirection(e,t,n){try{return await this.scrollIntoViewIfNeeded(e),await B(this.performTargetRedirectionHelper(e,t,n),{milliseconds:3e3})??{locator:e}}catch(o){return t.warn({err:o},"Error performing target redirection, using original element"),{locator:e}}}async performTargetRedirectionHelper(e,t,n){let o=Date.now(),i=await Mr(e,t);if(n===void 0&&(n=await e.boundingBox({timeout:3e3})??void 0),!n){t.error(`Attempted to click on element with no bounding box: ${i}`);return}let{x:a,y:l,width:c,height:s}=n,u=this.getViewport();if(a<0||l<0||!u||a+c>u.width||l+s>u.height){t.info("Skipping locator redirection because the element is outside the viewport");return}let d=await this.getActivePageOrFrame(),{dataMomenticId:p,mPathSelector:m,error:g,serializedElement:h,point:f,force:E,logs:b}=await e.evaluate(A=>{let T=window;if(!T.performTargetRedirection)throw new Error("performTargetRedirection script is not defined");return T.performTargetRedirection(A)},void 0,{timeout:1e3}),v=Date.now()-o;if(g){t.warn({error:g,serializedElement:h,duration:v,force:E,logs:b},"Got error from target redirection with bounding box");return}else{if(p)return t.info({newDataMomenticId:p,serializedElement:h,duration:v,force:E,logs:b},"Redirected target to new element with bounding box with data-momentic-id"),{locator:d.locator(Qt(p)),hints:{clickableXY:f,force:E}};if(m)return t.info({newMPathSelector:m,serializedElement:h,duration:v,force:E,logs:b},"Redirected target to new element with bounding box with mPath"),{locator:d.locator(m),hints:{clickableXY:f,force:E}};if(f)return t.info({point:f,serializedElement:h,duration:v,force:E,logs:b},"Chose specific visible point on original element"),{locator:e,hints:{clickableXY:f,force:E}};if(E)return t.info({serializedElement:h,duration:v,force:E,logs:b},"Forcing click on original element"),{locator:e,hints:{force:E}}}}async fetchHtmlAttributes({locator:e,logger:t=this.logger,startingBoundingBox:n,allowNotActionableNodesOverride:o}){let{hybridSelectorMode:i,showZeroOpacityElements:a}=this.userControlledBrowserSettings,l=await e.evaluate((c,s)=>{let u=window;return u.generateHtmlCacheAttributes?u.generateHtmlCacheAttributes(c,s):{warnings:[],error:"generateHtmlCacheAttributes is not defined"}},{generateHybridSelector:i==="test"||i==="prefer",startingBoundingBox:n,showZeroOpacityElements:o?!0:a},{timeout:2e3});if("error"in l&&l.error)throw l.error.startsWith(kb)?new is(l.error):l.error.startsWith(Ub)?new as(l.error):new Error(l.error);return l.warnings.length&&t.warn(l,"Got warnings while generating HTML attributes for target"),l.attributes}async moveMouseFromPositionPercentages(e,t){let n=this.getViewport();if(!n)throw new Error("Cannot move mouse using percentages without viewport");let o=Math.ceil(n.width*e),i=Math.ceil(n.height*t);return await this.cdpClient.send({method:"Input.dispatchMouseEvent",params:{type:"mouseMoved",x:o,y:i,button:"left",clickCount:0}}),{x:o,y:i}}async clickMouseFromPositionPercentages(e,t,n){let o=this.getViewport();if(!o)throw new Error("Cannot click mouse using percentages without viewport");let i=Math.ceil(o.width*t),a=Math.ceil(o.height*n);await this.cdpClient.send({method:"Input.dispatchMouseEvent",params:{type:e==="down"?"mousePressed":"mouseReleased",x:i,y:a,button:"left",clickCount:e==="down"?1:0},timeout:1e3})}async scrollFromPositionPercentages(e,t,n,o){let i=this.getViewport();if(!i)throw new Error("Cannot scroll using percentages without viewport");let a=Math.ceil(i.width*e),l=Math.ceil(i.height*t);return await this.cdpClient.send({method:"Input.dispatchMouseEvent",params:{type:"mouseWheel",deltaX:a,deltaY:l,x:n,y:o}}),{deltaX:a,deltaY:l}}canSolveCaptchas(){return!!Ll}async getAllFrameUrls(){return await this.stateManager.getAllChildFrameUrls()}async setFileChooserHandler(e){setTimeout(()=>{try{e.cleanup()}catch(t){this.logger.debug({err:t,filePath:e.filePath},"Failed cleaning up file after upload")}},3e4),await this.setFileChooserHandlerHelper(e)}logToUserConsole(e,t,n,...o){let i=this.context.pages().indexOf(e);i=i===-1?0:i,Jd(e,this.debugData,i,{type:t,text:`[MOMENTIC] ${n}`,args:o})}async setFileChooserHandlerHelper({filePath:e,filename:t}){if(!Fn(e)){let c=`File chooser triggered after the source file ${e} has been cleaned up, ignoring...`;this.logger.error(c),this.logToUserConsole(this.page,"error",c);return}let n=t?.trim()||BN(e),o=LN(e),i=zN(e),a=pu[i];this.page.once("filechooser",async c=>{this.logger.info({filePath:e,fileName:n},"File chooser triggered");try{if(!Fn(e))throw new Error(`File chooser triggered after the source file ${e} has been cleaned up, ignoring...`);await c.setFiles({name:n,buffer:o,mimeType:FN.getType(e)||"application/octet-stream"},{timeout:8e3})}catch(s){this.logger.error({err:s},"Error handling file chooser"),this.logToUserConsole(this.page,"error",s.message)}});let l=o.toString("base64");await this.evaluateFunctionInPage(({fileName:c,base64Data:s,mimeType:u})=>{let d=window;d.momenticFileName=c,d.momenticFileBase64=s;let p=atob(s),m=new Array(p.length);for(let h=0;h<p.length;h++)m[h]=p.charCodeAt(h);let g=new Uint8Array(m);d.MomenticFile=class extends Blob{kind="file";name=d.momenticFileName;constructor(){super([g],{type:u})}isSameEntry(h){return h.name===this.name}queryPermission(h){return console.info("[MOMENTIC] MomenticFile.queryPermission called"),Promise.resolve("granted")}remove(){return console.info("[MOMENTIC] MomenticFile.remove called"),Promise.resolve()}async requestPermission(h){return console.info("[MOMENTIC] MomenticFile.requestPermission called"),Promise.resolve("granted")}async getFile(){console.info("[MOMENTIC] MomenticFile.getFile called");let h=new Blob([g]);return new File([h],d.momenticFileName,{type:u})}async createSyncAccessHandle(){throw console.error("[MOMENTIC] Not implemented"),new Error("Not implemented")}async createWritable(){throw console.error("[MOMENTIC] Not implemented"),new Error("Not implemented")}},d.showOpenFilePicker=async()=>(console.info("[MOMENTIC] showOpenFilePicker called"),[new d.MomenticFile])},{fileName:n,base64Data:l,mimeType:a},"set-file-chooser-handler",5e3)}getSerializedFormFromA11yId(e){return this.stateManager.a11yIdToNodeMap[e]?.getNodeOnlySerializedForm()}retrieveAndClearDebugData(){this.cdpClient.loadEventLogs.length>0&&(this.cdpClient.loadEventLogs=[]);let t={...this.debugData};return this.debugData={logsPerPage:[],harPages:{},harEntries:{}},t}async copy(e){try{await this.evaluateFunctionInPage(t=>navigator.clipboard.writeText(t),e,"copying text to clipboard")}catch(t){if(t instanceof Error&&t.message.includes("Document is not focused")){await this.evaluateFunctionInPage(()=>{document.activeElement||document.body.focus()},void 0,"focusing on body element before copying to clipboard"),await this.press("Tab",{}),await this.press("Shift+Tab",{}),await this.evaluateFunctionInPage(n=>navigator.clipboard.writeText(n),e,"copying text to clipboard");return}throw t}}async paste(){await this.waitForPageLoad(),await this.press("Meta+V",{convertMeta:!0})}async registerRequestListener(e){return this.page.waitForResponse(t=>{let n=t.request();return e.matches({url:n.url(),method:n.method()})})}registerRequestRecorder(e,t,n){this.requestRecorders[e]={onRequestStart:(o,i)=>{t.matches({url:i.request.url,method:i.request.method})&&n.onRequestStart(o,i)},onRequestComplete:(o,i)=>{t.matches({url:i.request.url,method:i.request.method})&&n.onRequestComplete(o,i)}}}removeRequestRecorder(e){delete this.requestRecorders[e]}setHeader(e,t,n){this.customHeaders.push({key:e.toLowerCase(),value:t,matcher:n})}registerMock(e,t,n,o){let i=e??hp();return this.mocks[i]={matcher:t,generateResponse:n,fetchOriginalResponse:o},i}removeMock(e){if(!e){this.mocks={};return}delete this.mocks[e]}static getPossibleCrashReportsDirs(){let e=[];if(Ol()==="linux"){let t=Uo();["chromium","google-chrome","chrome-canary"].forEach(n=>{e.push(yr(t,".config",n,"Crash Reports"))})}else if(Ol()==="darwin"){let t=Uo();["Chromium","Google","Chrome for Testing"].forEach(n=>{e.push(yr(t,"Library","Application Support",n,"Crashpad"))})}else if(Ol()==="win32"){let t=Uo();["Chromium","Google","Google Chrome Canary"].forEach(n=>{e.push(yr(t,"AppData","Local",n,"User Data","CrashPad","reports"))})}return e}static clearCrashReportsDirs(){try{r.getPossibleCrashReportsDirs().forEach(t=>{Fn(t)&&DN(t,{recursive:!0,force:!0})})}catch{}}async setOfflineMode(e){await this.context.setOffline(e)}get smartWaitingTimeout(){return this.userControlledBrowserSettings.smartWaitingTimeoutMs??5e3}get userBrowserSettings(){return ko(this.userControlledBrowserSettings)}get pageLoadTimeout(){return this.userControlledBrowserSettings.pageLoadTimeoutMs??8e3}get isInPageLoad(){return Object.values(this.pageLoadPromises).length>0}get devicePixelRatio(){return this.properties.systemDevicePixelRatio??1}get browserCrashDumpDir(){let e=r.getPossibleCrashReportsDirs();for(let t of e)if(!(!Fn(t)||!HT(t).isDirectory()||!["new","pending","completed"].some(o=>{let i=yr(t,o);return Fn(i)&&HT(i).isDirectory()&&NN(i).length>0})))return t}};import SD from"fetch-cookie";import{cloneDeep as fv}from"lodash-es";import{CookieJar as yD}from"tough-cookie";async function nn(r,e={}){let t=await r.getBrowserState(e);return{serializedTree:t.serialize(),tree:t}}async function Er({frameConfig:r,action:e,browser:t}){let n=t.getActiveFrameConfig();r?t.setActiveFrameConfig(r):n?.type==="auto"&&t.setActiveFrameConfig(void 0);try{return await e()}finally{t.setActiveFrameConfig(n)}}var qN=["NAVIGATE","NEW_TAB","TAB","REFRESH","WAIT_FOR_URL"];async function qT({beforeUrl:r,beforePages:e,browser:t,command:n,logger:o}){if(qN.includes(n.type))return;let l=("cache"in n&&n.cache&&"target"in n.cache?n.cache.target:void 0)?.nodeOnlySerializedHtml?.includes("<a")??!1?300:3e3,c=Date.now(),s=0;for(;s===0||Date.now()-c<l;){await $(250),s++;let u=(await t.getOpenPages()).map(p=>p.url),d=t.url();if(u.length!==e.length)for(let p=u.length-1;p>=e.length;p--){let m=u[p];if(Cn(m,o)&&m!==r&&m!==d){o.info({beforePages:e,afterPages:u,beforeUrl:r},"Auto-following new tab after preset action"),await t.switchToPage({type:"INDEX",index:String(p)});break}}}}var Bn=3.1783027;function KN(r){let e=0;for(let t=0;t<r.length;t++){let n=r.charCodeAt(t);!(n>=48&&n<=57)&&!(n>=65&&n<=90)&&!(n>=97&&n<=122)&&e++}return e}function Ir(r){return Math.ceil(yp(r)/Bn)}function yp(r){let e=0;if(typeof r=="string"){let t=r;t=t.replaceAll(`
3955
+ `,""),t=t.replaceAll(" ","");let n=KN(t);return t.length-n+Bn*n}if(typeof r>"u")return 0;if(typeof r=="number")return String(r).length;if(Array.isArray(r))return r.forEach(t=>{e+=yp(t)}),e;if(typeof r=="object"){let t=r;return Object.keys(t).forEach(n=>{e+=String(n).length,n==="image_url"?(t[n]??{}).detail==="high"?e+=1105*Bn:e+=85*Bn:e+=yp(t[n])}),e}if(typeof r=="boolean")return r?4:5;throw new Error(`Unsupported type passed to token length calculator '${typeof r}': ${r}`)}var YT={minChunkTokenCount:500,acceptableChunkTokenCount:3e3,maxChunkTokenCount:8e3,maxLineLength:4e3},XT={minChunkTokenCount:5e3,acceptableChunkTokenCount:15e3,maxChunkTokenCount:5e4,maxLineLength:500},KT=/<(\S+) id="(\d+)".*?>/g,YN=/(<\/(\S+)>)|(<(\S+).*?\/>)/g,JT=["h1","h2","section","footer","nav","aside","form","label","dialog"],XN=[...JT,"span","div","h3"],JN=["table","select","form","ul","ol","menu","pre","code","dialog"],QN=["table","form","dialog","nav","section","ul","select"];function Nl(r){return ZN(r)}function ZN({serializedTree:r,options:e,logger:t}){let{minChunkTokenCount:n,acceptableChunkTokenCount:o,maxChunkTokenCount:i,maxLineLength:a}=e,l=[],c=r.split(`
3956
+ `),s=0,u=[],d=0,p=[],m=[],g=!1;for(;s<c.length;){g&&(l.push({ids:p,content:u.join(`
3957
+ `),tokenLength:d}),u=[],d=0,p=m.length?[m[m.length-1].id]:[],g=!1);let h=c[s],f=Ir(h);d+=f,h.length>a&&(h=h.slice(0,a));let v=Array.from(h.matchAll(KT)).map(M=>M&&M.length>=3?{tagName:M[1],id:M[2]}:void 0).filter(M=>!!M),T=Array.from(h.matchAll(YN)).map(M=>M&&(M[2]||M[4])).filter(M=>!!M);T.reverse();let x=h.replace(/ id="[0-9]+"/g,"");u.push(x);for(let M of v)p.push(M.id),m.push(M);for(let M of T){let V=m[m.length-1];V&&V.tagName===M&&m.pop()}let N=m.some(M=>JN.includes(M.tagName)),U=c[s+1]??"",Y=Ir(U),te=Array.from(U.matchAll(KT)).map(M=>M&&M.length>2?M[1]:void 0).filter(M=>!!M),ie=te.some(M=>JT.includes(M)),ut=te.some(M=>XN.includes(M));d+Y>=i&&(g=!0),d>=n&&(ie&&!N||T.some(M=>QN.includes(M)))&&(g=!0),d>=o&&ut&&!N&&(g=!0),s++}return u.length&&l.push({ids:p,content:u.join(`
3958
+ `),tokenLength:d}),l.forEach((h,f)=>{t.debug({chunk:h},`Chunk for page filtering (index ${f+1}/${l.length})`)}),{chunks:l}}var eD=9e5,Dl=3e5,tD=5e3;async function zn(r){let{options:e,fixtures:t,screenshot:n}=r,{aiPageFiltering:o}=e,{logger:i,generator:a,orgId:l,signal:c}=t,s=r.tree,u=r.serializedTree,d=Ir(u);if(d>eD)try{let p=Nl({serializedTree:u,options:{minChunkTokenCount:1e4,maxChunkTokenCount:1e5,acceptableChunkTokenCount:5e4,maxLineLength:4e3},logger:i});s=await nD({...r,tokenLimit:Dl-1e4,chunks:p.chunks}),u=s.serialize();let m=Ir(u);i.info({oldTokens:d,newTokens:m},"Filtered page using keywords"),d=m}catch(p){i.warn({err:p},"Error filtering page using keyword matching, using naive truncation"),s=s.pruneToSerializedCharLimit(Dl*Bn),u=s.serialize(),i.info("Filtered page using naive truncation")}if(d>Dl)try{if(o){let p=Nl({serializedTree:u,options:XT,logger:i});s=await B(rD({...r,chunks:p.chunks}),{milliseconds:12e3}),u=s.serialize();let m=Ir(u);i.info({oldTokens:d,newTokens:m},"Filtered page using AI chunk ranking"),d=m}else{let p=Nl({serializedTree:u,options:YT,logger:i});s=await B(oD({...r,chunkResult:p,tokenLimit:4e4}),{milliseconds:12e3,signal:c}),u=s.serialize();let m=Ir(u);i.info({oldTokens:d,newTokens:m},"Filtered page using RAG"),d=m}}catch(p){i.warn({err:p},"Error filtering page using RAG/AI, using naive truncation"),s=s.pruneToSerializedCharLimit(Dl*Bn),u=s.serialize(),i.info("Filtered page using naive truncation")}if(o&&d>tD&&r.type==="locator"&&(l==="org_01HMSCJQBCCG51M2ZF65YC5B8W"||l==="org_01HMJTX4GT1KG94KZRCT8MZ6YB"))try{let p=await a.getPageSummary({browserContext:u,currentStep:r.description,screenshot:n,type:r.type},{logger:i,loggerTags:pe(i),abortSignal:c});i.info(p,"Got AI summaries");let m=new Set;for(let h of p.relevantSections){let f=Math.min(h.startId,h.endId),E=Math.max(h.startId,h.endId);for(let b=f;b<=E;b++)m.add(b.toString())}s=s.pruneUsingRelevantIds(m),u=s.serialize();let g=Ir(u);i.info({newTokens:g,oldTokens:d},"Filtered page using AI summary"),d=g}catch(p){i.warn({err:p},"Error filtering page using AI summary, continuing...")}return u}async function rD({type:r,chunks:e,description:t,fixtures:n,tree:o}){let{generator:i,signal:a,logger:l}=n,c=await i.rankChunksWithAi({chunks:e,description:t,type:r,softTokenLimit:4e4,hardTokenLimit:8e4},{abortSignal:a,logger:l,loggerTags:pe(l)}),s=[];return e.forEach((d,p)=>{c.indices.includes(p)&&(s=s.concat(d.ids))}),o.pruneUsingRelevantIds(new Set(s))}async function nD(r){let{description:e,fixtures:t,tree:n}=r,{generator:o,logger:i,signal:a}=t;if(!e.trim())throw new Error("Empty description passed to page filtering");let l=await o.getExtractedKeywords({goal:e},{logger:i,loggerTags:pe(i),abortSignal:a});i.info({keywordsResult:l},"Got keywords for page filtering");for(let c of l.keywords){let s=r.chunks.filter(m=>m.content.toLowerCase().includes(c.toLowerCase()));if(!s.length||s.reduce((m,g)=>m+g.tokenLength,0)>r.tokenLimit&&s.length>1)continue;let d=s.flatMap(m=>m.ids);return n.pruneUsingRelevantIds(new Set(d))}throw new Error("No keywords were unique enough for page filtering")}async function oD(r){let{description:e,fixtures:t,chunkResult:n,tokenLimit:o,tree:i}=r,{generator:a,logger:l,signal:c}=t,s=await a.rankChunksWithRag({description:e,chunks:n.chunks,tokenLimit:o},{abortSignal:c,logger:l,loggerTags:pe(l)});if(s.ids.length===0)throw new Error("RAG returned no important ids");return i.pruneUsingRelevantIds(new Set(s.ids.map(d=>`${d}`)))}async function bp(r,e){if(!r.description)throw new w("UserConfigurationError","Cannot locate element with empty description");return Er({action:async()=>iD(r,e),frameConfig:r.iframeUrl?{type:"url",url:r.iframeUrl}:void 0,browser:e.browser,logger:r.logger})}async function iD(r,e){let{disableCache:t,testContext:n,filterByViewport:o,skipWait:i,source:a,memory:l,aiPageFiltering:c,logger:s,allowNotActionableNodesOverride:u}=r,{ctx:d,orgId:p,browser:m,localCodeEvalTools:g,generator:h,abortSignal:f}=e,E=r.description,b=r.useMemory&&!t;n&&(E=await xu({orgId:p,s:E,context:n,localTools:g,signal:f,logger:s})),a&&(E=sD(E,a));let{serializedTree:v,tree:A}=await nn(m,{allowNotActionableNodesOverride:u,filterByViewport:o,abortSignal:f,skipWait:i,logger:s}),T,x=Date.now(),N;for(;!T&&Date.now()-x<3e3;){f.throwIfAborted();try{T=await m.screenshot({clearHighlights:!0,respectActiveFrame:!0,retries:2})}catch(Ce){N=Ce}}if(!T)throw new w("ActionFailureError",`Failed to take screenshot of page to locate element. The page may be unresponsive, or your machine might be severely resource constrained. Error: ${N?.message}`);let U=v,Y=!1,te=`data:image/jpeg;base64,${T.toString("base64")}`;U=await zn({type:"locator",description:E,screenshot:te,serializedTree:v,options:{aiPageFiltering:c},tree:A,fixtures:{generator:h,signal:f,logger:s,orgId:p}}),U!==v&&(Y=!0);let ie=await h.getElementLocation({browserState:U,goal:E,screenshot:te,source:a,memory:b?l:void 0},{disableCache:t,abortSignal:f,loggerTags:pe(s),useMemory:b});s.debug({usedRag:Y,result:ie},"Got locator result");let ut=ie.id>0;if(d?.details?.push({type:"AI_LOCATION",matched:ut,pageState:U,ragUsed:Y,thoughts:ie.thoughts}),!ut)throw new go(`Could not find any relevant element: ${ie.thoughts}`,ie.updatedMemory?{type:"GCS_TRACES",traces:ie.updatedMemory}:void 0);let{resolution:M,target:V,frameConfig:re}=await m.createTargetFromA11yId({id:ie.id,requirements:ie.requirements,additionalElements:ie.additionalElements,description:E,targetSource:"AI",logger:s});if(M.a11yNode?.properties?.hidden&&M.a11yNode?.properties?.hidden!=="false")throw new w("ActionFailureError",`Momentic's AI found a relevant element to interact with, but it is explicitly marked with an 'aria-hidden' attribute. Please remove this attribute or adjust the element description to locate a different element. Element chosen: ${M.displayString}`);return b&&(ie.updatedMemory?V.memory={type:"GCS_TRACES",traces:ie.updatedMemory}:l&&(V.memory=l)),{thoughts:ie.thoughts,target:V,resolution:M,frameConfig:re,screenshot:te}}var aD=["Element exactly matching the description below. Interpret the description narrowly and do not assume there are any typos or errors. Err on the side of returning -1 unless there is a perfect match. Description:","Element closely matching the description below. Interpret the description narrowly and do not return elements that are merely loosely related. Description:","Element matching the description below. This element is being located as part of a negative check step (i.e. we are trying to verify the element does not exist). Therefore, interpret the description narrowly, do not assume there are typos, and err on the side of returning -1 unless there is a perfect match. Description:"],QT="<select> element:",ZT="text input or contenteditable element:",ev="Element matching the description below. It is possible the element is hidden or doesn't exist. Interpret the description narrowly and do not assume there are typos. Return -1 unless there is an straightforward match. Description:",tv="Element matching the description below. This element is being located as part of a check step (i.e. we are trying to verify certain properties about the element). Interpret the description narrowly and do not return elements that are merely loosely related. Description:",Ep=[QT,ZT,ev,tv,...aD];function rv(r,e){if(r===e)return!0;for(let t of Ep){if(!r.startsWith(t))continue;let n=r.slice(t.length).trim();if(Ep.some(o=>e.startsWith(o)&&e.slice(o.length).trim()===n)||n===e.trim())return!0}return!!Ep.some(t=>e.startsWith(t)&&e.slice(t.length).trim()===r.trim())}function sD(r,e){if(!r||!e)return r;switch(e){case"SELECT_OPTION":return`${QT} ${r}`;case"TYPE":return`${ZT} ${r}`;case"NEGATED_ELEMENT_VISIBLE_CHECK":return`${ev}
3959
+ ${r}`;case"ELEMENT_CHECK":return`${tv}
3960
+ ${r}`;default:return r}}var lD=15;async function kl({command:r,aiPageFiltering:e,logger:t,fixtures:n,source:o,useMemory:i,maxRetries:a=lD}){if(!r.assertion.trim())throw new w("ActionFailureError","Assertion command is missing the assertion content");let{browser:l}=n,c=r.timeout?r.timeout*1e3:l.smartWaitingTimeout,s=Rs(c),u=0,d=Date.now(),p,m,g;try{await Er({action:()=>l.clearHighlights(),frameConfig:r.iframeUrl?{type:"url",url:r.iframeUrl}:void 0,browser:l,logger:t})}catch(f){t.warn({err:f},"Failed to clear highlights before AI check, continuing...")}let h;for(;u<a&&(!h||h-d<c);){n.abortSignal.throwIfAborted(),u!==0&&await $(s,n.abortSignal),h=Date.now();try{if(p=await Er({action:async()=>{let E=await nv(l,t,n.abortSignal);return m&&m.serializedTree===E.serializedTree&&m.screenshotBuff.equals(E.screenshotBuff)?p:(m=E,ov({command:r,state:E,fixtures:n,useMemory:i,useConsensus:!1,highlightElementsOnFailure:!1,attemptNumber:u,aiPageFiltering:e,logger:t,source:o}))},frameConfig:r.iframeUrl?{type:"url",url:r.iframeUrl}:void 0,logger:t,browser:l}),p?.updatedMemory&&bs(r,p.updatedMemory,t),p?.success)break;throw p?.thoughts?new w("AssertionFailureError",p.thoughts):new w("InternalPlatformError","No thoughts were provided for AI assertion failure")}catch(f){n.abortSignal.throwIfAborted(),g=f instanceof Error?f:new Error(`${f}`),t.info({err:f},`AI check assert attempt ${u} failed, retrying...`)}finally{u++}}if(!p?.success)try{p=await Er({action:async()=>ov({command:r,state:await nv(l,t,n.abortSignal),fixtures:n,useMemory:i,useConsensus:!0,highlightElementsOnFailure:!0,attemptNumber:u,aiPageFiltering:e,logger:t}),frameConfig:r.iframeUrl?{type:"url",url:r.iframeUrl}:void 0,logger:t,browser:l})}catch(f){n.abortSignal.throwIfAborted(),g=f instanceof Error?f:new Error(`${f}`)}finally{u++}if(!p?.success){let f=`AI check still failing after ${u} attempts.`;throw g&&(f+=` Latest result: ${g.message}`),new w("AssertionFailureError",f)}return{...p,succeedImmediately:!1,urlAfterCommand:l.url()}}async function nv(r,e,t){let[n,o]=await Promise.all([nn(r,{abortSignal:t,skipWait:!0,skipWaitForPageLoad:!0,logger:e}),r.screenshot({retries:1,respectActiveFrame:!0})]);return{...n,screenshotBuff:o}}async function ov({command:r,state:e,fixtures:t,useConsensus:n,useMemory:o,highlightElementsOnFailure:i,aiPageFiltering:a,attemptNumber:l,source:c,logger:s}){let{browser:u,generator:d,abortSignal:p}=t,m={type:"ASSERTION"},{serializedTree:g,tree:h}=e,f=e.screenshotBuff,E=f.toString("base64"),b=u.url(),v=r.contextChoice??"MULTIMODAL",A=g;v!=="VISION_ONLY"&&(A=await zn({type:"assertion",serializedTree:g,tree:h,description:r.assertion,screenshot:E,options:{aiPageFiltering:a},fixtures:{generator:d,signal:p,logger:s,orgId:t.orgId}}),A!==g&&(m.ragUsed=!0),m.pageState=A);let T={goal:r.assertion,url:b,memory:o?r.cache?.memory:void 0,browserState:A,screenshot:E,contextChoice:v,source:c},N=await(v==="VISION_ONLY"?(U,Y)=>d.getVisualAssertionResult(U,Y):(U,Y)=>d.getAssertionResult(U,Y))(T,{useConsensus:n,attemptNumber:l,useMemory:o,disableCache:!!r.disableCache,abortSignal:p,logger:s,loggerTags:pe(s)});return(N.result||i)&&N.relevantElements&&(m.relevantElementsSerialized=N.relevantElements.map(U=>u.getSerializedFormFromA11yId(U)).filter(U=>!!U),await cD(N.relevantElements,u,s)),{success:N.result,thoughts:N.thoughts,afterScreenshotOverride:f,updatedMemory:o?N.updatedMemory:void 0}}async function cD(r,e,t){let n=Date.now();for(let o of r){if(Date.now()-n>2e3){t.debug("Highlighting relevant elements took over 2s, aborting...");return}try{let i=new AbortController;await B(e.highlightA11yId(o),{milliseconds:1e3,fallback:()=>{throw i.abort(),new Error("Timed out waiting for highlighting to complete")}})}catch(i){t.debug({err:i},"Failed to highlight relevant element after assertion, continuing...");return}}}import{cloneDeep as av}from"lodash-es";async function sv(r){let{command:e,timeoutMs:t,fixtures:n}=r,{abortSignal:o}=n,i=Pm(e.cache)?e.cache:void 0,a=av(i),l=()=>{i&&(a?i.target={...a.target,memory:i.target.memory}:hc(i.target))},c=Date.now(),s=0,u,d=500,p=!1;for(;s<2||Date.now()-c<t;){s++,s>1&&await $(d,o),o?.throwIfAborted();let{result:m,elementWasFound:g}=await iv({cacheToUse:i,params:r});if(u=m,p=g,m.success)break;l(),d=Math.min(d*2,1e4)}if(!u)throw new w("InternalPlatformError",`Failed to evaluate manual element assertion in ${t}ms.`);if(o?.throwIfAborted(),!u.success&&i?.target&&_a(i.target)){let m=i?.target?.memory?{target:{id:-1,memory:i.target.memory}}:void 0,{result:g}=await iv({cacheToUse:m,params:r});u=g,u.success||l()}return u.success&&i?.target&&!p&&hc(i.target),u}async function iv({cacheToUse:r,params:e}){let{command:t,disableCache:n,fixtures:o,tracer:i,targetingWrapper:a}=e,{logger:l}=o;if(t.target&&!Nr(t.target))throw new Error("Element assertion with x/y is not supported yet");let c=dD(t.assertion),s,u=!1,d=av(r);try{let{elementInteractedDisplayString:p,result:m,thoughts:g}=await a({ctx:o.ctx,tracer:i,command:t,target:t.target,cache:d?.target,action:async h=>uD(h.locator,e),options:{...t,allowNotActionableNodesOverride:!0,disableCache:n,memory:d?.target?.memory,disableGlobalLocatorRedirect:!0,source:gi(t),targetName:"target"}});return s={success:m.success,data:m.data,err:m.err,elementInteractedDisplayString:p,thoughts:g},u=!0,m.success||(l.warn({aiThoughts:g,elementString:p,err:m.err},"Element check found an element but failed"),s={...m,thoughts:g}),{result:s,elementWasFound:u}}catch(p){if(c)return s={success:!0,thoughts:`The element described does not exist on the page: ${p.message}`,err:void 0,data:void 0},{result:s,elementWasFound:u};if(!(p instanceof w)||p.reason!="ActionFailureError")throw p;return s={success:!1,err:p,data:void 0,thoughts:void 0},l.warn({err:p},"Element check did not find an element and failed"),{result:s,elementWasFound:u}}}async function uD(r,{command:e,fixtures:t}){let n=e.assertion;await t.browser.highlight(r);let o=!0,i,a;switch(n.type){case"ELEMENT_CONTENT":{let c=await r.textContent()??"";if(a={elementTextContent:St(c,500,!0)},!Ul(c,n.value,n.operation,!!n.negated)){let s=n.negated?vn[n.operation]:An[n.operation];o=!1,i=new w("AssertionFailureError",`The content ${s} '${n.value}': ${c}`)}break}case"ELEMENT_ATTRIBUTE":{a={elementOuterHtml:St(await r.evaluate(s=>s.cloneNode(!1).outerHTML),500,!0)};let c;try{c=await r.getAttribute(n.attr,{timeout:3e3})??""}catch(s){i=new w("AssertionFailureError",`The element does not have an attribute named ${n.attr}: ${s}`),o=!1;break}if(!Ul(c,n.value,n.operation,!!n.negated)){let s=n.negated?vn[n.operation]:An[n.operation];o=!1,n.operation==="EXISTS"?i=new w("AssertionFailureError",`The attribute ${n.attr} ${s}`):i=new w("AssertionFailureError",`The attribute ${n.attr} ${s} '${n.value}': ${c}`)}break}case"ELEMENT_EXISTENCE":{switch(n.condition){case"VISIBLE":{o=await r.evaluate(async(s,u)=>{let d=Date.now();for(;Date.now()-d<u;){await new Promise(m=>setTimeout(m,250));let p=s.getBoundingClientRect();if(!(p.width===0||p.height===0)&&window.getComputedStyle(s).visibility!=="hidden"&&window.getComputedStyle(s).display!=="none")return!0}return!1},kr*1e3);break}case"EDITABLE":{o=await r.isEditable({timeout:kr*1e3});break}case"EXISTS":{o=!0;break}case"ENABLED":{o=await r.isEnabled({timeout:kr*1e3});break}case"FOCUSED":{o=await r.evaluate(s=>s===document.activeElement);break}default:return(s=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(n.condition)}if(o=n.negated?!o:o,!o){let c=n.negated?Bf[n.condition]:zf[n.condition];i=new w("AssertionFailureError",`The element ${c}`)}break}case"ELEMENT_NAME":{let c=await r.evaluate(s=>s.tagName);if(!Ul(c,n.value,n.operation,!!n.negated)){let s=n.negated?vn[n.operation]:An[n.operation];o=!1,i=new w("AssertionFailureError",`The element tag name ${s} '${n.value}': ${c}`)}break}case"ELEMENT_STYLE":{let c=await r.evaluate((s,u)=>window.getComputedStyle(s).getPropertyValue(u),n.property);if(!Ul(c,n.value,n.operation,!!n.negated)){let s=n.negated?vn[n.operation]:An[n.operation];o=!1,n.operation==="EXISTS"?i=new w("AssertionFailureError",`The style property ${n.property} ${s}`):i=new w("AssertionFailureError",`The style property ${n.property} ${s} '${n.value}': ${c}`)}break}default:return(c=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(n)}return{success:o,data:a,err:i}}function Ul(r,e,t,n){let o;switch(t){case"CONTAINS":{o=r.includes(e);break}case"EQUALS":{o=r.trim()===e.trim();break}case"STARTS_WITH":{o=r.trim().startsWith(e);break}case"EXISTS":{o=r.trim().length>0;break}default:return(a=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(t)}return n?!o:o}function dD(r){return r.type==="ELEMENT_EXISTENCE"&&r.negated&&(r.condition==="EXISTS"||r.condition==="VISIBLE")}function lv(r){return r.type==="ELEMENT_EXISTENCE"&&r.negated&&r.condition==="EXISTS"}import{Jimp as pD}from"jimp";async function sa(r,e){let t=await r.screenshot(e),n=await pD.fromBuffer(t);return{buffer:t,width:Math.ceil(n.bitmap.width??0),height:Math.ceil(n.bitmap.height??0)}}import{Jimp as cv}from"jimp";import Tp from"jpeg-js";import mD from"pixelmatch";async function uv({ctx:r,tracer:e,command:t,disableCache:n,browser:o,targetingWrapper:i,logger:a,screenshotStorage:l}){if(t.target&&!Nr(t.target))throw new Error("Visual Diff with x/y is not supported yet");await o.waitForDOMStability({logger:a});let c={clearHighlights:!0,hideCaret:!0},s;t.target?.elementDescriptor?s=(await i({ctx:r,tracer:e,command:t,target:t.target,cache:t.cache?.target,action:async te=>sa(o,{locator:te.locator,...c}),options:{...t,disableCache:n,disableGlobalLocatorRedirect:!0,memory:t.cache?.target?.memory,targetName:"target"}})).result:s=await sa(o,c);let u=await l.prepareGoldenScreenshotForComparison(a,t,s);if((s.height!==u.height||s.width!==u.width)&&a.warn({currHeight:s.height,currWidth:s.width,savedHeight:u.height,savedWidth:u.width},"Mismatched before and after visual diff screenshot sizes"),Math.abs(s.height-u.height)>10||Math.abs(s.width-u.width)>10){let ke=`${s.width}x${s.height}`,te=`${u.width}x${u.height}`;return{fail:!0,thoughts:`Current screenshot (${ke}) does not match saved screenshot dimensions (${te}) - did you change the size of the target or the viewport?`,beforeScreenshotOverride:u.buffer,afterScreenshotOverride:s.buffer,succeedImmediately:!1,urlAfterCommand:o.url()}}let d=await cv.fromBuffer(s.buffer),p={width:s.width,height:s.height},m=await cv.fromBuffer(u.buffer),g={width:u.width,height:u.height},h,f=p.width*p.height,E=g.width*g.height,b=Math.abs(p.height-g.height),v=Math.abs(p.width-g.width);if(f>E){let ke=d.cover({w:g.width,h:g.height});s.buffer=await ke.getBuffer("image/jpeg"),h="current",s.width=g.width,s.height=g.height}else if(E>f){let ke=m.cover({w:p.width,h:p.height});u.buffer=await ke.getBuffer("image/jpeg"),h="saved"}let A={data:Buffer.alloc(s.width*s.height*4),width:s.width,height:s.height},T=t.threshold??.1,N=mD(Tp.decode(u.buffer).data,Tp.decode(s.buffer).data,A.data,s.width,s.height,{threshold:T,diffColorAlt:[0,255,0]})/(s.width*s.height)*100,U=N>T*100,Y=`Visual diff of ${N.toFixed(2)}% detected, which is ${U?"over":"under"} the threshold of ${T*100}%.`;if(h&&(Y+=` The ${h} screenshot was cropped since it was taller by ${b} pixels and wider by ${v} pixels.`),U)throw new w("ActionFailureError",Y);return{fail:U,thoughts:Y,beforeScreenshotOverride:s.buffer,afterScreenshotOverride:Tp.encode(A,75).data,succeedImmediately:!1,urlAfterCommand:o.url()}}var gD=3e4;async function dv({command:r,logger:e,baseUrl:t,fetchImplementation:n=fetch}){let o=r.timeout??gD/1e3,i=Object.fromEntries(Object.entries(r.headers||{}).filter(([m,g])=>m&&g)),a=new URLSearchParams;Object.entries(r.params||{}).filter(([m,g])=>m&&g).forEach(([m,g])=>{a.append(m,g)});let l=a.toString(),c;if(So(r.url)&&(c=r.url),t&&yo(r.url,t)&&(c=new URL(r.url,t).toString()),!c)throw new w("ActionFailureError",`Invalid URL: ${r.url}`);e.info({url:c,searchParams:l,headers:i,body:r.body,method:r.method},"Making HTTP request");let u=await B((async()=>{let m=l?`${c}?${l}`:c;try{return await n(m,{headers:i,method:r.method,body:r.body})}catch(g){throw e.error({err:g},"Failed to make HTTP request"),new Error(`Failed to make HTTP request: ${g}`)}})(),{milliseconds:o*1e3,fallback:()=>{throw new w("ActionFailureError",`Fetch request timed out after ${o} seconds`)}});if(!u.ok){let m;try{m=await u.text()}catch(g){m=`Failed to read response body: ${g}`}throw new w("ActionFailureError",`Fetch request failed with status ${u.status}: ${m}`)}let d={};u.headers.forEach((m,g)=>{d[g]=m});let p={status:u.status,headers:d};if(u.headers.get("content-type")?.includes("json"))try{p.json=await u.json()}catch{}else u.headers.get("content-type")?.includes("text")&&(p.text=await u.text());return p}var hD=5e3;async function gv({timeout:r=kr,...e}){let t=Date.now(),n=r*1e3,o=n+1e4,i,a=0,l=500;for(;a-t<n;){if(Date.now()-t>o){e.logger.warn("Exceeded max system timeout for page assertion, exiting...");break}e.signal.throwIfAborted();let c=Date.now();i=await pv(e),a=Date.now();let s=a-c;if(s>1e3&&e.logger.warn({pageAssertDuration:s},"Page assertion took longer than expected"),!i.success)await $(l,e.signal),l=Math.min(Math.floor(l*1.5),hD);else return i}return i=await pv(e),i}async function pv({assertion:r,browser:e,autoExpandIframes:t}){switch(r.type){case"CONTENT":{let o,i=!1,a;try{let l;if(t){let c=await e.evaluateFunctionInAllFrames(mv,{value:r.value,negated:!!r.negated,returnHtml:!1});i=r.negated?c.every(s=>s.evaluation):c.some(s=>s.evaluation),l=c.find(s=>s.pageHtml)?.pageHtml}else({evaluation:i,pageHtml:l}=await e.evaluateFunctionInPage(mv,{value:r.value,negated:!!r.negated,returnHtml:!0},"checking page content"));if(!i){let c=r.negated?vn.CONTAINS:An.CONTAINS;a=new w("AssertionFailureError",`The page ${c} '${r.value}'.`),o=l}}catch(l){a=new w("AssertionFailureError",`Failed to evaluate page content assertion: ${l instanceof Error?l.message:`${l}`}`)}return{success:i,err:a,data:i||!o?void 0:{pageContent:o}}}default:return(o=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(r.type)}}function mv({value:r,negated:e,returnHtml:t}){let n=document.documentElement.outerHTML,o=n.includes(r)===!e;return n.length>1e4&&(n=n.slice(0,1e4)+"...TRUNCATED"),{evaluation:o,pageHtml:!o&&t?n:void 0}}var fD=3e4;async function hv({command:r,logger:e,baseUrl:t,fetchImplementation:n=fetch}){let o=r.timeout??fD/1e3,i=new AbortController,a=Object.fromEntries(Object.entries(r.headers||{}).filter(([d,p])=>d&&p));a["Content-Type"]="application/json";let l;if(So(r.url)&&(l=r.url),t&&yo(r.url,t)&&(l=new URL(r.url,t).toString()),!l)throw new w("ActionFailureError",`Invalid URL: ${r.url}`);let s=await B((async()=>{try{return await n(l,{headers:a,method:"POST",body:JSON.stringify({query:r.query,variables:r.variables?JSON.parse(r.variables):void 0}),signal:i.signal})}catch(d){e.error({err:d},"Failed to make HTTP request")}})(),{milliseconds:o*1e3});if(!s)throw new w("ActionFailureError",`GraphQL request timed out after ${o} seconds`);if(!s.ok){let d,p=await s.text();try{d=JSON.parse(p)}catch{throw new w("ActionFailureError",`GraphQL request failed with status ${s.status}: ${p}`)}throw d?.errors?.length&&d?.errors[0]?.message?new w("ActionFailureError",`GraphQL request failed with status ${s.status}: ${d.errors[0].message}`):new w("ActionFailureError",`GraphQL request failed with status ${s.status}: ${p}`)}let u={};return s.headers.forEach((d,p)=>{u[p]=d}),{status:s.status,headers:u,json:await s.json()}}var Fl=class{orgId;options;storage;localCodeEvalTools;uploadedFileStorage;visualDiffScreenshotStorage;browser;generator;executeAbortController=new AbortController;logger;recordAbortController=null;registeredListeners={};recordedRequests={};constructor({browser:e,generator:t,logger:n,storage:o,orgId:i,localCodeEvalTools:a,uploadedFileStorage:l,visualDiffScreenshotStorage:c,options:s}){this.orgId=i,this.options=s,this.browser=e,this.browser.registerAbortSignal(this.executeAbortController.signal),this.storage=o,this.uploadedFileStorage=l,this.visualDiffScreenshotStorage=c,this.localCodeEvalTools=a,this.generator=t,this.logger=n}setOpen(){this.executeAbortController=new AbortController,this.browser.registerAbortSignal(this.executeAbortController.signal)}setClosed(){this.executeAbortController.abort()}throwIfClosed(){this.executeAbortController.signal.throwIfAborted()}get closed(){return this.executeAbortController.signal.aborted}async evaluateAiAction({goal:e,startingScreenshot:t,history:n,disableCache:o,langfuseSessionId:i,lastError:a,logger:l=this.logger}){let[c,s]=await Promise.all([nn(this.browser,{abortSignal:this.executeAbortController.signal,skipWait:!0,skipWaitForPageLoad:!0,logger:l}),this.browser.screenshot({retries:1,clearHighlights:!0})]),u=`data:image/jpeg;base64,${s.toString("base64")}`,d=await zn({type:"ai-action",description:e,screenshot:u,serializedTree:c.serializedTree,tree:c.tree,options:{aiPageFiltering:!!this.options?.aiPageFiltering},fixtures:{generator:this.generator,signal:this.executeAbortController.signal,logger:l,orgId:this.orgId}}),p={url:this.browser.url(),browserState:d,startingScreenshot:t,history:n,goal:e,screenshot:u,lastError:a};return await this.generator.getMultiturnAiActionEvaluation(p,{disableCache:o,abortSignal:this.executeAbortController.signal,loggerTags:{...pe(l)},langfuseSessionId:i})}async promptToCommand({goal:e,startingScreenshot:t,history:n,actionHint:o,disableCache:i,logger:a=this.logger,langfuseSessionId:l}){let c=this.browser.url(),[s,u]=await Promise.all([nn(this.browser,{abortSignal:this.executeAbortController.signal,skipWait:!0,skipWaitForPageLoad:!0,logger:a}),this.browser.screenshot({retries:1,clearHighlights:!0})]),d=`data:image/jpeg;base64,${u.toString("base64")}`,p=await zn({type:"ai-action",description:e,screenshot:d,serializedTree:s.serializedTree,tree:s.tree,options:{aiPageFiltering:!!this.options?.aiPageFiltering},fixtures:{generator:this.generator,signal:this.executeAbortController.signal,logger:a,orgId:this.orgId}}),m={url:c,browserState:p,startingScreenshot:t,history:n,goal:e,actionHint:o,screenshot:d};try{return await this.generator.getMultiturnAiActionCommand(m,{disableCache:i,abortSignal:this.executeAbortController.signal,loggerTags:{...pe(a)},langfuseSessionId:l})}catch(g){throw new w("InternalWebAgentError",`Error generating command: ${g instanceof Error?g.message:g}`,{errOptions:{cause:g}})}}async getBrowserState(e){return nn(this.browser,e)}async locateElement(e){return await bp({...e,aiPageFiltering:!!this.options?.aiPageFiltering},this.getControllerFixtures())}async locateElementWithSelector(e,t){return Er({action:async()=>{let n=await this.browser.resolveHardcodedCssSelector({ctx:null,selector:e,timeoutMs:2e3,logger:this.logger});return{thoughts:"Located element with selector",target:{id:-1,selector:e,targetSource:"USER_CSS_SELECTOR",targetUpdateTime:new Date().toUTCString()},resolution:n}},frameConfig:t?{type:"url",url:t}:void 0,browser:this.browser,logger:this.logger})}getControllerFixtures(e){return{ctx:e??null,browser:this.browser,generator:this.generator,logger:this.logger,orgId:this.orgId,storage:this.storage,localCodeEvalTools:this.localCodeEvalTools,abortSignal:this.executeAbortController.signal}}shouldUseMemory(){return this.options?.useMemory??(this.orgId==="org_01HMSCJQBCCG51M2ZF65YC5B8W"||this.orgId==="org_01HMJTX4GT1KG94KZRCT8MZ6YB")}async wrapMultiElementTargetingCommand({ctx:e,tracer:t,command:n,targetNames:o,descriptions:i,caches:a,action:l,options:c,retriesWithAI:s=1}){let u=[];for(let d=0;d<i.length;d++){let p=i[d],m=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:p,cache:a[d],action:async g=>g,options:{...c,targetName:o[d]}});u.push(m)}try{let d=await l(...u.map(g=>g.result)),p=g=>g==="fromTarget"?"From Target":g==="toTarget"?"To Target":"Target",m=u.map((g,h)=>g.thoughts?`${p(o[h])}: ${g.thoughts}`:void 0).filter(g=>!!g).join(" -------------- ")||void 0;return{result:d,elementInteractedDisplayStrings:u.map(g=>g.elementInteractedDisplayString),thoughts:m}}catch(d){if(this.throwIfClosed(),s>0)return this.logger.warn({err:d},"Failed to execute action with multiple cached targets, retrying with AI"),this.wrapMultiElementTargetingCommand({ctx:e,tracer:t,command:n,targetNames:o,descriptions:i,caches:i.map(()=>{}),action:l,options:c,retriesWithAI:s-1});throw new w("ActionFailureError",d.message,{errOptions:{cause:d}})}}async wrapElementTargetingCommand(e){let t=this.logger.child({commandId:e.command.id}),n;for(let o=0;o<2;o++)try{return await Er({action:()=>this.wrapElementTargetingCommandHelper({...e,originalCache:e.originalCache??e.cache}),frameConfig:e.options.iframeUrl?{type:"url",url:e.options.iframeUrl}:void 0,browser:this.browser,logger:t})}catch(i){if(n=i,this.browser.userBrowserSettings.visualActions&&lu(i)){t.warn({err:i},"Invalid mpath error, retrying element targeting command");continue}if(!this.browser.userBrowserSettings.visualActions&&(uu(i)||cu(i))){t.warn({err:i},"Invalid momentic id error, retrying element targeting command");continue}if(du(i)){t.warn({err:i},"Invalid backend node id error, retrying element targeting command");continue}if(i instanceof sr&&i.retryableWithAI){t.warn({err:i},"Element cache disqualification error, retrying element targeting command");continue}throw i}throw n instanceof w?n:new w("ActionFailureError",n?.message??"An unknown error occurred during element targeting")}async wrapHardcodedCssTargetingCommandHelper({ctx:e,target:t,action:n,options:o,command:i}){let a=this.logger.child({commandId:i.id}),{targetName:l}=o;if(t.type!=="description")throw new w("ActionFailureError","Cannot use selector with non-description target");let c,s=Date.now(),u=Date.now();for(;Date.now()-u<this.browser.smartWaitingTimeout;){s=Date.now();try{let d=await this.browser.resolveHardcodedCssSelector({ctx:e,selector:t.elementDescriptor,targetName:l,logger:a});return{result:await n({locator:d.locator}),elementInteractedDisplayString:d.displayString}}catch(d){if(d.name==="AbortError")throw d;c=d,a.warn({err:d},"Failed to action on hardcoded css selector"),Date.now()-s<500&&await $(500)}}throw c}async wrapElementTargetingCommandHelper(e){let{ctx:t,tracer:n,target:o,originalCache:i,action:a,options:l,command:c}=e,{disableCache:s,useSelector:u,targetName:d,targetHealingInProgress:p,source:m}=l,g=this.logger.child({commandId:c.id}),h=this.shouldUseMemory(),f=l.retriesWithAI??1,E=!1,b=fv(e.cache);if((!b||s)&&!fc(o))throw new w("ActionFailureError","Cannot target element with no cached data or element descriptor");if(u)return this.wrapHardcodedCssTargetingCommandHelper(e);s&&(g.info("Cache explicitly disabled for this step"),E=!0,b=void 0),b&&this.browser.userBrowserSettings.disableSecondaryCacheResolution&&b.targetSource==="HEURISTIC_HEALED"&&(E=!0,b=void 0),b?.inputDescription&&!rv(o.elementDescriptor,b.inputDescription)&&(g.warn({old:b.inputDescription,new:o.elementDescriptor},"Target cache was generated with a different description, clearing it automatically"),E=!0,b=void 0);let v=T=>!!T&&_a(T),A=!0;if(!v(b)){A=!1,g.info({description:o.elementDescriptor,targetHealingInProgress:p,cacheBustedBeforeAction:E,memory:l.memory,useMemory:h},"Prompting AI for an updated element location"),E&&await $(this.browser.smartWaitingTimeout,this.executeAbortController.signal),f--;let T;try{T=await bp({description:o.elementDescriptor,disableCache:!!l.disableCache,iframeUrl:l.iframeUrl,source:m,useMemory:h,memory:h?l.memory:void 0,aiPageFiltering:!!this.options?.aiPageFiltering,allowNotActionableNodesOverride:l.allowNotActionableNodesOverride,logger:g},this.getControllerFixtures(t))}catch(U){if(U instanceof go&&U.updatedLocatorMemory){let Y={id:-1,...i,memory:U.updatedLocatorMemory};Es({cmd:c,key:d,newTarget:Y,logger:g})}throw new w("ActionFailureError",U.message)}T.frameConfig&&this.browser.setActiveFrameConfig(T.frameConfig);let x=l.disableGlobalLocatorRedirect?{locator:T.resolution.locator}:await this.attemptLocatorRedirect(T.resolution.locator,g),N=await a(x);return Es({cmd:c,key:d,newTarget:T.target,logger:g}),p&&(n.recordTargetAutoHeal({healType:"AI"}),T.target.targetSource="AI_HEALED",T.target.targetUpdateTime=new Date().toUTCString(),T.target.targetUpdateLoggerTags=pe(g)),{result:N,elementInteractedDisplayString:T.resolution.displayString,thoughts:T.thoughts}}try{let T=await this.browser.resolveTarget(t,b,{allowNotActionableNodesOverride:l.allowNotActionableNodesOverride,targetName:d,logger:g,signal:this.executeAbortController.signal});(this.browser.userBrowserSettings.visualActions||this.browser.userBrowserSettings.globalLocatorRedirect!==!1)&&await this.browser.scrollIntoViewIfNeeded(T.locator);let x=l.disableGlobalLocatorRedirect?{locator:T.locator}:await this.attemptLocatorRedirect(T.locator,g),N=await a(x);if(Mt.increment("cache_target_resolution_v2",1,["outcome:hit","platform:web",`hasRequirements:${!!b.requirements}`,`hasAdditionalElements:${!!b.additionalElements}`]),Es({cmd:c,key:d,newTarget:b,logger:g}),A){let U=T.decisions.filter(Y=>Y.matched);if(U.length!==1)g.warn({decisions:T.decisions},"Expected exactly 1 matching method for element location, got more or less");else{let Y=U[0].type;n.recordTargetAutoHeal({healType:Y})}}return{result:N,elementInteractedDisplayString:T.displayString}}catch(T){this.throwIfClosed(),Mt.increment("cache_target_resolution_v2",1,["outcome:miss","platform:web",`hasRequirements:${!!b.requirements}`,`hasAdditionalElements:${!!b.additionalElements}`]);let x=!1;if((T instanceof sr||lu(T)||uu(T)||du(T)||gh(T)||cu(T))&&(x=!0),T instanceof w&&!x)throw g.error({err:T},"Failed to execute action with cached target (fatal)"),T;if(f>0&&o){g.info({err:T},"Failed to execute action with cached target, retrying with AI");let N;return b.memory&&wm(b.memory)&&(N=b.memory),this.wrapElementTargetingCommand({ctx:t,tracer:n,command:c,target:o,cache:void 0,originalCache:i,action:a,options:{...l,memory:N,retriesWithAI:f,targetHealingInProgress:!0}})}throw new w("ActionFailureError",T.message,{errOptions:{cause:T}})}}async attemptLocatorRedirect(e,t){return this.browser.userBrowserSettings.globalLocatorRedirect!==!1?this.browser.performTargetRedirection(e,t):{locator:e}}async screenshotWithDimensions(e){return sa(this.browser,e)}async executePresetCommand(e,t,n,o,i){this.options?.slowMoMs&&await $(this.options.slowMoMs);let a=await this.browser.getOpenPages(),l=this.browser.url(),c;try{c=await this.resolveCommandTemplateStrings(n,o)}catch(s){throw this.throwIfClosed(),new w("ActionFailureError",`Failed to substitute template strings in command: ${s.message}`,{errOptions:{cause:s}})}try{let s=await this.executePresetCommandHelper(e,t,n,o,i);return this.browser.userBrowserSettings.visualActions&&Dm(n)?await this.browser.waitForDOMStability({timeout:2e3}):!this.browser.userBrowserSettings.visualActions&&["PRESS","TYPE"].includes(n.type)&&await this.browser.waitForDOMStability({timeout:1e3}),this.options?.autoFollowNewTabs&&await qT({beforeUrl:l,command:n,beforePages:a.map(u=>u.url),browser:this.browser,logger:this.logger}),s}catch(s){throw s.name!=="AbortError"&&this.logger.error({err:s},"Error thrown in action controller"),s}finally{ys(n,c)}}createCallbacksForBrowser(e){return{createIsolatedFolder:()=>Yd(e)}}async resolveCommandTemplateStrings(e,t){return Ss({obj:e,context:t,bannedKeys:["type","a11yData","thoughts","cache","code"],orgId:this.orgId,logger:this.logger,signal:this.executeAbortController.signal,localTools:this.localCodeEvalTools})}async executePresetCommandHelper(e,t,n,o,i){i=i||"disableCache"in n&&!!n.disableCache;let a=this.logger.child({commandId:n.id});switch(n.type){case"SUCCESS":let l=n.condition;return l?.assertion.trim()?kl({command:l,fixtures:this.getControllerFixtures(e),useMemory:this.shouldUseMemory(),aiPageFiltering:!!this.options?.aiPageFiltering,logger:a}):{succeedImmediately:!1,urlAfterCommand:this.browser.url()};case"AI_ASSERTION":{if(!n.assertion.trim())throw new w("ActionFailureError","Missing assertion");if(n.timeout&&n.timeout>1800)throw new w("AssertionFailureError",`AI check timeout of ${n.timeout} exceeds the maximum allowed value of 30 minutes.`);return kl({command:n,fixtures:this.getControllerFixtures(e),useMemory:this.shouldUseMemory(),aiPageFiltering:!!this.options?.aiPageFiltering,logger:a})}case"AI_EXTRACT":{if(!n.goal.trim())throw new w("ActionFailureError","Cannot perform AI extraction without goal");if(n.schema){let f=bf(n.schema);if(f)throw new w("UserConfigurationError",f)}let g=await this.browser.getCondensedHtml(),h=await this.browser.screenshot({retries:2});try{let f=await this.generator.getTextExtraction({goal:n.goal,browserState:g,returnSchema:n.schema,screenshot:`data:image/jpeg;base64,${h.toString("base64")}`},{disableCache:i,abortSignal:this.executeAbortController.signal,loggerTags:pe(a)});if(f.result==="NOT_FOUND")throw new w("ActionFailureError","No relevant data found for extraction goal on this page");if(f.thoughts?.includes("MaxGenerationLengthExceededError"))throw new w("UserConfigurationError",f.thoughts);return{thoughts:f.thoughts||void 0,data:f.result,succeedImmediately:!1,urlAfterCommand:this.browser.url()}}catch(f){let E=f.message;throw E.includes("MaxGenerationLengthExceededError")?new w("UserConfigurationError","You tried to extract too much data. Please rephrase your query to limit the results returned or use a JavaScript step in the browser instead."):E.includes("AIProviderError")&&E.includes("time")?new w("AIProviderError","The AI provider responded with an error. This may be because you tried to extract too much data. Please limit extraction results to 2000 characters.",{errOptions:{cause:f}}):f}}case"NAVIGATE":if(!So(n.url)&&!yo(n.url,this.browser.baseUrl))throw new w("ActionFailureError",`Invalid URL provided to navigate command: ${n.url}`);await this.browser.navigate({url:n.url,loadTimeoutMs:n.loadTimeout?n.loadTimeout*1e3:void 0});break;case"DIALOG":this.browser.registerDialogHandler(n.action);break;case"CAPTCHA":if(!this.browser.canSolveCaptchas())break;let c=await this.browser.solveCaptcha();c&&(await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:{type:"description",elementDescriptor:"the captcha image solution input"},cache:void 0,action:g=>this.browser.click(g,this.createCallbacksForBrowser(this.orgId),{}),options:{...n,targetName:"target",disableCache:i}}),await this.browser.type(c,{clearContent:!0,pressEnter:!0},!0));break;case"GO_BACK":await this.browser.goBack();break;case"GO_FORWARD":await this.browser.goForward();break;case"SCROLL_LEFT":case"SCROLL_RIGHT":case"SCROLL_DOWN":case"SCROLL_UP":{let g,h;if(n.target&&nr(n.target))await this.browser.hoverUsingVisualCoordinates(n.target.pixels);else if(n.target&&n.target.elementDescriptor.trim()){let{elementInteractedDisplayString:b,thoughts:v}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:n.target,cache:n.cache?.target,action:A=>this.browser.hover(A),options:{...n,targetName:"target",disableGlobalLocatorRedirect:!0,disableCache:i}});g=b,h=v}let f=this.browser.getViewport()?.height??Br.height,E=this.browser.getViewport()?.width??Br.width;switch(n.type){case"SCROLL_UP":await this.browser.scrollVertical(-(n.deltaY??f));break;case"SCROLL_DOWN":await this.browser.scrollVertical(n.deltaY??f);break;case"SCROLL_LEFT":await this.browser.scrollHorizontal(-(n.deltaX??E));break;case"SCROLL_RIGHT":await this.browser.scrollHorizontal(n.deltaX??E);break}return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:g,thoughts:h}}case"WAIT_FOR_URL":{if(n.timeout&&n.timeout>1800)throw new w("UserConfigurationError",`Wait for URL timeout of ${n.timeout} exceeds the maximum allowed value of 30 minutes.`);let g=n.matcher;await this.browser.waitForUrl({beforeUrl:this.browser.url(),matcher:g},{timeout:n.timeout?n.timeout*1e3:void 0,negated:n.negated,caseInsensitive:n.caseInsensitive});break}case"WAIT":if(n.delay>1800)throw new w("UserConfigurationError",`Wait timeout of ${n.delay} seconds exceeds the maximum allowed value of 30 minutes`);let s=n.delay*1e3;await $(s,this.executeAbortController.signal);break;case"REFRESH":await this.browser.refresh({loadTimeoutMs:n.loadTimeout?n.loadTimeout*1e3:void 0});break;case"CLICK":{if(nr(n.target)){await this.browser.clickUsingVisualCoordinates(n.target.pixels,n);break}let g=this.browser.url(),{elementInteractedDisplayString:h,result:f,thoughts:E}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,target:n.target,command:n,cache:n.cache?.target,action:v=>this.browser.click(v,this.createCallbacksForBrowser(this.orgId),n),options:{disableCache:i,targetName:"target",...n}}),b={urlAfterCommand:this.browser.url(),succeedImmediately:!1,elementInteracted:h,thoughts:E,data:f};return Cs(g,b.urlAfterCommand)&&(b.succeedImmediately=!0,b.succeedImmediatelyReason="URL changed"),b}case"COPY":return await this.browser.copy(n.value),{succeedImmediately:!1,data:n.value,urlAfterCommand:this.browser.url()};case"PASTE":{await this.browser.paste();break}case"DRAG":{if(nr(n.fromTarget)&&nr(n.toTarget)){await this.browser.dragAndDropUsingVisualCoordinates(n.fromTarget.pixels,n.toTarget.pixels,{hoverSeconds:n.hoverSeconds});break}if(nr(n.fromTarget)||nr(n.toTarget))throw new Error("Drag and drop targets must be both coordinates or both descriptions");let{elementInteractedDisplayStrings:g,thoughts:h}=await this.wrapMultiElementTargetingCommand({ctx:e,tracer:t,command:n,targetNames:["fromTarget","toTarget"],descriptions:[n.fromTarget,n.toTarget],caches:[n.cache?.fromTarget,n.cache?.toTarget],action:(f,E)=>this.browser.dragAndDrop(f.locator,E.locator,{hoverSeconds:n.hoverSeconds,steps:n.steps}),options:{useSelector:!!n.useSelector,disableCache:i}});return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:g[0],thoughts:h}}case"MOUSE_DRAG":{let g=parseInt(n.deltaX),h=parseInt(n.deltaY),f=n.steps??5;if(isNaN(g)||isNaN(h))throw new w("ActionFailureError",`Invalid pixel values passed to mouse drag command: (${n.deltaX}, ${n.deltaY})`);if(n.target&&nr(n.target)){await this.browser.mouseDragUsingVisualCoordinates(g,h,f,n.target.pixels,{force:n.force});break}let E,b,v;if(n.target?.elementDescriptor){let{elementInteractedDisplayString:A,result:T,thoughts:x}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:n.target,cache:n.cache?.target,action:async N=>N.locator,options:{disableCache:i,targetName:"target",...n}});E=T,b=A,v=x}return await this.browser.mouseDrag(g,h,f,E,{force:n.force}),{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:b,thoughts:v}}case"SELECT_OPTION":{if(!Nr(n.target))throw new Error("Select with x/y is not supported yet");let g=n.target.elementDescriptor,h=n.choice,{elementInteractedDisplayString:f,thoughts:E}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:{type:"description",elementDescriptor:g},cache:n.cache?.target,action:b=>this.browser.selectOption(b,h,n.force),options:{...n,targetName:"target",disableCache:i,source:gi(n)}});return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:f,thoughts:E}}case"TAB":{let g={loadTimeoutMs:n.loadTimeout?n.loadTimeout*1e3:void 0,retry:!0};await this.browser.switchToPage(n.action,g);break}case"NEW_TAB":await this.browser.createNewTab(n.url,{loadTimeoutMs:n.loadTimeout?n.loadTimeout*1e3:void 0});break;case"COOKIE":if(!n.value)break;let u=await this.browser.setCookie(n.value);a.debug({results:u},"Set cookies");break;case"LOCAL_STORAGE":if(!n.value||!n.key)break;await this.browser.setLocalStorage(n.key,n.value);break;case"JAVASCRIPT":{let g;try{n.environment==="BROWSER"?(g=await this.browser.evaluateCodeInPage({code:n.code,fragment:n.fragment??!1,context:o.toObjectCopy(),timeoutMs:n.timeout?n.timeout*1e3:void 0}),a.info({result:g},"Executed JavaScript in browser")):g=await ur({orgId:this.orgId,code:n.code,fragment:!!n.fragment,context:o,timeoutMs:n.timeout?n.timeout*1e3:void 0,logger:a,localTools:this.localCodeEvalTools,signal:this.executeAbortController.signal,callbacks:{onPersistentVariableUpdates:async h=>{if(!this.options?.scratchPadId){a.warn({updates:h},"Got persistent variable updates but scratch pad is not available");return}await this.storage.savePersistentVariables?.({scratchPadId:this.options?.scratchPadId,orgId:this.orgId,updates:h,logger:a})}}})}catch(h){throw this.throwIfClosed(),new w("ActionFailureError",h instanceof Error?h.message:`${h}`,{errOptions:{cause:h}})}try{JSON.stringify(g)}catch(h){throw new w("ActionFailureError",`Return value is not serializable: ${h instanceof Error?h.message:`${h}`}`,{errOptions:{cause:h}})}return{urlAfterCommand:this.browser.url(),succeedImmediately:!1,data:g}}case"TYPE":{if(n.target&&nr(n.target)){await this.browser.clickUsingVisualCoordinates(n.target.pixels,n),await this.browser.type(n.value,{force:n.force,clearContent:n.clearContent,forceClearContent:n.forceClearContent,delay:n.delay,pressEnter:n.pressEnter},!0);break}let g=this.browser.url(),h,f,E=fv(n.target);if(E){let{elementInteractedDisplayString:v,thoughts:A}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:E,cache:n.cache?.target,action:T=>this.browser.typeIntoTarget(n.value,T,{force:n.force,clearContent:n.clearContent,forceClearContent:n.forceClearContent,delay:n.delay,pressEnter:n.pressEnter}),options:{...n,targetName:"target",disableCache:i,disableGlobalLocatorRedirect:!0,source:gi(n)}});h=v,f=A}else await this.browser.type(n.value,{force:n.force,clearContent:n.clearContent,forceClearContent:n.forceClearContent,delay:n.delay,pressEnter:n.pressEnter},!0);let b={urlAfterCommand:this.browser.url(),succeedImmediately:!1,elementInteracted:h,thoughts:f};return Cs(g,b.urlAfterCommand)&&(b.succeedImmediately=!0,b.succeedImmediatelyReason="URL changed"),b}case"HOVER":{if(nr(n.target)){await this.browser.hoverUsingVisualCoordinates(n.target.pixels);break}let{elementInteractedDisplayString:g,thoughts:h}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:n.target,cache:n.cache?.target,action:f=>this.browser.hover(f),options:{...n,targetName:"target",disableCache:i}});return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:g,thoughts:h}}case"FOCUS":{if(!Nr(n.target))throw new Error("Focus with x/y is not supported yet");let{elementInteractedDisplayString:g,thoughts:h}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:n.target,cache:n.cache?.target,action:f=>this.browser.focus(f),options:{...n,targetName:"target",disableCache:i}});return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:g,thoughts:h}}case"BLUR":{if(n.target&&!Nr(n.target))throw new Error("Blur with x/y is not supported yet");if(!n.target||!n.target.elementDescriptor)return await this.browser.blur(null),{succeedImmediately:!1,urlAfterCommand:this.browser.url()};let{elementInteractedDisplayString:g,thoughts:h}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,target:n.target,command:n,cache:n.cache?.target,action:f=>this.browser.blur(f),options:{...n,targetName:"target",disableCache:i}});return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:g,thoughts:h}}case"PRESS":let d=this.browser.url();await this.browser.press(n.value,{repeat:n.repeat,convertMeta:n.convertMeta??!0,delayMs:n.delayMs});let p={urlAfterCommand:this.browser.url(),succeedImmediately:!1};return Cs(d,p.urlAfterCommand)&&(p.succeedImmediately=!0,p.succeedImmediatelyReason="URL changed"),p;case"KEY_DOWN":return await this.browser.keyDown(n.value,{convertMeta:n.convertMeta??!0}),{urlAfterCommand:this.browser.url(),succeedImmediately:!1};case"KEY_UP":return await this.browser.keyUp(n.value,{convertMeta:n.convertMeta??!0}),{urlAfterCommand:this.browser.url(),succeedImmediately:!1};case"REQUEST":{let g=new yD,h=SD(fetch,g),f;try{f=new URL(n.url).hostname}catch{}return{data:{...await dv({command:n,baseUrl:this.browser.baseUrl,logger:a,fetchImplementation:h}),cookies:jg(g,f)},succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"GRAPHQL_REQUEST":return{data:await hv({command:n,baseUrl:this.browser.baseUrl,logger:a}),succeedImmediately:!1,urlAfterCommand:this.browser.url()};case"VISUAL_DIFF":return uv({ctx:e,tracer:t,command:n,disableCache:i,browser:this.browser,logger:a,storage:this.storage,screenshotStorage:this.visualDiffScreenshotStorage,targetingWrapper:g=>this.wrapElementTargetingCommand(g)});case"FILE_UPLOAD":{let g,h;if(n.fileSource.type==="URL"?(h=n.fileSource.url,g=await Gb({uri:n.fileSource.url,logger:a,orgId:this.orgId})):n.fileSource.type==="USER_FILE"&&(h=n.fileSource.name,g=await this.uploadedFileStorage?.getFileForUpload(n.fileSource.name,this.orgId)),!g)throw new w("UserConfigurationError",`Attempted to use non-existent file for upload step: ${h}`);await this.browser.setFileChooserHandler({...g,filename:n.filename});break}case"AUTH_SAVE":return{data:await this.browser.saveAuthState(),succeedImmediately:!1,urlAfterCommand:this.browser.url()};case"AUTH_LOAD":{let g;if(!n.storageState.trim())g=void 0;else if(g=await ur({orgId:this.orgId,code:n.storageState,fragment:!1,context:o,logger:a,localTools:this.localCodeEvalTools,signal:this.executeAbortController.signal}),typeof g!="object")throw new w("ActionFailureError",`Credentials must evaluate to an object (received ${typeof g} instead)`);let h;try{h=Vg.optional().parse(g)}catch(f){throw new w("ActionFailureError",`Credentials provided do not follow the required format: ${f}`)}await this.browser.loadAuthState(h);break}case"ELEMENT_CHECK":{let g=(n.timeout??kr)*1e3,h=this.generator.getAgentConfig()?.assertion;if(lv(n.assertion)&&!n.useSelector&&n.target.type==="description"&&h&&h!=="v1"){let E={id:n.id,type:"AI_ASSERTION",assertion:`There is no element on the page closely matches the following description. If the description has single quotes, remember that requires an exact text substring match. Description: ${n.target.elementDescriptor}`,iframeUrl:n.iframeUrl,timeout:n.timeout,cache:n.cache&&"memory"in n.cache?{memory:n.cache?.memory}:void 0};try{let b=await kl({command:E,logger:a,aiPageFiltering:!!this.options?.aiPageFiltering,fixtures:this.getControllerFixtures(e),useMemory:this.shouldUseMemory(),source:"NEGATED_CHECK"});return{succeedImmediately:!1,thoughts:`The element described does not exist on the page: ${b.thoughts}`,urlAfterCommand:this.browser.url(),afterScreenshotOverride:b.afterScreenshotOverride}}finally{E.cache?.memory&&bs(n,E.cache?.memory.traces,a)}}let f=await sv({command:n,tracer:t,timeoutMs:g,targetingWrapper:E=>this.wrapElementTargetingCommand(E),fixtures:this.getControllerFixtures(e),disableCache:i});return{fail:!f.success,data:f.data,elementInteracted:f.elementInteractedDisplayString,thoughts:f.err?.message??f.thoughts??`Element assertion ${f.success?"succeeded":"failed"}.`,succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"PAGE_CHECK":{let g=await Er({action:async()=>gv({assertion:n.assertion,browser:this.browser,logger:a,timeout:n.timeout,signal:this.executeAbortController.signal,autoExpandIframes:!!this.browser.userBrowserSettings.autoExpandIframes}),frameConfig:n.iframeUrl?{type:"url",url:n.iframeUrl}:void 0,browser:this.browser,logger:a});return{fail:!g.success,data:g.data,thoughts:g.success?"Page assertion passed.":g.err?.message??`Page assertion still failing after ${n.timeout} seconds.`,urlAfterCommand:this.browser.url(),succeedImmediately:!1}}case"REGISTER_REQUEST_LISTENER":{let g=new rn(n.requestMatcher),h=this.browser.registerRequestListener(g);return this.registeredListeners[n.key]=h.then(async f=>await pp(f)).catch(f=>{a.error({err:f},"Failed to get request listener response")}),{succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"AWAIT_LISTENER":{let g=this.registeredListeners[n.key];if(!g)throw new w("ActionFailureError",`No listener registered with key: ${n.key}`);let h=n.timeout??10;return{data:await B(g,{milliseconds:h*1e3,message:`Request listener timed out after ${h} seconds`}),succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"RECORD_REQUESTS":{let g=new rn(n.requestMatcher);return this.recordedRequests[n.key]={},this.browser.registerRequestRecorder(n.key,g,{onRequestStart:(h,f)=>{this.recordedRequests[n.key][h]=_l(f)},onRequestComplete:(h,f)=>{this.recordedRequests[n.key][h]=_l(f)}}),{succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"GET_RECORDED_REQUESTS":{let g=this.recordedRequests[n.key];if(!g)throw new w("ActionFailureError",`No recorder registered with key: ${n.key}`);return delete this.recordedRequests[n.key],{data:Object.values(g),succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"SET_HEADER":{let g;return n.requestMatcher&&(g=new rn(n.requestMatcher)),this.browser.setHeader(n.name,n.value,g),{succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"MOCK_ROUTE":return{data:{key:this.browser.registerMock(n.key,new rn(n.requestMatcher),async(h,f)=>{let E=await ur({orgId:this.orgId,code:n.responseGenerator,fragment:!1,context:o,timeoutMs:void 0,logger:a,localTools:this.localCodeEvalTools,mock:{request:h,response:f},disallowVariableUpdates:!0,responseSerialization:"RESPONSE"}),b=oh.parse(E);return new Response(b.body,{status:b.status,headers:b.headers})},n.fetchOriginalResponse??!1)},succeedImmediately:!1,urlAfterCommand:this.browser.url()};case"REMOVE_ROUTE_MOCK":return this.browser.removeMock(n.key),{succeedImmediately:!1,urlAfterCommand:this.browser.url()};case"OFFLINE_MODE":return await this.browser.setOfflineMode(n.enable),{succeedImmediately:!1,urlAfterCommand:this.browser.url()};default:return(g=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(n)}return{succeedImmediately:!1,urlAfterCommand:this.browser.url()}}async getReverseMappedDescription({browserState:e,targetId:t,disableCache:n,screenshot:o}){return(await this.generator.getReverseMappedDescription({browserState:e,target:t,screenshot:o},{disableCache:n,abortSignal:this.executeAbortController.signal,loggerTags:pe(this.logger)})).phrase}async stopRecordMode(){this.recordAbortController?.abort(),await this.browser.clearAllCdpHighlights()}async startRecordMode({params:e,abortController:t,isClickToRecord:n}){this.recordAbortController=t;let o=new Il({signal:t.signal,...e});return await this.browser.startRecording(this.recordAbortController.signal,o,n),o}async runSectionAutohealing(e){return this.generator.getAutohealingProposal(e,{disableCache:!0,abortSignal:this.executeAbortController.signal,loggerTags:pe(this.logger)})}async getFailureRecoveryPlan(e){return this.generator.getFailureRecoveryPlan(e,{disableCache:!0,abortSignal:this.executeAbortController.signal,loggerTags:pe(this.logger)})}};import{z as De}from"zod";var Sv=De.array(De.object({proc:De.string(),webview:De.string(),info:De.object({"Android-Package":De.string(),Browser:De.string(),"Protocol-Version":De.string(),"User-Agent":De.string(),"V8-Version":De.string(),"WebKit-Version":De.string(),webSocketDebuggerUrl:De.string()}),pages:De.array(De.object({description:De.string(),devtoolsFrontendUrl:De.string(),id:De.string(),title:De.string(),type:De.string(),url:De.string(),webSocketDebuggerUrl:De.string()})),webviewName:De.string()}));var Bl=class r{driver;device;currentContext;logger;webviews=new Map;fixtures;orgId;options;aborter;constructor({driver:e,context:t,logger:n,device:o,fixtures:i,orgId:a,options:l,aborter:c}){this.driver=e,this.device=o,this.currentContext=t,this.logger=n,this.fixtures=i,this.orgId=a,this.options=l,this.aborter=c;for(let s of["SIGINT","SIGTERM"])process.on(s,async()=>{await this.cleanupWebviews()})}static async init({driver:e,logger:t,fixtures:n,orgId:o,adbPort:i,options:a,aborter:l}){let c=await e.getContext(),s=typeof c=="string"?c:c.id,u=(await bD.devices()).filter(m=>m._initializer?.serial?.endsWith(i.toString()));if(u.length!==1)throw new Error(`Playwright detected ${u.length} Android devices, expected 1. Please stop all other emulators and try again.`);let d=u[0];return new r({driver:e,context:s,logger:t,device:d,fixtures:n,orgId:o,options:a,aborter:l})}async getContexts(){let e=await this.driver.getContexts({}),t=Array.from(this.webviews.values());return{contexts:e,webviews:t.map(n=>({contextId:n.contextId,packageName:n.packageName,active:n.active,hasPlaywright:!!n.browserController,lastSeen:n.lastSeen,socketName:n.socketName}))}}async getCurrentScreenshot(){return`data:image/png;base64,${await this.driver.takeScreenshot()}`}async waitForScreenshotStability({timeoutMs:e,signal:t,reason:n,tracer:o}){await o.startAsyncSpan("WAIT_FOR_STABILITY",async()=>{let i=Date.now(),a,l=!1;for(;Date.now()-i<e;){if(t?.throwIfAborted(),!a){a=await this.getCurrentScreenshot();continue}if(await this.getCurrentScreenshot()===a){l=!0;break}await $(250,t)}l||this.logger.warn({reason:n},"Timed out waiting for screenshot stability")})}async getDomState(e){let t;if(e?.includeWebviews)try{let i=await this.getActiveWebview();i&&i.browserController&&(t=(await i.browserController.getBrowserState({abortSignal:this.aborter.controller?.signal})).serializedTree)}catch(i){this.logger.error({err:i},"Could not get webview info to get the nested DOM state")}this.throwIfAborted();let n=await this.driver.getPageSource();return this.throwIfAborted(),{graph:await _b(n,{injectedWebviewContent:t,disallowAccessibilityBridgeForWebviews:this.options.disableDefaultWebviewAccessibilityTree}),context:this.currentContext}}async refreshWebviews(){await this.driver.getPageSource(),this.throwIfAborted();let e=await this.getDetailedContexts();if(!e){this.logger.warn("No context details, not proceeding with refreshing webviews");return}let t=Date.now(),n=new Set;for(let o of e){if(this.throwIfAborted(),o.webview==="NATIVE_APP")continue;let i=o.info["Android-Package"];if(n.add(o.webview),!this.webviews.has(o.webview)||!this.webviews.get(o.webview)?.active){let a={contextId:o.webview,packageName:i,active:!1,lastSeen:t,socketName:o.proc.startsWith("@")?o.proc.substring(1):o.proc};this.logger.info({contextId:a.contextId,packageName:a.packageName,socketName:a.socketName},"New webview detected"),this.webviews.set(o.webview,a);let l;if(i==="com.android.chrome"?(l=await this.connectPlaywrightToChrome(a),this.logger.info(`Connected Playwright to Android Chrome: ${o.webview}`)):(this.logger.info(`Attempting to connect Playwright to webview: ${o.webview}`),l=await this.connectPlaywrightToWebview(i,a.socketName),this.logger.info(`Connected Playwright to webview ${o.webview}`)),!l)continue;a.browserController=l,a.active=!0}}for(let[o,i]of this.webviews.entries())!n.has(o)&&i.active&&(this.logger.info(`Disconnecting dead webview ${o}`),this.disconnectPlaywrightFromWebview(i),i.active=!1)}async getActiveWebview(){await this.refreshWebviews();let e=await this.driver.getCurrentPackage(),t=[];for(let n of this.webviews.values())n.packageName===e&&n.active&&t.push(n);if(t.length!==0){if(t.length>1)throw new Error("Multiple active webviews in a single package is currently not supported");return t[0]}}async executeRawADBCommand(e){let t=this.driver.capabilities,n=t.deviceUDID||t.udid||t["appium:udid"]||t["appium:deviceUDID"],o=process.env.ANDROID_HOME?`${process.env.ANDROID_HOME}/platform-tools/adb`:"adb",i=n?`-s ${n}`:"",a=`${o} ${i} ${e}`;this.logger.info(`Executing ADB command: ${a}`);let l=yv(a,{encoding:"utf8"});return this.logger.info(`ADB command result: ${l}`),l}async cleanupWebviews(){for(let[e,t]of this.webviews.entries())this.logger.info(`Disconnecting webview ${e}`),this.disconnectPlaywrightFromWebview(t),t.active=!1}async getDetailedContexts(){let e=await this.driver.execute("mobile: getContexts");return this.aborter.controller?.signal.throwIfAborted(),Sv.parse(e)}async createBrowserController({context:e}){let t=await aa.fromExistingContext({context:e,logger:this.logger,userBrowserSettings:{visualActions:!0},storage:this.fixtures.storage,enricher:this.fixtures.browserEnricher});await t.getActivePage().waitForLoadState();let n=await t.getBrowserState({skipWait:!0,skipWaitForPageLoad:!0});return new Fl({browser:t,generator:this.fixtures.browserGenerator,logger:this.logger,orgId:this.orgId,storage:this.fixtures.storage,localCodeEvalTools:this.fixtures.localCodeEvalTools,visualDiffScreenshotStorage:new hs})}async connectPlaywrightToWebview(e,t){let o=this.device.webViews().find(a=>!(a.pkg()!==e||"_socketName"in a&&typeof a._socketName=="string"&&a._socketName!==t));if(!o){this.logger.warn(`[WebviewManager] Could not find webview for ${e} with socket name ${t}`);return}return this.logger.info({packageName:e,socketName:t},"Connecting Playwright to app webview"),await this.createBrowserController({context:(await o.page()).context()})}async connectPlaywrightToChrome(e){let{contextId:t,socketName:n}=e;try{this.logger.info({contextId:t,socketName:n},"Connecting to Chrome webview");let o;e.forwardedPort?(o=`http://127.0.0.1:${e.forwardedPort}`,this.logger.info({contextId:t,endpoint:o,socketName:n},"Using existing forwarded port")):(o=`http://127.0.0.1:${await this.forwardDevToolsSocket(e.socketName)}`,this.logger.info({contextId:t,endpoint:o,socketName:n},`Forwarding DevTools socket for ${e.socketName}`)),this.logger.info({endpoint:o,socketName:n},"Connecting to CDP endpoint");let i=await TD.connectOverCDP({endpointURL:o,timeout:12e3}),a=i.contexts()[0];if(!a){this.logger.warn("No browser context available after CDP connection"),await i.close();return}return this.createBrowserController({context:a})}catch(o){this.logger.error({err:o},`Error connecting Playwright to webview ${e.contextId}`);return}}async disconnectPlaywrightFromWebview(e){try{e.browserController&&(this.logger.info(`Disconnecting Playwright from webview: ${e.contextId}`),await e.browserController.browser.cleanup(),e.browserController=void 0),e.forwardedPort&&await this.removeDevToolsForwarding(e.forwardedPort)}catch(t){this.logger.error({err:t},`Error disconnecting Playwright from webview ${e.contextId}:`)}}async forwardDevToolsSocket(e){this.logger.info("Setting up port forwarding for DevTools");let t=1e4+Math.floor(Math.random()*1e4),n=this.driver.capabilities,o=n.deviceUDID||n.udid||n["appium:udid"]||n["appium:deviceUDID"];this.logger.info({deviceId:o},`Device ID from capabilities: ${o||"not found"}`);let i=process.env.ANDROID_HOME?`${process.env.ANDROID_HOME}/platform-tools/adb`:"adb",a=o?`-s ${o}`:"",l=`${i} ${a} forward tcp:${t} ${`localabstract:${e}`||"localabstract:chrome_devtools_remote"}`;this.logger.info(`Executing command: ${l}`);let c=yv(l,{encoding:"utf8"});return this.logger.info(`ADB command result: ${c}`),this.logger.info(`Successfully forwarded DevTools socket to port ${t}`),t}async removeDevToolsForwarding(e){await this.executeRawADBCommand(`forward --remove tcp:${e}`),this.logger.info("Successfully removed port forwarding")}throwIfAborted(){this.aborter.controller?.signal.throwIfAborted()}};var Fo=class r extends Lo{options;appsWithGrantedPermissions=new Set;adbPort;constructor(e){super(e),this.options=e.options??{},this.adbPort=e.adbPort}static async init({driver:e,generator:t,logger:n,fixtures:o,orgId:i,options:a,abortController:l,adbPort:c}){let s={controller:l},u=await Bl.init({driver:e,logger:n,fixtures:o,orgId:i,options:a?.emulator??{},aborter:s,adbPort:c}),d=new r({driver:e,generator:t,stateManager:u,logger:n,fixtures:o,options:a,aborter:s,orgId:i,adbPort:c});return await d.initializeSettings(),d}async installApp(e){await this.stateManager.executeRawADBCommand(`install ${AD.resolve(e)}`)}async executeCommand(e){let t=["type","a11yData","thoughts","cache","code"],n;try{n=await Ss({obj:e.command,context:this.fixtures.testContext,bannedKeys:t,orgId:this.orgId,logger:this.logger,signal:this.aborter.controller?.signal,localTools:this.fixtures.localCodeEvalTools})}catch(o){throw this.throwIfAborted(),new Error(`ActionFailureError: Failed to substitute template strings in command: ${o.message}`,{cause:o})}try{return await this.executeCommandHelper(e)}catch(o){throw o.name!=="AbortError"&&this.logger.error({err:o},"Error thrown in action controller"),o}finally{ys(e.command,n)}}async executeCommandHelper({command:e,tracer:t}){switch(e.type){case"STATE":{await this.stateManager.refreshWebviews();let n=await this.stateManager.getDomState(),o=await this.stateManager.getContexts();return{output:{xml:n.graph.xml,contexts:o},success:!0}}case"TAP":return new Tl(this.constructPerformerParams()).executeTap({command:e,tracer:t});case"TYPE":{let n;if(e.target){let o={type:"TAP",id:vD(),target:e.target,cache:e.cache,longPress:e.clearContent};try{n=(await this.executeCommand({command:o,tracer:t})).message}finally{e.cache=o.cache}}if(await this.stateManager.waitForScreenshotStability({timeoutMs:2e3,signal:this.aborter.controller?.signal,tracer:t,reason:"Waiting for keyboard to appear before typing"}),e.clearContent)try{let o=await this.driver.$('//android.widget.LinearLayout[@package="app.lawnchair" and @content-desc="Select all" and @clickable="true"]');await o.waitForExist({timeout:750}),await o.click(),await this.driver.pressKeyCode(67)}catch(o){throw new Error(`Failed to clear content because the select all button was not found: ${o}`)}if(e.keyPressDelayMs)for(let o of e.text)await this.driver.keys(o),await $(e.keyPressDelayMs);else await this.driver.keys(e.text);return{success:!0,message:n}}case"AI_CHECK":{let o=e.timeoutSecs?e.timeoutSecs*1e3:5e3,i=Rs(o),a=Date.now(),l=0,c,s=!1,u;for(;l<15&&!s;){this.throwIfAborted(),s||c&&c-a>=o&&(s=!0),l!==0&&await $(i,this.aborter.controller?.signal),c=Date.now();try{let d="",p="";await t.startAsyncSpan("GET_EMULATOR_STATE",async()=>{d=(await this.stateManager.getDomState({includeWebviews:!0})).graph.xml,p=await this.stateManager.getCurrentScreenshot()});let m=await t.startAsyncSpan("AI_ASSERTION_CALL",async g=>{let h=await this.generator.evaluateAssertion({assertion:e.assertion,screenXml:d,screenshot:p},{logger:this.logger,loggerTags:pe(this.logger)});return g.result={thoughts:h.thoughts,result:h.result},h});if(m.result)return{success:m.result,message:m.thoughts};{let g=`AssertionFailureError: ${m.thoughts}`;u=new Error(g)}}catch(d){this.throwIfAborted(),this.logger.info({err:d},`AI check assert attempt ${l} failed, retrying...`),u=d instanceof Error?d:new Error(`${d}`)}finally{l++}}return{success:!1,message:u?.message}}case"JAVASCRIPT":{let n=await ur({orgId:this.orgId,code:e.code,fragment:!1,context:this.fixtures.testContext,timeoutMs:e.timeout?e.timeout*1e3:void 0,logger:this.logger,localTools:this.fixtures.localCodeEvalTools,signal:this.aborter.controller?.signal});try{JSON.stringify(n)}catch(o){throw new Error(`UserConfigurationError: Return value is not serializable: ${o instanceof Error?o.message:`${o}`}`)}return{success:!0,output:n}}case"OPEN_NOTIFICATION_DRAWER":return await this.driver.pressKeyCode(83),{success:!0};case"OPEN_APP":{let n=e.activityName;if(!n){let o=await B(this.driver.execute("mobile: shell",{command:"pm",args:["resolve-activity","--brief","-a","android.intent.action.MAIN","-c","android.intent.category.LAUNCHER",e.packageName]}),{signal:this.aborter.controller?.signal,milliseconds:1e4});if(typeof o!="string")throw new Error(`Could not find main activity name for package ${e.packageName}. Unexpected output: ${o}`);if(o.includes("No activity found"))throw new Error(`No activity found for package ${e.packageName}.`);if(n=o.trim().split(`
3961
+ `).pop()?.replace(/^.*\//,""),!n)throw new Error(`Could not parse main activity name for package ${e.packageName}. Raw output: ${o}`)}if(this.options.emulator?.autoGrantPermissions&&!this.appsWithGrantedPermissions.has(e.packageName)){let o={permissions:"all",appPackage:e.packageName,action:"grant"};await this.driver.executeScript("mobile: changePermissions",[o]),this.appsWithGrantedPermissions.add(e.packageName)}return await this.driver.execute("mobile: shell",{command:"am",args:["start","-n",`${e.packageName}/${n}`]}),await this.stateManager.waitForScreenshotStability({timeoutMs:5e3,signal:this.aborter.controller?.signal,tracer:t,reason:"Waiting for stability after app launch"}),{success:!0}}case"PRESS":{let n=o=>e.longPress?this.driver.longPressKeyCode(o):this.driver.pressKeyCode(o);switch(e.key){case"HOME":await n(3);break;case"BACK":await n(4);break;case"APP_SWITCHER":await n(187);break;case"POWER":await n(26);break;case"SEARCH":await n(84);break;case"VOLUME_UP":await n(24);break;case"VOLUME_DOWN":await n(25);break;case"VOLUME_MUTE":await n(164);break}return{success:!0}}case"ADB":return{success:!0,output:await this.driver.execute("mobile: shell",{command:e.command}),message:"ADB command executed successfully"};case"PRESS_KEYBOARD":{switch(e.key){case"CLOSE_KEYBOARD":await this.driver.isKeyboardShown()&&await this.driver.hideKeyboard();break;case"ENTER":await this.driver.pressKeyCode(66);break;case"BACKSPACE":await this.driver.pressKeyCode(67);break;default:{let n=e}}return{success:!0}}default:{let n=e;return{success:!0}}}}async initializeSettings(){}constructPerformerParams(){return{stateManager:this.stateManager,generator:this.generator,driver:this.driver,logger:this.logger,fixtures:this.fixtures,aborter:this.aborter,orgId:this.orgId}}async screenshot(){return this.driver.takeScreenshot()}resetAbortController(e){this.aborter.controller=e??new AbortController}isAborted(){return this.aborter.controller?.signal.aborted}abort(){this.aborter.controller?.abort()}get context(){return this.fixtures.testContext}get localCodeEvalTools(){return this.fixtures.localCodeEvalTools}};async function Ev({socket:r,logger:e,androidDriverFactory:t,getOrgId:n,mobileGeneratorFactory:o,browserGeneratorFactory:i,browserEnricherFactory:a,storageFactory:l,localToolsFactory:c,globalStateManager:s,settingsFactory:u}){let d=r.id,p=r.handshake.query?.testMetadata,m=r.handshake.query?.fileName,g=m?.endsWith("test.yaml")?m.slice(0,-"test.yaml".length):m,h=ar.parse(JSON.parse(p??"")),f=h.id,E=h.settings?.defaultChannel,b=h.settings?.defaultTag,v=await n({testId:f});e=e.child({sessionId:d,testId:f,orgId:v});let T={...(await u(v,e)).emulator,...h.settings?.emulator},x=Date.now(),{driver:N,cleanup:U,limbarToken:Y,limbarUrl:ke,emulatorName:te,adbTunnelPort:ie}=await t({socket:r,logger:e,creationOpts:{region:T.region,apkToInstall:E?{channel:E,tag:b}:void 0}});e.info({adbTunnelPort:ie,apkChannel:E,apkTag:b,duration:Date.now()-x,emulatorName:te},"Android emulator session initiated"),e=e.child({emulator:te});let ut=await o(v,e),M=await i(v,e),V=await a(v,e),re=await l(v),Ce=c?await c(v):void 0,Me={};h.settings?.defaultEnv&&(Me=(await re.fetchEnvironment(h.settings?.defaultEnv,e))?.variables??{});let Ae=new co({variablesFromEnvironment:Me,envName:h.settings?.defaultEnv,testName:g}),xt=await Fo.init({driver:N,generator:ut,logger:e,options:{emulator:T},fixtures:{storage:re,browserEnricher:V,browserGenerator:M,localCodeEvalTools:Ce,testContext:Ae},orgId:v,adbPort:ie,abortController:new AbortController});if(!r.connected)throw await U(),new Error("Socket not connected anymore, not proceeding with Android session setup");let dt=RD({socket:r,testContext:Ae}),Re=async()=>{clearInterval(dt);try{await U()}catch(We){e.warn({err:We},"Failed to clean up emulator in socket server")}};return s.registerSession(d,{controller:xt,cleanup:Re,emulatorName:te}),r.emit("session",{testId:f,sessionId:d,limbarUrl:ke,limbarToken:Y}),{sessionId:d,testId:f,orgId:v,emulatorName:te,logger:e}}function RD({socket:r,testContext:e}){return setInterval(()=>{let t=e.toEditorDisplayCopy();r.emit("emulatorState",{context:t})},3e3)}async function bv({socket:r,logger:e,globalStateManager:t}){await t.removeSession(r.id,e)}var wD=({socket:r,globalStateManager:e})=>async()=>{let t=e.getSession(r.id);if(!t)throw new Error("No active Android session found");t.controller.abort()},Tv={event:"cancel",createHandler:wD};import{diff as VD}from"deep-object-diff";import{cloneDeep as jD}from"lodash-es";import Age,{multistream as wge}from"pino";import xge from"pino-pretty";import CD from"fetch-retry";import xD from"os";import vv,{multistream as _D}from"pino";import MD from"pino-pretty";import ID from"pino-std-serializers";var zo=new Map,PD=!0,Av="Log throttle exceeded",OD=100,LD=5e3,ND=CD(global.fetch,{retries:2,retryOn:function(r,e,t){return!!(e!==null||t&&t.status>=500)},retryDelay:function(r){return Math.pow(2,r)*500}}),vp=class r{consoleLogger;hostname;bindingAttributes;disableConsoleLogs;minLevelValue=20;logsInCurrentWindow=0;droppedLogsInWindow=!1;lastWindowStart=Date.now();site="https://ingest.us.signoz.cloud:443/logs/json";flushIntervalMs;maxBatchSize;buffer=[];flushTimer;constructor({bindings:e,hostname:t,disableConsoleLogs:n,flushIntervalMs:o,maxBatchSize:i}){this.hostname=t??xD.hostname(),this.disableConsoleLogs=n,this.bindingAttributes={...e,env:"production"},this.flushIntervalMs=o??5e3,this.maxBatchSize=i??10;let a={base:this.bindingAttributes,errorKey:"err",level:"debug"};this.consoleLogger=PD?vv(a):vv(a,_D([{stream:MD({colorize:!0})}]))}getLevel(){return ps[this.minLevelValue]}child(e){return new r({bindings:{...this.bindingAttributes,...e},hostname:this.hostname,disableConsoleLogs:this.disableConsoleLogs,flushIntervalMs:this.flushIntervalMs,maxBatchSize:this.maxBatchSize})}flush(e){this.flushBuffer(),this.disableConsoleLogs||this.consoleLogger.flush(e)}scheduleFlush(){this.flushTimer||(this.flushTimer=setTimeout(()=>{this.flushTimer=void 0,this.flushBuffer()},this.flushIntervalMs))}async flushBuffer(){if(this.buffer.length===0)return;let e=this.buffer;this.buffer=[];try{let t=await ND(this.site,{method:"POST",headers:{"Content-Type":"application/json","signoz-access-token":"CumAaTMUcwjt05OddAmefKgshbhfRmWxzxih"},body:$r(e),signal:AbortSignal.timeout(5e3)});if(!t.ok)throw new Error(`Got error status (${t.statusText}) from SigNoz`)}catch(t){this.consoleLogger.warn({err:t},"Failed to log to SigNoz")}}shouldAllowLog(e){if(e===Av)return!0;let t=Date.now();return t-this.lastWindowStart>LD&&(this.logsInCurrentWindow=0,this.droppedLogsInWindow&&this.log("error",void 0,Av),this.droppedLogsInWindow=!1,this.lastWindowStart=t),this.logsInCurrentWindow<OD?(this.logsInCurrentWindow++,!0):(this.droppedLogsInWindow=!0,!1)}log(e,t,n,...o){try{this.logHelper(e,t,n,...o)}catch(i){this.consoleLogger.warn(`Failed to log to Signoz: ${i}`)}}logHelper(e,t,n,...o){if(Ii[e]<this.minLevelValue||!this.shouldAllowLog(n))return;typeof t=="string"&&!n&&(t={message:t}),typeof t=="object"&&t&&"err"in t&&t.err instanceof Error&&(t.err=ID.err(t.err));let i={...this.bindingAttributes,...t&&typeof t=="object"?t:{},...o.length>0?{args:o}:{}},a={host:this.hostname,env:this.bindingAttributes.env};this.disableConsoleLogs||this.consoleLogger[e](i,n,...o);let l={timestamp:Math.round(Date.now()*1e6),severity_text:e.toUpperCase(),resources:a,attributes:{},body:Rh({message:n||"",...i})};this.buffer.push(l),this.buffer.length>=this.maxBatchSize?(this.flushTimer&&(clearTimeout(this.flushTimer),this.flushTimer=void 0),this.flushBuffer()):this.scheduleFlush()}setApp(e){let t=this.bindingAttributes.app;this.bindingAttributes.app=e,zo.set("app",this),zo.delete(t)}debug(e,t,...n){this.log("debug",e,t,...n)}info(e,t,...n){this.log("info",e,t,...n)}warn(e,t,...n){this.log("warn",e,t,...n)}error(e,t,...n){this.log("error",e,t,...n)}bindings(){return this.bindingAttributes}addBinding(e,t){this.bindingAttributes[e]=t}setMinLevel(e){typeof e=="number"?(this.minLevelValue=e,this.consoleLogger.level=ps[e]):(this.minLevelValue=Ii[e],this.consoleLogger.level=e)}enableConsoleLogs(){this.disableConsoleLogs=!1}},zl=({app:r,hostname:e,disableConsoleLogs:t})=>(zo.has(r)||zo.set(r,new vp({bindings:{app:r},hostname:e,disableConsoleLogs:t})),zo.get(r));function Rv(){for(let r of zo.values())r.flush()}import{PostHog as Vge}from"posthog-node";import{PostHog as Qge}from"posthog-node";import la from"os";import DD from"v8";var wv,br,kD=la.platform(),UD=la.cpus().map(r=>({model:r.model,speed:r.speed})).reduce((r,e)=>(r[e.model]={speed:e.speed},r.totalCores=(r.totalCores??0)+1,r),{});function Cv(r){if(En)return;let e=()=>{try{let t=!1,n=FD(),o=BD();n.freeMemory<1e6&&(t=!0),o&&o?.total>70&&(t=!0);let i=DD.getHeapStatistics(),a=i.used_heap_size,l=i.heap_size_limit;a/l>.9&&(t=!0),t?r.warn({memory:n,cpu:o,heapStats:i},"Critical resource usage metrics detected"):r.debug({memory:n,cpu:o},"Got machine resource usage metrics")}catch{}};return e(),{interval:setInterval(e,2e4),cpuMetadata:UD,platform:kD}}function FD(){let r=la.totalmem(),e=la.freemem(),t=r-e;return{totalMemory:r,freeMemory:e,usedMemory:t}}function BD(){let r=la.cpus(),e=Date.now(),t={measurementTime:e,user:0,nice:0,sys:0,idle:0,irq:0,total:0};for(let o of r)t.user+=o.times.user,t.nice+=o.times.nice,t.sys+=o.times.sys,t.idle+=o.times.idle,t.irq+=o.times.irq;if(t.total=t.user+t.nice+t.sys+t.idle+t.irq,!br)return br=t,null;let n={user:t.user-br.user,nice:t.nice-br.nice,sys:t.sys-br.sys,idle:t.idle-br.idle,irq:t.irq-br.irq,total:t.total-br.total};return wv={measurementTime:e,intervalMs:e-br.measurementTime,user:n.user/n.total*100,nice:n.nice/n.total*100,sys:n.sys/n.total*100,idle:n.idle/n.total*100,irq:n.irq/n.total*100,total:100-n.idle/n.total*100},br=t,wv}function xv(r,e,t=1e4,n=5e3){let o=0;async function i(){try{let l=await B(r.driver.execute("mobile: shell",{command:"echo",args:["ping"]}).catch(c=>{throw c}),{milliseconds:n});if(typeof l=="string"&&l.trim()==="ping")o>0&&e.info("Driver heartbeat restored"),o=0;else throw new Error(`Unexpected heartbeat output: ${l}`)}catch(l){o++;let c=l instanceof Error?l.message:`${l}`;e.error({attempt:o,error:c},"Driver heartbeat failed"),o>=3&&e.error("Driver appears unresponsive \u2014 possible ADB tunnel/emulator failure")}}let a=setInterval(()=>{i()},t);return i(),a}async function _v(r){let e=Date.now(),t=r.fixtures.controller;try{return await zD(r)}catch(n){let o=t.isAborted()||n instanceof DOMException&&n.name==="AbortError";return{...r.moduleParams.step,steps:[],type:"MOBILE_MODULE_STEP",startTime:e,endTime:Date.now(),status:o?"CANCELLED":"FAILED",message:o?"Step cancelled.":`${n}`}}}async function zD({moduleParams:r,...e}){let t=Date.now(),{step:n,stepTracer:o,executeMobileStepList:i}=r,a=await GD({step:n,params:e}),l={};Object.entries(a).forEach(([p,m])=>{l[p]=JSON.stringify(m)});let c={...n,type:"MOBILE_MODULE_STEP",inputs:l,startTime:t,steps:[],endTime:Date.now(),status:"SUCCESS"},s=await o.startSubSteps(),{status:u,results:d}=await i({...e,listParams:{steps:n.steps,containerName:`module ('${n.name}')`,tracer:s}});return c.steps=d,c.status=u,c.endTime=Date.now(),Xf({result:c,...Yf(d)}),c}async function GD({step:r,params:e}){let t={},{logger:n,controller:o}=e.fixtures;for(let i of r.parameters?.parameterNames??[]){let a=r.inputs?.[i]??r.parameters?.defaultParameters?.[i];if(!a){n.warn({k:i},"No value found for parameter in module");continue}t[i]=await ur({orgId:e.inputs.orgId,code:a,fragment:!0,logger:n,context:o.context,localTools:o.localCodeEvalTools})}return t}import{randomUUID as Mv}from"crypto";async function Iv({fixtures:r,step:e,inputs:t,stepTracer:n}){let o=Date.now(),{logger:i,controller:a}=r,l;if(!t.interactive)try{l=await a.screenshot()}catch(s){i.warn({err:s},"Failed to take before screenshot")}let c=n.startCommand();try{let s=await a.executeCommand({command:e.command,tracer:c}),u=c.getRootSpan(),d={...e,status:s.success?"SUCCESS":"FAILED",message:s.message,trace:u,startTime:o,endTime:Date.now(),data:s.output};if(!t.interactive){try{let p=Mv(),m=await a.screenshot();d.afterSnapshot=p,n.attachAfterScreenshot({logger:i,snapshotId:p,screenshot:Buffer.from(m,"base64")})}catch(p){i.warn({err:p},"Failed to take after screenshot")}if(l){let p=Mv();d.beforeSnapshot=p,n.attachBeforeScreenshot({logger:i,snapshotId:p,screenshot:Buffer.from(l,"base64")})}}return d}catch(s){let u=c.getRootSpan();return s instanceof Error&&s.name==="AbortError"||a.isAborted()?{...e,status:"CANCELLED",message:"Step cancelled.",startTime:o,endTime:Date.now(),trace:u}:(i.error({err:s},"Failed to execute preset step"),{...e,status:"FAILED",message:s instanceof Error?s.message:String(s),startTime:o,endTime:Date.now(),trace:u})}}async function Ap(r){let{fixtures:e,inputs:t,listParams:n}=r,{containerName:o,steps:i,tracer:a}=n,{logger:l,controller:c,usageTracker:s}=e,u=a.getParentStepIdChain(),d=[],p,m="SUCCESS",{fromStep:g,toStep:h}=t,f=!!g;for(let E=0;E<i.length;E++){let b=i[E];if(l.info({step:b},`Executing step ${E+1} of ${i.length} in ${o}: ${Hf(b)}`),b.skipped){l.debug("Step skipped");continue}if(f&&g){let T=JSON.stringify(u);if(b.id===g.fromStepId&&T===JSON.stringify(g.parentStepIdChain))f=!1;else if(!Kf({currentStep:b,currentParentChain:u,desiredStepId:g.fromStepId,desiredStepParentChain:g.parentStepIdChain}))continue}let v=await a.startStep({logger:l,step:b,attempt:1,parentStepIdChain:[]});s.trackStepExecution(b);let A=await HD({step:b,stepTracer:v,params:r});if(d.push(A),await v.finish({parentStepIdChain:[],result:A}),A.status!=="SUCCESS"){m=A.status,p=A;break}if(b.envKey&&c.context.setVariable(b.envKey,A.data),h){let T=JSON.stringify([]);if(b.id===h.toStepId&&T===JSON.stringify(h.parentStepIdChain))break}}return{results:d,status:m,terminalResult:p}}async function HD({step:r,stepTracer:e,params:t}){let{fixtures:n,inputs:o}=t,i;switch(r.type){case"MOBILE_PRESET_STEP":{i=await Iv({fixtures:n,inputs:o,step:r,stepTracer:e});break}case"RESOLVED_MOBILE_MODULE":{i=await _v({...t,moduleParams:{step:r,stepTracer:e,executeMobileStepList:Ap}});break}}return i}async function Gl(r){let{tracer:e,containerName:t}=r,{steps:n,testMetadata:o}=r.inputs,{cacheStorage:i,logger:a,controller:l}=r.fixtures;await i.resolveEntries({logger:a,testId:o.id,stepLists:{steps:n}});let c=jD(n);a.info({testMetadata:ar.parse(o)},"Starting mobile test");let s=await e.startMainStepList(),u=Cv(a),d=xv(l,a);a.info({cpu:u?.cpuMetadata,platform:u?.platform},`Starting execution of ${t}`);let{status:p,results:m}=await Ap({...r,listParams:{containerName:t,tracer:s,steps:c}});if(clearInterval(u?.interval),clearInterval(d),p==="SUCCESS"){let g=VD(c,n);if(g&&Object.keys(g).length>0){a.debug({diffs:g},"Saving mobile step cache entries post-success");let{cachesToSave:h}=await Rn({steps:c,cacheCreationParams:{orgId:r.inputs.orgId,testId:o.id}});await i.saveEntries({logger:a,testId:o.id,entries:h})}return{status:"PASSED",results:m}}return p==="CANCELLED"?{status:"CANCELLED",results:m}:{status:"FAILED",results:m}}var Rp=class{parentTracer=null;socket;step;commandTracer;constructor({step:e,socket:t,parentTracer:n}){this.socket=t,this.parentTracer=n,this.step=e,this.commandTracer=new fo("command")}attachBeforeScreenshot(){}attachAfterScreenshot(){}attachBeforeHtmlSnapshot(){}attachAfterHtmlSnapshot(){}async finish(e){switch(e.result.status){case"SUCCESS":this.socket.emit("success",e);break;case"FAILED":this.socket.emit("failure",e);break;case"CANCELLED":this.socket.emit("cancelled",e);break}return this.commandTracer.finish(),{trace:this.commandTracer.getRootSpan()}}startCommand(){return this.commandTracer}getParentStepIdChain(){return this.parentTracer?this.parentTracer?.getParentStepIdChain()??[]:[]}async startSubSteps(){return new Go({parentStep:this.step,socket:this.socket,parentTracer:this})}},Go=class{parentTracer;parentStep;socket;constructor({parentStep:e,socket:t,parentTracer:n}){this.parentTracer=n,this.parentStep=e,this.socket=t}getParentStepIdChain(){return this.parentStep?[...this.parentTracer?.getParentStepIdChain()??[],this.parentStep.id]:[]}async startStep(e){return this.socket.emit("started",{stepId:e.step.id,parentStepIdChain:e.parentStepIdChain,attempt:e.attempt}),new Rp({step:e.step,parentTracer:this,socket:this.socket})}},Hl=class{constructor(e){this.socket=e}attachConsoleLogs(){}attachNetworkLogs(){}async finish(){this.socket.emit("finished")}async startBeforeStepList(){return new Go({parentStep:null,parentTracer:null,socket:this.socket})}async startMainStepList(){return new Go({parentStep:null,parentTracer:null,socket:this.socket})}async startAfterStepList(){return new Go({parentStep:null,parentTracer:null,socket:this.socket})}};var WD=({metadata:r,logger:e,globalStateManager:t,socket:n,cacheStorageFactory:o})=>async(i,a)=>{let l=t.getSession(n.id);if(!l)throw new Error("No active Android session found");let c=await o(r.orgId),s=l.controller;s.resetAbortController();let u=new Hl(n),d=await Gl({fixtures:{controller:s,logger:e,cacheStorage:c,usageTracker:new Ya},containerName:"entire test",inputs:{steps:i.steps,fromStep:i.fromStep,toStep:i.toStep,orgId:r.orgId,testMetadata:i.testMetadata,interactive:!0},tracer:u});await u.finish();let p={results:d.results,status:d.status},m=JSON.parse($r(p));a?.(m)},Pv={event:"execute",createHandler:WD};import{debounce as $D}from"ts-debounce";var qD=({socket:r,globalStateManager:e,keepSessionAlive:t})=>{let n=$D(t,3e4,{maxWait:6e4});return async()=>{let o=e.getSession(r.id);if(!o)throw new Error("No active Android session found");o.emulatorName&&n(o.emulatorName)}},Ov={event:"keepalive",createHandler:qD};var Lv=[Pv,Tv,Ov];function Nv(r){let{logger:e,baseServer:t,globalStateManager:n}=r,o=new KD(t,{cors:{origin:"*",methods:["GET","POST"]},pingTimeout:15*60*1e3,pingInterval:15*60*1e3,maxHttpBufferSize:1e7,perMessageDeflate:!0}),i=async()=>{await n.removeAllSessions(e)};o.on("connection",async l=>{e.info({event:"connection",transport:l.conn.transport.name},"Android websocket connection initiated"),l.on("disconnect",async()=>{await bv({socket:l,globalStateManager:n,logger:e})});let c;try{c=await Ev({...r,socket:l,globalStateManager:n})}catch(s){e.error({err:s},"Failed to setup Android connection"),l.emit("error",{message:s instanceof Error?s.message:JSON.stringify(s)}),l.disconnect(!0);return}Lv.forEach(s=>a(s,{...r,socket:l,metadata:c,logger:e}))});let a=(l,c)=>{let s=l.createHandler(c),u=(...d)=>{l.event!=="keepalive"&&c.logger.debug({event:l.event},`Websocket event (${l.event})`);let p=m=>{c.logger.error({event:l.event,err:m instanceof Error?m:new Error(`${m}`)},"Unhandled exception in socket handler"),c.socket.emit("error",{message:m instanceof Error?m.message:`${m}`})};try{let m=s.apply(this,d);m&&typeof m.catch=="function"&&m.catch(p)}catch(m){p(m)}};c.socket.on(l.event,u)};return{server:o,dispose:i}}import{cloneDeep as YD}from"lodash-es";import Bv from"truncate-json";var Dv=1e3,kv=5e6,XD=5*1024*1024;function zv(r,e){for(let t=0;t<r.length;t++){let n=r[t];try{if(n.data){let{jsonString:o}=Bv(JSON.stringify(n.data),1e3);n.data=JSON.parse(o)}}catch(o){e.error({err:o},"Failed to serialize individual result output data"),n.data=`Result output data could not be serialized: ${o}`}switch(n.type){case"MOBILE_PRESET_STEP":Uv(n);break;case"MOBILE_MODULE_STEP":Uv(n),zv(n.steps,e);break;default:return(()=>{throw new Error("If Typescript complains about the line below, you missed a case or break in the switch above")})()}}}function Uv(r){if(r.type==="MOBILE_PRESET_STEP"){let e=r.command;"cache"in e&&e.cache&&(e.cache=void 0)}}function Fv(r,e){let t=JSON.stringify(r),n=t.replaceAll("\\u0000","");if(t.length!==n.length){let o=t.indexOf("\\u0000");e.warn({input:t.slice(Math.max(0,o-500),Math.min(t.length,o+500))},"Database content violation: stripped unicode character from input")}return n}function Vl(r,e){let t=YD(r);if(zv(t,e),t.length>Dv)return e.error("Database content violation: results too long, truncating before insertion"),t.slice(0,Dv);let n=Fv(t,e);if(n.length>kv)for(e.error({serializedLength:n.length,resultsArrayLength:t.length},"Database content violation: results too large, truncating before insertion");n.length>kv;)t.pop(),n=Fv(t,e);let{jsonString:o}=Bv(n,XD);try{return yn.array().parse(JSON.parse(o))}catch(i){throw e.error({serialized:n,err:i},"Could not parse serialized results into JSON structure after processing"),i}}var ca=!!process.env.CI||!!process.env.GITHUB_ACTIONS||!!process.env.GITHUB_RUN_ID||!!process.env.GITLAB_CI||!!process.env.CI_COMMIT_SHA||!!process.env.JENKINS_URL||!!process.env.BUILD_NUMBER||!!process.env.JENKINS_HOME||!!process.env.CIRCLECI||!!process.env.CIRCLE_BUILD_NUM||!!process.env.TRAVIS||!!process.env.TRAVIS_BUILD_NUMBER||!!process.env.BITBUCKET_BUILD_NUMBER||!!process.env.BITBUCKET_COMMIT||!!process.env.CODEBUILD_BUILD_ID||!!process.env.TF_BUILD||!!process.env.BUILD_BUILDID||!!process.env.AGENT_ID||!!process.env.BUILDER_SA_EMAIL||!!process.env.HEROKU_TEST_RUN_ID||!!process.env.CI_NODE_INDEX||!!process.env.TEAMCITY_VERSION||!!process.env.BUILD_VCS_NUMBER||!!process.env.BUILDKITE||!!process.env.BUILDKITE_BUILD_NUMBER||!!process.env.APPVEYOR||!!process.env.APPVEYOR_BUILD_NUMBER||!!process.env.DRONE||!!process.env.DRONE_BUILD_NUMBER||!!process.env.SHIPPABLE||!!process.env.BUILD_URL||!!process.env.SEMAPHORE||!!process.env.SEMAPHORE_EXECUTABLE_UUID||!!process.env.WOODPECKER||!!process.env.CI_BUILD_NUMBER||!!process.env.WERCKER_MAIN_PIPELINE_STARTED||!!process.env.BUDDY_EXECUTION_ID;import{confirm as ZD,input as e0}from"@inquirer/prompts";import{existsSync as MSe,mkdirSync as ISe,statSync as t0}from"fs";import Ho,{supportsColor as QD}from"chalk";import{Console as Gv}from"console";import{format as ua}from"util";var wp=class extends Error{constructor(e,t,n){let o=Error.stackTraceLimit;n&&(Error.stackTraceLimit=Math.max(n,o||10)),super(e),Error.captureStackTrace&&Error.captureStackTrace(this,t),Error.stackTraceLimit=o}},jl=class r extends Gv{_buffer=[];_groupDepth=0;Console=Gv;constructor(){super({write:e=>(r.write(this._buffer,"log",e),!0)})}static write(e,t,n,o=2){let i=new wp(void 0,r.write).stack;if(!i)return e;let a=i.split(`
4012
3962
  `).slice(o).filter(Boolean).join(`
4013
- `);return e.push({message:n,origin:a,type:t}),e}_log(e,t){r.write(this._buffer,e," ".repeat(this._groupDepth)+t,3)}debug(e,...t){this._log("debug",Yi(e,...t))}error(e,...t){this._log("error",Yi(e,...t))}info(e,...t){this._log("info",Yi(e,...t))}log(e,...t){this._log("log",Yi(e,...t))}warn(e,...t){this._log("warn",Yi(e,...t))}getBuffer(){return this._buffer.length>0?this._buffer:void 0}};function Jb(r){let e=globalThis.console,t=new Al;globalThis.console=t;try{r()}finally{let o=t.getBuffer()?.map(i=>i.message).join(`
3963
+ `);return e.push({message:n,origin:a,type:t}),e}_log(e,t){r.write(this._buffer,e," ".repeat(this._groupDepth)+t,3)}debug(e,...t){this._log("debug",ua(e,...t))}error(e,...t){this._log("error",ua(e,...t))}info(e,...t){this._log("info",ua(e,...t))}log(e,...t){this._log("log",ua(e,...t))}warn(e,...t){this._log("warn",ua(e,...t))}getBuffer(){return this._buffer.length>0?this._buffer:void 0}};function Hv(r){let e=globalThis.console,t=new jl;globalThis.console=t;try{r()}finally{let o=t.getBuffer()?.map(i=>i.message).join(`
4014
3964
  `);process.stderr.write(`${o}
4015
- `),globalThis.console=e}}var tm=" ".repeat(6);import IN from"fetch-retry";import PN from"os";import Qb,{multistream as ON}from"pino";import LN from"pino-pretty";import NN from"pino-std-serializers";var Mo=new Map,DN=!0,Zb="Log throttle exceeded",kN=100,UN=5e3,FN=IN(global.fetch,{retries:2,retryOn:function(r,e,t){return!!(e!==null||t&&t.status>=500)},retryDelay:function(r){return Math.pow(2,r)*500}}),rm=class r{consoleLogger;hostname;bindingAttributes;disableConsoleLogs;minLevelValue=20;logsInCurrentWindow=0;droppedLogsInWindow=!1;lastWindowStart=Date.now();site="https://ingest.us.signoz.cloud:443/logs/json";flushIntervalMs;maxBatchSize;buffer=[];flushTimer;constructor({bindings:e,hostname:t,disableConsoleLogs:n,flushIntervalMs:o,maxBatchSize:i}){this.hostname=t??PN.hostname(),this.disableConsoleLogs=n,this.bindingAttributes={...e,env:"production"},this.flushIntervalMs=o??5e3,this.maxBatchSize=i??10;let a={base:this.bindingAttributes,errorKey:"err",level:"debug"};this.consoleLogger=DN?Qb(a):Qb(a,ON([{stream:LN({colorize:!0})}]))}getLevel(){return qa[this.minLevelValue]}child(e){return new r({bindings:{...this.bindingAttributes,...e},hostname:this.hostname,disableConsoleLogs:this.disableConsoleLogs,flushIntervalMs:this.flushIntervalMs,maxBatchSize:this.maxBatchSize})}flush(e){this.flushBuffer(),this.disableConsoleLogs||this.consoleLogger.flush(e)}scheduleFlush(){this.flushTimer||(this.flushTimer=setTimeout(()=>{this.flushTimer=void 0,this.flushBuffer()},this.flushIntervalMs))}async flushBuffer(){if(this.buffer.length===0)return;let e=this.buffer;this.buffer=[];try{let t=await FN(this.site,{method:"POST",headers:{"Content-Type":"application/json","signoz-access-token":"CumAaTMUcwjt05OddAmefKgshbhfRmWxzxih"},body:Ur(e),signal:AbortSignal.timeout(5e3)});if(!t.ok)throw new Error(`Got error status (${t.statusText}) from SigNoz`)}catch(t){this.consoleLogger.warn({err:t},"Failed to log to SigNoz")}}shouldAllowLog(e){if(e===Zb)return!0;let t=Date.now();return t-this.lastWindowStart>UN&&(this.logsInCurrentWindow=0,this.droppedLogsInWindow&&this.log("error",void 0,Zb),this.droppedLogsInWindow=!1,this.lastWindowStart=t),this.logsInCurrentWindow<kN?(this.logsInCurrentWindow++,!0):(this.droppedLogsInWindow=!0,!1)}log(e,t,n,...o){try{this.logHelper(e,t,n,...o)}catch(i){this.consoleLogger.warn(`Failed to log to Signoz: ${i}`)}}logHelper(e,t,n,...o){if(Si[e]<this.minLevelValue||!this.shouldAllowLog(n))return;typeof t=="string"&&!n&&(t={message:t}),typeof t=="object"&&t&&"err"in t&&t.err instanceof Error&&(t.err=NN.err(t.err));let i={...this.bindingAttributes,...t&&typeof t=="object"?t:{},...o.length>0?{args:o}:{}},a={host:this.hostname,env:this.bindingAttributes.env};this.disableConsoleLogs||this.consoleLogger[e](i,n,...o);let l={timestamp:Math.round(Date.now()*1e6),severity_text:e.toUpperCase(),resources:a,attributes:{},body:Xg({message:n||"",...i})};this.buffer.push(l),this.buffer.length>=this.maxBatchSize?(this.flushTimer&&(clearTimeout(this.flushTimer),this.flushTimer=void 0),this.flushBuffer()):this.scheduleFlush()}setApp(e){let t=this.bindingAttributes.app;this.bindingAttributes.app=e,Mo.set("app",this),Mo.delete(t)}debug(e,t,...n){this.log("debug",e,t,...n)}info(e,t,...n){this.log("info",e,t,...n)}warn(e,t,...n){this.log("warn",e,t,...n)}error(e,t,...n){this.log("error",e,t,...n)}bindings(){return this.bindingAttributes}addBinding(e,t){this.bindingAttributes[e]=t}setMinLevel(e){typeof e=="number"?(this.minLevelValue=e,this.consoleLogger.level=qa[e]):(this.minLevelValue=Si[e],this.consoleLogger.level=e)}enableConsoleLogs(){this.disableConsoleLogs=!1}},wl=({app:r,hostname:e,disableConsoleLogs:t})=>(Mo.has(r)||Mo.set(r,new rm({bindings:{app:r},hostname:e,disableConsoleLogs:t})),Mo.get(r));function ev(){for(let r of Mo.values())r.flush()}import{hostname as BN}from"os";var wt=wl({app:"cli",hostname:BN(),disableConsoleLogs:!0}).child({cliVersion:"0.0.18"});function nm(r){if(!r)return;r=r.toLowerCase();let e=$a.safeParse(r);if(e.success)return w.setMinLevel(e.data),e.data}function tv({results:r,startTime:e,entity:t,getDisplayLine:n,onFailed:o}){let i=r.filter(u=>u.status==="PASSED"&&u.quarantined),a=r.filter(u=>u.status==="PASSED"&&!u.quarantined),l=r.filter(u=>u.status==="FAILED"&&u.quarantined),c=r.filter(u=>u.status==="FAILED"&&!u.quarantined),s=r.filter(u=>u.status==="CANCELLED");return Jb(()=>{if(c.forEach(u=>{w.log(""),o(u)}),c.length){w.log("");let u=c.length===1?"":"s";w.error(`${c.length} ${t}${u} failed:`),c.forEach(d=>{w.dimmed(n(d))})}if(s.length){w.log("");let u=s.length===1?"":"s";w.warn(`${s.length} ${t}${u} cancelled:`),s.forEach(d=>{w.dimmed(n(d))})}if(a.length){w.log("");let u=a.length===1?"":"s";w.success(`${a.length} ${t}${u} passed:`),a.forEach(d=>{w.dimmed(n(d))})}if(l.length){w.log("");let u=l.length===1?"":"s";w.warn(`${l.length} quarantined ${t}${u} failed:`),l.forEach(d=>{w.dimmed(n(d))})}if(i.length){w.log("");let u=i.length===1?"":"s";w.warn(`${i.length} quarantined ${t}${u} passed:`),i.forEach(d=>{w.dimmed(n(d))})}w.log(""),w.dimmed(`Total time: ${Math.round((Date.now()-e)/1e3)}s`)}),{quarantinedPassed:i.length,passed:a.length,quarantinedFailed:l.length,failed:c.length,cancelled:s.length}}var Xi=({status:r,testLogRef:e,getRunningTestsCount:t,getTotalTestsCount:n,additionalText:o})=>{r=r.toUpperCase();let i=r,a;r.includes("FAIL")?(i=Io.bgRed.white("FAIL"),a=3):r.includes("PASS")?(i=Io.bgGreen.white("PASS"),a=3):r.includes("START")?(i=Io.bgBlue.white("START"),a=2):r.includes("CANCEL")?(i=Io.bgRgb(191,68,11).white("CANCEL"),a=1):r.includes("RETRY")?(i=Io.bgRgb(191,68,11).white("RETRY"),a=2):r.includes("RUN")||r.includes("PROG")?(i=Io.bgMagenta.white("RUNNING"),a=0):(w.warn(`Unknown status tried to be logged in run test locally: ${r}`),a=0),zN||(i=`${i}`),w.log(`${i}${" ".repeat(a)} ${e} ${o?`${o} `:""}(${t()}/${n()})`)};var jN=!1,rv=(()=>{try{return VN("/.dockerenv"),!0}catch{return!1}})();async function Rl(r,e){return Ki||jN||rv?!0:(w.flush(),wt.flush(),await new Promise(n=>setTimeout(n,500)),await GN({message:r}))}async function nv(r,e){return Ki||rv?e:(await HN({message:r,default:e})).trim()||e}import WN from"fs";import{tmpdir as $N}from"os";import qN from"path";import{registry as Ji}from"playwright-core/lib/server";import ov from"proper-lockfile";var iv=qN.join($N(),"momenticBrowserInstallation");var om=["chrome","chromium","chrome-for-testing"],KN={Chromium:"chromium","Google Chrome":"chrome","Chrome for Testing":"chrome-for-testing"},av={chrome:"chrome",chromium:"chromium","chrome-for-testing":"chromium-headless-shell"};function sv(r){let e=av[KN[r]??""]??"",t=Ji.findExecutable(e);return!t||t.installType==="none"?!1:im(t)}function im(r){let e=r.executablePath();return WN.existsSync(e)}function YN(r,e){let t=av[r];if(!t)throw new Error(`Requested install of unknown browser type ${r}`);let n=Ji.findExecutable(t);if(!n||n.installType==="none")throw new Error(`Requested install of unknown browser type ${r}`);if(!(!e&&im(n)))return n}async function XN({browser:r,force:e}){let t=YN(r,e);if(!t){w.info(`Browser '${r}' is already installed, skipping...`);return}w.info(`Installing browser '${r}'...`);try{await Ji.installDeps([t],!1),await Ji.install([t],!1)}catch(n){if(n.message.includes("Lock file is already being held")){w.warn("Another process is installing Playwright browsers. Waiting for completion before proceeding..");let o=Ji.findExecutable(r),i=5*60*1e3,a=Date.now();for(;Date.now()-a<i&&!im(o);)w.info("Waiting for browser to finish installing..."),await new Promise(l=>setTimeout(l,5e3))}else throw n}}async function Cl({rawBrowsers:r,force:e=!1,all:t=!1}){let n=t?om:Array.from(new Set(r));try{await ov.lock(iv,{stale:1e3*60*5,update:1e3*60,realpath:!1,retries:{retries:30,factor:2,maxTimeout:15e3,minTimeout:500}})}catch(i){w.warn(`Failed to acquire lock to install browsers. Please ensure that any other process installing browsers completes within 5 minutes: ${i}. Continuing without installation...`);return}let o;try{for(let i of n)try{await XN({browser:i,force:e})}catch(a){o=a,w.error(`Failed to install the ${i} browser: ${a}`)}}finally{await ov.unlock(iv,{realpath:!1})}if(o)throw o}import{createServer as JN}from"http";async function xl(r,e){for(let n=0;n<30;n+=1){let o=r+n;if(await QN(o))return o}w.error(`Could not find an available port for ${e} starting from ${r} after 30 attempts`),process.exit(1)}async function QN(r){return new Promise((e,t)=>{let n=JN();n.once("error",o=>{o.code==="EADDRINUSE"?e(!1):(w.warn({err:o},"Unexpected error checking for open ports, continuing..."),n.close(),e(!0))}),n.once("listening",()=>{n.close(()=>{e(!0)})}),n.listen(r)})}import{randomUUID as K0}from"crypto";import{diff as ihe}from"deep-object-diff";import fhe from"yaml";import{z as Ehe}from"zod";import{diff as kge}from"deep-object-diff";import{cloneDeep as Fge}from"lodash-es";import{v4 as Xge}from"uuid";import Qge from"yaml";import tD from"@dotenvx/dotenvx";import rD from"fs";import lv from"path";function nD(r){return r.includes("${")?r.replace(/\$\{([^}]+)\}/g,(e,t)=>{let[n,o]=t.split(/:-|-/,2),i=process.env[n];return t.includes(":-")?i&&i!==""?i:o||"":t.includes("-")?i!==void 0?i:o||"":i||""}):r}function oD(r){let{envVariables:e,project:t}=r;if(!e)return{};let n={};for(let[o,i]of Object.entries(e)){if(typeof i=="string"){let l=nD(i);l&&(n[o]=l);continue}let a;try{a=rD.readFileSync(lv.resolve(t.rootDir,i.fromFile),"utf-8")}catch(l){throw new Error(`Failed to read environment variable '${o}' from file '${i.fromFile}': ${l}`)}if(i.json)try{n[o]=JSON.parse(a)}catch(l){throw new Error(`Failed to parse environment variable '${o}' from file '${i.fromFile}' as JSON: ${l}`)}else n[o]=a}return Object.keys(n).length>0&&w.debug(n,"Set environment variables with interpolation from project configuration"),n}function iD(r){let{project:e,envFile:t,logger:n}=r,o={};if(!t)return o;let i=tD.config({path:lv.resolve(e.rootDir,t),processEnv:o,logLevel:"error",quiet:!0});if(i.error)throw new Error(`Failed to load .env file: ${i.error.message}`);return n.debug(o,"Set environment variables from .env file"),o}function _l(r,e,t){let n=(e.config.environments??[]).find(c=>c.name===r);if(!n)throw new Error(`Environment ${r} not found in local project configuration file`);let o={},i=oD({envVariables:n.envVariables,project:e});Object.assign(o,i);let a=iD({project:e,envFile:n.envFile,logger:t});return Object.assign(o,a),n.inheritFromShell&&(t.debug(process.env,"Inheriting environment variables from shell"),Object.assign(o,process.env)),{name:r,variables:o}}import{existsSync as SD,readFileSync as ED,readdirSync as yD,writeFileSync as TD}from"fs";import{globSync as bD}from"glob";import In,{dirname as mv}from"path";import{cwd as um}from"process";import pv from"yaml";import{z as ye}from"zod";import cv from"fs";import{globSync as aD}from"glob";import Qi from"path";import sD from"yaml";import{z as am}from"zod";var uv=!1,sm=[`**/*.${Xe.TEST}`,`**/*.${Xe.MODULE}`],lm=am.string().refine(r=>/^[a-zA-Z0-9-]+$/.test(r)),cm=50,lD=am.object({fileType:am.nativeEnum(qe)});function Ml(r,e=!1){let t={project:r,tests:{},modules:{},mobileTests:{},duplicateEntities:{}},n=r.config.include??sm,o=Array.from(r.config.exclude??[]).concat(ja),i=aD(n,{absolute:!1,cwd:r.rootDir,ignore:o,dotRelative:!1,maxDepth:cm,nodir:!0});for(let a of i){let l=cD(r.rootDir,a,t,e?dn:w);l&&(t.duplicateEntities[l.id]=l.paths)}return uv=!0,t}function cD(r,e,t,n){let o=Qi.join(r,e),i=uD(o,n);if(!i)return;let a=dD(i,o,n);if(!a)return;let l=lD.safeParse(a);if(l.success===!1){n.warn(`Possible Momentic file at ${o} does not have a 'fileType', skipping: ${l.error}`);return}let c=l.data.fileType,s=mD(o,n);if(!s)return;let u=pD(e,o,s);switch(c){case qe.TEST:try{return gD(a,t,u,o,n)}catch(d){n.warn(`Skipping file '${o}' because it is missing Momentic test metadata: ${d}`);return}case qe.MODULE:try{return hD(a,t,u,o,n)}catch(d){n.warn(`Skipping file '${o}' because it is missing Momentic module metadata: ${d}`);return}case qe.MOBILE_TEST:try{return fD(a,t,u,o,n)}catch(d){n.warn(`Skipping file '${o}' because it is missing Momentic mobile test metadata: ${d}`);return}default:{let d=c;return}}}function uD(r,e){try{return cv.readFileSync(r,"utf-8")}catch(t){e.warn(`Could not read possible Momentic file at ${r}, skipping: ${t}`);return}}function dD(r,e,t){try{let n=sD.parse(r);if(typeof n!="object"||n===null)throw new Error("The YAML document should parse as a map with key-value pairs");return n}catch(n){t.warn(`Could not parse possible Momentic file at ${e}, skipping: ${n}`);return}}function mD(r,e){try{return cv.statSync(r)}catch(t){e.warn(`Skipping path '${r}' because it could not be stat, skipping: ${t}`);return}}function pD(r,e,t){return{relativePath:r,fullFilePath:e,platformSep:Qi.sep,fullPathSegments:e.split(Qi.sep),relativePathSegments:r.split(Qi.sep),fileName:Qi.basename(e),lastModified:t.mtime,createdAt:t.birthtime}}function gD(r,e,t,n,o){let i=to.parse(r),a;if(e.tests[i.id]){let l=e.tests[i.id].fullFilePath;a={id:i.id,paths:[l,n]}}return e.tests[i.id]={type:qe.TEST,name:i.name,id:i.id,description:i.description??void 0,labels:i.labels,...t},a}function hD(r,e,t,n,o){let i=Ot.parse(r),a;if(e.modules[i.moduleId]){let c=e.modules[i.moduleId].fullFilePath;a={id:i.moduleId,paths:[c,n]}}e.modules[i.moduleId]={type:qe.MODULE,name:i.name,id:i.moduleId,description:i.description??void 0,...t};let l=t.fileName.replace(`.${Xe.MODULE}`,"");return!uv&&Jn(i.name)!==l&&o.warn(`The module with ID ${i.moduleId} has a name (${i.name}) that does not match its file name (${l}). We recommend renaming the module or the file to be consistent to avoid confusion and issues with module resolution.`),a}function fD(r,e,t,n,o){let i=cn.parse(r),a;if(e.mobileTests[i.id]){let c=e.mobileTests[i.id].fullFilePath;a={id:i.id,paths:[c,n]}}let l=t.fileName.replace(`.${Xe.TEST}`,"");return e.mobileTests[i.id]={type:qe.MOBILE_TEST,name:l,id:i.id,description:i.description??void 0,...t},a}var Po="momentic.config.yaml",dv="momentic.workspace.yaml",vD=ye.object({projects:ye.string().array().describe("list of glob patterns to find project (momentic.config.yaml) files")}),AD=ye.union([ye.string(),ye.object({fromFile:ye.string(),json:ye.boolean().optional()})]),wD=ye.object({name:lm,baseUrl:ye.string().optional().describe("Optional for mobile tests"),envFile:ye.string().optional().describe("path to a file on disk to read environment variables from. can be relative to project root or absolute."),envVariables:ye.record(ye.string(),AD).optional(),inheritFromShell:ye.boolean().optional().describe("inherit all environment variables from the shell - might be noisy"),browser:tn.optional().describe("deprecated: use project-level configuration only")}),RD=ye.object({postSave:ye.string().optional()}),CD=ye.object({name:lm,include:ye.string().array().optional().describe("list of glob patterns that match momentic files (optional)"),exclude:ye.string().array().optional().describe("opposite of include, takes precedence over include"),goldenFileDir:ye.string().optional(),reporterDir:ye.string().optional(),outputDir:ye.string().optional(),retries:ye.number().optional().describe("number of retries per test"),parallel:ye.number().optional().describe("degree of parallelism"),environments:ye.array(wD).optional(),gitMainBranch:ye.string().optional(),gitProtectedBranches:ye.string().array().optional(),ai:Kc.optional(),browser:tn.optional(),emulator:Uc.optional(),advanced:Yc.optional(),hooks:RD.optional()});function gv(r,e){let t;try{t=ED(r,"utf-8")}catch(o){w.warn(`Could not read possible Momentic ${e} file at ${r}: ${o}`);return}let n;try{if(n=pv.parse(t),typeof n!="object"||n===null)throw new Error(`The ${e} file should parse as a map with key-value pairs, but is type ${typeof n} instead`)}catch(o){w.warn(`Possible Momentic ${e} file at ${r} does not parse as valid YAML: ${o}`);return}return n}function dm(r){let e=gv(r,"project configuration");if(e!==void 0)try{return CD.parse(e)}catch(t){w.warn(`Possible Momentic project configuration file at ${r} does not adhere to the required schema: ${t}`);return}}function xD(r){let e=gv(r,"workspace configuration");if(e!==void 0)try{return vD.parse(e)}catch(t){w.warn(`Possible Momentic workspace configuration file at ${r} does not adhere to the required schema: ${t}`);return}}function _D(){let r=[],e=um(),t=In.parse(e).root,n=15,o=0;for(;o<n;){o++;let i=In.basename(e);if(Va.includes(i))return w.warn(`Stopping search for Momentic projects since the current directory name (${i}) is likely a system artifact folder.`),r;for(let a of yD(e))if(a.endsWith(Po)){let l=In.join(e,a),c=dm(l);c&&r.push({configFilePath:l,config:c,rootDir:mv(l)})}if(r.length)return r;if(e=In.dirname(e),e===t)break}return r}function Zi(r={}){let{configFilePath:e,nameFilter:t}=r,n=ID(e);if(t&&(n=n.filter(o=>o.config.name===t)),n.length>1)throw new Error(`Multiple valid projects were found in the same directory. Please use the '-c / --config' flag to disambiguate:
4016
- ${n.map(o=>o.configFilePath)}`);if(n.length===0)throw new Error("No valid Momentic project file available.");return w.debug(`Found valid project configuration at ${n[0].configFilePath}`),n[0]}function MD(r){let e=xD(r);if(!e||!e.projects||!e.projects.length)return;let t=e.projects.map(i=>(i.endsWith("/")||(i+="/"),`${i}*${Po}`)),n=bD(t,{absolute:!1,cwd:um(),dotRelative:!1,maxDepth:cm,nodir:!0}),o=[];for(let i of n){let a=In.join(um(),i),l=dm(a);l&&o.push({configFilePath:a,config:l,rootDir:mv(a)})}return o}function ID(r){if(r){r=In.resolve(r);let t=dm(r);return t||(console.error(`No valid Momentic project file found at ${r}.`),process.exit(1)),[{config:t,configFilePath:r,rootDir:In.dirname(r)}]}if(SD(dv)){let t=MD(dv);if(t)return t}return _D()}function hv(r,e){let t=pv.stringify(r);TD(e,t)}import{z as mm}from"zod";var fv="test-results";var rfe=mm.object({width:mm.number(),height:mm.number()});import{execFile as PD}from"node:child_process";import{promisify as OD}from"node:util";import LD from"simple-git";var Te=LD(),Sv=OD(PD);async function ND(r){let e=await be(r,Te.raw(["config","--list"])),t={};if(!e)return t;for(let n of e.split(`
4017
- `)){let o=n.indexOf("=");if(o===-1)continue;let i=n.slice(0,o),a=n.slice(o+1).trim();t[i]=a}return t}async function DD(r,e,t){try{let o=t["github.user"]||void 0;if(o)return o}catch{}let n;try{if(e?.startsWith("http://")||e?.startsWith("https://"))n=new URL(e).host;else if(e?.startsWith("git@")){let o=e.indexOf("@"),i=e.indexOf(":",o+1);o!==-1&&i!==-1&&(n=e.slice(o+1,i))}}catch{}if(n=n?.toLowerCase(),!!n){try{if(e?.startsWith("git@")&&n?.includes("github")){let{stdout:o,stderr:i}=await Sv("ssh",["-T","-o","BatchMode=yes",`git@${n}`],{timeout:5e3}),l=`${o??""}${i??""}`.trim().match(/Hi\s+([A-Za-z0-9_-]+)!/);if(l?.[1])return l[1]}}catch{}try{let o=n&&n!=="github.com"?["api","--hostname",n,"user","-q",".login"]:["api","user","-q",".login"],{stdout:i}=await Sv("gh",o,{timeout:5e3}),a=i?.toString().trim();if(a)return a}catch{}}}async function kD(r,e,t){let n=e?.includes("github.com"),o=e?.includes("gitlab.com");try{if(n)return DD(r,e,t);if(o)return}catch{}}function Il(r){if(r.startsWith("git@")){let e=r.split(":");if(e.length===2){let t=e[1].replace(".git","").split("/");if(t.length===2){let n=t[0],o=t[1];return`${n}/${o}`}}}else if(r.startsWith("http")||r.startsWith("https")){let t=new URL(r).pathname.split("/").filter(Boolean);if(t.length>=2){let n=t[0],o=t[1].replace(".git","");return`${n}/${o}`}}}async function be(r,e){try{return(await e).trim()}catch(t){r.error({err:t},"Failed to run git command");return}}function UD(){if(process.env.GITHUB_ACTION)return"GithubActions";if(process.env.GITLAB_CI)return"GitlabCI";if(process.env.CIRCLECI)return"CircleCI";if(process.env.BUILDKITE)return"Buildkite";if(process.env["System.CollectionUri"]?.includes("azure"))return"AzureDevOps";if(process.env.PROJECT_ID&&process.env.BUILD_ID)return"GCPCloudBuild"}async function FD(r){let[e,t,n]=await Promise.all([be(r,Te.show(["--no-patch","--format=%ci"])),be(r,Te.show(["-s","--pretty=%B"])),be(r,Te.show(["-s","--pretty=%an"]))]),o=process.env.GITHUB_SERVER_URL&&process.env.GITHUB_REPOSITORY?`${process.env.GITHUB_SERVER_URL}/${process.env.GITHUB_REPOSITORY}`:void 0;return{gitCommitSha:process.env.GITHUB_SHA,gitCommitShaShort:process.env.GITHUB_SHA?.slice(0,6),gitCommitTimestamp:e?new Date(e):void 0,gitBranchName:process.env.GITHUB_HEAD_REF||process.env.GITHUB_REF_NAME,gitOriginUrl:o,gitCommitMessage:t,gitCommitAuthorName:n,githubRepository:process.env.GITHUB_REPOSITORY,pipelineId:process.env.GITHUB_RUN_ID}}async function BD(r){let[e,t,n]=await Promise.all([be(r,Te.listRemote(["--get-url","origin"])),be(r,Te.show(["-s","--pretty=%B"])),be(r,Te.show(["-s","--pretty=%an"]))]);return{gitCommitSha:process.env.CI_COMMIT_SHA,gitCommitShaShort:process.env.CI_COMMIT_SHORT_SHA,gitCommitTimestamp:process.env.CI_COMMIT_TIMESTAMP?new Date(process.env.CI_COMMIT_TIMESTAMP):void 0,gitBranchName:process.env.CI_COMMIT_BRANCH||process.env.CI_COMMIT_REF_NAME,gitOriginUrl:e,gitCommitMessage:t,gitCommitAuthorName:n,gitlabProjectPath:process.env.CI_PROJECT_PATH,pipelineId:`${process.env.CI_PIPELINE_ID}:${process.env.CI_JOB_ID}`}}async function zD(r){let[e,t,n,o]=await Promise.all([be(r,Te.show(["--no-patch","--format=%ci"])),be(r,Te.listRemote(["--get-url","origin"])),be(r,Te.show(["-s","--pretty=%B"])),be(r,Te.show(["-s","--pretty=%an"]))]),i=t?.includes("github.com"),a=t?.includes("gitlab.com"),l=t?Il(t):void 0;return{gitCommitSha:process.env.CIRCLE_SHA1,gitCommitShaShort:process.env.CIRCLE_SHA1?.slice(0,6),gitCommitTimestamp:e?new Date(e):void 0,gitBranchName:process.env.CIRCLE_BRANCH,gitOriginUrl:process.env.CIRCLE_REPOSITORY_URL,gitCommitMessage:n,gitCommitAuthorName:o,githubRepository:i?l:void 0,gitlabProjectPath:a?l:void 0,pipelineId:process.env.CIRCLE_PIPELINE_ID}}async function GD(r){let[e,t,n]=await Promise.all([be(r,Te.show(["--no-patch","--format=%ci"])),be(r,Te.show(["-s","--pretty=%B"])),be(r,Te.show(["-s","--pretty=%an"]))]),o=process.env.BUILDKITE_REPO,i=o?.includes("github.com"),a=o?.includes("gitlab.com"),l=o?Il(o):void 0;return{gitCommitSha:process.env.BUILDKITE_COMMIT,gitCommitShaShort:process.env.BUILDKITE_COMMIT?.slice(0,6),gitCommitTimestamp:e?new Date(e):void 0,gitBranchName:process.env.BUILDKITE_BRANCH,gitOriginUrl:o,gitCommitMessage:t,gitCommitAuthorName:n,githubRepository:i?l:void 0,gitlabProjectPath:a?l:void 0,pipelineId:`${process.env.BUILDKITE_PIPELINE_ID}:${process.env.BUILDKITE_BUILD_ID}:${process.env.BUILDKITE_JOB_ID}`}}async function HD(r){let[e,t,n]=await Promise.all([be(r,Te.show(["--no-patch","--format=%ci"])),be(r,Te.show(["-s","--pretty=%B"])),be(r,Te.show(["-s","--pretty=%an"]))]),o=process.env["Build.Repository.Uri"],i=o?.includes("github.com"),a=o?.includes("gitlab.com"),l=o?Il(o):void 0;return{gitCommitSha:process.env["Build.SourceVersion"],gitCommitShaShort:process.env["Build.SourceVersion"]?.slice(0,6),gitCommitTimestamp:e?new Date(e):void 0,gitBranchName:process.env["Build.SourceBranchName"],gitOriginUrl:o,gitCommitMessage:t,gitCommitAuthorName:n,githubRepository:i?l:void 0,gitlabProjectPath:a?l:void 0,pipelineId:`${process.env["System.JobId"]}:${process.env["System.JobAttempt"]}`}}async function VD(r,e){let[t,n,o,i,a,l,c,s,u]=await Promise.all([be(r,Te.revparse(["HEAD"])),be(r,Te.revparse(["--short","HEAD"])),be(r,Te.revparse(["--abbrev-ref","HEAD"])),be(r,Te.listRemote(["--get-url","origin"])),be(r,Te.show(["--no-patch","--format=%ci"])),be(r,Te.show(["-s","--pretty=%B"])),be(r,Te.show(["-s","--pretty=%an"])),e?be(r,Te.raw(["merge-base","--fork-point",e])):Promise.resolve(void 0),ND(r)]),d=s?await be(r,Te.show(["--no-patch","--format=%ci",s])):void 0,m=i?.includes("github.com"),p=i?.includes("gitlab.com"),g=i?Il(i):void 0,h=u["user.email"]||void 0,f=u["user.name"]||void 0,y=u["user.username"]||void 0,T=await kD(r,i,u)??y??void 0;return r.debug({userUsername:T,gitLocalUserLogin:y,gitLocalUserEmail:h,gitLocalUserName:f},"Resolved local git identity"),{gitCommitSha:t,gitCommitShaShort:n,gitBranchName:o,gitOriginUrl:i,gitCommitTimestamp:a?new Date(a):void 0,gitCommitMessage:l,gitCommitAuthorName:c,gitLocalUsername:T,gitLocalEmail:h,gitLocalName:f,lastCommitOnMainSha:s,lastCommitOnMainTimestamp:d?new Date(d):void 0,githubRepository:m?g:void 0,gitlabProjectPath:p?g:void 0,pipelineId:void 0}}async function jD(){let r=process.env._HEAD_REPO_URL;return{gitCommitSha:process.env.COMMIT_SHA,gitCommitShaShort:process.env.COMMIT_SHA?.slice(0,6),gitBranchName:process.env.BRANCH_NAME,gitOriginUrl:r?process.env._HEAD_REPO_URL:void 0,gitCommitTimestamp:void 0,gitCommitMessage:void 0,gitCommitAuthorName:void 0,githubRepository:r?process.env.REPO_FULL_NAME:void 0,pipelineId:`${process.env.PROJECT_ID}:${process.env.BUILD_ID}`}}async function WD(r){let e=r.config.gitProtectedBranches??[];return r.config.gitMainBranch&&e.push(r.config.gitMainBranch),{gitMainBranch:r.config.gitMainBranch,gitProtectedBranches:e}}async function $D(r,e){let t=UD();if(!t)return VD(r,e);switch(t){case"GithubActions":return FD(r);case"GitlabCI":return BD(r);case"CircleCI":return zD(r);case"Buildkite":return GD(r);case"AzureDevOps":return HD(r);case"GCPCloudBuild":return jD()}}async function qD(r,e,t,n){let o=n;if(!n.gitCommitSha)return o;if(n.gitMainBranch&&(!o.lastCommitOnMainSha||!o.lastCommitOnMainTimestamp))try{let i=await e.getMergeBaseCommitFromGitlab(t,n.gitMainBranch,n.gitCommitSha);o={...o,lastCommitOnMainSha:i.sha,lastCommitOnMainTimestamp:i.committer.date}}catch(i){r.warn({err:i},"Failed to get merge base commit from Gitlab")}if(!o.gitCommitTimestamp||!o.gitCommitAuthorName||!o.gitCommitMessage||!o.gitCommitAuthorName)try{let i=await e.getCommitFromGitlab(t,n.gitCommitSha);i&&(o={...o,gitCommitTimestamp:o.gitCommitTimestamp??i.committer.date,gitCommitAuthorName:o.gitCommitAuthorName??i.author.name,gitCommitMessage:o.gitCommitMessage??i.message})}catch(i){r.warn({err:i},"Failed to get commit from Gitlab")}if(n.gitBranchName&&n.gitBranchName===n.gitMainBranch&&!o.mergedGitBranchName)try{let i=await e.getMergedBranchFromGitlab(t,n.gitBranchName??"",n.gitCommitSha);i.mergedBranch&&(o={...o,mergedGitBranchName:i.mergedBranch})}catch(i){r.warn({err:i},"Failed to get merged branch from Gitlab")}return o}async function KD(r,e,t,n,o){let i=o;if(!o.gitCommitSha)return i;if(o.gitMainBranch&&(!i.lastCommitOnMainSha||!i.lastCommitOnMainTimestamp))try{let a=await e.getMergeBaseCommitFromGithub(t,n,o.gitMainBranch,o.gitCommitSha);i={...i,lastCommitOnMainSha:a.sha,lastCommitOnMainTimestamp:a.committer.date}}catch(a){r.warn({err:a},"Failed to get merge base commit from GitHub")}if(!i.gitCommitTimestamp||!i.gitCommitAuthorName||!i.gitCommitMessage||!i.gitCommitAuthorName)try{let a=await e.getCommitFromGithub(t,n,o.gitCommitSha);a&&(i={...i,gitCommitTimestamp:i.gitCommitTimestamp??a.committer.date,gitCommitAuthorName:i.gitCommitAuthorName??a.author.name,gitCommitMessage:i.gitCommitMessage??a.message})}catch(a){r.warn({err:a},"Failed to get commit from GitHub")}if(o.gitBranchName&&o.gitBranchName===o.gitMainBranch&&!i.mergedGitBranchName)try{let a=await e.getMergedBranchFromGithub(t,n,o.gitBranchName??"",o.gitCommitSha);a.mergedBranch&&(i={...i,mergedGitBranchName:a.mergedBranch})}catch(a){r.warn({err:a},"Failed to get merged branch from GitHub")}return i}async function YD(r,e,t){try{if(t.githubRepository){let[n,o]=t.githubRepository.split("/");return await KD(r,e,n,o,t)}else if(t.gitlabProjectPath)return await qD(r,e,t.gitlabProjectPath,t)}catch(n){r.warn({err:n},"Failed to get remote git metadata")}return t}async function Pl(r,e,t){let n=await WD(t),o=await $D(r,n.gitMainBranch),i={...n,...o};(!i.lastCommitOnMainSha||!i.lastCommitOnMainTimestamp)&&i.gitBranchName===n.gitMainBranch&&(i.lastCommitOnMainSha=i.gitCommitSha,i.lastCommitOnMainTimestamp=i.gitCommitTimestamp);let a=await YD(r,e,i);return{...n,...o,...a}}import{randomUUID as XD}from"crypto";import Pn from"fs";import Ol from"path";import Ll from"yaml";function Ev({name:r,description:e="",steps:t=[],settings:n={},folder:o}){let a=`${Jn(r)}.${Xe.TEST}`,l=Ol.join(o,a);if(Pn.existsSync(l))throw new Error(`A test named '${r}' already exists at path '${l}'. Choose a different name.`);let c={fileType:qe.MOBILE_TEST,id:XD(),description:e,schemaVersion:ba,settings:n,steps:t},s=Ll.stringify(c);return Pn.writeFileSync(l,s,"utf-8"),l}function pm(r,e){let t=Ol.join(e,r);if(!Pn.existsSync(t))throw new Error(`Test file not found: ${t}`);let n=Pn.readFileSync(t,"utf-8").replace(/\r\n|\r/g,`
4018
- `),o=Ll.parse(n),i=un.parse(o);if(i.fileType!==qe.MOBILE_TEST)throw new Error(`File '${r}' is not a mobile test (fileType=${i.fileType}).`);return i}async function yv({filePath:r,steps:e,settings:t,folder:n}){let o=Ol.isAbsolute(r)?r:Ol.join(n,r);if(!Pn.existsSync(o))throw new Error(`Test file not found: ${o}`);let i=Pn.readFileSync(o,"utf-8").replace(/\r\n|\r/g,`
4019
- `),a=Ll.parse(i),l=un.parse(a);if(l.fileType!==qe.MOBILE_TEST)throw new Error(`File at '${o}' is not a mobile test (fileType=${l.fileType}).`);let c;e&&(c=(await To({steps:e})).stepsToSave);let s={...l,...c!==void 0?{steps:c}:{},...t!==void 0?{settings:t}:{}},u=Ll.stringify(un.parse(s));Pn.writeFileSync(o,u,"utf-8")}import{randomUUID as JD}from"crypto";import br from"fs";import On from"path";var Tv={status:(r,e)=>{if(r.status===e.status)return r.status;if(r.status==="FAILED"||e.status==="FAILED")return"FAILED";if(r.status==="CANCELLED"||e.status==="CANCELLED")return"CANCELLED";if(r.status==="RETRYING"||e.status==="RETRYING")return"RETRYING";if(r.status==="RUNNING"||e.status==="RUNNING")return"RUNNING";if(r.status==="PENDING"||e.status==="PENDING")return"PENDING";throw new Error(`Invalid run status merge: ${r.status} and ${e.status}`)},startedAt:(r,e)=>r.startedAt<e.startedAt?r.startedAt:e.startedAt,updatedAt:(r,e)=>r.updatedAt>e.updatedAt?r.updatedAt:e.updatedAt,finishedAt:(r,e)=>!r.finishedAt||!e.finishedAt?new Date:r.finishedAt>e.finishedAt?r.finishedAt:e.finishedAt,gitCommitTimestamp:(r,e)=>{if(!(!r&&!e)){if(!r.gitCommitTimestamp||!e.gitCommitTimestamp||r.gitCommitTimestamp.getTime()!==e.gitCommitTimestamp.getTime())throw new Error(`Git commit timestamps must match to be merged: ${r.gitCommitTimestamp} and ${e.gitCommitTimestamp}`);return r.gitCommitTimestamp}},pipelineId:(r,e)=>r.pipelineId===e.pipelineId?r.pipelineId:!r.pipelineId&&e.pipelineId?e.pipelineId:!e.pipelineId&&r.pipelineId?r.pipelineId:r.startedAt<e.startedAt?e.pipelineId:r.pipelineId,labels:(r,e)=>{let t=new Set([...r.labels??[],...e.labels??[]]);return Array.from(t)}};function QD(r,e,t){if(Tv[t]){let i=Tv[t];return i(r,e)}let n=r[t],o=e[t];if(n!==o)throw new Error(`Metadata values for key "${t}" do not match: "${n}" vs "${o}"`);return n}var bv=new Set([".DS_Store","__MACOSX"]);function vv(r,e,t){let n=JD(),o=r.child({runGroupId:n});br.rmSync(e,{recursive:!0,force:!0});let i=br.readdirSync(t).filter(s=>!bv.has(s)).map(s=>On.join(t,s));if(i.length===0)throw new Error(`No run groups found in results path: ${t}`);br.mkdirSync(e,{recursive:!0});let a=On.join(i[0],"metadata.json"),l={...yi.parse(JSON.parse(br.readFileSync(a,"utf-8"))),id:n};for(let s of i){let u=On.join(s,"runs");if(!br.existsSync(u))continue;let d=br.readdirSync(u);for(let g of d){if(bv.has(g))continue;let h=On.join(u,g),f=On.join(e,"runs",g);br.cpSync(h,f,{recursive:!0})}let m=On.join(s,"metadata.json"),p=yi.parse(JSON.parse(br.readFileSync(m,"utf-8")));o.info({oldRunGroupId:p.id},"Merging metadata from run groups");for(let g in p){if(g==="id")continue;let h=g;l[h]=QD(l,p,h)}}let c=On.join(e,"metadata.json");br.writeFileSync(c,JSON.stringify(l,null,2))}import wv from"adm-zip";import ym from"fs";import{z as fm}from"zod";var D="v1",gm="mobile-cli",ea="0.0.18";var ZD=9e4,e0=3,t0=1500,r0=15e3,Kt=class extends Error{status;rawError;constructor(e,t,n,o={}){super(n,o),this.status=e,this.rawError=t}};async function n0(r){return r.text().then(e=>{try{return JSON.parse(e).error}catch{return e}})}var hm=class{baseUrl;logger;constructor(e){this.baseUrl=e.baseUrl,this.logger=e.logger}getHeaders(){let e={"Content-Type":"application/json"};return ea&&(e[rh]=ea),gm&&(e[nh]=gm),e}async sendRequest(e,t){let{retries:n=e0,requestTimeoutMs:o=ZD,initialRetryDelayMs:i=t0,maxRetryDelayMs:a=r0}=t,l=n,c=n,s,u={path:e,baseUrl:this.baseUrl,method:t.method};for(;l>0;)try{return l--,await this.sendSingleRequestHelper(e,t,o)}catch(d){if(s=d,d instanceof Kt&&d.status>=400&&d.status<500)throw d;if(d instanceof Error&&d.name==="AbortError"&&(s=new Fr),l===0)throw s;let m=c-l,p=Math.min(i*Math.pow(2,m-1),a);await new Promise(g=>setTimeout(g,p))}throw this.logger.warn({...u,err:s},"Got fatal error response from Momentic server"),s}async sendSingleRequestHelper(e,t,n){let o={path:e,baseUrl:this.baseUrl,method:t.method},i=new AbortController,a=setTimeout(()=>i.abort(),n),l=()=>i.abort();t.signal&&t.signal.addEventListener("abort",l);let c={...this.getHeaders(),...t.extraHeaders};try{let s=await fetch(`${this.baseUrl}${e}`,{method:t.method,body:t.body?JSON.stringify(t.body):void 0,headers:c,signal:i.signal});if(!s.ok){let d=await n0(s);throw new Kt(s.status,d,`Request to ${t.method} ${e} failed with status ${s.status}: ${d}`)}let u;if(s.status===204)u={};else{let d=await s.text();try{u=JSON.parse(d)}catch{u=d}}return this.logger&&t.logResponse===!0&&u&&this.logger.debug({result:u,status:s.status,...o},"Got response from Momentic server"),u}finally{clearTimeout(a),t.signal&&t.signal.removeEventListener("abort",l)}}},ur=class extends hm{apiKey;constructor(e){super(e),this.apiKey=e.apiKey}getHeaders(){return{...super.getHeaders(),Authorization:`Bearer ${this.apiKey}`}}};var Yt=class extends ur{constructor(e){super(e)}getAppUrl(){return this.baseUrl==="http://localhost:8000"?"http://localhost:3000":this.baseUrl.replace(/\/\/api/,"//app")}async getAuthInfo(){let e=await this.sendRequest(`/${D}/auth/check`,{method:"GET",retries:10,requestTimeoutMs:5e3});return bh.parse(e)}async bulkGetRunStatus(e){let t=await this.sendRequest(`/${D}/runs/status`,{method:"POST",body:e,retries:3,requestTimeoutMs:1e4});return Sh.parse(t)}async getTestYAMLExport(e){let t=await this.sendRequest(`/${D}/tests/export`,{method:"POST",body:e,retries:3,requestTimeoutMs:3e4});return uh.parse(t)}async updateStepCaches(e,t){await this.sendRequest(`/${D}/cache`,{method:"PATCH",body:e,extraHeaders:t,retries:3,requestTimeoutMs:1e4,initialRetryDelayMs:3e3})}async getStepCacheForTest(e,t){let n=await this.sendRequest(`/${D}/cache`,{method:"POST",body:e,extraHeaders:t,retries:10,requestTimeoutMs:3e4,initialRetryDelayMs:3e3});return mh.parse(n)}async updateMobileStepCaches(e,t){await this.sendRequest(`/${D}/mobile-cache`,{method:"PATCH",body:e,extraHeaders:t,retries:3,requestTimeoutMs:1e4,initialRetryDelayMs:3e3})}async getMobileStepCacheForTest(e,t){let n=await this.sendRequest(`/${D}/mobile-cache`,{method:"POST",body:e,extraHeaders:t,retries:10,logResponse:!0,requestTimeoutMs:3e4,initialRetryDelayMs:3e3});return ph.parse(n)}async queueTests(e){let t=await this.sendRequest(`/${D}/tests/queue`,{method:"POST",body:e,retries:3,requestTimeoutMs:1e4});return ch.parse(t)}async uploadScreenshot(e){let t=await this.sendRequest(`/${D}/screenshots`,{method:"POST",body:e,retries:3,requestTimeoutMs:5e3});return Th.parse(t)}async getAllEnvironments(){let e=await this.sendRequest(`/${D}/environments`,{method:"GET",retries:3,requestTimeoutMs:5e3});return vh.parse(e)}async acquireCacheLock(e,t){let n=await this.sendRequest(`/${D}/result-cache/lock`,{method:"POST",body:e,signal:t,retries:3,requestTimeoutMs:3e4});return kh.parse(n)}async releaseCacheLock(e){await this.sendRequest(`/${D}/result-cache/lock`,{method:"DELETE",body:{key:e},retries:3,requestTimeoutMs:5e3})}async deleteCacheResult(e){await this.sendRequest(`/${D}/result-cache/entry`,{method:"DELETE",body:e,retries:3,requestTimeoutMs:5e3})}async setCacheResult(e){await this.sendRequest(`/${D}/result-cache/entry`,{method:"PATCH",body:e,retries:3,requestTimeoutMs:5e3})}async getCacheResult(e){try{return await this.sendRequest(`/${D}/result-cache/entry`,{method:"POST",body:e,retries:3,requestTimeoutMs:5e3})}catch(t){if(t instanceof Error&&t.message.includes("404"))return null;throw t}}async queueSuiteRuns(e){let t=await this.sendRequest(`/${D}/suites/queue`,{method:"POST",body:e,retries:3,requestTimeoutMs:5e3});return Ah.parse(t)}async bulkGetRunGroupStatus(e){let t={runGroupIds:e},n=await this.sendRequest(`/${D}/run-groups/status`,{method:"POST",body:t,retries:3,requestTimeoutMs:5e3});return Vp.array().parse(n)}async uploadProposedSteps(e,t){try{await this.sendRequest(`/${D}/test-fragments/`,{method:"POST",body:e,retries:3,requestTimeoutMs:1e4})}catch(n){t.error({err:n},"Failed to upload proposed steps")}}async reportBillableEvents(e,t){try{await this.sendRequest(`/${D}/billing/events`,{method:"POST",body:t,retries:10,requestTimeoutMs:1e4})}catch(n){e.error({err:n},"Failed to report billable event")}}async fetchTestFragment(e){let t=await this.sendRequest(`/${D}/test-fragments/${e}`,{method:"GET",retries:3,requestTimeoutMs:1e4});return wh.parse(t)}async patchTestFragment(e,t){await this.sendRequest(`/${D}/test-fragments/${e}`,{method:"PATCH",body:t,retries:3,requestTimeoutMs:1e4})}async getPastTestResults(e,t){let n=await this.sendRequest(`/${D}/results/tests/${e}`,{method:"POST",body:t,retries:3,requestTimeoutMs:1e4});return Rh.parse(n)}async generateTestResultsUploadUrl(){let e=await this.sendRequest(`/${D}/results/uploads`,{method:"POST",retries:3,requestTimeoutMs:1e4});return Ch.parse(e)}async startProcessingResultsUpload(e,t){let n=await this.sendRequest(`/${D}/results/uploads/${e}/process`,{method:"POST",body:t,retries:3,requestTimeoutMs:1e4});return xh.parse(n)}async fetchIconKnowledgeBase(e){try{let t=await this.sendRequest(`/${D}/knowledge-base/icons`,{method:"GET",retries:3,requestTimeoutMs:5e3});return Bh.parse(t)}catch(t){return e.error({err:t},"Failed to fetch icon knowledge base"),null}}async saveNewIcons(e,t){try{await this.sendRequest(`/${D}/knowledge-base/icons`,{method:"POST",body:e,retries:3,requestTimeoutMs:5e3})}catch(n){t.error({err:n},"Failed to save new icons to icon knowledge base")}}async getMergeBaseCommitFromGithub(e,t,n,o){let i=new URLSearchParams;i.set("base",n),i.set("head",o);let a=await this.sendRequest(`/${D}/git/github/${e}/${t}/merge-base-commit?${i.toString()}`,{method:"GET",retries:3,requestTimeoutMs:1e4});return Ei.parse(a)}async getCommitFromGithub(e,t,n){let o=await this.sendRequest(`/${D}/git/github/${e}/${t}/commits/${n}`,{method:"GET",retries:3,requestTimeoutMs:1e4});return Ei.parse(o)}async getMergedBranchFromGithub(e,t,n,o){let i=encodeURIComponent(n),a=await this.sendRequest(`/${D}/git/github/${e}/${t}/${i}/${o}/merged-branch`,{method:"GET",retries:3,requestTimeoutMs:1e4});return tu.parse(a)}async getMergeBaseCommitFromGitlab(e,t,n){let o=new URLSearchParams;o.set("base",t),o.set("head",n);let i=encodeURIComponent(e),a=await this.sendRequest(`/${D}/git/gitlab/${i}/merge-base-commit?${o.toString()}`,{method:"GET",retries:3,requestTimeoutMs:5e3});return Ei.parse(a)}async getCommitFromGitlab(e,t){let n=encodeURIComponent(e),o=await this.sendRequest(`/${D}/git/gitlab/${n}/commits/${t}`,{method:"GET",retries:3,requestTimeoutMs:1e4});return Ei.parse(o)}async getMergedBranchFromGitlab(e,t,n){let o=encodeURIComponent(t),i=encodeURIComponent(e),a=await this.sendRequest(`/${D}/git/gitlab/${i}/${o}/${n}/merged-branch`,{method:"GET",retries:3,requestTimeoutMs:1e4});return tu.parse(a)}async getAgentConfig(){let e=await this.sendRequest(`/${D}/web-agent/agent-config`,{method:"GET",retries:3,requestTimeoutMs:5e3});return fm.record(fm.string(),fm.string()).parse(e)}async getQuarantinedTests(){let e=await this.sendRequest(`/${D}/quarantine`,{method:"GET"});return _h.parse(e)}async quarantineTest(e,t,n){await this.sendRequest(`/${D}/quarantine`,{method:"POST",body:{testId:e.id,testName:e.name,reason:t,...n??{}},retries:3,requestTimeoutMs:1e4})}async unquarantineTest(e,t,n){await this.sendRequest(`/${D}/quarantine/${e.id}`,{method:"DELETE",body:{testName:e.name,reason:t,...n??{}},retries:3,requestTimeoutMs:1e4})}async createAndroidEmulator(e){let t=await this.sendRequest(`/${D}/limbar/android`,{method:"POST",retries:3,body:e,requestTimeoutMs:9e4,initialRetryDelayMs:5e3,maxRetryDelayMs:15e3});return Mh.parse(t)}async extendAndroidEmulatorTtl(e){try{await this.sendRequest(`/${D}/limbar/android/${e}/keepalive`,{method:"POST",retries:3,requestTimeoutMs:15e3})}catch{}}async generateAndroidAssetUrls({channel:e,tag:t,md5:n}){let o={channel:e,tag:t,md5:n},i=await this.sendRequest(`/${D}/limbar/android/upload-url`,{method:"POST",retries:3,body:o,requestTimeoutMs:15e3,logResponse:!0});return Ih.parse(i)}async deleteAndroidEmulator(e){await this.sendRequest(`/${D}/limbar/android/${e}`,{method:"DELETE",retries:3,requestTimeoutMs:3e4})}async getAndroidAssets(){let e=await this.sendRequest(`/${D}/limbar/assets`,{method:"GET",retries:3,requestTimeoutMs:1e4});return Ph.parse(e)}async deleteAndroidAsset(e,t){await this.sendRequest(`/${D}/limbar/assets/${e}/${t}`,{method:"DELETE",retries:3,requestTimeoutMs:1e4})}};async function Sm(r){let e=process.versions.node,t=parseInt(e.split(".")[0]);(isNaN(t)||t<18)&&(w.error(`Node.js version 20 or higher is required to run the CLI. Detected: ${process.versions.node}.`),process.exit(1)),w.debug(`Identified node version ${e}`);let n=await r.client.getAuthInfo();return w.debug("Got auth info from API"),n}var Nl=class{apiClient;constructor(e){this.apiClient=e}async reportBillableEvents(e,t){await this.apiClient.reportBillableEvents(e,t)}};var Oo=class{constructor(e,t){this.client=e;this.orgId=t}async acquireCacheLock(e,t){return this.client.acquireCacheLock(e,t)}async uploadScreenshot(e){return(await this.client.uploadScreenshot({screenshot:e.toString("base64")})).key}async releaseCacheLock(e){return this.client.releaseCacheLock(e)}async deleteCacheResult(e){return this.client.deleteCacheResult(e)}async setCacheResult(e){return this.client.setCacheResult(e)}async getCacheResult(e){return this.client.getCacheResult(e)}fetchIconKnowledgeBase(e){return this.client.fetchIconKnowledgeBase(e)}saveNewIcons(e,t){return this.client.saveNewIcons(e,t)}};import{Faker as o0,en as i0}from"@faker-js/faker";var Lo="v1",No=class{httpClient;fakerInstance;type="API_CLIENT";sms={send:this.sendSms.bind(this),fetchLatest:this.fetchLatestSms.bind(this)};email={send:this.sendEmail.bind(this),fetchLatest:this.fetchLatestEmail.bind(this),fetchAll:this.fetchAllEmails.bind(this)};ai={generate:this.sendAiGenerate.bind(this)};constructor(e){this.httpClient=e.httpClient,e.fakerSeed&&(this.fakerInstance=new o0({locale:i0}),this.fakerInstance.seed(e.fakerSeed))}async sendAiGenerate(e){let t=typeof e=="string"?{input:e}:e;return this.httpClient.sendRequest(`/${Lo}/tools/ai/generate`,{method:"POST",body:t}).catch(n=>{throw n instanceof Kt?new Error(n.rawError):new Error(`Failed to send AI generation: ${n.message}`)})}async sendSms(e){return this.httpClient.sendRequest(`/${Lo}/tools/sms/send`,{method:"POST",body:e}).then(()=>{}).catch(t=>{throw t instanceof Kt?new Error(t.rawError):new Error(`Failed to send sms: ${t.message}`)})}async fetchLatestSms(e){return this.httpClient.sendRequest(`/${Lo}/tools/sms/fetchLatest`,{method:"POST",body:e}).catch(t=>{throw t instanceof Kt?new Error(t.rawError):t})}async sendEmail(e){return this.httpClient.sendRequest(`/${Lo}/tools/email/send`,{method:"POST",body:e}).then(()=>{}).catch(t=>{throw t instanceof Kt?new Error(t.rawError):new Error(`Failed to send email: ${t.message}`)})}async fetchAllEmails(e){return this.httpClient.sendRequest(`/${Lo}/tools/email/fetchAll`,{method:"POST",body:e}).catch(t=>{throw t instanceof Kt?new Error(t.rawError):new Error(`Failed to fetch all emails: ${t.message}`)})}async fetchLatestEmail(e){return this.httpClient.sendRequest(`/${Lo}/tools/email/fetchLatest`,{method:"POST",body:e}).catch(t=>{throw t instanceof Kt?new Error(t.rawError):new Error(`Failed to fetch latest emails: ${t.message}`)})}};import{z as a0}from"zod";var Ln=class extends ur{agentConfig;constructor(e,t){super(t),this.agentConfig=e}getAgentConfig(){return this.agentConfig}async rankChunksWithAi(e,t){let n={...e,loggerTags:t.loggerTags},o=await this.sendRequest(`/${D}/web-agent/recommend-chunks-ai`,{method:"POST",body:n,signal:t.abortSignal});return Kp.parse(o)}async rankChunksWithRag(e,t){let n=await this.sendRequest(`/${D}/web-agent/recommend-chunks`,{method:"POST",body:{cliVersion:ea,...e},signal:t.abortSignal});return qp.parse(n)}async getScreenshotFromS3(e){let t=await this.sendRequest(`/${D}/s3/visual-diff-screenshot`,{method:"POST",body:{url:e}});return a0.string().parse(t)}async getElementLocation(e,t){let n={...e,disableCache:t.disableCache,loggerTags:t.loggerTags,useMemory:t.useMemory,agentConfigVersion:this.agentConfig?.locator},o=await this.sendRequest(`/${D}/web-agent/locate-element`,{method:"POST",body:n,signal:t.abortSignal});return sh.parse(o)}async getAssertionResult(e,t){let n={...e,disableCache:!!t.disableCache,useConsensus:!!t.useConsensus,attemptNumber:t.attemptNumber,loggerTags:t.loggerTags,useMemory:t.useMemory,agentConfigVersion:this.agentConfig?.assertion},o=await this.sendRequest(`/${D}/web-agent/assertion`,{method:"POST",body:n,signal:t.abortSignal});return Jc.parse(o)}async getLintStepResult(e,t){let n={...e,disableCache:!!t.disableCache,loggerTags:t.loggerTags},o=await this.sendRequest(`/${D}/web-agent/lint/step`,{method:"POST",body:n,signal:t.abortSignal});return ah.parse(o)}async getLintMcpCopilotMessageResult(e,t){let n={message:e.message,disableCache:!!t.disableCache,loggerTags:t.loggerTags},o=await this.sendRequest(`/${D}/web-agent/lint/mcp-copilot`,{method:"POST",body:n,signal:t.abortSignal});return ih.parse(o)}async getVisualAssertionResult(e,t){let n={...e,disableCache:!!t.disableCache,useConsensus:!!t.useConsensus,attemptNumber:t.attemptNumber,loggerTags:t.loggerTags,useMemory:t.useMemory,agentConfigVersion:this.agentConfig?.["visual-assertion"]},o=await this.sendRequest(`/${D}/web-agent/visual-assertion`,{method:"POST",body:n,signal:t.abortSignal});return Jc.parse(o)}async getAiActionCommand(e,t){let n=await this.sendRequest(`/${D}/web-agent/next-command-dynamic`,{method:"POST",body:{...e,disableCache:t.disableCache,loggerTags:t.loggerTags},signal:t.abortSignal});return oh.parse(n)}async getMultiturnAiActionCommand(e,t){return await this.sendRequest(`/${D}/web-agent/ai-action/next-command`,{method:"POST",body:{...e,disableCache:t.disableCache,loggerTags:t.loggerTags},signal:t.abortSignal})}async getMultiturnAiActionEvaluation(e,t){let n=await this.sendRequest(`/${D}/web-agent/ai-action/evaluate`,{method:"POST",body:{...e,disableCache:t.disableCache,loggerTags:t.loggerTags},signal:t.abortSignal});return dc.parse(n)}async getReverseMappedDescription(e,t){let n=await this.sendRequest(`/${D}/web-agent/reverse-mapped-description`,{method:"POST",body:{...e,disableCache:t.disableCache,loggerTags:t.loggerTags},signal:t.abortSignal});return lh.parse(n)}async getTextExtraction(e,t){let n={...e,disableCache:t.disableCache,loggerTags:t.loggerTags,agentConfigVersion:this.agentConfig?.["text-extraction"]},o=await this.sendRequest(`/${D}/web-agent/text-extraction`,{method:"POST",body:n,signal:t.abortSignal});return cc.parse(o)}async getPageSummary(e,t){let n={...e,disableCache:t.disableCache,loggerTags:t.loggerTags},o=await this.sendRequest(`/${D}/web-agent/page-summary`,{method:"POST",body:n,signal:t.abortSignal});return Cp.parse(o)}async getTestResultClassification(e,t){let n=await this.sendRequest(`/${D}/web-agent/result-classification`,{method:"POST",body:{...e,loggerTags:t.loggerTags},signal:t.abortSignal});return fc.parse(n)}async getExtractedKeywords(e,t){let n=await this.sendRequest(`/${D}/web-agent/extract-keywords`,{method:"POST",body:{goal:e,disableCache:t.disableCache,context:e},signal:t.abortSignal});return ig.parse(n)}async getAutohealingProposal(e,t){let n=await this.sendRequest(`/${D}/web-agent/autoheal-section`,{method:"POST",body:{...e,loggerTags:t.loggerTags},signal:t.abortSignal});return vp.parse(n)}async getFailureRecoveryProposal(e,t){let n=await this.sendRequest(`/${D}/web-agent/failure-recovery`,{method:"POST",body:{...e,loggerTags:t.loggerTags},signal:t.abortSignal});return Rp.parse(n)}async getFailureRecoveryPlan(e,t){let n=await this.sendRequest(`/${D}/web-agent/failure-recovery-plan`,{method:"POST",body:{...e,loggerTags:t.loggerTags},signal:t.abortSignal});return wp.parse(n)}async getIframeRegex(e,t){let n=await this.sendRequest(`/${D}/web-agent/iframe-regex`,{method:"POST",body:e,signal:t.abortSignal});return Km.parse(n)}};var Do=class extends ur{generator;constructor(e,t){super(e),this.generator=t}async runTemplateMatching(e,t={}){let n=await this.sendRequest(`/${D}/web-agent/template-matching`,{method:"POST",body:e,signal:t?.signal});return Ym.parse(n)}async constructIframeRegex(e,t={}){return this.generator.getIframeRegex(e,{abortSignal:t.signal})}};function Av(r,e,t){return fetch(r,{method:"PUT",body:t,headers:{"Content-Type":e}})}var Dl=class{constructor(e){this.client=e}async uploadResultsArchive(e,t){let{uploadUrl:n,id:o}=await this.client.generateTestResultsUploadUrl(),i=await Av(n,"application/zip",t);if(!i.ok)throw new Error(`Failed to upload test results: ${await i.text()}`);let{runGroupId:a}=await this.client.startProcessingResultsUpload(o,{runGroupId:e});return a}};var ko=class extends ur{constructor(e){super(e)}async getElementLocation(e,t){let n={...e,loggerTags:t.loggerTags},o=await this.sendRequest(`/${D}/mobile-agent/locate-element`,{method:"POST",body:n,signal:t.abortSignal});return sg.parse(o)}async evaluateAssertion(e,t){let n={...e,loggerTags:t.loggerTags},o=await this.sendRequest(`/${D}/mobile-agent/assertion`,{method:"POST",body:n,signal:t.abortSignal});return ug.parse(o)}};function kl({orgId:r,client:e,gitMetadata:t,alwaysSaveCache:n,noCache:o}){return o?new Ja:new Em(r,e,t,n)}var Em=class{constructor(e,t,n,o){this.orgId=e;this.client=t;let{gitBranchName:i,gitProtectedBranches:a}=n;this.cacheHeaders=Qc(n),o?this.writeCaches=!0:i?this.writeCaches=!a.includes(i):this.writeCaches=!0}cacheHeaders;writeCaches;async saveEntries({entries:e,testId:t,logger:n}){if(!this.writeCaches){n.debug("Skipping cache storage because branch is protected");return}try{await this.client.updateMobileStepCaches({entries:e,testId:t},this.cacheHeaders)}catch(o){n.error({err:o},"Failed to save mobile step cache entries")}}async resolveEntries(e){let{steps:t}=e.stepLists,n=await this.client.getMobileStepCacheForTest({testId:e.testId},this.cacheHeaders);if(!this.writeCaches){e.logger.debug("Skipping mobile cache last used at update because branch is protected");return}for(let i of[t])i&&gy({steps:i,stepCacheEntries:n,logger:e.logger});let{cachesToSave:o}=await To({steps:t,cacheCreationParams:{testId:e.testId,orgId:this.orgId}});this.client.updateMobileStepCaches({entries:o,testId:e.testId},this.cacheHeaders)}};import Ul from"path";function s0(r){let e=new wv,t=Ul.join(r,"metadata.json"),n=yi.parse(JSON.parse(ym.readFileSync(t,"utf-8")));e.addLocalFile(t);for(let o of ym.readdirSync(Ul.join(r,"runs"))){if(!o.endsWith(".zip"))continue;let i=o.replace(/\.zip$/,""),a=new wv(Ul.join(r,"runs",o));for(let l of a.getEntries())l.isDirectory||e.addFile(Ul.join("runs",i,l.entryName),l.getData())}return{runGroupId:n.id,buffer:e.toBuffer()}}async function Fl(r){let{client:e,consoleLogger:t,resultsPath:n}=r;if(!ym.existsSync(n)){t.warn("Results path does not exist, skipping upload.");return}let o=new Dl(e);try{let{runGroupId:i,buffer:a}=s0(n),l=await o.uploadResultsArchive(i,a),c=`${e.getAppUrl()}/run-groups/${l}`;t.success(`Successfully uploaded test results. Once processed, your results can be found at ${c}`);return}catch(i){let a;i instanceof Error?a=i.message:typeof i=="string"?a=i:a="Unknown error",t.error(`Failed to upload test results: ${a}.`);return}}import l0 from"adm-zip";import ft from"fs";import Xt from"path";var ta=class r{constructor(e){this.filePath=e;ft.rmSync(this.filePath,{recursive:!0,force:!0}),ft.mkdirSync(this.filePath,{recursive:!0})}cd(e){return new r(Xt.join(this.filePath,e))}mkdir(e){ft.mkdirSync(Xt.join(this.filePath,e),{recursive:!0})}readFile(e){let t=Xt.join(this.filePath,e);if(ft.existsSync(t))return ft.readFileSync(t)}storeFile(e){let{name:t,contents:n}=e,o=Xt.join(this.filePath,t);try{ft.writeFileSync(o,n)}catch{}}createRunArchive(e){return new Tm(Xt.join(this.filePath,"runs"),e)}},Tm=class{constructor(e,t){this.filePath=e;this.tempPath=Xt.join(e,`.${t}`),this.finalPath=Xt.join(e,`${t}.zip`),ft.rmSync(this.tempPath,{recursive:!0,force:!0}),ft.rmSync(this.finalPath,{recursive:!0,force:!0}),ft.mkdirSync(this.tempPath,{recursive:!0})}tempPath;finalPath;readFile(e){let t=Xt.join(this.tempPath,e);if(ft.existsSync(t))return ft.readFileSync(t)}mkdir(e){ft.mkdirSync(Xt.join(this.tempPath,e),{recursive:!0})}cd(e){return new ta(Xt.join(this.tempPath,e))}storeFile(e){let{name:t,contents:n}=e,o=Xt.join(this.tempPath,t);ft.writeFileSync(o,n)}close(){let e=new l0;e.addLocalFolder(this.tempPath,void 0,n=>n!==".DS_Store");let t=e.toBuffer();ft.writeFileSync(this.finalPath,t),ft.rmSync(this.tempPath,{recursive:!0,force:!0})}};import $l from"fs";import kv from"body-parser";import w0 from"cors";import R0 from"dedent";import{Router as m0}from"express";import yt from"fs";import{globSync as p0}from"glob";import Qe from"path";import vm from"fs";import c0 from"path";var u0=new tl(30,60*1e3),Rm="https://api.momentic.ai",Am,Cv=r=>{Rm=r},Cm=()=>Rm,xm=()=>Am;var Uo,wm,Rv,xv=async r=>{if(Am&&Uo&&Rv)return Uo;let e=new Yt({baseUrl:Rm,apiKey:r,logger:w});Am=e;try{let t=await e.getAuthInfo();return Uo=t.orgId,wm=t.userId,Rv=r,Uo}catch(t){throw new Error(`Error checking API key against server: ${t}`)}},ra=()=>{if(!Uo)throw new Error("Your organization ID is invalid.");return Uo},Bl=()=>{if(!wm)throw new Error("Your user ID is invalid.");return wm};var _m,bm,_v=(r,e)=>{_m=r,bm?.abort(),bm=new AbortController;let t=bm.signal,n=[r.configFilePath];r.config.environments?.forEach(o=>{if(!o.envFile)return;let i=c0.resolve(r.rootDir,o.envFile);try{if(vm.lstatSync(i).isSymbolicLink())return;vm.existsSync(i)&&n.push(i)}catch(a){w.warn({err:a},`Failed to check if env file ${i} exists`)}});try{d0({filesToWatch:n,revalidator:e,signal:t,project:r})}catch(o){w.error({err:o},"Failed to start config file watchers")}},St=()=>_m;function d0({filesToWatch:r,revalidator:e,signal:t,project:n}){r.forEach(o=>{vm.watch(o,{signal:t,persistent:!1,recursive:!1},(i,a)=>{a&&(u0.increment("setLocalProject")&&w.warn(`A file change under the ${n.rootDir} directory has caused Momentic to reload its configuration more than 30 times in the last minute. Rapid changes to files may indicate your momentic.config.yaml 'include' glob is incorrect. Please ensure temporary, library, and auto-generated files are not included in Momentic's context.`),_m=e(n.configFilePath))})})}function Et(r){return function(...e){let t=e[e.length-1],n=r(...e);Promise.resolve(n).catch(t)}}var oa=m0();function na(r){let e=St(),t=Qe.dirname(e.configFilePath);return Qe.join(t,...r)}function g0(r){let e=St(),t=Qe.dirname(e.configFilePath),n=Qe.relative(t,r);return n?n.split(Qe.sep):[]}function h0(r,e){let t=yt.statSync(r),n=g0(r);return Wc.parse({name:e,absolutePath:r,relativePath:n.join(Qe.sep),pathSegments:n,isDirectory:t.isDirectory(),size:t.size,createdAt:t.birthtime,modifiedAt:t.mtime,accessedAt:t.atime})}oa.post("/",Et(async(r,e,t)=>{let n;try{n=Wg.parse(r.body).pathSegments}catch(d){e.status(400).json({error:`Failed to parse folder read body: ${d}`});return}let o=na(n);if(!yt.existsSync(o)){e.status(404).json({error:`Path not found: ${n.join(Qe.sep)}`});return}if(!yt.statSync(o).isDirectory()){e.status(400).json({error:`Path is not a directory: ${n.join(Qe.sep)}`});return}let a=St(),l=Array.from(a.config.exclude??[]).concat(ja),s=p0("*",{absolute:!1,cwd:o,ignore:l,dotRelative:!1,maxDepth:1,nodir:!1}).map(d=>{let m=Qe.join(o,d);return h0(m,d)}),u={absolutePath:o,pathSegments:n,contents:s};e.status(200).json(u)}));oa.put("/",Et(async(r,e,t)=>{let n;try{n=$g.parse(r.body).pathSegments}catch(a){e.status(400).json({error:`Failed to parse folder create body: ${a}`});return}let o=na(n);if(yt.existsSync(o)){e.status(200).json({success:!0,message:`Folder already exists: ${n.join(Qe.sep)}`,pathSegments:n});return}yt.mkdirSync(o,{recursive:!0});let i={success:!0,message:`Folder created: ${n.join(Qe.sep)}`,pathSegments:n};e.status(201).json(i)}));oa.patch("/",Et(async(r,e,t)=>{let n,o;try{let s=qg.parse(r.body);n=s.pathSegments,o=s.newPathSegments}catch(s){e.status(400).json({error:`Failed to parse folder update body: ${s}`});return}let i=na(n),a=na(o);if(!yt.existsSync(i)){e.status(400).json({error:`Folder not found: ${n.join(Qe.sep)}`});return}if(yt.existsSync(a)){e.status(400).json({error:`Destination already exists: ${o.join(Qe.sep)}`});return}let l=Qe.dirname(a);yt.existsSync(l)||yt.mkdirSync(l,{recursive:!0}),yt.renameSync(i,a);let c={success:!0,message:`Folder moved from ${n.join(Qe.sep)} to ${o.join(Qe.sep)}`,pathSegments:o};e.status(200).json(c)}));oa.delete("/",Et(async(r,e,t)=>{let n,o=!0;try{let c=Kg.parse(r.body);n=c.pathSegments,o=c.recursive??!0}catch(c){e.status(400).json({error:`Failed to parse folder delete body: ${c}`});return}let i=na(n);if(!yt.existsSync(i)){e.status(200).json({success:!0,message:`Folder not found: ${n.join(Qe.sep)}`,pathSegments:n});return}if(!yt.statSync(i).isDirectory()){e.status(400).json({error:`Path is not a directory: ${n.join(Qe.sep)}`});return}if(o)yt.rmSync(i,{recursive:!0,force:!0});else{if(yt.readdirSync(i).length>0){e.status(409).json({error:`Cannot delete non-empty directory without recursive flag: ${n.join("/")}`});return}yt.rmdirSync(i)}let l={success:!0,message:`Folder deleted: ${n.join("/")}`,pathSegments:n};e.status(200).json(l)}));var Mm=oa;import C0 from"events";import Uv,{Router as x0}from"express";import _0 from"http";import M0 from"path";var zl=class{sessions=new Map;registerSession(e,t){this.sessions.set(e,t)}getSession(e){return this.sessions.get(e)}async removeSession(e,t){let n=this.sessions.get(e);if(n)try{await n.cleanup?.(),t.info({sessionId:e,emulatorName:n.emulatorName},"Android emulator cleaned up")}catch(o){t.error({err:o},"Error during Android session cleanup")}finally{this.sessions.delete(e)}}async removeAllSessions(e){let t=Array.from(this.sessions.keys());await Promise.all(t.map(n=>this.removeSession(n,e)))}};var Mv=new zl;import{Router as E0}from"express";import{existsSync as y0}from"fs";import T0 from"path";import{hostname as f0}from"os";var S0="0.0.18",vr=wl({app:"mobile-desktop-server",hostname:f0(),disableConsoleLogs:!0}).child({cliVersion:S0});var Im=E0();Im.get("/",Et(async(r,e)=>{let t=xm();if(!t){e.status(500).json({message:"API client not initialized"});return}let n=await t.getAndroidAssets();e.status(200).json(n)}));Im.post("/upload-url",Et(async(r,e)=>{let t;try{t=Zg.parse(r.body)}catch(i){e.status(400).json({error:`Invalid request body: ${i}`});return}let n=xm();if(!n){e.status(500).json({error:"API client not initialized"});return}let o=T0.resolve(t.filePath);if(!y0(o)){e.status(400).json({error:`File not found: ${o}`});return}await ca({tag:t.tag,channel:t.channel,filePath:o,apiClient:n,logger:vr}),e.sendStatus(204)}));var Iv=Im;import{Router as b0}from"express";var Pv=b0();Pv.get("/",Et(async(r,e)=>{let t=St(),n=Ml(t),o=new Set;n?.tests&&Object.values(n.tests).forEach(c=>{c.labels?.forEach(s=>o.add(s))});let i=Array.from(o).sort(),a=Object.values(n.mobileTests),l={labels:i,modules:[],tests:a};e.status(200).json(l)}));var Ov=Pv;import{Router as v0}from"express";var Lv=v0();Lv.get("/",(r,e)=>{e.status(200).json({userId:Bl(),orgId:ra()})});var Nv=Lv;import{Router as A0}from"express";import Pm from"path";var Gl=A0();Gl.patch("/:testPath",Et(async(r,e)=>{let t=r.params.testPath;if(!t){e.status(400).json({error:"Missing testPath in path"});return}let n;try{n=Qg.parse(r.body)}catch(l){e.status(400).json({error:`Invalid request body: ${l}`});return}if(n.steps===void 0&&n.settings===void 0){e.status(400).json({error:"At least one of steps or settings is required"});return}let o=St(),i=t.endsWith(`.${Xe.TEST}`)?t:`${t}.${Xe.TEST}`;await yv({filePath:i,steps:n.steps,settings:n.settings,folder:o.rootDir});let a={message:"ok"};e.status(200).json(a)}));Gl.post("/",Et((r,e)=>{let t;try{t=Jg.parse(r.body)}catch(h){e.status(400).json({error:`Invalid request body: ${h}`});return}let{name:n,description:o,steps:i,settings:a,pathSegments:l}=t;if(!n||typeof n!="string"){e.status(400).json({error:"Missing or invalid 'name' in body"});return}try{_c(n)}catch(h){e.status(400).json({error:h.message});return}let c=St(),s=Pm.join(c.rootDir,...l),u=Ev({name:n,description:o,steps:i,settings:a,folder:s}),d=Pm.basename(u),m=pm(d,s),p=Pm.relative(c.rootDir,u),g={id:m.id,fileName:d,fullPath:u,relativeFilePath:p};e.status(201).json(g)}));Gl.get("/:fileName",Et((r,e)=>{let t=r.params.fileName;if(!t){e.status(400).json({error:"Missing fileName in path"});return}let n=t.endsWith(`.${Xe.TEST}`)?t:`${t}.${Xe.TEST}`,o=St(),a=pm(n,o.rootDir);e.status(200).json(a)}));var Dv=Gl;var Hl=class extends Oo{constructor(t,n){super(t,n);this.client=t;this.orgId=n}async fetchEnvironment(t,n){let o=St();return _l(t,o,w)}};var Fv="10mb";async function Bv(r){let{serverPort:e,apiKey:t,momenticServerUrl:n,staticDir:o,initialProject:i,logLevel:a,alwaysSaveCache:l,noCache:c}=r;n&&Cv(n),await xv(t);let s=ra(),u=Bl(),d=r.logger.child({orgId:s,userId:u});_v(i,R=>Zi({configFilePath:R}));let m=Uv();m.use(w0()),m.use(kv.json({limit:Fv})),m.use(kv.urlencoded({extended:!1,limit:Fv}));let p=x0();if(p.use("/folders",Mm),p.use("/entities",Ov),p.use("/identify",Nv),p.use("/mobile-tests",Dv),p.use("/assets",Iv),m.use("/api",p),m.use((R,b,x)=>{w.debug({url:R.url,path:R.path,query:R.query,method:R.method,body:R.body,headers:R.rawHeaders,client:R.ip},"Incoming request on mobile-desktop-server"),b.on("close",()=>{b.statusCode>=400&&(w.error({url:R.url,method:R.method,statusCode:b.statusCode},"Request completed in error on mobile-desktop-server"),vr.error({url:R.url,method:R.method,statusCode:b.statusCode},"Request completed in error on mobile-desktop-server"))}),x()}),m.use((R,b,x,N)=>{if(R instanceof Error&&R.message.includes("BadRequestError: request aborted")){x.status(400).send("Client disconnected");return}w.error({stack:R.stack,msg:R.message,err:R,url:b.url,method:b.method},"Unhandled exception leading to 500 on mobile-desktop-server"),vr.error({stack:R.stack,msg:R.message,err:R,url:b.url,method:b.method},"Unhandled exception leading to 500 on mobile-desktop-server"),x.status(500).send(`Internal Server Error: ${R.message}`)}),o){let R=Uv.static(o,{setHeaders:b=>{b.setHeader("Cache-Control","no-cache")},redirect:!1});m.use(R),m.use("*",(b,x)=>{x.sendFile(M0.join(o,"index.html"))})}let g=_0.createServer(m),h=`http://localhost:${e}`;await new Promise(R=>{try{g.listen(e,()=>{d.info(`Mobile desktop server is running at ${h}`),R()})}catch(b){b.message.includes("EADDRINUSE")?I0(e):w.error(`An unexpected error occurred while starting the server: ${b.message}`),process.exit(1)}});let y={type:"API_KEY",baseUrl:Cm(),apiKey:t,logger:d},T=new Yt(y),{dispose:v}=$b({baseServer:g,logger:d,authorization:y,globalStateManager:Mv,getOrgId:()=>ra(),androidDriverFactory:async({socket:R,logger:b,creationOpts:x})=>{let N=Math.floor(Math.random()*1e4)+4e4,k=await xl(N,"appium");return la({logger:b,logLevel:a,apiClient:T,creationOpts:x,socket:R,appiumPort:k,onStatusUpdate:$=>{R.emit("connectionStatusUpdate",{message:$})}})},mobileGeneratorFactory:async R=>new ko({baseUrl:Cm(),apiKey:t,logger:d}),browserGeneratorFactory:async R=>new Ln({},y),browserEnricherFactory:async R=>new Do(y,new Ln({},y)),storageFactory:async R=>new Hl(T,R),cacheStorageFactory:async R=>{let b=St(),x=await Pl(d,T,b);return kl({orgId:R,client:T,gitMetadata:x,noCache:c,alwaysSaveCache:l})},localToolsFactory:async()=>new No({httpClient:T,fakerSeed:void 0}),keepSessionAlive:R=>T.extendAndroidEmulatorTtl(R),settingsFactory:async()=>({emulator:St().config.emulator})});process.once("SIGUSR2",async()=>{return;try{await v(),await xt.flush()}catch(R){w.error({err:R},"Error during session dispose on SIGUSR2")}try{g.close(()=>{process.kill(process.pid,"SIGUSR2")})}catch{process.kill(process.pid,"SIGUSR2")}}),process.once("SIGTERM",async()=>{w.info("SIGTERM in Momentic mobile app received");try{await v(),await xt.flush()}finally{g.close(()=>process.exit(0))}}),process.once("SIGINT",async()=>{w.info("SIGINT in Momentic mobile app received");try{await v(),await xt.flush()}finally{g.close(()=>process.exit(0))}})}C0.setMaxListeners(50);process.on("warning",r=>{vr.warn({err:r},`Node warning received on mobile-desktop-server: ${r.message}`)});process.on("uncaughtException",r=>{vr.error({err:r},"Uncaught exception on mobile-desktop-server"),w.error(`Oh no! The Momentic mobile desktop app encountered a fatal error \u{1F61E}. Error logs: ${r.message}`)});process.on("unhandledRejection",r=>{vr.error({reason:`${r}`,stack:r?.stack},"Uncaught exception on mobile-desktop-server (promise rejection)"),w.error(`Oh no! The Momentic mobile desktop app encountered an asynchronous error \u{1F61E}. Error logs: ${r}`)});function I0(r){w.error(R0`Port ${r} is already in use by another process. Please close the other process and try again.
3965
+ `),globalThis.console=e}}var Cp=" ".repeat(6);import{hostname as JD}from"os";var Ct=zl({app:"cli",hostname:JD(),disableConsoleLogs:!0}).child({cliVersion:"0.0.20"});function xp(r){if(!r)return;r=r.toLowerCase();let e=ds.safeParse(r);if(e.success)return R.setMinLevel(e.data),e.data}function Vv({results:r,startTime:e,entity:t,getDisplayLine:n,onFailed:o}){let i=r.filter(u=>u.status==="PASSED"&&u.quarantined),a=r.filter(u=>u.status==="PASSED"&&!u.quarantined),l=r.filter(u=>u.status==="FAILED"&&u.quarantined),c=r.filter(u=>u.status==="FAILED"&&!u.quarantined),s=r.filter(u=>u.status==="CANCELLED");return Hv(()=>{if(c.forEach(u=>{R.log(""),o(u)}),c.length){R.log("");let u=c.length===1?"":"s";R.error(`${c.length} ${t}${u} failed:`),c.forEach(d=>{R.dimmed(n(d))})}if(s.length){R.log("");let u=s.length===1?"":"s";R.warn(`${s.length} ${t}${u} cancelled:`),s.forEach(d=>{R.dimmed(n(d))})}if(a.length){R.log("");let u=a.length===1?"":"s";R.success(`${a.length} ${t}${u} passed:`),a.forEach(d=>{R.dimmed(n(d))})}if(l.length){R.log("");let u=l.length===1?"":"s";R.warn(`${l.length} quarantined ${t}${u} failed:`),l.forEach(d=>{R.dimmed(n(d))})}if(i.length){R.log("");let u=i.length===1?"":"s";R.warn(`${i.length} quarantined ${t}${u} passed:`),i.forEach(d=>{R.dimmed(n(d))})}R.log(""),R.dimmed(`Total time: ${Math.round((Date.now()-e)/1e3)}s`)}),{quarantinedPassed:i.length,passed:a.length,quarantinedFailed:l.length,failed:c.length,cancelled:s.length}}var da=({status:r,testLogRef:e,getRunningTestsCount:t,getTotalTestsCount:n,additionalText:o})=>{r=r.toUpperCase();let i=r,a;r.includes("FAIL")?(i=Ho.bgRed.white("FAIL"),a=3):r.includes("PASS")?(i=Ho.bgGreen.white("PASS"),a=3):r.includes("START")?(i=Ho.bgBlue.white("START"),a=2):r.includes("CANCEL")?(i=Ho.bgRgb(191,68,11).white("CANCEL"),a=1):r.includes("RETRY")?(i=Ho.bgRgb(191,68,11).white("RETRY"),a=2):r.includes("RUN")||r.includes("PROG")?(i=Ho.bgMagenta.white("RUNNING"),a=0):(R.warn(`Unknown status tried to be logged in run test locally: ${r}`),a=0),QD||(i=`${i}`),R.log(`${i}${" ".repeat(a)} ${e} ${o?`${o} `:""}(${t()}/${n()})`)};var r0=!1,jv=(()=>{try{return t0("/.dockerenv"),!0}catch{return!1}})();async function Wl(r,e){return ca||r0||jv?!0:(R.flush(),Ct.flush(),await new Promise(n=>setTimeout(n,500)),await ZD({message:r}))}async function Wv(r,e){return ca||jv?e:(await e0({message:r,default:e})).trim()||e}import n0 from"fs";import{tmpdir as o0}from"os";import i0 from"path";import{registry as pa}from"playwright-core/lib/server";import $v from"proper-lockfile";var qv=i0.join(o0(),"momenticBrowserInstallation");var _p=["chrome","chromium","chrome-for-testing"],a0={Chromium:"chromium","Google Chrome":"chrome","Chrome for Testing":"chrome-for-testing"},Kv={chrome:"chrome",chromium:"chromium","chrome-for-testing":"chromium-headless-shell"};function Yv(r){let e=Kv[a0[r]??""]??"",t=pa.findExecutable(e);return!t||t.installType==="none"?!1:Mp(t)}function Mp(r){let e=r.executablePath();return n0.existsSync(e)}function s0(r,e){let t=Kv[r];if(!t)throw new Error(`Requested install of unknown browser type ${r}`);let n=pa.findExecutable(t);if(!n||n.installType==="none")throw new Error(`Requested install of unknown browser type ${r}`);if(!(!e&&Mp(n)))return n}async function l0({browser:r,force:e}){let t=s0(r,e);if(!t){R.info(`Browser '${r}' is already installed, skipping...`);return}R.info(`Installing browser '${r}'...`);try{await pa.installDeps([t],!1),await pa.install([t],!1)}catch(n){if(n.message.includes("Lock file is already being held")){R.warn("Another process is installing Playwright browsers. Waiting for completion before proceeding..");let o=pa.findExecutable(r),i=5*60*1e3,a=Date.now();for(;Date.now()-a<i&&!Mp(o);)R.info("Waiting for browser to finish installing..."),await new Promise(l=>setTimeout(l,5e3))}else throw n}}async function $l({rawBrowsers:r,force:e=!1,all:t=!1}){let n=t?_p:Array.from(new Set(r));try{await $v.lock(qv,{stale:1e3*60*5,update:1e3*60,realpath:!1,retries:{retries:30,factor:2,maxTimeout:15e3,minTimeout:500}})}catch(i){R.warn(`Failed to acquire lock to install browsers. Please ensure that any other process installing browsers completes within 5 minutes: ${i}. Continuing without installation...`);return}let o;try{for(let i of n)try{await l0({browser:i,force:e})}catch(a){o=a,R.error(`Failed to install the ${i} browser: ${a}`)}}finally{await $v.unlock(qv,{realpath:!1})}if(o)throw o}import{createServer as c0}from"http";async function ql(r,e){for(let n=0;n<30;n+=1){let o=r+n;if(await u0(o))return o}R.error(`Could not find an available port for ${e} starting from ${r} after 30 attempts`),process.exit(1)}async function u0(r){return new Promise((e,t)=>{let n=c0();n.once("error",o=>{o.code==="EADDRINUSE"?e(!1):(R.warn({err:o},"Unexpected error checking for open ports, continuing..."),n.close(),e(!0))}),n.once("listening",()=>{n.close(()=>{e(!0)})}),n.listen(r)})}import{randomUUID as sU}from"crypto";import{diff as Pye}from"deep-object-diff";import Hye from"yaml";import{z as jye}from"zod";import{execSync as d0}from"child_process";function Gn(r,e){let t=e.hooks?.postSave;if(!t)return;let n;t.includes("$1")?n=t.replaceAll("$1",r):n=`${t} ${r}`,R.debug({postSaveCommand:n},"Executing post-save hook command");try{d0(n,{encoding:"utf-8"})}catch(o){R.warn({err:o,postSaveCommand:n},"Failed to execute post-save hook command, continuing...")}}import{diff as lye}from"deep-object-diff";import{cloneDeep as uye}from"lodash-es";import{v4 as vye}from"uuid";import Rye from"yaml";import p0 from"@dotenvx/dotenvx";import m0 from"fs";import Xv from"path";function g0(r){return r.includes("${")?r.replace(/\$\{([^}]+)\}/g,(e,t)=>{let[n,o]=t.split(/:-|-/,2),i=process.env[n];return t.includes(":-")?i&&i!==""?i:o||"":t.includes("-")?i!==void 0?i:o||"":i||""}):r}function h0(r){let{envVariables:e,project:t}=r;if(!e)return{};let n={};for(let[o,i]of Object.entries(e)){if(typeof i=="string"){let l=g0(i);l&&(n[o]=l);continue}let a;try{a=m0.readFileSync(Xv.resolve(t.rootDir,i.fromFile),"utf-8")}catch(l){throw new Error(`Failed to read environment variable '${o}' from file '${i.fromFile}': ${l}`)}if(i.json)try{n[o]=JSON.parse(a)}catch(l){throw new Error(`Failed to parse environment variable '${o}' from file '${i.fromFile}' as JSON: ${l}`)}else n[o]=a}return Object.keys(n).length>0&&R.debug(n,"Set environment variables with interpolation from project configuration"),n}function f0(r){let{project:e,envFile:t,logger:n}=r,o={};if(!t)return o;let i=p0.config({path:Xv.resolve(e.rootDir,t),processEnv:o,logLevel:"error",quiet:!0});if(i.error)throw new Error(`Failed to load .env file: ${i.error.message}`);return n.debug(o,"Set environment variables from .env file"),o}function Kl(r,e,t){let n=(e.config.environments??[]).find(c=>c.name===r);if(!n)throw new Error(`Environment ${r} not found in local project configuration file`);let o={},i=h0({envVariables:n.envVariables,project:e});Object.assign(o,i);let a=f0({project:e,envFile:n.envFile,logger:t});return Object.assign(o,a),n.inheritFromShell&&(t.debug(process.env,"Inheriting environment variables from shell"),Object.assign(o,process.env)),{name:r,variables:o}}import{existsSync as M0,readFileSync as I0,readdirSync as P0,writeFileSync as O0}from"fs";import{globSync as L0}from"glob";import Hn,{dirname as eA}from"path";import{cwd as Np}from"process";import tA from"yaml";import{z as be}from"zod";import Jv from"fs";import{globSync as S0}from"glob";import ma from"path";import y0 from"yaml";import{z as Ip}from"zod";var Qv=!1,Pp=["**/*.test.yaml","**/*.module.yaml"],Op=Ip.string().refine(r=>/^[a-zA-Z0-9-]+$/.test(r)),Lp=50,E0=Ip.object({fileType:Ip.nativeEnum(ye)});function Zt(r,e=!1){let t={project:r,tests:{},modules:{},mobileTests:{},mobileModules:{},duplicateEntities:{}},n=r.config.include??Pp,o=Array.from(r.config.exclude??[]).concat(cs),i=S0(n,{absolute:!1,cwd:r.rootDir,ignore:o,dotRelative:!1,maxDepth:Lp,nodir:!0});for(let a of i){let l=b0(r.rootDir,a,t,e?bn:R);l&&(t.duplicateEntities[l.id]=l.paths)}return Qv=!0,t}function b0(r,e,t,n){let o=ma.join(r,e),i=T0(o,n);if(!i)return;let a=v0(i,o,n);if(!a)return;let l=E0.safeParse(a);if(l.success===!1){n.warn(`Possible Momentic file at ${o} does not have a 'fileType', skipping: ${l.error}`);return}let c=l.data.fileType,s=A0(o,n);if(!s)return;let u=R0(e,o,s);switch(c){case ye.TEST:try{return w0(a,t,u,o,n)}catch(d){n.warn(`Skipping file '${o}' because it is missing Momentic test metadata: ${d}`);return}case ye.MODULE:try{return C0(a,t,u,o,n)}catch(d){n.warn(`Skipping file '${o}' because it is missing Momentic module metadata: ${d}`);return}case ye.MOBILE_TEST:try{return _0(a,t,u,o,n)}catch(d){n.warn(`Skipping file '${o}' because it is missing Momentic mobile test metadata: ${d}`);return}case ye.MOBILE_MODULE:try{return x0(a,t,u,o,n)}catch(d){n.warn(`Skipping file '${o}' because it is missing Momentic mobile module metadata: ${d}`);return}default:{let d=c;return}}}function T0(r,e){try{return Jv.readFileSync(r,"utf-8")}catch(t){e.warn(`Could not read possible Momentic file at ${r}, skipping: ${t}`);return}}function v0(r,e,t){try{let n=y0.parse(r);if(typeof n!="object"||n===null)throw new Error("The YAML document should parse as a map with key-value pairs");return n}catch(n){t.warn(`Could not parse possible Momentic file at ${e}, skipping: ${n}`);return}}function A0(r,e){try{return Jv.statSync(r)}catch(t){e.warn(`Skipping path '${r}' because it could not be stat, skipping: ${t}`);return}}function R0(r,e,t){return{relativePath:r,fullFilePath:e,platformSep:ma.sep,fullPathSegments:e.split(ma.sep),relativePathSegments:r.split(ma.sep),fileName:ma.basename(e),lastModified:t.mtime,createdAt:t.birthtime}}function w0(r,e,t,n,o){let i=uo.parse(r),a;if(e.tests[i.id]){let l=e.tests[i.id].fullFilePath;a={id:i.id,paths:[l,n]}}return e.tests[i.id]={type:ye.TEST,name:i.name,id:i.id,description:i.description??void 0,labels:i.labels,...t},a}function C0(r,e,t,n,o){let i=Nt.parse(r),a;if(e.modules[i.moduleId]){let c=e.modules[i.moduleId].fullFilePath;a={id:i.moduleId,paths:[c,n]}}e.modules[i.moduleId]={type:ye.MODULE,name:i.name,id:i.moduleId,description:i.description??void 0,...t};let l=t.fileName.replace(".module.yaml","");return!Qv&&zr(i.name)!==l&&o.warn(`The module with ID ${i.moduleId} has a name (${i.name}) that does not match its file name (${l}). We recommend renaming the module or the file to be consistent to avoid confusion and issues with module resolution.`),a}function x0(r,e,t,n,o){let i=Ri.parse(r),a;if(e.mobileModules[i.moduleId]){let c=e.mobileModules[i.moduleId].fullFilePath;a={id:i.moduleId,paths:[c,n]}}let l=t.fileName.replace(".module.yaml","");return e.mobileModules[i.moduleId]={type:ye.MOBILE_MODULE,name:l,id:i.moduleId,description:i.description??void 0,...t},a}function _0(r,e,t,n,o){let i=ar.parse(r),a;if(e.mobileTests[i.id]){let c=e.mobileTests[i.id].fullFilePath;a={id:i.id,paths:[c,n]}}let l=t.fileName.replace(".test.yaml","");return e.mobileTests[i.id]={type:ye.MOBILE_TEST,name:l,id:i.id,description:i.description??void 0,...t},a}var Vo="momentic.config.yaml",Zv="momentic.workspace.yaml",N0=be.object({projects:be.string().array().describe("list of glob patterns to find project (momentic.config.yaml) files")}),D0=be.union([be.string(),be.object({fromFile:be.string(),json:be.boolean().optional()})]),k0=be.object({name:Op,baseUrl:be.string().optional().describe("Optional for mobile tests"),envFile:be.string().optional().describe("path to a file on disk to read environment variables from. can be relative to project root or absolute."),envVariables:be.record(be.string(),D0).optional(),inheritFromShell:be.boolean().optional().describe("inherit all environment variables from the shell - might be noisy"),browser:dn.optional().describe("deprecated: use project-level configuration only")}),U0=be.object({postSave:be.string().optional()}),F0=be.object({name:Op,include:be.string().array().optional().describe("list of glob patterns that match momentic files (optional)"),exclude:be.string().array().optional().describe("opposite of include, takes precedence over include"),goldenFileDir:be.string().optional(),reporterDir:be.string().optional(),outputDir:be.string().optional(),retries:be.number().optional().describe("number of retries per test"),parallel:be.number().optional().describe("degree of parallelism"),environments:be.array(k0).optional(),gitMainBranch:be.string().optional(),gitProtectedBranches:be.string().array().optional(),ai:fu.optional(),browser:dn.optional(),emulator:au.optional(),advanced:Su.optional(),hooks:U0.optional()});function rA(r,e){let t;try{t=I0(r,"utf-8")}catch(o){R.warn(`Could not read possible Momentic ${e} file at ${r}: ${o}`);return}let n;try{if(n=tA.parse(t),typeof n!="object"||n===null)throw new Error(`The ${e} file should parse as a map with key-value pairs, but is type ${typeof n} instead`)}catch(o){R.warn(`Possible Momentic ${e} file at ${r} does not parse as valid YAML: ${o}`);return}return n}function Dp(r){let e=rA(r,"project configuration");if(e!==void 0)try{return F0.parse(e)}catch(t){R.warn(`Possible Momentic project configuration file at ${r} does not adhere to the required schema: ${t}`);return}}function B0(r){let e=rA(r,"workspace configuration");if(e!==void 0)try{return N0.parse(e)}catch(t){R.warn(`Possible Momentic workspace configuration file at ${r} does not adhere to the required schema: ${t}`);return}}function z0(){let r=[],e=Np(),t=Hn.parse(e).root,n=15,o=0;for(;o<n;){o++;let i=Hn.basename(e);if(ls.includes(i))return R.warn(`Stopping search for Momentic projects since the current directory name (${i}) is likely a system artifact folder.`),r;for(let a of P0(e))if(a.endsWith(Vo)){let l=Hn.join(e,a),c=Dp(l);c&&r.push({configFilePath:l,config:c,rootDir:eA(l)})}if(r.length)return r;if(e=Hn.dirname(e),e===t)break}return r}function ga(r={}){let{configFilePath:e,nameFilter:t}=r,n=H0(e);if(t&&(n=n.filter(o=>o.config.name===t)),n.length>1)throw new Error(`Multiple valid projects were found in the same directory. Please use the '-c / --config' flag to disambiguate:
3966
+ ${n.map(o=>o.configFilePath)}`);if(n.length===0)throw new Error("No valid Momentic project file available.");return R.debug(`Found valid project configuration at ${n[0].configFilePath}`),n[0]}function G0(r){let e=B0(r);if(!e||!e.projects||!e.projects.length)return;let t=e.projects.map(i=>(i.endsWith("/")||(i+="/"),`${i}*${Vo}`)),n=L0(t,{absolute:!1,cwd:Np(),dotRelative:!1,maxDepth:Lp,nodir:!0}),o=[];for(let i of n){let a=Hn.join(Np(),i),l=Dp(a);l&&o.push({configFilePath:a,config:l,rootDir:eA(a)})}return o}function H0(r){if(r){r=Hn.resolve(r);let t=Dp(r);return t||(console.error(`No valid Momentic project file found at ${r}.`),process.exit(1)),[{config:t,configFilePath:r,rootDir:Hn.dirname(r)}]}if(M0(Zv)){let t=G0(Zv);if(t)return t}return z0()}function nA(r,e){let t=tA.stringify(r);O0(e,t)}import{z as kp}from"zod";var oA="test-results";var _Ee=kp.object({width:kp.number(),height:kp.number()});import{execFile as V0}from"node:child_process";import{promisify as j0}from"node:util";import W0 from"simple-git";var Te=W0(),iA=j0(V0);async function $0(r){let e=await ve(r,Te.raw(["config","--list"])),t={};if(!e)return t;for(let n of e.split(`
3967
+ `)){let o=n.indexOf("=");if(o===-1)continue;let i=n.slice(0,o),a=n.slice(o+1).trim();t[i]=a}return t}async function q0(r,e,t){try{let o=t["github.user"]||void 0;if(o)return o}catch{}let n;try{if(e?.startsWith("http://")||e?.startsWith("https://"))n=new URL(e).host;else if(e?.startsWith("git@")){let o=e.indexOf("@"),i=e.indexOf(":",o+1);o!==-1&&i!==-1&&(n=e.slice(o+1,i))}}catch{}if(n=n?.toLowerCase(),!!n){try{if(e?.startsWith("git@")&&n?.includes("github")){let{stdout:o,stderr:i}=await iA("ssh",["-T","-o","BatchMode=yes",`git@${n}`],{timeout:5e3}),l=`${o??""}${i??""}`.trim().match(/Hi\s+([A-Za-z0-9_-]+)!/);if(l?.[1])return l[1]}}catch{}try{let o=n&&n!=="github.com"?["api","--hostname",n,"user","-q",".login"]:["api","user","-q",".login"],{stdout:i}=await iA("gh",o,{timeout:5e3}),a=i?.toString().trim();if(a)return a}catch{}}}async function K0(r,e,t){let n=e?.includes("github.com"),o=e?.includes("gitlab.com");try{if(n)return q0(r,e,t);if(o)return}catch{}}function Yl(r){if(r.startsWith("git@")){let e=r.split(":");if(e.length===2){let t=e[1].replace(".git","").split("/");if(t.length===2){let n=t[0],o=t[1];return`${n}/${o}`}}}else if(r.startsWith("http")||r.startsWith("https")){let t=new URL(r).pathname.split("/").filter(Boolean);if(t.length>=2){let n=t[0],o=t[1].replace(".git","");return`${n}/${o}`}}}async function ve(r,e){try{return(await e).trim()}catch(t){r.error({err:t},"Failed to run git command");return}}function Y0(){if(process.env.GITHUB_ACTION)return"GithubActions";if(process.env.GITLAB_CI)return"GitlabCI";if(process.env.CIRCLECI)return"CircleCI";if(process.env.BUILDKITE)return"Buildkite";if(process.env["System.CollectionUri"]?.includes("azure"))return"AzureDevOps";if(process.env.PROJECT_ID&&process.env.BUILD_ID)return"GCPCloudBuild"}async function X0(r){let[e,t,n]=await Promise.all([ve(r,Te.show(["--no-patch","--format=%ci"])),ve(r,Te.show(["-s","--pretty=%B"])),ve(r,Te.show(["-s","--pretty=%an"]))]),o=process.env.GITHUB_SERVER_URL&&process.env.GITHUB_REPOSITORY?`${process.env.GITHUB_SERVER_URL}/${process.env.GITHUB_REPOSITORY}`:void 0;return{gitCommitSha:process.env.GITHUB_SHA,gitCommitShaShort:process.env.GITHUB_SHA?.slice(0,6),gitCommitTimestamp:e?new Date(e):void 0,gitBranchName:process.env.GITHUB_HEAD_REF||process.env.GITHUB_REF_NAME,gitOriginUrl:o,gitCommitMessage:t,gitCommitAuthorName:n,githubRepository:process.env.GITHUB_REPOSITORY,pipelineId:process.env.GITHUB_RUN_ID}}async function J0(r){let[e,t,n]=await Promise.all([ve(r,Te.listRemote(["--get-url","origin"])),ve(r,Te.show(["-s","--pretty=%B"])),ve(r,Te.show(["-s","--pretty=%an"]))]);return{gitCommitSha:process.env.CI_COMMIT_SHA,gitCommitShaShort:process.env.CI_COMMIT_SHORT_SHA,gitCommitTimestamp:process.env.CI_COMMIT_TIMESTAMP?new Date(process.env.CI_COMMIT_TIMESTAMP):void 0,gitBranchName:process.env.CI_COMMIT_BRANCH||process.env.CI_COMMIT_REF_NAME,gitOriginUrl:e,gitCommitMessage:t,gitCommitAuthorName:n,gitlabProjectPath:process.env.CI_PROJECT_PATH,pipelineId:`${process.env.CI_PIPELINE_ID}:${process.env.CI_JOB_ID}`}}async function Q0(r){let[e,t,n,o]=await Promise.all([ve(r,Te.show(["--no-patch","--format=%ci"])),ve(r,Te.listRemote(["--get-url","origin"])),ve(r,Te.show(["-s","--pretty=%B"])),ve(r,Te.show(["-s","--pretty=%an"]))]),i=t?.includes("github.com"),a=t?.includes("gitlab.com"),l=t?Yl(t):void 0;return{gitCommitSha:process.env.CIRCLE_SHA1,gitCommitShaShort:process.env.CIRCLE_SHA1?.slice(0,6),gitCommitTimestamp:e?new Date(e):void 0,gitBranchName:process.env.CIRCLE_BRANCH,gitOriginUrl:process.env.CIRCLE_REPOSITORY_URL,gitCommitMessage:n,gitCommitAuthorName:o,githubRepository:i?l:void 0,gitlabProjectPath:a?l:void 0,pipelineId:process.env.CIRCLE_PIPELINE_ID}}async function Z0(r){let[e,t,n]=await Promise.all([ve(r,Te.show(["--no-patch","--format=%ci"])),ve(r,Te.show(["-s","--pretty=%B"])),ve(r,Te.show(["-s","--pretty=%an"]))]),o=process.env.BUILDKITE_REPO,i=o?.includes("github.com"),a=o?.includes("gitlab.com"),l=o?Yl(o):void 0;return{gitCommitSha:process.env.BUILDKITE_COMMIT,gitCommitShaShort:process.env.BUILDKITE_COMMIT?.slice(0,6),gitCommitTimestamp:e?new Date(e):void 0,gitBranchName:process.env.BUILDKITE_BRANCH,gitOriginUrl:o,gitCommitMessage:t,gitCommitAuthorName:n,githubRepository:i?l:void 0,gitlabProjectPath:a?l:void 0,pipelineId:`${process.env.BUILDKITE_PIPELINE_ID}:${process.env.BUILDKITE_BUILD_ID}:${process.env.BUILDKITE_JOB_ID}`}}async function ek(r){let[e,t,n]=await Promise.all([ve(r,Te.show(["--no-patch","--format=%ci"])),ve(r,Te.show(["-s","--pretty=%B"])),ve(r,Te.show(["-s","--pretty=%an"]))]),o=process.env["Build.Repository.Uri"],i=o?.includes("github.com"),a=o?.includes("gitlab.com"),l=o?Yl(o):void 0;return{gitCommitSha:process.env["Build.SourceVersion"],gitCommitShaShort:process.env["Build.SourceVersion"]?.slice(0,6),gitCommitTimestamp:e?new Date(e):void 0,gitBranchName:process.env["Build.SourceBranchName"],gitOriginUrl:o,gitCommitMessage:t,gitCommitAuthorName:n,githubRepository:i?l:void 0,gitlabProjectPath:a?l:void 0,pipelineId:`${process.env["System.JobId"]}:${process.env["System.JobAttempt"]}`}}async function tk(r,e){let[t,n,o,i,a,l,c,s,u]=await Promise.all([ve(r,Te.revparse(["HEAD"])),ve(r,Te.revparse(["--short","HEAD"])),ve(r,Te.revparse(["--abbrev-ref","HEAD"])),ve(r,Te.listRemote(["--get-url","origin"])),ve(r,Te.show(["--no-patch","--format=%ci"])),ve(r,Te.show(["-s","--pretty=%B"])),ve(r,Te.show(["-s","--pretty=%an"])),e?ve(r,Te.raw(["merge-base","--fork-point",e])):Promise.resolve(void 0),$0(r)]),d=s?await ve(r,Te.show(["--no-patch","--format=%ci",s])):void 0,p=i?.includes("github.com"),m=i?.includes("gitlab.com"),g=i?Yl(i):void 0,h=u["user.email"]||void 0,f=u["user.name"]||void 0,E=u["user.username"]||void 0,b=await K0(r,i,u)??E??void 0;return{gitCommitSha:t,gitCommitShaShort:n,gitBranchName:o,gitOriginUrl:i,gitCommitTimestamp:a?new Date(a):void 0,gitCommitMessage:l,gitCommitAuthorName:c,gitLocalUsername:b,gitLocalEmail:h,gitLocalName:f,lastCommitOnMainSha:s,lastCommitOnMainTimestamp:d?new Date(d):void 0,githubRepository:p?g:void 0,gitlabProjectPath:m?g:void 0,pipelineId:void 0}}async function rk(){let r=process.env._HEAD_REPO_URL;return{gitCommitSha:process.env.COMMIT_SHA,gitCommitShaShort:process.env.COMMIT_SHA?.slice(0,6),gitBranchName:process.env.BRANCH_NAME,gitOriginUrl:r?process.env._HEAD_REPO_URL:void 0,gitCommitTimestamp:void 0,gitCommitMessage:void 0,gitCommitAuthorName:void 0,githubRepository:r?process.env.REPO_FULL_NAME:void 0,pipelineId:`${process.env.PROJECT_ID}:${process.env.BUILD_ID}`}}async function nk(r){let e=r.config.gitProtectedBranches??[];return r.config.gitMainBranch&&e.push(r.config.gitMainBranch),{gitMainBranch:r.config.gitMainBranch,gitProtectedBranches:e}}async function Up(r,e){let t=Y0();if(!t)return tk(r,e);switch(t){case"GithubActions":return X0(r);case"GitlabCI":return J0(r);case"CircleCI":return Q0(r);case"Buildkite":return Z0(r);case"AzureDevOps":return ek(r);case"GCPCloudBuild":return rk()}}async function ok(r,e,t,n){let o=n;if(!n.gitCommitSha)return o;if(n.gitMainBranch&&(!o.lastCommitOnMainSha||!o.lastCommitOnMainTimestamp))try{let i=await e.getMergeBaseCommitFromGitlab(t,n.gitMainBranch,n.gitCommitSha);o={...o,lastCommitOnMainSha:i.sha,lastCommitOnMainTimestamp:i.committer.date}}catch(i){r.warn({err:i},"Failed to get merge base commit from Gitlab")}if(!o.gitCommitTimestamp||!o.gitCommitAuthorName||!o.gitCommitMessage||!o.gitCommitAuthorName)try{let i=await e.getCommitFromGitlab(t,n.gitCommitSha);i&&(o={...o,gitCommitTimestamp:o.gitCommitTimestamp??i.committer.date,gitCommitAuthorName:o.gitCommitAuthorName??i.author.name,gitCommitMessage:o.gitCommitMessage??i.message})}catch(i){r.warn({err:i},"Failed to get commit from Gitlab")}if(n.gitBranchName&&n.gitBranchName===n.gitMainBranch&&!o.mergedGitBranchName)try{let i=await e.getMergedBranchFromGitlab(t,n.gitBranchName??"",n.gitCommitSha);i.mergedBranch&&(o={...o,mergedGitBranchName:i.mergedBranch})}catch(i){r.warn({err:i},"Failed to get merged branch from Gitlab")}return o}async function ik(r,e,t,n,o){let i=o;if(!o.gitCommitSha)return i;if(o.gitMainBranch&&(!i.lastCommitOnMainSha||!i.lastCommitOnMainTimestamp))try{let a=await e.getMergeBaseCommitFromGithub(t,n,o.gitMainBranch,o.gitCommitSha);i={...i,lastCommitOnMainSha:a.sha,lastCommitOnMainTimestamp:a.committer.date}}catch(a){r.warn({err:a},"Failed to get merge base commit from GitHub")}if(!i.gitCommitTimestamp||!i.gitCommitAuthorName||!i.gitCommitMessage||!i.gitCommitAuthorName)try{let a=await e.getCommitFromGithub(t,n,o.gitCommitSha);a&&(i={...i,gitCommitTimestamp:i.gitCommitTimestamp??a.committer.date,gitCommitAuthorName:i.gitCommitAuthorName??a.author.name,gitCommitMessage:i.gitCommitMessage??a.message})}catch(a){r.warn({err:a},"Failed to get commit from GitHub")}if(o.gitBranchName&&o.gitBranchName===o.gitMainBranch&&!i.mergedGitBranchName)try{let a=await e.getMergedBranchFromGithub(t,n,o.gitBranchName??"",o.gitCommitSha);a.mergedBranch&&(i={...i,mergedGitBranchName:a.mergedBranch})}catch(a){r.warn({err:a},"Failed to get merged branch from GitHub")}return i}async function ak(r,e,t){try{if(t.githubRepository){let[n,o]=t.githubRepository.split("/");return await ik(r,e,n,o,t)}else if(t.gitlabProjectPath)return await ok(r,e,t.gitlabProjectPath,t)}catch(n){r.warn({err:n},"Failed to get remote git metadata")}return t}async function Xl(r,e,t){let n=await nk(t),o=await Up(r,n.gitMainBranch),i={...n,...o};(!i.lastCommitOnMainSha||!i.lastCommitOnMainTimestamp)&&i.gitBranchName===n.gitMainBranch&&(i.lastCommitOnMainSha=i.gitCommitSha,i.lastCommitOnMainTimestamp=i.gitCommitTimestamp);let a=await ak(r,e,i);return{...n,...o,...a}}import{diff as aA}from"deep-object-diff";import Vn from"fs";import{cloneDeep as sk}from"lodash-es";import Fp from"path";import{v4 as YEe}from"uuid";import Jl from"yaml";function sA({content:r,schemaVersion:e,momenticFiles:t,project:n,forceSaveOnNoDiffs:o}){let i=t.mobileModules[r.moduleId]?.fullFilePath;if(!i||!Vn.existsSync(i))throw new Error(`Tried to update mobile module ${r.moduleId} that could not be found on disk`);let a=Vn.readFileSync(i,"utf-8"),l=Jl.parse(a),c={...r,schemaVersion:e},s=Tn({fileType:ye.MOBILE_MODULE,...Ri.parse(c),steps:Yt.array().parse(r.steps)}),u=aA(s,l);if(u&&Object.keys(u).length===0&&!o)return;let d=Jl.stringify(s);Vn.writeFileSync(i,d,"utf-8"),Gn(i,n.config)}function lA({moduleId:r,patch:e,momenticFiles:t,project:n,logger:o}){let i=t.mobileModules[r]?.fullFilePath;if(!i)throw new Error(`Tried to update mobile module ${r} that could not be found on disk`);let a=ha(i,o),l={...a,...e},c=Tn({fileType:ye.MOBILE_MODULE,...Za.parse(l)}),s=aA(c,a);if(s&&Object.keys(s).length===0)return;let u=Jl.stringify(c);Vn.writeFileSync(i,u,"utf-8");let d;if(e.name){let p=`${zr(e.name)}.module.yaml`;if(d=Fp.join(Fp.dirname(i),p),Vn.existsSync(d))throw new Error(`A conflicting file already exists at the following path: ${d}`);Vn.renameSync(i,d)}Gn(d||i,n.config)}function ha(r,e){let t=Vn.readFileSync(r,"utf-8"),n=Jl.parse(t);try{return{...Za.parse(n),name:Fp.basename(r,".module.yaml")}}catch(o){throw e.error({err:o,moduleFilePath:r,moduleContents:t},`${r} does not parse as a valid Momentic mobile module`),o}}async function Bp(r,e,t,n){let o=ha(r.fullFilePath,t),{resolvedSteps:i}=await Ts({rawSteps:o.steps,resolvedModuleCache:n||{},onFetchModule:async l=>{let c=e.mobileModules[l]?.fullFilePath;if(!c)throw new Error(`Could not find mobile module with id ${l}`);return ha(c,t)},logger:t,metadata:{id:o.moduleId,schemaVersion:o.schemaVersion}}),a={...o,name:r.name,steps:i};return n&&(n[r.id]=sk(a)),a}async function cA(r,e){let t={};return await Promise.all(Object.values(r.mobileModules).map(async n=>{await Bp(n,r,e,t)})),Array.from(Object.values(t))}import{randomUUID as lk}from"crypto";import jn from"fs";import zp from"path";import Ql from"yaml";function uA({name:r,description:e="",steps:t=[],settings:n={},folder:o}){let a=`${zr(r)}.test.yaml`,l=zp.join(o,a);if(jn.existsSync(l))throw new Error(`A test named '${r}' already exists at path '${l}'. Choose a different name.`);let c={fileType:ye.MOBILE_TEST,id:lk(),description:e,schemaVersion:Ic,settings:n,steps:t},s=Ql.stringify(c);return jn.writeFileSync(l,s,"utf-8"),{fullPath:l,testId:c.id}}function ck(r){if(!jn.existsSync(r))throw new Error(`Test file not found: ${r}`);let e=jn.readFileSync(r,"utf-8").replace(/\r\n|\r/g,`
3968
+ `),t=Ql.parse(e),n=rs.parse(t);if(n.fileType!==ye.MOBILE_TEST)throw new Error(`File is not a mobile test (fileType=${n.fileType}): ${r}`);return n}async function Zl(r,e,t){let n=ck(r),o;try{o=ar.parse(n)}catch(l){throw new Error(`Mobile test ${r} is missing metadata or has invalid metadata: ${l}`)}let{resolvedStepLists:i}=await jf({rawStepLists:{steps:n.steps,beforeSteps:void 0,afterSteps:void 0},logger:e,testMetadata:o,onFetchModule:async l=>{let c=t.mobileModules[l]?.fullFilePath;if(!c)throw new Error(`Mobile module ${l} not found`);return ha(c,e)}});return{...o,steps:i.steps}}async function dA({filePath:r,steps:e,settings:t,folder:n,project:o,momenticFiles:i}){let a=zp.isAbsolute(r)?r:zp.join(n,r);if(!jn.existsSync(a))throw new Error(`Test file not found: ${a}`);let l=jn.readFileSync(a,"utf-8").replace(/\r\n|\r/g,`
3969
+ `),c=Ql.parse(l),s=rs.parse(c);if(s.fileType!==ye.MOBILE_TEST)throw new Error(`File at '${a}' is not a mobile test (fileType=${s.fileType}).`);let u;e&&(u=await Rn({steps:e}));let d={...s,...u?.stepsToSave!==void 0?{steps:u.stepsToSave}:{},...t!==void 0?{settings:t}:{}},p=Ql.stringify(rs.parse(d));for(let m of u?.moduleUpdates??[])sA({content:m,schemaVersion:Ic,momenticFiles:i,project:o});jn.writeFileSync(a,p,"utf-8"),Gn(a,o.config)}import{randomUUID as uk}from"crypto";import Pr from"fs";import Wn from"path";var pA={status:(r,e)=>{if(r.status===e.status)return r.status;if(r.status==="FAILED"||e.status==="FAILED")return"FAILED";if(r.status==="CANCELLED"||e.status==="CANCELLED")return"CANCELLED";if(r.status==="RETRYING"||e.status==="RETRYING")return"RETRYING";if(r.status==="RUNNING"||e.status==="RUNNING")return"RUNNING";if(r.status==="PENDING"||e.status==="PENDING")return"PENDING";throw new Error(`Invalid run status merge: ${r.status} and ${e.status}`)},startedAt:(r,e)=>r.startedAt<e.startedAt?r.startedAt:e.startedAt,updatedAt:(r,e)=>r.updatedAt>e.updatedAt?r.updatedAt:e.updatedAt,finishedAt:(r,e)=>!r.finishedAt||!e.finishedAt?new Date:r.finishedAt>e.finishedAt?r.finishedAt:e.finishedAt,gitCommitTimestamp:(r,e)=>{if(!(!r&&!e)){if(!r.gitCommitTimestamp||!e.gitCommitTimestamp||r.gitCommitTimestamp.getTime()!==e.gitCommitTimestamp.getTime())throw new Error(`Git commit timestamps must match to be merged: ${r.gitCommitTimestamp} and ${e.gitCommitTimestamp}`);return r.gitCommitTimestamp}},pipelineId:(r,e)=>r.pipelineId===e.pipelineId?r.pipelineId:!r.pipelineId&&e.pipelineId?e.pipelineId:!e.pipelineId&&r.pipelineId?r.pipelineId:r.startedAt<e.startedAt?e.pipelineId:r.pipelineId,labels:(r,e)=>{let t=new Set([...r.labels??[],...e.labels??[]]);return Array.from(t)}};function dk(r,e,t){if(pA[t]){let i=pA[t];return i(r,e)}let n=r[t],o=e[t];if(n!==o)throw new Error(`Metadata values for key "${t}" do not match: "${n}" vs "${o}"`);return n}var mA=new Set([".DS_Store","__MACOSX"]);function gA(r,e,t){let n=uk(),o=r.child({runGroupId:n});Pr.rmSync(e,{recursive:!0,force:!0});let i=Pr.readdirSync(t).filter(s=>!mA.has(s)).map(s=>Wn.join(t,s));if(i.length===0)throw new Error(`No run groups found in results path: ${t}`);Pr.mkdirSync(e,{recursive:!0});let a=Wn.join(i[0],"metadata.json"),l={...Oi.parse(JSON.parse(Pr.readFileSync(a,"utf-8"))),id:n};for(let s of i){let u=Wn.join(s,"runs");if(!Pr.existsSync(u))continue;let d=Pr.readdirSync(u);for(let g of d){if(mA.has(g))continue;let h=Wn.join(u,g),f=Wn.join(e,"runs",g);Pr.cpSync(h,f,{recursive:!0})}let p=Wn.join(s,"metadata.json"),m=Oi.parse(JSON.parse(Pr.readFileSync(p,"utf-8")));o.info({oldRunGroupId:m.id},"Merging metadata from run groups");for(let g in m){if(g==="id")continue;let h=g;l[h]=dk(l,m,h)}}let c=Wn.join(e,"metadata.json");Pr.writeFileSync(c,JSON.stringify(l,null,2))}import fA from"adm-zip";import $p from"fs";import{z as Vp}from"zod";var D="v1",Gp="mobile-cli",fa="0.0.20";var pk=9e4,mk=3,gk=1500,hk=15e3,er=class extends Error{status;rawError;constructor(e,t,n,o={}){super(n,o),this.status=e,this.rawError=t}};async function fk(r){return r.text().then(e=>{try{return JSON.parse(e).error}catch{return e}})}var Hp=class{baseUrl;logger;constructor(e){this.baseUrl=e.baseUrl,this.logger=e.logger}getHeaders(){let e={"Content-Type":"application/json"};return fa&&(e[Ph]=fa),Gp&&(e[Oh]=Gp),e}async sendRequest(e,t){let{retries:n=mk,requestTimeoutMs:o=pk,initialRetryDelayMs:i=gk,maxRetryDelayMs:a=hk}=t,l=n,c=n,s,u={path:e,baseUrl:this.baseUrl,method:t.method};for(;l>0;)try{return l--,await this.sendSingleRequestHelper(e,t,o)}catch(d){if(s=d,d instanceof er&&d.status>=400&&d.status<500)throw d;if(d instanceof Error&&d.name==="AbortError"&&(s=new qr),l===0)throw s;let p=c-l,m=Math.min(i*Math.pow(2,p-1),a);await new Promise(g=>setTimeout(g,m))}throw this.logger.warn({...u,err:s},"Got fatal error response from Momentic server"),s}async sendSingleRequestHelper(e,t,n){let o={path:e,baseUrl:this.baseUrl,method:t.method},i=new AbortController,a=setTimeout(()=>i.abort(),n),l=()=>i.abort();t.signal&&t.signal.addEventListener("abort",l);let c={...this.getHeaders(),...t.extraHeaders};try{let s=await fetch(`${this.baseUrl}${e}`,{method:t.method,body:t.body?JSON.stringify(t.body):void 0,headers:c,signal:i.signal});if(!s.ok){let d=await fk(s);throw new er(s.status,d,`Request to ${t.method} ${e} failed with status ${s.status}: ${d}`)}let u;if(s.status===204)u={};else{let d=await s.text();try{u=JSON.parse(d)}catch{u=d}}return this.logger&&t.logResponse===!0&&u&&this.logger.debug({result:u,status:s.status,...o},"Got response from Momentic server"),u}finally{clearTimeout(a),t.signal&&t.signal.removeEventListener("abort",l)}}},Tr=class extends Hp{apiKey;constructor(e){super(e),this.apiKey=e.apiKey}getHeaders(){return{...super.getHeaders(),Authorization:`Bearer ${this.apiKey}`}}};var tr=class extends Tr{constructor(e){super(e)}getAppUrl(){return this.baseUrl==="http://localhost:8000"?"http://localhost:3000":this.baseUrl.replace(/\/\/api/,"//app")}async getAuthInfo(){let e=await this.sendRequest(`/${D}/auth/check`,{method:"GET",retries:10,requestTimeoutMs:5e3});return Xh.parse(e)}async bulkGetRunStatus(e){let t=await this.sendRequest(`/${D}/runs/status`,{method:"POST",body:e,retries:3,requestTimeoutMs:1e4});return $h.parse(t)}async getTestYAMLExport(e){let t=await this.sendRequest(`/${D}/tests/export`,{method:"POST",body:e,retries:3,requestTimeoutMs:3e4});return Bh.parse(t)}async updateStepCaches(e,t){await this.sendRequest(`/${D}/cache`,{method:"PATCH",body:e,extraHeaders:t,retries:3,requestTimeoutMs:1e4,initialRetryDelayMs:3e3})}async getStepCacheForTest(e,t){let n=await this.sendRequest(`/${D}/cache`,{method:"POST",body:e,extraHeaders:t,retries:10,requestTimeoutMs:3e4,initialRetryDelayMs:3e3});return Gh.parse(n)}async updateMobileStepCaches(e,t){await this.sendRequest(`/${D}/mobile-cache`,{method:"PATCH",body:e,extraHeaders:t,retries:3,requestTimeoutMs:1e4,initialRetryDelayMs:3e3})}async getMobileStepCacheForTest(e,t){let n=await this.sendRequest(`/${D}/mobile-cache`,{method:"POST",body:e,extraHeaders:t,retries:10,logResponse:!0,requestTimeoutMs:3e4,initialRetryDelayMs:3e3});return Hh.parse(n)}async queueTests(e){let t=await this.sendRequest(`/${D}/tests/queue`,{method:"POST",body:e,retries:3,requestTimeoutMs:1e4});return Fh.parse(t)}async uploadScreenshot(e){let t=await this.sendRequest(`/${D}/screenshots`,{method:"POST",body:e,retries:3,requestTimeoutMs:5e3});return Yh.parse(t)}async getAllEnvironments(){let e=await this.sendRequest(`/${D}/environments`,{method:"GET",retries:3,requestTimeoutMs:5e3});return Jh.parse(e)}async acquireCacheLock(e,t){let n=await this.sendRequest(`/${D}/result-cache/lock`,{method:"POST",body:e,signal:t,retries:3,requestTimeoutMs:3e4});return pf.parse(n)}async releaseCacheLock(e){await this.sendRequest(`/${D}/result-cache/lock`,{method:"DELETE",body:{key:e},retries:3,requestTimeoutMs:5e3})}async deleteCacheResult(e){await this.sendRequest(`/${D}/result-cache/entry`,{method:"DELETE",body:e,retries:3,requestTimeoutMs:5e3})}async setCacheResult(e){await this.sendRequest(`/${D}/result-cache/entry`,{method:"PATCH",body:e,retries:3,requestTimeoutMs:5e3})}async getCacheResult(e){try{return await this.sendRequest(`/${D}/result-cache/entry`,{method:"POST",body:e,retries:3,requestTimeoutMs:5e3})}catch(t){if(t instanceof Error&&t.message.includes("404"))return null;throw t}}async queueSuiteRuns(e){let t=await this.sendRequest(`/${D}/suites/queue`,{method:"POST",body:e,retries:3,requestTimeoutMs:5e3});return Qh.parse(t)}async bulkGetRunGroupStatus(e){let t={runGroupIds:e},n=await this.sendRequest(`/${D}/run-groups/status`,{method:"POST",body:t,retries:3,requestTimeoutMs:5e3});return fg.array().parse(n)}async uploadProposedSteps(e,t){try{await this.sendRequest(`/${D}/test-fragments/`,{method:"POST",body:e,retries:3,requestTimeoutMs:1e4})}catch(n){t.error({err:n},"Failed to upload proposed steps")}}async reportBillableEvents(e,t){try{await this.sendRequest(`/${D}/billing/events`,{method:"POST",body:t,retries:10,requestTimeoutMs:1e4})}catch(n){e.error({err:n},"Failed to report billable event")}}async fetchTestFragment(e){let t=await this.sendRequest(`/${D}/test-fragments/${e}`,{method:"GET",retries:3,requestTimeoutMs:1e4});return Zh.parse(t)}async patchTestFragment(e,t){await this.sendRequest(`/${D}/test-fragments/${e}`,{method:"PATCH",body:t,retries:3,requestTimeoutMs:1e4})}async getPastTestResults(e,t){let n=await this.sendRequest(`/${D}/results/tests/${e}`,{method:"POST",body:t,retries:3,requestTimeoutMs:1e4});return ef.parse(n)}async generateTestResultsUploadUrl(){let e=await this.sendRequest(`/${D}/results/uploads`,{method:"POST",retries:3,requestTimeoutMs:1e4});return tf.parse(e)}async startProcessingResultsUpload(e,t){let n=await this.sendRequest(`/${D}/results/uploads/${e}/process`,{method:"POST",body:t,retries:3,requestTimeoutMs:1e4});return rf.parse(n)}async fetchIconKnowledgeBase(e){try{let t=await this.sendRequest(`/${D}/knowledge-base/icons`,{method:"GET",retries:3,requestTimeoutMs:5e3});return hf.parse(t)}catch(t){return e.error({err:t},"Failed to fetch icon knowledge base"),null}}async saveNewIcons(e,t){try{await this.sendRequest(`/${D}/knowledge-base/icons`,{method:"POST",body:e,retries:3,requestTimeoutMs:5e3})}catch(n){t.error({err:n},"Failed to save new icons to icon knowledge base")}}async getMergeBaseCommitFromGithub(e,t,n,o){let i=new URLSearchParams;i.set("base",n),i.set("head",o);let a=await this.sendRequest(`/${D}/git/github/${e}/${t}/merge-base-commit?${i.toString()}`,{method:"GET",retries:3,requestTimeoutMs:1e4});return Pi.parse(a)}async getCommitFromGithub(e,t,n){let o=await this.sendRequest(`/${D}/git/github/${e}/${t}/commits/${n}`,{method:"GET",retries:3,requestTimeoutMs:1e4});return Pi.parse(o)}async getMergedBranchFromGithub(e,t,n,o){let i=encodeURIComponent(n),a=await this.sendRequest(`/${D}/git/github/${e}/${t}/${i}/${o}/merged-branch`,{method:"GET",retries:3,requestTimeoutMs:1e4});return Au.parse(a)}async getMergeBaseCommitFromGitlab(e,t,n){let o=new URLSearchParams;o.set("base",t),o.set("head",n);let i=encodeURIComponent(e),a=await this.sendRequest(`/${D}/git/gitlab/${i}/merge-base-commit?${o.toString()}`,{method:"GET",retries:3,requestTimeoutMs:5e3});return Pi.parse(a)}async getCommitFromGitlab(e,t){let n=encodeURIComponent(e),o=await this.sendRequest(`/${D}/git/gitlab/${n}/commits/${t}`,{method:"GET",retries:3,requestTimeoutMs:1e4});return Pi.parse(o)}async getMergedBranchFromGitlab(e,t,n){let o=encodeURIComponent(t),i=encodeURIComponent(e),a=await this.sendRequest(`/${D}/git/gitlab/${i}/${o}/${n}/merged-branch`,{method:"GET",retries:3,requestTimeoutMs:1e4});return Au.parse(a)}async getAgentConfig(){let e=await this.sendRequest(`/${D}/web-agent/agent-config`,{method:"GET",retries:3,requestTimeoutMs:5e3});return Vp.record(Vp.string(),Vp.string()).parse(e)}async getQuarantinedTests(){let e=await this.sendRequest(`/${D}/quarantine`,{method:"GET"});return nf.parse(e)}async quarantineTest(e,t,n){await this.sendRequest(`/${D}/quarantine`,{method:"POST",body:{testId:e.id,testName:e.name,reason:t,...n??{}},retries:3,requestTimeoutMs:1e4})}async unquarantineTest(e,t,n){await this.sendRequest(`/${D}/quarantine/${e.id}`,{method:"DELETE",body:{testName:e.name,reason:t,...n??{}},retries:3,requestTimeoutMs:1e4})}async createAndroidEmulator(e){let t=await this.sendRequest(`/${D}/limbar/android`,{method:"POST",retries:3,body:e,requestTimeoutMs:9e4,initialRetryDelayMs:5e3,maxRetryDelayMs:15e3});return of.parse(t)}async extendAndroidEmulatorTtl(e){try{await this.sendRequest(`/${D}/limbar/android/${e}/keepalive`,{method:"POST",retries:3,requestTimeoutMs:15e3})}catch{}}async generateAndroidAssetUrls({channel:e,tag:t,md5:n}){let o={channel:e,tag:t,md5:n},i=await this.sendRequest(`/${D}/limbar/android/upload-url`,{method:"POST",retries:3,body:o,requestTimeoutMs:15e3,logResponse:!0});return af.parse(i)}async deleteAndroidEmulator(e){await this.sendRequest(`/${D}/limbar/android/${e}`,{method:"DELETE",retries:3,requestTimeoutMs:3e4})}async getAndroidAssets(){let e=await this.sendRequest(`/${D}/limbar/assets`,{method:"GET",retries:3,requestTimeoutMs:1e4});return sf.parse(e)}async deleteAndroidAsset(e,t){await this.sendRequest(`/${D}/limbar/assets/${e}/${t}`,{method:"DELETE",retries:3,requestTimeoutMs:1e4})}};async function jp(r){let e=process.versions.node,t=parseInt(e.split(".")[0]);(isNaN(t)||t<18)&&(R.error(`Node.js version 20 or higher is required to run the CLI. Detected: ${process.versions.node}.`),process.exit(1)),R.debug(`Identified node version ${e}`);let n=await r.client.getAuthInfo();return R.debug("Got auth info from API"),n}var ec=class{apiClient;constructor(e){this.apiClient=e}async reportBillableEvents(e,t){await this.apiClient.reportBillableEvents(e,t)}};var jo=class{constructor(e,t){this.client=e;this.orgId=t}async acquireCacheLock(e,t){return this.client.acquireCacheLock(e,t)}async uploadScreenshot(e){return(await this.client.uploadScreenshot({screenshot:e.toString("base64")})).key}async releaseCacheLock(e){return this.client.releaseCacheLock(e)}async deleteCacheResult(e){return this.client.deleteCacheResult(e)}async setCacheResult(e){return this.client.setCacheResult(e)}async getCacheResult(e){return this.client.getCacheResult(e)}fetchIconKnowledgeBase(e){return this.client.fetchIconKnowledgeBase(e)}saveNewIcons(e,t){return this.client.saveNewIcons(e,t)}};import{Faker as Sk,en as yk}from"@faker-js/faker";var Wo="v1",$o=class{httpClient;fakerInstance;type="API_CLIENT";sms={send:this.sendSms.bind(this),fetchLatest:this.fetchLatestSms.bind(this)};email={send:this.sendEmail.bind(this),fetchLatest:this.fetchLatestEmail.bind(this),fetchAll:this.fetchAllEmails.bind(this)};ai={generate:this.sendAiGenerate.bind(this)};constructor(e){this.httpClient=e.httpClient,e.fakerSeed&&(this.fakerInstance=new Sk({locale:yk}),this.fakerInstance.seed(e.fakerSeed))}async sendAiGenerate(e){let t=typeof e=="string"?{input:e}:e;return this.httpClient.sendRequest(`/${Wo}/tools/ai/generate`,{method:"POST",body:t}).catch(n=>{throw n instanceof er?new Error(n.rawError):new Error(`Failed to send AI generation: ${n.message}`)})}async sendSms(e){return this.httpClient.sendRequest(`/${Wo}/tools/sms/send`,{method:"POST",body:e}).then(()=>{}).catch(t=>{throw t instanceof er?new Error(t.rawError):new Error(`Failed to send sms: ${t.message}`)})}async fetchLatestSms(e){return this.httpClient.sendRequest(`/${Wo}/tools/sms/fetchLatest`,{method:"POST",body:e}).catch(t=>{throw t instanceof er?new Error(t.rawError):t})}async sendEmail(e){return this.httpClient.sendRequest(`/${Wo}/tools/email/send`,{method:"POST",body:e}).then(()=>{}).catch(t=>{throw t instanceof er?new Error(t.rawError):new Error(`Failed to send email: ${t.message}`)})}async fetchAllEmails(e){return this.httpClient.sendRequest(`/${Wo}/tools/email/fetchAll`,{method:"POST",body:e}).catch(t=>{throw t instanceof er?new Error(t.rawError):new Error(`Failed to fetch all emails: ${t.message}`)})}async fetchLatestEmail(e){return this.httpClient.sendRequest(`/${Wo}/tools/email/fetchLatest`,{method:"POST",body:e}).catch(t=>{throw t instanceof er?new Error(t.rawError):new Error(`Failed to fetch latest emails: ${t.message}`)})}};import{z as Ek}from"zod";var $n=class extends Tr{agentConfig;constructor(e,t){super(t),this.agentConfig=e}getAgentConfig(){return this.agentConfig}async rankChunksWithAi(e,t){let n={...e,loggerTags:t.loggerTags},o=await this.sendRequest(`/${D}/web-agent/recommend-chunks-ai`,{method:"POST",body:n,signal:t.abortSignal});return Tg.parse(o)}async rankChunksWithRag(e,t){let n=await this.sendRequest(`/${D}/web-agent/recommend-chunks`,{method:"POST",body:{cliVersion:fa,...e},signal:t.abortSignal});return bg.parse(n)}async getScreenshotFromS3(e){let t=await this.sendRequest(`/${D}/s3/visual-diff-screenshot`,{method:"POST",body:{url:e}});return Ek.string().parse(t)}async getElementLocation(e,t){let n={...e,disableCache:t.disableCache,loggerTags:t.loggerTags,useMemory:t.useMemory,agentConfigVersion:this.agentConfig?.locator},o=await this.sendRequest(`/${D}/web-agent/locate-element`,{method:"POST",body:n,signal:t.abortSignal});return kh.parse(o)}async getAssertionResult(e,t){let n={...e,disableCache:!!t.disableCache,useConsensus:!!t.useConsensus,attemptNumber:t.attemptNumber,loggerTags:t.loggerTags,useMemory:t.useMemory,agentConfigVersion:this.agentConfig?.assertion},o=await this.sendRequest(`/${D}/web-agent/assertion`,{method:"POST",body:n,signal:t.abortSignal});return Eu.parse(o)}async getLintStepResult(e,t){let n={...e,disableCache:!!t.disableCache,loggerTags:t.loggerTags},o=await this.sendRequest(`/${D}/web-agent/lint/step`,{method:"POST",body:n,signal:t.abortSignal});return Dh.parse(o)}async getLintMcpCopilotMessageResult(e,t){let n={message:e.message,disableCache:!!t.disableCache,loggerTags:t.loggerTags},o=await this.sendRequest(`/${D}/web-agent/lint/mcp-copilot`,{method:"POST",body:n,signal:t.abortSignal});return Nh.parse(o)}async getVisualAssertionResult(e,t){let n={...e,disableCache:!!t.disableCache,useConsensus:!!t.useConsensus,attemptNumber:t.attemptNumber,loggerTags:t.loggerTags,useMemory:t.useMemory,agentConfigVersion:this.agentConfig?.["visual-assertion"]},o=await this.sendRequest(`/${D}/web-agent/visual-assertion`,{method:"POST",body:n,signal:t.abortSignal});return Eu.parse(o)}async getAiActionCommand(e,t){let n=await this.sendRequest(`/${D}/web-agent/next-command-dynamic`,{method:"POST",body:{...e,disableCache:t.disableCache,loggerTags:t.loggerTags},signal:t.abortSignal});return Lh.parse(n)}async getMultiturnAiActionCommand(e,t){return await this.sendRequest(`/${D}/web-agent/ai-action/next-command`,{method:"POST",body:{...e,disableCache:t.disableCache,loggerTags:t.loggerTags},signal:t.abortSignal})}async getMultiturnAiActionEvaluation(e,t){let n=await this.sendRequest(`/${D}/web-agent/ai-action/evaluate`,{method:"POST",body:{...e,disableCache:t.disableCache,loggerTags:t.loggerTags},signal:t.abortSignal});return Lc.parse(n)}async getReverseMappedDescription(e,t){let n=await this.sendRequest(`/${D}/web-agent/reverse-mapped-description`,{method:"POST",body:{...e,disableCache:t.disableCache,loggerTags:t.loggerTags},signal:t.abortSignal});return Uh.parse(n)}async getTextExtraction(e,t){let n={...e,disableCache:t.disableCache,loggerTags:t.loggerTags,agentConfigVersion:this.agentConfig?.["text-extraction"]},o=await this.sendRequest(`/${D}/web-agent/text-extraction`,{method:"POST",body:n,signal:t.abortSignal});return Pc.parse(o)}async getPageSummary(e,t){let n={...e,disableCache:t.disableCache,loggerTags:t.loggerTags},o=await this.sendRequest(`/${D}/web-agent/page-summary`,{method:"POST",body:n,signal:t.abortSignal});return Zm.parse(o)}async getTestResultClassification(e,t){let n=await this.sendRequest(`/${D}/web-agent/result-classification`,{method:"POST",body:{...e,loggerTags:t.loggerTags},signal:t.abortSignal});return Fc.parse(n)}async getExtractedKeywords(e,t){let n=await this.sendRequest(`/${D}/web-agent/extract-keywords`,{method:"POST",body:{goal:e,disableCache:t.disableCache,context:e},signal:t.abortSignal});return Og.parse(n)}async getAutohealingProposal(e,t){let n=await this.sendRequest(`/${D}/web-agent/autoheal-section`,{method:"POST",body:{...e,loggerTags:t.loggerTags},signal:t.abortSignal});return Ym.parse(n)}async getFailureRecoveryProposal(e,t){let n=await this.sendRequest(`/${D}/web-agent/failure-recovery`,{method:"POST",body:{...e,loggerTags:t.loggerTags},signal:t.abortSignal});return Qm.parse(n)}async getFailureRecoveryPlan(e,t){let n=await this.sendRequest(`/${D}/web-agent/failure-recovery-plan`,{method:"POST",body:{...e,loggerTags:t.loggerTags},signal:t.abortSignal});return Jm.parse(n)}async getIframeRegex(e,t){let n=await this.sendRequest(`/${D}/web-agent/iframe-regex`,{method:"POST",body:e,signal:t.abortSignal});return vm.parse(n)}};var qo=class extends Tr{generator;constructor(e,t){super(e),this.generator=t}async runTemplateMatching(e,t={}){let n=await this.sendRequest(`/${D}/web-agent/template-matching`,{method:"POST",body:e,signal:t?.signal});return Am.parse(n)}async constructIframeRegex(e,t={}){return this.generator.getIframeRegex(e,{abortSignal:t.signal})}};function hA(r,e,t){return fetch(r,{method:"PUT",body:t,headers:{"Content-Type":e}})}var tc=class{constructor(e){this.client=e}async uploadResultsArchive(e,t){let{uploadUrl:n,id:o}=await this.client.generateTestResultsUploadUrl(),i=await hA(n,"application/zip",t);if(!i.ok)throw new Error(`Failed to upload test results: ${await i.text()}`);let{runGroupId:a}=await this.client.startProcessingResultsUpload(o,{runGroupId:e});return a}};var Ko=class extends Tr{constructor(e){super(e)}async getElementLocation(e,t){let n={...e,loggerTags:t.loggerTags},o=await this.sendRequest(`/${D}/mobile-agent/locate-element`,{method:"POST",body:n,signal:t.abortSignal});return Ng.parse(o)}async evaluateAssertion(e,t){let n={...e,loggerTags:t.loggerTags},o=await this.sendRequest(`/${D}/mobile-agent/assertion`,{method:"POST",body:n,signal:t.abortSignal});return Ug.parse(o)}};function rc({orgId:r,client:e,gitMetadata:t,alwaysSaveCache:n,noCache:o}){return o?new fs:new Wp(r,e,t,n)}var Wp=class{constructor(e,t,n,o){this.orgId=e;this.client=t;let{gitBranchName:i,gitProtectedBranches:a}=n;this.cacheHeaders=bu(n),o?this.writeCaches=!0:i?this.writeCaches=!a.includes(i):this.writeCaches=!0}cacheHeaders;writeCaches;async saveEntries({entries:e,testId:t,logger:n}){if(!this.writeCaches){n.debug("Skipping cache storage because branch is protected");return}try{await this.client.updateMobileStepCaches({entries:e,testId:t},this.cacheHeaders)}catch(o){n.error({err:o},"Failed to save mobile step cache entries")}}async resolveEntries(e){let{steps:t}=e.stepLists,n=await this.client.getMobileStepCacheForTest({testId:e.testId},this.cacheHeaders);if(!this.writeCaches){e.logger.debug("Skipping mobile cache last used at update because branch is protected");return}for(let i of[t])i&&_u({steps:i,stepCacheEntries:n,logger:e.logger});let{cachesToSave:o}=await Rn({steps:t,cacheCreationParams:{testId:e.testId,orgId:this.orgId}});this.client.updateMobileStepCaches({entries:o,testId:e.testId},this.cacheHeaders)}};import nc from"path";function bk(r){let e=new fA,t=nc.join(r,"metadata.json"),n=Oi.parse(JSON.parse($p.readFileSync(t,"utf-8")));e.addLocalFile(t);for(let o of $p.readdirSync(nc.join(r,"runs"))){if(!o.endsWith(".zip"))continue;let i=o.replace(/\.zip$/,""),a=new fA(nc.join(r,"runs",o));for(let l of a.getEntries())l.isDirectory||e.addFile(nc.join("runs",i,l.entryName),l.getData())}return{runGroupId:n.id,buffer:e.toBuffer()}}async function oc(r){let{client:e,consoleLogger:t,resultsPath:n}=r;if(!$p.existsSync(n)){t.warn("Results path does not exist, skipping upload.");return}let o=new tc(e);try{let{runGroupId:i,buffer:a}=bk(n),l=await o.uploadResultsArchive(i,a),c=`${e.getAppUrl()}/run-groups/${l}`;t.success(`Successfully uploaded test results. Once processed, your results can be found at ${c}`);return}catch(i){let a;i instanceof Error?a=i.message:typeof i=="string"?a=i:a="Unknown error",t.error(`Failed to upload test results: ${a}.`);return}}import Tk from"adm-zip";import yt from"fs";import rr from"path";var Sa=class r{constructor(e){this.filePath=e;yt.rmSync(this.filePath,{recursive:!0,force:!0}),yt.mkdirSync(this.filePath,{recursive:!0})}cd(e){return new r(rr.join(this.filePath,e))}mkdir(e){yt.mkdirSync(rr.join(this.filePath,e),{recursive:!0})}readFile(e){let t=rr.join(this.filePath,e);if(yt.existsSync(t))return yt.readFileSync(t)}storeFile(e){let{name:t,contents:n}=e,o=rr.join(this.filePath,t);try{yt.writeFileSync(o,n)}catch{}}createRunArchive(e){return new qp(rr.join(this.filePath,"runs"),e)}},qp=class{constructor(e,t){this.filePath=e;this.tempPath=rr.join(e,`.${t}`),this.finalPath=rr.join(e,`${t}.zip`),yt.rmSync(this.tempPath,{recursive:!0,force:!0}),yt.rmSync(this.finalPath,{recursive:!0,force:!0}),yt.mkdirSync(this.tempPath,{recursive:!0})}tempPath;finalPath;readFile(e){let t=rr.join(this.tempPath,e);if(yt.existsSync(t))return yt.readFileSync(t)}mkdir(e){yt.mkdirSync(rr.join(this.tempPath,e),{recursive:!0})}cd(e){return new Sa(rr.join(this.tempPath,e))}storeFile(e){let{name:t,contents:n}=e,o=rr.join(this.tempPath,t);yt.writeFileSync(o,n)}close(){let e=new Tk;e.addLocalFolder(this.tempPath,void 0,n=>n!==".DS_Store");let t=e.toBuffer();yt.writeFileSync(this.finalPath,t),yt.rmSync(this.tempPath,{recursive:!0,force:!0})}};import pc from"fs";import MA from"body-parser";import Bk from"cors";import zk from"dedent";import{Router as wk}from"express";import Et from"fs";import{globSync as Ck}from"glob";import tt from"path";import Yp from"fs";import vk from"path";var Ak=new Al(30,60*1e3),Qp="https://api.momentic.ai",Xp,yA=r=>{Qp=r},Zp=()=>Qp,em=()=>Xp;var Yo,Jp,SA,EA=async r=>{if(Xp&&Yo&&SA)return Yo;let e=new tr({baseUrl:Qp,apiKey:r,logger:R});Xp=e;try{let t=await e.getAuthInfo();return Yo=t.orgId,Jp=t.userId,SA=r,Yo}catch(t){throw new Error(`Error checking API key against server: ${t}`)}},ya=()=>{if(!Yo)throw new Error("Your organization ID is invalid.");return Yo},ic=()=>{if(!Jp)throw new Error("Your user ID is invalid.");return Jp};var tm,Kp,bA=(r,e)=>{tm=r,Kp?.abort(),Kp=new AbortController;let t=Kp.signal,n=[r.configFilePath];r.config.environments?.forEach(o=>{if(!o.envFile)return;let i=vk.resolve(r.rootDir,o.envFile);try{if(Yp.lstatSync(i).isSymbolicLink())return;Yp.existsSync(i)&&n.push(i)}catch(a){R.warn({err:a},`Failed to check if env file ${i} exists`)}});try{Rk({filesToWatch:n,revalidator:e,signal:t,project:r})}catch(o){R.error({err:o},"Failed to start config file watchers")}},Xe=()=>tm;function Rk({filesToWatch:r,revalidator:e,signal:t,project:n}){r.forEach(o=>{Yp.watch(o,{signal:t,persistent:!1,recursive:!1},(i,a)=>{a&&(Ak.increment("setLocalProject")&&R.warn(`A file change under the ${n.rootDir} directory has caused Momentic to reload its configuration more than 30 times in the last minute. Rapid changes to files may indicate your momentic.config.yaml 'include' glob is incorrect. Please ensure temporary, library, and auto-generated files are not included in Momentic's context.`),tm=e(n.configFilePath))})})}function Je(r){return function(...e){let t=e[e.length-1],n=r(...e);Promise.resolve(n).catch(t)}}var ba=wk();function Ea(r){let e=Xe(),t=tt.dirname(e.configFilePath);return tt.join(t,...r)}function xk(r){let e=Xe(),t=tt.dirname(e.configFilePath),n=tt.relative(t,r);return n?n.split(tt.sep):[]}function _k(r,e){let t=Et.statSync(r),n=xk(r);return mu.parse({name:e,absolutePath:r,relativePath:n.join(tt.sep),pathSegments:n,isDirectory:t.isDirectory(),size:t.size,createdAt:t.birthtime,modifiedAt:t.mtime,accessedAt:t.atime})}ba.post("/",Je(async(r,e,t)=>{let n;try{n=Eh.parse(r.body).pathSegments}catch(d){e.status(400).json({error:`Failed to parse folder read body: ${d}`});return}let o=Ea(n);if(!Et.existsSync(o)){e.status(404).json({error:`Path not found: ${n.join(tt.sep)}`});return}if(!Et.statSync(o).isDirectory()){e.status(400).json({error:`Path is not a directory: ${n.join(tt.sep)}`});return}let a=Xe(),l=Array.from(a.config.exclude??[]).concat(cs),s=Ck("*",{absolute:!1,cwd:o,ignore:l,dotRelative:!1,maxDepth:1,nodir:!1}).map(d=>{let p=tt.join(o,d);return _k(p,d)}),u={absolutePath:o,pathSegments:n,contents:s};e.status(200).json(u)}));ba.put("/",Je(async(r,e,t)=>{let n;try{n=bh.parse(r.body).pathSegments}catch(a){e.status(400).json({error:`Failed to parse folder create body: ${a}`});return}let o=Ea(n);if(Et.existsSync(o)){e.status(200).json({success:!0,message:`Folder already exists: ${n.join(tt.sep)}`,pathSegments:n});return}Et.mkdirSync(o,{recursive:!0});let i={success:!0,message:`Folder created: ${n.join(tt.sep)}`,pathSegments:n};e.status(201).json(i)}));ba.patch("/",Je(async(r,e,t)=>{let n,o;try{let s=Th.parse(r.body);n=s.pathSegments,o=s.newPathSegments}catch(s){e.status(400).json({error:`Failed to parse folder update body: ${s}`});return}let i=Ea(n),a=Ea(o);if(!Et.existsSync(i)){e.status(400).json({error:`Folder not found: ${n.join(tt.sep)}`});return}if(Et.existsSync(a)){e.status(400).json({error:`Destination already exists: ${o.join(tt.sep)}`});return}let l=tt.dirname(a);Et.existsSync(l)||Et.mkdirSync(l,{recursive:!0}),Et.renameSync(i,a);let c={success:!0,message:`Folder moved from ${n.join(tt.sep)} to ${o.join(tt.sep)}`,pathSegments:o};e.status(200).json(c)}));ba.delete("/",Je(async(r,e,t)=>{let n,o=!0;try{let c=vh.parse(r.body);n=c.pathSegments,o=c.recursive??!0}catch(c){e.status(400).json({error:`Failed to parse folder delete body: ${c}`});return}let i=Ea(n);if(!Et.existsSync(i)){e.status(200).json({success:!0,message:`Folder not found: ${n.join(tt.sep)}`,pathSegments:n});return}if(!Et.statSync(i).isDirectory()){e.status(400).json({error:`Path is not a directory: ${n.join(tt.sep)}`});return}if(o)Et.rmSync(i,{recursive:!0,force:!0});else{if(Et.readdirSync(i).length>0){e.status(409).json({error:`Cannot delete non-empty directory without recursive flag: ${n.join("/")}`});return}Et.rmdirSync(i)}let l={success:!0,message:`Folder deleted: ${n.join("/")}`,pathSegments:n};e.status(200).json(l)}));var rm=ba;import Gk from"events";import IA,{Router as Hk}from"express";import Vk from"http";import jk from"path";var ac=class{sessions=new Map;registerSession(e,t){this.sessions.set(e,t)}getSession(e){return this.sessions.get(e)}async removeSession(e,t){let n=this.sessions.get(e);if(n)try{await n.cleanup?.(),t.info({sessionId:e,emulatorName:n.emulatorName},"Android emulator cleaned up")}catch(o){t.error({err:o},"Error during Android session cleanup")}finally{this.sessions.delete(e)}}async removeAllSessions(e){let t=Array.from(this.sessions.keys());await Promise.all(t.map(n=>this.removeSession(n,e)))}};var TA=new ac;import{Router as Pk}from"express";import{existsSync as Ok}from"fs";import Lk from"path";import{hostname as Mk}from"os";var Ik="0.0.20",bt=zl({app:"mobile-desktop-server",hostname:Mk(),disableConsoleLogs:!0}).child({cliVersion:Ik});(async()=>{try{let r=await Up(bt);r.gitBranchName&&bt.addBinding("branch",r.gitBranchName)}catch{}})();var nm=Pk();nm.get("/",Je(async(r,e)=>{let t=em();if(!t){e.status(500).json({message:"API client not initialized"});return}let n=await t.getAndroidAssets();e.status(200).json(n)}));nm.post("/upload-url",Je(async(r,e)=>{let t;try{t=xh.parse(r.body)}catch(i){e.status(400).json({error:`Invalid request body: ${i}`});return}let n=em();if(!n){e.status(500).json({error:"API client not initialized"});return}let o=Lk.resolve(t.filePath);if(!Ok(o)){e.status(400).json({error:`File not found: ${o}`});return}await Ca({tag:t.tag,channel:t.channel,filePath:o,apiClient:n,logger:bt}),e.sendStatus(204)}));var vA=nm;import{Router as Nk}from"express";var AA=Nk();AA.get("/",Je(async(r,e)=>{let t=Xe(),n=Zt(t),o=new Set;n?.tests&&Object.values(n.tests).forEach(c=>{c.labels?.forEach(s=>o.add(s))});let i=Array.from(o).sort(),a=Object.values(n.mobileTests),l={labels:i,modules:[],tests:a};e.status(200).json(l)}));var RA=AA;import{Router as Dk}from"express";var wA=Dk();wA.get("/",(r,e)=>{e.status(200).json({userId:ic(),orgId:ya()})});var CA=wA;import{Router as kk}from"express";var sc=kk();async function Uk(r){return(await cA(r,bt)).map(n=>{let o=r.mobileModules[n.moduleId];if(!o){R.warn(`Found a dangling mobile module with ID ${n.moduleId} that could not be found on disk.`);return}return{...o,content:n}}).filter(n=>n!==void 0)}sc.get("/",Je(async(r,e)=>{let t=Xe(),n=Zt(t),o=await Uk(n);e.status(200).json(o)}));sc.get("/:moduleId",Je(async(r,e)=>{if(!r.params.moduleId){e.status(400).json({error:"Missing moduleId in url path."});return}let t=Zt(Xe()),n=t.mobileModules[r.params.moduleId];if(!n){e.status(404).json({error:"Mobile module not found."});return}try{let o=await Bp(n,t,R);e.json(o)}catch(o){e.status(400).json({err:o})}}));sc.patch("/:moduleId/metadata",Je(async(r,e)=>{if(!r.params.moduleId){e.status(400).json({error:"Missing moduleId in url path."});return}let t;try{t=_h.parse(r.body)}catch(i){e.status(400).json({error:`Invalid request body: ${i}`});return}let n=Xe(),o=Zt(n);lA({moduleId:r.params.moduleId,patch:t,momenticFiles:o,logger:R,project:n}),e.status(201).json({message:"ok"})}));var xA=sc;import{Router as Fk}from"express";import om from"path";var lc=Fk();lc.patch("/:testPath",Je(async(r,e)=>{let t=r.params.testPath;if(!t){e.status(400).json({error:"Missing testPath in path"});return}let n;try{n=Ch.parse(r.body)}catch(c){e.status(400).json({error:`Invalid request body: ${c}`});return}if(n.steps===void 0&&n.settings===void 0){e.status(400).json({error:"At least one of steps or settings is required"});return}let o=Xe(),i=t.endsWith(".test.yaml")?t:`${t}.test.yaml`,a=Zt(o);await dA({filePath:i,steps:n.steps,settings:n.settings,folder:o.rootDir,project:o,momenticFiles:a});let l={message:"ok"};e.status(200).json(l)}));lc.post("/",Je((r,e)=>{let t;try{t=wh.parse(r.body)}catch(g){e.status(400).json({error:`Invalid request body: ${g}`});return}let{name:n,description:o,settings:i,pathSegments:a}=t;if(!n||typeof n!="string"){e.status(400).json({error:"Missing or invalid 'name' in body"});return}try{Xc(n)}catch(g){e.status(400).json({error:g.message});return}let l=Xe(),c=om.join(l.rootDir,...a),{fullPath:s,testId:u}=uA({name:n,description:o,steps:[],settings:i,folder:c}),d=om.basename(s),p=om.relative(l.rootDir,s),m={id:u,fileName:d,fullPath:s,relativeFilePath:p};e.status(201).json(m)}));lc.get("/:fileName",Je(async(r,e)=>{let t=r.params.fileName;if(!t){e.status(400).json({error:"Missing fileName in path"});return}let n=t.endsWith(".test.yaml")?t:`${t}.test.yaml`,o=Xe(),i=Zt(o),l=await Zl(n,bt,i);e.status(200).json(l)}));var _A=lc;var cc=class extends jo{constructor(t,n){super(t,n);this.client=t;this.orgId=n}async fetchEnvironment(t,n){let o=Xe();return Kl(t,o,R)}};var PA="10mb";async function OA(r){let{serverPort:e,apiKey:t,momenticServerUrl:n,staticDir:o,initialProject:i,logLevel:a,alwaysSaveCache:l,noCache:c}=r;n&&yA(n),await EA(t);let s=ya(),u=ic(),d=r.logger.child({orgId:s,userId:u});bA(i,A=>ga({configFilePath:A}));let p=IA();p.use(Bk()),p.use(MA.json({limit:PA})),p.use(MA.urlencoded({extended:!1,limit:PA}));let m=Hk();if(m.use("/folders",rm),m.use("/entities",RA),m.use("/identify",CA),m.use("/mobile-tests",_A),m.use("/mobile-modules",xA),m.use("/assets",vA),p.use("/api",m),p.use((A,T,x)=>{R.debug({url:A.url,path:A.path,query:A.query,method:A.method,body:A.body,headers:A.rawHeaders,client:A.ip},"Incoming request on mobile-desktop-server"),T.on("close",()=>{T.statusCode>=400&&(R.error({url:A.url,method:A.method,statusCode:T.statusCode},"Request completed in error on mobile-desktop-server"),bt.error({url:A.url,method:A.method,statusCode:T.statusCode},"Request completed in error on mobile-desktop-server"))}),x()}),p.use((A,T,x,N)=>{if(A instanceof Error&&A.message.includes("BadRequestError: request aborted")){x.status(400).send("Client disconnected");return}R.error({stack:A.stack,msg:A.message,err:A,url:T.url,method:T.method},"Unhandled exception leading to 500 on mobile-desktop-server"),bt.error({stack:A.stack,msg:A.message,err:A,url:T.url,method:T.method},"Unhandled exception leading to 500 on mobile-desktop-server"),x.status(500).send(`Internal Server Error: ${A.message}`)}),o){let A=IA.static(o,{setHeaders:T=>{T.setHeader("Cache-Control","no-cache")},redirect:!1});p.use(A),p.use("*",(T,x)=>{x.sendFile(jk.join(o,"index.html"))})}let g=Vk.createServer(p),h=`http://localhost:${e}`;await new Promise(A=>{try{g.listen(e,()=>{d.info(`Mobile desktop server is running at ${h}`),A()})}catch(T){T.message.includes("EADDRINUSE")?Wk(e):R.error(`An unexpected error occurred while starting the server: ${T.message}`),process.exit(1)}});let E={type:"API_KEY",baseUrl:Zp(),apiKey:t,logger:d},b=new tr(E),{dispose:v}=Nv({baseServer:g,logger:d,authorization:E,globalStateManager:TA,getOrgId:()=>ya(),androidDriverFactory:async({socket:A,logger:T,creationOpts:x})=>{let N=Math.floor(Math.random()*1e4)+4e4,U=await ql(N,"appium");return wa({logger:T,logLevel:a,apiClient:b,creationOpts:x,socket:A,appiumPort:U,onStatusUpdate:Y=>{A.emit("connectionStatusUpdate",{message:Y})}})},mobileGeneratorFactory:async A=>new Ko({baseUrl:Zp(),apiKey:t,logger:d}),browserGeneratorFactory:async A=>new $n({},E),browserEnricherFactory:async A=>new qo(E,new $n({},E)),storageFactory:async A=>new cc(b,A),cacheStorageFactory:async A=>{let T=Xe(),x=await Xl(d,b,T);return rc({orgId:A,client:b,gitMetadata:x,noCache:c,alwaysSaveCache:l})},localToolsFactory:async()=>new $o({httpClient:b,fakerSeed:void 0}),keepSessionAlive:A=>b.extendAndroidEmulatorTtl(A),settingsFactory:async()=>({emulator:Xe().config.emulator})});process.once("SIGUSR2",async()=>{return;try{await v(),await Mt.flush()}catch(A){R.error({err:A},"Error during session dispose on SIGUSR2")}try{g.close(()=>{process.kill(process.pid,"SIGUSR2")})}catch{process.kill(process.pid,"SIGUSR2")}}),process.once("SIGTERM",async()=>{R.info("SIGTERM in Momentic mobile app received");try{await v(),await Mt.flush()}finally{g.close(()=>process.exit(0))}}),process.once("SIGINT",async()=>{R.info("SIGINT in Momentic mobile app received");try{await v(),await Mt.flush()}finally{g.close(()=>process.exit(0))}})}Gk.setMaxListeners(50);process.on("warning",r=>{bt.warn({err:r},`Node warning received on mobile-desktop-server: ${r.message}`)});process.on("uncaughtException",r=>{bt.error({err:r},"Uncaught exception on mobile-desktop-server"),R.error(`Oh no! The Momentic mobile desktop app encountered a fatal error \u{1F61E}. Error logs: ${r.message}`)});process.on("unhandledRejection",r=>{bt.error({reason:`${r}`,stack:r?.stack},"Uncaught exception on mobile-desktop-server (promise rejection)"),R.error(`Oh no! The Momentic mobile desktop app encountered an asynchronous error \u{1F61E}. Error logs: ${r}`)});function Wk(r){R.error(zk`Port ${r} is already in use by another process. Please close the other process and try again.
4020
3970
  Using Bash on MacOS or Linux:
4021
3971
  lsof -t -i :58888 | xargs kill -9
4022
3972
 
4023
3973
  Using Command Prompt on Windows:
4024
3974
  for /f "tokens=5" %a in ('netstat -ano ^| findstr :58888') do taskkill /PID %a /F
4025
- `)}import Jbe,{multistream as Zbe}from"pino";import tve from"pino-pretty";import{PostHog as sve}from"posthog-node";import{PostHog as fve}from"posthog-node";import Y0 from"open";import ql from"path";import{fileURLToPath as X0}from"url";import{InvalidArgumentError as Om,Option as Tt}from"@commander-js/extra-typings";import{z as P0}from"zod";var zv=58890;function O0(r){let e=parseInt(r,10);if(isNaN(e))throw new Om("Not a number.");return e}var ia=new Tt("--api-key <key>","Momentic API key").env("MOMENTIC_API_KEY").argParser(r=>{if(!r)throw new Om("API key is required.");return r}).makeOptionMandatory(),Lm=new Tt("-c, --config <configPath>","Absolute or relative path to a Momentic configuration file."),aa=new Tt("--server <server>","Momentic server to use.").env("MOMENTIC_SERVER").default("https://api.momentic.ai").argParser(r=>{try{return P0.string().url().parse(r),r}catch{throw new Om("Not a valid URL.")}}),Nm=new Tt("-y, --yes","Skip all confirmation prompts.").env("CI"),Dm=new Tt("--save-cache","Always save updated step caches after successful test runs. By default, caches are not saved when running on protected branches, which are specified in your momentic.config.yaml.").env("CI"),km=new Tt("--disable-cache","Disable using step caches completely. Using this option may lead to non-deterministic behavior and significantly longer runtimes."),Um=new Tt("--tag <tag>","Tag identifier for the asset."),Gv=new Tt("--channel <channel>","Channel name for the asset."),Hv=new Tt("--channel <channel>","Channel name for the asset.").makeOptionMandatory(),Vv=new Tt("--env <env>","Environment to run all tests in (overrides test-level configuration)."),jv=new Tt("-p, --parallel <parallel>","The number of tests to run in parallel. Defaults to 1.").argParser(O0),Fm=new Tt("--output-dir <outputDir>","Output directory to store run artifacts such as screenshots, results, and logs."),Wv=new Tt("--upload-results","Upload test results to Momentic Cloud.").default(!1),Bm=new Tt("--log-level <logLevel>","Log level for Momentic and dependent services.").choices(["error","warn","info","debug"]),$v=new Tt("--ignore-quarantine","Run all tests even if they are quarantined. This is useful for validating that quarantined tests are fixed before moving them out of quarantine.").implies({skipQuarantined:!1,onlyQuarantined:!1});import{randomUUID as V0}from"crypto";import{existsSync as j0}from"fs";import Vl from"fs";import sa from"path";import{cwd as N0}from"process";import{gt as D0}from"semver";import k0 from"yaml";async function qv({tests:r,momenticFiles:e,project:t,yes:n,include:o,exclude:i,logger:a,quarantinedTestReasons:l}){let c=new Set;if(r&&r.length>0){let u=r.some(m=>Vl.existsSync(m)),d=N0();u?(d!==t.rootDir&&a.warn(`The current working directory ('${d}') is different from the project root directory ('${t.rootDir}'). All test path arguments will be resolved relative to the current working directory and only those tests matched by the project inclusion configuration will be ran. To avoid confusion, Momentic strongly recommends running the CLI from the project root directory or using substring filters rather than file paths.`),a.info(`Reading tests from the following local file paths:
3975
+ `)}import lU from"open";import mc from"path";import{fileURLToPath as cU}from"url";import{InvalidArgumentError as im,Option as Tt}from"@commander-js/extra-typings";import{z as $k}from"zod";var LA=58890;function qk(r){let e=parseInt(r,10);if(isNaN(e))throw new im("Not a number.");return e}var Ta=new Tt("--api-key <key>","Momentic API key").env("MOMENTIC_API_KEY").argParser(r=>{if(!r)throw new im("API key is required.");return r}).makeOptionMandatory(),am=new Tt("-c, --config <configPath>","Absolute or relative path to a Momentic configuration file."),va=new Tt("--server <server>","Momentic server to use.").env("MOMENTIC_SERVER").default("https://api.momentic.ai").argParser(r=>{try{return $k.string().url().parse(r),r}catch{throw new im("Not a valid URL.")}}),sm=new Tt("-y, --yes","Skip all confirmation prompts.").env("CI"),lm=new Tt("--save-cache","Always save updated step caches after successful test runs. By default, caches are not saved when running on protected branches, which are specified in your momentic.config.yaml.").env("CI"),cm=new Tt("--disable-cache","Disable using step caches completely. Using this option may lead to non-deterministic behavior and significantly longer runtimes."),um=new Tt("--tag <tag>","Tag identifier for the asset."),NA=new Tt("--channel <channel>","Channel name for the asset."),DA=new Tt("--channel <channel>","Channel name for the asset.").makeOptionMandatory(),kA=new Tt("--env <env>","Environment to run all tests in (overrides test-level configuration)."),UA=new Tt("-p, --parallel <parallel>","The number of tests to run in parallel. Defaults to 1.").argParser(qk),dm=new Tt("--output-dir <outputDir>","Output directory to store run artifacts such as screenshots, results, and logs."),FA=new Tt("--upload-results","Upload test results to Momentic Cloud.").default(!1),pm=new Tt("--log-level <logLevel>","Log level for Momentic and dependent services.").choices(["error","warn","info","debug"]),BA=new Tt("--ignore-quarantine","Run all tests even if they are quarantined. This is useful for validating that quarantined tests are fixed before moving them out of quarantine.").implies({skipQuarantined:!1,onlyQuarantined:!1});import{randomUUID as rU}from"crypto";import{existsSync as nU}from"fs";import mm from"fs";import Aa from"path";import{cwd as Yk}from"process";async function zA({tests:r,momenticFiles:e,project:t,yes:n,include:o,exclude:i,logger:a,quarantinedTestReasons:l}){let c=new Set;if(r&&r.length>0){let u=r.some(p=>mm.existsSync(p)),d=Yk();u?(d!==t.rootDir&&a.warn(`The current working directory ('${d}') is different from the project root directory ('${t.rootDir}'). All test path arguments will be resolved relative to the current working directory and only those tests matched by the project inclusion configuration will be ran. To avoid confusion, Momentic strongly recommends running the CLI from the project root directory or using substring filters rather than file paths.`),a.info(`Reading tests from the following local file paths:
4026
3976
  - ${r.join(`
4027
3977
  - `)}
4028
- `),r.forEach(m=>{if(!Vl.existsSync(m))throw new Error(`Path '${m}' does not exist.`);let p,g;try{p=Vl.statSync(m),g=p.isDirectory()}catch(f){a.warn({err:f},`Skipping path ${m} because it cannot be read`);return}let h=sa.resolve(m);Object.values(e.mobileTests).filter(f=>g?f.fullFilePath.startsWith(h):f.fullFilePath===h).forEach(f=>{c.add(f.fullFilePath)})})):(a.info("The arguments provided don't appear to be valid paths. Treating them as substrings instead... "),Object.values(e.mobileTests).forEach(m=>{r.some(p=>m.relativePath.includes(p))&&c.add(m.fullFilePath)}))}else{!n&&!await Rl("No test paths or substrings were provided. Do you want to run all tests?")&&(a.error("Cancelled by user."),process.exit(1));let u=Object.values(e.mobileTests);a.info(`Reading all ${u.length} mobile tests in the project from local disk.`),u.forEach(d=>{c.add(d.fullFilePath)})}for(let u of Array.from(c)){let d=sa.relative(t.rootDir,u);o&&!o.some(m=>new RegExp(m).test(d))&&c.delete(u),i&&i.some(m=>new RegExp(m).test(d))&&c.delete(u)}return(await Promise.all(Array.from(c).map(async u=>{try{let d=Vl.readFileSync(u,"utf-8").replace(/\r\n|\r/g,`
4029
- `),p=un.parse(k0.parse(d));D0(p.schemaVersion,ba)&&a.warn(`Test ${u} has schema version ${p.schemaVersion}, which is greater than what is currently supported by this SDK. Please update your momentic package version to avoid unexpected behavior.`);let g=sa.relative(t.rootDir,u),h=e.mobileTests[p.id]?.name??sa.basename(u,sa.extname(u));return{id:p.id,name:h,description:p.description,schemaVersion:p.schemaVersion,settings:p.settings,steps:p.steps,fullFilePath:u,relativeFilePath:g,quarantined:p.id in l,quarantinedReason:l[p.id]}}catch(d){a.error(`Failed to read and resolve mobile test at '${u}': ${d}`),process.exit(1)}}))).filter(u=>!!u)}import{cloneDeep as U0}from"lodash-es";async function Kv(r){let{inputs:e,fixtures:t,metadata:n,options:o}=r,{tracer:i,logger:a}=t,{runId:l}=n,{testDefinition:c,runSigIntHandlers:s}=e,u=new Date,d=await i.startRun({logger:a,testId:c.id,testName:c.name,runId:l,testDescription:c.description,schemaVersion:c.schemaVersion,originalSteps:{steps:U0(c.steps),beforeSteps:void 0,afterSteps:void 0},quarantined:c.quarantined,quarantinedReason:c.quarantinedReason}),m=a.child(d.loggerBindings||{}),p=1+(c.settings?.retries??1);try{for(let g=0;g<p;g++){let h=new Date,f=await F0({runTracer:d,testDefinition:c,metadata:n,constants:{attemptNumber:g,totalAttempts:p},fixtures:{...t,logger:m},inputs:e,options:o}),y=new Date;if(f.status!=="FAILED")return await d.finish({logger:a,...f,finishedAt:y}),{...f,startedAt:u,lastAttemptStartedAt:h,finishedAt:y,attempts:g+1,testMetadata:c,steps:c.steps,filePath:c.relativeFilePath,quarantined:c.quarantined,quarantinedReason:c.quarantinedReason};if(g!==p-1){a.warn("Retrying failed mobile run");continue}return a.error("Mobile test failed after all exhausting attempts"),await d.finish({logger:a,...f,finishedAt:y}),{...f,startedAt:u,lastAttemptStartedAt:h,finishedAt:y,attempts:g+1,testMetadata:c,steps:c.steps,filePath:c.relativeFilePath,quarantined:c.quarantined,quarantinedReason:c.quarantinedReason}}throw new Error("This code should not be reachable")}finally{s?.pop()}}async function F0(r){let{runTracer:e,testDefinition:t,metadata:n,constants:o,fixtures:i,inputs:a,options:l}=r,{attemptNumber:c,totalAttempts:s}=o,{orgId:u,gitMetadata:d}=n,{apiClient:m,logger:p,usageTracker:g}=i,{logUpdate:h,channel:f,tag:y,project:T,envOverride:v}=a,{alwaysSaveCache:R,noCache:b,logLevel:x}=l;c!==0&&h("RETRY",`attempt ${c}/${s}`);let N={...a.project.config.emulator,...t.settings?.emulator},k=kl({orgId:u,client:m,gitMetadata:d,alwaysSaveCache:R,noCache:b}),$=new Oo(m,u),De=new ko(m),ee={type:"API_KEY",baseUrl:m.baseUrl,apiKey:m.apiKey,logger:p},oe=new Ln({},ee),lt=new Do(ee,oe),M=new No({httpClient:m,fakerSeed:void 0}),V=Math.floor(Math.random()*1e4)+4e4,te=await xl(V,"appium"),_e=await la({apiClient:m,logger:p,logLevel:x,creationOpts:{apkToInstall:f?{channel:f,tag:y}:void 0,region:N.region},onStatusUpdate:Go=>{p.debug({status:Go},"Limbar emulator status update")},appiumPort:te}),ve=await e.startAttempt({emulatorName:_e.emulatorName}),Rt=p.child(ve.loggerBindings||{}),ct=v||t.settings?.defaultEnv,Ae;ct&&(Ae=_l(ct,T,Rt).variables);let Ve=new Qn({variablesFromEnvironment:Ae??{},envName:ct,testName:t.name}),Jr=await xo.init({driver:_e.driver,generator:De,logger:Rt,orgId:u,adbPort:_e.adbTunnelPort,options:{emulator:N},fixtures:{storage:$,browserEnricher:lt,browserGenerator:oe,localCodeEvalTools:M,testContext:Ve}}),dr;try{dr=await Tl({fixtures:{controller:Jr,logger:Rt,cacheStorage:k,usageTracker:g},inputs:{steps:t.steps,orgId:u,testMetadata:t},tracer:ve})}finally{await _e.cleanup()}return await ve.finish({logger:Rt,results:dr.results,status:dr.status}),dr}import{randomUUID as B0}from"crypto";import{debounce as z0}from"ts-debounce";var Fo="0.0.18";var jl="assets";function G0(r){switch(r){case"PASSED":return"SUCCESS";case"FAILED":return"FAILED";case"CANCELLED":return"CANCELLED";case"RUNNING":case"PENDING":case"RETRYING":case"WAITING_FOR_USER":return"RUNNING"}}function H0(r){switch(r){case"SUCCESS":return"PASSED";case"FAILED":return"FAILED";case"CANCELLED":return"CANCELLED";case"RUNNING":return"RUNNING";case"IDLE":return"PENDING"}}var zm=class{constructor(e,t,n,o){this.keepalive=e;this.testId=t;this.testName=n;this.diskStorage=o;this.commandTracer=new oo("command")}children=[];commandTracer;finished=!1;getParentStepIdChain(){return[]}attachBeforeScreenshot(e){let{snapshotId:t,screenshot:n}=e;this.diskStorage.storeFile({name:`${jl}/${t}.jpeg`,contents:n})}attachAfterScreenshot(e){let{snapshotId:t,screenshot:n}=e;this.diskStorage.storeFile({name:`${jl}/${t}.jpeg`,contents:n})}async finishInternal(e){this.finished||(this.finished=!0,await Promise.all(this.children.map(t=>t.finish({status:H0(e.status),finishedAt:e.finishedAt}))))}async finish(e){return await this.finishInternal({status:e.result.status,finishedAt:new Date(e.result.endTime)}),this.commandTracer.finish(),{trace:this.commandTracer.getRootSpan()}}startCommand(){return this.commandTracer}async startSubSteps(){let e=new Bo(this.keepalive,this.testId,this.testName,this.diskStorage);return this.children.push(e),e}},Bo=class{constructor(e,t,n,o){this.keepalive=e;this.testId=t;this.testName=n;this.diskStorage=o}children=[];finished=!1;async getScreenshot(e,t){return this.diskStorage.readFile(`${jl}/${t}.jpeg`)}getParentStepIdChain(){return[]}async startStep(e){this.keepalive();let t=new zm(this.keepalive,this.testId,this.testName,this.diskStorage);return this.children.push(t),t}async finish(e){this.finished||(this.finished=!0,await Promise.all(this.children.map(t=>t.finishInternal({status:G0(e.status),finishedAt:e.finishedAt}))))}},Gm=class{constructor(e,t,n,o,i,a){this.keepalive=e;this.testId=t;this.testName=n;this.runAttemptId=o;this.metadata=i;this.diskStorage=a;this.diskStorage.mkdir("assets")}finished=!1;children=[];get loggerBindings(){return{runAttemptId:this.runAttemptId}}attachNetworkLogs(e){let{logs:t}=e;this.diskStorage.storeFile({name:"network.har",contents:JSON.stringify(t,null,2)})}attachConsoleLogs(e){let{logs:t}=e;this.diskStorage.storeFile({name:"console.json",contents:JSON.stringify(t,null,2)})}async finish(e){if(this.finished)return;this.finished=!0;let{logger:t,status:n,results:o,beforeResults:i,afterResults:a}=e,l={...this.metadata,status:n,finishedAt:new Date,results:vl(o,t),beforeResults:i?vl(i,t):void 0,afterResults:a?vl(a,t):void 0};await Promise.all(this.children.map(c=>c.finish({status:l.status,finishedAt:l.finishedAt}))),this.diskStorage.storeFile({name:"metadata.json",contents:JSON.stringify(l,null,2)})}async startBeforeStepList(){let e=new Bo(this.keepalive,this.testId,this.testName,this.diskStorage);return this.children.push(e),e}async startMainStepList(){let e=new Bo(this.keepalive,this.testId,this.testName,this.diskStorage);return this.children.push(e),e}async startAfterStepList(){let e=new Bo(this.keepalive,this.testId,this.testName,this.diskStorage);return this.children.push(e),e}async getScreenshot(e,t){return this.diskStorage.readFile(`${jl}/${t}.jpeg`)}},Hm=class{constructor(e,t,n,o,i,a){this.client=e;this.testId=t;this.testName=n;this.runId=o;this.metadata=i;this.diskStorage=a}children=[];finished=!1;get loggerBindings(){return{runId:this.runId}}async finish(e){if(this.finished)return;this.finished=!0;let t={...this.metadata,finishedAt:e.finishedAt||new Date,status:e.status,failureDetails:e.failureDetails,failureReason:e.failureReason,flake:e.isFlake||!1,failureRecoveryDetails:e.failureRecoveryDetails};await Promise.all(this.children.map(n=>n.finish({logger:e.logger,status:t.status,results:[],beforeResults:[],afterResults:[]}))),this.diskStorage.storeFile({name:"metadata.json",contents:JSON.stringify(t,null,2)}),this.diskStorage.close()}async startAttempt(e){this.metadata.attempts=this.metadata.attempts+1,this.metadata.status="RUNNING",this.diskStorage.storeFile({name:"metadata.json",contents:JSON.stringify(this.metadata,null,2)});let t=this.diskStorage.cd(`attempts/${this.metadata.attempts}`),n=B0(),o={id:n,schemaVersion:Wn,runAttemptSchemaVersion:qh,startedAt:new Date,status:"RUNNING"};t.storeFile({name:"metadata.json",contents:JSON.stringify(o,null,2)});let i=z0(async()=>{await this.client.extendAndroidEmulatorTtl(e.emulatorName)},3e4,{maxWait:6e4}),a=new Gm(()=>void i(),this.testId,this.testName,n,o,t);return this.children.push(a),a}},Wl=class r{constructor(e,t,n,o,i){this.orgId=e;this.runGroupId=t;this.metadata=n;this.client=o;this.diskStorage=i}children=[];finished=!1;get loggerBindings(){return{orgId:this.orgId,runGroupId:this.runGroupId,branch:this.metadata.gitBranchName}}static async start({orgId:e,runGroupId:t,outputDir:n,client:o,gitMetadata:i,labels:a}){let l={...i,id:t,trigger:Dt.CLI,startedAt:new Date,status:"RUNNING",cliVersion:Fo,labels:a??[]},c=new ta(n);return c.storeFile({name:"metadata.json",contents:JSON.stringify(l,null,2)}),new r(e,t,l,o,c)}async finish(e){if(this.finished)return;this.finished=!0;let{status:t}=e,n={...this.metadata,status:t,updatedAt:new Date,finishedAt:new Date};await Promise.all(this.children.map(o=>o.finish({logger:e.logger,status:n.status,finishedAt:n.finishedAt}))),this.diskStorage.storeFile({name:"metadata.json",contents:JSON.stringify(n,null,2)})}async startRun(e){let t=this.diskStorage.createRunArchive(e.runId),n={stepsSnapshot:e.originalSteps.steps,runGroupId:this.runGroupId,testId:e.testId,testName:e.testName,testDescription:e.testDescription,labels:e.testLabels,trigger:"CLI",status:"RUNNING",environmentName:e.environmentName,cliVersion:Fo,schemaVersion:e.schemaVersion,startedAt:new Date,attempts:0,quarantined:e.quarantined,quarantinedReason:e.quarantinedReason,executionType:"ANDROID"};t.storeFile({name:"metadata.json",contents:JSON.stringify(n,null,2)});let o=new Hm(this.client,e.testId,e.testName,e.runId,n,t);return this.children.push(o),o}};async function Yv(r,e,t){if(t)return{};try{return(await e.getQuarantinedTests()).quarantined.reduce((o,i)=>(o[i.testId]=i.quarantinedReason,o),{})}catch(n){return r.warn({err:n},"Failed to fetch quarantined tests, proceeding without them."),{}}}async function Xv(r){let{options:e,fixtures:t,inputs:n,metadata:o}=r,{project:i,apiClient:a,logger:l}=t,{orgId:c,runGroupId:s,gitMetadata:u}=o,{outputDir:d,parallel:m}=e;j0(d)&&w.warn(`Output directory ${d} already exists, removing before test execution...`);let p=await Yv(l,a,e.ignoreQuarantine),g=Ml(i),h=await qv({tests:n.tests,yes:e.yes,project:i,momenticFiles:g,logger:w,quarantinedTestReasons:p}),f=l.child({orgId:c,runGroupId:s,branch:u.gitBranchName}),y=await Wl.start({logger:f,orgId:c,runGroupId:s,outputDir:d,client:a,gitMetadata:u,labels:[]}),T=[],v=new Date,R=new Set,b=async()=>W0({runResults:T,startTime:v,ranTests:R,apiClient:a,uploadResults:e.uploadResults??!1,outputDir:d}),x=[],N=async()=>{w.warn("SIGINT received. Stopping tests and printing latest results..."),await y.finish({logger:f,status:"CANCELLED"}),await b(),await Promise.allSettled(x.map(ee=>ee())),process.exit(1)};process.once("SIGINT",N);let k={};for(let ee=0;ee<h.length;ee++){let oe=Object.values(k);oe.length===m&&await Promise.race(oe.map(V=>V.promise));let lt=h[ee],M=`test-${ee}`;k[M]={done:!1,promise:(async({testDefinition:V})=>{R.add(M);let te=V.relativeFilePath.includes("..")?V.fullFilePath:V.relativeFilePath;Xi({status:"START",testLogRef:te,getRunningTestsCount:()=>R.size,getTotalTestsCount:()=>h.length});let Re=setInterval(()=>Xi({status:"RUN",testLogRef:te,getRunningTestsCount:()=>R.size,getTotalTestsCount:()=>h.length}),5*60*1e3),_e=V0(),ve=f.child({testId:V.id,runId:_e}),Rt=new Js({logger:ve,reporter:new Nl(a),runType:"mobile-test-run",runId:_e,testMetadata:V,suiteMetadata:void 0});try{let ct=await Kv({metadata:{...o,runId:_e},fixtures:{...t,tracer:y,logger:ve,usageTracker:Rt},inputs:{...n,project:i,testDefinition:V,channel:n.channel??V.settings?.defaultChannel,tag:n.tag??V.settings?.defaultTag,logUpdate:(Ae,Ve)=>Xi({status:Ae,testLogRef:te,getRunningTestsCount:()=>R.size,getTotalTestsCount:()=>h.length,additionalText:Ve}),runSigIntHandlers:x},options:e});Xi({status:ct.status,testLogRef:te,getRunningTestsCount:()=>R.size,getTotalTestsCount:()=>h.length}),T.push(ct)}catch(ct){let Ae=`Encountered unexpected fatal error when running test '${V.name}': ${ct.message}`;w.error(Ae),ve.error(Ae)}finally{clearInterval(Re),k[M].done=!0,delete k[M]}await Rt.flush(l)})({testDefinition:lt})}}await Promise.allSettled(Object.values(k).map(ee=>ee.promise));let De=T.some(ee=>ee.status==="FAILED"&&!ee.quarantined)?"FAILED":"PASSED";return await y.finish({logger:f,status:De}),process.off("SIGINT",N),b()}async function W0({runResults:r,startTime:e,ranTests:t,apiClient:n,uploadResults:o,outputDir:i}){let a=n.getAppUrl(),l=tv({results:r,startTime:e.getTime(),onFailed:c=>{},getDisplayLine:c=>{let s=`${tm}- ${c.filePath}`;return c.runId&&(s+=` ( link when uploaded: ${a}/runs/${c.runId} )`),s},entity:"mobile test"});return w.log(""),o?(w.success(`Test results have been saved to the folder ${i}. Uploading to Momentic Cloud...`),await Fl({client:n,consoleLogger:w,resultsPath:i})):w.success(`Test results have been saved to the folder ${i}. Upload them to Momentic Cloud by running 'npx momentic-mobile results upload ${i}'.`),l}async function Vm(){tf(),sv("Chromium")||(Ki?(await Rl("The Chromium browser is not installed but is required for automating webviews. Install it now?")||process.exit(1),await Cl({rawBrowsers:["chromium"],force:!1,all:!1})):(w.error("The Chromium browser is not installed but is required for automating webviews. Please install it using 'momentic-mobile install-browsers chromium'"),process.exit(1)))}my({serviceName:"mobile-cli"});wt.setApp("mobile-cli");var Xr=new $0;Xr.name("momentic-mobile").description("Momentic Mobile CLI").version(Fo);var J0=Xr.command("assets").description("Manage mobile testing assets");J0.command("upload").description("Upload an asset for mobile tests").argument("<file>","Path to the asset file to upload").addOption(ia).addOption(aa).addOption(Um).addOption(Hv).action(async(r,e)=>{let{apiKey:t,server:n,tag:o,channel:i}=e,a=ql.resolve(r);$l.existsSync(a)||(w.error(`File not found: ${a}`),process.exit(1));let l=new Yt({baseUrl:n,apiKey:t,logger:w});/\.apk$/i.test(a)||(w.error(`File is not an APK file: ${a}`),process.exit(1)),await ca({tag:o?.toLowerCase(),channel:i.toLowerCase(),filePath:a,apiClient:l,logger:w})});Xr.command("app").addOption(ia).addOption(aa).addOption(Nm).addOption(Lm).addOption(Bm).addOption(Dm).addOption(km).action(async r=>{let{apiKey:e,server:t,yes:n,disableCache:o,saveCache:i}=r,a=nm(r.logLevel);wt.setApp("mobile-desktop-server");let l=new Yt({baseUrl:t,apiKey:e,logger:wt});await Sm({client:l,skipPrompts:n}),w.debug("API key check complete");let c=X0(import.meta.url),s=ql.dirname(c),u=ql.resolve(s,"..","static");await Vm(),w.debug({appiumHome:Ti},"Resolved resource paths");let d=Zi({configFilePath:r.config}),m=zv;await Bv({momenticServerUrl:t,serverPort:m,apiKey:e,staticDir:u,initialProject:d,logLevel:a,logger:wt,noCache:o,alwaysSaveCache:i});let p=`http://localhost:${m}`;w.info(`Local app started on: ${p}`),await Y0(p)});var Jv=Xr.command("results").description("Merge and upload test results.");Jv.command("merge").description("Merge test results files.").addOption(Fm).addArgument(new jm("<resultsPath>","Path to a directory that contains on or more test results archives.").argRequired()).action(async(r,e)=>{let{outputDir:t}=e;t||(w.error("Output directory is required."),process.exit(1)),$l.existsSync(r)||(w.warn("Results path does not exist, skipping merge."),process.exit(0)),$l.existsSync(t)&&w.warn(`Output directory ${t} already exists, removing before merging...`),vv(wt,t,r),zo(),process.exit(0)});var Q0=new jm("<results>","Path to the results archive.").argRequired();Jv.command("upload").description("Upload test results to Momentic cloud.").addOption(ia).addOption(aa).addArgument(Q0).action(async(r,e)=>{let{apiKey:t,server:n}=e,o=wt,i=new Yt({baseUrl:n,apiKey:t,logger:o});await Fl({consoleLogger:w,resultsPath:r,client:i}),zo(),process.exit(0)});var Z0=Xr.command("run").alias("test").description("Run tests on the local machine");Z0.addOption(ia).addOption(aa).addOption(Lm).addOption(Nm).addOption(jv).addOption(Bm).addOption(Dm).addOption(km).addOption(Fm).addOption(Wv).addOption($v).addOption(Um).addOption(Gv).addOption(Vv).addArgument(new jm("<tests...>","One or more test file path or folders that exist on the local machine.").argOptional()).action(async(r,e)=>{let{apiKey:t,server:n,tag:o,channel:i,outputDir:a}=e,l=nm(e.logLevel);await Vm(),w.debug({appiumHome:Ti},"Resolved resource paths");let c=Zi({configFilePath:e.config}),s=a??c.config.outputDir??fv,u=e.parallel??c.config.parallel??1;w.debug("Checking API key and dependencies");let d=new Yt({baseUrl:n,apiKey:t,logger:w}),{orgId:m,userId:p}=await Sm({client:d,skipPrompts:e.yes});w.debug("API key check and browser installation complete");let g=K0(),h=wt.child({runGroupId:g,orgId:m,userId:p,cliVersion:Fo}),f=await Pl(wt,d,c);h.debug(f,"Got local git metadata");try{let y=await Xv({options:{...e,outputDir:s,parallel:u,logLevel:l,alwaysSaveCache:e.saveCache,noCache:e.disableCache},fixtures:{logger:h,project:c,apiClient:d},inputs:{envOverride:e.env,tag:o,channel:i,tests:r},metadata:{gitMetadata:f,runGroupId:g,orgId:m}});zo(),y.failed>0?process.exit(1):process.exit(0)}catch(y){w.error("Failed to run tests locally. Please check the error message below or run with the --verbose flag."),w.error(y),wt.error({err:y},"Failed to run tests locally"),zo(),process.exit(1)}});Xr.command("init").description("Initialize an empty Momentic project in the current working directory").addOption(new q0("--name <name>","Name of the project")).action(async r=>{w.info(`Welcome to the Momentic Mobile project setup wizard! \u{1F680}
4030
- `),w.info("This wizard will help you bootstrap a new Momentic project."),$l.existsSync(Po)&&(w.error("A momentic.config.yaml file already exists in this directory. Please rename or remove it to initialize a new project."),process.exit(1));let t={name:r.name??await nv("Choose an identifier for your project, such as a service, product, or team name (default: 'app'):","app"),include:sm};hv(t,Po),w.success(`Initialized Momentic project file at ${ql.resolve(Po)}`)});Xr.command("install-browsers").description("Install browser executables onto the local machine.").option("-f, --force","Force reinstallation even if the browser executables already exist on disk.").option("-a, --all","Install all browsers types.").argument("[browsers...]",`Browsers to install. Available choices: ${om.join(", ")}.`).action(async(r,e)=>{!e.all&&r.length===0&&(w.error("No browsers specified"),process.exit(1)),await Cl({rawBrowsers:r,force:e.force,all:e.all})});async function zo(){try{await xt.flush(),ev()}catch{}}async function ek(){try{await Xr.parseAsync(process.argv),zo()}catch(r){wt.error({err:r},"Uncaught error in CLI"),w.error(r),zo(),process.exit(1)}}ek();
3978
+ `),r.forEach(p=>{if(!mm.existsSync(p))throw new Error(`Path '${p}' does not exist.`);let m,g;try{m=mm.statSync(p),g=m.isDirectory()}catch(f){a.warn({err:f},`Skipping path ${p} because it cannot be read`);return}let h=Aa.resolve(p);Object.values(e.mobileTests).filter(f=>g?f.fullFilePath.startsWith(h):f.fullFilePath===h).forEach(f=>{c.add(f.fullFilePath)})})):(a.info("The arguments provided don't appear to be valid paths. Treating them as substrings instead... "),Object.values(e.mobileTests).forEach(p=>{r.some(m=>p.relativePath.includes(m))&&c.add(p.fullFilePath)}))}else{!n&&!await Wl("No test paths or substrings were provided. Do you want to run all tests?")&&(a.error("Cancelled by user."),process.exit(1));let u=Object.values(e.mobileTests);a.info(`Reading all ${u.length} mobile tests in the project from local disk.`),u.forEach(d=>{c.add(d.fullFilePath)})}for(let u of Array.from(c)){let d=Aa.relative(t.rootDir,u);o&&!o.some(p=>new RegExp(p).test(d))&&c.delete(u),i&&i.some(p=>new RegExp(p).test(d))&&c.delete(u)}return(await Promise.all(Array.from(c).map(async u=>{try{let d=Aa.relative(t.rootDir,u),p=await Zl(u,a,e),m=Aa.basename(u,Aa.extname(u));return{id:p.id,name:m,description:p.description,schemaVersion:p.schemaVersion,settings:p.settings,steps:p.steps,fullFilePath:u,relativeFilePath:d,quarantined:!!l[p.id],quarantinedReason:l[p.id]}}catch(d){a.error(`Failed to read and resolve mobile test at '${u}': ${d}`),process.exit(1)}}))).filter(u=>!!u)}import{cloneDeep as Xk}from"lodash-es";async function GA(r){let{inputs:e,fixtures:t,metadata:n,options:o}=r,{tracer:i,logger:a}=t,{runId:l}=n,{testDefinition:c,runSigIntHandlers:s}=e,u=new Date,d=await i.startRun({logger:a,testId:c.id,testName:c.name,runId:l,testDescription:c.description,schemaVersion:c.schemaVersion,originalSteps:{steps:Xk(c.steps),beforeSteps:void 0,afterSteps:void 0},quarantined:c.quarantined,quarantinedReason:c.quarantinedReason}),p=a.child(d.loggerBindings||{}),m=1+(c.settings?.retries??1);try{for(let g=0;g<m;g++){let h=new Date,f=await Jk({runTracer:d,testDefinition:c,metadata:n,constants:{attemptNumber:g,totalAttempts:m},fixtures:{...t,logger:p},inputs:e,options:o}),E=new Date;if(f.status!=="FAILED")return await d.finish({logger:a,...f,finishedAt:E}),{...f,startedAt:u,lastAttemptStartedAt:h,finishedAt:E,attempts:g+1,testMetadata:c,steps:c.steps,filePath:c.relativeFilePath,quarantined:c.quarantined,quarantinedReason:c.quarantinedReason};if(g!==m-1){a.warn("Retrying failed mobile run");continue}return a.error("Mobile test failed after all exhausting attempts"),await d.finish({logger:a,...f,finishedAt:E}),{...f,startedAt:u,lastAttemptStartedAt:h,finishedAt:E,attempts:g+1,testMetadata:c,steps:c.steps,filePath:c.relativeFilePath,quarantined:c.quarantined,quarantinedReason:c.quarantinedReason}}throw new Error("This code should not be reachable")}finally{s?.pop()}}async function Jk(r){let{runTracer:e,testDefinition:t,metadata:n,constants:o,fixtures:i,inputs:a,options:l}=r,{attemptNumber:c,totalAttempts:s}=o,{orgId:u,gitMetadata:d}=n,{apiClient:p,logger:m,usageTracker:g}=i,{logUpdate:h,channel:f,tag:E,project:b,envOverride:v}=a,{alwaysSaveCache:A,noCache:T,logLevel:x}=l;c!==0&&h("RETRY",`attempt ${c}/${s}`);let N={...a.project.config.emulator,...t.settings?.emulator},U=rc({orgId:u,client:p,gitMetadata:d,alwaysSaveCache:A,noCache:T}),Y=new jo(p,u),ke=new Ko(p),te={type:"API_KEY",baseUrl:p.baseUrl,apiKey:p.apiKey,logger:m},ie=new $n({},te),ut=new qo(te,ie),M=new $o({httpClient:p,fakerSeed:void 0}),V=Math.floor(Math.random()*1e4)+4e4,re=await ql(V,"appium"),Me=await wa({apiClient:p,logger:m,logLevel:x,creationOpts:{apkToInstall:f?{channel:f,tag:E}:void 0,region:N.region},onStatusUpdate:Qo=>{m.debug({status:Qo},"Limbar emulator status update")},appiumPort:re}),Ae=await e.startAttempt({emulatorName:Me.emulatorName}),xt=m.child(Ae.loggerBindings||{}),dt=v||t.settings?.defaultEnv,Re;dt&&(Re=Kl(dt,b,xt).variables);let We=new co({variablesFromEnvironment:Re??{},envName:dt,testName:t.name}),an=await Fo.init({driver:Me.driver,generator:ke,logger:xt,orgId:u,adbPort:Me.adbTunnelPort,options:{emulator:N},fixtures:{storage:Y,browserEnricher:ut,browserGenerator:ie,localCodeEvalTools:M,testContext:We}}),vr;try{vr=await Gl({containerName:"mobile-test",fixtures:{controller:an,logger:xt,cacheStorage:U,usageTracker:g},inputs:{steps:t.steps,orgId:u,testMetadata:t},tracer:Ae})}finally{await Me.cleanup()}return await Ae.finish({logger:xt,results:vr.results,status:vr.status}),vr}import{randomUUID as Qk}from"crypto";import{debounce as Zk}from"ts-debounce";var Ra="0.0.20";var uc="assets";function eU(r){switch(r){case"PASSED":return"SUCCESS";case"FAILED":return"FAILED";case"CANCELLED":return"CANCELLED";case"RUNNING":case"PENDING":case"RETRYING":case"WAITING_FOR_USER":return"RUNNING"}}function tU(r){switch(r){case"SUCCESS":return"PASSED";case"FAILED":return"FAILED";case"CANCELLED":return"CANCELLED";case"RUNNING":return"RUNNING";case"IDLE":return"PENDING"}}var gm=class{constructor(e,t,n,o){this.keepalive=e;this.testId=t;this.testName=n;this.diskStorage=o;this.commandTracer=new fo("command")}children=[];commandTracer;finished=!1;getParentStepIdChain(){return[]}attachBeforeScreenshot(e){let{snapshotId:t,screenshot:n}=e;this.diskStorage.storeFile({name:`${uc}/${t}.jpeg`,contents:n})}attachAfterScreenshot(e){let{snapshotId:t,screenshot:n}=e;this.diskStorage.storeFile({name:`${uc}/${t}.jpeg`,contents:n})}async finishInternal(e){this.finished||(this.finished=!0,await Promise.all(this.children.map(t=>t.finish({status:tU(e.status),finishedAt:e.finishedAt}))))}async finish(e){return await this.finishInternal({status:e.result.status,finishedAt:new Date(e.result.endTime)}),this.commandTracer.finish(),{trace:this.commandTracer.getRootSpan()}}startCommand(){return this.commandTracer}async startSubSteps(){let e=new Xo(this.keepalive,this.testId,this.testName,this.diskStorage);return this.children.push(e),e}},Xo=class{constructor(e,t,n,o){this.keepalive=e;this.testId=t;this.testName=n;this.diskStorage=o}children=[];finished=!1;async getScreenshot(e,t){return this.diskStorage.readFile(`${uc}/${t}.jpeg`)}getParentStepIdChain(){return[]}async startStep(e){this.keepalive();let t=new gm(this.keepalive,this.testId,this.testName,this.diskStorage);return this.children.push(t),t}async finish(e){this.finished||(this.finished=!0,await Promise.all(this.children.map(t=>t.finishInternal({status:eU(e.status),finishedAt:e.finishedAt}))))}},hm=class{constructor(e,t,n,o,i,a){this.keepalive=e;this.testId=t;this.testName=n;this.runAttemptId=o;this.metadata=i;this.diskStorage=a;this.diskStorage.mkdir("assets")}finished=!1;children=[];get loggerBindings(){return{runAttemptId:this.runAttemptId}}attachNetworkLogs(e){let{logs:t}=e;this.diskStorage.storeFile({name:"network.har",contents:JSON.stringify(t,null,2)})}attachConsoleLogs(e){let{logs:t}=e;this.diskStorage.storeFile({name:"console.json",contents:JSON.stringify(t,null,2)})}async finish(e){if(this.finished)return;this.finished=!0;let{logger:t,status:n,results:o,beforeResults:i,afterResults:a}=e,l={...this.metadata,status:n,finishedAt:new Date,results:Vl(o,t),beforeResults:i?Vl(i,t):void 0,afterResults:a?Vl(a,t):void 0};await Promise.all(this.children.map(c=>c.finish({status:l.status,finishedAt:l.finishedAt}))),this.diskStorage.storeFile({name:"metadata.json",contents:JSON.stringify(l,null,2)})}async startBeforeStepList(){let e=new Xo(this.keepalive,this.testId,this.testName,this.diskStorage);return this.children.push(e),e}async startMainStepList(){let e=new Xo(this.keepalive,this.testId,this.testName,this.diskStorage);return this.children.push(e),e}async startAfterStepList(){let e=new Xo(this.keepalive,this.testId,this.testName,this.diskStorage);return this.children.push(e),e}async getScreenshot(e,t){return this.diskStorage.readFile(`${uc}/${t}.jpeg`)}},fm=class{constructor(e,t,n,o,i,a){this.client=e;this.testId=t;this.testName=n;this.runId=o;this.metadata=i;this.diskStorage=a}children=[];finished=!1;get loggerBindings(){return{runId:this.runId}}async finish(e){if(this.finished)return;this.finished=!0;let t={...this.metadata,finishedAt:e.finishedAt||new Date,status:e.status,failureDetails:e.failureDetails,failureReason:e.failureReason,flake:e.isFlake||!1,failureRecoveryDetails:e.failureRecoveryDetails};await Promise.all(this.children.map(n=>n.finish({logger:e.logger,status:t.status,results:[],beforeResults:[],afterResults:[]}))),this.diskStorage.storeFile({name:"metadata.json",contents:JSON.stringify(t,null,2)}),this.diskStorage.close()}async startAttempt(e){this.metadata.attempts=this.metadata.attempts+1,this.metadata.status="RUNNING",this.diskStorage.storeFile({name:"metadata.json",contents:JSON.stringify(this.metadata,null,2)});let t=this.diskStorage.cd(`attempts/${this.metadata.attempts}`),n=Qk(),o={id:n,schemaVersion:un,runAttemptSchemaVersion:vf,startedAt:new Date,status:"RUNNING"};t.storeFile({name:"metadata.json",contents:JSON.stringify(o,null,2)});let i=Zk(async()=>{await this.client.extendAndroidEmulatorTtl(e.emulatorName)},3e4,{maxWait:6e4}),a=new hm(()=>void i(),this.testId,this.testName,n,o,t);return this.children.push(a),a}},dc=class r{constructor(e,t,n,o,i){this.orgId=e;this.runGroupId=t;this.metadata=n;this.client=o;this.diskStorage=i}children=[];finished=!1;get loggerBindings(){return{orgId:this.orgId,runGroupId:this.runGroupId,branch:this.metadata.gitBranchName}}static async start({orgId:e,runGroupId:t,outputDir:n,client:o,gitMetadata:i,labels:a}){let l={...i,id:t,trigger:Ut.CLI,startedAt:new Date,status:"RUNNING",cliVersion:Ra,labels:a??[]},c=new Sa(n);return c.storeFile({name:"metadata.json",contents:JSON.stringify(l,null,2)}),new r(e,t,l,o,c)}async finish(e){if(this.finished)return;this.finished=!0;let{status:t}=e,n={...this.metadata,status:t,updatedAt:new Date,finishedAt:new Date};await Promise.all(this.children.map(o=>o.finish({logger:e.logger,status:n.status,finishedAt:n.finishedAt}))),this.diskStorage.storeFile({name:"metadata.json",contents:JSON.stringify(n,null,2)})}async startRun(e){let t=this.diskStorage.createRunArchive(e.runId),n={stepsSnapshot:e.originalSteps.steps,runGroupId:this.runGroupId,testId:e.testId,testName:e.testName,testDescription:e.testDescription,labels:e.testLabels,trigger:"CLI",status:"RUNNING",environmentName:e.environmentName,cliVersion:Ra,schemaVersion:e.schemaVersion,startedAt:new Date,attempts:0,quarantined:e.quarantined,quarantinedReason:e.quarantinedReason,executionType:"ANDROID"};t.storeFile({name:"metadata.json",contents:JSON.stringify(n,null,2)});let o=new fm(this.client,e.testId,e.testName,e.runId,n,t);return this.children.push(o),o}};async function HA(r,e,t){if(t)return{};try{return(await e.getQuarantinedTests()).quarantined.reduce((o,i)=>(o[i.testId]=i.quarantinedReason,o),{})}catch(n){return r.warn({err:n},"Failed to fetch quarantined tests, proceeding without them."),{}}}async function VA(r){let{options:e,fixtures:t,inputs:n,metadata:o}=r,{project:i,apiClient:a,logger:l}=t,{orgId:c,runGroupId:s,gitMetadata:u}=o,{outputDir:d,parallel:p}=e;nU(d)&&R.warn(`Output directory ${d} already exists, removing before test execution...`);let m=await HA(l,a,e.ignoreQuarantine),g=Zt(i),h=await zA({tests:n.tests,yes:e.yes,project:i,momenticFiles:g,logger:R,quarantinedTestReasons:m}),f=l.child({orgId:c,runGroupId:s,branch:u.gitBranchName}),E=await dc.start({logger:f,orgId:c,runGroupId:s,outputDir:d,client:a,gitMetadata:u,labels:[]}),b=[],v=new Date,A=new Set,T=async()=>oU({runResults:b,startTime:v,ranTests:A,apiClient:a,uploadResults:e.uploadResults??!1,outputDir:d}),x=[],N=async()=>{R.warn("SIGINT received. Stopping tests and printing latest results..."),await E.finish({logger:f,status:"CANCELLED"}),await T(),await Promise.allSettled(x.map(te=>te())),process.exit(1)};process.once("SIGINT",N);let U={};for(let te=0;te<h.length;te++){let ie=Object.values(U);ie.length===p&&await Promise.race(ie.map(V=>V.promise));let ut=h[te],M=`test-${te}`;U[M]={done:!1,promise:(async({testDefinition:V})=>{A.add(M);let re=V.relativeFilePath.includes("..")?V.fullFilePath:V.relativeFilePath;da({status:"START",testLogRef:re,getRunningTestsCount:()=>A.size,getTotalTestsCount:()=>h.length});let Ce=setInterval(()=>da({status:"RUN",testLogRef:re,getRunningTestsCount:()=>A.size,getTotalTestsCount:()=>h.length}),5*60*1e3),Me=rU(),Ae=f.child({testId:V.id,runId:Me}),xt=new xs({logger:Ae,reporter:new ec(a),runType:"mobile-test-run",runId:Me,testMetadata:V,suiteMetadata:void 0});try{let dt=await GA({metadata:{...o,runId:Me},fixtures:{...t,tracer:E,logger:Ae,usageTracker:xt},inputs:{...n,project:i,testDefinition:V,channel:n.channel??V.settings?.defaultChannel,tag:n.tag??V.settings?.defaultTag,logUpdate:(Re,We)=>da({status:Re,testLogRef:re,getRunningTestsCount:()=>A.size,getTotalTestsCount:()=>h.length,additionalText:We}),runSigIntHandlers:x},options:e});da({status:dt.status,testLogRef:re,getRunningTestsCount:()=>A.size,getTotalTestsCount:()=>h.length}),b.push(dt)}catch(dt){let Re=`Encountered unexpected fatal error when running test '${V.name}': ${dt.message}`;R.error(Re),Ae.error(Re)}finally{clearInterval(Ce),U[M].done=!0,delete U[M]}await xt.flush(l)})({testDefinition:ut})}}await Promise.allSettled(Object.values(U).map(te=>te.promise));let ke=b.some(te=>te.status==="FAILED"&&!te.quarantined)?"FAILED":"PASSED";return await E.finish({logger:f,status:ke}),process.off("SIGINT",N),T()}async function oU({runResults:r,startTime:e,ranTests:t,apiClient:n,uploadResults:o,outputDir:i}){let a=n.getAppUrl(),l=Vv({results:r,startTime:e.getTime(),onFailed:c=>{},getDisplayLine:c=>{let s=`${Cp}- ${c.filePath}`;return c.runId&&(s+=` ( link when uploaded: ${a}/runs/${c.runId} )`),s},entity:"mobile test"});return R.log(""),o?(R.success(`Test results have been saved to the folder ${i}. Uploading to Momentic Cloud...`),await oc({client:n,consoleLogger:R,resultsPath:i})):R.success(`Test results have been saved to the folder ${i}. Upload them to Momentic Cloud by running 'npx momentic-mobile results upload ${i}'.`),l}async function Sm(){If(),Yv("Chromium")||(ca?(await Wl("The Chromium browser is not installed but is required for automating webviews. Install it now?")||process.exit(1),await $l({rawBrowsers:["chromium"],force:!1,all:!1})):(R.error("The Chromium browser is not installed but is required for automating webviews. Please install it using 'momentic-mobile install-browsers chromium'"),process.exit(1)))}Cb({serviceName:"mobile-cli"});Ct.setApp("mobile-cli");var on=new iU;on.name("momentic-mobile").description("Momentic Mobile CLI").version(Ra);var uU=on.command("assets").description("Manage mobile testing assets");uU.command("upload").description("Upload an asset for mobile tests").argument("<file>","Path to the asset file to upload").addOption(Ta).addOption(va).addOption(um).addOption(DA).action(async(r,e)=>{let{apiKey:t,server:n,tag:o,channel:i}=e,a=mc.resolve(r);pc.existsSync(a)||(R.error(`File not found: ${a}`),process.exit(1));let l=new tr({baseUrl:n,apiKey:t,logger:R});/\.apk$/i.test(a)||(R.error(`File is not an APK file: ${a}`),process.exit(1)),await Ca({tag:o?.toLowerCase(),channel:i.toLowerCase(),filePath:a,apiClient:l,logger:R})});on.command("app").addOption(Ta).addOption(va).addOption(sm).addOption(am).addOption(pm).addOption(lm).addOption(cm).action(async r=>{let{apiKey:e,server:t,yes:n,disableCache:o,saveCache:i}=r,a=xp(r.logLevel);Ct.setApp("mobile-desktop-server");let l=new tr({baseUrl:t,apiKey:e,logger:Ct});await jp({client:l,skipPrompts:n}),R.debug("API key check complete");let c=cU(import.meta.url),s=mc.dirname(c),u=mc.resolve(s,"..","static");await Sm(),R.debug({appiumHome:Li},"Resolved resource paths");let d=ga({configFilePath:r.config}),p=LA;await OA({momenticServerUrl:t,serverPort:p,apiKey:e,staticDir:u,initialProject:d,logLevel:a,logger:Ct,noCache:o,alwaysSaveCache:i});let m=`http://localhost:${p}`;R.info(`Local app started on: ${m}`),await lU(m)});var jA=on.command("results").description("Merge and upload test results.");jA.command("merge").description("Merge test results files.").addOption(dm).addArgument(new ym("<resultsPath>","Path to a directory that contains on or more test results archives.").argRequired()).action(async(r,e)=>{let{outputDir:t}=e;t||(R.error("Output directory is required."),process.exit(1)),pc.existsSync(r)||(R.warn("Results path does not exist, skipping merge."),process.exit(0)),pc.existsSync(t)&&R.warn(`Output directory ${t} already exists, removing before merging...`),gA(Ct,t,r),Jo(),process.exit(0)});var dU=new ym("<results>","Path to the results archive.").argRequired();jA.command("upload").description("Upload test results to Momentic cloud.").addOption(Ta).addOption(va).addArgument(dU).action(async(r,e)=>{let{apiKey:t,server:n}=e,o=Ct,i=new tr({baseUrl:n,apiKey:t,logger:o});await oc({consoleLogger:R,resultsPath:r,client:i}),Jo(),process.exit(0)});var pU=on.command("run").alias("test").description("Run tests on the local machine");pU.addOption(Ta).addOption(va).addOption(am).addOption(sm).addOption(UA).addOption(pm).addOption(lm).addOption(cm).addOption(dm).addOption(FA).addOption(BA).addOption(um).addOption(NA).addOption(kA).addArgument(new ym("<tests...>","One or more test file path or folders that exist on the local machine.").argOptional()).action(async(r,e)=>{let{apiKey:t,server:n,tag:o,channel:i,outputDir:a}=e,l=xp(e.logLevel);await Sm(),R.debug({appiumHome:Li},"Resolved resource paths");let c=ga({configFilePath:e.config}),s=a??c.config.outputDir??oA,u=e.parallel??c.config.parallel??1;R.debug("Checking API key and dependencies");let d=new tr({baseUrl:n,apiKey:t,logger:R}),{orgId:p,userId:m}=await jp({client:d,skipPrompts:e.yes});R.debug("API key check and browser installation complete");let g=sU(),h=Ct.child({runGroupId:g,orgId:p,userId:m}),f=await Xl(Ct,d,c);h.debug(f,"Got local git metadata");try{let E=await VA({options:{...e,outputDir:s,parallel:u,logLevel:l,alwaysSaveCache:e.saveCache,noCache:e.disableCache},fixtures:{logger:h,project:c,apiClient:d},inputs:{envOverride:e.env,tag:o,channel:i,tests:r},metadata:{gitMetadata:f,runGroupId:g,orgId:p}});Jo(),E.failed>0?process.exit(1):process.exit(0)}catch(E){R.error("Failed to run tests locally. Please check the error message below or run with the --verbose flag."),R.error(E),Ct.error({err:E},"Failed to run tests locally"),Jo(),process.exit(1)}});on.command("init").description("Initialize an empty Momentic project in the current working directory").addOption(new aU("--name <name>","Name of the project")).action(async r=>{R.info(`Welcome to the Momentic Mobile project setup wizard! \u{1F680}
3979
+ `),R.info("This wizard will help you bootstrap a new Momentic project."),pc.existsSync(Vo)&&(R.error("A momentic.config.yaml file already exists in this directory. Please rename or remove it to initialize a new project."),process.exit(1));let t={name:r.name??await Wv("Choose an identifier for your project, such as a service, product, or team name (default: 'app'):","app"),include:Pp};nA(t,Vo),R.success(`Initialized Momentic project file at ${mc.resolve(Vo)}`)});on.command("install-browsers").description("Install browser executables onto the local machine.").option("-f, --force","Force reinstallation even if the browser executables already exist on disk.").option("-a, --all","Install all browsers types.").argument("[browsers...]",`Browsers to install. Available choices: ${_p.join(", ")}.`).action(async(r,e)=>{!e.all&&r.length===0&&(R.error("No browsers specified"),process.exit(1)),await $l({rawBrowsers:r,force:e.force,all:e.all})});async function Jo(){try{await Mt.flush(),Rv()}catch{}}async function mU(){try{await on.parseAsync(process.argv),Jo()}catch(r){Ct.error({err:r},"Uncaught error in CLI"),R.error(r),Jo(),process.exit(1)}}mU();
4031
3980
  //# sourceMappingURL=cli.js.map